Skip to content

🛡️ Sentinel: [CRITICAL] Fix arbitrary code execution in AST eval#374

Open
bashandbone wants to merge 1 commit into
mainfrom
sentinel/fix-ast-call-ace-1920070606635761678
Open

🛡️ Sentinel: [CRITICAL] Fix arbitrary code execution in AST eval#374
bashandbone wants to merge 1 commit into
mainfrom
sentinel/fix-ast-call-ace-1920070606635761678

Conversation

@bashandbone

@bashandbone bashandbone commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

🚨 Severity: CRITICAL
💡 Vulnerability: _safe_eval_type relied on unrestricted ast.Call evaluation inside string-based type annotations. Any malicious string passed containing functions mapping back to the global namespace could execute arbitrary code during resolution.
🎯 Impact: Attackers providing malicious strings to evaluation mechanisms could hijack execution flow or gain RCE through eval() bypass by utilizing python's internal mechanisms like __builtins__['eval']() or imported OS functions.
🔧 Fix: Implemented explicit whitelist checks to limit allowed ast.Call nodes uniquely to valid Dependency Injection / Pydantic field definitions (Depends, depends, Field, PrivateAttr, Tag, Parameter), explicitly raising TypeError for arbitrary ones.
✅ Verification: Ensure the targeted unit test coverage pytest tests/unit/core/di and mise //:check passed flawlessly. Tested locally mimicking an ACE exploit and successfully blocked the behavior.


PR created automatically by Jules for task 1920070606635761678 started by @bashandbone

Summary by Sourcery

Harden AST-based type string evaluation to prevent arbitrary code execution via unsafe function calls in dependency injection type resolution.

Bug Fixes:

  • Restrict function calls in AST-validated type annotation strings to a small whitelist of known-safe DI and Pydantic helpers, raising errors for all other calls to eliminate an arbitrary code execution vector.

Documentation:

  • Document the newly discovered AST evaluation arbitrary code execution vulnerability and its mitigation steps in the security sentinel notes.

This commit patches a critical vulnerability in `TypeValidator`'s AST evaluation inside `src/codeweaver/core/di/container.py` where `ast.Call` nodes were permitted without restriction. This lack of validation allowed Arbitrary Code Execution (ACE) via injection of malicious callables into string type annotations evaluated during dynamic dependency injection. The patch adds strict whitelist filtering for functions relevant only to DI/Pydantic configurations (`Depends`, `depends`, `Field`, `PrivateAttr`, `Tag`, and `Parameter`). It properly handles standard function resolution and updates the internal security journal.

Co-authored-by: bashandbone <89049923+bashandbone@users.noreply.github.com>
Copilot AI review requested due to automatic review settings June 1, 2026 17:44
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai

sourcery-ai Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Locks down the AST-based type string evaluator used in the DI container by whitelisting allowed function calls inside annotations and updates the security Sentinel documentation with details of the vulnerability and its mitigation.

File-Level Changes

Change Details Files
Harden AST-based type string evaluation to prevent arbitrary function calls and code execution.
  • Adds a complexity noqa comment to _safe_eval_type to acknowledge increased control-flow complexity.
  • Extends the AST visitor to inspect ast.Call nodes and derive the function name from ast.Name or ast.Attribute, rejecting any other callable node types.
  • Introduces an explicit whitelist of allowed call targets (Depends, depends, Field, PrivateAttr, Tag, Parameter) and raises TypeError for any other function name encountered in type strings.
src/codeweaver/core/di/container.py
Document the newly discovered AST eval arbitrary code execution vulnerability and its prevention in Sentinel security notes.
  • Adds a new dated section describing the AST-based arbitrary code execution vulnerability in TypeValidator.
  • Captures key learning about risks of generic ast.Call handling within restricted AST evaluation contexts.
  • Documents the prevention strategy of whitelisting specific allowed functions when validating AST trees for dynamic type evaluation.
.jules/sentinel.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions

github-actions Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

🤖 Hi @bashandbone, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@github-actions

github-actions Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

🤖 I'm sorry @bashandbone, but I was unable to process your request. Please see the logs for more details.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • Instead of inlining allowed_calls inside the visitor, consider hoisting it to a module-level constant or class attribute so it’s easier to share, audit, and update as the set of allowed callables evolves.
  • The blanket # noqa: C901 on _safe_eval_type suggests the function is doing too much; consider extracting the AST validation logic (or at least the call-node checks) into a dedicated helper/visitor class to keep complexity localized and more maintainable.
  • The ast.Call check currently whitelists by simple function/attribute name, which could match unintended symbols; consider tightening this by also validating the module/qualname or restricting the namespace from which these callables can be resolved.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Instead of inlining `allowed_calls` inside the visitor, consider hoisting it to a module-level constant or class attribute so it’s easier to share, audit, and update as the set of allowed callables evolves.
- The blanket `# noqa: C901` on `_safe_eval_type` suggests the function is doing too much; consider extracting the AST validation logic (or at least the call-node checks) into a dedicated helper/visitor class to keep complexity localized and more maintainable.
- The `ast.Call` check currently whitelists by simple function/attribute name, which could match unintended symbols; consider tightening this by also validating the module/qualname or restricting the namespace from which these callables can be resolved.

## Individual Comments

### Comment 1
<location path="src/codeweaver/core/di/container.py" line_range="144-150" />
<code_context>
+                if isinstance(node, ast.Call):
+                    if isinstance(node.func, ast.Name):
+                        func_name = node.func.id
+                    elif isinstance(node.func, ast.Attribute):
+                        func_name = node.func.attr
+                    else:
+                        raise TypeError(f"Forbidden call function node type: {type(node.func).__name__}")
+
+                    allowed_calls = {"Depends", "depends", "Field", "PrivateAttr", "Tag", "Parameter"}
+                    if func_name not in allowed_calls:
+                        raise TypeError(f"Forbidden function call in type string: {func_name}")
+
</code_context>
<issue_to_address>
**🚨 issue (security):** Relying only on the function name for `ast.Attribute` calls may allow unexpected call targets.

Because only `node.func.attr` is checked for `ast.Attribute`, any `*.Depends` / `*.Field` / etc. call is accepted, regardless of what object actually provides the attribute. A user could supply an object in `globalns` with a malicious `.Depends` that still passes this check. To strengthen ACE protection, also validate the base (`node.func.value`) or resolve the callable from `globalns` and ensure it matches the expected functions instead of trusting the attribute name alone.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +144 to +150
elif isinstance(node.func, ast.Attribute):
func_name = node.func.attr
else:
raise TypeError(f"Forbidden call function node type: {type(node.func).__name__}")

allowed_calls = {"Depends", "depends", "Field", "PrivateAttr", "Tag", "Parameter"}
if func_name not in allowed_calls:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 issue (security): Relying only on the function name for ast.Attribute calls may allow unexpected call targets.

Because only node.func.attr is checked for ast.Attribute, any *.Depends / *.Field / etc. call is accepted, regardless of what object actually provides the attribute. A user could supply an object in globalns with a malicious .Depends that still passes this check. To strengthen ACE protection, also validate the base (node.func.value) or resolve the callable from globalns and ensure it matches the expected functions instead of trusting the attribute name alone.

@github-actions

github-actions Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Security Fix Review

I've reviewed this critical security fix for the arbitrary code execution vulnerability in AST evaluation. Here's my assessment:

✅ Security Fix Analysis

Vulnerability Addressed: The fix correctly addresses a critical ACE vulnerability where arbitrary functions could be called during type annotation evaluation in the DI container's _safe_eval_type method (src/codeweaver/core/di/container.py:87-179).

Fix Implementation: The patch adds a whitelist validation for ast.Call nodes at lines 141-151:

  • Extracts function names from ast.Name and ast.Attribute nodes
  • Validates against an explicit whitelist: {"Depends", "depends", "Field", "PrivateAttr", "Tag", "Parameter"}
  • Raises TypeError for any non-whitelisted function calls
  • Properly rejects other call node types

Test Coverage: Excellent! The codebase has comprehensive security tests in tests/di/test_container_security.py that validate:

  • Safe type resolution for legitimate cases
  • Blocking of malicious strings (eval, import, lambda, etc.)
  • Dunder name/attribute blocking
  • Prevention of type() exploitation

🔍 Code Quality

Strengths:

  1. Clear inline comments explaining the security rationale
  2. Follows defense-in-depth approach (AST validation + restricted eval)
  3. Specific error messages for debugging
  4. Documentation in sentinel.md provides good context

Minor Observations:

  1. The # noqa: C901 complexity suppression is warranted given the security-critical nature
  2. The whitelist is hardcoded - this is actually good for security (no dynamic configuration risk)

⚠️ CI Status

Build Failures: The Docker build is failing due to a version mismatch issue unrelated to this security fix:

  • code-weaver==0.1.2.post9.dev0 requires code-weaver-daemon==0.1.2.post9.dev0
  • But the built wheel is code_weaver_daemon-0.1.3.dev9+g2812da7d

This appears to be a versioning/build configuration issue in the monorepo, not a problem with the security fix itself.

Review Job: Failed but appears to be related to Gemini CLI setup, not code quality.

📋 Recommendations

  1. Immediate: The security fix is sound and should be merged once CI is resolved
  2. Follow-up: Add a regression test specifically for the ACE scenario (e.g., attempting to call eval or __import__ in type annotations)
  3. Follow-up: Consider if the whitelist should include any additional Pydantic v2 field types

✅ Verdict

APPROVED - The security fix correctly addresses the critical vulnerability with proper validation logic. The code is well-documented and follows security best practices. The CI failures are infrastructure-related and don't reflect on the quality of this security patch.

Once the version mismatch in the Docker build is resolved, this should be merged promptly given the critical severity.


Reviewed by Claude Code

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR hardens CodeWeaver’s DI container string-annotation type resolution to prevent arbitrary code execution during AST-based evaluation of type strings.

Changes:

  • Adds an allowlist for ast.Call nodes in _safe_eval_type to block unsafe function calls during type string evaluation.
  • Updates Sentinel security notes documenting the discovered AST-eval ACE/RCE vector and mitigation.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
src/codeweaver/core/di/container.py Restricts which function calls are permitted in AST-validated type-string evaluation.
.jules/sentinel.md Documents the vulnerability and the mitigation approach in Sentinel notes.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +139 to +151
# Security: Restrict ast.Call nodes to known safe functions to prevent arbitrary code execution (ACE).
# Allowing arbitrary functions (like 'eval' or malicious callables) inside type annotations is dangerous.
if isinstance(node, ast.Call):
if isinstance(node.func, ast.Name):
func_name = node.func.id
elif isinstance(node.func, ast.Attribute):
func_name = node.func.attr
else:
raise TypeError(f"Forbidden call function node type: {type(node.func).__name__}")

allowed_calls = {"Depends", "depends", "Field", "PrivateAttr", "Tag", "Parameter"}
if func_name not in allowed_calls:
raise TypeError(f"Forbidden function call in type string: {func_name}")
Comment on lines +139 to +141
# Security: Restrict ast.Call nodes to known safe functions to prevent arbitrary code execution (ACE).
# Allowing arbitrary functions (like 'eval' or malicious callables) inside type annotations is dangerous.
if isinstance(node, ast.Call):
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants