Skip to content

🛡️ Sentinel: [CRITICAL] Fix arbitrary code execution in AST type evaluation#364

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

🛡️ Sentinel: [CRITICAL] Fix arbitrary code execution in AST type evaluation#364
bashandbone wants to merge 1 commit into
mainfrom
sentinel-fix-ast-call-ace-13648616864975803255

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented May 26, 2026

🚨 Severity: CRITICAL
💡 Vulnerability: The TypeValidator used before resolving typing annotations with eval() allowed any ast.Call to pass validation. This meant an attacker who could control type annotation strings (e.g., dynamically generated or user-provided) could execute arbitrary code functions present in the target module's namespace.
🎯 Impact: A malicious user or external plugin could gain arbitrary code execution (ACE) privileges on the server or developer machine.
🔧 Fix: Added a whitelist strictly limiting allowable functions inside ast.Call nodes to those natively used for DI annotations (i.e. Depends, depends, Field, PrivateAttr, Tag). Any other call function correctly throws a TypeError.
✅ Verification: Ran formatting and comprehensive unit tests (tests/unit/core/) ensuring existing DI resolutions properly continue functioning while unsafe eval behaviors are mitigated.


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

Summary by Sourcery

Harden type annotation evaluation to prevent arbitrary code execution during dependency injection AST processing.

Bug Fixes:

  • Reject unsafe ast.Call nodes in type annotation strings by enforcing a strict whitelist of allowed call targets used for dependency-injection-related annotations.

Documentation:

  • Document the new AST call evaluation vulnerability, its root cause, and the whitelist-based prevention in the Sentinel security log.

…uation

Co-authored-by: bashandbone <89049923+bashandbone@users.noreply.github.com>
Copilot AI review requested due to automatic review settings May 26, 2026 17:27
@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
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 26, 2026

Reviewer's Guide

Tightens the AST-based type annotation validator used before eval() by whitelisting only known-safe DI-related callables in ast.Call nodes and documents the security fix in the Sentinel log.

File-Level Changes

Change Details Files
Harden AST type annotation validation to prevent arbitrary function calls from being evaluated.
  • Extend the TypeValidator.generic_visit to inspect ast.Call nodes encountered while traversing type annotation ASTs.
  • Reject any ast.Call whose func is not a simple ast.Name node or whose name is not in the allowed whitelist of DI helpers.
  • Derive a human-readable function identifier for disallowed calls and raise a TypeError with a clear error message before eval() is reached.
src/codeweaver/core/di/container.py
Document the new ACE vulnerability and its mitigation in the Sentinel security notes.
  • Add a new dated entry describing the arbitrary code execution risk via generic ast.Call handling in type evaluation.
  • Record the security learning about eval() and the need for strict whitelisting of callables in annotation ASTs.
  • Describe the prevention strategy of restricting calls to a fixed set of safe DI-related functions.
.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
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
Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

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:

  • The whitelist of allowed call names is currently hard-coded inline; consider centralizing it into a constant or configuration at module level so it’s easier to audit and extend consistently across future security-related checks.
  • Right now only bare ast.Name calls are allowed (e.g., Depends) and attribute-style calls (e.g., di.Depends) are always rejected and reported with the raw type name; if attribute-style usage is expected, you may want to explicitly support/forbid it with a clearer error message to avoid confusing developers.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The whitelist of allowed call names is currently hard-coded inline; consider centralizing it into a constant or configuration at module level so it’s easier to audit and extend consistently across future security-related checks.
- Right now only bare ast.Name calls are allowed (e.g., Depends) and attribute-style calls (e.g., di.Depends) are always rejected and reported with the raw type name; if attribute-style usage is expected, you may want to explicitly support/forbid it with a clearer error message to avoid confusing developers.

## Individual Comments

### Comment 1
<location path="src/codeweaver/core/di/container.py" line_range="143-152" />
<code_context>
+                # Allowing generic ast.Call nodes could lead to Arbitrary Code Execution (ACE)
+                # during eval() as it permits running any callable in the global namespace.
+                # We strictly limit ast.Call usage to known safe functions used in annotations.
+                if isinstance(node, ast.Call) and (
+                    not isinstance(node.func, ast.Name)
+                    or node.func.id
+                    not in {
+                        "Depends",
+                        "depends",
+                        "Field",
+                        "PrivateAttr",
+                        "Tag",
+                    }
+                ):
+                    func_name = (
+                        node.func.id if isinstance(node.func, ast.Name) else str(type(node.func))
</code_context>
<issue_to_address>
**question:** Consider whether rejecting all non-whitelisted calls (including attribute calls) is too strict for valid annotation use cases

This will reject any `ast.Call` whose `func` is not a bare `ast.Name` in the allowlist, so attribute-based helpers like `fastapi.Depends(...)` or `pydantic.Field(...)` will now error even when equivalent to their name-imported forms. If attribute access is a common pattern, this becomes a subtle breaking change. If acceptable for your threat model, consider also allowing `ast.Attribute` where the attribute name is in the safe set (e.g. `Depends`, `Field`), while still rejecting other callables.
</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 +143 to +152
if isinstance(node, ast.Call) and (
not isinstance(node.func, ast.Name)
or node.func.id
not in {
"Depends",
"depends",
"Field",
"PrivateAttr",
"Tag",
}
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.

question: Consider whether rejecting all non-whitelisted calls (including attribute calls) is too strict for valid annotation use cases

This will reject any ast.Call whose func is not a bare ast.Name in the allowlist, so attribute-based helpers like fastapi.Depends(...) or pydantic.Field(...) will now error even when equivalent to their name-imported forms. If attribute access is a common pattern, this becomes a subtle breaking change. If acceptable for your threat model, consider also allowing ast.Attribute where the attribute name is in the safe set (e.g. Depends, Field), while still rejecting other callables.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Hardens CodeWeaver’s DI type-string evaluation path (Container._safe_eval_type) to prevent arbitrary code execution by restricting which ast.Call nodes are allowed through AST validation before eval() runs.

Changes:

  • Added an ast.Call whitelist in the AST validator to only allow known annotation helper calls (e.g., Depends, depends, Field, PrivateAttr, Tag).
  • Updated the Sentinel security log with a new entry documenting the AST-call evaluation vulnerability and the whitelist-based 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 Adds a strict ast.Call allowlist during AST traversal to block unsafe call expressions prior to eval().
.jules/sentinel.md Documents the vulnerability, its cause, and the mitigation approach in the Sentinel security log.

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

Comment on lines +154 to +157
func_name = (
node.func.id if isinstance(node.func, ast.Name) else str(type(node.func))
)
raise TypeError(f"Forbidden function call in type string: {func_name}")
Comment thread .jules/sentinel.md
Comment on lines +7 to +8
## 2025-02-14 - Arbitrary Code Execution (ACE) via AST Call Evaluation
**Vulnerability:** Allowed arbitrary `ast.Call` nodes in type annotation evaluation strings, potentially leading to arbitrary code execution if user input or malicious type strings are evaluated.
@github-actions
Copy link
Copy Markdown
Contributor

Security Review - PR #364

Summary

This PR implements a critical security fix to prevent arbitrary code execution (ACE) in the dependency injection container's type annotation evaluation system. The fix adds a whitelist for ast.Call nodes to restrict which functions can be invoked during type string evaluation.

Security Analysis

Vulnerability Assessment:

  • Severity: CRITICAL ✅
  • Attack Vector: Malicious type annotation strings containing arbitrary function calls
  • Impact: Arbitrary code execution if an attacker controls type annotation strings
  • Root Cause: The TypeValidator class allowed any ast.Call node, permitting execution of arbitrary callables in the module's namespace

Fix Implementation (container.py:139-157):
The fix implements a strict whitelist approach:

  • Only allows specific DI-related functions: Depends, depends, Field, PrivateAttr, Tag
  • Rejects all other function calls with a clear TypeError
  • Validates that node.func is an ast.Name type before checking the whitelist
  • Provides clear error messages indicating which forbidden function was attempted

Code Quality

Strengths:

  1. Defense in depth: The whitelist is checked before eval() executes, preventing exploitation
  2. Clear documentation: Excellent inline comments explaining the security rationale
  3. Minimal change: Targeted fix with minimal surface area for regressions
  4. Error handling: Proper error messages for debugging legitimate failures
  5. Sentinel documentation: Well-documented in .jules/sentinel.md with vulnerability details and prevention strategy

Potential Concerns:

  1. Test Coverage: ⚠️ I could not find specific tests validating that malicious function calls are rejected. Consider adding a test like:
def test_safe_eval_type_rejects_malicious_calls():
    container = Container()
    # Should reject arbitrary function calls
    assert container._safe_eval_type('system("malicious")', {}) is None
    assert container._safe_eval_type('__import__("os")', {}) is None
    assert container._safe_eval_type('eval("code")', {}) is None
  1. Whitelist Completeness: The whitelist includes Depends, depends, Field, PrivateAttr, and Tag. Have you verified these are the only functions legitimately used in type annotations across the codebase? Consider:

    • Searching for other Pydantic/typing functions that might be needed (e.g., Literal, Union)
    • However, note that Literal uses ast.Constant, not ast.Call, and Union uses ast.BinOp, so they're already allowed
  2. Attribute Access: The fix only checks ast.Name types. What about attribute access like module.Depends()? The current code would reject these. Is this intentional? If so, it's fine, but worth documenting.

CI Status

The PR has 2 failing checks:

  • "Build Docker Image" - appears to be infrastructure-related (Debian package installation)
  • "review / review" - appears to be a Gemini review workflow issue

These failures appear unrelated to the security fix itself. The core tests (Lint, CodeQL, Socket Security) are passing.

Recommendations

  1. Add Security Tests (High Priority): Add explicit tests for the security fix to prevent regression
  2. Verify Whitelist (Medium Priority): Confirm no legitimate use cases are blocked
  3. CI Investigation (Low Priority): The Docker build and review failures seem environmental, not code-related

Verdict

Approve with recommendations

The security fix is sound and addresses a critical vulnerability effectively. The implementation follows security best practices (whitelist approach, fail-safe defaults). However, I strongly recommend adding explicit security tests before merging to ensure this protection is maintained in future refactorings.

The failing CI checks appear to be infrastructure issues unrelated to this code change and should not block the merge of this critical security fix.


Review conducted by Claude Code

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