Skip to content

fix(studio): keep Studio's auth directory out of the tool loop - #10895

Merged
danielhanchen merged 95 commits into
mainfrom
studio-auth-dir-tool-guard
Sep 15, 2026
Merged

danielhanchen merged 95 commits into
mainfrom
studio-auth-dir-tool-guard

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

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_RE covers .ssh, .aws, /etc/shadow and friends, but nothing of Studio's own. So in the default "Approve for me" mode a model-emitted

terminal {"command": "cat ~/.unsloth/studio/auth/.cli_api_key_cli_<digest>"}

was classified as an ordinary read, ran with no confirmation, and the plaintext bearer was appended as a role=tool message 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/completions and the server-side python and terminal tools in turn. The same directory also holds .bootstrap_password, .desktop_secret, the llama stream key and auth.db with 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_credential in studio/backend/core/inference/tools.py recognises .cli_api_key_*, .bootstrap_password, .desktop_secret, <dir>/llama_api_key, the default .unsloth/studio/auth layout, and the resolved auth_root() so a custom UNSLOTH_STUDIO_HOME is 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_file and 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 or desktop- secret that reaches a tool result by some other route is masked in strip_result_for_model, which is the one transform every model-bound tool result passes through (it feeds model_message, so all three loops are covered). Only that copy: record_result and tool_end_event are untouched, so the tool card the user is looking at renders exactly as before. _split_frontend_suffix opts out via redact = 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_secret additionally chmods auth/ to 0700, the way _connect_auth_db already 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.db and a llama_api_key variable 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:

failed passed
main 38 4792
this branch 38 6520

The 38 are pre-existing in this environment (missing fastmcp, missing node, network), identical set both times. unsloth_cli tests: 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, the ls -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 False for the "before" column:

before after
is_high_risk_tool_call terminal, 5 commands 1760 us 1996 us
is_high_risk_tool_call python, 3 snippets 725 us 800 us
executor entry check, 5 commands - 7 us
strip_result_for_model, 120 B result 0.4 us 0.5 us
strip_result_for_model, 100 KB result 25 us 122 us

The 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.py is new: refusal in both sandbox modes for terminal, python, edit_file and MCP, a custom UNSLOTH_STUDIO_HOME, nested and list-shaped MCP arguments, MCP prose left alone, redaction idempotency and the desktop secret, the _split_frontend_suffix suffix-only invariant, and the user-facing tool card staying raw. test_permission_mode.py gains 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 8760d4437 and this branch at c105ec81b, 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.

Tool card before and after, at merge base 8760d4437 and head c105ec81b

The output block 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_end payload 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.

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.
@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:30.939885Z 0e4fa12 Manual request
🔒 Security Review ✅ Completed 2026-09-14T03:34:05.488260Z 8a159fe 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.

pre-commit-ci Bot and others added 3 commits September 14, 2026 03:45
…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Simulation results: what changed, what it breaks, and what it costs

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

A fake external provider emits the structured terminal call an attacker-controlled model would send. Everything else is production code: stream_with_studio_tools, execute_tool, the sandboxed bash executor, the approval gate at permission_mode="auto" with confirm_calls=True, and the conversation replay into the provider's next request. The verdict is whether the raw key text appears in the provider's second request.

command on main on this branch
cat <home>/auth/.cli_api_key_cli_<digest> no approval, ran, key in the provider's next request approval asked, then refused, no key
cat <home>/auth/.cli_api_key_* no approval, ran, key in the provider's next request approval asked, then refused, no key
ls -a <home>/auth no approval, listed the credential filenames approval asked, then refused
cat $UNSLOTH_STUDIO_HOME/auth/.cli_api_key_... ran, failed only because the child env is scrubbed refused on the text

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 echo hello-from-sim7 still returns hello-from-sim7 in all five.

Does it break ordinary work?

Classifier parity over 1,861 strings: every string literal in main's own test_permission_mode.py (the whole benign development vocabulary the suite pins) plus a hand-written list of ordinary work and of credential access in Linux, WSL, macOS and Windows spellings. Each string is classified through is_potentially_unsafe_tool_call and is_high_risk_tool_call for terminal, python and MCP, on both trees, and the two JSON dumps are diffed.

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 tool_start / tool_output / tool_end frames (the single diff was ls -la printing a file the previous test had created). No frontend file is touched, so there is nothing for Chrome, Firefox, Safari or Edge to render differently.

Two gaps the simulations found, now fixed

  1. cd <studio home> && ls -a auth reached the directory anyway: no absolute auth path, no Studio basename. The platform matrix (Linux default, custom UNSLOTH_STUDIO_HOME, venv-prefix install, legacy home, WSL, macOS default and Application Support, Windows default / custom drive / ProgramData, and an unresolvable root) caught it. The studio root is now recognised as well, 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.
  2. A key cut in half by the window fit slipped past the mask. The floor dropped from 16 characters to 8; sk-unsloth- with nothing after it still reads through.

Also added while checking the blast radius: unsloth start keeps the coding-agent keys in $STUDIO_HOME/auth/agent_api_key.json, in the clear, in the same directory. The directory patterns already covered it by path; the filename counts now too.

Robustness

3,013 pathological inputs through the predicate (1 MB strings, 100k separators, .cli_api_key_ repeated 10,000 times, random unicode, NUL, unterminated quotes): no exception, and cost is linear at about 68 ns/char, so there is no ReDoS in it. 2,000 concurrent cold-start calls across 32 threads all answer correctly. The MCP walker survives a 200-level nested payload and non-dict shapes. 18 terminal forms of the same read (cat, head, od, base64, xxd, sh -c, timeout, a pipe into curl) and 7 python forms are all refused.

Old installs and updating

An isolated uv venv with nothing but typer, pyyaml, pydantic, click and rich (so the touched CLI code needs no new dependency), on Python 3.11 rather than this box's 3.13:

scenario result
fresh install key written, file 0600, auth dir 0700, exactly one key minted
old install, 0755 auth dir, valid cached key reused, zero keys minted, cache file untouched, dir tightened to 0700
old install, revoked key re-minted once and re-cached
corrupt cache (empty, whitespace, junk, binary) replaced cleanly, launch unaffected
mode change unsupported (Windows, read-only mount) write still succeeds
file format 44 bytes, LF terminated, byte-identical to what an older CLI reads

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.

Hardware

No device code is touched: the diff is path matching, one regex substitution and a permission tighten. The guard test suite passes identically with CUDA_VISIBLE_DEVICES="" (CPU only) and with a GPU visible, and nothing in the change reads a device, a backend or a driver, so the NVIDIA / AMD / CPU axis has no branch to take. The platform axis is covered by the resolved-root matrix above, and cross-platform CI (Linux, Windows, Apple-Silicon macOS) is running on a staging repo in parallel with this comment.

Cost

Measured with the predicate stubbed to False for the "before" column, median of 7 repetitions:

before after
is_high_risk_tool_call terminal, 5 commands 1752 us 1850 us (+5.6%)
is_high_risk_tool_call python, 3 snippets 724 us 734 us (+1.4%)
predicate alone, per command - 0.63 us
strip_result_for_model, 120 B result 0.44 us 0.54 us
strip_result_for_model, 100 KB result 30 us 133 us

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 status

Same 4,800-test tool / inference / MCP / auth sweep, same tree, before and after: 38 failed / 4792 passed on main, 38 failed / 4825 passed here (+33 new tests). The 38 are pre-existing in this environment (missing fastmcp, missing node, network) and are the identical set both times. unsloth_cli: 1416 passed. ruff clean.

On the org queue, Core (HF=...) is red on main for the last eight completed runs, and the Windows Chat UI Tests lane has failed the same way on three unrelated branches in the last day (studio-prebuilt-precheck, feat/studio-compact-composer, codex/inline-mcp-image-attachments), so neither is this PR. Everything else on the first run was green, including Unsloth API and Auth Tests, the Linux Chat UI shard, Unsloth Updating Tests, the GGUF inference smoke and the Tauri build.

Known limits, unchanged

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 already leaked is not invalidated by this.

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

Copy link
Copy Markdown
Member Author

@codex security review

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

This comment was marked as resolved.

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

This comment was marked as resolved.

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

This comment was marked as resolved.

danielhanchen and others added 2 commits September 14, 2026 07:55
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.
@danielhanchen

Copy link
Copy Markdown
Member Author

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. tool_end is not the first thing the card paints: the live tool_output chunks are, and tool_end arrives after them. So the key was rendered in full and persisted that way, and the card ended up showing the key with [redacted] on the line below it rather than in its place.

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. _hold_back_partial_secret defers a tail that may still be an open credential token into the next chunk, including 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 held-back 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.

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

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

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

Comment thread studio/backend/core/inference/tools.py Outdated
_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())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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.

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.

@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: 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".

Comment on lines +3845 to +3848
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:

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

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

Comment thread studio/backend/core/inference/tools.py Outdated
Comment on lines +3028 to +3029
lowered = text.lower()
return any(spelling in lowered for spelling in _studio_root_spellings())

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

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

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