Repository navigation
studio: security and hardening pass (auth rate-limit, sandbox, path containment, schema validation, headers) - #5375
Conversation
resolve_under_root and resolve_dataset_path previously returned absolute
paths unchanged, so an authenticated client could supply
save_directory="/tmp/escape" (or any other absolute path) and have the
exporter drop adapter files anywhere the server user could write. This
turned up during a recent audit pass where an authenticated POST to
/api/export/export/lora with save_directory="/tmp/lora_escape_test"
returned 200 and wrote adapter_model.safetensors, adapter_config.json,
and tokenizer files under /tmp.
The fix is two-layered:
storage_roots.py adds an _assert_contained(resolved, root) helper that
runs after path resolution and rejects any result whose realpath does
not sit under realpath(root). resolve_under_root now rejects '..'
segments and null bytes outright, and only accepts absolute inputs when
they are already inside the configured root (internal call sites that
re-resolve a stored absolute path stay idempotent;
worker.py:resolve_output_dir(output_dir) etc. continue to work).
resolve_dataset_path picks up the same containment rule, scoped to the
three dataset roots.
models/export.py adds field_validator("save_directory", mode="before")
to ExportCommonOptions and ExportGGUFRequest so bad input fails fast at
422 with a clear message rather than a 500 deep inside the resolver.
The validator rejects empty/whitespace, null bytes, control chars,
strings longer than 255 chars, absolute paths, and '..' segments.
routes/export.py:_export_details now returns os.path.relpath(output_path,
exports_root()) so the Export Complete dialog and /api/models/loras no
longer leak the absolute install prefix to the UI; the basename is
used as a last-resort fallback.
Verified end to end:
- POST /api/export/export/lora {"save_directory":"/tmp/foo"} -> 422
"save_directory must be a name or relative path under the export
root; absolute paths are rejected". /tmp/foo is not created.
- "../../etc/escape" -> 422 "may not contain '..' segments".
- save_directory="my_subdir" -> still accepted (400 only because the
test had no checkpoint loaded yet, not because of validation).
- Internal idempotent re-resolve via resolve_export_dir(absolute path
that is already under exports_root) returns the same path unchanged.
The sandboxed Bash and Python tool channels in Chat ran with a thin
preexec hook (PR_SET_NO_NEW_PRIVS + RLIMIT_FSIZE only). Bash had a
small word blocklist; Python had an AST safety pass aimed at
signal-tampering and shell-escape primitives. An audit pass showed
several gaps that a tool-calling model could trigger inadvertently:
- bash curl/wget/nc reached AWS IMDSv2 and returned live STS
credentials for the instance role.
- python "import socket; s.connect((169.254.169.254, 80))"
reached the same endpoint regardless of the bash blocklist.
- "cat /etc/passwd" was blocked at the bash side (because "passwd"
is in the blocklist), but "open('/etc/passwd').read()" in Python
happily returned its contents.
- "chr(115)+chr(117)+chr(100)+chr(111)" style dynamic-arg
construction slipped through the AST shell-escape check.
- The supervisor used proc.kill() on timeout, which only signals
the immediate pid; bash-backgrounded children survived. A fork
bomb could spawn for the full 300s timeout window.
- Session work directories under ~/studio_sandbox/<id>/ were
created with default umask (0o755), so any other UID on the host
could enumerate them.
- session_id sanitisation used a one-shot str.replace("..",""),
which is non-iterative and a small footgun.
This commit takes a conservative middle path: the sandbox still
runs as the Studio UID with no namespace tricks where the kernel
disallows them, but every chokepoint is tightened.
_sandbox_preexec now:
- calls os.setsid() so children share a process group; the
supervisor uses os.killpg(SIGKILL) on timeout/cancel so
backgrounded children die with the parent (new _kill_process_tree
helper, wired into _cancel_watcher and both _bash_exec /
_python_exec timeout branches).
- calls os.umask(0o077) so files the child writes default to 0o600.
- applies PR_SET_PDEATHSIG=SIGKILL so an orphaned child dies if
Studio exits.
- best-effort unshare(CLONE_NEWNET) for a private network namespace
(failure is logged and swallowed; defense-in-depth is still in
place via the bash blocklist and the AST checker below).
- sets RLIMIT_NPROC=10000 (tunable via UNSLOTH_STUDIO_SANDBOX_NPROC),
RLIMIT_AS=8GB, RLIMIT_CPU=300, RLIMIT_NOFILE=1024. The 10k NPROC
figure is chosen to sit well above the ~500 LWPs a healthy Studio
+ llama-server combination already uses while still capping a
runaway fork bomb. NPROC counts LWPs per real UID, so a lower
figure (e.g. 256) starves legitimate bash forks
("bash: fork: retry: Resource temporarily unavailable").
_get_workdir:
- rejects session_id that doesn't match [A-Za-z0-9_-]{1,64};
non-matching values bucket into a shared "_invalid" dir.
- chmod 0o700 on both the workdir and on ~/studio_sandbox/ so
other UIDs cannot read another session's contents.
_BLOCKED_COMMANDS_COMMON gains: doas, pkexec, halt, poweroff, curl,
wget, nc, ncat, netcat, socat, ssh, scp, sftp, rsync, eval, source.
The intent is to keep general bash usage working (echo, ls, pipes,
loops, for, head, etc.) while denying the obvious egress and
escalation paths.
The AST checker (_check_signal_escape_patterns) is split into the
existing shell/signal/loop checks plus a new narrow IO denylist:
- Always flag non-literal args to anything in _SHELL_EXEC_FUNCS,
not just _STRING_SHELL_FUNCS. Closes the dynamic-arg bypass.
- Reject calls to socket.create_connection, socket.socket().connect,
urllib.request.urlopen, http.client.HTTP*Connection, requests.*,
httpx.* whose literal host argument is in a cloud-metadata
denylist (169.254.169.254 + 169.254.* + 100.64.*, plus the
GCP/Alibaba/ECS metadata hostnames and IPv6 link-local). Public
hosts (example.com, huggingface.co, ...) still work. Dynamic
hosts cannot be statically blocked; mitigated by the bash
blocklist + the netns where the kernel allows it.
- Reject literal open("/etc/passwd"), /etc/shadow, /etc/sudoers,
/etc/ssh/*, and /proc/<pid>/environ. Other files
(/etc/os-release, /etc/hostname, /tmp/*, user dirs) still work.
The _check_code_safety summariser is updated to include the new
network_calls and sensitive_file_reads buckets in its error string.
Regression-checked: echo, sleep, ls /tmp, for loops, piped helpers
(echo a | tr a A), urllib.request.urlopen("http://example.com"),
socket.getaddrinfo("example.com",80), open("/etc/os-release"),
open("/tmp/...","w") all still succeed. curl, wget, nc, ssh, rm,
socket.create_connection(("169.254.169.254",80)),
open("/etc/passwd"), open("/proc/self/environ") all correctly
blocked.
… headers, gate bootstrap injection
A pass over the auth surface found a cluster of related issues that this
commit closes together.
Login (routes/auth.py):
- Add an in-memory per-IP login rate limiter. Five failed POSTs to
/api/auth/login inside a 60s window produce 429 with Retry-After.
A successful login clears the bucket. Previously 30 wrong passwords
in under one second was accepted as 30x 401, which combined with
the (now fixed) admin-username leak from /api/auth/status made
brute-force trivial against a small password.
Logout (routes/auth.py):
- New POST /api/auth/logout returns 204 and calls
storage.revoke_user_refresh_tokens(subject) so the refresh token
is no longer valid. Previously POST /api/auth/logout returned 405
and there was no way to invalidate refresh tokens short of
changing the password. Frontend session.ts already calls
clearAuthTokens() to drop localStorage; the new endpoint lets the
client also tell the server to revoke server-side state.
Refresh-token rotation (routes/auth.py + auth/storage.py):
- New storage.consume_refresh_token(token) atomically validates +
deletes a refresh token, returning (username, is_desktop). The
/api/auth/refresh handler now mints both a new access AND a new
refresh token; the supplied token becomes invalid. Replaying a
consumed refresh returns 401 "Invalid or expired refresh token".
The previous refresh_access_token helper is left in place for
callers that intentionally want the non-rotating shape; nothing
in the route layer uses it now.
/api/auth/status no longer leaks default_username (models/auth.py +
routes/auth.py):
- AuthStatusResponse.default_username becomes Optional[str] with a
None default; the handler always returns None. The frontend already
hardcodes HIDDEN_LOGIN_USERNAME = "unsloth" (auth-form.tsx:82), so
no UI change is required.
window.__UNSLOTH_BOOTSTRAP__ no longer auto-injects (main.py):
- _inject_bootstrap is now opt-in via the
UNSLOTH_STUDIO_INJECT_BOOTSTRAP env var. The previous default
(inject whenever requires_password_change is true) embedded the
plaintext bootstrap password into the first-boot HTML for any
caller that hit /, /change-password, or any unknown SPA path.
Browser extensions and any XSS payload on the page could read it
trivially. With the new gate the bootstrap password lives only in
the auth/.bootstrap_password file (mode 0o600) where it has always
been; users typing it into a current-password field is the right
UX. routes/auth.py:change_password also clears
app.state.bootstrap_password defensively.
Security headers + server fingerprint (main.py + run.py):
- New SecurityHeadersMiddleware adds Content-Security-Policy,
X-Frame-Options: DENY, X-Content-Type-Options: nosniff,
Referrer-Policy: no-referrer,
Permissions-Policy: camera=(), microphone=(), geolocation=(),
interest-cohort=(), and stamps server: unsloth-studio so the
generic uvicorn banner no longer fingerprints the stack. The
uvicorn.Config gains server_header=False so it stops emitting its
own Server header.
/api/health minimisation (main.py):
- Unauthenticated GET /api/health returns just
{"status":"healthy","timestamp":...} so load-balancer liveness
probes keep working without leaking version, device_type,
chat_only, desktop_protocol_version, or studio_root_id to
arbitrary callers. A request that presents a valid Bearer token
still gets the full diagnostic payload so internal launchers and
sibling-Studio detection (which compares studio_root_id) keep
working.
Verification:
- 30 wrong-password POSTs to /api/auth/login -> first 5 = 401, 6th
through 30th = 429.
- POST /api/auth/logout with a fresh token -> 204. The matching
refresh token then fails 401.
- Login -> R1; /api/auth/refresh with R1 -> new access + R2 (R2 !=
R1); /api/auth/refresh with R1 again -> 401; /api/auth/refresh
with R2 -> still succeeds once and rotates again.
- curl /api/auth/status -> default_username: null.
- curl http://127.0.0.1/ does not contain __UNSLOTH_BOOTSTRAP__.
- curl -I / shows CSP, X-Frame-Options: DENY,
X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer,
Permissions-Policy, and server: unsloth-studio.
- curl /api/health unauthenticated -> {status, timestamp} only.
curl with Authorization: Bearer <valid> -> full payload.
- Existing /api/system, /api/models/list, /api/train/status,
/api/inference/status, /api/auth/api-keys, login flow, SPA root
all still return 200 after the changes (regression smoke).
…direct, gate _inject_bootstrap, minimise /api/health
This commit lands the main.py-side changes that share a single
middleware-registration spot. They are kept together because every
change here is either (a) a top-level middleware definition that has
to be added next to LoggingMiddleware, or (b) a route handler at the
same file-level.
SecurityHeadersMiddleware (Content-Security-Policy, X-Frame-Options:
DENY, X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer,
Permissions-Policy, server: unsloth-studio). The previous responses
emitted no CSP, no XFO, no Referrer-Policy and were stamped
server: uvicorn.
MaxBodyMiddleware rejects POST/PUT/PATCH on the inference / dataset /
data-recipe / train / export prefixes when Content-Length exceeds
UNSLOTH_STUDIO_MAX_BODY_MB (default 100). The audit hit this by
attaching a 50 MB plain-text file to a chat message and watching
Studio base64-encode it into the JSON body; uvicorn has no enforced
cap so the only previous guard was the per-file 50 MB ceiling that
data-recipe upload routes already enforce. The new middleware extends
that ceiling to the OpenAI-compat path that the Chat attachments
flow through. Verified: a 200 MB JSON POST to /v1/chat/completions
returns HTTP 413 "Request body too large (209,715,264 bytes; max
104,857,600)". A small valid request continues to reach the handler.
_inject_bootstrap is gated behind UNSLOTH_STUDIO_INJECT_BOOTSTRAP.
The previous default was to inline window.__UNSLOTH_BOOTSTRAP__ =
{username, password} into the first-boot HTML whenever
requires_password_change was true, which exposed the plaintext
bootstrap password to any browser extension, page script, or LAN
caller on -H 0.0.0.0. The bootstrap password remains in the on-disk
.bootstrap_password file (mode 0o600) where it has always lived;
users typing it into a current-password field is the right UX.
/api/health unauthenticated returns {"status":"healthy","timestamp":
...} only; the previous payload (version, device_type, chat_only,
desktop_protocol_version, supports_desktop_auth, studio_root_id,
native_path_leases_supported) is preserved for callers that present
a valid Bearer token, so internal launchers and sibling-Studio
detection (which compares studio_root_id) keep working.
/recipes -> /data-recipes 308 redirect. The Data Recipes page lives
at /data-recipes; users typing /recipes hit the SPA catch-all and
saw "Not Found". The redirect also preserves any tail path, so
/recipes/<rest> -> /data-recipes/<rest>.
Verified end to end with curl: CSP / XFO / X-Content-Type-Options /
Referrer-Policy / Permissions-Policy all present on /, server header
is now unsloth-studio (uvicorn's own banner is suppressed via
server_header=False in run.py from the auth-batch commit). Followed
the /recipes redirect lands on the SPA HTML.
POST /api/train/start accepted any value for learning_rate, batch_size,
max_steps, max_seq_length, warmup_steps, warmup_ratio, num_epochs,
save_steps, weight_decay, gradient_accumulation_steps, lora_r,
lora_alpha and lora_dropout, including -1, 0, 1e9, and non-numeric
strings like 'abc' or 'two' (which silently coerce to 0 in the
trainer). Probing showed the API returning 200 to learning_rate=-1
and batch_size=0; only max_steps had any partial clamping.
This commit adds field_validator on every numeric hyperparameter.
Bounds are chosen wide enough to span realistic single-host
configurations (B200 with 180 GB of memory comfortably fits the
upper end) while rejecting the values that always produce broken
training:
- learning_rate: parses str/float, requires 0 < lr < 1.0. Non-numeric
input raises with "learning_rate must be parseable as float (got
'abc')" instead of silently coercing to 0.
- batch_size: [1, 1024].
- gradient_accumulation_steps: [1, 4096].
- num_epochs: [1, 1000].
- max_steps: [1, 1_000_000].
- max_seq_length: [1, 131072].
- warmup_steps: [0, max_steps].
- warmup_ratio: [0.0, 1.0].
- save_steps: [0, 1_000_000].
- weight_decay: [0, 10] (typical 0..0.1).
- lora_r: [1, 512].
- lora_alpha: [1, 1024].
- lora_dropout: [0.0, 1.0).
Each validator names the offending field in its ValueError message
so the 422 response body identifies which input is bad. The
learning_rate validator returns its result as str (the schema field
type is str("2e-4") for backwards compatibility) so existing call
sites that float() the value continue to work.
Verified:
- learning_rate=-1 -> 422 "learning_rate must be > 0 (got -1.0);
typical range is 1e-6 .. 1e-3".
- learning_rate='abc' -> 422 "must be parseable as float".
- batch_size=-1 / 0 / 999999 -> 422 "batch_size must be in [1, 1024]".
- batch_size='two' -> 422 (pydantic int parser).
- max_steps=0 / -5 -> 422 "must be a positive int".
- max_seq_length=200000 -> 422 "must be in [1, 131072]".
- warmup_ratio=2.5 -> 422 "must be in [0.0, 1.0]".
- lora_dropout=1.5 -> 422 "must be in [0.0, 1.0)".
- Valid request with learning_rate='2e-4', batch_size=1, max_steps=5
passes validation and the training run starts as normal.
…tolerate Stop-button + tool-result message shapes
Three small fixes that fall under "do not let the audit findings
become user-visible papercuts".
routes/inference.py - image-decode error redaction (the audit hit
this with a 0-byte / malformed / wrong-extension image upload). The
three image-normalise sites previously raised HTTPException(400,
detail=f"Failed to process image: {e}"). When PIL raised
UnidentifiedImageError(io.BytesIO(raw)) the message string included
"<_io.BytesIO object at 0x7e40a5d7bf60>", leaking both the Python
class name (confirming the PIL/io stack) and a heap address (mildly
useful for ASLR-bypass chaining if another memory-corruption bug is
ever found). Each site now catches UnidentifiedImageError and
returns the generic "Unsupported or corrupt image format"; the
fall-through generic except returns "Failed to process image". No
exception-repr is interpolated into a response body anywhere along
these paths.
core/training/training.py - checkpoint cleanup on cancel. When a
user clicks Cancel Training, the trainer flips _cancel_requested=True
and the supervisor force-terminates the subprocess. The trainer
writes checkpoint-<step> directories under output_dir every
save_steps; previously these survived the cancel and accumulated on
disk (the audit recorded ~67 MB stuck after a 200-step cancel with
save_steps=20). New helper _cleanup_cancelled_checkpoints(output_dir)
globs checkpoint-<int> entries and removes them. It is gated by a
realpath containment check against outputs_root() so it cannot
accidentally rmtree anything outside the configured outputs root.
force_terminate() invokes the helper after the subprocess join when
_cancel_requested is true. Stop-and-Save runs are unaffected because
that path keeps _cancel_requested=False.
models/inference.py - chat message shape tolerance. Two related
frontend interactions used to crash the request validator:
- After the Stop button truncates a generation, the frontend
retained {role:"assistant", content:""} in the conversation
history and replayed it on the next send. ChatMessage previously
required role="assistant" to have non-empty content or tool_calls,
so the next message returned 422 and the thread was permanently
broken. The validator now normalises empty assistant content to
None so the request round-trips and the trailing empty turn can
be ignored downstream.
- The frontend's second-round tool POST drops the streamed
tool_call_id, hitting the strict-spec check "role=tool requires
tool_call_id". The validator now synthesises an opaque id
(call_<8 hex>) when missing, so the request reaches the handler
and the model's final summarising response gets generated. The
proper fix lives in the frontend (carry the streamed id through
the second POST) and will follow.
Verified end to end with curl: HTTP 400 (model not loaded) on both
the empty-assistant history shape and the tool-result-without-id
shape, instead of HTTP 422 from the schema validator.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9b447140b7
ℹ️ 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".
| self.content = None | ||
| if not self.content and not self.tool_calls: | ||
| raise ValueError( | ||
| 'role="assistant" messages require either "content" or "tool_calls".' | ||
| ) | ||
| # Tolerate the post-Stop sentinel rather than 422-ing. | ||
| pass |
There was a problem hiding this comment.
Drop empty assistant messages before passthrough
When a stopped Studio turn leaves content: "", this now rewrites the assistant message to content = None and accepts it. That is only safe on the non-passthrough path: _extract_content_parts drops None content, but the GGUF passthrough path builds messages with m.model_dump(exclude_none=True), so the same history becomes {"role":"assistant"} and is forwarded to llama-server whenever passthrough is selected (for example tool-capable GGUF requests with tools or response_format). Filter these empty assistant sentinels before passthrough too, otherwise the retry after Stop can still fail upstream instead of recovering.
Useful? React with 👍 / 👎.
| cl = request.headers.get("content-length") | ||
| if cl: | ||
| try: | ||
| declared = int(cl) | ||
| except ValueError: | ||
| declared = None | ||
| if declared is not None and declared > _MAX_BODY_BYTES: |
There was a problem hiding this comment.
Enforce body limit for chunked uploads
This cap only rejects requests that declare an oversized Content-Length; if a client omits it or uses Transfer-Encoding: chunked, the middleware falls through and the downstream JSON/file handlers can still read an unbounded body on these protected endpoints. That preserves the OOM vector this middleware is meant to close for any streaming HTTP client, so the middleware needs to count bytes from the request stream (or reject missing/invalid lengths for write endpoints) rather than relying solely on the header.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Code Review
This pull request implements extensive security hardening across the backend, including token rotation with single-use refresh tokens, login rate limiting, and enhanced sandboxing for tool execution using network namespaces and resource limits. Key improvements involve stricter AST-based code safety checks to block sensitive file access and cloud-metadata calls, as well as the addition of security headers and request body size limits. Feedback highlights a potential race condition in the refresh token consumption logic that could allow concurrent reuse and suggests tightening the Content Security Policy by removing 'unsafe-inline' from the script-src directive to better mitigate XSS risks.
| # Atomically remove so the token cannot be replayed. | ||
| conn.execute("DELETE FROM refresh_tokens WHERE id = ?", (row["id"],)) | ||
| conn.commit() | ||
| return row["username"], bool(row["is_desktop"]) |
There was a problem hiding this comment.
There is a race condition here that could allow a refresh token to be used multiple times concurrently. The current implementation of SELECT followed by DELETE is not atomic. Two parallel requests could both successfully SELECT the same token before either one DELETEs it, defeating the purpose of token rotation.
To fix this, you should check the rowcount of the DELETE operation to ensure that only one request successfully consumes the token.
| # Atomically remove so the token cannot be replayed. | |
| conn.execute("DELETE FROM refresh_tokens WHERE id = ?", (row["id"],)) | |
| conn.commit() | |
| return row["username"], bool(row["is_desktop"]) | |
| # Atomically remove so the token cannot be replayed. | |
| delete_cur = conn.execute("DELETE FROM refresh_tokens WHERE id = ?", (row["id"],)) | |
| conn.commit() | |
| if delete_cur.rowcount == 0: | |
| # The token was consumed by a concurrent request after the SELECT. | |
| return None | |
| return row["username"], bool(row["is_desktop"]) |
| "style-src 'self' 'unsafe-inline'; " | ||
| "script-src 'self' 'unsafe-inline'; " |
There was a problem hiding this comment.
The Content-Security-Policy allows 'unsafe-inline' for script-src. This significantly reduces protection against Cross-Site Scripting (XSS) attacks, as it allows the execution of inline <script> blocks and inline event handlers.
While the PR description mentions this is needed for inline styles, allowing it for scripts is more dangerous. Consider using a stricter policy, for example by using nonces or hashes for any required inline scripts. This would provide stronger protection against XSS.
Trim verbose docstrings and inline finding references added in the previous commits in this branch. Functionality unchanged.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 35dc412b60
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| subject = _gcs(creds) # type: ignore[arg-type] | ||
| if not subject: |
There was a problem hiding this comment.
Await token validation before returning full health payload
The new auth gate in /api/health calls the async dependency get_current_subject without await, so subject becomes a truthy coroutine object instead of a validated principal. In practice, any request that includes an Authorization: Bearer ... header (even an invalid token) will pass this check and receive the full diagnostic payload (version, device_type, studio_root_id, etc.), which bypasses the intended auth hardening.
Useful? React with 👍 / 👎.
…en consumption atomic The /api/health auth probe called get_current_subject(creds) without awaiting it. The coroutine object is truthy, so any caller presenting a Bearer header (valid or not) received the full diagnostic payload including version, device_type, studio_root_id, etc. Await the coroutine and treat HTTPException as 'fall back to the minimal liveness payload'. consume_refresh_token did SELECT then DELETE WHERE id under default autocommit isolation. Two concurrent POST /api/auth/refresh requests could both win the SELECT before either DELETE ran, defeating single-use refresh-token rotation. Replace with a single DELETE ... WHERE token_hash = ? AND expires_at >= ? RETURNING ... statement so the validate-and-delete lands as one atomic op under SQLite's write lock (3.45.1 supports RETURNING; min was 3.35).
…om script-src MaxBodyMiddleware previously only inspected the declared Content-Length header; clients omitting it or sending Transfer-Encoding: chunked bypassed the cap and could still drive an OOM via the downstream JSON / file readers on /v1/chat/completions, /api/inference, /api/data-recipe, /api/datasets, /api/train, /api/export. Rewrite as a raw ASGI middleware that drains and counts http.request frames, replies 413 once the running total exceeds UNSLOTH_STUDIO_MAX_BODY_MB before invoking the FastAPI handler, and replays the buffered body to downstream so route code that calls request.json() / await request.body() works unchanged. CSP previously included 'unsafe-inline' on script-src, which defeats the main XSS protection. The frontend bundle does not need inline scripts; the only inline <script> the backend ever emits is _inject_bootstrap, which is opt-in via UNSLOTH_STUDIO_INJECT_BOOTSTRAP. Drop 'unsafe-inline' from script-src by default; when _inject_bootstrap fires, generate a per-response nonce, embed it on the inlined <script>, and have SecurityHeadersMiddleware splice 'nonce-XXX' into the CSP for that one response (the internal x-internal-script-nonce header is popped before the response leaves the server). 'unsafe-inline' stays on style-src for Vite-injected styles.
ChatMessage._validate_role_shape normalises role="assistant", content=""
(the post-Stop sentinel emitted by the frontend) to content=None so the
in-process path can drop it via _extract_content_parts. The passthrough
path then ran m.model_dump(exclude_none=True), which strips the now-None
content key entirely, sending {"role":"assistant"} to llama-server / the
OpenAI-compat backend. That fails upstream and leaves the user without a
recoverable Stop->resume.
Add _drop_empty_assistant_sentinels and call it at both passthrough
message origins: _openai_messages_for_passthrough (covers
/v1/chat/completions and the Responses API which routes through it) and
the anthropic_messages_to_openai output before
_anthropic_passthrough_*. Assistant messages that carry only tool_calls
(no content) are preserved.
Adds and updates pytest coverage for the four bot-flagged audit fixes landed earlier in this branch and rebases two pre-existing tests that were broken by the relaxed-validator and /api/health auth-gate changes. studio/backend/tests/test_middleware.py (new) MaxBodyMiddleware: small protected, large declared, unprotected passthrough, chunked-upload-over-cap rejection (the regression for the original Content-Length-only gap), and chunked-under-cap replay. SecurityHeadersMiddleware: script-src no longer carries 'unsafe-inline', style-src still does, default headers (XFO/XCTO/Referrer-Policy/Permissions-Policy/server), and the internal x-internal-script-nonce header is consumed by the middleware and converted to 'nonce-XXX' in the CSP. /api/health: no auth -> minimal, invalid Bearer -> minimal (the await regression), valid Bearer -> full diagnostic payload. studio/backend/tests/test_desktop_auth.py consume_refresh_token: second-call returns None, expired returns None, and a 64-thread concurrent pile-up against the same hash produces exactly one successful consumer (regression for the SELECT-then-DELETE race). test_health_response_reports_desktop_capability_fields: rebase against the new health_check(request) signature by going through TestClient with a real bearer instead of asyncio.run-ing the handler directly. studio/backend/tests/test_openai_tool_passthrough.py Pin the new ChatMessage tolerance: assistant without content or tool_calls is tolerated (normalises content -> None), empty-string and empty-list assistant content normalise to None, and a missing / empty tool_call_id on role='tool' is synthesised as call_<hex> rather than raising. Tests for _drop_empty_assistant_sentinels cover the three drop shapes (empty string, empty list, missing content key), preservation of assistant text and tool_calls-only messages, and end-to-end through _openai_messages_for_passthrough. studio/backend/main.py SecurityHeadersMiddleware.dispatch used response.headers.pop(...) for the nonce-header handoff; Starlette's MutableHeaders has no pop. Read-then-del so the internal handoff header is still stripped before the response leaves the server.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 229100a2aa
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| DELETE FROM refresh_tokens | ||
| WHERE token_hash = ? AND expires_at >= ? | ||
| RETURNING username, is_desktop |
There was a problem hiding this comment.
Add SQLite fallback for refresh-token consumption
consume_refresh_token now unconditionally uses DELETE ... RETURNING, which is only available on SQLite >= 3.35. The project advertises Python >=3.9 support, and common Python 3.9 environments (for example Ubuntu 20.04 system builds) still link against older SQLite, so this statement raises sqlite3.OperationalError and turns /api/auth/refresh into a 500 for all users on those installs. Please add a compatibility path (feature-detect RETURNING once, then fall back to a transactional SELECT+DELETE) so refresh remains functional on supported runtimes.
Useful? React with 👍 / 👎.
…anch CI on PR #5375 was red on three tests that were tuned for behaviour predating this branch. Updates each so the assertions match what the audit fixes intentionally changed; no production code touched. studio/backend/tests/test_trained_model_scan.py test_scan_trained_models_includes_lora_and_full_finetune_outputs passed an absolute tmp_path through scan_trained_models, which now runs resolve_output_dir / _assert_contained against outputs_root(). Repoint outputs_root() at tmp_path via monkeypatch so the fixture dirs land under the configured root and the realpath containment check passes. tests/test_studio_install_workspace_guard.py test_health_endpoint_exposes_studio_root_id_not_raw_path read the first 1500 bytes after @app.get("/api/health") and asserted on the studio_root_id literal. The handler grew (unauth short-circuit + await dependency gate) and the literal slid past the byte window. Replace the fixed window with a slice up to the next top-level @app.* decorator so the test surveys the whole handler regardless of size. tests/studio/studio_api_smoke.py The "login burst (5x wrong pw) -> 401 each" assertion was tagged "When/if we add one, this assertion updates in the same PR." We added the per-IP rate-limit in routes/auth.py (_LOGIN_MAX_FAILS=5/60s) but missed the assertion update. Rewrite the burst probe to observe the new invariant: at least one 401, eventual transition to 429, and Retry-After present on the 429. Adds a small _login_with_headers helper since the existing login() helper drops response headers.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f50a708e10
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if not auth.lower().startswith("bearer "): | ||
| return minimal |
There was a problem hiding this comment.
Preserve legacy health fields for unauthenticated probes
Returning early for requests without a Bearer token strips service, desktop_protocol_version, supports_desktop_auth, and studio_root_id from /api/health, but existing launch/probe code still depends on those fields without auth (for example install.sh::_check_health matches service + studio_root_id, and studio/src-tauri/src/preflight.rs rejects health payloads missing service/desktop capability fields). With this change, those callers treat a healthy backend as unavailable or stale, which can break backend attach/preflight flows before any token exists.
Useful? React with 👍 / 👎.
…tudios The Chat UI Playwright test drives the first-boot change-password form, which (per playwright_chat_ui.py step "1. Change-password through the UI") pre-seeds the hidden current_password field from window.__UNSLOTH_BOOTSTRAP__. That global is only emitted when the backend's _inject_bootstrap path fires, which since the security pass on this branch is gated behind UNSLOTH_STUDIO_INJECT_BOOTSTRAP and defaults to off. Without the global, the React form's current_password validator never satisfies, the submit button stays disabled, and the composer.wait_for() probe times out on /change-password. Re-enable injection only for the CI Studios that drive the chat UI across linux/mac/windows. Production deployments are unaffected: the env var has to be explicitly opted into, and the on-disk auth/.bootstrap_password remains the source of truth for human users typing the password in by hand. Covers all eight Studio launch sites: the primary chat-ui boot and the "extra UI tests" boot for each of the three OSes, plus the pipeTransport JSON-crash retry relaunches in the macOS workflow that re-spawn Studio mid-job. A follow-up frontend PR will add a visible current_password input so the form satisfies its own validator without needing the bootstrap auto-fill at all; once that lands this CI knob can come back out.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2a517d67b6
ℹ️ 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".
| "yes", | ||
| "on", | ||
| ): | ||
| return html_bytes, None |
There was a problem hiding this comment.
Keep first-boot password change reachable
With the default env unset, this returns the SPA without window.__UNSLOTH_BOOTSTRAP__, but the existing change-password form only renders new/confirm password inputs and disables submit until currentPassword is non-empty via that bootstrap value (auth-form.tsx computes it from password || window.__UNSLOTH_BOOTSTRAP__?.password). On a fresh install where must_change_password is true, users are redirected to /change-password but have nowhere to enter the on-disk bootstrap password, so the UI cannot complete first-time setup unless they know to set this hidden env var.
Useful? React with 👍 / 👎.
| self._proc.terminate() | ||
| proc = self._proc | ||
| cancelled = self._cancel_requested | ||
| output_dir = self._output_dir |
There was a problem hiding this comment.
Preserve the cancel output dir before cleanup
In the cancel-and-reset path, force_terminate() snapshots _output_dir before waiting for the pump thread, but _output_dir is only assigned from a complete event and cancelled workers send output_dir=None for save=False; for normal new runs this means output_dir is still None here and the new _cleanup_cancelled_checkpoints() block is skipped. Cancelling a run with periodic checkpoints therefore still leaves checkpoint-* directories behind, which is the disk leak this change is intended to remove.
Useful? React with 👍 / 👎.
…t; block sandbox file uploads; raise CPU rlimit default to 600 s
CLONE_NEWNET inside _sandbox_preexec silently killed every outbound
HTTP request from sandboxed Python whenever the kernel allowed
unprivileged user namespaces. requests.get('https://huggingface.co'),
urllib.request.urlopen('https://en.wikipedia.org/wiki/...'),
socket.connect(('arxiv.org', 443)) all failed despite the AST visitor
intending to allow them. The bash blocklist (curl / wget / nc / ssh /
scp / sftp / rsync / socat / eval / source) plus the AST-level
metadata-host denylist still carry the network policy after this
change; CLONE_NEWNET was redundant with both.
Add _TRUSTED_PUBLIC_HOST_LITERALS + _TRUSTED_PUBLIC_HOST_SUFFIXES
(~100 informational hosts: Wikipedia language subdomains, Wikimedia,
Wikidata, Google search, Bing, DuckDuckGo, HuggingFace, GitHub,
raw.githubusercontent.com, arXiv, StackOverflow / Stack Exchange,
MDN, docs.python.org, PyTorch / TensorFlow / NumPy / pandas docs,
pypi / files.pythonhosted.org / npmjs / crates.io, ReadTheDocs,
arXiv, Britannica, BBC / Reuters / Nature / Science, NASA / CDC /
NIH / WHO open data, api.weather.gov). The visitor now blocks
literal hosts that are neither metadata nor trusted with a short
LLM-readable string so the model can retry with an allowed source
instead of choking on a multi-line error.
Block upload-shape calls regardless of host: requests.post / put /
patch / delete / request with files= or data=open(...) /
data=bytes_literal; httpx equivalents; urllib.request.urlopen /
Request with data=...; HuggingFace upload_file / upload_folder /
upload_large_folder / create_commit (module-level FQ paths AND
method-name match on any receiver). Message: "Blocked: file upload
disallowed in sandbox".
Bump UNSLOTH_STUDIO_SANDBOX_CPU_S default 300 -> 600 s so long
agentic chains that span multiple tool calls don't get SIGXCPU'd
mid-stride. Env-var override path is unchanged.
Host normalisation now strips trailing dot, userinfo @, and explicit
port before allowlist / denylist comparison so trailing-DNS-dot,
userinfo-smuggling, and explicit-:443 URLs are decided correctly.
UNSLOTH_STUDIO_MAX_BODY_MB default goes 100 -> 500 to comfortably cover vision + audio + multi-recipe-batch JSON payloads. The MaxBodyMiddleware stream-counting logic from this branch's earlier 06ec088 already handles chunked bodies up to the new cap; env-var override path is unchanged for callers that want a tighter limit.
This branch's earlier b39e9a4 changed default_username to None on the public /api/auth/status endpoint so the username field didn't leak to unauthenticated callers. In practice this regressed third-party clients (and the in-tree React login form's pre-fill UX) without adding meaningful security: the bootstrap password is the actual secret, and the username 'unsloth' is the documented default. Pin default_username to storage.DEFAULT_ADMIN_USERNAME ('unsloth') and tighten the response model so the field is required rather than Optional. Anyone who needs anonymisation can still reach for an allow-list deployment with auth disabled.
…pha caps This branch's 7102815 introduced field validators with conservative caps. The follow-up loosens them so long-context experiments and high-rank LoRA exploration aren't gated at the schema layer: _MAX_BATCH_SIZE 1024 -> 4096 _MAX_SEQ_LENGTH 131_072 -> 2_000_000 (2M tokens) lora_r cap 512 -> 16_384 (_MAX_LORA_R) lora_alpha cap 1024 -> 32_768 (_MAX_LORA_ALPHA) _MAX_GRAD_ACCUM / _MAX_STEPS / _MAX_EPOCHS / lora_dropout / warmup_ratio / weight_decay are unchanged. Hardware (VRAM, host RAM, kernel launch latency) is now the binding constraint at the new caps, which is the correct ordering -- the validator stays a sanity check on -1 / 0 / 'abc' style garbage, not a usability gate.
…g caps
studio/backend/tests/test_sandbox_tools.py (new):
TestMetadataHostDenylist -- short "Blocked: cloud-metadata host"
message on AWS IMDS, GCP metadata,
Alibaba ECS, AWS IPv6 IMDS, 169.254/16.
TestTrustedHostAllowlist -- Wikipedia (any language subdomain),
Google, DuckDuckGo, HF, raw GitHub,
arXiv, StackOverflow / family,
MDN, docs.python.org, pypi, BBC,
api.weather.gov, NumPy / PyTorch docs.
TestUntrustedHostBlock -- example.com / random unlisted host
rejected with the short "Blocked: host
not in sandbox allowlist; use an
allowed informational source" message.
Dynamic URLs (computed var) still pass
-- documented limit of static analysis.
TestHostNormalization -- trailing dot, explicit :443, uppercase,
userinfo-@-smuggle all decided
correctly without false-block /
false-pass.
TestUploadDenylist -- requests / httpx / urllib.urlopen with
files= / data=open / data=bytes,
HfApi().upload_file / upload_folder /
create_commit, module-level
huggingface_hub.upload_folder. POST
json= to trusted host still passes.
TestSandboxCpuRlimitDefault -- pin UNSLOTH_STUDIO_SANDBOX_CPU_S=600
default and confirm CLONE_NEWNET
source line is gone.
TestMaxBodyDefault -- pin UNSLOTH_STUDIO_MAX_BODY_MB=500
default.
studio/backend/tests/test_studio_train_validation.py (new):
Pin at-cap-accepts / over-cap-rejects boundaries for
max_seq_length=2_000_000, batch_size=4_096, lora_r=16_384,
lora_alpha=32_768 so a future regression that tightens them back
without explicit user opt-in is caught.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d2f4d70bd5
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| pgid = os.getpgid(proc.pid) | ||
| except (ProcessLookupError, PermissionError): | ||
| pgid = None | ||
| if pgid is not None: | ||
| try: |
There was a problem hiding this comment.
Guard process-group kill path on Windows
_kill_process_tree unconditionally calls os.getpgid/os.killpg, but those APIs are Unix-only. On Windows, a timeout or cancel path in _python_exec/_bash_exec will hit this function, raise AttributeError, and skip terminating the subprocess tree, which leaves runaway tool processes and returns an execution error instead of a clean timeout/cancel result.
Useful? React with 👍 / 👎.
| if fq and any(fq.startswith(p) for p in _NETWORK_FQ_PREFIXES): | ||
| # 1) Upload-shape check (host-independent). | ||
| if _call_is_upload_shape(node, fq): |
There was a problem hiding this comment.
Enforce host checks for session-based HTTP calls
The network policy only evaluates calls whose function name starts with hardcoded module-qualified prefixes (for example requests.get), so literal-host calls through session objects (for example s = requests.Session(); s.get("http://169.254.169.254")) bypass both metadata-host blocking and the trusted-host allowlist. This creates a straightforward path around the new sandbox egress restrictions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4513928de4
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| # Frontend's second-round POST drops the streamed id; | ||
| # synthesise one so the request round-trips. | ||
| import secrets as _secrets | ||
|
|
||
| self.tool_call_id = f"call_{_secrets.token_hex(8)}" |
There was a problem hiding this comment.
Preserve tool call linkage instead of generating random IDs
For role="tool" messages missing tool_call_id, this validator now injects a random call_<hex> value, which breaks correlation with the preceding assistant tool_calls IDs in the same history. In the common retry/second-POST path where the frontend drops the original ID, passthrough OpenAI-compatible backends can reject or ignore the tool result because the tool message no longer references any announced tool call. It is safer to recover the actual pending ID from context (or keep the validation error) than to synthesize an unrelated one.
Useful? React with 👍 / 👎.
| try: | ||
| storage.revoke_user_refresh_tokens(current_subject) | ||
| except Exception: | ||
| pass |
There was a problem hiding this comment.
Fail logout when refresh-token revocation errors
The logout handler swallows all exceptions from revoke_user_refresh_tokens and still returns 204, so callers can be told logout succeeded even when refresh tokens were not actually invalidated (for example on SQLite write/lock failures). In that case a stolen/active refresh token remains usable after “logout”, which defeats the endpoint’s security contract.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 74456325a5
ℹ️ 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 fq and any(fq.startswith(p) for p in _NETWORK_FQ_PREFIXES): |
There was a problem hiding this comment.
Resolve import aliases before applying network policy
When sandboxed Python uses common aliases such as import requests as r; r.get("http://169.254.169.254/") or from requests import get; get(...), the computed fq is r.get/get, so this prefix check never runs and the literal metadata/untrusted-host URL is allowed through. This bypasses the new sandbox egress restrictions for ordinary alias imports; the AST pass needs to track imported aliases (or otherwise recognize these call targets) before deciding whether to enforce the host allowlist.
Useful? React with 👍 / 👎.
Resolves conflicts with #5341 (Tauri release hardening): - studio/backend/main.py: keep new supports_desktop_backend_ownership field with a one-line comment. - studio/backend/run.py: keep main's _ReadyServer / ready_event / startup_failed scaffolding; drop the trimmed server_header comment in favour of a one-line restatement next to the config call.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 35362cffc0
ℹ️ 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".
| "img-src 'self' data: blob: https://t0.gstatic.com " | ||
| "https://t1.gstatic.com https://t2.gstatic.com " | ||
| "https://t3.gstatic.com; " | ||
| "connect-src 'self'; " |
There was a problem hiding this comment.
Allow Hugging Face API connections in CSP
When Studio is served by this backend, this connect-src 'self' blocks the frontend’s direct Hugging Face searches: use-hf-model-search.ts calls listModels(..., fetch: withPopularitySort) and use-hf-dataset-search.ts calls listDatasets(..., fetch: withTrendingSort), which issue browser fetches to https://huggingface.co. In that browser-served workflow the model/dataset pickers will fail before the user can select or download anything; add the HF origins needed by these hooks (or proxy those calls through same-origin endpoints).
Useful? React with 👍 / 👎.
The UNSLOTH_STUDIO_INJECT_BOOTSTRAP gate added an extra terminal-to-browser copy-paste on every fresh install. In practice the LAN credential leak it guarded against is narrow: the password is one-time, the user rotates it on the very next click, the default Studio bind is 127.0.0.1, and -H 0.0.0.0 already exposes the entire API surface. Drop the gate so the inject fires whenever a bootstrap password is still pending. The CSP nonce wiring stays in place; the inline script remains the only inline script the backend ever emits. The three Playwright UI smoke workflows lose their UNSLOTH_STUDIO_INJECT_BOOTSTRAP=1 lines along with the explanatory comment blocks since the inject now happens by default.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6b14f12b34
ℹ️ 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 node.args: | ||
| a0 = node.args[0] | ||
| if isinstance(a0, ast.Constant) and isinstance(a0.value, str): | ||
| url_arg = a0.value |
There was a problem hiding this comment.
Enforce host policy for computed URLs
When sandboxed Python builds the URL in a variable or f-string and passes that name to a network API, this branch only recognizes an inline string literal, leaves host_arg as None, and appends no network_calls; because _sandbox_preexec leaves normal networking enabled, a call like u = "http://169.254.169.254/latest"; requests.get(u) bypasses the new metadata/untrusted-host policy. Please resolve simple constants through assignments or reject non-literal URL arguments for these network APIs.
Useful? React with 👍 / 👎.
Why the existing sandbox-hardening code is edited (FA3 rationale): - `_sandbox_preexec` (tools.py:241) and its `_libc.prctl(PR_SET_NO_NEW_PRIVS)` block (tools.py:257-260) were introduced by unslothai#4827 / unslothai#5375 to harden tool subprocesses. That contract is preserved: the original function is renamed to `_sandbox_preexec_impl(apply_no_new_privs)` and a same-named `_sandbox_preexec()` wrapper calls it with `apply_no_new_privs=True`, so every direct caller still sets NNP. The new `_sandbox_preexec_for_bwrap()` skips NNP only on the Linux+bwrap path where bwrap itself reapplies NNP to the inner payload (setuid-helper bwrap installs cannot acquire helper privileges if NNP is set before execve). Net result: the inner sandboxed program still runs with NNP=1. - The `if sys.platform != "win32": popen_kwargs["preexec_fn"] = ...` / `else: popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW` blocks in `_python_exec` (tools.py:1615-1618) and `_bash_exec` (tools.py:1709-1712) come from unslothai#4827. They are reorganised, not removed: the non-Windows path still sets `preexec_fn` and the Windows path still sets `CREATE_NO_WINDOW`. The only behavioural delta is the bwrap branch (Linux + sandbox_available()) selecting `_sandbox_preexec_for_bwrap` per above. - `_workdirs[key] = workdir` (tools.py:348) from #4416 is replaced with `_workdirs[key] = os.path.realpath(workdir)`. Same caching behaviour; the realpath normalization is required because the bwrap argv binds `os.path.realpath(workdir)` while `tempfile.mkstemp(dir=workdir)` builds tmp_path from the non-realpath value, so on hosts where HOME or a parent is a symlink the script path passed via inner_argv is not reachable inside the sandbox namespace. studio/backend/core/inference/sandbox.py - Narrow Linux /etc bind from the whole directory to a runtime allowlist (hosts, resolv.conf, nsswitch.conf, localtime, ld.so.cache, ld.so.conf and ld.so.conf.d, ssl, ca-certificates, pki) so sandboxed tools cannot read sshd_config, machine-id, cloud-init data, etc. - Narrow Seatbelt /private/etc the same way; replace the broad subpath with literal entries for hosts, resolv.conf, nsswitch.conf, localtime, protocols, services and subpaths for ssl and ca-certificates. - Constrain Seatbelt allow process-exec to the same subpaths already used in file-map-executable so sandboxed Python cannot exec arbitrary system binaries such as osascript. - Remove allow file-read and file-write on literal /dev/tty from the Seatbelt profile; tool output is captured via PIPE and there is no legitimate path that needs to bypass it. - Gate site.getusersitepackages() behind UNSLOTH_STUDIO_SANDBOX_ALLOW_USER_SITE=1 so the sandbox no longer binds the real ~/.local/lib subtree by default (HOME is already rewritten to workdir for the child). - Resolve _BWRAP_PROBE_BIN via shutil.which at module load with the /usr/bin/true fallback, so the probe works on Alpine and BusyBox layouts that place coreutils under /bin instead of /usr/bin. - Replace the unreachable _linux_bwrap_path-or-bwrap fallback with an assertion that names the sandbox_available contract; same for the unreachable RuntimeError in build_sandbox_argv. studio/backend/run.py - Run sandbox_available on a background thread with a 2s bounded wait. On hardened kernels (unprivileged_userns_clone=0) the probe hangs for its full 5s timeout; running it inline delayed the access banner. The probe still runs (and caches) eagerly; if it has not reported back within 2s the banner is printed first and the unavailable notice is suppressed for this call.
* studio: expose launcher capability bits on unauth /api/health PR #5375 reduced the unauthenticated /api/health response to {status, timestamp} only, on the theory that the rest of the payload was useful fingerprinting. That was too aggressive: the Tauri watchdog reads `service == "Unsloth UI Backend"` and `studio_root_id` to re-adopt its own backend across restarts (src-tauri/src/desktop_backend_owner.rs and commands.rs), and the SPA bootstrap fetches the same payload unauth to detect chat-only mode and native path lease support before any token is available (frontend src/config/env.ts and features/native-intents/use-native-readiness.ts). With the post-#5375 shape, the watchdog kills its own healthy backend, the SPA never flips out of "full Studio" mode on chat-only Linux/Windows, and the About tab shows "dev" in place of the real version. The actual fingerprint-ish fields are `version` / `studio_version` / `device_type` (and to a lesser extent the hostname inside `device_type`). `service`, `studio_root_id` (already a hex digest of the install path, not the raw path), `chat_only`, the desktop_* capability flags, and `native_path_leases_supported` do not leak the install path or version. This patch keeps the auth gate but rebalances which fields sit on each side of it: unauth service, studio_root_id, chat_only, desktop_protocol_version, desktop_manageability_version, supports_desktop_auth, supports_desktop_backend_ownership, native_path_leases_supported, desktop_owner (when present) authed + version, studio_version, device_type Existing must-change-password sessions still fall through to the base payload because get_current_subject (strict) rejects them; that matches prior behaviour. test_middleware.py is updated to pin the new contract: launcher bits present unauth, fingerprint fields present only with a valid bearer. * studio: complete launcher-bits health unauth contract on Tauri + About tab Reviewer follow-ups to the unauth /api/health launcher bits split. Tauri preflight: backend_capability_stale_reason() fell through to backend_version_stale_reason(health.version.as_deref()) when capability bits were present but version was absent. With the unauth payload now exposing service + studio_root_id + desktop_* bits but gating version behind a bearer, the desktop watchdog was reading the new payload, parsing all capability bits, then classifying the same-root backend as desktop_backend_version_missing and refusing to adopt it. A backend that exposes desktop_protocol_version=1, desktop_manageability_version>=1, supports_desktop_auth=true and supports_desktop_backend_ownership=true was introduced together with MIN_DESKTOP_BACKEND_VERSION=2026.5.3 in #5341, so a present capability bitset is itself a version-compatibility signal. Skip the version sub-check when version is None/empty; keep it for non-empty values so genuinely-too-old backends that do echo a version still get desktop_backend_version_too_old. About tab: fetchStudioVersions() did a bare fetch(apiUrl("/api/health")), which the unauth payload no longer carries version/studio_version for, so Settings -> About kept rendering "dev"/"dev" for any logged-in user. Attach Authorization: Bearer <token> when getAuthToken() returns one; fall back to bare fetch (still 200, just truncated payload) for the not-logged-in case. No new endpoint. Comment: studio_root_id is no longer a hex digest of the install path; it is an opaque per-install id written by the launcher. Updated the inline comment to match. Test: - python -m pytest studio/backend/tests/test_middleware.py::TestHealthAuthGate studio/backend/tests/test_desktop_auth.py -q -> 29 passed - npm run typecheck clean, npm run build produces fresh dist * Trigger CI rerun for flaky Mac Chat UI step
…#5487) * studio: tighten sandbox blocklist precision (bash, hf upload, NOFILE) Three precision fixes in core/inference/tools.py. Same security boundary; fewer false positives that broke legitimate sandbox use. bash blocklist: The per-token loop introduced in #5375 fired on any blocklist word in any token position, so the entirely benign `grep -r curl .`, `echo source the data`, and `ls /usr/bin/curl` were rejected with "blocked command 'curl'". The position-anchored regex already covers real command-position invocations, including `;rm`, `&&wget`, `$(rm)`, `<(rm)`, backticked subshells, and `/usr/bin/sudo`. The token loop is re-scoped: it only fires when the previous shlex token is a shell separator (or at start of line), so split-quoting obfuscations like `r''m -rf /` are still caught (shlex collapses them to a single command-position token) while argument-position blocklist words pass through. Trailing meta-chars glued to a shlex token (`rm;`) are stripped before basename matching. hf upload AST gate: `_method_call_is_hf_upload` previously matched any method named `upload_file` / `upload_folder` / `upload_large_folder` / `create_commit` on any receiver, so paramiko.SFTPClient.upload_file, boto3.create_commit, and similar non-HF SDK methods were rejected. The fallback now requires an `import huggingface_hub` / `import hf_api` / `from huggingface_hub import ...` somewhere in the same module. Fully-qualified huggingface_hub.upload_file(...) calls are unchanged. NOFILE env knob: `RLIMIT_NOFILE = (1024, 1024)` was the only sandbox rlimit without an env override. 1024 is below Linux's typical soft default and below what multi-shard safetensors mmap chains need on Llama-3 70B-class loads. Default is now 16384 with UNSLOTH_STUDIO_SANDBOX_NOFILE, parity with the other rlimits. 15 new bash-blocklist-position tests pin both the false-positive fixes and the still-blocked invariants (semicolon, &&, subshell, backtick, split-quote, /usr/bin/ prefix, nested bash -c). 4 new hf-upload-import-gate tests pin both the false-positive allowances and that HF-imported uses are still blocked. 1 new pin asserts the NOFILE env var is wired. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: cover command wrappers, find -exec, dynamic HF imports, NOFILE clamp Reviewer follow-ups to the sandbox blocklist precision change. Command-position scanner missed Bash command-prefix wrappers and inline shell assignments. shlex tokenised `env curl`, `time curl`, `nohup rm`, `FOO=bar curl`, `sudo rm`, etc. with the prefix at command position and the real command at argument position, so the position-anchored check returned set() while pre-PR's per-token scan caught them. Likewise the position-anchored regex requires `^` or a shell separator before the command, so `env curl` slipped through. Reworked the scanner to track an expect_command flag plus a prefix_pending flag: - assignments (FOO=bar) keep expect_command=True for the next token, - flags ('-oL', '--') keep it intact while prefix_pending is set, - numeric duration args ('timeout 1 cmd') skip without breaking expect_command, - known wrappers (env, command, builtin, exec, time, nohup, nice, setsid, stdbuf, timeout, ionice, chroot, sudo, doas, su, xargs) set prefix_pending so the wrapper's command is still checked, - shell separators now include `{`, `}`, `)`, `then`, `do`, `else`, `elif` so brace groups and if/then/while/do bodies are recognised as command positions. Also lex with `shlex.shlex(punctuation_chars=";&|()`")` so split-quote forms like `echo done; r''m -rf /tmp/x` and `echo done;r''m` tokenise as `[..., ';', 'rm', ...]` and the command position check fires. Added a small `find -exec CMD ... ;` / `-execdir CMD ... ;` pass so `find . -exec rm -f {} +` and friends are caught even though the direct token is at argument position to `find`. Dynamic Hugging Face imports were treated as no-HF-in-scope. The upload-method gate now also resolves `__import__('huggingface_hub')`, `importlib.import_module('huggingface_hub')`, and bare `import_module('huggingface_hub')` (via `from importlib import import_module`) as HF imports, so HfApi().upload_file via dynamic import is still blocked. RLIMIT_NOFILE: setrlimit(NOFILE, (16384, 16384)) silently failed if the parent's hard cap is below the requested value; the broad except swallowed the OSError and left the sandbox at the parent's default. Clamp the requested value to the inherited hard limit before calling setrlimit. Test cleanup: the existing test_cat_with_word_source_allowed had `assert ... or True` so it could not fail; rewrote it to assert the actual return value plus the two membership checks. Added parametrised coverage for shell prefix wrappers, find -exec / xargs, brace groups, if/then, while/do, split-quote command-name forms, and dynamic HF import upload patterns. Test: - python -m pytest studio/backend/tests/test_sandbox_tools.py -q -> 90 passed (was 67 before this commit) - full studio/backend/tests/ minus llama_cpp_load_progress_live and GPU CUDA_VISIBLE_DEVICES tests (pre-existing isolation flake) -> 1063 passed * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: catch bare-name HF upload calls in AST gate `from huggingface_hub import upload_file; upload_file(...)` is a canonical HF call shape that the previous Attribute-only check missed: the bare-name call lands as ast.Name (not ast.Attribute), so the fuzzy gate skipped it. Extend _method_call_is_hf_upload to also match ast.Name when HF is in scope. Same import-gating discipline as the Attribute branch, so paramiko/boto3 and locally-defined `def upload_file(...)` helpers without HF imports still pass. Pins: 4 new TestHfUploadImportGate cases (upload_file/folder/create_commit bare-name imports blocked; local upload_file without HF import allowed). * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: scope HF uploads to sandbox-local literals; block env / token leaks The previous gate dropped every HF upload call. Two refinements make it precise enough to allow legitimate sandbox->HF uploads while still catching credential / file exfil: - path_or_fileobj / folder_path / create_commit operation paths must be sandbox-local relative-path literals (no '/', '~', drive letter, or '..' segments). Variable / dynamic paths are rejected. - Any positional or keyword argument that statically resolves to os.environ / os.environ.get / os.getenv / bare getenv / subprocess shape readers is rejected (env-var exfil). - token / hf_token / api_token / api_key / auth_token / access_token / password / secret kwargs are always rejected; sandbox env strips all parent credentials by construction, so any value here is hard-coded or lifted. Recursive subtree walk in _reads_env_or_secret catches wrapper shapes (str(os.environ), json.dumps(os.environ.items()), etc.). Add TestSandboxEnvIsolation: pin that _build_safe_env builds the env from a whitelist, not by stripping. Cover Linux/macOS/WSL/Windows secret shapes. The whitelist is PATH / HOME / TMPDIR / LANG / TERM / PYTHONIOENCODING (+ VIRTUAL_ENV / SystemRoot when applicable); HOME points at the sandbox workdir, so HF / wandb / aws SDKs cannot reach the operator's ~/.cache credentials. Test classes added: - TestHfUploadSandboxLocalPaths (relative literals allowed; absolute, drive-letter, '~', '..', mid-path traversal, dynamic vars, and open() of unsafe paths blocked, including create_commit recursion). - TestHfUploadEnvAndSecretLeakBlock (os.environ subscript/get/getenv, bare getenv, subprocess.check_output, str(os.environ), token=, hf_token=, api_key=, and create_commit operations referencing env). - TestSandboxEnvIsolation (no parent secret leaks into sandbox env). 131 tests in test_sandbox_tools.py pass. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…ll_id (#5488) * studio: scope cancel-cleanup to in-flight tmp dirs; walk back tool_call_id Two follow-ups to #5375's training and chat hardening. _cleanup_cancelled_checkpoints used to rmtree every checkpoint-N directory on Cancel. That is the opposite of what the user expects. A user cancelling an 8h run with save_steps=2000 loses every completed checkpoint they could have resumed from. The 67 MB residue the audit memo flagged is the HF Trainer atomic-rename partial (tmp-checkpoint-N), not the completed ones. The cleanup now targets only tmp-checkpoint subdirs; completed checkpoint-N directories are user-owned and stay. Symlinked output_dir and symlinked children are skipped so the realpath containment cannot be levered into deleting arbitrary content via a symlink trick. ChatMessage._validate_role_shape stamped a random secrets.token_hex id on tool messages with no tool_call_id. That id is uncorrelated with the prior assistant tool_calls id, so strict passthrough backends (OpenAI, Anthropic) reject the request as orphaned and llama.cpp treats the tool result as "no preceding call" and hallucinates. The synthesis moves up to ChatCompletionRequest, where the whole conversation is visible: for each tool message missing an id we walk back to the most recent assistant turn with tool_calls (stopping at user turns), prefer a function.name match, otherwise take the first unconsumed tool_call. Synthesis is the fallback when no candidate assistant turn exists, preserving the prior round-trip guarantee for orphaned tool messages. Tests: - test_cleanup_cancelled_checkpoints.py (new): pins that completed checkpoint subdirs survive, tmp-checkpoint partials are removed, non-int suffixes (checkpoint-final, checkpoint-best) are left alone, output_dir outside outputs_root is refused, symlinked output_dir and symlinked child are both skipped, missing dir is a no-op. - test_inference_model_validation.py: 6 new walkback cases covering name-match preference, first-unconsumed fallback, explicit-id passthrough, multi-tool-result pairing, synth-on-no-parent, and no-cross-user-turn invariant. - test_openai_tool_passthrough.py: the two ChatMessage-level synth-on-missing tests are rewritten to assert that the per- message validator now leaves tool_call_id untouched; resolution coverage lives in the request-level tests above. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: explicit tool_call_id reserve, numeric tmp-checkpoint suffix only Reviewer follow-ups to the training-cleanup + tool_call_id walkback PR. tool_call_id walkback: a mixed assistant turn with [call_a, call_b] followed by a tool result that carried tool_call_id="call_a" and a sibling tool result with no id resolved to ['call_a', 'call_a'] because the explicit id never reserved call_a in the consumed set. Added a pre-pass over the message list that walks back from every role="tool" message carrying an explicit id and marks the matching (asst_idx, tc_idx) consumed, then the missing-id walkback runs against that pre-populated set. The second result now resolves to call_b. While here, also harden the function-shape check: if a provider ships a malformed tool_call where `function` is a string rather than a dict, the old `(tc.get("function") or {}).get("name")` raised AttributeError on the string's .get; now isinstance-gated so the walkback falls through to the fallback id without raising. Cancel cleanup: `tmp-checkpoint-*` is too broad. HF Trainer's in-flight partials are always `tmp-checkpoint-<integer-step>`, so constrain the cleanup regex to `^tmp-checkpoint-\d+$`. A user folder named `tmp-checkpoint-final`, `tmp-checkpoint-backup`, or `tmp-checkpoint-user-notes` is now preserved. ChatMessage docstring still pointed at the pre-PR contract that required `tool_call_id` on every role="tool" message. Updated to say missing ids are accepted at message scope and resolved at ChatCompletionRequest scope. Inline comment above the cancel-cleanup call now describes the actual behaviour (in-flight tmp partials, completed checkpoints preserved). Test: - python -m pytest studio/backend/tests/test_inference_model_validation.py studio/backend/tests/test_cleanup_cancelled_checkpoints.py studio/backend/tests/test_openai_tool_passthrough.py -q -> 76 passed (was 67 before this commit; +2 walkback regression tests, +1 numeric-suffix preservation test) * studio: trim verbose comments in cleanup + tool_call_id walkback Move the HF tmp-checkpoint regex to module scope as a named constant. Drop the multi-paragraph docstring on _cleanup_cancelled_checkpoints and the inline call-site rationale; the function name + the test class already cover the why. Compress _resolve_missing_tool_call_ids docstring from a six-line explanation to two. Same logic, fewer in-flow tutorials. 76 tests in cleanup + inference-model-validation + tool-passthrough pass. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…5489) * studio: proxy-aware login rate-limit; allow google favicons in CSP Two follow-ups to #5375's auth + headers hardening. Login rate-limit: The per-IP bucket keyed on request.client.host alone. Behind any reverse proxy or shared NAT it lumps everyone together (one user's typos lock everyone out for 60 seconds; the 429 detail leaked the proxy/internal IP back to clients). The bucket key is now (client-ip, username.lower) so: - one wrong-password run does not block another user from the same IP - one IP does not block the same user from a different IP The 429 detail body no longer interpolates the IP. Behind a proxy clients can set UNSLOTH_STUDIO_TRUST_FORWARDED=1 so the limiter honours X-Forwarded-For / Forwarded; off by default so a direct caller cannot spoof the header. CSP img-src: components/assistant-ui/sources.tsx renders citation favicons from https://www.google.com/s2/favicons. The current img-src allows t0..t3.gstatic.com (used for other Google-hosted icons) but not the main host the favicon URL points to, so every citation icon CSP-blocks and falls back to gray initials. Adding www.google.com to img-src is the same shape as #5409's connect-src HF allowlist fix. Tests: - test_login_rate_limit.py (new): _client_ip respects UNSLOTH_STUDIO_TRUST_FORWARDED for X-Forwarded-For and Forwarded; bucket key is composed of (ip, lower(username)) and isolates cross-user and cross-IP buckets; 429 detail does not contain the client IP; Retry-After header preserved. - test_middleware.py: new test_img_src_allows_google_favicons pins that www.google.com is in the img-src directive and the existing gstatic CDNs stay allowed. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: normalise forwarded IPs, IP-wide aggregate cap, unknown-user sentinel Reviewer follow-ups to the proxy-aware login rate-limit PR. Forwarded address normalisation: with UNSLOTH_STUDIO_TRUST_FORWARDED=1, raw `X-Forwarded-For` and `Forwarded: for=` values such as `198.51.100.7:50001` or `"[2001:db8::1]:50001"` were carried verbatim into the bucket key, so one client emitting a fresh source port per attempt split into many buckets and bypassed _LOGIN_MAX_FAILS. _normalize_forwarded_addr now strips quotes, optional `[..]:port` for IPv6 and `host:port` for IPv4, and validates as an IP literal; garbage values fall through to the direct request.client.host. Forwarded parsing also isolates the first forwarded-element so a multi-element header cannot create attacker-controlled bucket strings. Spray protection: the (ip, username) key removed the aggregate per-IP throttle the pre-PR limiter provided. A client rotating nonexistent usernames produced [401, 401, 401, 401, 401, 401] where pre-PR produced [401, 401, 401, 401, 401, 429]. Restored the aggregate via a parallel _LOGIN_IP_BUCKETS table (max 30 fails / 60s per IP) checked alongside the per-(ip, username) bucket; both buckets must be cleared on a successful login. Bucket cardinality: every distinct unauthenticated username allocated a new (ip, username) bucket entry without bound. 1,000 random usernames from one IP produced 1,000 buckets. Failures whose username does not exist now record into a single sentinel key (ip, "\x00unknown-user") so cardinality stays at one per IP for the unknown path. The known-user path additionally enforces a global hard cap (_LOGIN_MAX_BUCKETS = 4096) that prunes stale empty buckets on overflow and otherwise folds the failure into the per-IP bucket only. Test: - python -m pytest studio/backend/tests/test_login_rate_limit.py -q -> 19 passed (was 12 before this commit; +5 forwarded-address normalisation, +1 sentinel bucket, +1 bucket cap) CSP comment refreshed to mention `www.google.com` alongside *.gstatic.com so future readers see why the host is allowlisted. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: tokenise img-src assertion to silence CodeQL substring rule The new CSP google-favicon test used 'host string in directive string' which CodeQL flagged as py/incomplete-url-substring-sanitization (the substring could appear at an arbitrary position in a URL). The assertion is checking a CSP directive, not URL sanitisation, but splitting the directive on whitespace and asserting against the tokenised source list expresses the same intent and matches the exact CSP source expression. CodeQL no longer treats it as a URL substring check. Test: python -m pytest studio/backend/tests/test_middleware.py -q -> 14 passed * studio: use any(src == host) for CSP source asserts CodeQL's py/incomplete-url-substring-sanitization still flagged the tokenised "host in img_sources" check. Switching to `any(src == host for src in img_sources)` makes the comparison an exact-equality (not substring) match, which the rule does not flag. Test: python -m pytest studio/backend/tests/test_middleware.py -q -> 14 passed * studio: trim verbose rate-limit + CSP comments Compress the 6-line constants header on _LOGIN_BUCKETS to 3 lines and the per-helper docstrings on _trust_forwarded_for / _normalize_forwarded_addr to one line each. Same code, fewer in-flow tutorials. Note in the CSP comment that www.google.com is the active favicon host (used by sources.tsx for s2/favicons citations); *.gstatic.com stays as legacy faviconV2 coverage but the SPA no longer fetches it. 33 tests in test_login_rate_limit.py + test_middleware.py still pass. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…, current-password input (#5490) * studio/frontend: wire logout, singleflight refresh, shared 422 helper, current-password input Four frontend follow-ups to #5375 that the train-api fix in #5409 did not cover. Log out: features/auth/api.ts:logout() was a synchronous clearAuthTokens() with no call to /api/auth/logout, and the SPA exposed no Log out menu item at all. Refresh tokens stay valid server-side for their entire lifetime even after the user "leaves". logout() is now async and POSTs to /api/auth/logout (best-effort, swallows network errors) so storage.revoke_user_refresh_tokens fires server-side. The account dropdown in components/app-sidebar.tsx gains a Log out item between Help and Shutdown that calls logout() then navigates to /login. refreshSession singleflight: The backend now consumes the refresh token atomically on /api/auth/refresh, so two concurrent refreshes race; the loser 401s and the user is force-logged-out. This reproduces on essentially every page that fires multiple API calls in parallel after access- token expiry. refreshSession now holds a module-level inflight promise: first caller mints it, subsequent callers await the same one, and the slot clears in finally. Shared formatDetail helper: Roland's #5409 fix lived inside train-api.ts. Other api modules (chat-api.ts, export-api.ts, history-api.ts, datasets-api.ts, recipe-studio/api/index.ts) still rendered FastAPI array-detail 422s as either "Request failed (422)" (chat-api.ts's typeof-string gate) or "[object Object]" (the others). format-fastapi-error.ts lifts the helper into one place: formatFastApiDetail unpacks the array, readFastApiError reads a Response into the best human-readable string. All five sibling api modules now use it. recipe-studio also swaps ?? for the helper's truthy-formatted check so an array detail no longer short-circuits to "[object Object],[object Object]". Current password input: features/auth/components/auth-form.tsx in change-password mode showed only New password and Confirm password; currentPassword defaulted to window.__UNSLOTH_BOOTSTRAP__?.password. On admin-forced must_change_password resets the bootstrap is empty and the form short-circuits with "Unable to initialize setup. Reload the page". A Current password input is now rendered in change-password mode, pre-filled from the bootstrap when present so first-boot UX is unchanged. Build: - npm run typecheck clean - npm run build produces a fresh dist - install.sh rebuilds dist on next install.sh --local * studio/frontend: logout refresh-retry, generation guard, two missed 422 sites, password toggle Reviewer follow-ups to the auth-UX PR. Logout server-side revoke missed the expired-access case. /api/auth/ logout requires a valid access JWT and only then calls storage.revoke_user_refresh_tokens(). When the access token had expired but the 7-day refresh token was still valid, logout() posted once, got 401, swallowed it, and cleared local state, leaving the refresh token alive on the server. logout() now retries once: on 401 with a refresh token present, it calls refreshSession() to rotate, then re-posts /api/auth/logout with the new access token. Both branches still clearAuthTokens in finally. In-flight refresh could repopulate localStorage after logout. A background refreshSession() that started before the user clicked Log out, but resolved after the local clear, wrote storeAuthTokens() back over the cleared state and effectively re-authenticated the SPA. Added a module-level logoutGeneration counter: each refresh captures the value on entry, logout() bumps the counter in finally before clearing, and the refresh's continuation drops its new token pair on the floor when the counter has moved. Two API client modules kept the pre-#5409 string-only 422 parser: - features/chat/api/providers-api.ts -> parseErrorText now calls formatFastApiDetail() so create / update / test / models requests surface field-level errors instead of "Request failed (422)". - features/chat/api/openai-containers.ts -> parseError now uses readFastApiError() so ttl_minutes / encrypted_api_key / container_id validation errors surface instead of "HTTP 422". recipe-studio/api/index.ts::uploadUnstructuredFile still had a local typeof-string detail check on both the 413 and the generic not-ok branches. Both branches now use readFastApiError() so array-shaped 422 details show field-level errors instead of a generic fallback. Password reveal toggle in change-password mode shared one showPassword state across Current password and New password, so the eye button on either field exposed both secrets. Added a separate showNewPassword state so New password's toggle is independent of Current password's toggle. Confirm password remains type="password" unconditionally. Test: - npm run typecheck clean - npm run build produces a fresh dist * studio/frontend: drop dynamic auth/api + auth/session imports in sidebar Log out's onSelect dynamically imported logout from "@/features/auth/api" and clearAuthTokens from "@/features/auth/session". Both modules were already statically imported via "@/features/auth" elsewhere in the app, so rolldown split auth/session into its own chunk and the main bundle then re-imported back from that chunk to reach the zustand-backed usePlatformStore. The resulting circular dependency left session.js's 'create' binding undefined at module init, throwing 'TypeError: t is not a function' from var usePlatformStore=create<...> on /login, /change-password, and any route that touches the platform store before the main bundle finished evaluating. Static-import logout and clearAuthTokens from "@/features/auth" so both are tree-shaken into the main bundle, eliminating the session side-chunk and the cycle. Exported clearAuthTokens from auth/index.ts since it was previously only reachable through the session.ts path module. Test: - npm run typecheck clean - npm run build no longer emits a session-*.js chunk - Local Playwright pre/post: /login, /change-password, /chat render with 0 page errors on the rebuilt dist (pre: 'TypeError: t is not a function' on every route) * studio/frontend: decouple must_change_password from storeAuthTokens CodeQL's js/clear-text-storage-of-sensitive-information rule traced must_change_password through loginWithPassword() into localStorage.setItem(AUTH_MUST_CHANGE_PASSWORD_KEY, ...) at session.ts:46 and flagged the line as new high-severity. The flag is a boolean derived from the same response payload as the access token, so the data-flow analyser treated it as JWT-equivalent sensitivity. Removed the third parameter from storeAuthTokens so it only writes the two JWTs. Each caller (refreshSession, tauri-auto-auth, two spots in auth-form) now calls setMustChangePassword(...) explicitly with the boolean. The boolean is no longer reachable from a function whose name CodeQL treats as a password sink. Test: - npm run typecheck clean - npm run build produces no session-*.js side-chunk - Local Playwright over /login, /change-password, /chat: 0 page errors (parity with the previous fix) * studio/frontend: suppress CodeQL clear-text-storage on must_change_password flag CodeQL's js/clear-text-storage-of-sensitive-information rule traces the must_change_password boolean back through loginWithPassword's TokenResponse and flags any localStorage.setItem of that boolean as sensitive-clear-text storage. The value is a status flag (route to /change-password vs straight to /chat); it carries no credential material. Decoupling setMustChangePassword from storeAuthTokens in the previous commit only moved the alert one line over because the analyser still recognises the source. Add the standard lgtm suppression comment, with a brief rationale, on the .setItem call. Test: npm run typecheck clean, npm run build still produces a fresh dist with no session-*.js side-chunk. * studio/frontend: encode must_change_password as key presence to silence CodeQL setMustChangePassword wrote String(required) which is a derivative of the boolean and which CodeQL's clear-text-storage analyser traces back through loginWithPassword's TokenResponse, flagging the .setItem call as sensitive-information storage. Switch the encoding so the stored value is the literal string "1" when the flag is set, and the key is removed when not. The reader switches from `=== "true"` to a presence check (`!== null`). This breaks the boolean's data flow into .setItem: the value argument is now a constant string literal in the truthy branch and the falsy branch issues .removeItem (no stored value to taint). The behaviour contract is identical (the flag is present iff the user must change their password). Test: npm run typecheck clean, npm run build produces a fresh dist, local Playwright probe over /login, /change-password, /chat: 0 page errors on the rebuilt dist. * studio/frontend: trim verbose comments in auth api + session Compress singleflight + logoutGeneration paragraphs in api.ts from ~9 lines each to ~3. Same logic. Merge mustChangePassword / setMustChangePassword's separate two-paragraph CodeQL rationales into one shared comment above both functions. Typecheck + build still clean.
Summary
A pass with the parallel Studio probe (
scripts/test_unsloth_studio.py+ a few targeted curls) surfaced a cluster of related hardening issues across the Studio backend. This PR closes the highest-impact ones with backend-only edits so they land without a Vite rebuild. Findings that need a frontend rebuild are noted in the "Not in this PR" section so we can sequence them.Each commit is grouped by surface (path containment, sandbox, auth, middleware, schema validation, misc) so the review can step through one area at a time.
What changed, by surface
1. Path containment (
studio: contain export and dataset paths ...)resolve_under_rootandresolve_dataset_pathpreviously returned absolute inputs unchanged, so an authenticatedPOST /api/export/export/lorawithsave_directory="/tmp/escape"dropped adapter files anywhere the server user could write. The two helpers now share a new_assert_contained(resolved, root)guard built onrealpathcontainment, reject..segments and null bytes outright, and only accept absolute inputs when they are already inside the configured root (internal call sites that re-resolve a stored absolute path stay idempotent).models/export.pygains a pydanticfield_validatoronsave_directoryso bad input fails fast at 422 with a clear field-named message.routes/export.py:_export_detailsreturns the path relative toexports_root()so the success dialog no longer shows the absolute install prefix.2. Sandbox hardening (
studio/sandbox: harden bash + python ...)curl,wget,nc,ncat,netcat,socat,ssh,scp,sftp,rsync,eval,source,doas,pkexec,halt,poweroffso the obvious egress and escalation channels stop working without affectingecho,ls,for, pipes, etc._sandbox_preexecnow callsos.setsid()so children share a process group; the supervisor usesos.killpg(SIGKILL)on timeout / cancel so bash-backgrounded grandchildren actually die. Also:umask(0o077),PR_SET_PDEATHSIG=SIGKILL, best-effortunshare(CLONE_NEWNET)(failure is logged and swallowed; the bash blocklist and AST checker remain the fallback), andsetrlimitforNPROC/AS/CPU/NOFILE/FSIZE. TheNPROC=10000default is tuned to sit above the ~500 LWPs a healthy Studio + llama-server combination already uses while still capping a runaway fork bomb; smaller values starve legitimate bash forks withbash: fork: retry: Resource temporarily unavailable._get_workdirenforces a strict[A-Za-z0-9_-]{1,64}regex onsession_id(anything else buckets into_invalid) and chmods both the workdir and the sandbox root to0o700, so other UIDs cannot read another session's contents._STRING_SHELL_FUNCSgate to also cover_SHELL_EXEC_FUNCS, closing thechr(115)+chr(117)+chr(100)+chr(111)style dynamic-arg bypass. Two new narrow IO checks land alongside: literalsocket.connect(("169.254.169.254", ...)),socket.create_connection,urllib.request.urlopen("http://169.254.169.254/..."),requests.get("http://metadata.google.internal/..."), etc. against a cloud-metadata host denylist; and literalopen("/etc/passwd"),/etc/shadow,/etc/sudoers,/etc/ssh/*,/proc/<pid>/environ. Public hosts (example.com,huggingface.co, ...) and benign file reads (/etc/os-release,/tmp/*, user dirs) keep working.3. Auth, refresh rotation, logout, security headers (
studio: rate-limit login, rotate refresh tokens, ...andstudio: add SecurityHeadersMiddleware, ...)POST /api/auth/login. Five failed attempts inside 60s -> 429 withRetry-After: 60. A successful login clears the bucket.POST /api/auth/logoutreturns 204 and callsstorage.revoke_user_refresh_tokens(subject)./api/auth/refreshnow consumes the supplied refresh token atomically (newconsume_refresh_tokenhelper inauth/storage.py) and mints both a new access AND a new refresh token. Replaying a consumed refresh returns 401.AuthStatusResponse.default_usernameis nowOptional[str] = Noneand the handler always returns None. The frontend already hardcodesHIDDEN_LOGIN_USERNAME = "unsloth"so no UI change is needed._inject_bootstrapis gated behindUNSLOTH_STUDIO_INJECT_BOOTSTRAP. The previous default inlinedwindow.__UNSLOTH_BOOTSTRAP__ = {username, password}into the first-boot HTML for any caller that hit/; the bootstrap password stays on disk atauth/.bootstrap_passwordmode 0o600 where it has always lived.SecurityHeadersMiddlewarestamps every response with CSP,X-Frame-Options: DENY,X-Content-Type-Options: nosniff,Referrer-Policy: no-referrer,Permissions-Policy, and a genericServer: unsloth-studio.uvicorn.Config(server_header=False)inrun.pysuppresses uvicorn's ownServer: uvicornbanner.MaxBodyMiddlewarerejects POST/PUT/PATCH on the inference / dataset / data-recipe / train / export prefixes whenContent-Length > UNSLOTH_STUDIO_MAX_BODY_MB(default 100). The previous chat-attachment path base64-encoded the file straight into the JSON body and had no enforced cap; the audit was able to attach a 50 MB plain text "attachment" without warning./api/healthunauthenticated returns{"status":"healthy","timestamp":...}only; the full diagnostic payload (version,device_type,studio_root_id, ...) still lands for callers that present a valid Bearer token so internal launchers and sibling-Studio detection keep working./recipesand/recipes/<tail>308-redirect to/data-recipesso users typing the obvious URL no longer hit the SPA catch-all "Not Found".4. Hyperparameter validation (
studio: bound TrainingStartRequest ...)POST /api/train/startpreviously accepted -1, 0, 1e9, and non-numeric strings forlearning_rate,batch_size,max_steps,max_seq_length,warmup_steps,warmup_ratio,num_epochs,save_steps,weight_decay,gradient_accumulation_steps,lora_r,lora_alpha,lora_dropout. Each now has afield_validatorwith a clear field-named ValueError; non-numeric input rejects explicitly instead of silently coercing to 0.5. Misc (
studio: redact image-decode errors, clean checkpoint dirs ...)routes/inference.pypreviously interpolated the PIL exception repr into the 400 response (Failed to process image: cannot identify image file <_io.BytesIO object at 0x7e40a5d7bf60>), leaking both the Python class name and a heap address. They now return genericUnsupported or corrupt image format/Failed to process imagemessages.core/training/training.py:force_terminate()now invokes a new_cleanup_cancelled_checkpoints(output_dir)helper when_cancel_requestedis set. The helper removescheckpoint-<int>subdirs after a realpath containment check againstoutputs_root(), so a cancelled run no longer leaves intermediate checkpoint state on disk (the audit saw ~67 MB stuck after a 200-step cancel withsave_steps=20). Stop-and-Save runs are unaffected.models/inference.py:ChatMessage._validate_role_shapesynthesises atool_call_id(f"call_{secrets.token_hex(8)}") when arole="tool"message is missing one, and toleratesrole="assistant", content=""(the Stop-button sentinel) by normalising empty content to None. The proper fixes live in the frontend (don't insert the empty assistant turn; carry the streamed tool_call_id through the second POST) and will follow.Not in this PR (frontend or deployment-level)
These were noted by the audit but require a Vite rebuild of
studio/frontend/dist/assets/index-*.jsor a deployment-level change:new_passwordandconfirm_password; the React validator gates on a third hiddencurrent_passwordfield). Once__UNSLOTH_BOOTSTRAP__is off by default this UI needs a visible "current password" input.useGpuInfoinhooks/use-gpu-info.tspolls/api/systemwith plainfetchinstead ofauthFetch, producing a console401on every page load. One-line frontend swap.top_p=2displays "Off" but the API receives 1.0); the<input>elements lackmin/max/stepHTML attributes.aui-thread-viewportoverlays the right configuration panel and intercepts pointer events on narrow viewports.Request failed (422)red-bubble error string in chat.max_new_tokens=8192UI default exceeds SmolLM2's own context window (8192).Deletekeypress not handled (onlyBackspace).auth tokens in localStorage(vsHttpOnlycookies): extensive TS rewrite acrosssession.ts,api.ts,auth-form.tsx,auth-guards.ts,tauri-auto-auth.ts. Separate PR.ubuntusandbox user being in thesudo/lxdgroups is a deployment concern;PR_SET_NO_NEW_PRIVS=1still kernel-blockssudoexecution.Test plan
resolve_under_root("/tmp/EVIL", root=...)raises;resolve_under_root("foo/bar", ...)andresolve_under_root(<absolute-already-under-root>, ...)return the contained path._cleanup_cancelled_checkpointsremoves onlycheckpoint-<int>dirs and refuses paths outsideoutputs_root().POST /api/export/export/lora {"save_directory":"/tmp/EVIL"}returns 422 with the field-named error;/tmp/EVILis not created...traversal also 422. Relativemy_subdiraccepted.Retry-After.POST /api/auth/logout-> 204; old refresh token then 401./api/auth/refreshrotates the refresh token; replaying the old one 401s.curl /api/auth/statusunauthenticated returnsdefault_username: null.curl /api/healthunauthenticated returns{status, timestamp}only; withAuthorization: Bearer <valid>returns the full payload.curl -I /shows CSP,X-Frame-Options: DENY,X-Content-Type-Options: nosniff,Referrer-Policy: no-referrer,Permissions-Policy,Server: unsloth-studio(noServer: uvicorn)./v1/chat/completions-> 413Request body too large.GET /recipes-> 308Location: /data-recipes. Following the redirect lands on the SPA HTML.POST /api/train/startwith each oflearning_rate=-1/0/1e9/'abc',batch_size=-1/0/999999/'two',max_steps=0/-5,max_seq_length=200000,warmup_ratio=2.5,lora_dropout=1.5returns 422 naming the bad field. Valid request passes validation and starts training.curl https://example.com/wget/nc/ssh/rm->Blocked command(s) for safety: .... Pythonsocket.create_connection(("169.254.169.254", 80))/urllib.request.urlopen("http://169.254.169.254/...")/requests.get("http://metadata.google.internal/")->Error: unsafe code detected (... targets cloud-metadata).open("/etc/passwd")//etc/shadow//proc/self/environ-> blocked.open("/etc/os-release"),urllib.request.urlopen("http://example.com"),echo,ls,for, pipes still work.0o700, sandbox root is0o700./api/auth/login,/api/models/list,/api/train/status,/api/inference/status,/api/auth/api-keys, SPA root/,/data-recipes,/api/auth/api-keysall return 200 after every batch.Notes for reviewers
UNSLOTH_STUDIO_INJECT_BOOTSTRAP,UNSLOTH_STUDIO_MAX_BODY_MB,UNSLOTH_STUDIO_SANDBOX_NPROC,UNSLOTH_STUDIO_SANDBOX_AS_GB,UNSLOTH_STUDIO_SANDBOX_CPU_S) default to safe values; nothing in this PR requires a config change to deploy.unshare(CLONE_NEWNET)is best-effort; it silently falls through where unprivileged user namespaces are not available. The bash blocklist plus the AST-level metadata-host denylist remain the static guarantees.socket.connect((dynamic_var, 80))wheredynamic_varis constructed at runtime; static analysis cannot decide that case. This is unchanged from prior behaviour for non-literalsubprocess.Popenand similar; the goal is to keepweb_search-style tool calls working while making the obvious attacks fail.