Repository navigation
Fail CI on exec, eval or compile of an interpolated string - #9827
danielhanchen wants to merge 46 commits into
Conversation
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. scripts/lint_dynamic_exec.py walks the AST of every package file 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(inspect.getsource(...)) is the normal case here and is not flagged. The 40 reviewed sites live in scripts/dynamic_exec_allowlist.json, each with a written reason, keyed on the path, the enclosing qualname and a hash of ast.unparse of the call. Reformatting a site keeps its justification; changing what gets interpolated invalidates it. Stdlib only, so it runs in the existing source-lint job with no new dependency, and it has a --self-test.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 70badcee53
ℹ️ 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".
| for statement in node.body: | ||
| self.visit(statement) | ||
| for statement in node.orelse: | ||
| self.visit(statement) |
There was a problem hiding this comment.
Preserve taint from both conditional branches
When a nonconstant condition assigns interpolated source in the if branch and a literal in the else branch, both suites are visited sequentially against the same taint map, so the literal assignment clears the earlier taint. For example, if flag: payload = f"import {name}"; else: payload = "pass"; exec(payload) exits this lint successfully even though flag=True executes the interpolated source. Analyze each branch from the pre-if state and merge their possible bindings instead of letting the last visited branch win.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining, standing limit. The checker is a best-effort heuristic for one shape, an untrusted value spliced into executed source, and it is explicitly not a sound taint analysis. Merging state from branches it cannot decide means modelling both worlds across every stack it keeps - taint, aliases, shadows, deferred shadows, star restores, globals, nonlocals - which is a dataflow engine rather than a lint.
Decidable folding IS taken, and three items in this round were: a short-circuited walrus, a statically empty repetition, and the final body of a literal loop. The line is at what a written-out constant decides.
| 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']}" |
There was a problem hiding this comment.
Give each allowlisted call site a distinct identity
When an already allowlisted call is copied elsewhere in the same function, this key is unchanged because path, qualname, and normalized call hash are all identical; load_allowlist() then treats both sites as the same reviewed entry. This already collapses distinct calls at lines 3330 and 3373 of unsloth/models/_utils.py, and it means a new copy placed after rebinding an interpolated variable to attacker-controlled data inherits the old justification without review. Include a stable per-call-site discriminator and validate matching multiplicity.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining, standing limit, and the trade is deliberate. The allowlist key is (path, enclosing qualname, hash of ast.unparse of the call). Adding a positional discriminator would mean an unrelated insertion above a reviewed call silently revokes its justification, which turns every refactor into a re-review and is exactly the drift the content hash exists to avoid.
Two identical calls in one function share a justification, which is correct: they are the same call with the same interpolated value, so one written reason covers both. What it costs is that a reviewer approving one has approved the other, and that is the deliberate half of the trade.
| self.tainted.append( | ||
| self._implicit_base_taint() if isinstance(node, ast.ClassDef) else {} | ||
| ) |
There was a problem hiding this comment.
Carry visible taint into nested function scopes
When interpolated source is assigned in an enclosing function or at module scope and then executed by a nested function, initializing every function's taint map to {} loses the binding even though Python resolves it through a closure or global lookup. For example, payload = f"import {name}" followed by def inner(): exec(payload) passes this lint with zero findings while inner() executes the interpolated source. Seed nested functions with visible enclosing taint, excluding class namespaces and names shadowed by parameters or local bindings.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining, standing limit. Taint stops at the scope boundary on purpose: the checker resolves a name where it is EXECUTED, one level of local indirection, and never chains a binding into another scope. A nested function, a closure or a lambda may run at any time, or never, and with any enclosing state; following taint into one means modelling when it runs, which is the dataflow engine this deliberately is not.
The direction is a miss rather than a false positive, and the interpolation is still reported wherever it is built in the scope that builds it.
| not. Unparsing means reindenting, rewrapping or reflowing the call does not | ||
| invalidate a justification, while changing what is interpolated does. | ||
| """ | ||
| return hashlib.sha256(ast.unparse(node).encode("utf-8")).hexdigest()[:16] |
There was a problem hiding this comment.
Invalidate reviews when interpolated values change origin
When a justification depends on where an interpolated variable originates, changing that producer does not alter this call-only hash. For example, an existing allowlisted exec(f"...{config_filename}...") remains approved if config_filename is changed from the hardcoded list cited by its reason to a downloaded configuration value, reintroducing the motivating vulnerability without touching the call AST. Include the reviewed value-producing expressions in the fingerprint, or otherwise require re-review when those dependencies change.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining, standing limit, and the trade is the same one as the duplicate-call-site item. The hash covers ast.unparse of the CALL, so changing what is interpolated invalidates it and reformatting does not. Hashing the producer of the interpolated value as well would mean an edit anywhere upstream revokes an unrelated approval, and a reviewer would be re-justifying calls whose own text has not changed.
The justification is written about the call and what can reach it; that is what the reviewer signs off on.
| out.append(indent + _magic_argument(rest)) | ||
| continuing = line.rstrip().endswith("\\") | ||
| continue | ||
| out.append(indent + "pass") |
There was a problem hiding this comment.
Scan Python commands in notebook shell escapes
When a scanned notebook uses the common !python -c '...' form, this branch replaces the entire shell escape with pass, including the Python program that actually runs. python --help defines -c cmd as a program passed in as a string, yet a cell such as !python -c 'name=input(); exec(f"import {name}")' exits this lint with zero findings. Reuse the existing %%script command extraction for Python interpreter invocations reached through ! rather than discarding their -c payload.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in f3c0628. Reproduced: !python -c 'name=input(); exec(f"import {name}")' exited 0 with zero findings, because the whole escape was replaced with pass.
The %%script extractor now answers the ! form too, since it is the same question. One detail worth stating: the program takes the escape's place in the neutralised text rather than being appended after it, so a one-line -c program keeps the line count exactly and a sink further down the same cell is still reported at its own line. Pinned by a regression case.
Each reproduced against the checker first, and each is a specific named mechanism
rather than a general widening.
from functools import partial as bind, then bind(exec, f"...")(): only a callee
literally spelled partial was read, so the ordinary imported-alias form went unseen.
The alias is recorded under its own key and cleared when the name is rebound, and a
function-local assignment shadows it for the whole body, so bind = print inside a
function is a print again.
exec(codeop.compile_command(f"...")): the stdlib compiles the interpolated source
straight to a code object. Checked against CPython: compile_command("x = 1")
returns a code object. Positional and the documented source keyword.
exec(operator.add("import ", name)) and operator.concat: the stdlib documents both
as returning a + b, so they are rebuilt as that operator and read there, which also
applies the visibly numeric exclusion. operator.add(1, 2) stays quiet.
getattr(__import__("builtins"), "exec")(f"..."): the attribute spelling already
recognised the inline import; the getattr owner still required a plain Name.
Verified: allowlist counts unchanged at 0 / 60 / 40, so none of these matches
anything already in tree; a 331-file corpus gives identical per-file findings for
every pre-existing case; the three copies stay byte-identical apart from
DEFAULT_TARGETS. Seven regression cases added.
Each reproduced against the checker before any change.
False positive removed: any attribute named partial was treated as
functools.partial, so an application object's own runner.partial(exec, ...) method
failed the gate on valid code. The owner now has to be functools, written out or
under an import alias, which is recorded in its own key so ft.exec does not become
a sink.
Bypasses closed: dict(run = exec).get("run") on the callee side, which the source
side already read; a walrus in a short-circuited operand, which cleared a taint
that survives at runtime; an assignment in the final body of a literal loop, which
was overwritten by the iterable's last element in both directions;
contextlib.nullcontext(builtins.exec) as run, whose target is stated outright
rather than opaque; a literal template reached through a name, which is a two-line
refactor away from the literal receiver already handled; and a program attached to
a bundled short option, python -uc'prog', checked against the CLI.
The template tracking is deliberately narrow: only a name a written-out string
bound sets the marker, so exec(inspect.getsource(f).replace(...)), the idiom this
repo is built on, still resolves to nothing there.
Verified: allowlist counts unchanged at 0 / 60 / 40; a 342-file corpus gives
identical per-file findings for every pre-existing case; the three copies stay
byte-identical apart from DEFAULT_TARGETS; self-test green on 3.9 and 3.13. Ten
regression cases added, 143 in the file.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 796cbe4a78
ℹ️ 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".
| for child in ast.walk(node.target): | ||
| if isinstance(child, ast.Name) and isinstance(child.ctx, ast.Store): | ||
| self.tainted[-1].pop(child.id, None) | ||
| if child.id in before_loop: | ||
| self.tainted[-1][child.id] = before_loop[child.id] |
There was a problem hiding this comment.
Preserve all bindings when an opaque loop may be empty
For an iterable whose contents are unknown, this restores only names in the loop target, while assignments made by the visited body remain applied even though the loop may execute zero times. For example, payload = f"import {name}"; for _ in items: payload = "pass"; exec(payload) exits successfully when scanned, but with items=[] the interpolated payload reaches exec. Restore the complete pre-loop state for the zero-iteration path and merge it with the state after one or more iterations.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining, standing limit, and it is the same one as the try item on this PR. Reproduced the miss, so the report is accurate.
What is being asked for is a state merge: analyse the zero-iteration path from the pre-loop state, analyse the one-or-more path, and join them. This checker does statement-level binding within one path and has no join operator, deliberately. The same reasoning already declined taint across conditional rebinding, and a loop that may run zero times is that in another spelling. Adding a join for loops alone would make the two answers inconsistent depending on which construct wrote the branch.
The loop TARGET is restored because that part is not a merge: the target is unbound if the loop never ran and holds the last element if it did, and neither of those is the aggregate. Documented in the file as a best-effort heuristic rather than sound taint analysis, which is what this is.
| if empty and function.attr == "format_map" and not node.keywords: | ||
| # `format_map` requires exactly one mapping argument, so the empty | ||
| # call raises TypeError before the sink is reached. | ||
| return None |
There was a problem hiding this comment.
Preserve receiver taint through an empty format_map
When format_map is given an empty literal mapping, empty is true even though the required mapping argument is present, so this branch incorrectly treats the call as the argument-less TypeError case. Consequently, exec(f"import {name}".format_map({})) exits this lint successfully even though the call returns the already-interpolated receiver and exec runs it. Distinguish a missing argument from a present empty mapping and propagate interpolation from the receiver in the latter case.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 151fb79. Reproduced: exec(f"import {name}".format_map({})) exited 0.
empty was doing two jobs. It is set from not spliced and then RESET when the one argument is an empty container, so by the time the format_map TypeError branch reads it, "no argument at all" and "one argument that happens to be empty" look the same. The argument-less fact now has its own name and that branch keys on it; the receiver-preserving branch below still keys on empty, which is what it wanted all along.
| # The numeric marker travels with an annotated assignment too, or | ||
| # `payload: int = 1; payload += 2` read as concatenation and failed the | ||
| # gate on arithmetic that can only ever raise TypeError at the sink. | ||
| self._bind(node.target, reason, numeric = _visibly_numeric(node.value)) |
There was a problem hiding this comment.
Mark annotated literal templates before replace
Unlike visit_Assign, this annotated-assignment path never sets the literal-text marker when the value is a written-out string. Therefore template: str = "import MODULE"; exec(template.replace("MODULE", name)) exits the lint successfully even though replace splices name into executable syntax; the equivalent unannotated assignment is detected. Pass the same literal_text fact into _bind here so adding a type annotation cannot disable the check.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. Reproduced: template: str = "import MODULE"; exec(template.replace("MODULE", name)) exited 0 while the identical unannotated spelling exited 1.
visit_AnnAssign was passing numeric through and not literal_text, so an annotation switched off the .replace() detection. It now passes the same reason is None and _visibly_literal_text(node.value) fact visit_Assign records.
Each reproduced against the checker first.
!python -c 'prog' runs prog as Python exactly as %%script python -c does, but the
whole escape was replaced with pass and the program thrown away. The same extractor
answers both now, and the program takes the escape's place rather than being added
after it, so a sink further down the same cell keeps its own line number.
exec(*{**{}, f"...": None}) went unreported because a leading **{} makes the first
AST key None; the empty expansion is stepped over to reach the key the mapping
really yields.
Three false positives removed. str() of visibly bytes is the repr, "b'import os'",
which executes as a string expression and imports nothing, so str is no longer
unwrapped over a bytes-like argument. A visibly zero or negative repetition builds
the empty string, so exec(f"..." * 0) and * -1 are quiet.
Verified: allowlist counts unchanged at 0 / 60 / 40; a 349-file corpus gives
identical per-file findings for every pre-existing case; the three copies stay
byte-identical apart from DEFAULT_TARGETS. 148 cases in the test file.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f3c0628813
ℹ️ 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".
| return None | ||
|
|
||
|
|
||
| class _Visitor(ast.NodeVisitor): |
There was a problem hiding this comment.
Preserve taint across exceptional paths
Because _Visitor has no visit_Try, the generic sequential walk treats assignments in a try suite as unconditional. For example, payload = f"import {name}"; try: may_raise(); payload = "pass"; except Exception: pass; exec(payload) exits this lint successfully: visiting the literal assignment clears payload, although an exception from may_raise() reaches the handler before that assignment and leaves the interpolated source executable. Analyze the normal and exceptional paths from the pre-try state and merge their possible bindings.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining, standing limit, same one as the empty-loop item above. Reproduced the miss.
try/except is a control-flow join: the handler sees whatever the suite had bound when it raised, and there is no single point in the suite where that is. Answering it means merging the possible bindings at the handler, which is the state merge this checker does not do; it also already declines the plain conditional form, if cond: payload = "pass". Answering one and not the other would mean the gate's behaviour depends on which construct expressed the branch.
The cost is stated plainly: a name rebound inside a try reads as unconditionally rebound. It is a bypass in the same class as the if one, and a value that reaches a sink through it is not caught.
| if module == "builtins" or (aliases is not None and aliases(f"module:{module}")): | ||
| return f"builtins.{function.attr}" |
There was a problem hiding this comment.
Recognize the implicit builtins sink
In an ordinary CPython module, the unshadowed implicit __builtins__ name is the builtins module, so __builtins__.exec(f"import {name}") executes the interpolated source. This resolver only accepts the literal owner name builtins or a recorded alias, causing that example to exit the lint with zero findings. Treat an unshadowed __builtins__ owner as the builtin namespace as well, including its module and mapping spellings.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. Reproduced: __builtins__.exec(f"import {name}") exited 0.
_is_builtins_mapping already accepted an unshadowed __builtins__ as the namespace MAPPING; the attribute-owner resolver did not, so the module spelling was unread. It accepts both names now. Worth stating which case this really is: CPython binds __builtins__ to the module in __main__ and to its dict in an imported module, so the attribute call works exactly in a script that is run directly, and the dict spelling raises AttributeError. Reporting is right for a gate either way, since these files are run both ways.
| if candidates: | ||
| answer = candidates[0] | ||
| for other in candidates[1:]: | ||
| answer = _either_value(answer, other) | ||
| return answer |
There was a problem hiding this comment.
Merge compile's keyword source after an opaque star
When compile has an opaque starred positional argument, this early return prevents the later source= keyword from being considered. For example, def f(name, args=()): compile(*args, source=f"import {name}", filename="<x>", mode="exec") is valid and compiles the f-string when args is empty, but the lint exits successfully because it examines only the unresolvable *args. Since an opaque expansion may contribute no values, merge the explicit or expanded keyword source into the candidate set before returning.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. Reproduced: compile(*args, source = f"import {name}", filename = "<x>", mode = "exec") with args = () exited 0.
An opaque expansion is already kept as a candidate rather than stopping the scan, on the argument that it may contribute nothing, but the early return then skipped the keyword form entirely. For compile, when any candidate is an opaque Starred, the source= keyword is merged in as the other value the argument may take. The keyword lookup moved into _compile_keyword_source so both paths read the same one rather than a copy.
| for child in ast.walk(item.optional_vars): | ||
| if isinstance(child, ast.Name) and isinstance(child.ctx, ast.Store): | ||
| self.tainted[-1].pop(child.id, None) |
There was a problem hiding this comment.
Keep nullcontext's handed-off taint
For a recognized nullcontext, the preceding _bind records the interpolated argument on the as target, but this loop immediately removes that binding along with bindings from opaque context managers. Consequently, with contextlib.nullcontext(f"import {name}") as payload: exec(payload) exits the lint successfully even though nullcontext.__enter__ returns the f-string unchanged. Only clear targets when the context result is opaque; preserve the reason derived from handed otherwise.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. Reproduced: with contextlib.nullcontext(f"import {name}") as payload: exec(payload) exited 0.
Ordering bug of my own making: the loop that clears stale target names ran AFTER the _bind that records what nullcontext handed over, so it deleted the reason it had just written. The clearing now runs first, which keeps both jobs: a tuple target against an opaque manager still loses its stale reason, and the handed value survives.
Each reproduced against the checker first. Misses closed. A mixed literal loop now prefers a sink over a constructor, so for run in [builtins.str, builtins.exec] no longer records only the conversion and loses the second iteration's call. A statically false while body is not traversed, which is what visit_If already did for if, so an unreachable run = print stops suppressing the real builtin. _constant_truth folds a boolean operation, so a comprehension filter like True and False is decided and the walrus it never binds is not exported. And a literal loop element is resolved against the taint map, so for source in [payload] carries what payload holds. False positives removed. The constructor conditional folds with _constant_truth rather than a bare constant, matching the sink resolver. An except target now clears the prefixed alias tables as well, so from builtins import str as text followed by except E as text no longer reports a call that raises first. async for over a synchronous literal raises TypeError before the body, checked against CPython, so it no longer infers iterations from one. And installing a constructor alias clears any earlier sink entry for the same name, since a name holds one thing. Verified: allowlist counts unchanged at 0 / 60 / 40; a 358-file corpus gives identical per-file findings for every pre-existing case; the three copies stay byte-identical apart from DEFAULT_TARGETS. 156 cases in the test file.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0c4aa66f07
ℹ️ 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 isinstance(function, ast.Name): | ||
| preserving = function.id | ||
| elif isinstance(function, ast.Attribute) and isinstance(function.value, ast.Name): | ||
| preserving = function.attr |
There was a problem hiding this comment.
Resolve aliases of text-preserving wrappers
When dedent or indent is imported under an alias, this check sees only the alias name and stops before inspecting the interpolated argument. For example, from textwrap import dedent as clean; exec(clean(f"import {name}")) exits with zero findings even though clean returns the generated source that exec runs. Record and resolve aliases for these recognized text-preserving functions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in d003d60. Reproduced: from textwrap import dedent as clean; exec(clean(f"import {name}")) exited 0.
from textwrap import ... as ... is now recorded in a text: namespace and the callee resolves through it, with the same shadow test, and a local rebinding of the alias clears it like every other prefixed entry.
| shadowed is not None and shadowed("codeop") | ||
| ): | ||
| return _is_interpolated(compiled, resolve, shadowed, resolve_alias) | ||
| if function.attr in ("add", "concat") and isinstance(function.value, ast.Name): |
There was a problem hiding this comment.
Recognize operator.mod as percent formatting
When percent formatting is written through its standard-library functional spelling, this branch ignores it because it recognizes only operator.add and operator.concat. Thus exec(operator.mod("import %s", name)) executes the interpolated source but the lint exits successfully with zero findings. Handle operator.mod equivalently to an ast.Mod binary expression.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. operator.mod is % written as a call, exactly as add is +. The three recognised names became a table from name to AST operator, which also picked up imod, and the call is rebuilt as that operator and read there, so the visibly numeric exclusion still applies to operator.mod(5, 2).
| isinstance(function, ast.Call) | ||
| and isinstance(function.func, ast.Attribute) | ||
| and function.func.attr == "get" | ||
| and function.args | ||
| and isinstance(function.args[0], ast.Constant) |
There was a problem hiding this comment.
Resolve getitem calls on the builtins mapping
When a sink is selected with the method spelling of a mapping lookup, the call resolver handles .get(...) but not .__getitem__(...). Consequently, builtins.__dict__.__getitem__("exec")(f"import {name}") executes the interpolated source while this lint exits with zero findings; assigning that result to a local alias also remains undetected. Resolve this spelling the same way as builtins.__dict__["exec"].
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. builtins.__dict__.__getitem__('exec')(f"import {name}") exited 0.
The resolver already read .get(...) as the mapping lookup it is; __getitem__ is the subscript spelling written as a call and goes through the same branch now, so the local-alias form resolves with it.
| def visit_TypeAlias(self, node): | ||
| """`type run = int` rebinds the name for the rest of the scope.""" | ||
| bound = getattr(node, "name", None) | ||
| if isinstance(bound, ast.Name): | ||
| self._shadow_sink(bound.id) |
There was a problem hiding this comment.
Traverse lazy type-alias values
On Python 3.12+, this visitor rebinds the alias name but never visits the alias value. A module containing type Payload = (exec(f"import {name}") or int) therefore passes the lint with zero findings, while accessing Payload.__value__ evaluates the lazy alias and executes the interpolated source. Visit the alias value so dynamic-execution calls stored in PEP 695 aliases are checked.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed, and lazy is the right word for it: a PEP 695 alias value is not dead code, reading Payload.__value__ evaluates it. type Payload = (exec(f"import {NAME}") or int) exited 0.
The visitor rebound the name and never visited the value. It visits it now, after the rebinding, which is the order the alias is evaluated in.
| if level != len(self.scope_kinds) - 1: | ||
| # `global exec; del exec` deletes the MODULE binding, so the shadow an | ||
| # earlier `exec = print` left there has to go and the following call | ||
| # reaches the builtin. Treating it as a function-local delete kept that | ||
| # shadow and reported the call as nothing. Same for `nonlocal`. |
There was a problem hiding this comment.
Keep nonlocal names unbound after deletion
When del targets a nonlocal sink spelling, this branch treats it like a deleted global and removes the enclosing shadow. For example, if outer binds exec = print and inner declares nonlocal exec, then del exec; exec(f"import {name}") raises NameError because the closure cell is empty, but the lint instead resolves the final call as the builtin and fails the gate. Preserve an unbound/shadowed fact for deleted nonlocal cells rather than applying the global fallback rule.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed, and the distinction you draw is the right one. A deleted GLOBAL falls back to the builtin, which is why that branch exists; a deleted NONLOCAL cell is empty and the name raises NameError.
Only the nonlocal half changed: the name is marked shadowed in the deleting scope and in the cell's own scope, so the following call reads as unresolvable rather than as the builtin.
… reason
Each reproduced against the checker before it was changed.
Misses closed. A visible nullcontext hands its argument to the as target, and
the stale-target clearing that followed deleted the very binding it had just
recorded. An annotated assignment now carries the literal-text marker, so an
annotation no longer disables the .replace() check. format_map keyed its
TypeError case on empty rather than argument-less, so .format_map({}) returned
the built receiver unread. compile behind an opaque star merges its source
keyword, since the expansion may contribute nothing. __builtins__ resolves as
the builtins module for the attribute spelling as well as the mapping one. A
positive augmented repetition keeps the receiver's own taint. codeop, operator
and ast resolve through an import alias instead of the literal module name. A
statement after an unconditional break in a loop body is no longer visited.
An unknown boolean operand ahead of a decisive constant still decides:
flag and False is falsy either way.
False positives fixed. A local binding of operator, codeop, ast, importlib or
functools now shadows the module, so a helper parameter is not rewritten as the
stdlib call. Assigning the builtins module to a name clears the sink and
constructor entries it had, which the reverse direction already did.
Allowlist reason corrected. incremental_save_pretrained formats repo_id and
revision into the generated save_pretrained, so 'nothing external is spliced in'
was false. Both go through repr now and the reason says so.
Corpus of 358 files: no change in findings. Allowlists unchanged.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 151fb793d8
ℹ️ 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".
| function.value, "codeop", shadowed, resolve_alias, | ||
| ): | ||
| return _is_interpolated(compiled, resolve, shadowed, resolve_alias) | ||
| if function.attr in ("add", "concat") and isinstance(function.value, ast.Name): |
There was a problem hiding this comment.
Recognize in-place operator concatenation
operator.iadd and operator.iconcat also return the concatenation of two strings, but this branch recognizes only add and concat. Consequently, exec(operator.iadd("import ", name)) and the equivalent iconcat spelling execute interpolated source while the lint exits successfully with zero findings; handle these names through the same ast.Add path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed, in the same table as mod. str has no in-place add, so operator.iadd and iconcat return the concatenation just as add and concat do, and both are rebuilt as ast.Add.
| if not _visibly_numeric(node): | ||
| if isinstance(node.op, ast.Mod): | ||
| return "%-format" | ||
| if isinstance(node.op, ast.Add): | ||
| return "string concatenation" |
There was a problem hiding this comment.
Exclude visibly non-text additions
When both operands visibly produce containers rather than text, this unconditional ast.Add classification creates a false CI failure. For example, exec([f"import {name}"] + []) is reported as string concatenation even though the result is a list and exec always raises TypeError before executing anything; recognize visibly list/tuple concatenation as non-source just as the numeric case is excluded.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed, and thank you for it: false positives are the reports worth the most here. exec([f"import {name}"] + []) exited 1 on a call that can only raise TypeError.
Both operands have to be written-out list, tuple or set displays; anything unknown still reads as concatenation. Same argument the visibly numeric exclusion beside it already makes.
| for statement in (node.body if decided else node.orelse): | ||
| self.visit(statement) |
There was a problem hiding this comment.
Stop walking a while suite after an unconditional break
When a while body contains a top-level break, statements below it are still visited and can clear taint that survives at runtime. For example, payload = f"import {name}"; while True: break; payload = "pass"; exec(payload) exits this lint successfully because the unreachable literal assignment is applied, although execution breaks out of the loop and hands the original interpolated payload to exec; stop at unconditional control-transfer statements as visit_For already does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. The rule now lives in one place, _definitely_jumps, and both loop forms use it - along with the if suites, which end at a jump for the same reason. Your while True: break case and the nested if True: continue case reported on another copy of this file are both closed by it.
| `visit_For` inferred iterations from those literals and reported a sink that | ||
| cannot execute. The literal is still visited, since it is evaluated. | ||
| """ | ||
| if self._literal_elements(node.iter): |
There was a problem hiding this comment.
Treat empty synchronous async iterables as invalid
When the synchronous literal is empty, _literal_elements returns [], so this truthiness check falls through to visit_For and visits the loop's else suite. At runtime, async for _ in [] raises TypeError before either suite can complete, so an interpolated sink in its else is incorrectly reported and blocks CI; distinguish an unreadable iterable (None) from every readable synchronous literal, including an empty one.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed, and the bug was mine: I wrote a truthiness test where I needed is not None. An empty literal made it fall through to visit_For, which read the list as an empty ITERABLE and visited the else suite, when CPython raises TypeError while getting the async iterator and neither suite runs.
| if case.guard is not None: | ||
| self.visit(case.guard) | ||
| for statement in case.body: | ||
| self.visit(statement) |
There was a problem hiding this comment.
Skip match bodies guarded by a constant false condition
When a case has a statically false guard, its body is still visited and its assignments leak into the taint map. For example, payload = f"import {name}"; match value: case _ if False: payload = "pass"; exec(payload) exits this lint successfully even though the case body cannot run and the interpolated payload reaches exec; visit the guard for side effects, but skip the body when _constant_truth proves the guard false.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. A case guard this can decide now decides the body, which is the same literal rule visit_If and visit_While apply to their tests. The guard itself is still visited, since it is evaluated, and the case's own bindings are restored before moving on.
| for field in ("elt", "key", "value"): | ||
| child = getattr(node, field, None) | ||
| if child is not None: | ||
| self.visit(child) |
There was a problem hiding this comment.
Restore taint when an eager comprehension cannot iterate
Although runs_a_pass prevents sink aliases from being exported for an empty comprehension, the element is visited unconditionally and a walrus there still mutates the enclosing taint map. Thus payload = f"import {name}"; [(payload := "pass") for _ in []]; exec(payload) passes the lint even though the walrus never runs and the original interpolated payload is executed; when no comprehension pass is possible, restore taint for its walrus targets as is already done for lazy generator expressions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. Suppressing the alias export was only half of it, exactly as it was for the lazy generator expression: visiting the element had already cleared what those names held. When no pass is possible, the pre-comprehension taint is put back for the walrus names, which is what the generator branch already did.
| if ( | ||
| isinstance(count, ast.Constant) | ||
| and isinstance(count.value, int) | ||
| and not isinstance(count.value, bool) | ||
| ): | ||
| return sign * count.value > 0 |
There was a problem hiding this comment.
Treat False as a zero repetition count
Python accepts booleans as integer repetition counts, so f"import {name}" * False evaluates to the empty string and executes no generated source. Excluding bool here makes _positive_repetition(False) return the conservative default True, causing this harmless call to fail CI; handle False as zero while retaining True as one.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. bool was excluded outright, so False fell through to the conservative default. It is read as its integer value now, which makes s * False empty and s * True one copy.
Each reproduced against the checker first, and the pre-existing corpus of 358
files reports exactly what it did before.
Misses closed. A textwrap function imported under an alias resolves through its
own namespace. operator.mod, imod, iadd and iconcat join add and concat, each
rebuilt as the operator it is. __getitem__ is read as the subscript it spells,
so builtins.__dict__.__getitem__('exec') resolves. A PEP 695 type alias value is
visited: it is lazy, not dead, and reading __value__ evaluates it. A while suite
now ends at a jump that always leaves it, and a jump under a decidable test
counts, which covers the if True: continue spelling in a for body as well. A
statically false case guard no longer runs its body. A comprehension that can run
no pass restores the taint its walrus appeared to clear, which the lazy generator
case already did. An empty display is a decidable false condition. A literal
sequence subject pairs element for element with a literal sequence pattern. A
conditional constructor callee checks every arm rather than the first that
resolves.
False positives fixed. False is a zero repetition count and True is one. Two
written-out containers add to a list, which a sink cannot execute. An async loop
over an empty synchronous literal raises before its else suite, as it does over a
nonempty one. A deleted nonlocal cell is empty rather than the builtin. A zero
precision format spec keeps nothing. Removing the receiver as its own prefix
leaves nothing. A written-out nonempty expansion supplies the source, so the
argument after it is not merged in. Unpacking and walrus bindings carry the
numeric and literal-text markers ordinary assignments record. dict takes at most
one positional argument. The decoding form of str rejects text. A local
contextlib, nullcontext or textwrap function shadows the stdlib one. A literal
template with no replacement field ignores its arguments.
Allowlists unchanged at 0, 60 and 40. Self-test green on 3.9 and 3.13.
str(b'...') is the repr of the bytes and executes nothing, but str(b'...', 'utf-8')
decodes and hands the text straight back. The exemption now applies only to the
one-argument spelling, so exec(str(f'import {name}'.encode(), 'utf-8')) reports.
async with cannot enter a synchronous context manager: CPython answers TypeError
before the body runs. visit_AsyncWith is no longer an alias of visit_With, so a
written-out nullcontext there stops the body being read at all. Everything else
visit_With does still applies, since an ordinary async manager does run its body.
Corpus of 358 files: no change in findings. Allowlists unchanged.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d003d603bb
ℹ️ 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 `str.format` replacement field. `{{` and `}}` are escapes for a literal brace, so | ||
| # they are stepped over before a real field is looked for. | ||
| _FORMAT_FIELD = re.compile(r"(?<!\{)\{(?!\{)[^{}]*\}") |
There was a problem hiding this comment.
Parse replacement fields nested inside escaped braces
When a real replacement field is surrounded by escaped braces, this regex mistakes the whole template for field-free text. For example, exec("{{{x}}}".format(x=name)) produces {<name>} and executes attacker-controlled syntax when name is something like __import__('os'), but the lint exits successfully because _FORMAT_FIELD.search() returns no match. Use Python's format-string parsing semantics rather than the brace-adjacency regex before suppressing the finding.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 2ae6017, and the regex was mine from last round, so this is a good catch on a fresh edge. exec("{{{x}}}".format(x = name)) produces {<name>} and exited 0.
Replaced with string.Formatter().parse, which is what str.format itself uses, so {{ and }} are escapes and the field between them is found. A template format would reject raises ValueError there, and that is treated as unknown, which keeps the source.
| return _is_interpolated( | ||
| ast.copy_location(equivalent, node), resolve, shadowed, resolve_alias, | ||
| ) | ||
| if function.attr == "parse" and isinstance(function.value, ast.Name): |
There was a problem hiding this comment.
Resolve directly imported ast.parse aliases
When parse is imported directly, this attribute-only branch never inspects the source it parses. For example, from ast import parse; compile(parse(f"import {name}"), "<x>", "exec") exits the lint with zero findings even though the AST handed to compile was built from the interpolated source. Record and resolve direct imports of ast.parse, including aliases, just as the checker already does for other source-preserving wrappers.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. from ast import parse binds the helper with no module attribute to match on.
Both direct-import helpers are recorded now - ast.parse and codeop.compile_command - under a stdlibfunc: namespace keyed by the qualified name, and such a call is rewritten to the qualified spelling and read by the existing branch. One implementation of each rule rather than a second copy for the direct form.
| if module == "builtins" or ( | ||
| aliases is not None and aliases(f"module:{module}") | ||
| ): |
There was a problem hiding this comment.
Recognize getattr on the implicit builtins module
When __builtins__ is the module, as it is for a directly executed script, getattr(__builtins__, "exec")(f"import {name}") executes the interpolated source but exits this lint with zero findings. Fresh evidence beyond the previously fixed attribute spelling is that the current _getattr_sink_name owner check still accepts only literal builtins or a recorded module alias; include an unshadowed __builtins__ here as _sink_name already does for __builtins__.exec.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. The attribute spelling learned __builtins__ last round and this owner check did not, so the two disagreed on the same module. Both accept it now.
Same caveat worth restating: CPython binds __builtins__ to the module in __main__ and to its dict elsewhere, so this is exactly the script-run-directly case.
| if function.attr in ("format", "format_map"): | ||
| return _is_interpolated(function.value, resolve, shadowed, resolve_alias) | ||
| return None | ||
| if function.attr == "format" and _visibly_literal_text(function.value): |
There was a problem hiding this comment.
Exclude field-free format_map templates
When a literal format_map template contains no replacement fields, its mapping is never consulted and no interpolation occurs, but this exemption applies only to format. Consequently, exec("pass".format_map({"x": name})) fails the new hard CI gate even though the result is always the literal "pass"; apply the same field-free-template check to format_map.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. format_map never consults its mapping for a template with no replacement field, so it takes the same answer format does. Both spellings go through the one check now, which is also the one that moved to string.Formatter for the escaped-brace case in this round.
| # exists at all. Nested scopes still see the binding, because they | ||
| # are deferred - that is `_collect_aliases` on their own body plus | ||
| # the outward walk, not this shadow. | ||
| return |
There was a problem hiding this comment.
Apply later module rebindings to deferred function bodies
When a module-level name is rebound after a function definition, the function resolves that final global binding when it is called, but this return prevents the deferred view from recording ordinary non-sink assignments. For example, def f(name): exec(f"hello {name}") followed by exec = print is reported even though calling f after module initialization only invokes print; keep eager statements above the assignment unshadowed while separately marking the rebinding for deferred nested bodies.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining, and this one I implemented, measured and reverted, so the reasoning is empirical rather than a matter of principle.
The change was exactly what you describe: record the rebinding for deferred bodies only, leaving the eager statements above it unshadowed. It closed your case. It also turned five existing corpus findings into misses, because a deferred shadow is consulted ahead of the alias table and is never cleared, and all five re-establish the builtin AFTER the assignment: global exec; exec = builtins.exec inside the function itself, a module-level for exec in [builtins.exec], a class body's global exec; from builtins import exec, and global exec; del exec. Each of those is a real call to the builtin, and each went quiet.
The def exec form does not have that problem, which is why it is recorded: a name given a def is not handed back to the builtin further down. An assignment is, in four different spellings.
The cost is stated plainly: def f(name): exec(f"...") above a module-level exec = print is reported, and can carry a written justification. I would rather have that than five bypasses, and the reasoning is now a comment at the site so the next reader does not retry it.
| was skipped entirely. `studio/backend/core/inference/tools.py` already resolves | ||
| sink arguments this way. | ||
| """ | ||
| if node.args[skip:]: |
There was a problem hiding this comment.
Ignore compile calls missing required arguments
When compile is given only an interpolated source, this branch reports it without checking that the mandatory filename and mode arguments exist. Thus compile(f"import {name}") fails the hard CI gate even though Python raises TypeError before compiling any source; only return a source candidate when the visible call can satisfy compile's required arguments, while retaining conservative handling for opaque expansions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. compile(source, filename, mode) has no defaults, so compile(f"import {name}") raises TypeError before compiling anything.
Only a call whose arguments are all visible is judged this way: a * or ** may supply what is missing and counts as complete, so this only ever declines to report a call CPython refuses outright.
| if empty: | ||
| return _is_interpolated(function.value, resolve, shadowed, resolve_alias) | ||
| return None |
There was a problem hiding this comment.
Preserve taint through identity translation tables
When translate receives a nonempty mapping, this unconditional None result drops the interpolated receiver even if the mapping is provably an identity transformation. For example, exec(f"import {name}".translate({0: 0})) executes the unchanged f-string for every value of name, but the lint exits successfully because the table is nonempty; recognize literal entries that map a code point to itself, rather than treating every nonempty table as removing the source.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. A table that maps every code point it names to itself changes nothing, so the receiver comes through unaltered.
Every entry has to be a written-out integer on both sides and equal; a computed key, a name or a ** leaves the table unknown and the source is still dropped, since translate({0: None}) really does remove text.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6ebfc24207
ℹ️ 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 ast.dump(function.value) == ast.dump(node.args[0]): | ||
| return None |
There was a problem hiding this comment.
Restrict the self-prefix exemption to stable expressions
When the repeated expression has side effects, identical ASTs do not imply identical runtime values because the receiver and argument are evaluated separately. For example, with values = iter(["result = 42", "not-a-prefix"]), exec(f"{next(values)}".removeprefix(f"{next(values)}"), scope) executes the first generated string, but this equality check suppresses the finding and the lint exits successfully. Limit this exemption to expressions whose repeated evaluation is guaranteed to produce the same text.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 2a36e6c, and this is a real hole in a fix I added two rounds ago: identical source is not identical value when either side can advance something.
The exemption now requires a stable expression - constants, names and f-strings built from them. Any call, walrus, await, yield, subscript or attribute access makes it unstable, since each of those can run arbitrary code. f"{next(values)}".removeprefix(f"{next(values)}") reports again, and the plain literal case stays quiet.
| if function.attr == "format" and _visibly_literal_text(function.value): | ||
| # `"pass".format(name)` has no replacement field, so the arguments | ||
| # change nothing and the result is the literal. Only a written-out | ||
| # template is read this way; a variable receiver may well hold one. | ||
| template = function.value.value | ||
| if isinstance(template, str) and not _FORMAT_FIELD.search(template): | ||
| return None |
There was a problem hiding this comment.
Recognize fieldless literal templates reached through names
When a fieldless literal is assigned to a local first, this check no longer recognizes it as a literal template: template = "pass"; exec(template.format(user)) is reported even though user is ignored and the executed source is always the fixed literal. The visitor already records such assignments with _LITERAL_TEXT, so consult that marker here as well; otherwise this harmless one-line refactor causes the new hard CI gate to fail.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. Making the check work through a name needed the marker to carry the TEXT rather than just the fact that a literal is held, since template = "pass" and template = "import {m}" are different questions.
It does now, so the field scan is the same one, and I added the second case as a test alongside yours: the templated one still reports. The .replace() rule that already read the marker is unchanged.
| if isinstance(statement, ast.ImportFrom): | ||
| if statement.module == "builtins" and not statement.level: |
There was a problem hiding this comment.
Pre-collect non-builtin aliases for deferred functions
When a function is defined before a recognized non-builtin import and invoked after that import, this pre-pass records only builtins aliases, so the function is scanned before the later alias is known and is never revisited. For example, def f(name): exec(clean(f"result = {name}")) followed by from textwrap import dedent as clean and then f("42") executes the interpolated source while the lint exits successfully; the same gap affects later codeop and functools aliases. Pre-collect the recognized stdlib aliases used by deferred bodies just as the existing constructor and sink aliases are collected.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. The pre-pass collected the builtins imports for deferred bodies and stopped there, so every stdlib alias added over the last few rounds had the same gap.
textwrap, codeop, ast, importlib, functools, the direct-helper imports and from functools import partial are all pre-collected now, in both the import x as y and from x import y spellings.
| def _keeps_everything(bound, whole): | ||
| if bound is None: | ||
| return True | ||
| if isinstance(bound, ast.Constant) and bound.value == whole: | ||
| return not isinstance(bound.value, bool) | ||
| return False |
There was a problem hiding this comment.
Normalize signed constants in whole-object slices
When a whole-object slice spells its zero lower bound or unit step with a unary sign, _keeps_everything rejects the UnaryOp even though the slice is unchanged. For example, exec(f"result = {name}"[-0::+1], scope) executes the complete interpolated source but produces zero findings, giving a trivial bypass of the new security gate. Normalize unary +/- integer constants here as the literal-index and repetition helpers already do.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. -0 and +1 are UnaryOp nodes rather than constants, so the whole-object test rejected them and the slice read as narrowing. Normalised the same way the repetition and literal-index helpers already do.
| paired = self._sequence_pattern_pairs(node.subject, case.pattern) | ||
| for name, captures_subject in _pattern_bindings(case.pattern): | ||
| element_reason = None | ||
| if reason is not None and captures_subject: | ||
| element_reason = f"{reason} via `{name}`" | ||
| elif name in paired: | ||
| inner = _is_interpolated( | ||
| paired[name], self.tainted[-1].get, self._is_shadowed, self._alias, |
There was a problem hiding this comment.
Carry sink aliases through sequence-pattern captures
When a sequence pattern captures a builtin from a literal subject, the pairing logic propagates only interpolation taint and leaves the captured name shadowed as an ordinary local. For example, match [builtins.exec]: case [run]: run(f"result = {name}", globals()) executes the interpolated source, but the lint exits successfully because run is never installed as a sink alias. Resolve paired elements as sinks or constructors as well as source values before visiting the case body.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and already fixed - it landed a commit before this review ran, from the equivalent item on the zoo copy. Each paired element is resolved as a sink or a constructor and installed as the capture's meaning, so match [builtins.exec]: case [run]: run(f"result = {name}", globals()) reports on the current head. Verified against it.
| if isinstance(function, ast.IfExp) and _constant_truth(function.test) is None: | ||
| return [ | ||
| name for name in ( | ||
| _constructor_name(function.body, shadowed, aliases), | ||
| _constructor_name(function.orelse, shadowed, aliases), | ||
| ) if name is not None | ||
| ] | ||
| resolved = _constructor_name(function, shadowed, aliases) | ||
| return [] if resolved is None else [resolved] |
There was a problem hiding this comment.
Enumerate constructors in boolean callees
When a boolean callee contains multiple recognized constructors, this helper enumerates undecidable IfExp arms but collapses a BoolOp to the first constructor returned by _constructor_name. Thus (memoryview and str)(f"result = {name}") is treated only as memoryview, whose visible-text argument is rejected, even though both constructor objects are truthy and Python actually selects str; wrapping that expression in exec executes the generated source while the lint reports nothing. Return every reachable constructor from boolean callees before applying constructor-specific exclusions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. I enumerated the undecidable IfExp arms last round and left BoolOp collapsing to the first name, which is the same mistake one construct along. Every reachable operand is returned now, so (memoryview and str) offers both and the arm that forwards the argument is checked.
Each reproduced against the checker first. Misses closed. Replacement fields are found with string.Formatter, which is what str.format itself uses, so a field between escaped braces is a field. ast.parse and codeop.compile_command resolve through a direct import as well as through the module attribute. getattr reads the implicit __builtins__ module. An aliased importlib and an aliased contextlib resolve, which the stdlib: aliases already recorded. An identity translation table preserves the receiver. A literal sequence subject hands a sink or a constructor to its capture. Three evaluation order fixes: an unpacking binds each element before the next target is evaluated, an augmented subscript evaluates its target before the value, and a dict evaluates each key beside its own value rather than every key first. False positives fixed. A field-free format_map template ignores its mapping, as the format spelling already did. compile without a filename and a mode raises before it compiles. A bare partial is functools.partial only where the file imported it. A dedent or indent attribute has to be on the textwrap module. A class-body lambda installs its parameter shadows in the lambda's own scope, so _visible_scopes no longer skips them. One item declined with evidence. Applying a later module-level rebinding to deferred bodies was implemented and then reverted: five corpus cases re-establish the builtin after such an assignment, and a deferred shadow is consulted ahead of the alias table and never cleared, so it turned all five real findings into misses. The comment in the file records that. Corpus of 358 files: one change, the augmented subscript case, which is the fix. Allowlists unchanged at 0, 60 and 40. Self-test green on 3.9 and 3.13.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2ae6017442
ℹ️ 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".
| source = "".join(source) | ||
| if not isinstance(source, str): | ||
| # A cell whose `source` is a number or an object is not something this can | ||
| # read. Failing closed puts it in the unscannable c |
There was a problem hiding this comment.
Include the call site in allowlist identities
When two byte-identical calls occur in the same qualified scope, this key is identical for both because it contains no per-call location. For example, a reviewed exec(f"{payload}") followed later in the same function by rebinding payload from attacker input and repeating the call inherits the first call's justification; the repository already contains duplicate keys demonstrating the collision. Include a stable call-site discriminator so copying an allowlisted call requires a separate review.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining, standing limit - and the duplicate keys are real, so let me confirm that half rather than argue it.
Checked: five collisions, three in the zoo allowlist and two in the unsloth one, all of them two byte-identical calls in one function. That is the accepted consequence of the key, not evidence of a defect: they are the same call with the same interpolated value, so one written justification covers both, and the cost is that approving one approves the other.
The alternative costs more. A positional discriminator means an unrelated insertion above a reviewed call silently revokes its justification, so every refactor becomes a re-review - which is the drift the content hash exists to prevent, and a gate people learn to re-approve in bulk is a worse gate. Your scenario needs an author to rebind the name and then paste the call unchanged; the diff shows both edits, and the second is not hidden by the allowlist entry, it is covered by it.
I am accepting that half knowingly, and it is written down at the site.
| # Methods that build a string out of values. `format_map` is `format` with the | ||
| # fields taken from a mapping instead of keyword arguments - same interpolation, | ||
| # same shape, so leaving it out let `exec("import {m}".format_map(cfg))` through. | ||
| _BUILDERS = ("format", "format_map", "join") |
There was a problem hiding this comment.
Detect Template substitutions before dynamic execution
When interpolation uses the standard-library string.Template API, neither substitute nor safe_substitute is recognized as a builder. Consequently, exec(string.Template("import $module").substitute(module=name)) exits this hard security gate successfully even though name is spliced directly into executable syntax; recognize these template-building calls, including normal imported aliases.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in ac25e85. string.Template("import $module").substitute(module = name) splices exactly as .format does, and the receiver is a template object rather than a string, so it went through none of the builder branches.
substitute and safe_substitute are recognised on a written-out Template(...) receiver - qualified through string, through a recorded alias of it, or bare where from string import Template bound it here. An arbitrary object's substitute is still not read.
| if not isinstance(target, ast.Name): | ||
| return |
There was a problem hiding this comment.
Track interpolated values stored in compound targets
When built source is stored in an attribute or subscript before execution, this early return discards the taint completely. For example, self.payload = f"import {name}"; exec(self.payload) and payloads["run"] = f"import {name}"; exec(payloads["run"]) both exit the lint successfully while executing the interpolated source. Track syntactically resolvable attribute and subscript stores through their corresponding loads instead of limiting bindings to plain names.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed, and both spellings report now.
The key is the written-out path, and only a chain of names, attributes and literal indices: that spelling names the same place at the store and at the load, and it cannot run code of its own. A computed index, a call anywhere in the path, or anything else unreadable is still dropped rather than guessed at. Stored under a prefix no identifier can carry, so a path can never collide with a plain name in the same map.
| if node.args else None | ||
| ) | ||
| return _is_interpolated(function.value, resolve, shadowed, resolve_alias) | ||
| if function.attr in _BUILDERS: |
There was a problem hiding this comment.
Preserve builders assigned as bound-method aliases
When a recognized builder is saved as a bound method, the later call no longer has an attribute callee and bypasses this branch. For example, formatter = "import {}".format; exec(formatter(name)) exits with zero findings even though name is inserted into executable syntax; the equivalent direct .format(name) call is detected. Record the bound template and builder when such a method is assigned to a local alias.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. formatter = "import {}".format binds the method, template and all, and by the call site the callee is a bare name so none of the attribute branches saw it.
The receiver is recorded under a builder: alias and the later call is replayed against it, so it reads exactly as the direct spelling does. Only a written-out string or a string.Template(...) receiver, and only the builder method names, so nothing is recorded about an arbitrary object's attribute.
| visit_GeneratorExp = _visit_comprehension | ||
|
|
||
| def visit_Call(self, node: ast.Call): | ||
| sink = _sink_name(node.func, self._alias, self._is_shadowed) |
There was a problem hiding this comment.
Inspect sinks passed to eagerly consumed map calls
When a sink is invoked as a callback rather than as the call's callee, this visitor never associates it with the interpolated argument. For example, list(map(exec, [f"import {name}"])) eagerly calls exec with the f-string but exits the lint with zero findings. Recognize sink callbacks in visibly consumed map calls and inspect the iterable elements they receive.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. A sink handed to map is a callback, and the callee of the call node is map, so nothing associated the two.
Deliberately narrow: a written-out map with a written-out iterable, inside a written-out consumer - list, tuple, set, sorted, sum, any, all and the rest. map on its own is lazy and runs nothing, which is why the consumer is required. The finding is keyed on the map call, so editing what it iterates re-opens the review.
| if node.args else None | ||
| ) | ||
| return _is_interpolated(function.value, resolve, shadowed, resolve_alias) | ||
| if function.attr in _BUILDERS: |
There was a problem hiding this comment.
Exclude visibly custom format methods
When .format belongs to an application-defined object rather than a string, this unconditional attribute-name check invents interpolation that may not exist. For example, a visible class Safe whose format method always returns "pass", followed by exec(Safe().format(name)), fails the hard lint even though name never reaches the executed source. Exclude receivers that are visibly instances of locally defined non-string classes instead of treating every method named format, format_map, or join as a string builder.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed, and it closed an older one with it: temp/r38/b_renderformat.py in my corpus is the same shape and had been carrying this as an accepted false positive since round 38.
A receiver written out as a call to a class this file defines is not a string builder. The class names are collected in the same pre-pass that collects the aliases, and the receiver is still shadow-tested, so a name rebound away from the class falls back to the ordinary reading. Anything unknown is still read as a string method.
The self-prefix exemption now requires a stable expression: the receiver and the
argument are evaluated separately, so f"{next(values)}".removeprefix(the same text)
reads two different strings. Only constants, names and f-strings built from them
count as stable.
A field-free literal template is recognised through a name as well as inline. The
literal-text marker carries the text it stands for now, so the field scan is the
same one and a template WITH a field still reports.
The recognised stdlib aliases are pre-collected for deferred bodies, as the
builtins ones already were, so a function written above from textwrap import
dedent as clean no longer scans before clean means anything.
A whole-object slice normalises a signed bound, so [-0::+1] is the whole string.
A boolean callee enumerates every constructor it can select, which the
conditional form already did.
Corpus of 358 files: no change in findings. Allowlists unchanged at 0, 60 and 40.
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.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dfbd2635aa
ℹ️ 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".
| return _is_interpolated(template, resolve, shadowed, resolve_alias) | ||
| # An unrecognised call shape fell through to the closing `return None` in the | ||
| # original, because a Call is none of the disjoint shapes above it. Spelled out. | ||
| return None |
There was a problem hiding this comment.
Resolve source returned by visible local helpers
When the sink argument is a call to an ordinary visible helper, this fallback discards the helper's return expression. For example, def build(): return f"import {name}"; exec(build()) executes the interpolated source but the lint exits successfully with zero findings; resolve return expressions from visible local functions against their call arguments and closure state, analogous to the immediate-lambda handling above.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b76f8b2 / 45f8bb2 / eb1059b. A call to a def this file states outright, and binds to nothing else, is resolved through its own return expressions with the arguments paired to the parameters exactly as an immediately invoked lambda is. A name the body binds itself resolves to nothing rather than to the caller's value of the same spelling, and a recursion guard stops a self-calling helper. def build(): return f"import {name}"; exec(build()) reports.
| self.global_names.pop() | ||
| self.nonlocal_names.pop() | ||
| self.future_taint.pop() | ||
| self.tainted.pop() |
There was a problem hiding this comment.
Preserve class attribute taint after the class body
Popping the class body's taint map discards assignments that remain accessible through the resulting class object. For example, class C: payload = f"import {name}" followed by exec(C.payload) executes the interpolated source, but the lint exits successfully with zero findings; export visible class-local bindings to qualified compound paths such as C.payload before discarding this scope.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. A class body's bindings are exported to the compound paths the attribute access spells before the scope is popped, so class C: payload = f"import {name}" followed by exec(C.payload) reports. Rebinding C takes them away through the root-rebinding cleanup every other path already gets.
| if ( | ||
| isinstance(iterable, ast.Call) | ||
| and isinstance(iterable.func, ast.Name) | ||
| and iterable.func.id in ("iter", "tuple", "list", "set", "frozenset") |
There was a problem hiding this comment.
Unwrap enumerate when binding loop targets
When a visible literal is wrapped in the builtin enumerate, _literal_elements treats the iterable as opaque and clears the loop target. Thus for _, payload in enumerate([f"import {name}"]): exec(payload) necessarily executes the interpolated source while the lint reports zero findings; model an unshadowed enumerate over supported literal containers as yielding visible index/value pairs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. An unshadowed enumerate over a written-out container yields visible (index, element) pairs, so the ordinary unpacking machinery binds the element and for _, payload in enumerate([f"import {name}"]) reports.
| # calls the builtin and only then rebinds it. Pre-shadowing there | ||
| # hid the call entirely. Inside a function the compiler really does | ||
| # make the name local for the whole body, which is why this pass | ||
|
|
There was a problem hiding this comment.
Distinguish identical call sites in one scope
This key still collides for byte-identical calls within the same qualified scope, so one justification silently approves every copy. For example, after allowlisting one exec(f"import {x}") in f, adding an identical call later in f after x = input() produces two findings with the same key and the lint exits successfully; include a stable call-site identity in the key or reject duplicate finding keys so each newly added sink requires review.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Taken, by your second suggestion rather than the first. The key still hashes the call's own source - a line number or an ordinal in it churns every entry whenever anything above moves, which is how an allowlist stops being read - but the entry now records HOW MANY findings share that key, and the scan compares it. Adding a third copy of an approved call changes the count and the call is unreviewed until someone signs off the new number.
It also made the existing collisions visible, which is worth having on the record: the zoo allowlist's 60 entries were 49 distinct keys, one of them covering nine identical eval calls in unsloth_compile_transformers; unsloth's 40 were 38. Regenerated with every hand-written reason preserved, and both trees are green.
| # `report.py` and the rest under `.github/scripts` - so they are maintained | ||
| # executable source like anything else here, and an interpolated `exec` added to | ||
| # one of them was passing this gate unreviewed. | ||
| ".github/scripts", |
There was a problem hiding this comment.
Scan inline Python in workflow run blocks
The default invocation in lint-ci.yml includes .github/scripts but none of the workflow files, even though this repository contains many executable python <<'PY' blocks under .github/workflows. If a PR adds exec(f"...") inside one of those inline programs, it runs on the CI or release runner while both new dynamic-execution lint steps remain green; extract these programs into scanned .py files or scan Python heredocs and commands embedded in workflows.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed, and thank you for this one - it was a real hole. .github/workflows is now a scan target and a python - <<'PY' heredoc in a run: step is scanned as its own module, with findings pointing at the line in the workflow file. Only a heredoc whose introducing line names python, so a cat <<EOF data block is left alone; a block that will not parse is counted like a notebook cell rather than failing the file, since these are frequently templated.
Measured before landing it: 74 Python heredocs across the three repos, all of them parse, none of them contains a sink, so no allowlist entry was needed and the counts did not move. A planted exec(f"import {name}") in one is reported, and that is a test.
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.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 45f8bb2266
ℹ️ 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".
| return None | ||
| if function.id in _REBOUND_FUNCTION_NAMES: | ||
| return None | ||
| return _LOCAL_FUNCTIONS.get(function.id) |
There was a problem hiding this comment.
Exclude decorated definitions from visible helpers
A decorated def does not bind its original function object, but this returns the undecorated AST as the callee. For example, a decorator that replaces build with lambda name: f"import {name}", applied to an original build that returns "pass", makes exec(build(input())) execute interpolated source while the lint reports zero findings because it analyzes only the original fixed return. Treat decorated definitions as opaque unless the decorator's result is explicitly resolved.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6ce8f3b / c634f64 / 3ad1875, with a line drawn rather than a blanket exclusion. A decorated def no longer answers as a visible helper unless every decorator is one documented to hand the wrapped result back - cache, lru_cache, wraps, staticmethod, classmethod and friends. Your swapping decorator therefore reads as unknown, and @functools.cache def build(): return f"import {value}" is still read, which a blanket exclusion would have lost. Both are fixtures.
The residual: what a decorator RETURNS is not resolved, so a decorator that returns an interpolating function is a miss rather than a finding. Chasing that is general value flow, which this tool does not do.
| if element_reason is None or isinstance(element_reason, _LiteralText): | ||
| continue |
There was a problem hiding this comment.
Record nested literal-container elements
When an assigned container contains another literal container, the immediate item has no interpolation reason, so this continue drops all addressable descendants. Thus payloads = {"run": [f"import {name}"]}; exec(payloads["run"][0]) executes the f-string while the hard gate reports zero findings. Recursively record constant-addressable nested list, tuple, and mapping elements rather than stopping at the first container-valued item.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The element binding recurses, so payloads = {"run": [f"import {name}"]} records payloads['run'][0] and the sink reports.
| statement, (ast.For, ast.AsyncFor, ast.With, ast.AsyncWith, ast.Try, _MATCH) | ||
| ): | ||
|
|
There was a problem hiding this comment.
Fail closed on templated workflow heredocs
A Python heredoc containing an unquoted Actions expression is invalid before workflow interpolation but valid on the runner, yet this path merely skips it and still exits successfully. For example, name = ${{ toJSON(inputs.module) }} followed by exec(f"import {name}") is rendered into valid Python before execution, while the scanner records one skipped block and reports zero findings. Templated heredocs must be normalized or treated as unscannable failures rather than silently excluded.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed, by normalising rather than failing. An Actions expression inside a heredoc becomes a name, so the block parses and is scanned: name = ${{ toJSON(inputs.module) }} followed by exec(f"import {name}") reports, and no block is recorded as skipped. That is the same answer the notebook reader gives an unrecognised magic, and it is the right one here - what the runner substitutes is exactly the untrusted value this gate is about.
| self._visit_suite(node.body) | ||
| self._visit_suite(node.orelse) |
There was a problem hiding this comment.
Preserve possible taint from both if branches
For an undecidable condition, visiting the suites sequentially lets assignments in the else overwrite the state produced by the if, although either state can reach following statements. For example, if flag: payload = f"import {name}"; else: payload = "pass" followed by exec(payload) executes interpolated source when flag is true, but the clean assignment visited last clears the taint and the lint reports zero findings. Analyze each branch from the same incoming state and merge their possible bindings afterward.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining, for the sixth time on this PR family and with the reasoning unchanged: no control-flow state merging. Both branches of an undecidable if, try/except handler state, zero-iteration loops and unions of sink aliases have all been asked for, and each one turns a sequential walk over written-out code into a fixed-point analysis. The module docstring says what this is: a best-effort heuristic for one bug class, not sound taint analysis. The cost lands on ordinary code as findings about reachability rather than about splices, and the allowlist is read by people.
Your example is a real miss and I am accepting it as the cost of the shape.
| and _keeps_everything(node.slice.step, 1) | ||
| ): | ||
| return _is_interpolated(node.value, resolve, shadowed, resolve_alias) | ||
| return None |
There was a problem hiding this comment.
Analyze constant slices that retain interpolation
Every partial slice is discarded here even when its constant bounds provably remove only a literal prefix or suffix. Both exec(f"import {name}#"[:-1]) and exec(f"Ximport {name}"[1:]) execute the interpolated source while the lint reports zero findings. For constant slices of a visible joined string, retain the finding whenever the selected range overlaps an interpolated value rather than requiring the slice to preserve the entire object.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. A constant slice of a written-out f-string is read when the cut stays inside the receiver's own literal run: f"import {name}#"[:-1] and f"Ximport {name}"[1:] both report. A cut that may reach into the spliced value - f"import {name}"[:3] - still says nothing, and that is a fixture too.
| if self.scope_kinds[-1] == "function" and isinstance( | ||
| statement, (ast.For, ast.AsyncFor, ast.With, ast.AsyncWith, ast.Try, _MATCH) | ||
| ): | ||
|
|
There was a problem hiding this comment.
Handle list.sort key callbacks
The key-callback analysis only accepts bare sorted, min, and max calls, so the equivalent in-place list method is skipped. For example, [f"import {name}"].sort(key=exec) necessarily invokes exec on the interpolated element, yet the lint reports zero findings. Recognize sort(key=...) on a visibly built-in list receiver and feed its visible elements through the same key-sink reporting path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. [...].sort(key = ...) on a written-out list feeds the same key-callback path sorted does, and computes the key for every element.
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.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 410cb105e1
ℹ️ 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".
| for statement in node.body: | ||
| self.visit(statement) |
There was a problem hiding this comment.
Preserve taint when an opaque for-loop may be empty
When the iterable is opaque and happens to be empty, none of these body mutations occur, but they are still applied permanently to the analysis state. For example, payload = f"import {name}"; for _ in items: payload = "pass"; exec(payload) executes the interpolated source when items is empty, while the lint reports zero findings. Merge the pre-loop state with the body-executed state for possibly empty iterables instead of restoring only the loop target.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is a control-flow state merge, and it is out of scope here for the same reason the earlier six proposals of it were. This checker is a documented best-effort heuristic over written-out code, not a sound dataflow analysis: it has one taint map per scope and no join operator, and adding one for a single statement kind buys a partial answer while implying a soundness the rest of the file does not have. The example is real, and a merge would catch it. So would a merge for match, with, else on a loop, finally, a comprehension guard, an early return and every other place two paths meet, and stopping short of those is exactly the half-done analysis the current single-map design avoids claiming. The line I have held all along is that a mechanism has to be specific, decidable and bounded by what is written out; a taint join is none of those. Every other item in this round is fixed.
| if decided is None: | ||
| self._visit_suite(node.body) | ||
| self._visit_suite(node.orelse) |
There was a problem hiding this comment.
Preserve taint when an undecidable while-loop runs zero times
When the condition is undecidable and false on entry, the body never runs, but visiting it here still commits its assignments to the following state. For example, payload = f"import {name}"; while flag: payload = "pass"; exec(payload) executes the interpolated source when flag is false, yet the lint reports zero findings. Merge the zero-iteration state with the state produced by the body.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is a control-flow state merge, and it is out of scope here for the same reason the earlier six proposals of it were. This checker is a documented best-effort heuristic over written-out code, not a sound dataflow analysis: it has one taint map per scope and no join operator, and adding one for a single statement kind buys a partial answer while implying a soundness the rest of the file does not have. The example is real, and a merge would catch it. So would a merge for match, with, else on a loop, finally, a comprehension guard, an early return and every other place two paths meet, and stopping short of those is exactly the half-done analysis the current single-map design avoids claiming. The line I have held all along is that a mechanism has to be specific, decidable and bounded by what is written out; a taint join is none of those. Every other item in this round is fixed.
| for statement in node.body: | ||
| self.visit(statement) |
There was a problem hiding this comment.
Keep normal try-path taint when visiting exception handlers
When the try suite completes normally, an exception handler's assignments never occur, but the generic Try traversal subsequently applies them through this handler visitor. For example, try: payload = f"import {name}"; except Exception: payload = "pass" followed by exec(payload) executes the interpolated source for an ordinary string name, while the lint reports zero findings. Analyze the normal path and each handler from appropriate incoming states and merge their possible outcomes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is a control-flow state merge, and it is out of scope here for the same reason the earlier six proposals of it were. This checker is a documented best-effort heuristic over written-out code, not a sound dataflow analysis: it has one taint map per scope and no join operator, and adding one for a single statement kind buys a partial answer while implying a soundness the rest of the file does not have. The example is real, and a merge would catch it. So would a merge for match, with, else on a loop, finally, a comprehension guard, an early return and every other place two paths meet, and stopping short of those is exactly the half-done analysis the current single-map design avoids claiming. The line I have held all along is that a mechanism has to be specific, decidable and bounded by what is written out; a taint join is none of those. Every other item in this round is fixed.
| if not isinstance(node, ast.BinOp) or not isinstance(node.op, ast.Add): | ||
| return node |
There was a problem hiding this comment.
Fold constant f-strings when resolving getattr sinks
When the attribute passed to getattr is a constant-only f-string, it deterministically names the builtin but this folder returns the JoinedStr unchanged. For example, getattr(builtins, f"{'exec'}")(f"import {name}") invokes exec with interpolated source while the lint reports zero findings. Fold f-strings whose formatted values are all statically constant before checking the sink name.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. _folded_text now folds a JoinedStr whose replacements are all string constants, so getattr(builtins, f"{'exec'}") reads the same name CPython does. Only a plain replacement counts, with no conversion and no format spec, so the folded value is the one CPython produces rather than a guess. Fixture: 'a constant f-string names the same builtin'.
| and len(node.args) == 1 | ||
| and not node.keywords |
There was a problem hiding this comment.
Honor next's default for a visibly nonempty iterator
When next is given a default, this one-argument restriction skips the call even though the default is irrelevant for a visibly nonempty literal iterator. For example, exec(next(iter([f"import {name}"]), "pass")) necessarily selects and executes the f-string, but the lint reports zero findings. Accept the valid two-argument next(iterator, default) form and continue selecting the visible first element when it exists.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, the default is unreachable past a written-out element. The selection moved into _first_from_iterator, which now accepts next(iterator, default) and is shared with the callee side. Fixture: 'a default cannot be reached past a written-out element'.
| # `from textwrap import dedent as clean` was scanned before `clean` | ||
| # meant anything and reported nothing at all. Same for the direct | ||
| # helpers and `functools.partial`. | ||
| for alias in st |
There was a problem hiding this comment.
Revoke approvals when an upstream source expression changes
When an allowlisted sink receives source through a name, changing the assignment while retaining the same builder shape leaves both the call hash and kind unchanged. For example, changing payload = f"import safe.{name}" to payload = f"import {name}" above an unchanged exec(payload) preserves the key and the reason f-string via payload, so the old justification still makes the gate pass despite the security-sensitive payload change. Include the normalized originating expression in the reviewed identity rather than comparing only its broad reason.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This one already landed, in the commit under review. Findings now carry an origin field, the sha256 of the unparsed expression that built the source, and the gate compares it alongside kind and count. Measured on your example: payload = f"import safe.{name}" gives origin d1c3ae48 and payload = f"import {name}" gives ca3ac34a, so the entry goes unreviewed exactly as you describe.
| # `from textwrap import dedent as clean` was scanned before `clean` | ||
| # meant anything and reported nothing at all. Same for the direct | ||
| # helpers and `functools.partial`. | ||
| for alias in st |
There was a problem hiding this comment.
Scan Python heredocs embedded in maintained shell scripts
When Python is embedded in a committed shell script, these collection patterns omit the entire host file, so a new exec(f"...") in that program leaves the hard gate green. This is an active repository pattern: studio/setup.sh:776 and scripts/install_rocm_wsl_strixhalo.sh:324 both launch Python heredocs under directories in DEFAULT_TARGETS. Collect maintained .sh files and scan their Python heredocs just as workflow run: blocks are scanned.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Real hole, and both files you name are in scope. .sh now joins .yml/.yaml in scan_file and in the directory sweep, read through the same heredoc and python -c patterns; a shell script is all shell, so no run: block has to be lifted out first. Measured across the three repos: 31 shell files in unsloth, 4 Python blocks (studio/setup.sh, scripts/install_rocm_wsl_strixhalo.sh, .github/scripts/agent-guides-drive.sh, .github/scripts/lane-lockfile-audit.sh), all parsed, none skipped, no findings, so the allowlist is unchanged. Four tests, including one that reaches the file through a directory target rather than an explicit path.
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.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c634f642ad
ℹ️ 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".
| return | ||
| # Any OTHER binding of that name takes the exemption away, permanently and | ||
| # file-wide. `class Safe: ...` followed by `Safe = lambda: "import {}"` leaves | ||
| # `Safe()` a plain string builder, and reading the class definition thro |
There was a problem hiding this comment.
Parse multiline workflow python -c commands
This extractor passes each physical line to _script_command_source, so a quoted python -c program spanning multiple lines is never parsed. This is an active workflow pattern in .github/workflows/mlx-ci.yml:277-284 and :290-...; adding exec(f"import {name}") to one of those programs runs it on the CI runner while this gate reports zero findings. Accumulate the complete shell command or YAML run block before extracting the -c argument.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. Lines are now joined until the quoting balances, which is exactly when the shell considers the command finished, and the block indentation is stripped before the program is parsed. The -c extraction moved into _dash_c_program so the cell reader and the workflow reader share one implementation. mlx-ci.yml parses clean under it; a test covers the shape.
| self.collected_aliases.pop() | ||
| self.sink_aliases.pop() | ||
| self.shadowed_sinks.pop() |
There was a problem hiding this comment.
Export sink aliases from class bodies
Fresh evidence in the current revision is that class exit exports taint but pops the class alias maps outright. Consequently, class C: run = exec followed by C.run(f"import {name}") executes the interpolated source, while the lint reports zero findings. Export class-local sink and constructor aliases under qualified paths such as C.run before discarding these maps.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This landed in the previous push. A class scope exports its sink aliases under path>Class.attribute, into the deferred alias map as well as the executed one, and class C: run = exec followed by C.run(f"import {name}") reports one finding as written. Your follow-up about reaching the same attribute through an INSTANCE was a real remaining gap and is fixed now too.
| isinstance(function, ast.Attribute) | ||
| and function.attr == "pop" | ||
| and isinstance(function.value, (ast.List, ast.Tuple)) | ||
| and function.value.elts | ||
| and not any(isinstance(element, ast.Starred) for element in function.value.elts) |
There was a problem hiding this comment.
Resolve pop calls on bound literal containers
Fresh evidence in this revision is that the new pop handling only accepts an inline ast.List or ast.Tuple receiver. With payloads = [f"import {name}"]; exec(payloads.pop()), the assignment records the element under payloads[0], but the named receiver falls through here and the lint reports zero findings even though pop() deterministically returns and executes that f-string. Resolve no-argument and constant-index pop calls through the recorded container elements as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. A bound container now records each element under its negative index as well as its forward one, so pop() with nothing named reads the last element and pop(k) reads the one it names, through the same subscript rewrite the get spelling uses.
| return | ||
| # Any OTHER binding of that name takes the exemption away, permanently and | ||
| # file-wide. `class Safe: ...` followed by `Safe = lambda: "import {}"` leaves | ||
| # `Safe()` a plain string builder, and reading the class definition thro |
There was a problem hiding this comment.
Propagate built arguments into visible sink wrappers
Fresh evidence in the current revision is that visible helpers are analyzed when they return source, but calls into helpers that forward a parameter to a sink are not. For def run(source): exec(source) followed by run(f"import {name}"), the function body sees an untainted parameter and the outer call is not itself recognized as a sink, so the lint reports zero findings although the f-string is executed. Bind visible call arguments to helper parameters and inspect reachable sink calls in that helper scope.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed, and it found a real one. A call into a visible local def whose body hands a parameter to a sink now reports what the CALLER built. Only arguments the call supplies - a default is already read where the definition is written, and counting it reported the same execution twice. On the live tree this adds one finding, unsloth_zoo/compiler.py:5566, where model_location reaches the eval inside create_new_function; it is now in the allowlist with the [a-z0-9_]+ validation as its justification.
| reason = _is_interpolated(child.value) | ||
| if reason is None or isinstance(reason, _LiteralText): | ||
| continue |
There was a problem hiding this comment.
Resolve aliases in deferred closure taint
The future-taint prepass resolves assignment values against no bindings, so an alias created after a nested function definition is omitted. For payload = f"import {name}"; def inner(): exec(alias); alias = payload; inner(), the deferred function reads the interpolated value at runtime, but _later_taint does not associate alias with it and the lint reports zero findings. Resolve these written-out assignments transitively against the prepass's discovered taint.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The prepass now resolves each assignment against the taint it has found so far and repeats until nothing new appears, so an alias bound after a nested def carries the built string into it. Bounded at eight rounds, since each round can only add names.
…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.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ff2bf3d2d9
ℹ️ 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 _slice_keeps_interpolation(node.value, node.slice): | ||
| return _is_interpolated(node.value, resolve, shadowed, resolve_alias) | ||
| return None | ||
| return _literal_element(node, resolve, shadowed, resolve_alias) |
There was a problem hiding this comment.
Resolve constant selections from visible comprehensions
When a comprehension has a visibly nonempty literal iterable and no rejecting filters, a constant selection can deterministically return interpolated source, but this lookup only resolves literal containers. For example, exec([f"import {name}" for _ in [0]][0]) executes the f-string while the lint reports no findings, allowing this dynamic-execution pattern to pass the hard gate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. A comprehension with one generator, a visibly nonempty iterable and no filters produces its element, and the element is the same expression whichever index is taken - so an index this cannot read changes nothing, and what has to be certain is only that at least one element exists. Shared by _literal_selection and _literal_element, so the callee side reads it too.
| if isinstance(function, ast.Attribute): | ||
| literal_mapping = ( | ||
| _mapping_literal(function.value, shadowed) | ||
| if function.attr in ("get", "pop") else None |
There was a problem hiding this comment.
Handle setdefault on visible mappings
When setdefault is called with a visibly absent key, it returns its default argument, but the mapping accessor analysis is limited to get and pop. Consequently, exec({}.setdefault("x", f"import {name}")) necessarily executes the interpolated string while the lint reports zero findings, providing another direct bypass of the new gate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. setdefault on a written-out mapping now reads like get: a key the mapping already holds gives the stored value, an absent one gives the default it stores and hands back. An uncertain lookup merges both, as the get branch does.
| length is left alone rather than guessed at. | ||
| """ | ||
| for element, item in self._unpacked_pairs(target, value): | ||
| # Resolved against the taint map, as the whole-statemen |
There was a problem hiding this comment.
Record values written by visible dict.update calls
When a mapping is populated through a visible dict.update call, this visitor traverses the arguments but never updates the recorded compound paths. Thus payloads = {}; payloads.update(run=f"import {name}"); exec(payloads["run"]) executes the interpolated source while the lint exits successfully with zero findings; model visible keyword and literal-mapping updates as writes to the corresponding stored keys.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. A visible X.update(...) now writes the compound element paths: plain keywords and literal-mapping arguments, under the same path>X['k'] key the binding pass uses, so the ordinary subscript reads them. A ** of anything unreadable leaves the whole call alone rather than recording half of it.
| partial = _partial_call(node, aliases, shadowed) | ||
| if partial is None: | ||
| return None | ||
| return _sink_name(partial.args[0], aliases, shadowed) |
There was a problem hiding this comment.
Expand visible starred operands in partial
When every functools.partial operand is supplied by one visible starred tuple or list, partial.args[0] is an ast.Starred node rather than the bound callable, so sink resolution fails. For example, partial(*(exec, f"import {name}"))() is valid, invokes exec with the interpolated source, and produces zero lint findings; expand readable starred operands before selecting the partial's callable and bound arguments.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. A written-out starred tuple or list is expanded before the partial's callee and bound arguments are read, so partial(*(exec, f"import {name}"))() resolves. An opaque expansion says nothing about what it supplies and the call is handed back untouched.
| return _interpolated_binop(node, resolve, shadowed, resolve_alias) | ||
| if isinstance(node, ast.Call): | ||
| return _interpolated_call(node, resolve, shadowed, resolve_alias) | ||
| return None |
There was a problem hiding this comment.
Unwrap awaited visible helper results
When an async helper visibly returns built source, awaiting its call produces that source before the sink runs, but an ast.Await argument falls through this resolver without examining its value. For example, async def build(name): return f"import {name}" followed inside another async function by exec(await build(name)) executes the interpolated string while the lint reports zero findings; unwrap await before applying the visible-helper return analysis.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. await is unwrapped alongside the walrus at the top of the resolver, and on the callee side too, so exec(await build(name)) reads the coroutine's returned expression through the existing visible-helper analysis.
| if _names_module_function( | ||
| function, "codeop", "compile_command", shadowed, resolve_alias, | ||
| ): |
There was a problem hiding this comment.
Preserve source through copy.copy
When the visibly imported stdlib copy.copy receives an exact built-in string, it returns that immutable string unchanged, but this source-preserving helper is not recognized. Consequently, exec(copy.copy(f"import {name}")) executes the interpolated source while the hard lint reports zero findings; resolve copy.copy and its direct-import aliases in the same guarded way as the other known stdlib pass-through helpers.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The pass-through table is keyed by module now - textwrap for dedent/indent, copy for copy/deepcopy - so the attribute spelling, a module alias and a direct import all resolve, and copy joins the module receivers so a local binding of that name stops the unwrapping the way a local str does.
…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.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8ea934d15e
ℹ️ 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".
| for item in node.items: | ||
| self.visit(item.context_expr) | ||
|
|
There was a problem hiding this comment.
Bind approvals to every contributing source origin
When a sink argument references multiple bound source pieces, this returns after the first recorded origin. Fresh evidence beyond the earlier single-origin fix is that changing only b from b = f".{name}" to b = f"; __import__({name})" above an unchanged exec(a + b) leaves the path, qualname, hash, kind, and origin identical, so the existing justification still approves the security-sensitive change. Collect and compare the digests of every referenced source binding rather than only the first one visited.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. A finding now records the digests of EVERY binding its source reads, sorted and joined, so exec(a + b) is bound to both. Measured on your example: b = f".{name}" gives origin 62d946c2+ca3ac34a and b = f"; __import__({name})" gives 47415b96+ca3ac34a. Four live allowlist entries picked up a second digest; their justifications are unchanged and were re-confirmed by hand.
| # An unrecognised call shape fell through to the closing `return None` in the | ||
| # original, because a Call is none of the disjoint shapes above it. Spelled out. | ||
| return None |
There was a problem hiding this comment.
Resolve singleton extrema before dropping call taint
When an unshadowed min or max receives a visibly nonempty singleton container, its return value is necessarily that element, but this fallback discards the call result. For example, exec(min([f"import {name}"])) executes the interpolated source while the new hard gate reports zero findings; unwrap these deterministic singleton selections before returning None.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. An unshadowed min or max over a written-out container holding exactly ONE element hands that element back whichever way it compares. Two elements is a comparison of the values, so that stays unread.
| """ | ||
| for item in node.items: | ||
| self.visit(item.context_expr) | ||
|
|
There was a problem hiding this comment.
Initialize deferred taint for each extracted runner program
Extracted workflow and shell programs create a fresh visitor but never populate its module-level future_taint, unlike scan_file and the notebook scanner. Fresh evidence beyond the earlier closure-prepass fix is that a heredoc containing def inner(): exec(payload) followed by payload = f"import {name}"; inner() reports zero findings, although the identical .py module is caught. Run _later_taint(tree.body) before visiting each heredoc or python -c program so deferred closures see assignments that execute before they are called.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Real gap, and it was there before the per-block visitors too. _later_taint now runs for each extracted program, so a heredoc that defines a closure above the assignment it reads reports what the identical .py module reports. Test in the workflow group.
| The context expression is visited first, since it is evaluated first. | ||
| """ | ||
| for item in node.items: | ||
| self.visit(item.context_expr) | ||
|
|
There was a problem hiding this comment.
Scan Python programs embedded in PowerShell launchers
The embedded-program collector only accepts .sh, so maintained PowerShell launchers under the default target trees are omitted. Fresh evidence beyond the added shell-script coverage is install.ps1:1758, which defines a literal Python trampoline that is executed with -c at install.ps1:1823 and is mirrored in scripts/uninstall.ps1 and studio/setup.ps1; adding exec(f"...") to any of those shipped programs leaves the default hard gate green. Include maintained .ps1 files and extract their literal Python -c payloads.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Added. .ps1 joins .sh in the sweep, with a reader for the shape the installers actually use: a literal assignment or a here-string bound to a variable, and a -c that names it. Measured on install.ps1, which yields 14 candidate payloads including the trampoline at 1758; the ones that are not Python are counted as unparsed rather than failing the file, which is how the workflow reader already behaves. No findings, so the allowlist is unchanged.
| """ | ||
| for item in node.items: | ||
| self.visit(item.context_expr) | ||
|
|
There was a problem hiding this comment.
Reset justifications when reviewed identity changes
When --update is run after an upstream source change, this unconditionally copies the old justification whenever the call key is unchanged, even if the finding's origin, kind, or duplicate count changed. For example, changing payload = f"import safe.{name}" to payload = f"import {name}" makes the normal gate fail on a new origin, but the instructed --update immediately writes that new origin alongside the old “safe prefix” reason and the next run passes without requiring review. Reuse the previous reason only when every reviewed identity field still matches; otherwise seed REVIEW ME.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed, and this one bit immediately: --update now reseeds REVIEW ME unless the kind, count and origin all still match, and the four entries whose origins changed in this same round came back as REVIEW ME. I re-read each justification against its call and restored it deliberately rather than letting the tool carry it over.
…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.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 825daec073
ℹ️ 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".
| "cli.py", | ||
| "unsloth-cli.py", |
There was a problem hiding this comment.
Scan the shipped root installer by default
DEFAULT_TARGETS omits the maintained root install.sh, even though that shipped installer contains embedded Python commands (for example at install.sh:2908 and install.sh:5713). Consequently, adding exec(f"...") to one of those programs is reported when install.sh is passed explicitly but remains invisible to the default CI invocation; include the root installer among the default targets.
Useful? React with 👍 / 👎.
| if level != len(self.scope_kinds) - 1: | ||
| # `global exec; del exec` deletes the MODULE binding, so the shadow an | ||
| # earlier `exec = print` |
There was a problem hiding this comment.
Extract Python commands inside shell substitutions
Fresh evidence beyond the multiline python -c fix is that commands embedded in shell substitutions are still skipped: x=$(python -c 'exec(f"import {name}")') exits clean because _runs_python_command sees x=$(python rather than the interpreter. This is an active pattern in inspected targets such as studio/setup.sh:1799, scripts/install_qwen3_6_mlx.sh:99, and numerous workflow files, so an interpolated sink added to any of those -c programs bypasses the hard gate; extract nested command substitutions before applying the interpreter check.
Useful? React with 👍 / 👎.
| table[-1].pop(f"stdlibfunc:{target.id}", None) | ||
| level = self._binding_level(target.id) | ||
| if level != len(self.scope_kinds) - 1: | ||
| # `global exec; del exec` deletes the MODULE binding, so the shadow an | ||
| # earlier `exec = print` |
There was a problem hiding this comment.
Taint direct Actions-expression sink arguments
Fresh evidence beyond the earlier templated-heredoc fix is exec(${{ toJSON(inputs.source) }}): normalization turns the argument into the bare name _actions_expression, but _is_interpolated recognizes that marker only when it occurs inside a string constant, so this workflow reports zero findings even though the runner substitutes the input as executable Python source. Treat the substitution marker itself as tainted, not only constants containing it.
Useful? React with 👍 / 👎.
| level = self._binding_level(target.id) | ||
| if level != len(self.scope_kinds) - 1: | ||
| # `global exec; del exec` deletes the MODULE binding, so the shadow an | ||
| # earlier `exec = print` |
There was a problem hiding this comment.
Normalize shell expansion in unquoted Python heredocs
Fresh evidence beyond Actions-expression normalization is that POSIX shell interpolation is left untouched: an unquoted heredoc containing exec("${PAYLOAD}") is scanned as a fixed Python string and exits clean, while the shell expands PAYLOAD before Python parses and executes it. The heredoc regex already records whether the delimiter was quoted, so for unquoted delimiters the extractor needs to mark shell parameter and command substitutions as built source.
Useful? React with 👍 / 👎.
| if level != len(self.scope_kinds) - 1: | ||
| # `global exec; del exec` deletes the MODULE binding, so the shadow an | ||
| # earlier `exec = print` |
There was a problem hiding this comment.
Inspect immediately invoked lambda sink wrappers
Fresh evidence beyond the visible-def wrapper fix is that (lambda source: exec(source))(f"import {name}") still produces zero findings: the lambda body sees an untainted parameter, while _wrapper_sink_calls accepts only helpers returned by _visible_helper. An immediately invoked lambda has fully visible argument bindings just like the supported def run(source): exec(source) case, so inspect its sink calls with the existing lambda parameter resolver.
Useful? React with 👍 / 👎.
| table[-1].pop(f"stdlibfunc:{target.id}", None) | ||
| level = self._binding_level(target.id) | ||
| if level != len(self.scope_kinds) - 1: | ||
| # `global exec; del exec` deletes the MODULE binding, so the shadow an | ||
| # earlier `exec = print` |
There was a problem hiding this comment.
Bind approvals to the sink's control context
The reviewed identity hashes the call text but none of its surrounding control context. For example, after approving if name in SAFE: exec(payload), moving the unchanged call below the guard preserves its path, qualname, hash, kind, count, and source origin, so the old justification still passes even though arbitrary names now reach execution. Include a stable digest of the enclosing guards or otherwise force re-review when an allowlisted sink moves across control-flow boundaries.
Useful? React with 👍 / 👎.
| value is taken, whether it is going to be executed or is going to do the executing. | ||
| """ | ||
| container, index = node.value, node.slice | ||
| if isinstance(container, (ast.ListComp, ast.SetComp)): |
There was a problem hiding this comment.
Validate comprehension subscriptions before reporting
This treats every ListComp or SetComp over a visibly nonempty iterable as yielding the selected element without validating the subscription. Thus both {f"import {name}" for _ in [0]}[0] (sets are not subscriptable) and [f"import {name}" for _ in [0]][99] (the index is out of range) are reported even though Python raises before the sink runs, forcing impossible calls into the allowlist. Restrict this to subscriptable comprehensions and prove the constant index is in range.
Useful? React with 👍 / 👎.
| if level != len(self.scope_kinds) - 1: | ||
| # `global exec; del exec` deletes the MODULE binding, so the shadow an | ||
| # earlier `exec = print` |
There was a problem hiding this comment.
Match Python only in shell command positions
Fresh evidence beyond filtering redirection destinations is that the token walk still treats ordinary arguments as interpreters. A valid script containing echo python <<'PY' and a body with exec(f"import {name}") merely prints python and discards the heredoc, but the scanner reports the body because it matches the argument token python. Track command positions after separators and wrappers rather than accepting every non-redirection token, or harmless data heredocs can block CI.
Useful? React with 👍 / 👎.
| level = self._binding_level(target.id) | ||
| if level != len(self.scope_kinds) - 1: | ||
| # `global exec; del exec` deletes the MODULE binding, so the shadow an | ||
| # earlier `exec = print` |
There was a problem hiding this comment.
Scan generated Python files that workflows execute
The heredoc collector discards a cat > file.py <<'PY' body even when a later command executes that generated file. This is an active workflow pattern in .github/workflows/consolidated-tests-ci.yml, where multiple shims are written under tests/ and then run with pytest; adding exec(f"...") to one of those bodies leaves the default gate green because the committed workflow body is skipped and the generated test file does not exist during lint. Track file-writing heredocs that are subsequently passed to Python or pytest, or conservatively scan Python-suffixed generated files.
Useful? React with 👍 / 👎.
| table[-1].pop(f"stdlibfunc:{target.id}", None) | ||
| level = self._binding_level(target.id) | ||
| if level != len(self.scope_kinds) - 1: | ||
| # `global exec; del exec` deletes the MODULE binding, so the shadow an | ||
| # earlier `exec = print` |
There was a problem hiding this comment.
Scan Python launched from notebook shell cells
A %%bash notebook cell is classified as foreign and skipped wholesale, even when its shell body launches Python. For example, a cell containing %%bash, followed by python - <<'PY' and exec(f"import {name}"), executes the interpolated source but produces zero findings. Pass Bash and shell cell bodies through the same heredoc and python -c extractor used for maintained shell scripts rather than dropping the entire cell.
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.
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 31adf57d7f
ℹ️ 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 literal test decides the suite, as `visit_If` already does for `if`. | ||
|
|
||
| `while False: run = print` never runs, so recording that shadow suppressed a | ||
| call to the builtin that really does happen. Its `else` r |
There was a problem hiding this comment.
Track values inserted by visible list mutations
When a visible list is populated after assignment, this call-side binding handles only update, so payloads = []; payloads.append(f"import {name}"); exec(payloads[0]) exits successfully with zero findings even though the interpolated string is necessarily executed. Record elements written by deterministic append/insert/extend calls (at least for visibly known list state) so the later compound-path lookup remains tainted.
Useful? React with 👍 / 👎.
| if not _visible_length(generator.iter): | ||
| return None | ||
| return container.elt | ||
| if isinstance(container, (ast.Tuple, ast.List)): |
There was a problem hiding this comment.
Unwrap visible sequence constructors before selection
When a literal sequence is passed through an unshadowed list or tuple constructor, a constant subscript still deterministically selects its element, but this branch only accepts raw AST displays. For example, exec(list((f"import {name}",))[0]) is valid and executes the f-string, while the lint reports zero findings; unwrap visible sequence constructors before applying the existing literal-selection logic.
Useful? React with 👍 / 👎.
| """A literal test decides the suite, as `visit_If` already does for `if`. | ||
|
|
||
| `while False: run = print` never runs, so recording that shadow suppressed a | ||
| call to the builtin that really does happen. Its `else` r |
There was a problem hiding this comment.
Resolve literal shell variables passed to Python -c
When a maintained shell script stores Python source in a literal variable and invokes python -c "$variable", this passes the variable reference to the parser instead of resolving its assignment, so program='name=input(); exec(f"import {name}")'; python -c "$program" exits successfully with zero findings. This is an active shape in the inspected default target studio/setup.sh:2203-2206 (_setup_xpu_probe), and local python --help confirms that -c cmd runs the supplied string; resolve visible literal shell assignments before parsing the -c payload.
Useful? React with 👍 / 👎.
| self._visit_suite(node.body) | ||
| self._visit_suite(node.orelse) |
There was a problem hiding this comment.
Preserve taint across undecidable branches
When an if condition cannot be decided statically, visiting its suites sequentially lets a conditional clean assignment erase a value that remains tainted on the path where the suite is skipped. For example, payload = f"import {name}"; if safe: payload = "pass"; exec(payload) executes the f-string when safe is false, but the lint exits successfully with zero findings. Merge branch states conservatively so taint surviving any reachable arm remains visible after the conditional.
Useful? React with 👍 / 👎.
| for keyword in node.keywords: | ||
| if keyword.arg == "source": | ||
| return keyword.value | ||
| if keyword.arg is None and _mapping_literal(keyword.value) is not None: |
There was a problem hiding this comment.
Resolve compile source from a bound keyword mapping
When valid compile arguments are first stored in a visible mapping and then expanded, _compile_keyword_source accepts only an inline literal and loses the recorded source element. Thus kwargs = {"source": f"import {name}", "filename": "<x>", "mode": "exec"}; compile(**kwargs) compiles the interpolated source while the lint reports zero findings. Resolve a named mapping's recorded constant-key elements when processing a ** expansion.
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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
left a comment
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 971b9f4228
ℹ️ 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".
| # f-string and `exec(payload)` runs it. Clearing every sequence capture | ||
|
|
There was a problem hiding this comment.
Propagate wrapper arguments through source-preserving calls
Fresh evidence beyond the fixed bare-parameter wrapper case is def run(source): exec(source.strip()) followed by run(f"import {name}"): the inner argument is a Call, so this check skips it and the lint reports zero findings even though strip() preserves and executes the caller-built source. Resolve the complete inner source expression against the helper's argument bindings rather than accepting only a bare parameter name.
Useful? React with 👍 / 👎.
| if not isinstance(function, ast.Name): | ||
| return None |
There was a problem hiding this comment.
Resolve returns from visible methods
Fresh evidence beyond local-def helper handling is class Builder: @staticmethod; def build(name): return f"import {name}" followed by exec(Builder.build(name)): because the callee is an Attribute, this returns no helper and the lint exits successfully with zero findings. The same happens for a visible instance method such as Builder().build(name), so source returned by methods defined in the scanned file can bypass the gate.
Useful? React with 👍 / 👎.
| _TEXT_PRESERVING_MODULES = { | ||
| "textwrap": ("dedent", "indent"), | ||
| "copy": ("copy", "deepcopy"), | ||
| # `ast.unparse(ast.parse(f"..."))` is a round trip: the text that comes back | ||
| # executes what went in, so the interpolation survives it. The outer call read as | ||
| # opaque and the whole round trip passed the gate. | ||
| "ast": ("unparse",), |
There was a problem hiding this comment.
Preserve source through os text/path helpers
When an exact string is passed to os.fspath or os.fsdecode, the resulting value is the same source string, but neither helper is included in the pass-through table. Consequently, both exec(os.fspath(f"import {name}")) and exec(os.fsdecode(f"import {name}")) execute interpolated source while this hard gate reports zero findings; recognize their qualified, module-alias, and direct-import spellings like the existing copy helpers.
Useful? React with 👍 / 👎.
| # An opaque expansion may BE the source, `exec(*[f"..."])`, and it | ||
| # may also contribute nothing at runtime, in which case the next | ||
| # written-out argument is: `exec(*args, f"...")` with `args = ()` | ||
| # executes the f-string. Both stand, so it is kept as a candidate and | ||
| # the scan continues rather than stopping here. | ||
| candidates.append(argument) |
There was a problem hiding this comment.
Expand bound starred sink arguments
When the sink arguments are first stored in a visible sequence, this treats the starred name as opaque rather than consulting its recorded elements. Thus args = (f"import {name}",); exec(*args) is a valid call that executes the interpolated source while the lint reports zero findings; expand bound tuples and lists before choosing the first positional source argument.
Useful? React with 👍 / 👎.
| if isinstance(iterable, (ast.Tuple, ast.List, ast.Set)): | ||
| return iterable.elts | ||
| if isinstance(iterable, ast.Dict) and all(k is not None for k in iterable.keys): | ||
| return iterable.keys | ||
| return None |
There was a problem hiding this comment.
Resolve elements from bound visible iterables
A visible sequence stops being readable here once it is referenced by name: sources = [f"import {name}"]; for source in sources: exec(source) executes the interpolated element, but _literal_elements returns None, the loop target is cleared, and the lint reports zero findings. Resolve the recorded constant-index elements of a bound list or tuple when it is iterated.
Useful? React with 👍 / 👎.
| # `match [f"import {name}"]: case [payload]:` pairs element for element, | ||
| # exactly as an unpacking assignment does, so the capture holds the | ||
| # f-string and `exec(payload)` runs it. Clearing every sequence capture | ||
|
|
There was a problem hiding this comment.
Distinguish Bash here-strings from heredocs
In a maintained Bash launcher or workflow step, python -c 'name="os"; exec(f"import {name}")' <<< x runs successfully under the inspected Bash 5.2 shell, but the lint reports zero findings because the "<<" substring check mistakes the <<< here-string redirection for a heredoc and skips the entire -c command. Match the actual heredoc operator without excluding commands that merely carry a here-string.
Useful? React with 👍 / 👎.
| attribute = _folded_text(attribute) | ||
| if isinstance(attribute, ast.Constant) and attribute.value in SINKS: |
There was a problem hiding this comment.
Resolve bound constant names in builtins lookups
When the requested builtin name is first assigned to a visible string, the sink lookup no longer resolves it: import builtins; sink = "exec"; getattr(builtins, sink)(f"import {name}") executes the interpolated source while the lint reports zero findings. Consult the recorded literal-text binding before requiring the attribute expression itself to be an ast.Constant; the same issue affects builtins.__dict__[sink](...).
Useful? React with 👍 / 👎.
| # `match [f"import {name}"]: case [payload]:` pairs element for element, | ||
| # exactly as an unpacking assignment does, so the capture holds the | ||
| # f-string and `exec(payload)` runs it. Clearing every sequence capture | ||
|
|
There was a problem hiding this comment.
Scan run blocks executed with the Python shell
GitHub Actions supports shell: python, which executes the accompanying run block as a Python script (python {0}), but the workflow scanner only extracts heredocs and python -c commands. Therefore a step containing shell: python and run: | followed by exec(f"import {name}") runs the interpolated source while the default lint reports zero findings; inspect these Python-shell run blocks directly. See the jobs.<job_id>.steps[*].shell workflow syntax.
Useful? React with 👍 / 👎.
| ) | ||
| # `match [f"import {name}"]: case [payload]:` pairs element for element, | ||
| # exactly as an unpacking assignment does, so the capture holds the | ||
| # f-string and `exec(payload)` runs it. Clearing every sequence capture | ||
|
|
There was a problem hiding this comment.
Bind approvals to transitive source dependencies
Fresh evidence beyond collecting multiple names directly present at the sink is that name = "os"; payload = f"import {name}"; exec(payload) and the unsafe edit name = input() produce identical hash, kind, and origin values. This walk sees only the sink argument payload, not the names read by its recorded binding expression, so an existing justification remains valid after attacker-controlled data begins contributing to the executed source; include transitive binding digests in the reviewed identity.
Useful? React with 👍 / 👎.
commented
Aug 30, 2026
|
Closing this. The security fixes this checker was written alongside have already The checker grew to roughly ten thousand lines over about seventy review rounds, and Recording one thing that is worth keeping, since it surprised me. Both repositories The branch stays if anyone wants to pick the short rule out of it. |
Summary
unslothai/unsloth-zoo#1083closed one arbitrary-code-execution path: amodel_typeread straight out of a downloadedconfig.jsonwas interpolated into a string that was thenexec'd, so a hostile model repo got code execution with notrust_remote_code. That fix validated at the producer. This is the lint that stops the shape coming back anywhere in this repo.Split out of #9777, which carries the two actual security fixes. This PR is the checker on its own.
What it flags
scripts/lint_dynamic_exec.pywalks the AST of every package file and fails on a call toexec/eval/compilewhose source argument is a built string: an f-string, a stringBinOp, a%or.format()construction, or any of those reached through one level of local indirection, a text constructor, or another spelling of the builtin.exec(inspect.getsource(...))is the normal case here and is not flagged.The 40 reviewed sites live in
scripts/dynamic_exec_allowlist.json, each with a written reason, keyed on the path, the enclosing qualname and a hash ofast.unparseof the call. Reformatting a site keeps its justification; changing what gets interpolated invalidates it.Stdlib only, so it runs in the existing
source-lintjob with no new dependency, and it has a--self-test.Testing
--self-testand the live scan are green: 40 findings, all reviewedtests/security/test_lint_dynamic_exec.py: 126 cases, grouped by what each one provesRelated
The same checker lands in
unslothai/notebooks#365, andunslothai/unsloth-zoo#1108merged it there already.