Repository navigation
Studio: block sandbox bypass via command-position substitutions in terminal tool - #10860
Conversation
…rminal tool Fixes unslothai#10835 A command substitution at command position synthesizes the executed word, so the blocked name never appears literally. $(ls /usr/bin/ | grep "^reb") runs reboot and $(ls /usr/bin/ | grep "^rm$") -rf ... runs rm, and neither contains the blocked word, so the blocklist missed both. With tool permission set to Run automatically the ask gate approves by design, so it executed. Backend-only change in _find_blocked_commands (studio/backend/core/inference/tools.py). Command-position $(...) and backticks now get their bodies screened: a blocked literal anywhere in the body is reported, and an executable enumeration (ls/find/compgen of bin dirs, echo/printf glob expansion) is treated as unknowable and blocked. Same screening covers brace groups, branch and loop bodies, find -exec payloads, sudo/env-style wrappers, and laundered variables (c=$(...); $c, printf -v c, c=reboot; $c). Argument-position substitutions like echo $(date) and single-binary lookups like $(which python) stay allowed. The diff is purely additive, 270 insertions and 0 deletions, confined to the blocklist plus tests. Nothing else in the execution path changed. Testing: added 18 blocked cases (both issue repros verbatim) and 14 allowed cases in test_sandbox_tools.py. Full file plus test_windows_bash_shell.py: 349 passed, 4 skipped. ruff check and the repo formatter pass.
|
Confirmed the gap in _find_blocked_commands in studio/backend/core/inference/tools.py, where a command-position substitution synthesizes the executed word so the blocked name never appears literally, and the auto-run path has no second gate. Will get this reviewed. |
|
Confirmed the literal-name scan in studio/backend/core/inference/tools.py misses a command-position substitution, so both repros get through the blocklist, and the added screening covers them plus the laundered-variable shapes. Will get this reviewed. |
Six issues found while running the new screen against a corpus of everyday
terminal commands and of bypasses verified to really execute, on the posix
lexer and on both Windows lexer paths.
The screen is a hard block, not a prompt, so a false positive is a dead
command. Four of these produced one:
- A wrapper was allowed up to four arbitrary words before its operand, so
anything within reach of a timeout/nohup/xargs/env read as command position:
`timeout 60 python train.py --data $(ls -d data/*)` was refused. A wrapper
forwards to ONE operand, so only its own flags, assignments and numeric
arguments may sit in front of it now.
- A wrapper option taking a separate value has to swallow that value too, or
`xargs -P $n` reads the `$n` as the command. The regex cannot pin this down
on its own - it just backtracks to the shorter reading - so it is checked
against the existing flag table in code.
- The assignment screen was missing the arithmetic guard its sibling regexes
carry, so `sec=$((60*5)); timeout $sec make test` was refused over a value
that can only ever be a number.
- Neither the separators nor the bodies were quote-aware. Bash expands nothing
inside single quotes and an expansion inside double quotes is a word the
outer command receives, so `sed 's|x|$(ls)|' f` and `echo "check if $(ls -1
*.py | wc -l) files"` both ran nothing and were both refused. The body scan
also matched `.` - the synonym for `source` - against any dot in a filename,
reporting `$(cat .env)` as "Blocked command(s) for safety: .".
The remaining two let real commands through, or through the CPU:
- Assignment separators were narrower than execution separators, so a launder
behind a keyword, a subshell or another assignment was never collected:
`if true; then c=$(ls /usr/bin|grep rm); fi; $c`, `(c=$(...); $c)` and
`x=1 c=$(...); $c` all delete. So does `"$c"`, the recommended spelling,
which the screen did not cover.
- Each site costs a span walk over the rest of the line and this function has
no length cap, unlike the ask-gate screen. `";$(" * 10000` went from 0.1s
before the screen existed to over 30s after it, on the request thread. Past
64 sites the screen now refuses instead of reading, which fails closed.
Verified against the merge base on a 125-command corpus: 36 bypasses newly
blocked (up from 29), 0 everyday commands newly refused (down from 10), same
verdicts under the posix and both Windows lexer paths. The 12 failures in the
wider backend suite are identical before and after.
Opening comment-reduction pass. Comment lines on the added code drop from 95 to 54 in tools.py and 30 to 17 in the tests, with no code change (AST-gated). Stopped short of a deeper cut: what survives is one line per boundary naming the command that regressed when the boundary sat elsewhere, which is the fact a future reader needs in order not to move it back.
|
@codex review |
|
@codex security review |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 56105502e4
ℹ️ 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".
| ) | ||
| _SUBST_WRAPPER_ARG = ( | ||
| r"(?:(?:" + _WRAPPER_VALUE_FLAG_ALT + r")\s+[^\s;&|()]+" | ||
| r"|-[^\s;&|()]*|[A-Za-z_]\w*=[^\s;&|()]*|\d+)" |
There was a problem hiding this comment.
Accept timeout's full duration syntax in the wrapper scan
When timeout uses a valid suffixed or fractional duration, such as timeout 1s $(ls /usr/bin | grep '^rm$') -rf victim, _SUBST_WRAPPER_ARG does not recognize the duration and therefore never screens the command-position substitution. timeout --help documents DURATION as a floating-point number with an optional s, m, h, or d suffix, while this pattern admits only bare integers; the synthesized rm consequently reaches _bash_exec without being blocklisted.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in c436d30. timeout --help documents DURATION as a floating point number with an optional s/m/h/d suffix, and the argument class took bare integers only. Verified the bypass by running it against a stand-in rm on PATH: it executed. The class now accepts the suffixed and fractional spellings, with regression tests for timeout 1s and timeout 0.5.
| _SUBST_WRAPPER_RUN = ( | ||
| r"(?:(?:env|command|builtin|exec|time|nohup|nice|setsid|stdbuf|timeout|ionice|chroot" | ||
| r"|setpriv|sudo|doas|su|xargs)\s+(?:" + _SUBST_WRAPPER_ARG + r"\s+){0,4}){0,3}" |
There was a problem hiding this comment.
Fail closed when wrapper scanning exceeds its bounds
A valid wrapper invocation with more than four option operands, such as env -u A -u B -u C -u D -u E $(ls /usr/bin | grep '^rm$') -rf victim, exceeds the {0,4} repetition and makes the whole substitution-site regex fail instead of refusing the command. env --help explicitly permits [OPTION]... before COMMAND, so this crafted command executes the synthesized blocked binary; the bounded scan needs an overflow path that fails closed, analogous to _exec_child_index.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in c436d30. env --help documents [OPTION]..., so any cap is a count that can be exceeded to make the site regex fail open rather than closed; the five-option form executed against a stand-in rm. Rather than add an overflow path I removed both caps: the repetitions cannot overlap (a wrapper word never matches the argument class) and each must consume a mandatory space, so there is nothing to backtrack. Measured linear to 180 KB, including the near-miss shape that never reaches a $(.
| _SUBST_AT_CMD_SITE_RE = re.compile( | ||
| _SUBST_CMD_SEP + r"\s*" | ||
| r"(?:[A-Za-z_]\w*=[^\s;&|()]*\s+)*" + _SUBST_WRAPPER_RUN + r"(?:\"\$\((?!\()|\$\((?!\()|`)", |
There was a problem hiding this comment.
Preserve command position after leading redirections
Bash permits redirections before a command word, so >/tmp/log $(ls /usr/bin | grep '^rm$') -rf victim executes the substitution's output as the command. _SUBST_AT_CMD_SITE_RE only skips assignments and wrappers after its separator and cannot cross the leading redirection, leaving this synthesized blocked command unscreened even though the existing token walker already treats redirections as preserving command position.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in c436d30. Bash saves the leading redirections and assignments before the command name, and the token walker already treated a redirection as leaving command position intact, so the site scan was the odd one out. >out.log $(ls /usr/bin | grep '^rm$') executed against a stand-in rm. A redirection prefix is now stepped over on both sides of the assignment prefix.
| ) | ||
| # Command-position separators for the screens below. `:` is absent on purpose: its arguments are | ||
| # expanded but never executed. | ||
| _SUBST_CMD_SEP = r"(?:^|[;&|\n({]|&&|\|\||\b(?:then|do|else|elif|if|while|until)\b\s*|!\s*)" |
There was a problem hiding this comment.
Treat case labels as substitution command sites
In a Bash case arm, the closing ) is followed directly by executable commands, as in case x in x) $(ls /usr/bin | grep '^rm$') -rf victim;; esac. Because _SUBST_CMD_SEP omits ), the new body scanner does not recognize this substitution as being at command position, allowing the enumerated blocked command to execute.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in c436d30. case word in [ [(] pattern ) list ;; ] ... esac puts the arm's commands directly after the ), and the form executed against a stand-in rm. Not fixed by putting ) in the separator class, which would refuse an ordinary echo $(date) $(ls /tmp): case arms are a separate site kind, matched only inside a case ... in ... esac region and only for a ) that does not close a substitution. Both controls are now tests.
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
All four were reported by review and all four really delete: each was run against a stand-in rm on PATH and executed it. - timeout's DURATION is "a floating point number with an optional suffix: 's', 'm', 'h' or 'd'" (timeout --help), but the wrapper argument class took bare integers only, so `timeout 1s $(ls /usr/bin | grep '^rm$')` was never screened. - The wrapper option run was capped at 4 per wrapper and 3 wrappers. `env --help` documents `[OPTION]...`, so a fifth option made the whole site regex fail rather than refuse: `env -u A -u B -u C -u D -u E $(...)` ran. Both repetitions are unbounded now, which is safe because the parts cannot overlap (a wrapper word never matches the argument class) and each repetition must consume a mandatory space, so there is nothing to backtrack. Measured linear to 180 KB, including the near-miss shape that never reaches a `$(`. - Redirections may precede the command word, so `>out.log $(...)` runs the substitution's output. The token walker already knew this; the site scan did not. - A case arm's `)` is followed directly by the commands to run, so `case x in x) $(...) -rf victim;; esac` executes. Added as its own site kind rather than by putting `)` in the separator class, which would refuse an ordinary `echo $(date) $(ls /tmp)`: an arm's `)` is one that does not close a substitution, inside a case ... in ... esac region. Corpus unchanged at 0 regressions and 36 bypasses blocked, on the posix lexer and both Windows lexer paths, plus 10 new tests (5 blocked, 5 allowed controls).
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c436d3096b
ℹ️ 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".
| # fractional spellings too or the site behind them goes unscreened. | ||
| _SUBST_WRAPPER_ARG = ( | ||
| r"(?:(?:" + _WRAPPER_VALUE_FLAG_ALT + r")\s+[^\s;&|()]+" | ||
| r"|-[^\s;&|()]*|[A-Za-z_]\w*=[^\s;&|()]*|(?:\d+(?:\.\d*)?|\.\d+)[smhd]?)" |
There was a problem hiding this comment.
Accept every valid floating-point timeout duration
On GNU coreutils, timeout 1e1 $(ls /usr/bin | grep '^rm$') -rf victim and the suffixed 1.5e1s form are valid—the local timeout --help describes DURATION as “a floating point number with an optional suffix,” and both forms executed a stand-in rm—but this operand pattern rejects scientific notation, so _find_blocked_commands returns an empty set and the synthesized command bypasses the sandbox blocklist. The fresh evidence beyond the earlier fixed report is that scientific-notation floating-point durations remain accepted by timeout but unrecognized here.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 38c8c5a. Checked locally: timeout 1e1 true and timeout 1.5e1s true both exit 0, and both forms executed a stand-in rm. Float there means strtod, so the operand class now takes the scientific spellings; both are tests.
| ) | ||
| # Command-position separators for the screens below. `:` is absent on purpose: its arguments are | ||
| # expanded but never executed. | ||
| _SUBST_CMD_SEP = r"(?:^|[;&|\n({]|&&|\|\||\b(?:then|do|else|elif|if|while|until)\b\s*|!\s*)" |
There was a problem hiding this comment.
Treat coproc's command operand as a command site
In Bash, coproc $(ls /usr/bin | grep '^rm$') -rf victim executes the substitution output asynchronously, but coproc is absent from the command-site keywords and wrappers, so _find_blocked_commands returns an empty set. Bash's local help coproc documents the syntax as coproc [NAME] command [redirections]; therefore a synthesized blocked command in that operand reaches _bash_exec without being rejected.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 38c8c5a. help coproc gives coproc [NAME] command [redirections] and the form executed a stand-in rm. Added as its own branch of the separator class with the optional NAME matched only there, so it cannot widen any other separator; coproc echo hi stays allowed as a control.
| blocked.add(_BLOCKED_SYNTHESIZED_COMMAND) | ||
| if laundered_refs: | ||
| var_exec_pattern = ( | ||
| _SUBST_CMD_SEP |
There was a problem hiding this comment.
Scan laundered variables in case arms
When the synthesized name is first stored in a variable, c=$(ls /usr/bin|grep '^rm$'); case x in x) $c -rf victim;; esac executes the resulting rm, yet this variable-execution regex only recognizes _SUBST_CMD_SEP and has no case-arm handling, so _find_blocked_commands returns an empty set. The fresh evidence after the direct case-site fix is that _case_arm_sites is applied only to substitutions, leaving the newly added laundering path bypassable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 38c8c5a. Correct catch on the shape of the earlier fix: the arm handling was wired into the substitution scan only, so the laundered form still deleted. The arm walker now takes the pattern to anchor and the variable scan passes its own.
| + r")\})" | ||
| # The closing quote ends the word too, or `"$c"` - the recommended spelling - | ||
| # walks through the screen the bare one is caught by. | ||
| r"\"?)(?=\s|$|[;&|)\]}])" |
There was a problem hiding this comment.
Reject laundered variables embedded in a command word
Bash concatenates adjacent expansion and literal fragments into one command word, so x=$(printf r); ${x}m -rf victim invokes rm; however, this lookahead requires the variable expansion to end the word, causing _find_blocked_commands to return an empty set for that command. A laundered expansion used as a command-word prefix therefore bypasses the hard blocklist even though the assignment was collected as unscreenable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 38c8c5a. Bash concatenates adjacent fragments into one word, so x=$(printf r); ${x}m runs rm; the lookahead required the expansion to end the word. Trailing word characters are now part of the same word, and the precise literal is only reported when the expansion IS the whole word: glued to more text it is a fragment of an unknown name, not that name. v=$(date); echo ${v}Z stays allowed.
All four reported by review, all four verified here against a stand-in rm on
PATH before changing anything.
- timeout's DURATION is a float, and float there means strtod, so `timeout 1e1`
and `timeout 1.5e1s` are valid and both ran. The operand class now takes the
scientific spellings.
- `coproc [NAME] command` (bash `help coproc`) runs COMMAND asynchronously, so
its operand is a command position. Added with its optional NAME matched only
in the coproc branch, where it cannot widen any other separator.
- A case arm runs a laundered variable as readily as a substitution, but the
arm handling was wired only into the substitution scan, so
`c=$(ls /usr/bin|grep '^rm$'); case x in x) $c -rf victim;; esac` still
deleted. The arm walker now takes the pattern to anchor, and the variable
scan passes its own.
- Bash concatenates adjacent fragments into one word, so `x=$(printf r);
${x}m` runs rm. The scan required the expansion to END the word. Trailing
word characters are now part of the same word, and a precise literal is only
reported when the expansion is the whole word: glued to more text it is a
fragment of an unknown name, not that name.
Corpus unchanged at 0 regressions and 36 bypasses blocked across the posix and
both Windows lexer paths; timing still linear to 260 KB. 7 new tests.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 38c8c5afb2
ℹ️ 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".
| ) | ||
| # Redirections may precede the command word (`>out.log $(...)` runs the substitution's output), | ||
| # and the token walker already treats them as leaving command position intact. | ||
| _SUBST_REDIR_PREFIX = r"(?:\d*(?:>>|<<<|<<|>&|<&|>|<)[^\s;&|()]*\s*)*" |
There was a problem hiding this comment.
Consume separated redirection filenames
When the redirection target is separated from its operator, as in > out.log $(ls /usr/bin | grep '^rm$') -rf victim, Bash still treats the substitution output as the command, but this prefix consumes only an attached target and stops at out.log; the substitution is therefore never screened. The fresh evidence beyond the earlier leading-redirection fix is that Bash accepts whitespace between the operator and filename, whereas the added test covers only >out.log, allowing the synthesized blocked binary to reach execution.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in ec3170f; it executed a stand-in rm. The redirection prefix now allows whitespace between the operator and its target, with the target and the space after it BOTH mandatory: that is what keeps >$(ls) cmd out, since a substitution that is the redirection target names a file and is not run. Added as a test alongside the blocked form.
| _SUBST_WRAPPER_ARG = ( | ||
| r"(?:(?:" + _WRAPPER_VALUE_FLAG_ALT + r")\s+[^\s;&|()]+" | ||
| r"|-[^\s;&|()]*|[A-Za-z_]\w*=[^\s;&|()]*" | ||
| r"|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[smhd]?)" |
There was a problem hiding this comment.
Consume env long-option operands
For env --chdir /tmp $(ls /usr/bin | grep '^rm$') -rf victim, the generic flag branch consumes --chdir, but /tmp is then treated as the forwarded command and the substitution site is missed. In the inspected GNU environment, env --help documents -C, --chdir=DIR as taking a directory and the separated --chdir /tmp spelling is accepted, so this valid wrapper invocation can execute the synthesized blocked command unless all value-taking env options are represented.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in ec3170f; it executed a stand-in rm. Worth recording where the fix went: adding -C/--chdir to _WRAPPER_VALUE_FLAGS_BY_CMD broke two real detections in test_permission_mode, because that table also drives the high-risk classifier and -C / is exactly what makes a following relative etc/passwd sensitive. It is now scoped to the substitution site scan. -S/--split-string is deliberately left out of both: its operand is split into the argv that runs, and consuming it as a value made env -S 'rm -rf /tmp/x' come back empty.
| if state == '"': | ||
| # Double quotes DO substitute, but into a word the outer command receives - unless | ||
| # the quote opens at the site itself (`"$(...)"`), which is a command word. | ||
| return match.group(0).endswith('"$(') |
There was a problem hiding this comment.
Recognize double-quoted backticks as command sites
At the beginning of a command word, Bash executes a double-quoted backtick expansion just like the explicitly supported "$(...)" form; for example, "ls /usr/bin | grep '^rm$'" -rf victim invokes rm. This branch accepts only a match ending in "$( while _SUBST_OPENER also lacks a quoted-backtick alternative, so the enumeration body is skipped and the blocked binary can execute.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in ec3170f; it executed a stand-in rm. The opener now carries a quoted-backtick alternative and the command-position test accepts a match ending in it, matching the "$(...)" handling. echo "\date`"` stays allowed as a control.
| body = _command_subst_body(command, opener) | ||
| lowered_body = body.lower() | ||
| blocked.update(_blocked_body_words(lowered_body)) | ||
| if _SUBST_ENUMERATES_COMMANDS_RE.search(lowered_body): | ||
| blocked.add(_BLOCKED_SYNTHESIZED_COMMAND) |
There was a problem hiding this comment.
Reject substitutions glued to literal fragments
A recognized substitution can still form only part of the executable word: "$(printf r)"m -rf victim is concatenated by Bash into rm, while this loop sees only the benign body printf r and reports neither a blocked word nor an enumerator. The new evidence beyond the fixed laundered-variable-prefix case is that a direct substitution follows the same concatenation rule, and the leading quote also prevents the separate high-risk command-site regex from failing closed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in ec3170f. Both the quoted form you gave and the bare $(printf r)m executed a stand-in rm, so the fix covers both: a substitution with more word text after it now fails closed, since the body being benign says nothing about the word that runs. It also closes $(echo reb)oot, which my corpus had carried as an open vector since the first round.
Four more reported by review, all four verified against a stand-in rm before changing anything, plus a fifth found while testing them. - Bash allows whitespace between a redirection operator and its target, so `> out.log $(...)` is the same command the attached spelling was fixed for. The target and the space after it are mandatory in the prefix, which is what keeps `>$(ls) cmd` out: a substitution that IS the target names a file. - `env -C/--chdir DIR` takes a separate value, so the DIR read as the command. - A double-quoted backtick expands exactly like `"$(...)"` and opens a command word the same way. - Bash concatenates adjacent fragments into one word, so `"$(printf r)"m` and the bare `$(printf r)m` both run rm while the body reads benign. A substitution with more word text after it now fails closed. That also closes `$(echo reb)oot`, which the corpus had carried as open since the first round. The env fix is deliberately NOT in _WRAPPER_VALUE_FLAGS_BY_CMD. Putting it there broke two real detections, caught by test_permission_mode: that table also drives the high-risk classifier, where `-C /` is exactly what makes a following relative `etc/passwd` sensitive. And `-S`/`--split-string` is left out entirely, because its operand is split into the argv that RUNS - consuming it as a value lost the command, and `env -S 'rm -rf /tmp/x'` went unblocked. Corpus now 0 regressions and 37 bypasses blocked across the posix and both Windows lexer paths; timing linear to 260 KB; 10 new tests.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Checked the command-position sites against main, where the literal-name scan still lets both repros through, and the review round since has closed the redirection-prefix, case-arm, coproc, timeout-operand and glued-word variants. Will get this reviewed. |
|
Benchmarked this before merging, since tool-call screening runs on every command the model issues. Measured on a 2637-command corpus, interleaved base/head pairs to cancel drift on a shared host (the box was at load ~29, so sequential runs are not trustworthy here):
So about +17 us per command, or +24%. In absolute terms that is nothing against the milliseconds a tool call takes, and it is per command rather than per token, so nothing about inference throughput changes. I am not asking for it back: the substitution scan is doing real work and the cost is proportionate. Worth pointing out separately, because it more than pays for the above and is not your code. Profiling the head, the single hottest thing in the scan is pre-existing:
words_alt = "|".join(re.escape(w) for w in sorted(_BLOCKED_COMMANDS))
pattern = rf"...({words_alt})..."
blocked.update(re.findall(pattern, lowered))
Happy to land that hoist as its own change against main rather than widening this PR, since it is independent of what you are fixing. Say which you prefer. |
#10927) * Studio: build the blocked-command alternation once instead of per call _find_blocked_commands rebuilt its blocked-word regex on every command it screened. _BLOCKED_COMMANDS is a module-level frozenset assigned at import and never mutated, so that alternation is a compile-time constant and the work was pure waste: an re.escape per blocked name per command, then a fresh re.compile behind re.findall's cache lookup. It showed up as the top entry when profiling the scan over a 2637 command corpus, 567k calls to re.escape and 0.60s cumulative out of 3.9s. Hoisting it to a module-level compile takes the median from about 101 us to about 86 us per command, measured on interleaved pairs against main (the hoist wins all five pairs; absolute figures run high because the host is loaded, so only the pairing is meaningful). No behaviour change, and not taken on trust: verdicts were dumped for 1829 payloads on both sides, covering the corpus plus the command-position substitution shapes from #10860, path-qualified and .exe spellings, and ordinary commands. Zero differences. tests/test_sandbox_tools.py, tests/test_permission_mode.py, tests/test_bypass_permissions.py and tests/test_windows_bash_shell.py stay green (2199 passed, 5 skipped). This is per command screened, not per token, so it changes nothing about inference throughput. It is worth doing because the scan runs on every command a model issues. * Tighten the comment on the hoisted alternation --------- Co-authored-by: danielhanchen <[email protected]>
Fixes #10835
Neither contains the blocked word, so the blocklist missed both. With tool permission set to Run automatically the ask gate approves by design, so it executed.
Backend-only change in
_find_blocked_commands(studio/backend/core/inference/tools.py). Command-position substitutions and backticks now get their bodies screened: a blocked literal anywhere in the body is reported, and an executable enumeration (ls/find/compgenof bin dirs,echo/printfglob expansion) is treated as unknowable and blocked. Same screening covers brace groups, branch and loop bodies,find -execpayloads,sudo/env-style wrappers, and laundered variables. Argument-position substitutions likeecho $(date)and single-binary lookups like$(which python)stay allowed.The diff is purely additive, 270 insertions and 0 deletions, confined to the blocklist plus tests. Nothing else in the execution path changed.
Repro (both from the issue):
Testing: added 20 blocked cases (both issue repros verbatim) and 14 allowed cases in test_sandbox_tools.py. Full file plus test_windows_bash_shell.py: 349 passed, 4 skipped. ruff check and the repo formatter pass.

