Skip to content

πŸ›‘οΈ Sentinel: [CRITICAL] Fix Arbitrary Code Execution vulnerability in type annotation evaluation#357

Open
bashandbone wants to merge 1 commit into
mainfrom
sentinel/fix-ace-in-ast-eval-4029442110563029413
Open

πŸ›‘οΈ Sentinel: [CRITICAL] Fix Arbitrary Code Execution vulnerability in type annotation evaluation#357
bashandbone wants to merge 1 commit into
mainfrom
sentinel/fix-ace-in-ast-eval-4029442110563029413

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented May 22, 2026

🚨 Severity: CRITICAL
πŸ’‘ Vulnerability: Unrestricted ast.Call node parsing in dynamic type evaluation in src/codeweaver/core/di/container.py permitted any callable in the global scope (e.g. os.system) to be executed during resolution.
🎯 Impact: Allowed Arbitrary Code Execution (ACE) under the guise of dependency type injection/resolution.
πŸ”§ Fix: Strictly restricted allowed ast.Call names to well-known safe functions required for framework behavior: Depends, depends, Field, PrivateAttr, and Tag.
βœ… Verification: Verify tests pass and that attempting to dynamically resolve unsafe string types like Annotated[int, print()] explicitly raises a TypeError.


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

Summary by Sourcery

Harden safe AST evaluation for dynamic type annotations to prevent arbitrary code execution and document the security fix in Sentinel notes.

Bug Fixes:

  • Prevent arbitrary code execution via dynamic type annotation evaluation by restricting allowed ast.Call targets to a small set of safe framework functions.

Documentation:

  • Document the AST evaluation arbitrary code execution vulnerability, its root cause, and prevention measures in the Sentinel security log.

Implemented strict whitelisting of allowed function names for `ast.Call` nodes in `container.py`'s safe evaluation of string type annotations. Unrestricted usage previously allowed execution of arbitrary builtins or module functions. Added `Depends`, `depends`, `Field`, `PrivateAttr`, and `Tag` to the whitelist to maintain necessary DI and Pydantic functionality while neutralizing the vulnerability. Recorded critical learning in `.jules/sentinel.md`.

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 22, 2026 17:41
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 22, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Restricts dynamic type annotation evaluation to a safe subset of function calls and documents the security fix in the Sentinel log to prevent arbitrary code execution via AST-based evaluation.

File-Level Changes

Change Details Files
Harden AST-based type string evaluation to prevent arbitrary code execution from call expressions.
  • Add a whitelist check for ast.Call nodes to only allow calls to Depends, depends, Field, PrivateAttr, and Tag in type strings
  • Reject any ast.Call whose callee is not a simple ast.Name, blocking attribute access and other callable forms
  • Raise clear TypeError messages when forbidden calls are encountered during type string evaluation
src/codeweaver/core/di/container.py
Document the new AST call whitelisting mitigation and licensing metadata in Sentinel security notes.
  • Append SPDX copyright and license headers to the Sentinel security documentation file
  • Add a new Sentinel entry describing the AST call vulnerability, impact, and the whitelisting-based prevention approach
.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 extracting the allowed ast.Call function names into a named constant (e.g., SAFE_CALL_NAMES) near the visitor class so they can be reused, extended, or audited more easily.
  • The new ast.Call handling currently allows only bare names; if the framework ever uses qualified calls (e.g., mod.Depends), document that this is intentionally forbidden or adjust the logic to safely support such patterns.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider extracting the allowed `ast.Call` function names into a named constant (e.g., `SAFE_CALL_NAMES`) near the visitor class so they can be reused, extended, or audited more easily.
- The new `ast.Call` handling currently allows only bare names; if the framework ever uses qualified calls (e.g., `mod.Depends`), document that this is intentionally forbidden or adjust the logic to safely support such patterns.

## Individual Comments

### Comment 1
<location path="src/codeweaver/core/di/container.py" line_range="136-137" />
<code_context>
+                # Restrict Arbitrary Code Execution (ACE) via type hints by strictly whitelisting ast.Call
+                if isinstance(node, ast.Call):
+                    if isinstance(node.func, ast.Name):
+                        if node.func.id not in {"Depends", "depends", "Field", "PrivateAttr", "Tag"}:
+                            raise TypeError(f"Forbidden call in type string: {node.func.id}")
+                    else:
+                        raise TypeError("Forbidden call in type string: only simple names are allowed")
</code_context>
<issue_to_address>
**🚨 suggestion (security):** The hard-coded whitelist set may be better centralized and possibly made configurable to avoid scattering security-critical policy.

Since the allowed function names are inlined here, consider extracting them into a shared constant (e.g. `ALLOWED_TYPE_HINT_CALLS`) or config if they’re reused or may change with supported frameworks. Centralizing this policy helps avoid divergence and simplifies auditing these security restrictions.

Suggested implementation:

```python
import ast

# Whitelisted callable names allowed inside type-hint strings when parsing AST
# Centralizing this list makes the security policy easier to audit and update.
ALLOWED_TYPE_HINT_CALLS = {"Depends", "depends", "Field", "PrivateAttr", "Tag"}

```

```python
                # Restrict Arbitrary Code Execution (ACE) via type hints by strictly whitelisting ast.Call
                if isinstance(node, ast.Call):
                    if isinstance(node.func, ast.Name):
                        if node.func.id not in ALLOWED_TYPE_HINT_CALLS:
                            raise TypeError(f"Forbidden call in type string: {node.func.id}")
                    else:
                        raise TypeError("Forbidden call in type string: only simple names are allowed")

```

If this whitelist needs to be framework-configurable in the future, you can:
1. Move `ALLOWED_TYPE_HINT_CALLS` into a dedicated settings/config module and import it here.
2. Or extend it from configuration, e.g. `ALLOWED_TYPE_HINT_CALLS = DEFAULT_ALLOWED_TYPE_HINT_CALLS | settings.EXTRA_ALLOWED_TYPE_HINT_CALLS`.
This depends on how configuration is handled elsewhere in your project.
</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 +136 to +137
if node.func.id not in {"Depends", "depends", "Field", "PrivateAttr", "Tag"}:
raise TypeError(f"Forbidden call in type string: {node.func.id}")
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 (security): The hard-coded whitelist set may be better centralized and possibly made configurable to avoid scattering security-critical policy.

Since the allowed function names are inlined here, consider extracting them into a shared constant (e.g. ALLOWED_TYPE_HINT_CALLS) or config if they’re reused or may change with supported frameworks. Centralizing this policy helps avoid divergence and simplifies auditing these security restrictions.

Suggested implementation:

import ast

# Whitelisted callable names allowed inside type-hint strings when parsing AST
# Centralizing this list makes the security policy easier to audit and update.
ALLOWED_TYPE_HINT_CALLS = {"Depends", "depends", "Field", "PrivateAttr", "Tag"}
                # Restrict Arbitrary Code Execution (ACE) via type hints by strictly whitelisting ast.Call
                if isinstance(node, ast.Call):
                    if isinstance(node.func, ast.Name):
                        if node.func.id not in ALLOWED_TYPE_HINT_CALLS:
                            raise TypeError(f"Forbidden call in type string: {node.func.id}")
                    else:
                        raise TypeError("Forbidden call in type string: only simple names are allowed")

If this whitelist needs to be framework-configurable in the future, you can:

  1. Move ALLOWED_TYPE_HINT_CALLS into a dedicated settings/config module and import it here.
  2. Or extend it from configuration, e.g. ALLOWED_TYPE_HINT_CALLS = DEFAULT_ALLOWED_TYPE_HINT_CALLS | settings.EXTRA_ALLOWED_TYPE_HINT_CALLS.
    This depends on how configuration is handled elsewhere in your project.

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 β€œsafe” evaluation of string type annotations to prevent arbitrary code execution during dependency resolution, and records the incident in the Sentinel security log.

Changes:

  • Added an ast.Call whitelist in Container._safe_eval_type()’s AST validator to only allow framework-required call targets (Depends, depends, Field, PrivateAttr, Tag).
  • Documented the vulnerability and mitigation in .jules/sentinel.md.

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 callable targets in evaluated type strings to a small safe whitelist.
.jules/sentinel.md Adds a Sentinel entry describing the ACE/RCE vector and the whitelist-based mitigation.

πŸ’‘ Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +133 to +139
# Restrict Arbitrary Code Execution (ACE) via type hints by strictly whitelisting ast.Call
if isinstance(node, ast.Call):
if isinstance(node.func, ast.Name):
if node.func.id not in {"Depends", "depends", "Field", "PrivateAttr", "Tag"}:
raise TypeError(f"Forbidden call in type string: {node.func.id}")
else:
raise TypeError("Forbidden call in type string: only simple names are allowed")
Comment thread .jules/sentinel.md
Comment on lines +7 to +8
<!-- SPDX-FileCopyrightText: 2025 Knitli Inc. -->
<!-- SPDX-License-Identifier: MIT OR Apache-2.0 -->
@github-actions
Copy link
Copy Markdown
Contributor

PR Review: Security Fix for Arbitrary Code Execution Vulnerability

Summary

This PR addresses a CRITICAL security vulnerability in the dependency injection container's safe AST evaluation logic. The fix prevents arbitrary code execution during type annotation parsing by implementing strict whitelisting of allowed function calls.


Security Analysis

The Vulnerability

The original code in src/codeweaver/core/di/container.py allowed unrestricted ast.Call nodes during type string evaluation. This meant that type annotations like Annotated[int, os.system('malicious')] or Annotated[int, print()] would execute during dependency resolution, creating a critical arbitrary code execution (ACE) vulnerability.

Attack Vector: Any code that could influence type annotations (configuration files, user input, dynamic imports) could potentially execute arbitrary Python code.

The Fix

The PR adds lines 133-139 in container.py:

# Restrict Arbitrary Code Execution (ACE) via type hints by strictly whitelisting ast.Call
if isinstance(node, ast.Call):
    if isinstance(node.func, ast.Name):
        if node.func.id not in {"Depends", "depends", "Field", "PrivateAttr", "Tag"}:
            raise TypeError(f"Forbidden call in type string: {node.func.id}")
    else:
        raise TypeError("Forbidden call in type string: only simple names are allowed")

Effectiveness: βœ… This fix is correct and effective. It:

  1. Only allows specific framework functions needed for DI/Pydantic functionality
  2. Blocks all other function calls including builtins like print(), eval(), __import__()
  3. Prevents attribute-based calls (e.g., os.system) by requiring simple names only

Code Quality

Strengths

  1. Minimal, focused change - Only adds necessary security controls without refactoring
  2. Clear comments - Well-documented reasoning for the security fix
  3. Appropriate error messages - TypeError with descriptive messages for debugging
  4. Documentation - Excellent Sentinel notes in .jules/sentinel.md documenting the vulnerability, learning, and prevention

Concerns

⚠️ CRITICAL: Missing Test Coverage

The PR description explicitly states:

βœ… Verification: Verify tests pass and that attempting to dynamically resolve unsafe string types like Annotated[int, print()] explicitly raises a TypeError.

However, no tests were added to verify this critical security fix. While tests/di/test_container_security.py exists with tests for other security concerns, it does not include:

  1. A test verifying that Annotated[int, print()] raises TypeError
  2. A test verifying that Annotated[int, os.system('...')] raises TypeError
  3. A test verifying that allowed calls (Depends, Field, etc.) still work

Recommendation: Add these critical tests before merging:

def test_forbidden_calls_in_annotated_types() -> None:
    """Verify that function calls other than whitelisted ones are blocked."""
    container = Container()
    globalns = {"Annotated": Annotated, "int": int, "print": print}
    
    # Should block print()
    result = container._resolve_string_type("Annotated[int, print()]", globalns)
    assert result is None
    
    # Should allow Depends()
    globalns["Depends"] = Depends
    result = container._resolve_string_type("Annotated[int, Depends()]", globalns)
    assert result is not None

Whitelist Analysis

The allowed function names are:

  • Depends / depends - DI markers βœ…
  • Field - Pydantic field configuration βœ…
  • PrivateAttr - Pydantic private attributes βœ…
  • Tag - DI tagging system βœ…

Question: Should Tag be in this whitelist? I don't see it imported or used in the container module. If it's not actually needed for type resolution, it should be removed from the whitelist to minimize attack surface.


CI Failures

The PR has failing CI checks:

  • ❌ Build Docker Image - Failed
  • ❌ review / review - Failed

These failures appear unrelated to the code changes (based on the limited log output), but should be investigated before merge.


Recommendations

  1. MUST FIX: Add comprehensive test coverage for this security fix
  2. SHOULD FIX: Verify Tag is actually needed in the whitelist, remove if not
  3. SHOULD FIX: Investigate and resolve CI failures
  4. NICE TO HAVE: Consider adding a security-focused integration test that attempts actual exploit scenarios

Verdict

Status: ⚠️ Request Changes

The security fix itself is excellent and critical, but the lack of test coverage for such a critical vulnerability is concerning. This is a textbook example where tests are not optional - they serve as regression prevention for a severe security issue.

Once tests are added, this should be merged immediately as it addresses a CRITICAL vulnerability.


Security Impact: πŸ”΄ CRITICAL (ACE vulnerability)
Code Quality: 🟒 Good (clear, minimal, well-documented)
Test Coverage: πŸ”΄ Missing (critical gap)
Overall: ⚠️ Approve with required test additions

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