Repository navigation
fix(studio): keep Studio's auth directory out of the tool loop - #10895
Conversation
The CLI caches the raw API key at $STUDIO_HOME/auth/.cli_api_key_<stem>_<digest> so a relaunch reuses it instead of minting another (#10595). Tool subprocesses run as the backend's own OS user, so the 0600 mode on that file is no boundary against them, and the sandbox does not confine absolute paths. The auto-mode classifier did not recognise the auth directory either, so a model-emitted `cat ~/.unsloth/studio/auth/.cli_api_key_*` ran with no confirmation and the plaintext bearer went back to the provider in the next request. The same directory holds the bootstrap password, the desktop secret, the llama stream key and auth.db with the JWT secret. Two independent guards, so neither one has to be complete: - `_references_studio_credential` recognises those basenames, the default `.unsloth/studio/auth` layout, and the resolved `auth_root()` so a custom UNSLOTH_STUDIO_HOME is covered exactly. It feeds the existing `_references_sensitive_path`, so terminal, python and MCP all treat these as high risk, and it refuses the call outright in `_bash_exec`, `_python_exec`, `_edit_file` and MCP dispatch. That refusal holds in every permission mode, Bypass Permissions included: no user flow asks a tool to read Studio's own credentials, and an approval should not be able to hand them out. - Any sk-unsloth key or desktop secret that reaches a result by some other route is masked in `strip_result_for_model`, which is the one transform every model-bound tool result passes through. Only that copy: `record_result` and `tool_end_event` are untouched, so the tool card the user sees renders exactly as before. `_split_frontend_suffix` opts out, since it subtracts the stripped body from the text and needs the strip to stay suffix-only. The cache itself is unchanged (minting, reuse, revocation cleanup), so the launch flow still reuses one key across restarts; `_write_auth_secret` just chmods auth/ to 0700 the way the DB connection already does. Deliberately narrow, so ordinary work stays unprompted: an application's own auth/ package, auth.py, `grep -rn auth src/`, `sqlite3 ./auth/auth.db` and a `llama_api_key` variable all match nothing.
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. |
…ter the guard Three things simulation turned up. A platform matrix over what `auth_root()` resolves to (Linux default, custom STUDIO_HOME, venv prefix install, legacy home, WSL, macOS default and Application Support, Windows default / custom drive / ProgramData, and the case where the root cannot be resolved at all) found one spelling that reached the directory anyway: `cd <studio home> && ls -a auth`, which carries no absolute auth path and no Studio basename. The root spelling is now recognised too, but only together with a `cd` INTO it, so `grep -rn auth <studio root>/logs/studio.log` and `ls <studio root>/models && grep -c auth app.log` stay ordinary work. A result cut to fit the context window can end mid-key, and half a bearer is still credential material, so the redaction floor drops from 16 characters to 8. `sk-unsloth-` with nothing after it (prose about the format) still reads through. The terminal classifier calls the path check once per candidate token of every command, and the added ~2.5us per call showed up as +10% on that classifier. A literal prefilter over the five substrings every pattern needs takes the predicate to 0.63us and the classifier to +5.6% (about 20us per command). Tests cover the relative-read case with a temporary studio home, the benign root-mention commands next to it, and the truncated key.
`unsloth start` keeps the keys it mints for coding agents in $STUDIO_HOME/auth/agent_api_key.json, in the clear, next to the CLI cache. The directory patterns already covered it by path; naming the file counts now too, so it is refused the same way whatever route names it.
Simulation results: what changed, what it breaks, and what it costsI did not want to take "this only adds refusals" on trust, so the fix is now backed by simulations that run the real loop, the real executors and the real classifiers. Two of them found real gaps, which are fixed in this branch. Before vs after, through the production tool loopA fake external provider emits the structured
The "after" runs grant the approval automatically, which is the pessimistic case: a user who clicks Allow on a call they do not understand still does not hand the key over. Every permission mode, same harness: Ask, Approve for me, Off, Approve-for-me with Bypass Permissions, and Full access. The attack is refused in all five, and Does it break ordinary work?Classifier parity over 1,861 strings: every string literal in 25 verdicts moved. All 25 are Studio-credential accesses. Zero benign strings changed. The SSE stream is the only thing a browser ever sees, so browser coverage is the wire contract: nine ordinary tool calls replayed through the real loop on both trees produce byte-identical Two gaps the simulations found, now fixed
Also added while checking the blast radius: Robustness3,013 pathological inputs through the predicate (1 MB strings, 100k separators, Old installs and updatingAn isolated
The cache path, its digest and the file format are unchanged, so an install made by an older CLI keeps working and does not re-mint on update. HardwareNo device code is touched: the diff is path matching, one regex substitution and a permission tighten. The guard test suite passes identically with CostMeasured with the predicate stubbed to
The terminal classifier calls the path check once per candidate token, so the first cut of the predicate cost +10% there; a literal prefilter over the five substrings every pattern needs took it to +5.6%, about 20 us per command classified, once per tool call. Nothing is added to a per-token or per-request path. Suite statusSame 4,800-test tool / inference / MCP / auth sweep, same tree, before and after: 38 failed / 4792 passed on On the org queue, Known limits, unchangedPath matching is static, so an obfuscated read (base64, a dynamically assembled path) is only covered by the second guard, and only for credentials with a recognisable shape. A key that already leaked is not invalidated by this. |
…ored card Three issues from review. The guard matched the raw text, so OS-equivalent spellings walked past it: <home>//auth/auth.db and <home>/./auth/auth.db both opened the protected database while reading as ordinary paths. The path is collapsed with the existing redundant-separator normalization before the Studio checks now, and both spellings are matched. The marker test was a bare substring, so any path merely starting with the auth directory name was refused in every permission mode: <home>/authors/notes.txt and <home>/auth-backup/readme.md are harmless and were blocked. A marker now has to end at a separator or at the end of the path. Redaction ran on the model path only, so the card kept the raw text. That is a replay hole rather than a cosmetic difference: the frontend persists this payload and serializes the stored value back into a role=tool message on the user's next turn, so a leaked key was hidden from the continuation and sent to the provider one turn later. tool_end_payload masks it too, which also closes the stored copy. The card shows the user their own key, so masking it there costs nothing.
|
@codex security review |
The guard matched only the tidiest spelling of the auth path. The OS opens <home>/bin/../auth/auth.db and, on a Windows custom install, C:\Studio\.\auth\auth.db as the same protected database, and both walked past it: the existing collapse only handled // and /./ forward-slash forms. Canonicalize lexically instead -- separators unified, . dropped, x/.. cancelled -- and compare the markers in the same spelling, since on Windows they carry backslashes the canonical text no longer has. Lexical, not realpath: no filesystem access and nothing to race, and it is an extra candidate rather than a replacement, so a match in the raw text still counts. The cd marker had no trailing boundary, so it fired on any path merely starting with the Studio root. cd <home>/models && grep auth README and cd <home>-backup && ls auth were both refused in every permission mode despite never going near the auth directory. Require the root to end where it matched, or to continue into auth itself. Regression tests for all six equivalent spellings, both false positives, and the two real cd forms they must not cost.
Three gaps found while testing the guard across Linux, macOS, Windows, WSL and custom
studio homes, plus one false positive:
- `cat $STUDIO_HOME/auth/auth.db` reached the file. Both studio-home variables survive into
the tool subprocess environment, so the shell expands them for real. The variable
spellings of the home ($VAR, ${VAR}, %VAR%, $env:VAR) are now markers in their own right,
as is ${HOME} alongside $HOME and ~.
- A home whose name contains a space, which is the normal macOS case, is spelled with a
backslash escape in a shell. Read as a separator it split the directory name in half, so
unescape before canonicalising.
- A bare auth path ending at a newline missed the segment boundary.
- `print('agent_api_key.json')` was refused. The bare name is an ordinary string, so only
its path form counts now; a relative read still needs a cd into the auth directory, which
the existing rule catches.
The marker set grew, so it is now resolved into (marker, canonical marker) pairs once per
process, and the variable spellings are skipped for any text containing no $, % or ~. The
terminal classifier cost went from +5.6% to +5.1% while covering more spellings, and the
executor entry check from 3.3 us to 1.3 us per command.
Parity over the 1861-string corpus is unchanged: the same 25 verdicts move, all of them
reads of this install's own credentials.
Two more from the review: - A shell concatenates adjacent fragments, so `sqlite3 "$UNSLOTH_STUDIO_HOME"/auth/auth.db` opens the same file as the unquoted spelling. With the quote left in place no marker could span it, so the candidate is dequoted before matching. - The cached key is `sk-unsloth-` + token_hex(16), but the mask accepted any alphanumeric suffix, so this repository's own `sk-unsloth-internal-workflow` came back as `[redacted]-workflow` in source listings and test output. The suffix is hex now, which still masks a key cut in half by the context-window fit. Parity over the 1861-string corpus is unchanged at the same 25 moved verdicts.
Masking tool_end alone was not enough. The card is painted from the tool_output chunks that stream while the tool runs, and tool_end arrives afterwards, so a key was rendered in full and persisted that way regardless of what the final payload said. Caught by screenshotting the card: the output block showed the key with [redacted] on the line below it. Mask each chunk as it is emitted. A key can straddle a chunk boundary, where a per-chunk regex sees two halves that each match nothing and prints both, so _hold_back_partial_secret defers a tail that may still be an open credential token into the next chunk. It also defers a tail that is only a partial PREFIX (...sk-unslo), which no search for the complete marker can see. The carry is flushed when the stream ends or is capped, so deferred text that turns out to be ordinary is emitted rather than swallowed. Regression test covers whole, mid-token, mid-prefix and surrounded spellings, a chunk larger than the scan tail, and the two no-secret cases that must pass through byte for byte.
|
Following up on the masking item with something the unit tests did not catch. I screenshotted the tool card before and after, and the first version of this change was incomplete. Fixed in d268dd5 by masking each chunk as it is emitted. The part worth reviewing is the boundary handling: a key can straddle two chunks, where a per-chunk regex sees two halves that each match nothing and prints both. Regression test covers whole, mid-token, mid-prefix and surrounded spellings, a chunk larger than the scan tail, and the two no-secret cases that must pass through byte for byte. |
The tool cwd is <studio home>/sandbox/<session>, a sibling of the auth directory, so
`open('../../auth/auth.db')` reads the protected database while naming neither the
directory nor a credential basename. Bypass Permissions skips the blocklist, so this guard
was the only thing left, and it only saw the unresolved text.
The two executors now resolve the `..` tokens of a command against the cwd they are about
to use, and refuse when one of them lands in the auth directory. Only traversal is
resolved: a relative path without `..` stays inside the sandbox, which is not where the
credentials are, and the whole step is skipped for a command that contains no `..` at all,
so the ordinary command pays nothing. Traversal that lands anywhere else, `cat
../notes.txt`, `ls ../../models`, still runs.
|
@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: 249ac1b72e
ℹ️ 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".
| _PY_TREE_COPY_CALLS = frozenset({"copytree", "make_archive", "copy_tree", "unpack_archive"}) | ||
| # A recursive WALK of the root reaches `auth/` the same way a copy of it does, and reading | ||
| # what it yields prints the secrets without any of them being named. | ||
| _PY_TREE_WALK_CALLS = frozenset("walk rglob glob iglob iterdir listdir scandir".split()) |
There was a problem hiding this comment.
Exclude shallow listings from the recursive root guard
When Python calls os.listdir(os.environ["UNSLOTH_STUDIO_HOME"]) (or scandir/Path.iterdir) to inspect the Studio installation, this set causes _python_copies_the_studio_root to classify the call as a recursive credential read and _python_exec refuses it even in Bypass Permissions mode. These APIs enumerate only the root's immediate entries and do not read anything inside auth, matching the terminal path's explicitly allowed plain root listing; reserve this unconditional refusal for genuinely recursive APIs such as walk and rglob, or trace a subsequent read separately.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, and fixed in the latest commit. A shallow listing returns the root's own entry names and opens nothing inside auth, so os.listdir, scandir and Path.iterdir are no longer treated as recursive reads, matching what the terminal side already allowed for a plain root listing. glob and iglob now count only when the pattern descends (**), while walk and rglob still do. Allowed and refused rows added both ways.
|
@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: 0e4fa12fbd
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if _names_the_studio_home_env(argument): | ||
| return True | ||
| folded = _folded_path(argument) | ||
| if isinstance(folded, str) and folded and _folded_word(folded) == folded_root: |
There was a problem hiding this comment.
Unwrap Path constructors around recursive-copy sources
In Bypass Permissions mode, a natural call such as shutil.copytree(Path(os.environ["UNSLOTH_STUDIO_HOME"]), "./leak") bypasses this check: _names_the_studio_home_env only recognizes the environment lookup itself, while _folded_path reduces the surrounding Path(...) to a dynamic marker that cannot equal folded_root. The copy consequently stages the entire auth/ directory inside the sandbox, where a subsequent tool call can read the copied auth.db; unwrap recognized path constructors, or propagate the known Studio-home value through them, before comparing the source.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 903077b. A recognised constructor wrapping the source is unwrapped before the comparison, and the binding behind it resolved, so shutil.copytree(Path(os.environ["UNSLOTH_STUDIO_HOME"]), "./leak") and the root = Path(...) spelling are both refused.
| lowered = text.lower() | ||
| return any(spelling in lowered for spelling in _studio_root_spellings()) |
There was a problem hiding this comment.
Normalize escaped spaces before matching recursive roots
When a configured Studio root contains spaces, a POSIX command such as cp -a /tmp/Studio\ Home ./leak names that root exactly after shell expansion, but this raw substring check does not match /tmp/Studio Home; _names_the_studio_root_itself likewise converts the backslash to / rather than unescaping it. The recursive guard therefore returns false and copies the protected auth/ tree in Bypass Permissions mode (GNU cp --help confirms -a implies recursive -R); apply the same escaped-space normalization already used for direct auth paths before testing root spellings.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 903077b. This one matters more than the report suggests, since the default root has a space in it. The escaped spelling is unescaped before folding, and re-joined first because the lexer runs with escapes disabled so Windows paths survive, so cp -a /tmp/Studio\ Home ./leak is refused exactly as the quoted form is. Work inside a project under the root stays ordinary, and a regression test covers both spellings.
What this fixes
The CLI caches the raw Studio API key at
$STUDIO_HOME/auth/.cli_api_key_<stem>_<digest>so a relaunch reuses it instead of minting another (#10595). The tool subprocesses run as the backend's own OS user, so the 0600 mode on that file is no boundary against them, and the sandbox does not confine absolute paths.The auto-mode classifier did not recognise that directory either:
_SENSITIVE_PATH_REcovers.ssh,.aws,/etc/shadowand friends, but nothing of Studio's own. So in the default "Approve for me" mode a model-emittedwas classified as an ordinary read, ran with no confirmation, and the plaintext bearer was appended as a
role=toolmessage and replayed to the provider on the next turn. The key is reused across launches, so it stays useful after that conversation, and it authenticates/chat/completionsand the server-side python and terminal tools in turn. The same directory also holds.bootstrap_password,.desktop_secret, the llama stream key andauth.dbwith the JWT secret.The fix
Two independent guards, so neither one has to be complete.
1. The auth directory is not tool input.
_references_studio_credentialinstudio/backend/core/inference/tools.pyrecognises.cli_api_key_*,.bootstrap_password,.desktop_secret,<dir>/llama_api_key, the default.unsloth/studio/authlayout, and the resolvedauth_root()so a customUNSLOTH_STUDIO_HOMEis covered exactly rather than guessed. It is wired into the existing_references_sensitive_path, so the terminal, python and MCP classifiers all treat these as high risk, and it refuses the call outright in_bash_exec,_python_exec,_edit_fileand MCP dispatch, before anything is spawned.That refusal holds in every permission mode, Bypass Permissions included, unlike the command blocklist. No user flow asks a tool to read Studio's own credentials, and an approval should not be able to hand them out. The refusal string names neither the path nor any value.
2. A key never leaves in a result. Any
sk-unsloth-key ordesktop-secret that reaches a tool result by some other route is masked instrip_result_for_model, which is the one transform every model-bound tool result passes through (it feedsmodel_message, so all three loops are covered). Only that copy:record_resultandtool_end_eventare untouched, so the tool card the user is looking at renders exactly as before._split_frontend_suffixopts out viaredact = False, since it subtracts the stripped body from the text and needs the strip to stay suffix-only.The cache itself is unchanged. Minting, cache identity, reuse and revocation cleanup all behave as they did, so a relaunch still reuses one key.
_write_auth_secretadditionally chmodsauth/to 0700, the way_connect_auth_dbalready does.Not breaking anything
The predicate is deliberately narrow, so ordinary work stays unprompted: an application's own
auth/package,auth.py,grep -rn auth src/,sqlite3 ./auth/auth.dband allama_api_keyvariable all match nothing. Benign counter-cases are pinned in the tests alongside the positive ones.Same tree, 4,800-test tool / inference / MCP / auth sweep, before and after:
mainThe 38 are pre-existing in this environment (missing
fastmcp, missing node, network), identical set both times.unsloth_clitests: 1416 passed, including the cached-key reuse, revoked key, corrupt cache and cache-write-failure cases. ruff clean.End to end against a temporary studio home: the
cat, thels -a, the python read and the same read under Bypass Permissions are all refused; a stray copy of a key elsewhere on disk still shows raw in the user's tool card but reaches the model as[redacted]; ordinary commands run normally.No frontend, route, schema or DB change, so Studio, Desktop and the notebooks see no behaviour difference.
Performance
Measured with the predicate stubbed to
Falsefor the "before" column:is_high_risk_tool_callterminal, 5 commandsis_high_risk_tool_callpython, 3 snippetsstrip_result_for_model, 120 B resultstrip_result_for_model, 100 KB resultThe classifier is 13% slower on the terminal corpus and 10% on the python one, which is 47 us per command and 25 us per snippet, once per tool call. Those are best-of-nine numbers on a busy host; the absolute figure is what matters, and it sits against a tool call that spawns a subprocess costing milliseconds, so it is under a percent of the call it precedes. The predicate runs per candidate token, so it sits behind a literal prefilter and the resolved auth spellings are cached as (marker, canonical marker) pairs for the process. The executor check is ~1.4 us per command, and the redaction runs once per tool result behind a substring fast path. Nothing is added to a per-token or per-request path, and no inference path is touched at all.
Tests
studio/backend/tests/test_studio_auth_guard.pyis new: refusal in both sandbox modes for terminal, python,edit_fileand MCP, a customUNSLOTH_STUDIO_HOME, nested and list-shaped MCP arguments, MCP prose left alone, redaction idempotency and the desktop secret, the_split_frontend_suffixsuffix-only invariant, and the user-facing tool card staying raw.test_permission_mode.pygains the credential paths and the benign counter-cases in its existing parametrized lists.Known limits
Path matching is static, so an obfuscated read (base64, a dynamically assembled path) is only covered by the second guard, and only for credentials with a recognisable shape. A key that has already leaked is not invalidated by this; rotating it is a separate step.
The guard is scoped to the spellings that actually occur: a path naming the auth directory or a credential basename, the environment-variable and
~forms of the studio root, a relative path that walks out of the sandbox, a directory move that lands on the root, and a recursive read or copy of the root itself. The long tail (a path assembled at runtime, an encoding the guard does not decode, a shell construct nobody writes by hand) is a stated residual rather than an oversight. This is a guard on top of the approval flow, not a filesystem boundary, and the durable fix for the tail is the OS-level sandbox.Before and after in the UI
Two isolated installs, the merge base
8760d4437and this branch atc105ec81b, each with its own Studio home and its own cached CLI key file. One scripted OpenAI-compatible provider per side on loopback, so the backend is the thing that makes the call, runs the tool and streams the card. Permission mode is the shipped default on both sides, Approve for me.The
outputblock goes from the key in full to[redacted]. The command line above it keeps the key on both sides, which is deliberate: the model wrote that command, and masking it would be rewriting the transcript rather than protecting a secret. The literal key therefore appears twice in the card after the change instead of three times, and the rest of the card, the command block, the timing, the copy and download controls, is unchanged.Worth recording that this pair is what found an incomplete fix: masking only the final
tool_endpayload left the live streamed chunk on screen with[redacted]underneath it, so the stream is masked as it goes, with a carry across chunk boundaries.