← Back to Pull requests

Keep flow files from reaching installed code and values when reading signatures #119

Merged
chrisguidry merged 8 files (1102 lines) on Nov 24, 2026 21:42 UTC
View on GitHub
chrisguidry chrisguidry commented on Nov 24, 2026 20:03 UTC
Author

After #117, signature_from_source still let a flow file reach code and data on the deploying machine. Enum hooks like _missing_, non-enum mixin bases, and Field(default_factory=...) could call installed functions with arguments from the file. Pydantic evaluated strings the file built, like X = "..." in def f(x: X) or RootModel["..."], as forward references. Installed values such as os.environ, a BaseSettings model, an ImportString field validated through a default_factory, or a module's install path could end up in the uploaded parameter schema. Small files could also take tens of seconds or gigabytes of memory, through huge integers, str() growth, self-repeating tuples and type aliases, long | chains, and model subclass chains.

From installed modules, the file can now only reach modules, classes, typing constructs, enum members, time zones, and the fixed list of value constructors. Enums are rebuilt only from the standard enum bases, with str, int, or float mixins, or from a member-less enum in the same file. Models are rebuilt only from BaseModel or a model in the same file. Underscored enum members and model fields are skipped. Callable arguments must be value constructors, and calling a rebuilt model uses model_construct, so no installed field type is ever instantiated. Annotations that still hold a string outside Literal values or Annotated metadata are unknown, and subscript keys on installed types are checked before the subscript runs. Strings, integers, decimals, collections, unions, and the number of rebuilt fields are all bounded. The reader also gained enum.auto(), arithmetic on numbers, and enum .name/.value. A file that will not parse now gets "Could not parse" from the CLI instead of "Could not find function".

As before, anything the reader won't evaluate makes that parameter untyped, or its default None, without failing the deploy. Lost fidelity compared with main: installed constants used as defaults (like os.sep), quoted forward references nested in generics, BaseSettings and RootModel parameter types, integers over 128 bits, strings over 10,000 characters, and defaults or annotations over 1,000 items. Rebuilt model defaults are no longer coerced to their field types. Importing an installed module still runs its top-level code; the module docstring now says so. callables.py now treats a pydantic SchemaError like the other schema failures, and deployments.py annotates with builtins.list because a newer pyright read list[...] there as that module's own list function.

<details>
<summary>Session context</summary>

A late review of #117 listed ways a flow file could still run code or read the environment through signature_from_source. I reproduced them first: marker files appeared through an enum _missing_ hook, a subprocess.Popen mixin, and a default_factory, and os.environ and BaseSettings values appeared in defaults. The first commit restricted what installed objects the file can reach and fixed the smaller items. Two rounds of independent adversarial reviewers (three, then two) then attacked the branch for code execution, data leaks, and resource use. Each round found real problems: forward-reference eval through built strings and RootModel[...], a full os.environ dump through ImportString with validate_default behind a default_factory, install paths through str(module) and str-mixin enums, and several quadratic or exponential slowdowns. Each one has a regression test that failed before its fix. Tests pass on Python 3.10, 3.12, and 3.14.

</details>

🤖 Generated with Claude Code

https://claude.ai/code/session_01KgFwscCHoKkVwXCDDKXMdt

Diff: 1102 lines (+1039 / -63) across 8 files Reviewer: gaker Review duration: 99m
All Vouch review confidence checks passed
Residual risk 0.08 = Change Risk (0.53) × (1 − Review Confidence (0.85)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.53 · 1102 lines diff across 8 files
0.53
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.80 · 5 substantive comment(s)
0.80
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
85%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Real PR Conversation Timeline
8 items
chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 24, 2026 20:16 UTC
Bot

<!-- codex-pull-request-review-summary -->
<!-- codex-review-state:v1 {"code_review":{"commit_sha":"e93bd1ba56259c379b6849105ef4eab55c811e4a","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} -->

<details>
<summary><strong>Codex Review Summary</strong>: ✅ Completed</summary>

This comment shows the latest Codex review activity on this pull request.

| Review | Status | Commit | Review trigger |
| --- | --- | --- | --- |
| 📝 Code Review | ✅ Completed <relative-time datetime="2026-11-24T20:20:37.847597Z">2026-11-24T20:20:37.847597Z</relative-time> | e93bd1b | Draft marked ready |

<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review" or "@codex security review".
  • Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

    </details>

    </details>

    gaker gaker approved these changes on Nov 24, 2026 20:16 UTC
    Approved Reviewer

    Approved these changes.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 24, 2026 20:20 UTC
    Reviewer

    <!-- codex-review-receipt:v1 -->

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: e93bd1ba56

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 24, 2026 20:20 UTC
    Code Review
    src/prefect_cloud/utilities/source_signature.py:1
    @@ -296,16 +472,112 @@ def _apply(function: Any, *args: Any, **kwargs: Any) -> Any:
                 raise UnknownExpression(str(e)) from e
     
     
    -def _first_subclass(bases: list[Any], parent: type) -> Optional[Any]:
    -    return next(
    -        (base for base in bases if isinstance(base, type) and issubclass(base, parent)),
    -        None,
    -    )
    +def _check_argument(argument: Any) -> None:
    +    """Arguments to value constructors have to be data.
    +
    +    A callable argument could be called later, as pydantic calls a
    +    `default_factory`, so it has to be one of `VALUE_CONSTRUCTORS`.  Rebuilt
    +    model classes are not allowed there, because calling one validates its
    +    fields."""
    +    _check_structure(argument, is_annotation=False)
    +    if callable(argument) and not any(
    +        argument is allowed for allowed in VALUE_CONSTRUCTORS
    +    ):
    +        raise UnknownExpression(f"callable argument {argument!r}")
    +
    +
    +def _is_enum_class(value: Any) -> bool:
    +    return isinstance(value, type) and issubclass(value, enum.Enum)
    +
    +
    +def _check_subscript_key(container: Any, key: Any) -> None:
    +    items = list(key) if isinstance(key, tuple) else [key]
    +    if container in LITERALS:
    +        _check_structure(items, is_annotation=False)
    +    elif container in ANNOTATED:
    +        _check_structure(items[:1], is_annotation=True)
    +        _check_structure(items[1:], is_annotation=False)
    +    else:
    +        _check_structure(items, is_annotation=True)
    +
    +
    +def _check_structure(root: Any, *, is_annotation: bool) -> None:
    +    """Reject an annotation or value that pydantic could not handle safely.
    +
    +    In an annotation, pydantic resolves a string as a forward reference with
    +    `eval`, so a string the file built, like `X = "open(...)"` in `def f(x: X)`,
    +    would run as code.  Strings are allowed only as `Literal` values and in
    +    `Annotated` metadata, which pydantic does not resolve.  Annotations and
    +    values are also limited in size and depth.  The walk is iterative and stops
    +    at the size limit, so a structure that repeats itself cannot slow it down.
    +
    +    Modules are rejected anywhere, because converting one to a string, as
    +    `str()` or a `str` enum mixin does, includes the path it was installed at.
    +    """
    +    pending: list[tuple[Any, bool, int]] = [(root, is_annotation, 0)]
    +    visited = 0
    +    while pending:
    +        value, in_annotation, depth = pending.pop()
    +        visited += 1
    +        if visited > MAX_STRUCTURE_ITEMS or depth > MAX_STRUCTURE_DEPTH:
    +            raise UnknownExpression("structure too large")
    +        if in_annotation and isinstance(value, (str, typing.ForwardRef)):
    +            raise UnknownExpression("annotation with a forward reference")
    +        if isinstance(value, types.ModuleType):
    +            raise UnknownExpression("module in a value")
    +
    +        children: list[tuple[Any, bool]] = []
    +        if isinstance(value, (list, tuple, set, frozenset)):
    +            children = [(item, in_annotation) for item in value]
    +        elif isinstance(value, dict):
    +            children = [
    +                (item, in_annotation) for pair in value.items() for item in pair
    +            ]
    +        elif isinstance(value, pydantic.BaseModel):
    +            children = [(item, False) for item in value.__dict__.values()]
    +        elif isinstance(value, FieldInfo):
    +            children = [(value.default, False)]
    +        elif in_annotation:
    +            origin = typing.get_origin(value)
    +            arguments = typing.get_args(value)
    +            if origin in LITERALS:
    +                children = [(item, False) for item in arguments]
    +            elif origin in ANNOTATED:
    +                children = [(arguments[0], True)] + [
    +                    (item, False) for item in arguments[1:]
    +                ]
    +            else:
    +                children = [(item, True) for item in arguments]
    +        pending.extend(
    +            (child, child_in_annotation, depth + 1)
    +            for child, child_in_annotation in children
    +        )
    +
    +
    +def _is_number(value: Any) -> bool:
    +    return isinstance(value, (int, float, complex)) and not isinstance(value, bool)
    +
    +
    +def _bounded(value: Any) -> Any:
    +    if isinstance(value, int) and value.bit_length() > MAX_INTEGER_BITS:
    +        raise UnknownExpression("integer too large")
    +    if (
    +        isinstance(value, decimal.Decimal)
    +        and value.is_finite()
    +        and abs(value.adjusted()) > MAX_DECIMAL_EXPONENT
    +    ):
    +        raise UnknownExpression("decimal too large")
    +    if isinstance(value, (str, bytes)) and len(value) > MAX_STRING_LENGTH:
    +        raise UnknownExpression("string too long")
    +    return value

    <sub><sub>!P1 Badge</sub></sub> Bound constructed path values before returning

    Path and PurePath are allowed variadic constructors, but this bound treats their results as atomic and returns them unchecked. An untrusted flow can repeatedly construct P1 = Path(P0, P0, ...), then repeat P1 in later paths; each argument passes _check_argument, while pathlib exponentially expands the stored parts and eventually exhausts memory or creates an enormous schema when stringified. Bound path length/parts and aggregate constructor arguments rather than only str and bytes results.

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chrisguidry chrisguidry commented on code on Nov 24, 2026 20:22 UTC
    Code Review
    src/prefect_cloud/utilities/source_signature.py:1
    @@ -296,16 +472,112 @@ def _apply(function: Any, *args: Any, **kwargs: Any) -> Any:
                 raise UnknownExpression(str(e)) from e
     
     
    -def _first_subclass(bases: list[Any], parent: type) -> Optional[Any]:
    -    return next(
    -        (base for base in bases if isinstance(base, type) and issubclass(base, parent)),
    -        None,
    -    )
    +def _check_argument(argument: Any) -> None:
    +    """Arguments to value constructors have to be data.
    +
    +    A callable argument could be called later, as pydantic calls a
    +    `default_factory`, so it has to be one of `VALUE_CONSTRUCTORS`.  Rebuilt
    +    model classes are not allowed there, because calling one validates its
    +    fields."""
    +    _check_structure(argument, is_annotation=False)
    +    if callable(argument) and not any(
    +        argument is allowed for allowed in VALUE_CONSTRUCTORS
    +    ):
    +        raise UnknownExpression(f"callable argument {argument!r}")
    +
    +
    +def _is_enum_class(value: Any) -> bool:
    +    return isinstance(value, type) and issubclass(value, enum.Enum)
    +
    +
    +def _check_subscript_key(container: Any, key: Any) -> None:
    +    items = list(key) if isinstance(key, tuple) else [key]
    +    if container in LITERALS:
    +        _check_structure(items, is_annotation=False)
    +    elif container in ANNOTATED:
    +        _check_structure(items[:1], is_annotation=True)
    +        _check_structure(items[1:], is_annotation=False)
    +    else:
    +        _check_structure(items, is_annotation=True)
    +
    +
    +def _check_structure(root: Any, *, is_annotation: bool) -> None:
    +    """Reject an annotation or value that pydantic could not handle safely.
    +
    +    In an annotation, pydantic resolves a string as a forward reference with
    +    `eval`, so a string the file built, like `X = "open(...)"` in `def f(x: X)`,
    +    would run as code.  Strings are allowed only as `Literal` values and in
    +    `Annotated` metadata, which pydantic does not resolve.  Annotations and
    +    values are also limited in size and depth.  The walk is iterative and stops
    +    at the size limit, so a structure that repeats itself cannot slow it down.
    +
    +    Modules are rejected anywhere, because converting one to a string, as
    +    `str()` or a `str` enum mixin does, includes the path it was installed at.
    +    """
    +    pending: list[tuple[Any, bool, int]] = [(root, is_annotation, 0)]
    +    visited = 0
    +    while pending:
    +        value, in_annotation, depth = pending.pop()
    +        visited += 1
    +        if visited > MAX_STRUCTURE_ITEMS or depth > MAX_STRUCTURE_DEPTH:
    +            raise UnknownExpression("structure too large")
    +        if in_annotation and isinstance(value, (str, typing.ForwardRef)):
    +            raise UnknownExpression("annotation with a forward reference")
    +        if isinstance(value, types.ModuleType):
    +            raise UnknownExpression("module in a value")
    +
    +        children: list[tuple[Any, bool]] = []
    +        if isinstance(value, (list, tuple, set, frozenset)):
    +            children = [(item, in_annotation) for item in value]
    +        elif isinstance(value, dict):
    +            children = [
    +                (item, in_annotation) for pair in value.items() for item in pair
    +            ]
    +        elif isinstance(value, pydantic.BaseModel):
    +            children = [(item, False) for item in value.__dict__.values()]
    +        elif isinstance(value, FieldInfo):
    +            children = [(value.default, False)]
    +        elif in_annotation:
    +            origin = typing.get_origin(value)
    +            arguments = typing.get_args(value)
    +            if origin in LITERALS:
    +                children = [(item, False) for item in arguments]
    +            elif origin in ANNOTATED:
    +                children = [(arguments[0], True)] + [
    +                    (item, False) for item in arguments[1:]
    +                ]
    +            else:
    +                children = [(item, True) for item in arguments]
    +        pending.extend(
    +            (child, child_in_annotation, depth + 1)
    +            for child, child_in_annotation in children
    +        )
    +
    +
    +def _is_number(value: Any) -> bool:
    +    return isinstance(value, (int, float, complex)) and not isinstance(value, bool)
    +
    +
    +def _bounded(value: Any) -> Any:
    +    if isinstance(value, int) and value.bit_length() > MAX_INTEGER_BITS:
    +        raise UnknownExpression("integer too large")
    +    if (
    +        isinstance(value, decimal.Decimal)
    +        and value.is_finite()
    +        and abs(value.adjusted()) > MAX_DECIMAL_EXPONENT
    +    ):
    +        raise UnknownExpression("decimal too large")
    +    if isinstance(value, (str, bytes)) and len(value) > MAX_STRING_LENGTH:
    +        raise UnknownExpression("string too long")
    +    return value

    Valid: paths weren't covered by the string length bound. Fixed in https://github.com/PrefectHQ/prefect-cloud/commit/100500aca9506e8f926b9ed28fc7530b746ef656: paths now count toward that bound, and the combined length of string and path arguments is checked before a value constructor runs.

    ---
    Posted by Claude Opus 5.5 on behalf of @chrisguidry.
    <!-- monitor-pr -->

    bunchesofdonald bunchesofdonald commented on Nov 24, 2026 21:24 UTC
    Contributor

    My Claude reviewed this for schema output only, so please don't count it as a security review. Two changes from main, both reproduced at 100500a:

    1. source_signature.py:495: a model field like i: I = Field(default_factory=I), with I a model in the same file, now gets {"$ref": "#/definitions/I", "default": null}. On main it has no default. Null isn't valid for I. Leaving the default out when the factory is refused would keep main's schema.

    2. def f(x: M = M(a='bad')), where a is an int, now uploads {"a": "bad"} as the default. On main it's null. The description says defaults aren't coerced anymore, but not that invalid ones get through.

    chrisguidry chrisguidry commented on Nov 24, 2026 21:32 UTC
    Author

    @bunchesofdonald Thanks, both reproduced and fixed in 9e3b16a. A refused default_factory now leaves the field with no default, as on main. Rebuilt models whose fields use only builtin and standard value types, annotated_types constraints, and enums and models from the same file are now validated, so M(a='bad') is null again and M(a='5') becomes 5. Models with other field types, like ImportString, FilePath, or a BaseSettings model, still skip validation, because their validators can import modules, check files, or read the environment, so an invalid default can still get through for those.

    ---
    Posted by Claude Opus 5.5 on behalf of @chrisguidry.
    <!-- monitor-pr -->

    Reviewers
    Assignees
    chrisguidry chrisguidry
    Labels
    risk: low confidence: 85.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 53.2% (MEDIUM) · Higher = larger blast radius
    53.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.5% · Lower = rushed or shallow review
    85.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.7% · Safe to merge
    7.7%