Skip to content

Studio: ask before a chat tool reads or writes outside the sandbox - #10907

Merged
danielhanchen merged 80 commits into
mainfrom
harden-tool-path-approval
Sep 15, 2026
Merged

danielhanchen merged 80 commits into
mainfrom
harden-tool-path-approval

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

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 rm was blocked, but os.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() returns None for the installation owner, and owner is the ContextVar default, so a single user Desktop install never gets a Landlock ruleset or a sandbox-exec wrapper. Those apply only to managed multi account installs. What the owner gets is cwd plus HOME/TMPDIR repointing, 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 on is_high_risk_tool_call. Measured on main before this change, every one of these ran with no approval prompt at all:

operation, target outside the sandbox before after
open('/media/.../notes.md', 'w').write(...) runs silently asks
Path('/media/.../notes.md').write_text(...) runs silently asks
sed -i 's/a/b/' /media/.../notes.md runs silently asks
mv /media/.../notes.md /media/.../notes.md.bak runs silently asks
echo clobbered > /media/.../notes.md runs silently asks
cp /media/.../notes.md ./stolen.md runs silently asks
cat / head / tail / wc / stat / ls -la on any host path runs silently asks
open(...).read(), Path.read_text, pandas, numpy, json, csv, linecache, mmap runs silently asks
rm, dd, truncate, find -delete, os.remove, shutil.rmtree asks asks

So 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 /usr asks even though reading it does not.

Ordering matters and is pinned by a test: the credential checks run before the allowlist, so /etc/shadow and ~/.ssh/id_rsa still ask despite /etc being 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_path machinery, so a path assembled from literals, an f-string, os.path.join or a Path chain 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.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 (argv list and shell=True string), and ZipFile / 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_approval predicate, the command and python call tables, and the two operand scanners. tools.py is 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 in tools.py is 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 _BORROWED at 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:

baseline  239.0 us per classifier call
patched   246.4 us per classifier call

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.py goes 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_PYTHON and _INDIRECT_BENIGN_*, 33 cases that must stay silent
  • unit tests for credential precedence over the allowlist, relative path silence, Windows and UNC spellings, and unresolved dynamic paths

The 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 example cat ~/.config/app/settings.json is still not a credential, but it is a read of the user's home rather than the sandbox, so it now asks.

tests/test_permission_mode.py tests/test_sandbox_tools.py tests/test_windows_bash_shell.py tests/test_bypass_permissions.py
2213 passed, 1 skipped

ruff check and scripts/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:

  • A path computed at runtime. The analyzer folds what it can and stays quiet on what it cannot, which is deliberate: prompting on every dynamic path would fire on ordinary data-analysis loops.
  • A symlink that points outward. /proc/<pid>/root, /cwd and /fd are handled, because those are kernel links whose target is the process rather than a filesystem fact. An ordinary symlink is not: outside -> /home/alice/Documents already sitting in an opened project makes cat outside/private.txt a 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, since ln -s needs 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.py behind 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_commands against 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 terminal call reading a file outside the session sandbox. The only difference is the commit.

Approval card before and after, at merge base 8aef4f9c9 and head b2f1e0690

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_url so Studio's own loop evaluates is_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.

danielhanchen added 2 commits September 14, 2026 04:38
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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 14, 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-15T17:20:22.355684Z a17ebc3 Manual request
🔒 Security Review ✅ Completed 2026-09-14T05:29:19.544791Z 916b548 PR opened
ℹ️ 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

Full studio/backend test suite results, run on this branch and on main separately so any failure can be attributed rather than guessed at.

Branch: 586 failed, 43517 passed, 349 skipped, 377 errors (44m 24s, serial)

The failures are concentrated in test_video_backend.py, test_rag_upload_*, test_diffusion_compat_preflight.py, test_llama_admission_*, test_mcp_* and tests/multi_account/test_alice_bob_matrix.py. None of those touch the classifier. They are environment dependent on this box (no GPU, missing optional deps such as fastmcp and pymupdf, no network), and the same set fails on main.

To make the attribution exact rather than statistical, I ran the five failing files that actually import tools.py on both trees:

tests/test_account_tool_isolation.py tests/test_account_tool_confinement.py
tests/test_secure_tools_execute.py tests/test_sandbox_files_and_storage_roots.py
tests/test_blender_managed.py

branch    11 failed, 415 passed, 1 skipped
main      12 failed, 414 passed, 1 skipped

Identical failures on both, and the one extra on main (test_another_accounts_command_text_is_not_on_the_process_list) is order dependent, not a branch difference. So this change introduces no new failures.

The suites that actually cover this code are green:

tests/test_permission_mode.py tests/test_sandbox_tools.py
tests/test_windows_bash_shell.py tests/test_bypass_permissions.py
2190 passed, 5 skipped

@danielhanchen

Copy link
Copy Markdown
Member Author

The baseline run on main finished, so the comparison above is now exact rather than inferred:

main      586 failed, 43446 passed, 352 skipped, 377 errors   (43m 41s)
branch    586 failed, 43517 passed, 349 skipped, 377 errors   (44m 24s)

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 test_permission_mode.py.

danielhanchen added 2 commits September 14, 2026 06:12
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
@danielhanchen

Copy link
Copy Markdown
Member Author

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 closed

I 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:

  • Write mode was re-derived from a table that does not list open, so open(file = "/etc/evil.conf", mode = "w") was checked against the READ allowlist. Every read-silent root was therefore silently writable. Path(p).open("w") had the same defect from the other direction: as a method the receiver is the path, so the mode moves to the first argument and was read from the wrong position. Archive constructors too.
  • The shell lexer is not given < and > as punctuation, so echo CHANGED>/media/x arrived as a single 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 read or write: cp -t /abs, sort -o /abs, grep -f /abs, tar -cf /abs. Flags now resolve against a per-command table, which also stops cut -d / and sort -t / from reading a field separator as the root directory.
  • Two inversions of my own. \x02 marks a pathlib .parent walking out of its root; I had grouped it with the unresolved marker, which turned an escape signal into a pass. And the stricter classifier gated the new check behind a leading / or ~, which stopped it being a superset of the looser one for every Windows spelling.
  • Plus: rebinding a name no longer reclassifies a read that already happened; 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/joblib.dump put the destination second; a single leading backslash is root-relative on Windows and C:relative.txt is not.
  • False positives fixed as well. Path("route.txt").write_text("/api/v1/items") took its first argument as a destination, the builtin input("/data directory: ") prompt was read as a filename, and numpy.save takes its path first unlike torch.save. All three stay silent now.
  • 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.

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.

Performance

The classifier is now 2.6x faster than main, despite doing strictly more work. Measured by interleaving the two trees in the same loop, five pairs, on a byte-identical 2817-call corpus, because the box was loaded and absolute numbers taken minutes apart were not comparable:

metric main this branch change
is_high_risk_tool_call median 284.6 us 107.7 us -62%
is_potentially_unsafe_tool_call median 214.3 us 70.8 us -67%
p95 608.0 us 229.2 us -62%
p99 804.6 us 387.7 us -52%

The win is not in the new code. Profiling showed the path-approval work was about 9% of classifier time; the cost was _command_references_sensitive building twelve candidate strings that collapse to one identical string for an ordinary command, then running a superlinear credential regex over all twelve. Deduplicating those, adding early-outs to the glob checks, memoising ast.walk per tree and caching ast.parse accounts for nearly all of it.

For scale: one real tool call is 10.0 ms (_bash_exec) to 40.8 ms (_python_exec) on this machine, and the classifier runs once per tool call and never on the token path, so inference throughput is unaffected either way.

This optimisation changes no verdicts, and that is proved rather than asserted. Every payload in both this branch's and main's test files was classified through both gates before and after: 1700 payloads, 3400 verdicts, 0 differences, 0 classifier exceptions. The same check was run after each individual optimisation and under 8-thread contention (23376 verdicts, 0 mismatches), which matters because the parse cache and node list are now shared objects.

Safety suites: 2280 passed, 5 skipped. ruff check clean and the repo formatter (pinned ruff 0.6.9) applied.

Still open

This 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 tool_confinement.py behind the managed-account check. Extending that Landlock path to the owner account is the follow-up worth doing, and I would rather say that here than let this PR imply the hole is fully closed.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +2832 to +2834
argv0 = next(iter(_sequence_elements(head, containers)), None)
if argv0 is not None:
add(argv0, False)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +2760 to +2761
lowered = first.value.lower()
return lowered.startswith("file:") and ("mode=ro" in lowered or "immutable=1" in lowered)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +1701 to +1704
mode = next(
(kw.value for kw in _call_keywords(node) if kw.arg == "mode"),
node.args[1] if len(node.args) > 1 else None,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Comment on lines +1583 to +1584
if not (read_cmd or write_cmd or dest_last or flag_only):
return []

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +1883 to +1887
if (
_command_base_writes(base)
or _REDIR_WRITE_RE.match(token)
or _REDIR_PREFIX_RE.match(token)
and ">" in token

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Propagate 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +528 to +529
if not writing and candidate == os.sep:
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

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.

4 participants