Skip to content

🛡️ Sentinel: [CRITICAL] Prevent Arbitrary Code Execution in AST validation#368

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

🛡️ Sentinel: [CRITICAL] Prevent Arbitrary Code Execution in AST validation#368
bashandbone wants to merge 1 commit into
mainfrom
sentinel-ace-ast-call-fix-17808606302312772616

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented May 29, 2026

🚨 Severity: CRITICAL
đź’ˇ Vulnerability: The TypeValidator class inside _safe_eval_type previously used ast.parse and implicitly allowed all ast.Call nodes to bypass validation. This meant any callable (like os.system via sys.modules) present in the globalns dictionary could be executed arbitrarily when the string representation of a type annotation was parsed and then executed using the built-in eval() function.
🎯 Impact: This acts as an Arbitrary Code Execution (ACE) vulnerability. Any potentially unsanitized or user-injected code evaluated via _safe_eval_type during dependency resolution could execute malicious payloads under the permissions of the host system running CodeWeaver.
đź”§ Fix: Created a custom visit_Call method for the ast.NodeVisitor that explicitly checks the function name being executed. The logic limits execution to exactly six safe callables that CodeWeaver intrinsically relies upon for dependency injection (Depends, depends, Field, PrivateAttr, Tag, and Parameter). Any other ast.Call nodes actively trigger a TypeError. Added an inline security comment documenting the reason.
âś… Verification: Ran uv run pytest tests/unit/core/ --no-cov locally to ensure no valid DI annotations were falsely flagged. The entire test suite passed, and code-linting checks via mise //:check passed successfully as well. Added a Sentinel journal entry reflecting the learnings to ensure dynamic evaluation vulnerabilities are continually monitored.


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

Summary by Sourcery

Harden AST-based type string evaluation in the DI container to block arbitrary code execution and document the security lesson in the Sentinel journal.

Bug Fixes:

  • Restrict allowed AST call nodes during type string evaluation in the DI container to a small whitelist of safe dependency-related functions, preventing arbitrary code execution.

Documentation:

  • Add a Sentinel journal entry describing the AST validation arbitrary code execution vulnerability, its root cause, and prevention guidance.

…ation

- Added strict whitelisting to ast.Call nodes in `_safe_eval_type`.
- This prevents execution of arbitrary callables via dynamic type string evaluation.
- Added corresponding documentation in `.jules/sentinel.md`.

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

Reviewer's Guide

Tightens AST-based validation in the DI container to block arbitrary function calls during type-string evaluation by whitelisting only a small set of safe callables, and documents the security fix in the Sentinel journal.

Flow diagram for safe type-string evaluation in _safe_eval_type

flowchart TD
    A[type_str] --> B[ast.parse]
    B --> C[TypeValidator.visit]
    C --> D{ast node type}
    D -->|Call| E[visit_Call]
    D -->|Other| F[generic_visit]

    E --> G{func_name in allowed_calls}
    G -->|No| H[raise TypeError]
    G -->|Yes| I[generic_visit]

    F --> J[validation continues]
    I --> J
    J --> K[eval type_str with globalns]
Loading

File-Level Changes

Change Details Files
Harden AST validation in _safe_eval_type to prevent arbitrary code execution from type-string evaluation.
  • Annotate _safe_eval_type with noqa: C901 to suppress complexity warnings for the function.
  • Add a custom visit_Call implementation in the TypeValidator AST visitor that inspects the called function for each ast.Call node.
  • Derive the function name from ast.Name and ast.Attribute nodes and compare it against a fixed whitelist of allowed callables used for dependency injection.
  • Raise TypeError when a call target is not whitelisted, and continue generic traversal when it is, ensuring other validations still apply.
  • Ensure that any forbidden function calls in type strings are rejected before eval is invoked.
src/codeweaver/core/di/container.py
Record the ACE vulnerability and mitigation details in the security Sentinel journal.
  • Add an entry describing how generic ast.Call allowance in TypeValidator enabled arbitrary code execution in DI type evaluation.
  • Document the key learning that generic AST calls in restricted evaluators can lead to ACE because evaluation must invoke the function.
  • Capture the preventive measure of whitelisting allowed calls (e.g., Depends, Field) via a dedicated visit_Call implementation.
.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 left some high level feedback:

  • Consider moving allowed_calls = {"Depends", "depends", "Field", "PrivateAttr", "Tag", "Parameter"} to a class-level constant or shared module-level set so it isn’t reallocated on every visit_Call and can be reused/updated more easily.
  • When node.func is neither ast.Name nor ast.Attribute, func_name remains an empty string, which produces a slightly confusing error message; you might want to either reject those nodes with a clearer message or include the full ast.dump(node.func) (or similar) in the exception for easier debugging.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider moving `allowed_calls = {"Depends", "depends", "Field", "PrivateAttr", "Tag", "Parameter"}` to a class-level constant or shared module-level set so it isn’t reallocated on every `visit_Call` and can be reused/updated more easily.
- When `node.func` is neither `ast.Name` nor `ast.Attribute`, `func_name` remains an empty string, which produces a slightly confusing error message; you might want to either reject those nodes with a clearer message or include the full `ast.dump(node.func)` (or similar) in the exception for easier debugging.

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.

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

This PR hardens CodeWeaver’s DI container string-annotation resolution by tightening AST validation before eval() is used, with the goal of preventing arbitrary code execution during type evaluation. It also records the incident and mitigation approach in the Sentinel security journal.

Changes:

  • Add a visit_Call override in _safe_eval_type’s AST validator to restrict callable execution to a small whitelist.
  • Mark _safe_eval_type with # noqa: C901 (complexity).
  • Add a Sentinel journal entry documenting the ACE vulnerability and prevention guidance.

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 which ast.Call nodes are permitted during type-string evaluation to reduce ACE risk.
.jules/sentinel.md Documents the vulnerability, learning, and prevention approach in the Sentinel journal.

đź’ˇ Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +141 to +155
def visit_Call(self, node: ast.Call) -> None:
# Security Fix: Prevent Arbitrary Code Execution (ACE)
# Allowing generic ast.Call nodes permits execution of any callable in the globalns.
# We strictly limit ast.Call nodes to safe, required functions.
func_name = ""
if isinstance(node.func, ast.Name):
func_name = node.func.id
elif isinstance(node.func, ast.Attribute):
func_name = node.func.attr

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}")
self.generic_visit(node)

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