Repository navigation
Studio: add secure keyless localhost and private-LAN API access - #9102
Conversation
Studio can only be used from another app after minting an API key in Settings. LM Studio and Ollama serve their endpoints with no credential, so pointing an existing OpenAI-compatible tool at Unsloth means a detour to create and paste a key first. Add a Keyless API access card to Settings > API with two switches, both off by default: one serves the OpenAI-compatible endpoints, the other serves every route. Splitting them means opening up chat does not also hand over training and files. Turning either on opens a confirmation naming who it lets in, worded from how far the server currently reaches; the bind address never blocks the choice. With a scope on, a request that sends no usable credential authenticates as the local admin: no Authorization header, a dummy bearer (the OpenAI SDKs always send one), a malformed header, or a stale key. A key that still works keeps authenticating as itself, so per-key attribution survives. Sign-in is untouched: a session token this install knows stays authoritative, so an expired one still fails and the app re-authenticates. Keyless callers count as API callers, so every guard that already refuses an sk-unsloth key refuses them too, including the saved-provider-credential rules in routes/inference.py. The inference scope names its endpoints one by one because main.py aliases the whole inference router under /v1, where a prefix match would also have opened model loading, media generation and the sandbox routes.
Server-side tools stay off for a keyless caller until the admin ticks "Allow tools", with its own confirmation. /v1/chat/completions drives the python and terminal tool loop on this machine and `unsloth studio run` turns tools on by default, so serving that route without a key would otherwise hand the loop to anyone who can reach it. KeylessToolPolicyMiddleware applies the same tools_force_disabled() the public /p surface already uses. Only a signed-in UI session may change the setting: an sk-unsloth key must not be able to switch authentication off for the whole install, and a keyless caller must not be able to widen its own scope. _request_used_api_key now counts a keyless caller, so the API monitor opens on that traffic instead of filing it as the owner's own chat. The usage-examples snippets take the scope rather than a boolean; the coding agent reaches past /v1, so its command only drops the real key under full.
KeylessToolPolicyMiddleware read every bearer that is not a Studio session as keyless, so a valid sk-unsloth key hit tools_force_disabled() whenever keyless inference was on with the tool grant off. That took tools away from API clients that already had them. asgi_request_is_keyless now also asks whether the bearer validates as a key, matching what _get_current_credential does with it a moment later. A revoked or expired key still falls through to the keyless admin, so it keeps losing tools. Under the full scope an anonymous POST /api/auth/api-keys resolved to the admin credential and minted an sk-unsloth key that went on working after keyless access was switched off. admitted_without_credential is the narrower form of is_keyless: true only when the setting itself is what admitted the caller. A signed-in session and a working key still mint keys as before.
usage-examples.tsx and api-keys-tab.tsx came back through biome at its default 80 columns, and the repo is not formatted to that width. The rewrap split the fromCatalog expression that test_usage_examples_model_source_contract.py reads verbatim, failing test_examples_name_a_model_the_server_can_serve and test_standalone_idle_unload_still_names_the_stored_checkpoint. Both files now carry only the keylessScope wiring.
The tools and advanced variants ask for the built-in python, terminal and web search tools, and KeylessToolPolicyMiddleware refuses them to a keyless caller until the admin ticks the tool grant on. Building all nine snippets from one key meant that with keyless access on and the grant off, a copied tools example ran as plain chat with no sign anything had been dropped. buildSnippets now takes a second key for the six tool-requesting variants, and the panel only puts the dummy key there once the grant is on. KeylessApiAccessSection reports the tool state alongside the scope so the panel can see it.
_settings() published whatever _read_settings() returned. A sqlite read blocks, so a request could be holding the open scope when a concurrent PUT wrote "off" and cached it, then overwrite that with its stale answer. Every request for the rest of the 1s TTL still authenticated as the admin with no key, after the call that closed access had already returned. The two settings also come back through separate connections, so the same interleaving tears the scope from the tool grant. Writes now bump a generation under a lock, and a refresh only publishes when the generation it read under is still current, otherwise it returns the value the write published. test_a_refresh_that_raced_the_closing_write_cannot_republish_the_open_scope drives the interleaving with an event pair and fails on the old code.
…files Revoking a key outlives the setting exactly as minting one does: switching keyless access off does not restore a key it destroyed, so an anonymous caller under the full scope could permanently break every authenticated API client. The guard the mint route carried is now a shared dependency on all three /api-keys routes, with listing included because it is the step that names the key to revoke. The three /api/inference/sandbox routes resolve the bearer themselves, out of the Authorization header or the ?token= query param an <img src> has to use, so `security` never sees them and they answered 401 under a scope that covers them. credentials_for_token builds what the dependency would have, so those routes now follow the full scope, stay outside the inference scope, and keep treating a session token this install knows as authoritative on the query path too.
|
@codex review |
bearer_is_valid_api_key went through validate_api_key, which updates last_used_at inside a BEGIN IMMEDIATE. _get_current_credential then validates the same bearer again a moment later, so every API-key request on a keyless-scoped path counted as two uses and took sqlite's global write lock twice. The stamp belongs to the real validation, not to the advisory check the tool-policy middleware makes on the way past. validate_api_key_with_credential takes touch=False for that caller: same lookup, same expiry and active checks, no write and no write transaction. Every existing caller keeps the default, so the generation a route binds a write to still comes from the transaction that read it.
…full grants Three effects a keyless caller should not reach. With auto-download already on, an unauthenticated request could name any public Hub repo and make the server fetch it, which the inference dialog does not offer: it says the caller gets the loaded model. _maybe_auto_download_model now stops there, past the cheap disqualifiers so the bearer check only runs where a download would otherwise start, and the request falls through to the resident model as it does with auto-download off. A key still starts one, since that is a credential the owner issued. POST /api/auth/logout revokes every refresh token for the subject, and those do not come back when keyless access is switched off, so any reachable caller could sign the UI out again and again. It takes the guard the API-key routes already have, now a small factory so each route names itself in the 403. The full-scope confirmation said callers could read the files and settings. That scope serves every route, delete endpoints included, so the dialog now says read, change and delete at the point the operator consents to it.
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
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". |
# Conflicts: # studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
remote_connector_active answers for the cloudflare tunnel and, since unslothai#8951, for the LAN listener too. access_exposure read that single predicate and called both public_url, so turning keyless access on behind LAN access told the operator anyone with their public URL was being let in when the reach was the local network, and there may be no public URL at all. host_policy grows tunnel_connector_active and lan_connector_active beside the combined reader, which keeps its meaning for the stdio MCP gate. access_exposure asks the tunnel for public_url and the LAN listener for network, so a tunnel still wins when both are up.
…g one The guard added in 50ed867 sat in _maybe_auto_download_model, which _maybe_auto_switch_model only reaches once local resolution misses. With Switch model by request on and several GGUFs already downloaded, a keyless caller could still name any indexed one and evict the operator's active model, over and over. Downloads were blocked, local swaps were not. It moves up to _maybe_auto_switch_model, where clearing auto_switch_on gives the caller exactly the behaviour of the switch being off: the named model must be the one already serving or the request is refused by _reject_unservable_model, never answered by a different model, and no download follows either. The reload stash still runs, so an idle-unloaded model comes back for keyless chat. Placed after the _loaded_identity_satisfies check so the ordinary request that names the serving model returns before anything validates a bearer.
health_check reads its own bearer, so _BearerOrKeyless never saw it: no header returned the unauthenticated payload outright, and a dummy key was wrapped in a plain Bearer credential that get_current_subject then refused. Under the full scope a keyless caller was left without version, device_type, cloudflare_url and server_url on a route that scope covers. It now resolves through credentials_for_token, the same helper the sandbox handlers use. The authed fields stay behind a credential everywhere else: with keyless off there is nothing to stand in for one, and /api/health is not part of the inference scope.
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 00e19f74d9
ℹ️ 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".
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
|
Reviewed this end to end. Summary first: the feature is sound, the reported race is fixed and stale, and merging it does not change anything for anyone who leaves it off. I found one real gap, fixed it, and opened mahiatlinux#3 against this branch since I could not push here directly. Before and after, for someone who never touches the settingThis is the question I cared about most, because I ran the same 25 credential shapes against the merge base
Base takes the first of two conflicting credentials, which is the classic desync footgun. Head rejects. That is the only behaviour change with the feature off, it is a hardening, and no real client sends two I also diffed the pre-existing LAN feature, since Full backend suite as Backend CI runs it: 30414 passed, 155 skipped. The single failure, The reported race@Imagineer99's report was accurate against the then-head. I ran their reproducer from
What I fixed
Worth saying: the guards you added are what keep this from mattering more. Two things for you to decide
Platform coverage41 classifier cases across Linux, Windows, WSL2 in both NAT and mirrored mode, macOS, Docker and IPv6-only, with No GPU axis here, since nothing in the diff reads a device. |
|
Follow-up on one thing I wanted to be certain of rather than reason about: does turning the setting on ever stop a real credential working? No. 27 combinations, valid
That holds even on the transports keyless itself is refused on, which is the interesting part: public bind and public peer, active tunnel, Colab, Note "via credential" rather than "via keyless". Worth keeping deliberate: the middleware classifies a key-bearing request as non-keyless, so an existing API client keeps its own tool policy and never picks up the keyless tool restriction. Pinned as a regression test in mahiatlinux#3. It is mutation-checked, not just green: dropping the One asymmetry that follows from the design and is worth being explicit about in the docs: |
|
Follow-up now that this is merged: the two commits from my review did not land with it, so the cross-site browser gap is currently on Rebased onto main and retargeted as #9683, along with the adversarial suite. mahiatlinux#3 is closed as superseded. Nothing else outstanding on this PR. The two judgement calls from the review are noted in #9683 and left for you: the tunnel check sitting after the LAN branch in |
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.
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.
* serve the api without a key when the user opts in Studio can only be used from another app after minting an API key in Settings. LM Studio and Ollama serve their endpoints with no credential, so pointing an existing OpenAI-compatible tool at Unsloth means a detour to create and paste a key first. Add a Keyless API access card to Settings > API with two switches, both off by default: one serves the OpenAI-compatible endpoints, the other serves every route. Splitting them means opening up chat does not also hand over training and files. Turning either on opens a confirmation naming who it lets in, worded from how far the server currently reaches; the bind address never blocks the choice. With a scope on, a request that sends no usable credential authenticates as the local admin: no Authorization header, a dummy bearer (the OpenAI SDKs always send one), a malformed header, or a stale key. A key that still works keeps authenticating as itself, so per-key attribution survives. Sign-in is untouched: a session token this install knows stays authoritative, so an expired one still fails and the app re-authenticates. Keyless callers count as API callers, so every guard that already refuses an sk-unsloth key refuses them too, including the saved-provider-credential rules in routes/inference.py. The inference scope names its endpoints one by one because main.py aliases the whole inference router under /v1, where a prefix match would also have opened model loading, media generation and the sandbox routes. * keep tools, key minting and the ui switch behind their own gates Server-side tools stay off for a keyless caller until the admin ticks "Allow tools", with its own confirmation. /v1/chat/completions drives the python and terminal tool loop on this machine and `unsloth studio run` turns tools on by default, so serving that route without a key would otherwise hand the loop to anyone who can reach it. KeylessToolPolicyMiddleware applies the same tools_force_disabled() the public /p surface already uses. Only a signed-in UI session may change the setting: an sk-unsloth key must not be able to switch authentication off for the whole install, and a keyless caller must not be able to widen its own scope. _request_used_api_key now counts a keyless caller, so the API monitor opens on that traffic instead of filing it as the owner's own chat. The usage-examples snippets take the scope rather than a boolean; the coding agent reaches past /v1, so its command only drops the real key under full. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * let a working api key keep its tools, and refuse keyless key minting KeylessToolPolicyMiddleware read every bearer that is not a Studio session as keyless, so a valid sk-unsloth key hit tools_force_disabled() whenever keyless inference was on with the tool grant off. That took tools away from API clients that already had them. asgi_request_is_keyless now also asks whether the bearer validates as a key, matching what _get_current_credential does with it a moment later. A revoked or expired key still falls through to the keyless admin, so it keeps losing tools. Under the full scope an anonymous POST /api/auth/api-keys resolved to the admin credential and minted an sk-unsloth key that went on working after keyless access was switched off. admitted_without_credential is the narrower form of is_keyless: true only when the setting itself is what admitted the caller. A signed-in session and a working key still mint keys as before. * drop the formatter churn from the two touched settings files usage-examples.tsx and api-keys-tab.tsx came back through biome at its default 80 columns, and the repo is not formatted to that width. The rewrap split the fromCatalog expression that test_usage_examples_model_source_contract.py reads verbatim, failing test_examples_name_a_model_the_server_can_serve and test_standalone_idle_unload_still_names_the_stored_checkpoint. Both files now carry only the keylessScope wiring. * give the tool snippets a key that actually gets tools The tools and advanced variants ask for the built-in python, terminal and web search tools, and KeylessToolPolicyMiddleware refuses them to a keyless caller until the admin ticks the tool grant on. Building all nine snippets from one key meant that with keyless access on and the grant off, a copied tools example ran as plain chat with no sign anything had been dropped. buildSnippets now takes a second key for the six tool-requesting variants, and the panel only puts the dummy key there once the grant is on. KeylessApiAccessSection reports the tool state alongside the scope so the panel can see it. * do not let a stale refresh reopen the scope a write just closed _settings() published whatever _read_settings() returned. A sqlite read blocks, so a request could be holding the open scope when a concurrent PUT wrote "off" and cached it, then overwrite that with its stale answer. Every request for the rest of the 1s TTL still authenticated as the admin with no key, after the call that closed access had already returned. The two settings also come back through separate connections, so the same interleaving tears the scope from the tool grant. Writes now bump a generation under a lock, and a refresh only publishes when the generation it read under is still current, otherwise it returns the value the write published. test_a_refresh_that_raced_the_closing_write_cannot_republish_the_open_scope drives the interleaving with an event pair and fails on the old code. * keep keyless off credential management, and let it reach the sandbox files Revoking a key outlives the setting exactly as minting one does: switching keyless access off does not restore a key it destroyed, so an anonymous caller under the full scope could permanently break every authenticated API client. The guard the mint route carried is now a shared dependency on all three /api-keys routes, with listing included because it is the step that names the key to revoke. The three /api/inference/sandbox routes resolve the bearer themselves, out of the Authorization header or the ?token= query param an <img src> has to use, so `security` never sees them and they answered 401 under a scope that covers them. credentials_for_token builds what the dependency would have, so those routes now follow the full scope, stay outside the inference scope, and keep treating a session token this install knows as authoritative on the query path too. * stop the middleware key check stamping a use and taking the write lock bearer_is_valid_api_key went through validate_api_key, which updates last_used_at inside a BEGIN IMMEDIATE. _get_current_credential then validates the same bearer again a moment later, so every API-key request on a keyless-scoped path counted as two uses and took sqlite's global write lock twice. The stamp belongs to the real validation, not to the advisory check the tool-policy middleware makes on the way past. validate_api_key_with_credential takes touch=False for that caller: same lookup, same expiry and active checks, no write and no write transaction. Every existing caller keeps the default, so the generation a route binds a write to still comes from the transaction that read it. * hold keyless callers back from downloads and sign-outs, and say what full grants Three effects a keyless caller should not reach. With auto-download already on, an unauthenticated request could name any public Hub repo and make the server fetch it, which the inference dialog does not offer: it says the caller gets the loaded model. _maybe_auto_download_model now stops there, past the cheap disqualifiers so the bearer check only runs where a download would otherwise start, and the request falls through to the resident model as it does with auto-download off. A key still starts one, since that is a credential the owner issued. POST /api/auth/logout revokes every refresh token for the subject, and those do not come back when keyless access is switched off, so any reachable caller could sign the UI out again and again. It takes the guard the API-key routes already have, now a small factory so each route names itself in the 403. The full-scope confirmation said callers could read the files and settings. That scope serves every route, delete endpoints included, so the dialog now says read, change and delete at the point the operator consents to it. * report a lan listener as network reach, not a public url remote_connector_active answers for the cloudflare tunnel and, since #8951, for the LAN listener too. access_exposure read that single predicate and called both public_url, so turning keyless access on behind LAN access told the operator anyone with their public URL was being let in when the reach was the local network, and there may be no public URL at all. host_policy grows tunnel_connector_active and lan_connector_active beside the combined reader, which keeps its meaning for the stdio MCP gate. access_exposure asks the tunnel for public_url and the LAN listener for network, so a tunnel still wins when both are up. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * stop a keyless caller switching the loaded model, not just downloading one The guard added in 50ed867 sat in _maybe_auto_download_model, which _maybe_auto_switch_model only reaches once local resolution misses. With Switch model by request on and several GGUFs already downloaded, a keyless caller could still name any indexed one and evict the operator's active model, over and over. Downloads were blocked, local swaps were not. It moves up to _maybe_auto_switch_model, where clearing auto_switch_on gives the caller exactly the behaviour of the switch being off: the named model must be the one already serving or the request is refused by _reject_unservable_model, never answered by a different model, and no download follows either. The reload stash still runs, so an idle-unloaded model comes back for keyless chat. Placed after the _loaded_identity_satisfies check so the ordinary request that names the serving model returns before anything validates a bearer. * answer /api/health in full for a caller the scope admits health_check reads its own bearer, so _BearerOrKeyless never saw it: no header returned the unauthenticated payload outright, and a dummy key was wrapped in a plain Bearer credential that get_current_subject then refused. Under the full scope a keyless caller was left without version, device_type, cloudflare_url and server_url on a route that scope covers. It now resolves through credentials_for_token, the same helper the sandbox handlers use. The authed fields stay behind a credential everywhere else: with keyless off there is nothing to stand in for one, and /api/health is not part of the inference scope. * refuse external provider routing to a caller admitted without a credential /v1/chat/completions is in the inference scope, and its external-provider branch runs before anything touches the local model. provider_type with a caller-supplied provider_base_url needs no key, since llama.cpp, vLLM and Ollama commonly run without one, and validate_provider_base_url deliberately allows loopback and LAN so those work. Together that let an unauthenticated caller make this host issue requests to whatever it can reach, which is nothing like the loaded model the inference dialog offers. The branch now refuses a caller the setting alone admitted. A key or a signed-in session still routes as before, and the check costs nothing on a request that names no provider. Saved credentials were already withheld separately, so this closes the egress rather than the credential. * Studio: harden keyless LAN API access * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: stabilize keyless auth test collection * Studio: compact keyless access regression tests * Studio: keep keyless auth lookup off event loop * Studio: linearize keyless settings reads * Studio: recheck tools after keyless admission * Studio: publish refreshed keyless settings * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: close remaining keyless review gaps * Studio: preserve compact keyless test matrix * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: finish keyless review convergence * Studio: harden keyless model restore and token lookup * Tests: keep PR coverage at the line budget * fix keyless credential and listener boundaries * fix keyless usage examples * serialize keyless settings writes * close keyless hosted access gaps * tighten keyless credential boundaries * Tests: align keyless MCP CI scaffolding * Studio: show keyless access under Remote and LAN --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Etherll <[email protected]>
* Studio: refuse keyless access to a cross-site browser request 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. * Studio: document the keyless exposure refresh trigger for Biome 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. * Tests: pin that a real credential never stops working 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. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten the keyless comments and drop the stale PR references 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. * Studio: refuse keyless access to a rebound hostname 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. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Tighten the rebinding comments and the last stale PR reference 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. * Studio: match the browser on what loopback spells, before trusting absence 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. * Studio: require an authority the scope could actually be reached at 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). * Studio: answer "is this authority local" in one place 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). * Studio: make the example guard test address classes, not literal syntax 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. * Studio: take the keyless exposure and scope types from the API module 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. * Studio: format the keyless adversarial test with the pinned ruff 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. * Studio: tighten the keyless cross-site comments Comments and docstrings only, no code change. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: danielhanchen <[email protected]>
Secure keyless Studio API access
Unsloth Studio can now serve compatible API clients without requiring the user to mint and paste an API key first. The feature remains off by default and keeps one canonical persisted policy. The same Keyless API Access card is available in both Settings -> API and Settings -> Remote & LAN; both placements read and write the same state.
offinferencefullAgent tools are a separate opt-in and default off. A working API key retains its existing tool policy.
Security boundaries
scope.serverandscope.client;Host, forwarding,Origin, and proxy headers are never trusted for LAN identity.fullis always localhost-only.Originare rejected from keyless admission.inferenceuses an exact HTTP method + normalized path allowlist, including mountedroot_pathhandling. Load, unload, validate, generate/stream, media generation, sandbox/file, external-container, and other management aliases remain authenticated.sk-unsloth-*keys authenticate normally. Expired, revoked, invalid, malformed, duplicate, and arbitrary bearer credentials never downgrade to keyless admin access.not-needed,lm-studio, andollama, and only on otherwise eligible requests.Settings and examples
The richer Keyless API Access card remains authoritative and is reused in both the API and Remote & LAN tabs; there is no second LAN-authentication setting or competing switch. Remote & LAN also shows listener-specific status derived from the same
off | inference | fullscope and separate tool grant. Confirmation copy explains private-LAN inference, localhost-only full access, public/Colab denial, and the separate tool capability. When a public URL or tunnel is active, it explicitly warns that keyless access is disabled even for localhost until that exposure stops.Usage examples use
not-neededonly when the displayed loopback/private-LAN transport can actually be admitted; public URL and Colab examples continue to require a real key. Keyless examples are limited to the resident model and cannot switch, download, or restore an unrelated idle model. A settings or tunnel refresh propagates immediately to the examples so disabling keyless access, tools, or safe exposure cannot leave stale commands visible.LAN consolidation
This incorporates and supersedes the LAN-boundary work from #9611: authoritative listener/peer checks, exact route topology, root-path handling, address-family and hostname coverage, credential precedence, browser-origin rejection, and owner-visible API monitoring. Thank you to @Etherll for that implementation and its regression coverage.
Validation
auth_routes, and the MCP request-admission dependency is now separately overridden throughmcp_routes; the full 9-test dispatch suite passed.e7a23f1b0d089c79daabb8e049c81f9b1523b67f.The branch is synced with
mainate79354e9ec02d52dbd327a138f1145f91f101f3d. The original conflicts instudio/backend/routes/auth.pyandstudio/frontend/src/features/settings/tabs/api-keys-tab.tsxpreserve both current-main behavior and the consolidated keyless/LAN behavior; subsequent current-main merges were conflict-free.