Skip to content

Fail CI on exec, eval or compile of an interpolated string - #365

Closed
danielhanchen wants to merge 25 commits into
mainfrom
harden-exec-sinks
Closed

danielhanchen wants to merge 25 commits into
mainfrom
harden-exec-sinks

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

Summary

unslothai/unsloth-zoo#1083 closed one arbitrary-code-execution path: a model_type read straight out of a downloaded config.json was interpolated into a string that was then exec'd, so a hostile model repo got code execution with no trust_remote_code. This is the lint that stops the shape coming back.

What it flags

scripts/lint_dynamic_exec.py walks the AST of every package file and every notebook code cell, and fails on a call to exec / eval / compile whose source argument is a built string: an f-string, a string BinOp, a % or .format() construction, or any of those reached through one level of local indirection, a text constructor, or another spelling of the builtin. Bare exec(source) is not flagged.

Notebook cells are read through the IPython machinery that decides whether the body is executed Python at all: cell and line magics, captures, automagic, shell continuations, %%script with its interpreter options, and env wrappers. A %%bash cell is not Python, and a %%script python --help body is data the interpreter never reads.

Reviewed sites live in scripts/dynamic_exec_allowlist.json with a written reason each, keyed on the path, the enclosing qualname and a hash of ast.unparse of the call, so reformatting keeps a justification while changing what gets interpolated invalidates it. This repo currently needs no entries.

Stdlib only, so it runs in the existing source-lint job with no new dependency, and it has a --self-test.

Testing

  • --self-test and the live scan are green on Python 3.9 and 3.13
  • tests/security/test_lint_dynamic_exec.py: 126 cases, grouped by what each one proves
  • a 325-file regression corpus gives identical per-file findings across this copy and the unsloth and unsloth-zoo copies, which stay byte-identical apart from DEFAULT_TARGETS

The one failing check, notebook static checks, is pre-existing on main: nb/Kaggle-Qwen3.8_(27B)-GRPO.ipynb was added without its python_scripts mirror. Reproduced with this branch's changes stashed, same 143 failures.

Related

unslothai/unsloth#9827 and unslothai/unsloth-zoo#1113 carry the same checker; unslothai/unsloth-zoo#1108 merged it there already.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Checked the things that could make a lint like this a nuisance rather than a guard.

  • it passes on the branch, and its --self-test passes, so a broken lint fails loudly instead of silently approving everything
  • the allowlist is keyed on a sha256 of ast.unparse of the call, not on raw source. pre-commit.ci reformatted the sibling branch on unslothai/unsloth after I opened it, touching the lint and five test files, and every allowlist entry still validated. Keying on raw text or on line numbers would have gone red on a whitespace change
  • no allowlist key carries a backslash, so an entry regenerated on Windows still matches on Linux and vice versa. The lint normalises with as_posix() and never references os.sep
  • stdlib only, so source-lint needs no new dependency

tests/security: 32 passed. This repo has no interpolated dynamic-execution call today, so the allowlist ships empty and the lint exists to keep it that way.

Nothing here overlaps #364, which is the one that actually changes what the GRPO notebooks execute.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b8dff8e736

ℹ️ About Codex in GitHub

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".

Comment thread scripts/lint_dynamic_exec.py Outdated
Comment on lines +132 to +133
if reason is None:
self.tainted[-1].pop(target.id, None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve taint across conditional reassignments

When code assigns an interpolated source and conditionally replaces it with a literal, such as source = f"import {x}"; if trusted: source = "import os"; exec(source), the AST visitor unconditionally processes the branch assignment and clears source. The lint therefore reports no finding even though the false branch executes the interpolated value; taint must be merged conservatively across control-flow branches rather than cleared by any syntactically later assignment.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one. Branch-sensitive taint is a dataflow analysis and this is a heuristic CI gate. One level of local indirection is fixed because that is a two-line refactor of an existing shape.

Comment thread scripts/lint_dynamic_exec.py Outdated
Comment on lines +129 to +133
reason = _is_interpolated(node.value)
for target in node.targets:
if not isinstance(target, ast.Name): continue
if reason is None:
self.tainted[-1].pop(target.id, None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Propagate taint through name-to-name assignments

When an interpolated value is copied before execution, such as source = f"import {x}"; payload = source; exec(payload), _is_interpolated() returns None for the Name RHS and this assignment clears payload instead of inheriting source's taint. The hard gate consequently exits successfully for the same vulnerable source after an ordinary variable-extraction refactor; consult the current taint map when the assignment value is a name.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one, for the same reason: chaining name-to-name propagation is the start of general dataflow. The bounded bypasses with a real mechanism, builtins. and compile's source keyword, are both fixed.

justification without review. The location is half of what was reviewed, so it is
half of the key.
"""
return f"{finding['path']}::{finding['qualname']}::{finding['hash']}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Distinguish duplicate calls within the same qualname

If a byte-identical dynamic-execution call is copied elsewhere within the same function or module, both sites have the same path, qualname, and normalized-call hash, so they produce the same allowlist key. Once the original is reviewed, the copied call is silently accepted even though its surrounding control flow or inputs may require a different justification; include a per-site discriminator or reject duplicate keys.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one. Two identical calls in the same function legitimately share one justification, and a positional discriminator would reintroduce the line-number drift the ast.unparse hash exists to avoid. No approval spans two different locations, which is the property that matters.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9889070550

ℹ️ About Codex in GitHub

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".

Comment thread scripts/lint_dynamic_exec.py Outdated
Comment on lines +129 to +131
# A fresh scope: a name built in one function says nothing about the same name
# in another.
self.tainted.append({})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve taint for captured names in nested scopes

When an inner function executes an interpolated value captured from its enclosing function or module, such as payload = f"import {module}" followed by def run(): exec(payload), replacing the taint map with an empty one makes the sink appear clean even though Python resolves the unshadowed name from the outer scope. Nested scopes should retain access to ancestor taint while accounting for names actually rebound locally.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one, and it is worth saying why, because the bypass itself is real: exec(payload) inside an inner function does resolve an outer payload.

The problem is that the proposed remedy, inheriting taint from ancestor scopes, is wrong in both directions.

  • Class bodies are not links in the closure chain. Names defined in a class block do not extend to the code blocks of methods, and _enter handles ClassDef through the same code path as functions, so inheriting would flag methods for a name they genuinely cannot see. That is a false positive on ordinary code.
  • A local binding anywhere in the inner function makes the name local for the whole function, so exec(payload) followed later by payload = "x" raises UnboundLocalError and the outer taint is irrelevant.

Getting it right means implementing Python binding rules, global and nonlocal, parameter shadowing, and the class versus annotation versus comprehension scope distinctions, or moving to symtable. That is scope analysis, which is the general dataflow modelling this checker is deliberately not. It is also strictly weaker than the direct forms, since it needs a second function, so the "one line refactor away" argument that justified tracking one level of local indirection does not apply here.

The bounded, mechanism specific gaps in this round are all fixed. This one is a redesign, not an addition.

danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Aug 26, 2026
Keeps this copy identical to the ones on unslothai/unsloth#9777 and
unslothai/notebooks#365 apart from DEFAULT_TARGETS:

  - compile's source is not positional-only, so compile(source = f"...") executed
    with node.args empty. Scoped to compile; exec and eval raise TypeError for every
    keyword spelling on CPython 3.13.
  - a dangling symlink, a directory named *.py, or a symlink to one reached read_text
    and failed CI for a reason unrelated to dynamic execution. Also a NUL byte in the
    source (ValueError from ast.parse, not SyntaxError) and a RecursionError in the
    walk.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 749d825977

ℹ️ About Codex in GitHub

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".

Comment thread scripts/lint_dynamic_exec.py Outdated
"sink": sink,
"reason": reason,
"line": node.lineno,
"hash": _call_hash(node),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Include indirect source construction in the approval hash

When an indirect finding has been approved, such as payload = f"import safe.{trusted}"; exec(payload), changing only the assignment to interpolate attacker-controlled text leaves the hashed AST as exec(payload). The path, qualname, and hash therefore remain unchanged, so CI silently reuses the old justification. The fresh evidence after the path/qualname fix is that visit_Assign now recognizes interpolation outside the hashed call; include the taint-producing expression in the approval identity so changing that expression requires review.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping the current keying, same answer as before.

Hashing the producers as well as the sink call would mean the recorded justification stops surviving a reformat or a rename of an intermediate local, which is the property the hash keying exists to provide. The reviewed unit is the sink call and the reason it cannot take attacker controlled input, and that reason does not change when the string is assembled a line higher up.

The path and qualname refinement does not change the mechanism or the remedy, so it does not reopen it.

danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Aug 26, 2026
)

* Stop config-supplied values reaching exec, eval and getattr sinks

Follow-up to #1083, which stopped a config-supplied model_type reaching an exec'd
import by validating at the producer. This audits the rest of the exec/eval sites in
the package, closes the ones where an untrusted or user-level value can still reach
the executed string, and adds a lint so the shape cannot come back.

compiler.py re-checks model_type and the generated module name at the sink, so the
import path and the compiled-cache filename defend themselves rather than trusting the
caller, and resolves the UNSLOTH_FORCE_CUSTOM_DTYPE dtype field through _get_dtype
instead of eval.

empty_model.py gates config.architectures[0] on the names transformers registers in
its MODEL_*_MAPPING_NAMES tables before getattr and call.

peft_utils.py and tokenizer_utils.py drop three eval(f"...") lookups in favour of a
getattr walk, added next to the setter from #1083.

saving_utils.py turns an output-dtype assert into a ValueError, since asserts vanish
under python -O.

* Close the findings from the parallel review of this PR

Three runtime defects and the same four lint defects fixed on the unsloth side.

empty_model.py: a rejected architecture leaked global state

  create_empty_vision_model replaces SiglipVisionModel._init_weights with a no-op and
  restores it at the end of the function. The new guard raised in between, so a config
  with an unknown architecture left weight init disabled on a class shared by the whole
  process, and every SigLIP model built afterwards silently skipped initialisation.
  The guard now runs before the patch. Confirmed the leak was real by reproducing the
  old ordering, so the regression test is not vacuous.

empty_model.py: the getattr walk could not resolve bracket components

  peft_utils rewrites `.0.` to `[0].` before splitting. Its first call site skips paths
  containing brackets, but the second does not: when a module's forward calls
  `self.blocks[0](...)` directly, `final_where` includes the bracketed component and
  `getattr(obj, "blocks[0]")` fails where the removed eval indexed it happily. That is
  gradient checkpointing breaking on a real model shape. The walk now resolves digit
  subscripts, and only digits, so it is still a name-and-index walk rather than an
  expression.

vllm_utils.py: the architecture guard was asymmetric

  The vLLM vision path did the same getattr(transformers, config.architectures[0])
  followed by from_pretrained, gated only on model_type. model_type and architectures
  are independent fields of the same downloaded config.json, so that gate constrains
  neither. A config declaring a supported model_type and architectures ["AutoTokenizer"]
  resolved and invoked an unrelated class. Same check as create_empty_vision_model now.

  The comment in empty_model.py claimed this path already had the gate. It did not; the
  claim is removed rather than reworded.

scripts/lint_dynamic_exec.py

  Allowlist identity is path::qualname::hash rather than the hash alone, locals bound to
  a built string are tracked per scope, builtins.exec is a sink, and rebinding a tracked
  name clears it. The committed allowlist had 53 entries collapsing to 40 keys, so
  approvals were genuinely shared across unrelated locations.

  The stronger lint found four more interpolated sites, all the variable form and all
  self-generated from installed packages: the gguf reader partial class, the peft lora
  submodule scan, and the transformers quantizer patch. Recorded with reasons, 53 to 57.

tests/security plus tests/test_module_attribute_getter.py: 118 passed.

* Restore the SigLIP weight-init patch in a finally

create_empty_vision_model swaps SiglipVisionModel._init_weights for a no-op and puts
it back at the end. The restore sat after an `except Exception`, which does not catch
KeyboardInterrupt, so cancelling a cell partway through a load left weight init
disabled on a class shared by the whole process. Every SigLIP model built afterwards
then skipped initialisation, silently and nowhere near the cause.

Reproduced the old ordering under a simulated cancel to confirm it was real:

    PRE-FIX: _init_weights restored? False
    PRE-FIX: sentinel left behind?  True

The restore is now in a finally, and gated on `patched_here` so a nested or re-entrant
call that found the patch already installed cannot remove it from under the call that
owns it. The previous code would restore from the inner call.

This predates the PR, but the PR already moved the architecture guard above this block
for the same reason, so leaving the exception path leaking would be half a fix.

* Skip a non-canonical model_type instead of raising, and widen the walk

Three findings from independent verification passes over this PR.

compiler.py: the sink guard turned a skip into a hard failure

  38 of the model_type values transformers itself ships are hyphenated (`lfm2-vl`,
  `audio-spectrogram-transformer`, `data2vec-audio`, ...). The import below the guard
  raises ModuleNotFoundError for any name that is not a plain module name, and that
  happens BEFORE the compiled-cache filename is built, so such a value was always a
  silent skip and never reached the os.path.join. Raising made
  unsloth_compile_transformers(config.model_type) fail for real model types, and that
  function is exported. It returns now, which is the pre-change behaviour exactly, and
  the value still stops short of the filename. Verified the import fails first for
  `lfm2-vl`, `a/b` and `../../etc/passwd` alike.

empty_model.py: the indexed-component pattern was ASCII-only

  Python identifiers are not ASCII-only, and PyTorch registers a submodule under a
  Unicode name without complaint, so `self.层 = nn.ModuleList([...])` produced a path
  the walk could not resolve but the removed eval could. The name part is now anything
  without brackets; only the subscripts stay digit-constrained, which is what keeps
  this a name-and-index walk rather than an expression.

lint_dynamic_exec.py: the gate fell over on things that are not readable files

  A dangling symlink, a directory named `*.py`, or a symlink to one reaches scan_file
  through rglob and raised out of read_text, failing CI for a reason unrelated to
  dynamic execution. Now skipped, along with a NUL byte in the source (ValueError from
  ast.parse, not SyntaxError) and a RecursionError during the walk.

Tests cover all three. Allowlists unchanged: 37 unsloth, 57 zoo, 0 notebooks.

* State what the create_standalone_class justification actually covers

The entry justified `module` and said nothing about `model_location`, which is a
parameter. The function is not exported (absent from compiler.__all__) and all five
call sites are in the same file passing a path built from an already-validated
model_type, so the value is internal on every reachable path. The reason now says
that, and says that a caller outside this file would invalidate it.

* Carry the sink keyword resolution and unreadable-path skips

Keeps this copy identical to the ones on unslothai/unsloth#9777 and
unslothai/notebooks#365 apart from DEFAULT_TARGETS:

  - compile's source is not positional-only, so compile(source = f"...") executed
    with node.args empty. Scoped to compile; exec and eval raise TypeError for every
    keyword spelling on CPython 3.13.
  - a dangling symlink, a directory named *.py, or a symlink to one reached read_text
    and failed CI for a reason unrelated to dynamic execution. Also a NUL byte in the
    source (ValueError from ast.parse, not SyntaxError) and a RecursionError in the
    walk.

---------

Co-authored-by: danielhanchen <[email protected]>
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed 2b51504. Three real bypasses of the interpolation check taken, three declined.

Taken

All three were confirmed to actually execute on CPython 3.13 before being fixed, not just reasoned about.

  • format_map. Same replacement field machinery as format, fields taken from a mapping instead of keyword arguments. exec("import {module}".format_map(cfg)) imports the module and the checker said nothing. Added alongside format and join.
  • Annotated assignments. NodeVisitor.visit dispatches on the exact class name, and ast.AnnAssign is a sibling of ast.Assign rather than a subclass, so visit_Assign never saw an annotated binding and a type hint alone was enough to hide it. Added visit_AnnAssign sharing a _bind helper. AnnAssign.value is optional in the grammar, so a bare payload: str declares a name without binding anything and leaves existing taint alone rather than clearing it.
  • .encode(). The exec and eval docs say "string or code object", which is not accurate: builtin_exec_impl goes through _Py_SourceAsString, which has an explicit bytes branch. Fixed by unwrapping the receiver for .encode() and .decode(), since the conversion changes the type and not the syntax.

Also taken from the unsloth twin of this checker, since all three repos carry the same file: failing closed when the AST walk exhausts recursion, and scanning rather than crashing on an external directory passed to --paths.

Declined

  • Taint for names captured in nested scopes. The bypass is real, but the proposed remedy is wrong in both directions and I would rather leave a known limit than add an unsound rule. Class bodies are not links in the closure chain, so inheriting ancestor taint would flag methods for a name they genuinely cannot see. And a local binding anywhere in the inner function makes the name local for the whole function, so the outer taint is irrelevant. Getting it right means implementing Python binding rules, global and nonlocal, parameter shadowing, and the class versus annotation versus comprehension scope distinctions, or moving to symtable. That is the general dataflow analysis this checker is deliberately not.
  • Taint producers in the approval hash. Unchanged. Hashing the producers would mean a recorded justification stops surviving a reformat, which is the property the hash keying exists to provide.

Verification

Allowlist counts unchanged in all three repos (unsloth 37, unsloth-zoo 57, here 0), so the new detections match nothing already in tree and no existing call needed re-justification. Self test and full scan green in all three. All four bypasses now exit 1 and a clean file still exits 0.

Full test suite here, base 25937a6f versus this branch, failure sets diffed rather than counted: 143 failed on both, identical sets, zero regressions. The 143 are pre-existing tests/test_molab_generation_parity.py failures on main and are unrelated to this PR.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed. Six items this round, all taken, no rejections.

Four more shapes that reach the interpolated source

All confirmed to actually execute on CPython 3.13, not just reasoned about.

Shape Why it was missed
payload = f"import {name}" then exec(payload.encode()) the .encode() unwrap walked down to an ast.Name, but the taint lookup only fired when the argument itself was a Name, so nothing consulted the map
payload = f"import {name}" then payload = exec(payload) the target was bound before children were visited, clearing the taint before the sink inside the same statement was reached
exec(payload := f"import {name}") an ast.NamedExpr wrapping the f-string had no branch and fell through
exec(bytes(f"import {name}", "utf-8")) the constructor spelling of a conversion already covered as a method

The second one was under-reported and is worth calling out: the review flagged visit_AnnAssign, but visit_Assign had the identical ordering bug, and payload = exec(payload) is the more natural spelling of it. Both are fixed and both are in --self-test. Visiting children first is also the order the language specifies: an assignment evaluates the right hand side and only then assigns to the targets.

On bytes(...): the docs understate what exec accepts. It is documented as taking "a string or a code object", and only compile documents bytes, but empirically it accepts any buffer. bytes, bytearray, memoryview and str all work.

One taken with a narrowed remedy

exec("import MODULE".replace("MODULE", name)) is real. But the suggestion was to treat replace like format and join, and I measured that before doing it: it raises 10 findings across the repos, and every one is exec(inspect.getsource(f).replace(...)), the source-patching idiom this codebase is built on and which the module docstring already carves out. Ten allowlist entries for one PoC is the wrong trade, and it trains people to allowlist the shape instead of reading it.

Narrowed to a string-literal receiver, which keeps the named mechanism (the template is in the file, the substituted value becomes the syntax) and costs 0 new findings in all three repos while still catching the PoC.

Scope is unchanged

resolve is threaded from the sink and never while binding, so this stays at one level of indirection. a = f"import {n}"; b = a; exec(b) still reports nothing, as does b = a.encode(); exec(b). No chained propagation, no rebinding analysis, no scope modelling. The standing rejections all still stand.

Verification

Allowlist counts unchanged: unsloth 37, unsloth-zoo 57, notebooks 0. Zero new findings, zero stale entries, no allowlist regeneration. Self-test and full scan green on all three, on both Python 3.12 and 3.13. All six probe payloads now exit 1; the two negative controls still exit 0.

Suites: unsloth tests/security 499 passed, 6 skipped. unsloth-zoo tests/security 95 passed. notebooks full suite 143 failed / 17838 passed, the same pre-existing test_molab_generation_parity.py set as its merge base, sets diffed rather than counted.

One latent issue found while verifying, not fixed

_call_hash uses ast.unparse, whose f-string quoting is not stable across CPython patch releases (PEP 701 quote reuse, backported into the 3.12 series). On Ubuntu 24.04 stock python3.12 (3.12.3) the lint reports spurious stale entries on three f-strings containing nested quotes.

This does not affect CI: actions/setup-python with 3.12 resolves to 3.12.12, where all three repos are clean, and every lint step pins 3.12. I have left it alone deliberately, because changing _call_hash invalidates all 94 allowlist entries and key_of includes the hash, so a regeneration would reset every recorded justification to REVIEW ME. Flagging it as a known contributor-facing papercut rather than fixing it inside this PR. Note for anyone who hits it: do not run --update on 3.12.3, since that would rewrite those hashes and break the gate for everyone else.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed. Three items this round on the notebooks PR, all taken, plus the standing rejection on the zoo PR declined.

Taken

  • Standalone walrus binding. (payload := f"import {name}") then exec(payload) was missed, because unwrapping the walrus at the sink only helps when the named expression is handed straight to it. It is a pair of parentheses away from payload = f"...", which is already tracked, so visit_NamedExpr now binds it the same way.
  • Parse failures. A file that does not parse was returned as an empty finding list, i.e. reported clean. The point that settled it is about the surrounding job rather than the checker: both syntax-reporting steps in lint-ci.yml are continue-on-error: true, so compileall and ruff report an unparseable file and carry on, and nothing failed the build. Same bypass as swallowing a RecursionError, which I fixed earlier for exactly this reason and should have applied here at the same time. ast.parse failures now raise ScanError and count as unscannable. ValueError is included because that is what a NUL byte raises rather than SyntaxError.
  • Missing scan targets. A target that resolved to nothing was skipped in silence, so a rename or a typo left the gate exiting 0 over reduced coverage.

The third one found a live instance immediately

With unresolvable targets reported instead of skipped, the unsloth-zoo copy failed on its own configuration. DEFAULT_TARGETS there was ("unsloth_zoo", "unsloth", "studio", "scripts"), and neither unsloth nor studio exists in that repo. Both had been resolving to nothing on every run since the checker landed. Removed, and the finding count there is unchanged at 57, which confirms they were contributing nothing while the list claimed coverage it did not have.

That is a better argument for the check than anything I would have reasoned out in advance.

Declined on the zoo PR

Preserving taint across conditional annotated assignments. This is the standing rejection of taint across conditional rebinding, and I measured both spellings rather than answering by category: if cond: payload: str = "import os" and if cond: payload = "import os" are missed identically. So the limit is a property of the plain-assignment path that long predates visit_AnnAssign, not a hole the new handler opened. Fixing it for annotated assignments alone would be incoherent, and fixing it for both means control-flow merging, which is the dataflow modelling this checker deliberately is not.

Verification

Allowlist counts unchanged: unsloth 37, unsloth-zoo 57, notebooks 0. Self-test and full scan green on all three. All four new probes exit 1 (standalone walrus, syntax error, NUL byte, missing target) and a clean file still exits 0.

Suites: unsloth tests/security 499 passed / 6 skipped, unsloth-zoo 95 passed, notebooks 32 passed.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d773108254

ℹ️ About Codex in GitHub

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".

Comment thread scripts/lint_dynamic_exec.py Outdated
Comment on lines +192 to +197
def _enter(self, node):
self.scope.append(node.name)
# A fresh scope: a name built in one function says nothing about the same name
# in another.
self.tainted.append({})
self.generic_visit(node)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve enclosing taint while scanning function defaults

Python evaluates defaults and decorators in the enclosing scope, but _enter() pushes an empty taint map before generic_visit(). Consequently, payload = f"import {name}"; def f(result=exec(payload)): pass executes the interpolated payload at definition time while the gate reports no finding. Unlike a closure-body lookup, this occurs before entering the function scope; scan definition-time expressions with the enclosing taint and reset it only for the body.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one. Preserving enclosing taint while scanning function defaults means deciding what an inner scope can see from an outer one, which is the closure-scope item already declined earlier in this review, and it is unsound in both directions for the same reasons: class bodies are not links in the closure chain, and a local binding anywhere in the inner function makes the name local throughout.

Doing it properly needs Python binding rules or symtable. Every bounded item in this round is taken; this one is a redesign.

@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed. Four items, all taken, all on evaluation order or an alternate spelling. Each was verified against CPython 3.13 before being taken rather than read off the grammar.

Evaluation order

  • Chained assignment. The previous round fixed the order between the right hand side and the targets, but still walked every target as a group. Python binds them left to right, and a target that is not a plain name evaluates its own expressions at its turn. In payload = table[exec(payload)] = f"import {name}" the f-string reaches payload before the subscript runs, so the exec sees the value just assigned. Confirmed by running it. visit_Assign now visits the value, then visits and binds each target in order.

  • Annotated assignment. At module and class scope the store happens before the annotation is evaluated, so a runtime annotation observes the new binding. Confirmed by having the annotation read the name back:

    payload = "ORIGINAL"
    payload: peek() = "NEW"      # peek() sees payload == "NEW"
    

    visit_AnnAssign now visits the value, binds, then visits the annotation. This only bites where annotations are evaluated at all, so module and class scope rather than a function body, and from __future__ import annotations removes it entirely.

Alternate spellings of conversions already covered

  • Constructor keywords. Verified all three are keyword-callable and build exactly what the positional form does: bytes(source = ..., encoding = ...), bytearray(source = ...), str(object = ...). Only args[0] was being read.
  • Unbound conversions. str.encode(s) is the descriptor spelling of s.encode(), so the source is the first argument and the receiver is the type. Unwrapping the receiver looked at the name str and found nothing. Verified both directions: str.encode("import os") and bytes.decode(b"import os").

Verification

All four reproduce at head with 0 findings and exit 1 after the fix, in all three copies of the checker. Negative controls unchanged: a clean file and the chained-name case a = f"import {n}"; b = a; exec(b) both still exit 0, so this is still one level of indirection and not propagation.

Allowlist counts unchanged: unsloth 37, unsloth-zoo 57, notebooks 0. Self-test and full scan green on all three.

Suites: unsloth tests/security 499 passed / 6 skipped, unsloth-zoo 95 passed, notebooks 32 passed.

The self-test grew a module-level case for the annotation ordering, which meant widening its qualname assertion to accept <module> alongside the function names.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 26, 2026
Misses closed. map with more iterables than one still calls the sink, and a for
loop or a starred display consumes it as eagerly as list() does. A
string.Template bound to a local name substitutes as the inline spelling does.
A comparison of written-out constants is decidable, so if 1 == 2 no longer
traverses a suite that cannot run. A local class that subclasses str inherits the
real builder, so only a class that writes the method itself, or cannot have
inherited one, is exempt. A %%script python -i -c cell runs the command AND then
reads the cell body, so the body is no longer discarded.

False positives fixed. map is a tracked name, so a parameter of that name shadows
it; a keyword argument on map raises before the callback runs; the consumers that
may stop early - next, all, min, max - no longer report every element. A walrus
in a boolean operand binds before the next operand is read. Rebinding a name
clears the compound paths recorded against it. A template with no placeholder
ignores its arguments, read with string.Template.pattern so an escaped dollar
counts as one.

Corpus of 358 files: no change in findings. Allowlists unchanged at 0, 60 and 40.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5adafa7d80

ℹ️ About Codex in GitHub

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".

# `str = builtins.str` hands the constructor back to its own spelling, the
# same way `exec = builtins.exec` does for a sink, and `s = builtins.str`
# gives a FRESH name the constructor. Only the sinks were resolved here, so
# both read as shadows and `exec(s(f"..."))` stopped being

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add a call-site discriminator to allowlist keys

When one function contains two byte-identical sink calls, both findings have the same path, qualname, and hash, so load_allowlist() collapses them to one key and a single justification approves both. For example, name = "os"; exec(f"import {name}"); name = input(); exec(f"import {name}") allows the attacker-controlled second call to inherit the first call's review and pass the hard CI gate. Include a stable per-call-site discriminator in this identity.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declining, as in the earlier rounds where this was raised. The collision is real - five keys collide today, three in the zoo allowlist and two in unsloth - and the trade is deliberate: the key is a hash of the call's own source precisely so that EDITING a reviewed call forces a re-review, and adding a call-site discriminator (a line number, an ordinal) makes every entry churn when anything above it moves, which is how an allowlist stops being read. Two byte-identical calls in one function are also the case a reviewer sees together. The one you describe requires the author of the second call to be the attacker, and an attacker who is editing the file has better options than reusing a hash.

Comment thread scripts/lint_dynamic_exec.py Outdated
# `str = builtins.str` hands the constructor back to its own spelling, the
# same way `exec = builtins.exec` does for a sink, and `s = builtins.str`
# gives a FRESH name the constructor. Only the sinks were resolved here, so
# both read as shadows and `exec(s(f"..."))` stopped being

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stop treating sum and dict as exhaustive map consumers

Fresh evidence beyond the fixed next/all cases is that sum and dict also need partial-consumer handling when the callback is exec: because exec returns None, each consumer raises on the first mapped result and never requests later elements. Consequently, sum(map(exec, ["pass", f"import {name}"])) never evaluates the f-string, but the lint reports it and fails the hard CI gate; remove these consumers from the exhaustive set or model their early failure.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fbedba2. sum and dict are out of the exhaustive-consumer set: a sink returns None, so sum raises on 0 + None and dict raises unpacking None, both after the FIRST element and neither ever asking for the second. Both are fixtures now.

…ecognised magics

Ten review findings from the latest round.

Detections: a body that declares a name global or nonlocal no longer counts it as
a local, so the enclosing value is still read; a class name rebound elsewhere loses
its receiver exemption; a set expanded into compile offers every element, since a
set has no order; a computed comprehension target is evaluated on each pass; a
closure sees what its scope binds after the def; an immediately invoked lambda
binds its arguments to its parameters; and a notebook cell that will not parse now
loses only the lines that will not parse rather than the whole cell, so an
unrecognised automagic no longer hides the statements under it.

False positives: a .replace() between two literals, or with a zero count, splices
nothing; the first piece of a split whose separator sits in the receiver's leading
literal is fixed text, and the mirror holds for the last piece of rsplit and
rpartition; a compile call that binds one parameter twice raises before it runs.

Fifteen fixtures, including the cases that must stay reported: a piece after the
FIRST separator can still carry a value that moves that separator, and a zero
maxsplit hands back the whole receiver.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b24fdd91b8

ℹ️ About Codex in GitHub

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".

def _record_local_class(self, statement) -> None:
"""`class Safe:` makes `Safe()` a receiver whose methods are not string ones."""
if isinstance(statement, ast.ClassDef):
_LOCAL_CLASSES[statement.name] = statement

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep class metadata scoped to its definition

Fresh evidence beyond the fixed single-class subclass case is that this file-wide dictionary is overwritten by an unrelated nested class with the same name. For example, a module-level class Template(str): pass, followed by an uncalled function containing a non-string class Template, makes a later exec(Template('import {}').format(name)) report zero findings even though the module-level class inherits str.format and executes the interpolated source. Key this metadata by lexical binding/scope, or conservatively revoke the exemption when duplicate class names are recorded.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Two different classes recorded under one name revoke the exemption for that name, file-wide, alongside the rebinding rule from the previous round. Your example - a module-level class Template(str) and a class Template inside an uncalled function - reports .format().

Comment thread scripts/lint_dynamic_exec.py Outdated
Comment on lines +1129 to +1131
for index, argument in enumerate(node.args):
if isinstance(argument, ast.Starred):
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve visible expansions passed to invoked lambdas

Fresh evidence beyond the fixed direct-argument case is that a statically readable expansion is discarded here: exec((lambda source: source)(*[f'import {name}'])) necessarily executes the f-string, but the hard lint gate exits successfully with zero findings. The same miss occurs for **{'source': f'import {name}'} because the keyword-expansion branch returns the enclosing resolver; expand visible literal containers/mappings before binding lambda parameters.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. A written-out *[...] or *(...) at a lambda call site is expanded before the parameters are paired, and a ** of a literal mapping with constant string keys binds those parameters by name. Anything else still stops the pairing (a * moves every later argument; an unreadable ** can supply anything). Both of your spellings report.

Twenty review findings from the latest round.

Detections: string.Formatter().vformat is str.format with its arguments handed
over apart; the unbound str.__add__ and str.__mod__ descriptors take the receiver
as their first argument; a literal mapping's pop selects what its get would;
vars(builtins) is builtins.__dict__; a sink stored in a stable compound path
(obj.run, table['run']) is still the builtin at the call, and rebinding the root
takes that back; filter calls its callback with each element exactly as map does;
an unpacking target consumes the map that fills it; next(iter([...])) selects the
first element; two classes sharing one name earn no receiver exemption; a lambda
call site's written-out * and ** expansions pair with its parameters; and a
formatted value is no longer treated as stable across two evaluations, since
__format__ is under no obligation to answer the same way twice.

False positives: textwrap.indent has no default prefix; a search text visibly
absent from a literal receiver replaces nothing; a parsed tree is not source for
exec or eval, only for compile; a compile callback needs three iterables through
map; sum and dict raise on the FIRST mapped result, so they are no longer
exhaustive consumers; and the consumer spellings are tracked names, so a local
list that shadows the builtin is honoured.

Allowlists unchanged at 0 / 60 / 40, no drift across the 358-file corpus,
self-test green on 3.9 and 3.13, 288 lint tests.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fbedba2c3e

ℹ️ About Codex in GitHub

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".

Comment thread scripts/lint_dynamic_exec.py Outdated
Comment on lines +3272 to +3273
self._bind(target, reason, numeric, literal_text)
self._bind_unpacked(target, node.value)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Track interpolated elements in assigned literal containers

When a visible list, tuple, or dictionary is assigned to a name, this binds only the container itself as clean and discards the taint of its elements. Consequently, payloads = [f"import {name}"]; exec(payloads[0]) executes interpolated source while the new hard gate exits successfully; bind stable element paths for literal containers or resolve named containers during constant subscript lookup.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already fixed at this head - the review ran against the previous one. Binding a written-out list, tuple or mapping to a name records each constant-addressable element under the compound path the load spells, so both payloads = [f"import {name}"]; exec(payloads[0]) and the mapping form report. Fixtures for both.

Comment thread scripts/lint_dynamic_exec.py Outdated
Comment on lines +3178 to +3179
for statement in node.body:
self.visit(statement)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stop scanning function suites after unconditional exits

When a function has an unconditional return or raise, this loop continues visiting statements that can never execute. For example, def f(name): return; exec(f'import {name}') fails the new CI gate even though the sink is unreachable; walk the body with the same definite-jump suite handling already used for loop and selected branch bodies.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 672864c. A function body now ends at an unconditional return or raise, through the same suite walker loop bodies and if suites already use. def f(name): return; exec(f"import {name}") is quiet; a sink ABOVE the jump still reports, and that is a fixture too.

Comment on lines +215 to +217
_CONSUMER_NAMES = frozenset({
"list", "tuple", "set", "frozenset", "sorted", "min", "max", "any",
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Model early failure of min and max map consumers

The current consumer set explicitly includes min and max, which is fresh evidence after the earlier partial-consumer fix. With min(map(exec, ["pass", "pass", f"import {name}"])), the first two callbacks return None, their comparison raises TypeError, and the third interpolated element is never requested, but the scanner reports it and fails CI; treat these consumers as partial for map sinks or limit inference to elements reached before comparison.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already fixed at this head. Consumers are modelled by how many elements they provably evaluate: min and max pull two and compare, which raises on None, so exactly two are reported and your three-element example is quiet.

Twenty-one review findings from the latest round.

Detections: a partial consumer still runs the callback on the elements it does
reach, so `next(map(exec, [...]))` reports and `min`/`max`/`sum`/`dict`/`all` are
modelled by how many elements they provably evaluate rather than being dropped;
a sink handed back by an immediately invoked lambda; `memoryview(...).tobytes()`;
`iter([...])` as a loop iterable; a text subclass one level down; a
`string.Formatter()` bound to a name; `[...].pop()`; a sink passed as a `key`
callback to sorted, min or max; a folded constant name in `getattr`; and the
elements of a written-out container bound to a name, recorded under the same
compound paths attributes already use.

False positives: a generator expression discarded as a statement never evaluates
its element; `map` stops at the shortest visible iterable; a lambda given more
visible values than it takes raises first; a local class with its own `__add__`
is not concatenation; the same keyword from two visible expansions is a TypeError;
a normaliser called outside its documented arity raises; adding a visible number
to visible text raises; `.0s` truncates like `.0`; and `%%script python helper.py
-c ...` passes that string to the script, not to the interpreter.

The allowlist now also compares the recorded kind, so a finding whose source is
built above the sink call no longer inherits an old approval when the shape of
that construction changes.

Allowlists unchanged at 0 / 60 / 40, no drift across the 358-file corpus,
self-test green on 3.9 and 3.13, 310 lint tests.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a9676c78a2

ℹ️ About Codex in GitHub

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".

Comment on lines +5436 to +5439
# are deferred - that is `_collect_aliases` on their own body plus
# the outward walk, not this shadow.
#
# A later rebind

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Track assigned string-transform callables

When a known transformation method is assigned to a local, this restriction records only format/join/template builders, so the later bare call loses the receiver and its behavior. For example, replace = "import MODULE".replace; exec(replace("MODULE", name)) necessarily executes constructed source, but the new hard gate exits 0; the same bypass occurs with normalize = payload.strip or build = operator.add. Record and replay these known transformation callables through assignments as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b76f8b2. The bound-callable namespace covers every method that hands text on now - the builders, the normalisers, the conversions and replace - and a plain name receiver is recorded too, resolved at the CALL site against the taint map as it stands there rather than assumed at the binding. replace = "import MODULE".replace and normalize = payload.strip both report. build = operator.add is recorded as the stdlib helper it names, the same way from operator import add already was.

Comment on lines +1759 to +1760
spliced = list(node.args) + [k.value for k in node.keywords]
empty = no_arguments = not spliced

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject invalid builder arities before reporting

For builders other than the zero-argument format_map case, any supplied arguments are treated as a splice without checking whether the method can be invoked. Thus exec(','.join([f'import {name}'], [])) and exec('import {name}'.format_map({'name': name}, {})) fail this CI gate even though each builder raises TypeError before exec is called. Validate the visible argument count and keyword shape for join and format_map before returning a finding.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. join and format_map take exactly one positional argument and no keywords, so a second one raises before the sink and both of your examples are quiet. A ** this cannot read may still supply the one, so that shape is left alone.

The same reachability rule loop bodies and `if` suites already got: a `return` or
a `raise` at the top level of a body ends it, so `def f(name): return;
exec(f"import {name}")` no longer fails the gate on a sink nothing reaches. A sink
ABOVE the jump still reports, which is the fixture that keeps this honest.

No drift across the 358-file corpus; allowlists unchanged at 0 / 60 / 40;
313 lint tests.
Seven review findings, plus two structural ones.

Detections: a call to a visible local `def` is resolved through its own return
expressions, with the arguments paired to the parameters and a name the body binds
itself resolving to nothing; a class body's bindings are exported to the compound
path the attribute access spells, so `class C: payload = f"..."` followed by
`exec(C.payload)` reports; `enumerate` over a written-out container yields visible
index/value pairs; and a bound transform callable keeps its receiver, so
`replace = "import MODULE".replace`, `normalize = payload.strip` and
`build = operator.add` are read at the call.

False positives: `join` and `format_map` take exactly one argument, so a second
one raises before the sink.

Two structural changes. The allowlist now records how many identical calls share
a key and the scan compares that count, so adding a third copy of an approved
call is unreviewed rather than silently approved; entry counts are therefore
49 covering 60 findings in the zoo and 38 covering 40 in unsloth, with every
hand-written reason preserved. And `.github/workflows` is a scan target: a
`python - <<'PY'` block in a `run:` step executes on the CI runner with its token
in the environment, and was covered by nothing. 74 such blocks exist across the
three repos and all of them are clean, so no allowlist entry was needed.

No drift across the 358-file corpus, self-test green on 3.9 and 3.13, 323 tests.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b76f8b2855

ℹ️ About Codex in GitHub

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".

# A loop, `with`, `except` or `match` target is a local for the whole
# function exactly as an assignment is, so a nested `def` written above
# one cannot fall through to an outer alias of that name. Recording
# only assignments r

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bind allowlist entries to the source-building expression

Hashing only the sink call lets a reviewed justification survive a security-relevant edit immediately above it. For example, after allowlisting payload = f'import {safe_name}'; exec(payload) as trusted, changing the assignment to payload = f'import {input()}' preserves the path, qualname, exec(payload) hash, and reason f-string via payload, so this hard gate still exits 0 without re-review. Include the taint-producing expression or its content hash in the allowlist identity.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taken in full this time. An entry now records an origin: a digest of the expression that put the built source into the name the finding reads. Your example - payload = f'import {safe_name}' becoming payload = f'import {input()}' - keeps the path, the qualname, the call hash and the reason, and changes the origin, so the entry no longer matches and the call is unreviewed until someone signs it off.

Two calls sharing a key record both origins, so neither can be swapped for the other's. Entries written before the field existed carry none and still match on the rest, and both allowlists were regenerated with every hand-written reason preserved: zoo 49 entries over 60 findings, unsloth 38 over 40. The corpus is unchanged apart from 45 findings gaining the field.

The key itself still hashes only the call, for the reason given before: a line number or an ordinal churns every entry whenever anything above it moves.

Comment thread scripts/lint_dynamic_exec.py Outdated
Comment on lines +7435 to +7436
# one cannot fall through to an outer alias of that name. Recording
# only assignments r

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require the heredoc command to invoke Python

When python appears only in a destination filename, this substring test misclassifies data as executed Python. A workflow step such as cat > /tmp/python.py <<'PY' followed by exec(f"import {name}") is rejected even if the file is never run; cat --help confirms that with no FILE operand it reads standard input, which the redirection merely writes to disk. Parse the command receiving the heredoc instead of searching the entire introducer line for python.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. The command before the heredoc is tokenised, redirections and their operands are dropped, and the remaining words are matched against the same interpreter pattern _runs_python uses. cat > /tmp/python.py <<'PY' is data again, and that is a fixture.

Seven review findings.

Detections: `and` hands back its LAST operand when the earlier ones are truthy,
which every builtin function is, so `(compile and exec)(f"...")` is read as the
`exec` it calls rather than the `compile` whose arity test then suppressed it; an
augmented write below a `def` is part of what the closure reads; a class base this
file cannot resolve counts as textual, so a qualified base no longer earns the
string-builder exemption; and an attached `-Wignore::DeprecationWarning` is no
longer mistaken for a bundled `-c`, which had been extracting `ationWarning` as
the program and losing the real one.

False positives: every string normaliser except `expandtabs` takes no keyword at
all, and `str.replace`'s parameters are positional-only, both verified against
CPython; and a visibly invalid `compile` mode in a mapped call raises there, so
the sources after it are never reached.

No drift across the 358-file corpus, self-test green on 3.9 and 3.13, 330 tests.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f831e7708d

ℹ️ About Codex in GitHub

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".

Comment on lines +2456 to +2459
if isinstance(function, ast.Call):
# The third and last `ast.Call` arm, tried after the `partial` and mapping
# `.get` arms above and reached only when neither of them resolved.
return _getattr_sink_name(function, aliases, shadowed)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve sinks returned by visible helper functions

When a visible local helper returns a sink, this final ast.Call branch only attempts getattr resolution. For example, def choose(): return builtins.exec followed by choose()(f'import {name}') necessarily executes the interpolated source, but the lint exits successfully with zero findings. Resolve the helper's visible return expressions on the callee side, analogous to the existing source-side helper handling.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one already resolves on the head under review: _sink_name's first ast.Call arm reads a visible helper's returned expressions, and your example reports one finding (sink builtins.exec) as written. The gap it left was parameters, which is your later item, and that is now fixed too.

Comment thread scripts/lint_dynamic_exec.py Outdated
Comment on lines +3705 to +3709
element_reason = _is_interpolated(
item, self.tainted[-1].get, self._is_shadowed, self._alias,
)
if element_reason is None or isinstance(element_reason, _LiteralText):
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve sink aliases stored in literal containers

This container-binding pass records only interpolated source reasons, so callable elements that are sinks are discarded. For example, runners = [builtins.exec]; runners[0](f'import {name}') and the equivalent constant-key dictionary dispatch both execute the interpolated source while the hard gate reports zero findings. Record _sink_name(item, ...) under the same compound element path used for taint.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one already resolves on the head under review as well: both runners = [builtins.exec]; runners[0](f"...") and the constant-key dictionary spelling report a finding each, through the compound element path the container binding records. Measured on exactly your two shapes.

Comment on lines +1568 to +1570
literal_mapping = (
_mapping_literal(function.value, shadowed)
if function.attr in ("get", "pop") else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve named mappings before get and pop

The existing named-container fix only preserves exact subscript loads; this accessor branch still accepts only an inline mapping. Consequently, payloads = {'x': f'import {name}'}; exec(payloads.get('x')) (or .pop('x')) executes the stored interpolated string while the lint exits successfully. Consult the recorded compound element path, or retain the literal mapping binding, when the receiver is a resolved name.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. When the receiver resolves to a compound path, X.get(k) and X.pop(k) with a constant key are rewritten as X[k] and read there, so there is one implementation of the lookup rather than a second copy for the accessor spelling. A key with nothing recorded under it is a miss, which returns the default, so a second argument is read for it. Fixtures: 'get reads the same element the subscript reads' and 'pop reads it too'.

Comment on lines +3097 to +3099
if sink.rpartition(".")[2] == "compile" and not _compile_call_is_complete(
node, shadowed, skip,
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject sink calls with excess visible arguments

Runtime feasibility is checked only through the compile-specific completeness helper, which validates missing or duplicate arguments but not excessive positional arguments, and exec/eval receive no arity check. Thus exec(f'import {name}', {}, {}, 1) or a seven-argument compile(...) is reported even though Python raises TypeError before evaluating the source as code, causing a false CI failure for calls that cannot reach the sink.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. _visibly_too_many_arguments gives exec and eval three positional parameters and compile six, and _source_argument declines a call that visibly exceeds them, alongside the missing-argument case that was already there. Only when every argument is visible: an opaque *expansion says nothing about how many values it contributes and stays on the reporting side. Fixtures: 'exec given more arguments than it takes raises first' and 'compile given a seventh argument raises first'.

Fourteen review findings.

The allowlist gains an `origin`: a digest of the expression that put the built
source into the name a finding reads. The key still hashes the sink call, so
editing the call forces a re-review as before, and this closes the other half -
`payload = f"import {safe}"` becoming `payload = f"import {input()}"` leaves
`exec(payload)` byte for byte identical, and the reviewed entry used to cover it.
Two calls sharing a key record both origins. Entries written before the field
existed carry none and still match on the rest.

Detections: nested containers are addressable, so `payloads = {"run": [f"..."]}`
reaches the f-string at `payloads["run"][0]`; a sink stored in a written-out
container is still the builtin at the call; a helper that RETURNS a sink resolves
on the callee side; `builtins.map` and `builtins.filter` are the same builtins;
`list.sort(key = ...)` takes the same callback `sorted` does; a bound `__add__` or
`__mod__` keeps its left operand; and a constant slice that cuts only the literal
head or tail of an f-string still carries the interpolation.

Workflow scanning, tightened three ways: the command before a heredoc has to be an
interpreter rather than merely contain the word (a `cat > /tmp/python.py <<'PY'`
block is data); a one-line `run: python -c '...'` is scanned as well as a heredoc;
and an Actions expression inside a heredoc becomes a name rather than making the
block unparseable, since the runner substitutes it into valid Python.

False positives: a conversion or a normaliser called outside its documented shape
raises before the sink; a partition index outside its three elements raises; a
decorator that is not documented to hand the result back means the body below it
says nothing about what the name is bound to.

Corpus: identical findings, with the new `origin` field added to 45 of them.
Allowlists: zoo 49 entries covering 60 findings, unsloth 38 covering 40, every
hand-written reason preserved. Self-test green on 3.9 and 3.13, 347 tests.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6ce8f3bc3d

ℹ️ About Codex in GitHub

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".

Comment thread scripts/lint_dynamic_exec.py Outdated
_HELPER_STACK.add(helper.name)
try:
for value in _returned_expressions(helper):
resolved = _sink_name(value, aliases, shadowed)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bind helper arguments before resolving returned sinks

Fresh evidence beyond the fixed zero-argument helper case is that helper parameters are resolved without their call-site bindings: def choose(run): return run followed by choose(builtins.exec)(f'import {name}') necessarily invokes exec, but the lint exits successfully because run is unresolved here. Bind the visible call's positional, keyword, and default arguments before resolving its return expressions, as is already done for invoked lambdas.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. The pairing _lambda_result was doing is now _paired_arguments, shared with the callee-side helper arm, so a returned parameter resolves to the argument the call supplied. * or ** at the call site still gives up rather than guessing. Fixture: 'a helper hands back the sink it was given'.

# and reporting it failed the gate on code that does nothing.
self._visit_suite(node.body)
self.collected_aliases.pop()
self.sink_aliases.pop()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Export class-local sink aliases with class attributes

When a class body assigns a sink to an attribute, this pop discards the alias while the export below preserves only tainted source values. For example, class Runner: run = exec followed by Runner.run(f'import {name}') executes the interpolated source—exec remains directly callable when stored on a class—but the lint reports zero findings. Export class-local sink aliases under compound paths such as path>Runner.run before removing the class scope.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. A class scope now exports its sink aliases under path>Class.attribute, the same spelling the taint export already used, and into the deferred alias map as well as the executed one: a class body runs where it is written, so a function body written either side of it sees the attribute, and _alias reads the deferred map for every scope but the innermost. Fixture: 'a sink stored on a class is still the builtin'.

…nnot run

Detections, each with a fixture that fails without it:

- `getattr(builtins, f"{'exec'}")` folds like the concatenation already did.
- `next(iterator, default)` selects the written-out first element; the default
  is unreachable past it.
- `next(iter([exec]))(...)` resolves on the callee side too.
- A helper local carries its value to the `return`: `source = f"..."` then
  `return source`.
- `payloads.get("x")` and `.pop("x")` read the element the subscript reads.
- A helper hands back the argument it was given: `choose(builtins.exec)(...)`.
- A class body's sink aliases are exported with its attributes, so
  `class Runner: run = exec` leaves `Runner.run(...)` resolvable.
- An undecidable choice of callee keeps both arms, so
  `(compile if flag else exec)(f"...")` is no longer suppressed by `compile`'s
  arity.
- Committed `.sh` files are scanned for Python heredocs and `python -c`, as
  workflow `run:` blocks already are.

False positives removed:

- `(f"...",).pop()` - a tuple has no `pop`.
- More positional arguments than the sink takes raises TypeError first.

The 358-file corpus is unchanged finding for finding; only the two new module
constants differ. Live scans stay at 0 / 60 / 40, self-test passes on 3.9 and
3.13, and the suite is 363 cases in all three copies.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7513396762

ℹ️ About Codex in GitHub

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".

Comment thread scripts/lint_dynamic_exec.py Outdated
Comment on lines +2637 to +2640
for value in _returned_expressions(helper):
if isinstance(value, ast.Name) and value.id in bound:
value = bound[value.id]
resolved = _sink_name(value, aliases, shadowed)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Propagate helper bindings through composite returns

Fresh evidence beyond the fixed direct-name helper case is that parameter substitution only occurs when the entire returned node is an ast.Name. For def choose(run, flag): return run if flag else print, the call choose(builtins.exec, True)(f'import {name}') necessarily invokes exec, but the returned IfExp is resolved against the caller without replacing its nested run, so the hard gate reports zero findings. Resolve returned expressions with the complete helper argument scope rather than substituting only a top-level name.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed, and through the aliases rather than by substituting a node. Each parameter that resolves to a sink is answered for wherever it is written inside the returned expression, so a returned conditional resolves as a returned bare name already did, and so does anything else this resolver knows. Fixture: 'a helper hands back a choice between the sink and something else'.

Comment on lines +2614 to +2618
if isinstance(function, (ast.Attribute, ast.Subscript)) and aliases is not None:
# `obj.run = builtins.exec` then `obj.run(f"...")`, and the subscript spelling
# `table["run"]`. The path is written out and names the same place at the store
# and at the load, which is the same key `_bind` records taint against.
path = _compound_key(function)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve class sink aliases through instances

Fresh evidence beyond exporting Runner.run is that accessing the same class attribute through an instance remains unresolved: class Runner: run = builtins.exec followed by Runner().run(f'import {name}') executes the interpolated source because the builtin does not bind as an instance method, yet _compound_key rejects paths containing a call and the scanner exits successfully. Recognize visible local-class construction here and resolve its attribute against the exported class path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. A written-out construction of a local class is recognised on the callee side and its attribute is resolved against the exported class path, so Runner().run(f"...") reads the same record Runner.run(...) does. _compound_key still refuses a path with a call in it, which is right for taint - a call can return anything - but the class here is written out in the file.

Comment on lines +3415 to +3418
if _visibly_too_many_arguments(node, sink, skip):
# More positional arguments than the sink has parameters is a TypeError raised
# before any source is executed, exactly like the missing-argument case below.
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject visibly invalid sink keywords before reporting

The feasibility check added for excess positional arguments does not validate keyword names. In the Python 3.12 lint workflow, exec(f'import {name}', spam=1), eval(f'1+{name}', spam=1), and compile(f'import {name}', '<x>', 'exec', spam=1) all raise TypeError before executing or compiling their source, but this scanner reports each and fails the hard CI gate. When no opaque ** expansion is present, reject calls containing keywords unsupported by the selected sink.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Keyword names are checked against a per-sink set, taken as the UNION across supported Pythons: exec and eval accept no keywords at all before 3.11 and accept globals/locals/closure after, so only a name outside the union is refused by every version. A ** expansion says nothing about which names it supplies and leaves the call on the reporting side. Three fixtures, one per sink.

…rtial slices

Workflow and shell reading:

- `python -c "` with the program on the lines below is now joined until the
  quoting balances, and the block indentation is removed before it is parsed.
- `cat <<'PY' | python` is scanned: the interpreter may sit past a pipe, and
  cutting the line at `<<` threw the rest of the pipeline away.
- Each heredoc and each `-c` command gets its own visitor. They are separate
  processes, so a name bound in one no longer answers for the next.
- `${{ ... }}` is read as interpolated source rather than as a fixed name. The
  runner splices it in before Python parses anything.
- `.github/actions` joins `.github/workflows` in the default targets where the
  repository ships composite actions.

Resolution:

- A partial slice keeps its taint unless it provably cuts every interpolated
  value away, so `f"{input()}"[:1000]` reports. A slice whose whole extent lies
  inside a leading or trailing literal run still reads as clean.
- A call into a visible wrapper reports what the CALLER built:
  `def run(source): exec(source)` with `run(f"...")`.
- The deferred-taint prepass resolves transitively, so an alias bound after a
  nested def carries the built string into it.
- The helper registry is keyed by lexical scope, so a `build` in one function no
  longer counts as a rebind of an unrelated `build` in another.
- A helper's returned expression is resolved with its whole argument scope, so a
  returned conditional resolves as a returned name already did.
- `Runner().run(...)` resolves against the exported class attribute.
- `payloads.pop()` with nothing named reads the last element of a bound list.
- An allowlist entry inherits the provenance of the expression that BUILT the
  value, so changing an f-string two names upstream revokes it.
- A keyword the sink does not have is a TypeError, so it is no longer reported.

Corpus: two origin digests change, both deliberately; every finding is otherwise
identical. Live scans 0 / 61 / 40, self-test passes on 3.9 and 3.13, suite 378.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 791277d623

ℹ️ About Codex in GitHub

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".

Comment on lines +2730 to +2733
for parameter, argument in bound.items():
given = _sink_name(argument, aliases, shadowed)
if given is not None:
supplied[parameter] = given

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Propagate module-valued arguments into helper returns

Fresh evidence beyond the direct sink-parameter fix is that this scope records only arguments that _sink_name already recognizes as sinks, so other values needed to resolve a composite return are discarded. For example, import builtins; def choose(module): return module.exec; choose(builtins)(f'import {name}') necessarily calls the builtin, but the current scanner reports zero findings because builtins is never bound to module; preserve module/mapping/constructor bindings when resolving the helper's returned expression.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. A helper parameter now answers in every namespace its argument answers in - module, constructor, partial, functools, text, stdlib, stdlibfunc, builder, template, formatter - plus the bare builtins spelling, so def choose(module): return module.exec resolves. The prefixes are the ones this file already records under; nothing new is invented for it.

Comment thread scripts/lint_dynamic_exec.py Outdated
Comment on lines +6979 to +6980
# what the target gets: `nullcontext` is documented as returning its
# argumen

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Respect unreachable code while inspecting sink wrappers

This wrapper-specific walk visits every call in each helper statement without the definite-jump and branch handling used by normal function visitation. Consequently, def run(source): return; exec(source) followed by run(f'import {name}') is reported even though the sink cannot execute; the same false failure occurs for a sink guarded by a constant-false condition. Walk only reachable helper statements before inferring that the supplied argument reaches a sink.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Both the wrapper walk and the return collector now go through _reachable_statements, which stops at a statement that always leaves the suite and takes only the branch a decided if runs. A test this cannot decide leaves both suites standing, which is the reporting side. Fixture: 'a wrapper that returns first never reaches its sink'.

…t run

Detections:

- A comprehension over a visibly nonempty iterable with no filters produces its
  element, so `[f"..." for _ in [0]][0]` resolves on both sides.
- `setdefault` on a written-out mapping hands back the default it stores.
- `payloads.update(run = f"...")` writes the element `payloads["run"]` holds.
- `partial(*(exec, f"..."))()` expands a written-out starred operand before the
  callee and the bound source are read.
- `await` is unwrapped, so an awaited helper's built source reaches the sink.
- `copy.copy` and `copy.deepcopy` of a string hand the same string back.
- `[exec].pop()(...)` resolves the callee the source side already read.
- A shell command continued with a trailing backslash is joined before the `-c`
  program is extracted.
- `eval` returns the value of its expression, so its truthiness is unknown and
  neither `all` nor `any` can be assumed to stop at the first element.
- `contextlib.nullcontext` has implemented the async protocol since 3.10, so
  `async with` over one enters and its body is scanned.

False positives removed:

- `cached_property` hands back a descriptor, not a callable, so a call to a
  function decorated with it raises before any sink.
- A `return` below an unconditional `return` in a helper never runs.

Corpus unchanged finding for finding; only the new module constants differ.
Live scans 0 / 61 / 40, self-test passes on 3.9 and 3.13, suite 390.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a9a504b697

ℹ️ About Codex in GitHub

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".

Comment on lines +275 to +278
if consumer in ("sum", "dict"):
return 1
if consumer in ("min", "max"):
return 2

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Do not truncate consumers whose callback is eval

Fresh evidence beyond the prior exec-only min/max example is that eval can return values which remain comparable or addable: min(map(eval, ['1', '2', f'{name}'])) evaluates the third element successfully, but these unconditional caps make the scanner exit with zero findings. Apply early-failure limits only when the selected sink's return type guarantees that failure; the equivalent min/max key-callback cap needs the same distinction.

Useful? React with 👍 / 👎.

Comment on lines +7172 to +7174
# shadow and reported the call as nothing. Same for `nonlocal`.
self.tainted[level].pop(target.id, None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Propagate transformed wrapper parameters to sinks

When a visible wrapper applies a source-preserving operation before invoking the sink, requiring the inner argument itself to be an ast.Name drops the call-site taint. For example, def run(source): exec(source.strip()) followed by run(f'import {name}') executes the interpolated source, yet the scanner reports zero findings; resolve the inner source expression against the helper's bound parameter scope instead of accepting only a bare parameter.

Useful? React with 👍 / 👎.

Comment on lines +7157 to +7159
# shadow and reported the call as nothing. Same for `nonlocal`.
self.tainted[level].pop(target.id, None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve visible instance methods used as sink wrappers

When the wrapper is a visible local-class method, _visible_helper cannot resolve the attribute callee, so class Runner: def run(self, source): exec(source) followed by Runner().run(f'import {name}') executes interpolated source while the scanner exits successfully with zero findings. Resolve visible method definitions here and pair their arguments after accounting for the bound instance parameter.

Useful? React with 👍 / 👎.

…o every source

Runner programs:

- A `NAME=value` prefix no longer hides the interpreter behind it.
- `run: >` folds onto one line before the readers see it, so an interpreter and
  its `-c` written on separate lines are one command.
- PowerShell launchers are scanned: the shipped installers bind the program to a
  variable and hand that variable to `-c`, which the word-splitting reader could
  never see. `.ps1` joins `.sh` in the default sweep.
- A `%%bash` or `%%script bash` notebook cell is read for embedded programs
  rather than dropped whole.
- Each extracted program gets the deferred-taint prepass a module and a notebook
  already get, so a closure inside a heredoc reads its cell.

Resolution:

- `min`/`max` over a written-out singleton hands back that element.
- `ast.unparse(ast.parse(f"..."))` is a round trip and keeps its interpolation.
- A helper parameter answers in every namespace its argument does, so
  `def choose(module): return module.exec` resolves.

False positives removed:

- `[].format(...)` and `[].join(...)` raise AttributeError; a written-out
  receiver of the wrong type is no longer read as a string builder.
- A wrapper is walked only where it can run, so a sink under an unconditional
  `return` or a constant-false test is not reported.

Allowlist:

- A finding records the digest of EVERY binding its source was built from, so
  changing one of two contributing f-strings revokes the justification.
- `--update` reseeds `REVIEW ME` when the origin, kind or count moved, instead of
  copying the old justification onto a changed identity.

Corpus unchanged finding for finding. Live scans 0 / 61 / 40 with four allowlist
origins updated and their justifications unchanged, self-test passes on 3.9 and
3.13, suite 401.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2376a4f651

ℹ️ About Codex in GitHub

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".

Comment on lines +7267 to +7269
decided = _constant_truth(node.test)
if decided is None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Follow visible wrapper chains to their sinks

When one visible wrapper delegates to another, this only asks whether the immediate child callee is itself a sink. For example, def inner(source): exec(source); def outer(source): inner(source); outer(f'import {name}') necessarily executes the interpolated string, but inner resolves to no sink here and the scanner exits successfully. Recursively inspect visible helper callees while preserving the paired source argument.

Useful? React with 👍 / 👎.

Comment on lines +7267 to +7269
decided = _constant_truth(node.test)
if decided is None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve wrapper sink parameters from call bindings

When a wrapper receives the sink through a parameter, _sink_name resolves that parameter against the caller rather than the helper's paired arguments. Thus def run(source, sink): sink(source); run(f'import {name}', exec) executes interpolated source but produces zero findings; the omitted-default form sink=exec is also missed because pairing explicitly excludes defaults. Resolve helper-body callees through the bound argument/default scope before deciding they are not sinks.

Useful? React with 👍 / 👎.

Comment on lines +1267 to +1270
if (scope, function.id) in _REBOUND_FUNCTION_NAMES:
return None
found = _LOCAL_FUNCTIONS.get((scope, function.id))
if found is not None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Track stable aliases of visible wrappers

When a locally defined wrapper is assigned to another name, helper lookup only searches definitions under the callee's current spelling. Consequently, def run(source): exec(source); alias = run; alias(f'import {name}') invokes exec with interpolated source while the hard gate reports no findings. Preserve unambiguous helper aliases through assignments so _visible_helper can resolve the alias back to run.

Useful? React with 👍 / 👎.

The checker asked for the same scope walk seven to eight times per node - the
alias pass, the locals pass, the class pass and the taint fixpoint each rewalk
it - which put 40 million calls and three fifths of the runtime in one
function. Three changes, none of which alters a finding:

Memoise the scope walk on the node. The answer depends only on the subtree,
and nothing here rewrites a tree it is walking: the rewrites build new nodes
through ast.copy_location rather than assigning fields. Stored on the node
rather than in a dict keyed by id(), so a memo cannot outlive its tree.

Memoise the declared-locals set the same way, and collect the global and
nonlocal names in the pass that already walks for the locals instead of
walking a second time. The memo holds a frozenset copy, so a caller is free
to mutate what it gets back.

Gather the assignments in the later-taint fixpoint once instead of
rediscovering them on each of the eight rounds, and skip a value whose names
are all already answered.

Read children off _fields in the walk rather than through
ast.iter_child_nodes, which stacks two generators per node visited.

Measured, min of five runs per copy, whole-repo scan:
  notebooks  12.65s -> 7.70s   (39% faster)
  zoo        15.40s -> 6.45s   (58% faster)
  unsloth    41.39s -> 20.47s  (51% faster)

Verified inert: the 358-file findings oracle reports every finding identical
in all three copies, element for element, with only the two new module
constants differing. Live scans unchanged at 0 / 61 / 40 all reviewed, exit 0.
Self-test passes on 3.9 and 3.13. Four tests pin the memo - that it answers
what an uncached walk answers, that it does not carry between two trees, that
a caller mutating the result cannot poison it, and that it stays invisible to
ast.unparse, which the finding keys are digests of. Each fails under a
sabotaged memo.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-08-30T05:05:36.400178Z f8ec79e New commits
ℹ️ About Codex in GitHub

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f8ec79e95e

ℹ️ About Codex in GitHub

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".

if _MATCHAS is None or not isinstance(inner, _MATCHAS):
return {}
if inner.pattern is not None or inner.name is None:
# A nested pattern or a bare `_` binds nothing readab

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Inspect immediately invoked lambdas as sink wrappers

When the invoked wrapper is an inline lambda, _visible_helper returns nothing because the callee is not a named def. For example, (lambda source: exec(source))(f"import {name}") necessarily executes the interpolated string, but the new hard lint gate reports zero findings. Pair the lambda parameters with the call arguments and inspect its reachable body just as for a visible function wrapper.

Useful? React with 👍 / 👎.

Comment on lines +5444 to +5445
if inner.pattern is not None or inner.name is None:
# A nested pattern or a bare `_` binds nothing readab

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve named containers during unpacking

When the right-hand side of an unpacking is a name bound to a visible literal container, this restriction discards the element bindings already recorded for that container. Thus payloads = [f"import {name}"]; [source] = payloads; exec(source) executes interpolated source while the hard gate exits successfully with zero findings. Resolve constant element paths from named containers before giving up on the unpacking.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

Closing this. The security fixes this checker was written alongside have already
landed (unsloth-zoo#1108, unsloth-zoo#1111, unsloth#9777), so the actual holes are
closed; what is left here is the CI gate meant to stop them coming back, and it is
more machine than that job justifies.

The checker grew to roughly ten thousand lines over about seventy review rounds, and
almost all of that is precision rather than detection. Measured against the same
trees, a sixty-line rule of "the argument to exec, eval or compile must be a
written-out literal" reports 146 call sites where this reports 40 to 61, and it would
have caught both of the real bugs. The extra lines buy a smaller allowlist, not a
finding the short rule misses. Most of them close bypasses that only matter against
someone who can already commit to the repository, and who could simply delete the
workflow step instead.

Recording one thing that is worth keeping, since it surprised me. Both repositories
run CodeQL default setup with Python enabled, and it works: unsloth has raised
py/stack-trace-exposure, py/incomplete-url-substring-sanitization and five
py/path-injection alerts. But there has never been a single py/code-injection alert on
either repository, in any state, while both exec of an HTTPS response body and
exec of an interpolated model_type sat in the tree. So if this class is ever worth
gating again, CodeQL is not the thing that will catch it.

The branch stays if anyone wants to pick the short rule out of it.

danielhanchen added a commit that referenced this pull request Aug 30, 2026
… out (#369)

* Fail CI on a new exec, eval or compile of a value that is not written out

A small replacement for the checker in the closed #365. That one grew to about
ten thousand lines over seventy review rounds, and measured against the same
tree the extra machinery bought a smaller baseline rather than a finding this
misses.

The rule: the first argument to the exec, eval or compile BUILTIN must be a
written-out string. A name, a call, or an f-string with a placeholder is
reported. Matching the bare name and not an attribute matters - counting
re.compile and model.eval as sinks reported 69 false positives across the two
library repositories.

Notebooks are read as well, since they are the maintained source here. Magic
and shell lines are blanked rather than dropped so reported line numbers still
point at the cell.

Four existing call sites are recorded with a justification each: three notebooks
run the Studio chat module they have just downloaded, and the GRPO notebook runs
a model-generated program through the sandbox added in unsloth-zoo#1105. An
entry keeps the call's own text rather than its line number, so moving code does
not churn it, and a count, so a new call cannot hide behind a removed one. The
gate refuses to pass while any entry lacks a reason, and --update carries
existing reasons across rather than resetting them.

Worth recording: CodeQL default setup runs here with Python enabled and raises
other injection findings on these repositories, py/path-injection among them,
but has never once raised py/code-injection - including while exec of an HTTPS
response body sat in unsloth. This class is not covered by what already runs.

* Name the encoding when reading the workflow file

---------

Co-authored-by: danielhanchen <[email protected]>
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.

1 participant