Skip to content

🛡️ Sentinel: [CRITICAL] Fix Arbitrary Code Execution in AST validation#367

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

🛡️ Sentinel: [CRITICAL] Fix Arbitrary Code Execution in AST validation#367
bashandbone wants to merge 1 commit into
mainfrom
sentinel-fix-ast-call-4563127322899614225

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented May 28, 2026

🚨 Severity: CRITICAL
💡 Vulnerability: Generic ast.Call nodes were allowed during AST type parsing in TypeValidator.generic_visit within src/codeweaver/core/di/container.py. This input was subsequently fed to eval(). Without whitelisting, this allowed the execution of any callable in the restricted eval's global namespace, posing a potential Arbitrary Code Execution (ACE) risk.
🎯 Impact: An attacker who can control the string representation of a type annotation (e.g., via malicious configuration or dependency injection inputs) could execute arbitrary functions available in the module's global scope, compromising the security of the application.
🔧 Fix: Added a strict whitelist for ast.Call nodes in TypeValidator.generic_visit, limiting allowable functions strictly to safe known ones: Depends, depends, Field, PrivateAttr, and Tag.
✅ Verification: Ran unit tests using pytest for core, engine, and server packages to verify that no dependency injection logic or container behavior was broken, and that the ACE vector is closed.


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

Summary by Sourcery

Harden AST-based type annotation validation to prevent arbitrary code execution during eval of string annotations.

Bug Fixes:

  • Restrict allowed function calls in type-annotation ASTs to a small, safe whitelist to close an arbitrary code execution vector.

Documentation:

  • Document the newly discovered AST validation arbitrary code execution vulnerability and its mitigation steps in the Sentinel security log.

Co-authored-by: bashandbone <89049923+bashandbone@users.noreply.github.com>
@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.

Copilot AI review requested due to automatic review settings May 28, 2026 17:43
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 28, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Restricts which function calls are allowed in type-annotation AST validation to close an eval-based arbitrary code execution vector, and documents the vulnerability and fix in the Sentinel security log.

Flow diagram for AST validation whitelist before eval

flowchart TD
    A["Type annotation string"] --> B["ast.parse to AST"]
    B --> C["TypeValidator.generic_visit"]
    C --> D{"node is ast.Call"}

    D -- no --> G["super.generic_visit"]

    D -- yes --> E{"node.func is ast.Name"}
    E -- no --> X["raise TypeError: Only direct function calls are allowed"]

    E -- yes --> F{"node.func.id in {Depends, depends, Field, PrivateAttr, Tag}"}
    F -- no --> Y["raise TypeError: Forbidden function call in type annotation"]
    F -- yes --> G

    G --> H["eval on validated AST"]
Loading

File-Level Changes

Change Details Files
Harden AST validation for type annotations to only allow a small whitelist of safe function calls before eval is invoked.
  • In TypeValidator.generic_visit, detect ast.Call nodes and require that the called function is a simple ast.Name (no attributes, subscripts, etc.).
  • Enforce that only calls to whitelisted function names {Depends, depends, Field, PrivateAttr, Tag} are permitted in type annotations, raising TypeError for anything else.
  • Keep delegating to the base generic_visit for further traversal after the new checks pass.
src/codeweaver/core/di/container.py
Update Sentinel security documentation with details of the newly discovered AST validation ACE vulnerability and the mitigation.
  • Append a new dated section describing the AST-based arbitrary code execution issue in container type validation.
  • Document key learning about the danger of generic ast.Call validation before eval, and prescribe strict whitelisting and direct-call-only constraints as preventive measures.
.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:

  • Consider centralizing the allowed function names for type-annotation calls into a shared constant (e.g., ALLOWED_TYPE_CALLS) so it’s easier to audit and extend in one place if additional safe helpers are introduced later.
  • The new TypeError messages for forbidden calls could include the full node representation (or at least more context) to aid debugging, as just the function name may be ambiguous in larger codebases.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider centralizing the allowed function names for type-annotation calls into a shared constant (e.g., `ALLOWED_TYPE_CALLS`) so it’s easier to audit and extend in one place if additional safe helpers are introduced later.
- The new `TypeError` messages for forbidden calls could include the full node representation (or at least more context) to aid debugging, as just the function name may be ambiguous in larger codebases.

## Individual Comments

### Comment 1
<location path="src/codeweaver/core/di/container.py" line_range="143" />
<code_context>
+                if isinstance(node, ast.Call):
+                    if not isinstance(node.func, ast.Name):
+                        raise TypeError("Only direct function calls are allowed in type annotations")
+                    if node.func.id not in {"Depends", "depends", "Field", "PrivateAttr", "Tag"}:
+                        raise TypeError(f"Forbidden function call in type annotation: {node.func.id}")
+
</code_context>
<issue_to_address>
**suggestion:** Consider moving the allowlist of function names to a shared constant to avoid repeated set allocations and improve maintainability.

Right now the set literal is recreated for every `ast.Call` visit, which can add up on large ASTs. Hoisting it to a module- or class-level constant (e.g. `_ALLOWED_ANNOTATION_CALLS`) both avoids the repeated allocations and centralizes the allowlist so it can be updated or tested without touching the visitor logic.

Suggested implementation:

```python
                    if not isinstance(node.func, ast.Name):
                        raise TypeError("Only direct function calls are allowed in type annotations")
                    if node.func.id not in _ALLOWED_ANNOTATION_CALLS:
                        raise TypeError(f"Forbidden function call in type annotation: {node.func.id}")

```

To fully implement the change, add a module-level constant near the top of `src/codeweaver/core/di/container.py` (e.g. after the imports):

```python
_ALLOWED_ANNOTATION_CALLS = {"Depends", "depends", "Field", "PrivateAttr", "Tag"}
```

If this visitor is defined inside a class and you prefer class-level configuration, you can alternatively define it as a class attribute and reference it as `self._ALLOWED_ANNOTATION_CALLS` (or `cls._ALLOWED_ANNOTATION_CALLS` if using `@classmethod`), updating the check accordingly.
</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.

if isinstance(node, ast.Call):
if not isinstance(node.func, ast.Name):
raise TypeError("Only direct function calls are allowed in type annotations")
if 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.

suggestion: Consider moving the allowlist of function names to a shared constant to avoid repeated set allocations and improve maintainability.

Right now the set literal is recreated for every ast.Call visit, which can add up on large ASTs. Hoisting it to a module- or class-level constant (e.g. _ALLOWED_ANNOTATION_CALLS) both avoids the repeated allocations and centralizes the allowlist so it can be updated or tested without touching the visitor logic.

Suggested implementation:

                    if not isinstance(node.func, ast.Name):
                        raise TypeError("Only direct function calls are allowed in type annotations")
                    if node.func.id not in _ALLOWED_ANNOTATION_CALLS:
                        raise TypeError(f"Forbidden function call in type annotation: {node.func.id}")

To fully implement the change, add a module-level constant near the top of src/codeweaver/core/di/container.py (e.g. after the imports):

_ALLOWED_ANNOTATION_CALLS = {"Depends", "depends", "Field", "PrivateAttr", "Tag"}

If this visitor is defined inside a class and you prefer class-level configuration, you can alternatively define it as a class attribute and reference it as self._ALLOWED_ANNOTATION_CALLS (or cls._ALLOWED_ANNOTATION_CALLS if using @classmethod), updating the check accordingly.

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 the DI container’s string-annotation type resolution by tightening AST validation before eval(), closing an Arbitrary Code Execution vector where previously any ast.Call could be evaluated if a callable was reachable via the eval namespace. Also documents the incident and mitigation in the Sentinel security log.

Changes:

  • Add a strict whitelist for ast.Call nodes during AST validation so only known-safe functions can be invoked in type-annotation strings.
  • Reject non-direct function calls (e.g., attribute calls like obj.method()), further narrowing the eval surface.
  • Record the vulnerability and prevention guidance in .jules/sentinel.md.

Reviewed changes

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

File Description
src/codeweaver/core/di/container.py Restricts callable AST nodes to a safe whitelist prior to eval() during string type resolution.
.jules/sentinel.md Documents the AST-validation ACE finding and mitigation in the security log.

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

Comment on lines +139 to +145
# Security: Restrict callable nodes in `eval` to prevent Arbitrary Code Execution (ACE)
if isinstance(node, ast.Call):
if not isinstance(node.func, ast.Name):
raise TypeError("Only direct function calls are allowed in type annotations")
if node.func.id not in {"Depends", "depends", "Field", "PrivateAttr", "Tag"}:
raise TypeError(f"Forbidden function call in type annotation: {node.func.id}")

@github-actions
Copy link
Copy Markdown
Contributor

Code Review - PR #367: Fix Arbitrary Code Execution in AST validation

Summary

This PR addresses a CRITICAL security vulnerability in the dependency injection container where generic ast.Call nodes were allowed during AST type parsing before being passed to eval(). The fix adds a strict whitelist of allowed function calls to prevent arbitrary code execution.

Security Analysis ✅

The security fix is well-designed and effective:

  1. Proper whitelisting: The code now restricts ast.Call nodes to a carefully chosen set: {Depends, depends, Field, PrivateAttr, Tag}
  2. Defense in depth: The fix adds two layers of validation:
    • Ensures only direct function calls (ast.Name) are allowed (no attribute access like obj.method())
    • Validates the function name against a strict whitelist
  3. Appropriate error messages: Clear TypeError messages help developers understand what went wrong
  4. Good documentation: The .jules/sentinel.md entry properly documents the vulnerability, learning, and prevention strategy

Code Quality ✅

The implementation is clean and follows best practices:

  1. Placement: The security check is correctly placed in TypeValidator.generic_visit at src/codeweaver/core/di/container.py:139-144
  2. Minimal changes: The fix is surgical - only 7 lines added, no deletions
  3. Maintains existing functionality: The fix doesn't break the existing type annotation resolution logic
  4. Existing test coverage: I verified that tests/di/test_container_security.py already contains comprehensive security tests

Recommendations

1. Extract whitelist to a constant (Priority: Medium)

As Sourcery AI noted, consider moving the whitelist to a module-level constant to improve maintainability and avoid repeated set allocations:

# Near the top of the file, after imports
_ALLOWED_ANNOTATION_CALLS = frozenset({"Depends", "depends", "Field", "PrivateAttr", "Tag"})

# Then in the validation code:
if node.func.id not in _ALLOWED_ANNOTATION_CALLS:
    raise TypeError(f"Forbidden function call in type annotation: {node.func.id}")

Using frozenset is slightly more efficient than set for membership testing and signals immutability.

2. Add specific test for the vulnerability (Priority: Low)

Consider adding a test case specifically for this CVE that tries to exploit the exact vulnerability pattern:

def test_ast_call_whitelist_enforcement() -> None:
    """Verify that non-whitelisted function calls in annotations are blocked."""
    container = Container()
    globalns = {"callable_func": lambda: None, "Annotated": Annotated}
    
    # This should be blocked - arbitrary callable in eval namespace
    result = container._resolve_string_type("Annotated[int, callable_func()]", globalns)
    assert result is None, "Non-whitelisted function calls should be blocked"

3. CI failures are unrelated

The failing CI checks appear to be:

  • Build Docker Image: Likely a transient infrastructure issue
  • review / review: The Gemini reviewer failure is not related to this code change

The important checks are passing:

  • ✅ CodeQL security scanning
  • ✅ Lint and Format
  • ✅ Socket Security
  • ✅ Sourcery review
  • ⏳ Python 3.12, 3.13, 3.14 tests (pending)

Verdict: ✅ APPROVE with minor suggestions

This is a critical security fix that effectively closes an arbitrary code execution vulnerability. The implementation is solid, well-documented, and follows security best practices. The minor suggestions above are for code quality improvements but don't block approval.

The code change itself is ready to merge once the Python unit tests complete successfully. The Docker build failure appears unrelated to this security fix.

Great work on identifying and fixing this vulnerability! 🛡️


Review performed 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