Repository navigation
Studio: refuse keyless access to a cross-site browser request - #9683
Conversation
Origin is not enough to tell that a browser started a request. No engine attaches it to a same-origin GET, nor to a cross-site GET issued in no-cors mode, and a no-cors fetch aimed at http://127.0.0.1:<port> really does arrive: only Chromium withholds it, through Private Network Access, which Firefox and Safari have not shipped. Against a live server on the current head, a request shaped exactly the way those two emit it was served the model list keylessly under inference, and reached the management handlers under full. Sec-Fetch-Site says who initiated the request, on every request whatever the mode, and a page cannot forge it: the Sec- prefix makes it a forbidden header name. Only cross-site and same-site are refused. same-origin is Studio's own page and none is the user typing the URL, so both stay admitted. Absence stays admitted too, and has to: curl, the OpenAI SDKs and Safari before 16.4 send no Sec-Fetch-* at all, and serving them is the point of the setting. That also means the header is only there to be read where the transport is a potentially trustworthy URL, so this narrows full scope, which is loopback-only, more tightly than plain-HTTP LAN inference. It never widens either. Adds the adversarial suite the feature was missing, in its own file so the existing test budget is untouched: scope=off refused through the security dependency rather than only through scope_covers, the settings route that grants the scope refusing to let a keyless caller widen it, public bind and public peer, management routes under inference, root_path and trailing slash driven end to end, the dynamic /v1/models/ prefix pinned to the one handler it can reach, a session JWT naming an unknown subject, the ASGI twin of the header rules, every hosted-mode flag, the full-scope denials with the tunnel flag cleared so they are not over-determined, and the revoke-after-admission race from the review, pinned directly since the original reproducer can no longer run on this head.
biome check reports useExhaustiveDependencies on the effect that reloads keyless settings: cloudflareUrl is in the dependency list but never read in the body. That is deliberate. It is there so a tunnel appearing or going away re-fetches exposure from the backend and the warning copy stays current. Annotated the way the rest of the frontend annotates a trigger dependency, so the file is clean.
The setting adds an admission path and must never take one away. A working key or session has to keep authenticating on every scope and on every transport, including the ones keyless itself is refused on: public bind, active tunnel, Colab, --secure, and the browser shapes the Sec-Fetch-Site rule now rejects. A usable bearer is resolved before any scope or transport check runs, so nothing in the gating can reach it, and this holds that shape in place. It also asserts the credential authenticates as itself rather than through either keyless scheme. That is not cosmetic: the middleware classifies a key-bearing request as non-keyless precisely so an existing API client keeps its own tool policy, and a downgrade would quietly take away tools it already had. Removing the APPROVED_DUMMY_BEARERS clause from the dependency fails this test with "api_key was downgraded to keyless on loopback/inference". Revoked and expired keys are re-checked at the widest scope in the same test, so the two directions cannot drift apart.
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Comment-only pass. The helper docstring said the same thing twice about why Origin cannot identify a browser, and the test docstrings pointed at "the PR", which named nothing a reader could open once #9102 merged.
DNS rebinding produces every local signal the transport checks read. A page on evil.example whose record is re-pointed at 127.0.0.1 keeps its own origin, so the fetch is same-origin: no Origin header, Sec-Fetch-Site: same-origin, and a loopback peer on a loopback socket. Reproduced at the previous head, scope full, GET /api/chat/threads with Host: evil.example:8888 admitted, and unlike the no-cors case the response is readable by the page. This predates the branch, since a same-origin GET carries no Origin and the existing rule never fired either, but same-origin is a positive signal this branch introduced, so the check belongs with it. Host is what still differs: a direct client addresses the socket by literal address or localhost, and only a rebound page sends a domain, because the browser sends the name the page was served from. Absent Host stays admitted, since the merged suite and HTTP/1.0 callers send none and no browser omits it. Bracketed IPv6 junk such as [::1]evil.example is rejected rather than parsed, matching what _host_header_is_loopback already does for the bootstrap path. Costs a private hostname such as studio.internal:8888 its keyless access, which is fail-closed and the right default for a setting that removes authentication.
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Final comment-only pass. The helper docstring restated the attack twice, and two comments still said "the PR" where #9102 is merged and the reader has nothing to open.
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
CI status, since the red checks here are misleading. Every red check on this PR is I replicated this branch onto a staging repo, cut from fresh That file is on So the only genuine failure reachable from here is a pre-existing one with a fix already open. Nothing on this branch is failing. |
|
Confirmed studio/backend/utils/keyless_api_access.py on main has no Sec-Fetch-Site or Host authority check, so cross-site no-cors and rebound same-origin requests still reach keyless admission, and the same-origin rebinding case is closed here too. Will get this reviewed. |
…sence
The rule this branch added admits a request that carries no `Sec-Fetch-Site`, on
the docstring's claim that the header "is set on every request whatever the mode".
That is not what the spec says and not what browsers do. Fetch Metadata is attached
only to a *potentially trustworthy* URL, and Secure Contexts spells that set as
`127.0.0.0/8` and `::1/128`. Any other spelling that still reaches a loopback
listener arrives with no Fetch Metadata at all, and absence-means-not-a-browser
then reads a hostile page as curl.
Measured against a live server, Chromium 151 / Firefox 153 / WebKit 26.5:
| dialled from a cross-site page | Host seen | Sec-Fetch-Site | before |
| ------------------------------ | ---------------- | -------------- | ------ |
| `[::ffff:127.0.0.1]:<port>` | `[::ffff:7f00:1]`| absent, all 3 | ADMITTED |
| `[::ffff:7f00:1]:<port>` | `[::ffff:7f00:1]`| absent, all 3 | ADMITTED |
| `0.0.0.0:<port>` | `0.0.0.0` | absent | ADMITTED |
| `localhost.:<port>` | `localhost.` | absent on WebKit | ADMITTED |
| `127.0.0.1:<port>` (control) | `127.0.0.1` | cross-site | refused |
`_normalized_ip` un-maps the IPv4-mapped forms, which is right for the socket
addresses it was written for and wrong for an authority off the wire: it undoes
exactly the distinction the browser is drawing. The authority is now parsed here
and matched as written, refusing IPv4-mapped IPv6, the unspecified addresses, and
a trailing-dot `localhost` (Secure Contexts lists it, but WebKit's check is a
plain string compare and it sends nothing there).
`none` is no longer admitted. Its comment said "the user typing the URL, which no
page can cause" -- true of a page, false of a server. `none` is computed before
the redirect chain is walked, so an attacker 302 from a navigation the user started
lands here still saying `none`; Firefox and WebKit both delivered it. Nobody types
an API route into an address bar.
A repeated `Host` or `Sec-Fetch-Site` is refused rather than resolved. Both
predicates read `Headers.get()`, which takes the first value; h11 rejects a
repeated `Host` but httptools passes both through, and neither rejects a repeated
`Sec-Fetch-Site`. `asgi_request_is_keyless` already fails closed on a repeated
`Authorization` a hundred lines below, so this now matches the file's own rule.
Also fixes a drift the strengthened twin test caught: `asgi_request_is_keyless`
hand-rolled `partition(" ")` while the dependency uses FastAPI's parser, and they
disagreed on `Authorization: bearer not-needed` -- keyless to every route, and
not-keyless to `KeylessToolPolicyMiddleware`, which is what clamps the tool grant.
That one shape reached keyless admission with an unclamped tool policy. Both now
share the parser.
Malformed authorities are refused: the port suffix must be numeric, brackets must
close, and the literal must parse. `localhost:garbage`, `127.0.0.1:80@evil`,
`127.0.0.1%evil.example`, `::1]` and `127.0.0.1:<port>/../evil` all reached the app
through both uvicorn parsers and were admitted.
UI side, the panel stopped agreeing with the backend. `keylessBaseEligible` short
circuits on `exposure === "private_lan"`, which is computed from the RESOLVED
address, so `unsloth studio -H box.local` rendered a copyable
`Bearer not-needed` curl against a URL the new rule answers 401 on, and
`_has_keyless_lan_url` resolved the name and reported it eligible. Both now require
a literal. The LAN panel still shows the hostname URL -- the UI works there on a
session -- it just no longer claims keyless does.
Verification, all before/after on the same tree:
- raw-socket matrix over the real predicate behind real uvicorn, both parsers,
both scopes: 27 expectation failures -> 0. All 11 legitimate client shapes
(curl, OpenAI/Anthropic/LM Studio/Ollama SDKs, HTTP/1.0 without Host, `[::1]`,
Studio's own same-origin page) still admitted.
- closed loop, hostile page in all three engines against the real predicate:
10 hostile requests admitted -> 0, same-origin still admitted.
- backend suite as Backend CI runs it: failure set byte-identical to the merge
base (387 ids either side, 0 new), +18 passed.
- frontend: 4893 tests pass, typecheck clean, biome error free. Ruff clean.
Known residual, now pinned by a test rather than assumed away: on the plain-HTTP
private-LAN limb no URL is potentially trustworthy, so no engine sends
`Sec-Fetch-*` there and that predicate is structurally inert. `Origin` and the
authority rule are what carry the LAN limb. Narrowing it further would take away
the private-LAN inference the setting exists to provide.
|
Follow-up commit What was wrongThe docstring claimed Measured against a live server from a cross-site page, Chromium 151 / Firefox 153 / WebKit 26.5:
All of those reach a listener bound on Three more, same commit:
What changedThe authority is now parsed here and matched as written, refusing IPv4-mapped IPv6, the unspecified addresses, a trailing-dot UI side, the panel had stopped agreeing with the backend: VerificationBefore/after on the same tree, everything scripted:
CompatibilityNothing changes for an install that leaves the setting off, which is every existing install: Residual, now pinned by a test rather than assumed awayOn the plain-HTTP private-LAN limb no URL is potentially trustworthy, so no engine sends Also worth stating plainly, since the original description called the cost narrow: |
|
Cross-platform, on real runners in staging. The adversarial suite passes on all three, and the address-family probe explains why the bypass mattered where it did. Adversarial suite, Python 3.12: ubuntu-latest 18 passed, macos-15 18 passed, windows-latest 18 passed. Does a non-trustworthy loopback spelling actually reach a listener bound on
So the IPv4-mapped and unspecified bypasses were live on Linux and macOS and never reachable on Windows, which matches the documented Worth recording because it cuts the other way too: on Linux and macOS the peer address for every one of those is plain |
Being an address rather than a name was not enough. The authority rule accepted every literal, so on a loopback transport `Host: 8.8.8.8:8888` was admitted under `full` and served management responses. The socket checks only ever see the hop that connected. An SSH forward or a reverse proxy in front of a loopback bind makes both ASGI endpoints loopback while the page's own origin, and therefore `Host`, is the public address it was served from. That authority is the only place the difference is visible, which is the same reason the IPv4-mapped case needed fixing. `full` is loopback-only by construction -- `_full_scope_transport_allowed` already demands a loopback bind and a loopback peer -- so its authority must be loopback too, and nothing legitimate reaches a loopback-only server by typing a routable address. `inference` may additionally be reached across the private LAN, so it takes the same networks `lan_access_settings` admits and nothing wider. Spelled with the repo's existing `_private_non_loopback` rather than `is_private`, which means "not globally reachable" and so counts the documentation ranges as private (203.0.113.5 reports is_private=True). CGNAT and the doc ranges are outside `_PRIVATE_LAN_NETWORKS`, so both are refused, matching what the socket checks already enforce for the LAN limb. Before and after, on a loopback transport: | Host | full | inference | | ------------------- | ----------- | ----------- | | 127.0.0.1, ::1, 127.0.0.2, localhost | admitted -> admitted | admitted -> admitted | | absent | admitted -> admitted | admitted -> admitted | | 192.168.1.5, fd00::1 | admitted -> REFUSED | admitted -> admitted | | 8.8.8.8, 2001:db8::1 | admitted -> REFUSED | admitted -> REFUSED | | 100.64.0.1 (CGNAT) | admitted -> REFUSED | admitted -> REFUSED | Also runs the repo formatter over the three files, which is what `pre-commit.ci` was red on: the hook adjusts kwarg spacing and the test file had drifted. Verified: keyless, LAN, desktop-auth and off-event-loop suites 170 passed; the raw-socket matrix over the real predicate behind real uvicorn is 0 expectation failures on both parsers and both scopes; full backend suite as Backend CI runs it has 0 new failures against the merge base (385 vs 387).
The LAN panel decides whether to print `Bearer not-needed` through `_has_keyless_lan_url`, which had its own copy of the authority test, and the copy went through `_normalized_ip`. That un-maps IPv4-mapped IPv6, which is the one thing the mapped form is refused for, so a launch on `::ffff:192.168.1.24` was advertised as keyless-eligible while admission refused the mapped authority. Reproduced before changing anything: | URL / Host | panel said | admission said | | ------------------------------- | ---------- | -------------- | | `192.168.1.24:8888` | eligible | admitted | | `[::ffff:192.168.1.24]:8888` | eligible | REFUSED | | `[::ffff:c0a8:118]:8888` | eligible | REFUSED | Adding a second mapped-literal check next to the first is what produced the drift, so both ends now answer through one `keyless_authority_address_allowed`, and the panel parses the literal as written instead of normalising it. It takes an already-parsed address so the caller keeps responsibility for parsing the spelling faithfully, which is the part that has to stay honest. Same shape as the `asgi_request_is_keyless` split earlier on this branch: two copies of a rule that must agree will eventually not. Verified: keyless, LAN, desktop-auth and off-event-loop suites 171 passed; panel and admission agree on every literal spelling tested, including loopback, private v4/v6, mapped, CGNAT, public and a hostname; full backend suite has 0 new failures against the merge base (385 vs 387).
The guard asked whether a base LOOKS like an address. Every one of these is a well formed literal, and admission refuses all of them, so the panel kept advertising a copy-paste `Bearer not-needed` command that answers 401. Reproduced before changing anything, at scope=inference with exposure=private_lan: | base | panel said | admission says | | --------------------------------- | ---------- | -------------- | | `[::ffff:192.168.1.24]:8888` | eligible | refused | | `[::ffff:c0a8:118]:8888` | eligible | refused | | `[::]:8888`, `0.0.0.0:8888` | eligible | refused | | `8.8.8.8:8888` | eligible | refused | The public case was not in the report and is the same defect. Third time this guard has been wrong, each time because it tested something adjacent to the real question: first `exposure` short-circuited the host test, then syntax stood in for the address class, and `isPrivateLanHost` unwrapped `::ffff:` -- which is the one thing admission refuses the mapped form for. So the pure logic moves to `keyless-example-eligibility.ts`, mirroring `keyless_authority_address_allowed`, and the unwrapping is gone. Its own module because the old test could only scrape the component source: importing `usage-examples.tsx` drags react and shiki into a unit test. Now the table itself is pinned, not the presence of a guard, and it mirrors the backend test by name so the two are changed together. Verified: 4 new frontend tests pass, 4896 frontend tests pass overall, typecheck clean, biome error free (warning parity with the existing test files); backend keyless, LAN, desktop-auth and off-event-loop suites 171 passed.
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
The new eligibility module declared its own copies, and they were wrong in both
directions: the invented union carried a "loopback" member that does not exist and
was missing "network", which does. `Tauri Linux debug build` caught it:
usage-examples.tsx(705,45): error TS2345: Argument of type
'KeylessApiAccessExposure | null' is not assignable to parameter of type
'KeylessExposure | null'. Type '"network"' is not assignable to
'KeylessExposure | null'.
Redeclaring a type to avoid an import is the same mistake as the duplicated address
rule this module exists to remove, so it now imports both from
`../api/keyless-api-access`.
Worth noting for the next change here: `tsc --noEmit -p tsconfig.json` passes on the
broken version. `npm run build` runs `tsc -b`, which resolves project references and
is what actually fails, so that is the check to run.
No behaviour change -- "network" exposure falls through to the authority rule exactly
as before, and only "colab" and "public_url" are refused up front.
Verified: npm run build succeeds, 4896 frontend tests pass, biome error free, backend
keyless and LAN suites pass.
|
CI status on
Both types now come from Worth recording for anyone touching this next:
I ran the same hook against a pristine checkout of Everything else: |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
The pre-commit hook pins ruff 0.6.9, which wraps a long assert differently from newer ruff, so the file was not format-stable in CI.
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Comments and docstrings only, no code change.
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
… moves Source-inspection contracts still pointed at openai_chat_completions after unslothai#9187 split produce_openai_chat_completions out, and at strings that unslothai#7880 and unslothai#9683 moved. Point them at the live sites and defer PEP 604 unions in the new kv-cache estimate tests.
) * Studio: add Chat settings to disable or ease GGUF auto-compaction Local GGUF chats always opted into truncate_oldest, then compacted at the prompt budget with a 25% extra trim (or a full checkpoint reset). Settings now let you turn that off, switch to a sliding window, and choose how much extra room a rolling compaction takes. Compaction still keys off the configured context length, not free VRAM. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: honor Chat compaction settings over process defaults Send checkpoint/error overflow fields from Studio so Chat settings override UNSLOTH_CONTEXT_POLICY and UNSLOTH_CONTEXT_OVERFLOW. Refuse checkpoint-origin sticky boundaries when a request forces rolling, and route search_conversation from the same effective policy as the fitter. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * honor zero compaction headroom * test zero-headroom rolling compaction * preserve server compaction policy by default * test server policy inheritance * mark studio-owned tool history * keep studio tool history on the fitted path * isolate studio tool history provenance * test compaction after local tool use * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * complete locale settings translations * fix sanitized catalog guard coverage * run pip cache guard on workflow changes * set utf-8 for pip cache guard reads * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * mark studio tool history in token counts * reset boundaries when context policy changes * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * mark studio tool history from replayed calls Hosted server builtins such as web_search are dropped during OpenAI serialization, so ownership must be derived from the calls that actually go on the wire. Mixed hosted-plus-local history can then keep the studio_tool_history marker and stay on the compaction path. * align prune contract test with token-count history builder The send and count paths both prune through pruneOutboundHistory into survivingMessages; the source contract still expected the old outboundMessages name on the count path. * align sticky and token-count harnesses with current compaction APIs Recall fixtures store rolling-shaped truncation records, so pin CONTEXT_POLICY to rolling when faking studio_db. Recount and prune harnesses follow the renamed token-count builder, a tighter setActiveThreadId slice, and the send-path prune call rather than the earlier count-path copy. * test(studio): follow main's chat-completions extract and VRAM/keyless moves Source-inspection contracts still pointed at openai_chat_completions after #9187 split produce_openai_chat_completions out, and at strings that #7880 and #9683 moved. Point them at the live sites and defer PEP 604 unions in the new kv-cache estimate tests. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * drop the duplicate workflow guard entry this pr added tests/studio/test_pip_cache_naming.py was already listed at line 141 of .github/workflows/workflow-trigger-lint.yml, so the Workflow guard suites step collected it twice. The trailing newline it also removed goes back. * keep the eviction bite for requests that chose no compaction setting fit_rolling_context gated the 5% floor on each eviction bite on `headroom > 0`, but keeps_boundary = False zeroes the headroom for every threadless API request and incognito chat. Those callers send no new field, so they were handed the "no extra trim" behaviour anyway: on a 201-message transcript at context_length 1100 eviction fell from 12 messages to 2. Gate it on the requested ratio instead, so only a caller that actually asked for no extra trim gives the floor up. * replay a rolling boundary where the fit cannot start an epoch _sticky_compaction_boundary rejected any boundary whose recorded policy differed from the process policy, in both directions. The rolling-to-checkpoint direction is only unsafe where fit_checkpoint_context would read the boundary as an epoch already in force and skip the reset's recall, and that needs _can_reset_epoch. Threads it refuses -- a template that cannot render tools, --disable-tools, no conversation archive -- compact through fit_rolling_context and record a rolling boundary, so on a checkpoint-default server every later turn discarded it and the boundary slid again. Measured on a stored boundary of 6: base restored 6, this branch returned 0. Each call site now computes _can_reset_epoch once and hands the same value to the boundary read and to the fit. * declare studio_tool_history on the token-count request refreshContextUsage forwards the marker, but ChatCountTokensRequest only carried it through extra = "allow", which coerces nothing. A client sending the JSON string "false" reached _only_studio_tool_history as a truthy value and moved the count onto the Unsloth tool path the completion never takes, so the context-usage bar priced a different prompt. The model's own bypass_permissions field is declared for the same reason. * restore the constraint the renamed tool-history helper documented Renaming _only_studio_memory_tool_history to _only_studio_tool_history replaced its docstring with three lines that say what the marker is and no longer say why the strict route exists: a replayed tool pair read as a client contract sends the turn to the llama-server passthrough, which runs no context fit, so the epoch, the carried-forward block and the automatic recall are gone one turn after the compaction that created them. Put that back, and match the sentence case the rest of the file and the api.ts field comments use. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * keep a rolling boundary off the checkpoint replay branch A request that may not reset still takes the checkpoint REPLAY branch in _fit_context under a checkpoint policy, so the rolling-origin boundary the previous commit restored reached fit_checkpoint_context and read as an epoch already in force. The fit returned checkpoint_started false, and _archive_and_recall reads that as "already recalled" and injected nothing. Measured at context_length 1800 with a stored boundary of 30: the reply lost the archived turns the rolling fallback would have pulled back. _sticky_compaction_state now returns the depth and whether a checkpoint reset recorded it, mixed provenance across surviving rows counting as rolling since min(boundaries) may pick either row. _fit_context takes that as sticky_is_checkpoint and enters the replay branch only for a real epoch; otherwise the count stays on the rolling fitter, which reports no checkpoint_started and still recalls. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * discard a boundary cut with more extra trim than the request asks for Phase one of fit_rolling_context re-applies the saved boundary before anything else and returns as soon as the result fits, so an already-compacted chat that moved from 25% extra room down to 10%, 5% or none replayed the deeper cut and never reached the phase that reads the new ratio. Lowering the setting did nothing at all, and the history the client had re-sent stayed dropped. The persisted truncation now carries boundary_headroom_ratio beside boundary_messages and boundary_anchor, written through one _boundary_metadata helper so the three cannot drift apart. _sticky_compaction_state refuses a rolling boundary recorded under a larger ratio than this request wants; a larger request needs no refusal, since phase two moves the boundary out by itself. Rows saved before the ratio existed carry no key and replay as they did, and a checkpoint reset ignores headroom so its depth is never refused over it. * refuse a replayed boundary on any change of extra trim, not just a cut The previous commit only refused a boundary recorded under MORE headroom than the request asked for, on the reasoning that phase two would widen a shallower one by itself. It does not: phase one re-applies the saved count and phase two runs only when the result still does not fit, so a shallower boundary that already fits is just as inert. Measured on a 121-message transcript at context_length 1600, a stored boundary of 86 gave dropped 86 under both 0.05 and 0.25, so raising the setting did nothing either. Compare for equality instead. With the 5%-origin boundary of 86 above, a request at 0.05 still replays it and a request at 0.25 recomputes to 94. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: mahiatlinux <[email protected]>
) * Studio: add Chat settings to disable or ease GGUF auto-compaction Local GGUF chats always opted into truncate_oldest, then compacted at the prompt budget with a 25% extra trim (or a full checkpoint reset). Settings now let you turn that off, switch to a sliding window, and choose how much extra room a rolling compaction takes. Compaction still keys off the configured context length, not free VRAM. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: honor Chat compaction settings over process defaults Send checkpoint/error overflow fields from Studio so Chat settings override UNSLOTH_CONTEXT_POLICY and UNSLOTH_CONTEXT_OVERFLOW. Refuse checkpoint-origin sticky boundaries when a request forces rolling, and route search_conversation from the same effective policy as the fitter. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * honor zero compaction headroom * test zero-headroom rolling compaction * preserve server compaction policy by default * test server policy inheritance * mark studio-owned tool history * keep studio tool history on the fitted path * isolate studio tool history provenance * test compaction after local tool use * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * complete locale settings translations * fix sanitized catalog guard coverage * run pip cache guard on workflow changes * set utf-8 for pip cache guard reads * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * mark studio tool history in token counts * reset boundaries when context policy changes * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * mark studio tool history from replayed calls Hosted server builtins such as web_search are dropped during OpenAI serialization, so ownership must be derived from the calls that actually go on the wire. Mixed hosted-plus-local history can then keep the studio_tool_history marker and stay on the compaction path. * align prune contract test with token-count history builder The send and count paths both prune through pruneOutboundHistory into survivingMessages; the source contract still expected the old outboundMessages name on the count path. * align sticky and token-count harnesses with current compaction APIs Recall fixtures store rolling-shaped truncation records, so pin CONTEXT_POLICY to rolling when faking studio_db. Recount and prune harnesses follow the renamed token-count builder, a tighter setActiveThreadId slice, and the send-path prune call rather than the earlier count-path copy. * test(studio): follow main's chat-completions extract and VRAM/keyless moves Source-inspection contracts still pointed at openai_chat_completions after #9187 split produce_openai_chat_completions out, and at strings that #7880 and #9683 moved. Point them at the live sites and defer PEP 604 unions in the new kv-cache estimate tests. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * drop the duplicate workflow guard entry this pr added tests/studio/test_pip_cache_naming.py was already listed at line 141 of .github/workflows/workflow-trigger-lint.yml, so the Workflow guard suites step collected it twice. The trailing newline it also removed goes back. * keep the eviction bite for requests that chose no compaction setting fit_rolling_context gated the 5% floor on each eviction bite on `headroom > 0`, but keeps_boundary = False zeroes the headroom for every threadless API request and incognito chat. Those callers send no new field, so they were handed the "no extra trim" behaviour anyway: on a 201-message transcript at context_length 1100 eviction fell from 12 messages to 2. Gate it on the requested ratio instead, so only a caller that actually asked for no extra trim gives the floor up. * replay a rolling boundary where the fit cannot start an epoch _sticky_compaction_boundary rejected any boundary whose recorded policy differed from the process policy, in both directions. The rolling-to-checkpoint direction is only unsafe where fit_checkpoint_context would read the boundary as an epoch already in force and skip the reset's recall, and that needs _can_reset_epoch. Threads it refuses -- a template that cannot render tools, --disable-tools, no conversation archive -- compact through fit_rolling_context and record a rolling boundary, so on a checkpoint-default server every later turn discarded it and the boundary slid again. Measured on a stored boundary of 6: base restored 6, this branch returned 0. Each call site now computes _can_reset_epoch once and hands the same value to the boundary read and to the fit. * declare studio_tool_history on the token-count request refreshContextUsage forwards the marker, but ChatCountTokensRequest only carried it through extra = "allow", which coerces nothing. A client sending the JSON string "false" reached _only_studio_tool_history as a truthy value and moved the count onto the Unsloth tool path the completion never takes, so the context-usage bar priced a different prompt. The model's own bypass_permissions field is declared for the same reason. * restore the constraint the renamed tool-history helper documented Renaming _only_studio_memory_tool_history to _only_studio_tool_history replaced its docstring with three lines that say what the marker is and no longer say why the strict route exists: a replayed tool pair read as a client contract sends the turn to the llama-server passthrough, which runs no context fit, so the epoch, the carried-forward block and the automatic recall are gone one turn after the compaction that created them. Put that back, and match the sentence case the rest of the file and the api.ts field comments use. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * keep a rolling boundary off the checkpoint replay branch A request that may not reset still takes the checkpoint REPLAY branch in _fit_context under a checkpoint policy, so the rolling-origin boundary the previous commit restored reached fit_checkpoint_context and read as an epoch already in force. The fit returned checkpoint_started false, and _archive_and_recall reads that as "already recalled" and injected nothing. Measured at context_length 1800 with a stored boundary of 30: the reply lost the archived turns the rolling fallback would have pulled back. _sticky_compaction_state now returns the depth and whether a checkpoint reset recorded it, mixed provenance across surviving rows counting as rolling since min(boundaries) may pick either row. _fit_context takes that as sticky_is_checkpoint and enters the replay branch only for a real epoch; otherwise the count stays on the rolling fitter, which reports no checkpoint_started and still recalls. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * discard a boundary cut with more extra trim than the request asks for Phase one of fit_rolling_context re-applies the saved boundary before anything else and returns as soon as the result fits, so an already-compacted chat that moved from 25% extra room down to 10%, 5% or none replayed the deeper cut and never reached the phase that reads the new ratio. Lowering the setting did nothing at all, and the history the client had re-sent stayed dropped. The persisted truncation now carries boundary_headroom_ratio beside boundary_messages and boundary_anchor, written through one _boundary_metadata helper so the three cannot drift apart. _sticky_compaction_state refuses a rolling boundary recorded under a larger ratio than this request wants; a larger request needs no refusal, since phase two moves the boundary out by itself. Rows saved before the ratio existed carry no key and replay as they did, and a checkpoint reset ignores headroom so its depth is never refused over it. * refuse a replayed boundary on any change of extra trim, not just a cut The previous commit only refused a boundary recorded under MORE headroom than the request asked for, on the reasoning that phase two would widen a shallower one by itself. It does not: phase one re-applies the saved count and phase two runs only when the result still does not fit, so a shallower boundary that already fits is just as inert. Measured on a 121-message transcript at context_length 1600, a stored boundary of 86 gave dropped 86 under both 0.05 and 0.25, so raising the setting did nothing either. Compare for equality instead. With the 5%-origin boundary of 86 above, a request at 0.05 still replays it and a request at 0.25 recomputes to 94. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: mahiatlinux <[email protected]>
Follow-up to #9102, which merged before this landed. The keyless feature is on
mainnow; this closes a gap in its browser rule and adds the adversarial coverage.The gap
Origindoes not identify a browser. No engine attaches it to a same-origin GET, nor to a cross-site GET issued inno-corsmode, and only Chromium withholds ano-corsfetch aimed athttp://127.0.0.1:<port>, through Private Network Access. Firefox and Safari have not shipped it, so there the request arrives.Measured against a live server on current
main(8e06238e5), replaying the exact shapes those engines emit:no-corsGET/v1/modelsno-corsPOST/v1/unloadOriginThe response is opaque to the page, so this is not a read primitive. It is a blind request primitive and an "is Unsloth Studio running here" oracle, and under
fullit reaches management handlers, where only FastAPI's JSON body requirement stops the POSTs. The guards from #9102 are what hold the line:GET /api/auth/api-keysstill answers 403 through_require_a_credential_of_its_own.The fix
Read
Sec-Fetch-Site. The browser sets it on every request whatever the mode, and a page cannot forge it, because theSec-prefix makes it a forbidden header name. Onlycross-siteandsame-siteare refused.same-originis Studio's own page andnoneis the user typing the URL, so both stay admitted.Absence stays admitted, and has to: curl, the OpenAI SDKs and Safari before 16.4 send no
Sec-Fetch-*at all, and serving them is the point of the setting. That also means the header is only there to be read where the transport is a potentially trustworthy URL, so this narrowsfull, which is loopback-only, more tightly than plain-HTTP LAN inference. It never widens either.After the fix every browser row above is 401, the same-origin row is unchanged, and a 63-case end-to-end run over curl-shaped requests is byte-identical to before.
Tests
New file, so nothing #9102 owns is touched. 15 tests covering what the merged suite asserts only at the predicate layer, only in one direction, or not at all:
scope=offrefused through thesecuritydependency, not only throughscope_coversGET/PUT /api/settings/keyless-api-accessand_require_ui_session_for_keyless, which had no test at all. This is the self-promotion question: a keyless caller must not be able to widen its own scopeAPPROVED_DUMMY_BEARERSclause from the dependency fails it withapi_key was downgraded to keyless on loopback/inferenceinferencefrom a public bind and a public peerinferenceroot_pathand trailing slash driven throughkeyless_request_allowed, not justscope_coversGET /v1/models/prefix pinned to the one handler it can reach. It admits every non-empty suffix rather than an exact pair, so the safety argument rests on route topology; this fails the day a secondGET /models/...route is registeredasgi_request_is_keylesscalled directly. The duplicate-header rule has three implementations and only one was covered_hosted_mode_forbiddenflag, includinglan_access_is_colabandlan_access_secure_launchfulldenials with_remote_connector_activecleared. In the merged suite it is leftTrue, so the wildcard-bind and LAN denials pass even if_full_scope_transport_allowedis deletedVerification
test_tool_result_fits_window, fails identically on plainmainand is unrelatedbiome checkerror free. The middle commit annotates thecloudflareUrltrigger dependency, which was the one Biome error the feature shipped withStill open from the #9102 review, not changed here
keyless_transport_allowedreturnsTrueon the LAN branch before it consults_public_tunnel_active, so an active tunnel disables keyless for loopback but not for the LAN listener. Not exploitable through Studio's own tunnel, which targetshttp://localhost:<port>and so presents a loopback peer, but the #9102 description says keyless is disabled "even for localhost until that exposure stops" and the code does less than that. Left alone as a product call. Separately,_names_a_sessionandbearer_names_a_sessionhave no callers anywhere in the repo.Added during review: DNS rebinding
Codex raised a P1 on the
same-originbranch, and it was right. I reproduced it at the previous head before changing anything: scopefull,GET /api/chat/threadswithHost: evil.example:8888andSec-Fetch-Site: same-originwas admitted.DNS rebinding produces every local signal the transport checks read. A page on
evil.examplewhose record is re-pointed at127.0.0.1keeps its own origin, so the fetch is same-origin: noOrigin,Sec-Fetch-Site: same-origin, and a loopback peer on a loopback socket. Unlike theno-corscase above, the response is readable by the page.This predates the branch, since a same-origin GET carries no
Originand the existing rule never fired either. Butsame-originis a positive signal this branch introduces, so the check belongs with it._host_authority_is_directcloses it. A direct client addresses the socket by literal address orlocalhost; only a rebound page sends a domain, because the browser sends the name the page was served from. AbsentHoststays admitted, since the merged suite and HTTP/1.0 callers send none and no browser omits it. Bracketed IPv6 junk such as[::1]evil.exampleis rejected rather than parsed, matching what_host_header_is_loopbackalready does for the bootstrap path.Host: evil.example:8888,Sec-Fetch-Site: same-originHost: localhost.evil.example:8888Host: 127.0.0.1:8888(curl, SDK)Host: localhost:8888HostheaderOne narrow cost worth naming: reaching Studio keylessly through a private hostname such as
studio.internal:8888now needs a key. That is fail-closed, and the right default for a setting that removes authentication.