Skip to content

πŸ›‘οΈ Sentinel: [CRITICAL] Prevent Arbitrary Code Execution in type evaluations#372

Open
bashandbone wants to merge 1 commit into
mainfrom
sentinel-fix-ace-vulnerability-6024749506626654658
Open

πŸ›‘οΈ Sentinel: [CRITICAL] Prevent Arbitrary Code Execution in type evaluations#372
bashandbone wants to merge 1 commit into
mainfrom
sentinel-fix-ace-vulnerability-6024749506626654658

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented May 31, 2026

🚨 Severity: CRITICAL

πŸ’‘ Vulnerability:
The Container._safe_eval_type function evaluates type strings by constructing an Abstract Syntax Tree (AST) using ast.parse and then ensuring it is "safe" before calling Python's eval() on it. Previously, it allowed all generic ast.Call nodes to be present in the tree. Because the AST was ultimately compiled and passed to eval() with the module's globalns, this flaw inherently allowed evaluating strings to invoke any callable within the globalns dictionary or Python's __builtins__, resulting in an Arbitrary Code Execution (ACE) vulnerability.

🎯 Impact:
If an attacker could manipulate or inject arbitrary string type representations that _safe_eval_type processes (potentially through type inference APIs, dependency injection configurations, or dynamic parsing mechanisms), they could inject malicious ast.Call nodes. Since it fell through to eval(), it could be used to execute unintended underlying logic with the permissions of the application process.

πŸ”§ Fix:
Implemented a strict node validation layer by overriding the visit_Call method in the TypeValidator class. Now, ast.Call nodes are strongly restricted. If an ast.Call appears in the type string tree, it validates that the function call strictly matches a specific, hardcoded whitelist of expected dependency injection and type system functions (e.g., Depends, Parameter, Field, PrivateAttr, Tag). Any unexpected callable throws a TypeError, aborting the evaluation before eval() can be reached. An inline comment explaining the security concern was added alongside the fix.

βœ… Verification:

  1. Confirmed local changes explicitly enforce whitelist logic with ast.Call evaluations.
  2. Verified functionality using the primary backend test suite for core/di/ via pytest.
  3. Validated proper linting formatting passing mise //:check.
  4. Logged finding correctly inside .jules/sentinel.md.

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

Summary by Sourcery

Harden type string evaluation in the DI container to prevent arbitrary code execution and document the associated Sentinel security finding.

Bug Fixes:

  • Disallow arbitrary function calls in _safe_eval_type by validating ast.Call nodes against a strict whitelist of permitted functions before evaluation.

Enhancements:

  • Annotate _safe_eval_type with a complexity linter override and add inline documentation explaining the security rationale for restricting ast.Call nodes.

Documentation:

  • Record the new Arbitrary Code Execution vulnerability and its mitigation details in .jules/sentinel.md for future security tracking.

Restricts `ast.Call` nodes to a strict whitelist of explicitly required functions (`Depends`, `Field`, `Parameter`, `PrivateAttr`, `Tag`, `cast`, `depends`, `length`, `uuid7`) during dynamic type evaluations in `Container._safe_eval_type`. This prevents an Arbitrary Code Execution (ACE) vulnerability where potentially unvalidated type strings could call unrestricted functions from the module's global namespace. Added security finding to Sentinel's journal.

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

Reviewer's Guide

Introduces stricter AST validation for type string evaluation by whitelisting allowed function calls in Container._safe_eval_type, preventing arbitrary code execution, and documents the security fix in the Sentinel log.

Flow diagram for safe type string evaluation with whitelisted ast.Call

flowchart TD
    A[type_str input] --> B[ast.parse]
    B --> C[TypeValidator.visit]
    C --> D{ast.Call node?}
    D -- no --> F[eval compiled AST]
    D -- yes --> E[visit_Call]
    E --> G{func_name in allowed_functions?}
    G -- no --> H[raise TypeError]
    G -- yes --> I[generic_visit]
    I --> F[eval compiled AST]
Loading

File-Level Changes

Change Details Files
Harden type string evaluation by strictly whitelisting allowed function calls in AST Call nodes.
  • Add a visit_Call override in the TypeValidator inner class of _safe_eval_type to inspect all ast.Call nodes.
  • Derive the called function name from ast.Name and ast.Attribute nodes and compare it against a hardcoded whitelist of safe function names.
  • Raise TypeError when any non-whitelisted function is encountered, aborting evaluation before eval() is reached.
  • Call generic_visit after validation to continue traversing child nodes.
  • Mark _safe_eval_type with # noqa: C901 to suppress function complexity lint warnings.
src/codeweaver/core/di/container.py
Document the newly discovered and fixed ACE vulnerability in the Sentinel security log.
  • Append a dated entry describing the unsafe handling of ast.Call nodes in _safe_eval_type.
  • Record learnings about ACE risk from generic call allowance in AST-based validators.
  • Document prevention guidance emphasizing strict whitelisting of allowed functions in 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
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 hoisting the allowed_functions frozenset to a module- or class-level constant so it isn’t recreated on every visit_Call and can be more easily shared or updated in one place.
  • In visit_Call, you currently accept any ast.Attribute by checking only node.func.attr; if you care about tightening security further, you may want to validate the attribute’s base (e.g., ensure it’s from an expected module or name) rather than only whitelisting the attribute name.
  • When func_name cannot be resolved (e.g., non-Name/Attribute callables), consider raising with a clearer message like 'Unknown or dynamic callable in type string' instead of interpolating None, which will make debugging and log scanning easier.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider hoisting the `allowed_functions` frozenset to a module- or class-level constant so it isn’t recreated on every `visit_Call` and can be more easily shared or updated in one place.
- In `visit_Call`, you currently accept any `ast.Attribute` by checking only `node.func.attr`; if you care about tightening security further, you may want to validate the attribute’s base (e.g., ensure it’s from an expected module or name) rather than only whitelisting the attribute name.
- When `func_name` cannot be resolved (e.g., non-`Name`/`Attribute` callables), consider raising with a clearer message like `'Unknown or dynamic callable in type string'` instead of interpolating `None`, which will make debugging and log scanning easier.

## Individual Comments

### Comment 1
<location path="src/codeweaver/core/di/container.py" line_range="156-161" />
<code_context>
+                    "uuid7",
+                })
+                func_name = None
+                if isinstance(node.func, ast.Name):
+                    func_name = node.func.id
+                elif isinstance(node.func, ast.Attribute):
+                    func_name = node.func.attr
+
+                if func_name not in allowed_functions:
+                    raise TypeError(f"Forbidden function call in type string: {func_name}")
+
</code_context>
<issue_to_address>
**🚨 issue (security):** Tighten handling of attribute calls to avoid unexpected qualified names slipping through

Currently any `ast.Attribute` is accepted if its `.attr` is whitelisted, regardless of the base expression, so `dangerous.depends(...)` is treated like `depends(...)`. To avoid unintended qualified calls, consider either rejecting attribute calls entirely or only allowing them when the base is an explicitly approved name/module. This narrows the allowed surface for type string evaluation.
</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 +156 to +161
if isinstance(node.func, ast.Name):
func_name = node.func.id
elif isinstance(node.func, ast.Attribute):
func_name = node.func.attr

if func_name not in allowed_functions:
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): Tighten handling of attribute calls to avoid unexpected qualified names slipping through

Currently any ast.Attribute is accepted if its .attr is whitelisted, regardless of the base expression, so dangerous.depends(...) is treated like depends(...). To avoid unintended qualified calls, consider either rejecting attribute calls entirely or only allowing them when the base is an explicitly approved name/module. This narrows the allowed surface for type string evaluation.

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 DI type-string evaluation by adding validation for function calls in _safe_eval_type, aiming to prevent arbitrary callable execution during annotation resolution. It also records the security finding in the Sentinel log.

Changes:

  • Adds an ast.Call visitor that restricts callable names to a whitelist before eval().
  • Documents the ACE risk and mitigation in .jules/sentinel.md.
  • Adds a complexity lint suppression for _safe_eval_type.

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 call whitelist validation during safe type evaluation.
.jules/sentinel.md Logs the dynamic type evaluation security finding and prevention guidance.

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

Comment on lines +158 to +161
elif isinstance(node.func, ast.Attribute):
func_name = node.func.attr

if func_name not in allowed_functions:

super().generic_visit(node)

def visit_Call(self, node: ast.Call) -> None:
@github-actions
Copy link
Copy Markdown
Contributor

Pull Request Review

Summary

This PR addresses a critical security vulnerability (CVE-level) in the DI container's type evaluation system by implementing strict whitelisting for ast.Call nodes in Container._safe_eval_type.

Vulnerability Analysis

The vulnerability was real and serious:

  • The previous code allowed arbitrary ast.Call nodes during type string evaluation
  • Since the AST was compiled and passed to eval() with the module's globalns, any callable in the namespace could be invoked
  • This could lead to Arbitrary Code Execution (ACE) if an attacker could inject malicious type strings

Code Quality Review

βœ… Strengths

  1. Security Fix is Sound: The implementation correctly restricts ast.Call nodes to a hardcoded whitelist of legitimate DI/type functions:

    • Depends, Field, Parameter, PrivateAttr, Tag
    • cast, depends, length, uuid7
  2. Good Documentation: Inline comment clearly explains the security rationale (lines 142-143)

  3. Proper Error Handling: Returns None via TypeError when forbidden functions are encountered, maintaining backward compatibility

  4. Test Coverage: tests/di/test_container_security.py includes comprehensive security tests:

    • test_malicious_type_resolution() validates blocking of malicious strings
    • test_safe_type_resolution() ensures legitimate types still work
    • test_dunder_blocking() validates dunder access prevention
  5. Complexity Annotation: noqa: C901 acknowledges the function's complexity

⚠️ Areas for Consideration

  1. Whitelist Completeness: The whitelist includes uuid7 and length - verify these are actually used in type annotations. If not, consider removing them to minimize attack surface per principle of least privilege.

  2. Function Name Extraction: The logic only checks ast.Name and ast.Attribute nodes:

    func_name = None
    if isinstance(node.func, ast.Name):
        func_name = node.func.id
    elif isinstance(node.func, ast.Attribute):
        func_name = node.func.attr

    This means complex call patterns (e.g., getattr(...)(), subscripted callables) will have func_name = None and be blocked, which is the safe default. Good defensive programming.

  3. Edge Case: Nested calls like Depends(factory()) - does factory need to be whitelisted? Current code recursively visits children (self.generic_visit(node)), so nested calls will also be validated. This is correct.

CI Failures

The failing checks appear unrelated to this PR:

  1. Docker build failure: Dependency resolution issue with code-weaver-daemon==0.1.2.post9.dev0 - this is a packaging problem, not related to the security fix
  2. Review job failure: Appears to be CI infrastructure issue (Gemini CLI setup)

The relevant checks passed:

  • βœ… Lint / Lint and Format (2m11s)
  • βœ… CodeQL
  • βœ… Socket Security
  • βœ… Sourcery review

Recommendation

APPROVE with minor suggestions:

  1. Consider documenting why uuid7 and length are in the whitelist
  2. Consider adding a test case for nested function calls: Annotated[int, Depends(Field())]
  3. The Sentinel documentation in .jules/sentinel.md has wrong date (2026-04-22 should be 2026-05-31)

Security Impact

This fix successfully prevents a critical ACE vulnerability. The implementation follows security best practices with fail-safe defaults and clear documentation.

Verdict: βœ… APPROVED - This is an important security fix that should be merged once CI issues are resolved.

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