Repository navigation
Studio: ask before a chat tool reads or writes outside the sandbox - #10907
Conversation
The session sandbox directory is a working directory, not an OS boundary: for the installation owner account_confinement() returns None, so a tool child runs with the user's own permissions and an absolute path in a tool call reaches the real filesystem. Deleting outside it already prompted in auto mode, but reading and overwriting did not, so a model could clobber or exfiltrate host files with no approval. Relative paths still resolve inside the per-session workdir and stay silent, so ordinary in-sandbox work is unaffected. An absolute path outside a set of silent roots (the sandbox and project workspaces, the interpreter and its site-packages, installed-software trees, the configured model and HF caches, the model folders the owner registered) now asks first. The credential checks run before the allowlist, so /etc/shadow still asks even though /etc is read-silent. Both classifiers are covered: the terminal scan gates file operands and redirection targets of read and write commands, and the python scan folds reader and writer call arguments through the existing _folded_path machinery. Measured on the benign corpus: 239us -> 246us per classifier call, which runs once per tool call.
cd / pushd / os.chdir re-point every relative path that follows, xargs builds another command's argv out of the pipeline, tar takes its paths after a flag word, subprocess hands the path to a child this scan cannot follow, and ZipFile / Path.open carry the path as a constructor argument or a receiver. Each of those reached a file outside the sandbox without ever putting it in an operand position the first pass read.
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. |
|
Full Branch: 586 failed, 43517 passed, 349 skipped, 377 errors (44m 24s, serial) The failures are concentrated in To make the attribution exact rather than statistical, I ran the five failing files that actually import Identical failures on both, and the one extra on The suites that actually cover this code are green: |
|
The baseline run on Same 586 failures and same 377 collection errors on both, all environment dependent on this box. The +71 passing tests on the branch are the new cases in |
A review of the first two commits turned up routes that still reached a host
path with no prompt, several confirmed by executing them. Each is a different
way of losing the path or its access mode, not a variation on one mistake.
Write mode was being re-derived from a table that does not list open, so
open(file = ..., mode = "w") was checked against the READ allowlist and every
read-silent root became silently writable. Path(p).open("w") carries its mode in
the first argument, because the receiver is the path, so it read as a read.
Archive constructors had the same defect.
The shell lexer is not given < and > as punctuation, so echo X>/media/y arrived
as one token and the redirect target was never seen. A wrapper brings its own
options, so skipping only its name left timeout 5 cat /media/x reading 5 as the
command. A path can arrive as a flag value, and the flag decides whether it is
read or written, so flags now resolve against a per-command table: that also
stops cut -d / and sort -t / from reading a field separator as the root
directory.
The rest: a name rebound after a read no longer reclassifies that read; walrus,
annotated and tuple bindings fold; a later absolute component discards the
earlier one, so os.path.join("/usr", "/media/x") is judged as /media/x; a child
process argv is screened as a command line so its write targets stay writes;
torch.save and joblib.dump put the destination second; Path.rename keeps its
receiver as the source; a single leading backslash is root-relative on Windows;
and C:relative.txt is not.
Two inversions are fixed. \x02 marks a pathlib .parent walking out of its root,
and grouping it with the unresolved marker turned an escape signal into a pass.
The stricter classifier gated the new check behind a leading / or ~, which made
it no longer a superset of the looser one for Windows spellings.
Path(p).write_text(content) took its first argument as a destination, so an
ordinary config value that looked like a path prompted; the builtin input()
prompt was read as a filename; numpy.save takes its path first, unlike
torch.save. All three now stay silent.
Credentials inside an allowlisted root are named explicitly, so a relocated
HF_HOME cannot hide a token store from a regex that keys on the directory name,
and Studio's own auth database stays gated.
… change The auto-mode classifiers cost ~289 us (high risk) and ~225 us (potentially unsafe) per tool call, nearly all of it repeated work rather than analysis: - _command_references_sensitive built twelve candidate strings per call (three base forms times four expansions) and scanned every one. For an ordinary command all twelve are the same string, so the superlinear credential pattern ran up to twelve times over identical text. Deduplicating the candidates keeps every distinct form and drops only exact repeats. - The glob scans ran the fnmatch loops for tokens that contain no glob metacharacter at all. Nothing the rewrites do can introduce one, so a command without ? * or [ can skip the scan outright. - _references_sensitive_path always searched three spellings of the text. The redundant-slash and de-bracketed rewrites are identity for an ordinary command, and re-scanning text the pattern already rejected cannot change the answer, so only a rewrite that changed the text is scanned again. - The python classifiers swept the whole tree twenty-one times between them, each ast.walk rebuilding the same traversal. The node list is identical for all of them, so it is built once per parsed tree. - Classifying one python call parsed the same source two or three times over. The tree is read-only, so one bounded cached parse serves all of them. - The terminal operand scan built its segment machinery even when no token could spell an absolute path, and recomputed a basename per token for scans that mostly do not need one. Verdicts are unchanged: 1461 payloads drawn from both classifier corpora, 2922 verdicts, zero differences, and zero classifier exceptions before or after. The same comparison holds across 8 threads (23376 verdicts under contention), which matters because the parse cache and the node list are now shared. Measured on the fixed 2817-call corpus, median of five runs: is_high_risk_tool_call 289.0 us -> 103.4 us is_potentially_unsafe_tool_call 224.9 us -> 68.2 us p95 611 us -> ~240 us p99 791 us -> ~390 us
|
Two rounds of follow-up work on this branch: closing the routes a review of the first cut turned up, and then making the classifier considerably faster than it was before any of this landed. Bypasses closedI had 17 reviewers audit the first two commits. Every one of them asked for changes, and several of the findings were confirmed by executing the payload against the real executor rather than by reading the code. Each was a different way of losing the path or its access mode:
Every payload above is now a parametrised regression case, each paired with a must-stay-silent twin so the gap cannot be closed by nagging instead. PerformanceThe classifier is now 2.6x faster than
The win is not in the new code. Profiling showed the path-approval work was about 9% of classifier time; the cost was For scale: one real tool call is 10.0 ms ( This optimisation changes no verdicts, and that is proved rather than asserted. Every payload in both this branch's and Safety suites: Still openThis hardens approval decisions for statically identifiable file access. It is not filesystem isolation, and reviewers were unanimous that no amount of table expansion makes it so. A path computed at runtime, or a symlink planted inside the sandbox pointing outward, still reaches the host with the user's permissions. The durable fix is the OS-level sandbox, and the machinery already exists in |
studio_root() was allowlisted, and in the default layout tmp_root() and shared_sandbox_root() resolve to that same directory, so studio.db (chat history, provider and MCP configuration) and auth/ sat inside a silent root: cat and echo > against them both ran with no approval. Only the output subdirectories are silent now, and a structural guard drops any root that is the studio home or an ancestor of it, so a producer that falls back to the home cannot re-grant it later. The root cache keyed only on the account id, so repointing the studio home or a cache mid-process kept serving the previous install's roots for up to the TTL. The key now carries that environment.
|
@codex security review |
tar: the positional skip exists for the legacy option word (tar cf out.tar src), which GNU tar only accepts as the first argument. Applying it unconditionally ate a real operand from the ordinary spelling, so tar -cf local.tar /media/private archived an out-of-sandbox tree with no prompt. Scope the skip to args[0], and add -g/--listed-incremental, a snapshot file tar creates, as a write in both spellings. Archive create mode is now read from every short-flag token rather than args[0] alone, so -g before -cf no longer hides it. python: an attribute call is not always receiver-based. io.open(p), gzip.open(p), os.open(p) and friends are module functions taking the path first, so folding the receiver produced the bare module name and the read escaped. Split those out from Path(p).open(), where the receiver really is the path, and take the mode from the matching argument position. python: a chained assignment (source = backup = '/media/private/x') has more than one target and was skipped whole, leaving the name unfoldable at the later open(source). Bind every simple target, and expand tuple targets elementwise so a, b = c, d = ... is reached too. Regression rows for all four, plus benign controls: relative tar operands in each spelling, a filename containing a c not reading as create mode, relative io.open/gzip.open, and Path(p).open() keeping its receiver.
tar -C is where the operation happens, so its sense is the inverse of the
archive's: extracting creates and overwrites members under it, while creating
only reads them from it. It was classified as a read unconditionally, so
tar -C /usr/share -xf local.tar wrote into a read-silent root with no prompt,
while the equivalent cp prompted.
An aliased import (import io as stream) leaves a receiver that is in no table, so
stream.open('/media/private/x') read as a Path-style method and its first
argument was never looked at. Resolve Import aliases back to the root module
before the receiver tables are consulted.
shlex keeps a command substitution as one token, and that token is not itself
absolute, so cat "$(printf /media/private/x)" produced no operand at all while
the shell handed cat the real path. Literal absolute paths inside $(...),
backticks and ${...} now count as operands of the position they sit in, keeping
the read/write sense of that position. Only literals are recovered; a genuinely
dynamic substitution still yields nothing, which stays the documented gap rather
than a claim this closes.
Regression rows for all three, plus controls: -C in create mode is still only a
read, substitutions naming no path ($(date), $(ls)) stay silent, and relative
aliased opens stay silent. Classifier median is unchanged at ~105 us.
grep -f / sed -e and friends supply the pattern from a flag, so no positional is owed to one. The unconditional skip discarded the first real input file instead, leaving grep -f patterns.txt /media/private/report.txt unclassified. The skip is now cleared when a pattern-supplying flag is seen, in both the attached and separate spellings. grep --exclude-from names a file grep reads and was absent from the table, so the attached form was discarded as an unknown flag. A token may carry several redirections before the command word: bash accepts </dev/null>/media/private/out printf payload. Kept whole because it STARTS with a redirection, it recorded one read of /dev/null>/media/private/out under the silent /dev root and the write past it was never seen. A single leading redirection with its target attached is still left whole, which is the case that guard was for. from io import open as fopen leaves a plain Name in no table, so the call was never dispatched and its path argument never read. ImportFrom aliases of the module open functions now resolve back to the real name. A derived binding lost the alternate values of the name it was built from: base = 'local'; base = '/media/x'; p = base + '/f' folded p to local/f only. Each rebound dependency is now substituted one at a time, which keeps this linear in the number of rebindings rather than a cartesian product, and is capped. Regression rows for all five plus controls: ordinary grep with -e/-f, a plain redirect, a relative from-import alias, and a derived binding that was never rebound all stay silent. Classifier median unchanged at ~105 us.
…coverage os.rename(src, dst) and shutil.copy(src, dst) are spelled as attributes but are the FUNCTION form: both paths are arguments. Reading the receiver as the source folded the bare module name and lost the destination entirely, so a statically known out-of-sandbox move ran unprompted. The module-vs-receiver question is now decided once per call and resolved through the import aliases, since every branch that treats a receiver as a path has a module-function counterpart that does not. tarfile.open takes the path first like the other module opens and was missing from the receiver set, so the archive operand was never scanned. import torch as t left _serializes_to_second_arg looking at receiver 't', which is in no table, so t.save(model, '/media/private/model.pt') fell through to a branch that never inspects the second argument. The receiver is resolved through the aliases first. The alternate cap I added last round discarded by POSITION, so eight benign reassignments ahead of base = '/media/private' hid the only value that mattered. It now keeps absolute candidates first and spends the cap on the remainder, so the bound limits work rather than coverage. Regression rows for all four plus relative controls. Performance: measured on interleaved pairs against the previous commit; the two are indistinguishable. The absolute figures are not quotable right now because the host is at load ~124, which inflates both sides equally -- only the paired comparison means anything.
The absolute-component rule was applied to EVERY folded path rather than at the
join that needs it. A doubled separator inside one literal is just a separator,
which the OS collapses, so /home/alice//usr/report.txt was read as a second root
and reduced to /usr, which is read-silent: the user's own file went unprompted.
os.path.join, Path(a, b) and the Path / operator now resolve an absolute component
at the join itself, where the meaning is unambiguous, and literals are left alone.
tar -cf/media/private/out.tar was rejected the moment the cluster body contained a
separator, because the whole body had to be alphabetic. A cluster whose last letter
takes an ATTACHED value is now split at the first non-letter.
tar --create carries the same mode as -c and was not read at all, so
tar --create --file=/usr/share/out.tar classified the archive as a read.
Function aliases were collected only for the open-like imports, so
from pandas import read_csv as rc left every other modeled reader and writer
reachable under an alias. The aliasable set is now derived from the path tables
themselves rather than listed by hand.
The alternate cap ranked by absolute rather than by need, so nine /usr rebindings
crowded out the one /media value that actually required approval. It now ranks by
_path_needs_approval.
A command string recovered from a variable is now split like a literal one. Worth
being precise about this one: it was a real gap in the operand scan but not a live
bypass, because a string passed to subprocess is unconditionally high risk already,
including subprocess.run('ls'). Fixed because the scan should be right on its own
rather than leaning on that.
Regression rows for all six plus controls. Performance measured against 96071e0
on interleaved pairs: high-risk min 104-108 us versus 111-117 us, so this round is
slightly faster, most likely from dropping the per-path absolute-component rewrite.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e1c616ed22
ℹ️ 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".
| argv0 = next(iter(_sequence_elements(head, containers)), None) | ||
| if argv0 is not None: | ||
| add(argv0, False) |
There was a problem hiding this comment.
Preserve ordered argv for named subprocess lists
When a subprocess argv is referenced through a variable, _python_literal_containers retains only its absolute-looking strings, so this code mistakes the first such string for argv[0] and never reconstructs the real command. For example, with a registered model directory as a read-silent but write-gated root, argv = ["cp", "local", "/registered/models/out"]; subprocess.run(argv) classifies the destination merely as an executable/read and silently permits cp to overwrite it. Fresh evidence beyond the previously discussed /media example is that the accidental read classification suppresses approval specifically for destinations inside read-only silent roots; preserve the complete ordered literal sequence before scanning it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reproducible. A named argv list is already scanned in order: argv = ["cp", "local", "/usr/share/out"]; subprocess.run(argv) prompts, and so does the literal form, across every read-silent root that is not write-silent (/usr, /bin, /etc, /var/lib, /proc and the rest). _python_literal_containers feeds _sequence_elements, which keeps the whole ordered sequence; only the argv[0] fallback looks at absolute-looking strings alone.
… chdir subprocess writes for PR #10907
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 13b5a650d7
ℹ️ 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".
| lowered = first.value.lower() | ||
| return lowered.startswith("file:") and ("mode=ro" in lowered or "immutable=1" in lowered) |
There was a problem hiding this comment.
Parse exact SQLite URI parameters before allowing reads
A substring is not proof that SQLite opened the database read-only: for example, sqlite3.connect("file:/configured/models/catalog.db?foo=mode=ro", uri=True) ignores the unknown foo parameter and opens or creates catalog.db in the default writable mode, while this test returns true. Since configured model directories are read-silent but write-gated, the call can create or modify that database without approval; parse the query and require an exact mode=ro or immutable=1 parameter.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reproducible as a bypass. The sqlite rule prompts on the call itself whatever the URI says, so sqlite3.connect("file:/usr/share/doc/catalog.db?foo=mode=ro", uri = True) already asks, exactly as the plain mode=ro spelling does. _sqlite_opens_read_only only refines the operand's read/write label under a gate that has already fired, which is why the comment on that branch says so.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a46397843c
ℹ️ 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".
| mode = next( | ||
| (kw.value for kw in _call_keywords(node) if kw.arg == "mode"), | ||
| node.args[1] if len(node.args) > 1 else None, | ||
| ) |
There was a problem hiding this comment.
Treat HDFStore's default mode as writable
For pd.HDFStore('/registered/models/data.h5') with no explicit mode, this helper returns false and the path is checked as a read, but pandas defaults HDFStore to append mode (mode='a'), which creates or modifies the file. Consequently, a configured model directory or another read-silent but write-gated root becomes writable without approval; use the constructor-specific writable default when the mode is omitted.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reproducible as a bypass. pd.HDFStore prompts today whichever way the mode is given: the no-mode form, mode = "a" and mode = "r" all ask, so there is nothing silent here to close. If the intent is the operand's label rather than the gate, that label is only consulted under a gate that has already fired.
| if not (read_cmd or write_cmd or dest_last or flag_only): | ||
| return [] |
There was a problem hiding this comment.
Confirmed and fixed in 5701238. The compiler drivers (gcc, g++, cc, c++, clang, clang++) now carry a flag spec whose -o is a write, so gcc -E input.c -o /media/alice/private.txt asks while gcc -o out main.c stays silent.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5701238245
ℹ️ 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".
| break | ||
| if index >= len(segment): | ||
| return [] | ||
| command = os.path.basename(segment[index]).lower() |
There was a problem hiding this comment.
Gate absolute executable paths before dropping their directory
When an absolute path is the command itself, such as /media/alice/tool, taking only its basename means the operand scanner never submits that path to _path_needs_approval; _terminal_is_high_risk also does not reject arbitrary path-qualified commands. In the default auto mode an installation-owner session can therefore execute a host binary or script outside every silent root without approval, even though launching it necessarily reads that outside file and lets its code access the unconfined host filesystem. Treat a path-qualified command token as an executable/read operand before reducing it to its basename.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in the latest commit. A path-qualified command word is now reported as a read of itself before it is reduced to a basename, so /media/alice/tool --flag asks while /usr/bin/python3 script.py and ./tool stay silent. A token ending in a separator is excluded, since a directory can never be the binary and that spelling turns up in expression fragments rather than command positions.
| if ( | ||
| _command_base_writes(base) | ||
| or _REDIR_WRITE_RE.match(token) | ||
| or _REDIR_PREFIX_RE.match(token) | ||
| and ">" in token |
There was a problem hiding this comment.
Propagate nested writes after changing directories
When cd/pushd enters a read-silent but not write-silent root, this check only recognizes a small set of direct writer command names and redirections. For example, cd /configured/models && python -c "open('weights.gguf','w').write('x')" leaves writes_after false because python is not in _command_base_writes; the recursively scanned Python payload sees only a relative path and also stays silent. The default auto gate can consequently overwrite registered model files without approval, so nested interpreter/shell write semantics must charge the changed-directory target as a write too.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in the latest commit. An interpreter's -c payload is now scanned for writes when deciding whether a directory change is a write target, for both the python and shell spellings, so cd /usr/share/doc && python -c "open('w.gguf', 'w')" and cd /usr/share/doc && sh -c "touch w.gguf" ask while cd /usr/share/doc && python -c "print(1)" does not.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a17ebc3ae8
ℹ️ 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".
| ( | ||
| sandbox_root, | ||
| _legacy_sandbox_root, | ||
| tmp_root, |
There was a problem hiding this comment.
Exclude managed-account subtrees from owner silent roots
In an installation-owner context, tmp_root() is exactly shared_tmp_root(), so adding it here makes paths under .../accounts/<id>/ read- and write-silent even though those directories contain managed accounts' private temporary uploads and processing data. The same collision occurs for project_workspaces_root() when UNSLOTH_STUDIO_PROJECTS_HOME is set: the owner's root becomes the shared base containing every account's Accounts/<id>/Projects. Because owner tools have no OS confinement, a call such as cat /tmp/unsloth-studio/accounts/<id>/private.jsonl then runs without approval; carve managed-account subtrees out of owner silent roots rather than allowlisting a shared ancestor.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 76ad7c9. A path that descends into an accounts/<id> segment is never silent now, whichever root it sits under, so on a managed install cat <shared projects root>/Accounts/7/Projects/p/private.jsonl asks while the owner's own <root>/p/notes.txt stays silent.
| if not writing and candidate == os.sep: | ||
| return False |
There was a problem hiding this comment.
Gate recursive reads rooted at the filesystem root
For Python calls that recursively enumerate the exact root, such as os.walk('/') or Path('/').rglob('*'), the operand scanner correctly produces /, but this unconditional read exemption makes _python_reaches_outside_sandbox return false. In the default auto mode for an unconfined installation owner, these calls can therefore enumerate filenames and metadata across the entire host without approval. Keep the no-prompt behavior operation-specific to a shallow ls / rather than treating / as harmless for every reader.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 76ad7c9. The root exemption is operation-specific now: a shallow ls / and os.listdir("/") stay silent, while a recursive reader rooted there (os.walk("/"), Path("/").rglob("*")) reports what it descends into instead of the root, so it asks. Walks of ordinary directories are unaffected.
Reported by a user running Desktop v0.1.808-beta on Linux: a local model used the chat tools to read and write files outside the session sandbox, on a different partition entirely. Shell
rmwas blocked, butos.remove()was not.The report is correct, and the gap is wider than it describes.
What is actually going on
The session sandbox directory is a working directory, not an OS boundary.
tool_confinement.account_confinement()returnsNonefor the installation owner, and owner is the ContextVar default, so a single user Desktop install never gets a Landlock ruleset or asandbox-execwrapper. Those apply only to managed multi account installs. What the owner gets iscwdplusHOME/TMPDIRrepointing, a scrubbed env and rlimits. An absolute path in a tool call therefore reaches the real filesystem with the user's own permissions.That leaves the approval gate as the only thing standing between a prompt injection and the user's files, and the gate had a hole. The default mode is "Approve for me" (
permission_mode="auto"), which gates onis_high_risk_tool_call. Measured onmainbefore this change, every one of these ran with no approval prompt at all:open('/media/.../notes.md', 'w').write(...)Path('/media/.../notes.md').write_text(...)sed -i 's/a/b/' /media/.../notes.mdmv /media/.../notes.md /media/.../notes.md.bakecho clobbered > /media/.../notes.mdcp /media/.../notes.md ./stolen.mdcat/head/tail/wc/stat/ls -laon any host pathopen(...).read(),Path.read_text, pandas, numpy, json, csv, linecache, mmaprm,dd,truncate,find -delete,os.remove,shutil.rmtreeSo outright deletion was caught, while overwriting and reading were not. That is exactly the seam the reporter walked through.
The fix
One rule, applied at both classifiers:
A relative path stays silent. An absolute path outside a set of silent roots asks first.
Relative paths resolve inside the per session workdir, which is why ordinary in sandbox work is completely unaffected:
open('out.txt', 'w'),cat README.md,pip install -r requirements.txt,python train.py,git commit,tar czf out.tgz .all stay silent. That single property is what keeps the false positive cost near zero.The silent roots are assembled from what the install already knows about itself: the sandbox and project workspaces, the session tmp dir, the interpreter and its site-packages, installed software trees (
/usr,/bin,/lib,/etc,/opt,/proc,/sys,/run, plus the macOS and Windows equivalents), the configured Hugging Face and model caches, and the model folders the owner registered in the UI. Writable roots are the narrower subset where tool output ordinarily lands, so writing into/usrasks even though reading it does not.Ordering matters and is pinned by a test: the credential checks run before the allowlist, so
/etc/shadowand~/.ssh/id_rsastill ask despite/etcbeing read silent.Both classifiers are covered. The terminal scan gates file operands and redirection targets of read and write commands, reusing the token list the scan already builds and the existing quote and expansion unrolling. The python scan folds reader and writer call arguments through the existing
_folded_pathmachinery, so a path assembled from literals, an f-string,os.path.joinor aPathchain resolves the same way the credential scan resolves it.The second commit closes the indirect routes, each of which reached an outside path without ever putting it in an operand position:
cd/pushd/os.chdirre-point every relative path that follows,xargsbuilds another command's argv out of the pipeline,tartakes its paths after a flag word,subprocesshands the path to a child this scan cannot follow (argv list andshell=Truestring), andZipFile/Path(...).open()carry the path as a constructor argument or a receiver.Where the code lives
The approval subsystem is its own module,
studio/backend/core/inference/tool_path_approval.py: the silent roots, the shared_path_needs_approvalpredicate, the command and python call tables, and the two operand scanners.tools.pyis already a very large file, and putting 1,800 further lines into it would have made both the change and the file harder to read than they need to be. What stays intools.pyis the wiring plus the shared lexing helpers the rest of that file uses as well.The two modules reference each other, so each binds the other by module rather than by name and the borrowed names are listed explicitly in
_BORROWEDat the top of the new module. Both import orders are exercised.The move itself changes no behaviour: the classifiers were run over the full test corpus before and after, 784 payloads across both classifiers, with zero differences, and the benchmark above is unchanged at 71 microseconds.
Performance
The classifier runs once per tool call, never per generated token, so inference throughput is untouched. On the identical benign corpus, before and after on the same machine:
Root discovery is cached: 3.7 ms to build, once per 60 seconds, 0.21 us per cached lookup.
Tests
studio/backend/tests/test_permission_mode.pygoes from 1691 to 1780 cases. The new corpora are the reporter's own operations plus the routes that reach the same files another way, each paired with a must stay silent twin so a future change cannot fix the gap by nagging:_OUTSIDE_SANDBOX_TERMINAL/_OUTSIDE_SANDBOX_PYTHON, 38 cases that must ask_OUTSIDE_SANDBOX_INDIRECT_TERMINAL/_OUTSIDE_SANDBOX_INDIRECT_PYTHON, 13 cases that must ask_ALLOWLISTED_TERMINAL/_ALLOWLISTED_PYTHONand_INDIRECT_BENIGN_*, 33 cases that must stay silentThe existing 67 case
_BENIGN_*no nag corpus is untouched and still passes. Eleven pre-existing expectation rows changed, all of them a direct consequence of the new policy rather than an accident, and each carries a rewritten comment saying why. For examplecat ~/.config/app/settings.jsonis still not a credential, but it is a read of the user's home rather than the sandbox, so it now asks.ruff checkandscripts/run_ruff_format.py(pinned ruff 0.6.9) both pass.What this does not do
This hardens approval decisions for statically identifiable file access. It is not filesystem isolation.
What this is aimed at, and what it is not
This is a lexical classifier over an unbounded input space: every shell spelling that can name a path, and every Python API that can open one. It is deliberately scoped to the spellings a model or a user actually writes, not to every spelling bash and CPython will accept. Concretely, what gates is a literal, statically visible path reaching a common API: the shell's ordinary readers, writers, redirections, archives, substitutions and wrappers, and the stdlib and data-stack calls that open a file, under their documented keyword names and import aliases.
What does not gate is the long tail: a path assembled at runtime, an unusual alias or indirection, a shell construct nobody writes by hand. Those are a known, stated residual rather than an oversight. Closing them is not what a string-level classifier is for, and chasing each one adds table entries and false-positive risk for spellings that do not occur in practice.
Two residuals are worth naming, because neither is closable inside a lexical classifier:
/proc/<pid>/root,/cwdand/fdare handled, because those are kernel links whose target is the process rather than a filesystem fact. An ordinary symlink is not:outside -> /home/alice/Documentsalready sitting in an opened project makescat outside/private.txta relative path, and the classifier sees(name, arguments)with no working directory to resolve it against. Resolving candidates would also mean a stat per path token of every command, and the answer would be from before the call rather than at it. Planting one inside the sandbox does prompt, sinceln -sneeds an absolute target, but a pre-existing one does not.The durable fix for both is the OS level sandbox, and the machinery already exists in
tool_confinement.pybehind the managed account check. Extending that Landlock path to the owner is worth doing next, and is tracked separately from this change.Related: #10860 hardens
_find_blocked_commandsagainst command position substitutions. Same family of defect, different layer, no overlapping functions.What this looks like in the UI
Both halves are the same install of Studio at the same permission level, the shipped default "Approve for me", driven through a scripted provider that returns one
terminalcall reading a file outside the session sandbox. The only difference is the commit.Before, the card runs to completion unprompted and the host file's contents are printed into the thread. After, the same call parks on Allow / Always allow / Deny and nothing is read until the user decides.
Worth stating plainly, because it is the part a screenshot cannot show: the decision is made in the backend tool loop, not in the browser. The provider is driven through a real
base_urlso Studio's own loop evaluatesis_high_risk_tool_call, which is the function this PR changes. A stream faked in the page would have skipped it and produced two identical cards.