Repository navigation
Studio auth and bootstrap gates: throttle desktop-login, narrow the tunnel CORS origin, identify Colab's proxy - #11398
Conversation
The route takes no credential, and any body whose secret starts with the "desktop-" prefix reaches a 100,000 iteration PBKDF2 round plus a SQLite transaction before the constant time comparison can reject it. Two bounds its siblings have were missing. It was declared async def, so that work ran on the single uvicorn event loop rather than the threadpool, which is the one thread serving every other request. /identity is already a sync def for exactly this reason. Locally, three unauthenticated clients took the median latency of a trivial GET /api/auth/status from 1.95 ms to 340.92 ms. It also consulted no rate limiter, while /login puts every failure into a per IP bucket first. Failed desktop logins now count against the same unknown user bucket, so an attempt that is already blocked is answered 429 with Retry-After before any KDF runs, and a successful one clears the bucket so a shell holding a stale secret is not locked out by its own retry. The success path is unchanged.
POST /api/auth/login needs no credential and its 401 interpolates _reset_password_command(), which builds an absolute path from os.path.dirname(os.path.abspath(sys.executable)). On a normal user install that string is the home directory, so the body reads "Incorrect password. To reset it, run this in your terminal: /home/<name>/unsloth/.venv/bin/unsloth studio reset-password". The browser served default resolves CORS to ["*"], which Starlette applies by reflecting the caller's Origin, so any page the user has open can read it with one cross origin fetch, well inside the rate limiter's first five attempts. The hint is now given in its PATH form, which the function already produced as its fallback and which is just as actionable. The absolute form is unchanged for the banner and the console, where the audience is the local user. The 429 beside this one already withholds the client IP on the same grounds.
RemoteAccessCORSMiddleware.is_allowed_origin returned True for any origin whenever app.state.cloudflare_url was set, so the origin argument was unused on that branch. In a plain --api-only launch, which is the desktop shell's own launch mode, the startup allowlist is the five Tauri origins; turning on Settings > Remote access replaced that at request time with unconditional per origin reflection and Access-Control-Allow-Credentials: true, on every listener including the loopback socket. Any page the user visited while remote access was on could then read http://127.0.0.1:<port> responses it previously could not: /api/auth/status and its bootstrap deadline, the unauthenticated /api/health fields, /api/auth/identity, and /api/auth/login as a readable guessing oracle. The "null" origin was reflected too. The published URL is now the source of the one origin that needs admitting, compared canonically through _canonical_origin, and everything else falls through to the startup list. Legitimate tunnel use is unaffected: the UI served over the tunnel calls the API on relative URLs and so is same origin, the desktop app keeps its Tauri origins in both states, and non browser clients send no Origin at all. The default browser served mode was already ["*"] and is untouched. test_api_only_cors_tracks_published_public_url pinned the old behaviour with an unrelated origin, so it now pins the tunnel origin and asserts the refusal.
_should_inject_bootstrap decides whether the seeded admin passphrase is embedded in index.html as window.__UNSLOTH_BOOTSTRAP__. Off Colab the test is strict: loopback peer, loopback Host, and none of the five headers in _PROXIED_CLIENT_HEADERS. On Colab the branch returned early and applied one test, that cf-connecting-ip was absent, skipping the peer check, the Host check and four of the five headers. The relaxation itself is right, because Colab's notebook proxy is a remote forwarded-header ingress, which is why run.py gives uvicorn proxy_headers there. Naming a single tunnel vendor is not: ngrok, localtunnel, bore, localhost.run and ssh -R set none of cf-connecting-ip, so publishing the Colab port through any of them read as the local browser and an unauthenticated GET / handed the visitor the plaintext admin credential in the page source. The module said as much already, "never a public tunnel (sets cf-connecting-ip)" here and the same warning in colab.py, and only the tunnel Studio manages itself was covered. The Colab branch now identifies the notebook proxy positively, by its own authority on Host plus the shared header denylist, tolerating only the x-forwarded-for its proxy sets. Anything it cannot attribute falls through to the ordinary loopback refusal, which also means a browser inside the notebook VM keeps its autofill. The window closes at the first password change either way, and the startup banner still prints the credential. The existing Colab test asserted injection for an arbitrary off-loopback Host, which is the defect, so it now uses a real proxy authority, and a new case covers all five headers plus a header-free raw forward.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…s own probes The rate limit added to POST /api/auth/desktop-login counted the compatibility probes the shipped desktop shell posts on purpose. preflight/backend.rs and desktop_backend_owner.rs both POST a deliberately invalid secret and read the 401 as proof the backend is one they can manage, and both literals carry the desktop- prefix, so validate_desktop_secret_with_credential spent the full 100000-iteration PBKDF2 on them and the route then recorded a failure. The shell emits those probes on every preflight, on every 15 second watchdog tick, once per live candidate port across 8888-8908, and around every install mutation, so thirty in a sixty second window is ordinary against a limit of five. Worse, every preflight that finds owner metadata sends the real secret immediately after an invalid probe on the same bucket, and the 429 is raised before validation, so the valid exchange cannot recover it. The shell maps that 429 to desktop_auth_secret_probe_http_429, then Unmanageable, then ExternalConflict: the app reports its own healthy backend as someone else's. Gated on shape instead, before the bucket is read and before the KDF. create_desktop_secret has minted DESKTOP_SECRET_PREFIX + token_urlsafe(48), exactly 64 URL-safe characters, since the credential was introduced, the CLI mints the same shape, and nothing else writes the stored hash, so a candidate of any other shape cannot be the secret and is rejected for free. Both probe literals are 31 and 37 characters. A well-formed guess still pays the KDF and still fills the bucket, which is what the limit was for. The check lives in storage beside the minter, so the shell health probe in main.py gets it too. Two tests in this PR pinned the wrong candidate: they used desktop-invalid and desktop-stale, which are exactly the shapes that must not be counted. They now use a well-formed wrong secret and a rotated real one.
A successful POST /api/auth/desktop-login called _clear_login_bucket, which
pops the per-IP aggregate and its overflow entry as well as the route's own
bucket. That aggregate is what stops password spraying across many usernames,
none of which reaches its own per-account limit, so clearing it hands every
account behind the same address a fresh thirty-failure budget.
The desktop secret is not proof that anyone signed in. In multi-user mode the
route says so itself: it returns login_required and no session, because the
secret proves the shell owns the backend and nothing about which account is
using it. It was clearing other users' password-failure history on the way to
saying that. Reproduced: twenty-nine sprayed guesses, one desktop exchange,
aggregate 29 to 0, response {"login_required":true,"login_mode":"multi"}.
_clear_login_bucket takes ip_aggregate now, and desktop-login passes False, so
it still clears the bucket its own misses filled and the shell is still not
locked out by its own earlier miss. /login is untouched: a password success
there proves an account, and it already reset the aggregate before this PR.
On merge-base this route touched no bucket at all, so the coupling arrived with
the throttle in this PR rather than predating it.
|
@codex security review |
test_posix_is_untouched spoofs os.name = posix, then builds its expected command from tmp_path. On Windows that path is a real Windows path, so shlex.quote escapes its backslashes and the test compares POSIX quoting against a Windows path: - C:\Users\runneradmin\...\bin\unsloth studio reset-password + 'C:\Users\runneradmin\...\bin\unsloth' studio reset-password Pre-existing and independent of this PR: the file is byte identical through that assertion at the merge base, and the failure depends only on the runner's path separator. It surfaced here because this PR is the first to run studio/backend/tests/test_reset_password_command.py on a Windows runner. The POSIX branch cannot be exercised with a Windows path, since the command builder stats the file it names, so there is no POSIX-shaped path to hand it on that host. Skipped with the reason rather than weakened, and the Windows branches keep their own coverage in test_windows_*.
…n-user one /login 429s on max(its own account bucket, the unknown-user bucket) but never writes the second one: an unknown username is recorded per name, deliberately, so the shared slot is not an existence oracle. At the merge base that bucket had no writer at all, only a read and a clear. The throttle added here made desktop-login its first, so five unauthenticated desktop attempts rejected every account's correct password for the next sixty seconds, renewably at five requests a minute. Behind a published tunnel that is not per attacker. UNSLOTH_STUDIO_TRUST_FORWARDED is off by default, so _client_ip falls back to request.client.host and every tunnel visitor arrives as the same cloudflared peer: one caller locks out the whole installation. Reproduced on the previous head: a correct password returns 200, five unauthenticated POSTs to /api/auth/desktop-login with a well formed wrong secret, the same correct password returns 429 with 59 seconds to wait. Desktop-login now uses its own sentinel and still contributes to the shared per-IP aggregate, exactly as /login does, so cross-route spray accounting is unchanged and only the five-in-a-minute amplification through a bucket nothing else writes is gone.
|
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". |
Comment lines only, AST verified: six multi-line blocks collapsed where the extra lines restated the one above rather than carrying their own fact. Every surviving line names a mistake the next reader would otherwise make, which is the bar for keeping one.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b894b56426
ℹ️ 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".
| blocked_for = _login_blocked(key) | ||
| if blocked_for > 0: | ||
| raise HTTPException( | ||
| status_code = status.HTTP_429_TOO_MANY_REQUESTS, | ||
| detail = (f"Too many failed login attempts. " f"Try again in {blocked_for} seconds."), | ||
| headers = {"Retry-After": str(blocked_for)}, | ||
| ) | ||
|
|
||
| verified = storage.validate_desktop_secret_with_credential(payload.secret) |
There was a problem hiding this comment.
Reserve throttle slots before running the KDF
When multiple well-formed guesses arrive concurrently, every sync handler can observe an empty bucket here before any handler finishes the PBKDF2 and records its failure at line 581. Consequently, a remote unauthenticated caller can make up to the thread-pool concurrency worth of expensive validations at once, occupying the worker pool and exceeding the intended five-attempt cap; the new throttle only constrains sequential requests. Reserve/count an attempt atomically before starting validation, then undo that reservation when the credential succeeds.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Real as a property, but not this PR's and not fixable here without making the limiter less consistent than it is now, so declining.
Check-then-record is the shape /login has had on these exact helpers since before this PR: blocked_for = max(_login_blocked(key), _login_blocked(unknown_key)), then hashing.equalize_login_work or verify_password, then _record_login_failure(key). Nothing reserves a slot between the read and the write there either, so the same concurrent burst has always been available on the route that actually takes a username and a password.
It is also not cheaper there, measured on this head, three requests each:
desktop-login, well-formed miss : 27.99 ms/req
/login, unknown username : 24.76 ms/req (equalize_login_work)
/login, known user wrong password : 23.96 ms/req (verify_password)
The burst ceiling is anyio's default thread limiter, 40 tokens, which is shared by every sync route in the app including /identity, so a reservation on this one route does not bound the pool either.
Reserving atomically is the right fix, and it belongs across the limiter rather than on one caller: _login_blocked and _record_login_failure would take a combined reserve-and-check, every route that spends a KDF would use it, and the reservation would have to be released on success, on the 401 path, and on an exception, or a crashed handler leaks an attempt forever. That is a change to shared authentication throttling with its own failure modes, and doing it on /desktop-login alone would leave /login exposed while the two routes disagree about what the same bucket means.
What this PR is responsible for is narrower and is done: sequential unauthenticated attempts no longer buy unbounded KDF work, malformed candidates buy none at all, and the bucket is no longer shared with the one /login reads.
… own account slot The distinct sentinel stopped desktop failures from filling the bucket /login reads. It did not stop the reverse: _login_blocked also consults the shared _LOGIN_IP_BUCKETS aggregate and its overflow shard, both of which /login fills, so thirty password guesses across thirty usernames still put the shell's VALID secret exchange at 429. That is one address, not two. cloudflared reaches the backend over loopback and so does the desktop shell, and UNSLOTH_STUDIO_TRUST_FORWARDED is off by default, so a remote tunnel visitor and the local shell share request.client.host. A visitor spraying once a minute keeps the shell locked out of its own backend, which it reads as ExternalConflict, exactly the failure the first fix in this branch removed. Reproduced on the previous head: valid secret 200, thirty password guesses from the same peer, same valid secret 429 with 59 seconds to wait. The address in the desktop key is suffixed as well as the username, so the aggregate and the overflow shard are this route's own in both directions, with no change to the limiter's signatures. /login keeps its aggregate and is still throttled by it, which the same test asserts. On merge base this route consulted no bucket at all, so both couplings arrived with the throttle rather than predating it.
The ip_aggregate flag was added when the desktop key still shared /login's address, where clearing the aggregate would have handed every account behind the same NAT a fresh password-guessing budget. Suffixing the address removed that reason: the desktop aggregate is now its own entry, and clearing it cannot touch /login's. Leaving the skip in place was a leak. Failures accumulated in a bucket nothing ever cleared, so thirty rotate-then-reconnect cycles inside one window reached _LOGIN_IP_MAX_FAILS and put a VALID secret at 429. The flag had one caller and no reason left, so it is gone rather than set to True. test_a_desktop_success_clears_its_own_ip_aggregate runs _LOGIN_IP_MAX_FAILS miss-then-success cycles and fails with assert 429 == 200 without this. The isolation guard is unchanged and still passes, which is the point: what separates the two routes is the suffixed address, not a flag on the clear, and it now asserts that directly.
…of the 401 Splitting the reset hint left _reset_password_command() with no production caller at all, so the absolute form it exists to build was printed nowhere and the only recovery instruction any user saw was the bare PATH form. Studio launched from a managed or custom virtual environment need not have an unsloth shim on PATH, and then that hint does not resolve, or resolves to a different installation. Putting the path back in the 401 is the leak this branch exists to close: that body is produced before any credential is verified and the browser-served default resolves CORS to ["*"], so it is readable by any page the user has open. The two forms go to two different audiences instead. run.py's public-bind and reachable-bind warnings now print the absolute command. Both are stderr on the host, read by the person sitting at the machine, which is exactly where naming the install is the point and where a bare unsloth may not resolve. Local imports, matching the existing routes.inference imports in the same file. The 401 keeps the PATH form and now says which environment to run it in, which costs no disclosure and answers the case where a bare unsloth is not on PATH. test_the_console_warnings_name_the_absolute_command holds the wiring, so the helper cannot quietly go dead again. This also makes true a sentence the description had been carrying since the split: the absolute form is for the console banner, and now there is one.
|
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". |
Backend CI and Frontend CI have been failing on main since this morning, so every open PR inherits them. Four separate causes, none of which is a defect in the behaviour being guarded. tests/test_source_read_encoding.py, two offenders. unslothai#11398 added a read of run.py in test_reset_password_command.py and unslothai#11402 added a read of the llama prebuilt module in test_selection_logic.py, both with the platform default encoding, which breaks on Windows the moment either file gains a non-ASCII byte. The guard is right and the reads are wrong. Both now pass encoding = "utf-8". test_sidebar_exposes_queue_activity_for_each_thread pinned the literal "{showWorkSpinner && (". unslothai#11408 moved the working row's spinner to the trailing column and wrote the same gate as "{showWorkSpinner ? (", which mounts the same element under the same condition, so a correct change failed. It now asks gates_the_markup whether showWorkSpinner conditions mounted markup, which reads both spellings and rejects the inverted ternary that only looks like a guard. That is stricter than the old literal in the way that matters here: showWorkSpinner also picks class strings in this file, so a plain substring search would have gone on passing after the spinner stopped being rendered at all. The ANSI browser smoke failed with "element(s) not found". The real cause is that unslothai#11425 gave the transcript code cell an icon button with a tooltip, and CodeExecutionResultOutput renders it. Tooltip throws outside TooltipProvider, which takes the whole React root down, so every pane on the page went missing. The app mounts these components inside the provider tree in app/provider.tsx; the smoke page mounts them bare and had no provider of its own. It does now. The second half of that one is the reason it was hard to read. echo_browser_errors printed the pageerror and nothing acted on it, so the run failed fifteen seconds later on a locator timeout, with the real message sitting further up a log that otherwise looked fine. It now returns the uncaught errors and the smoke fails with them, which is what its own docstring says it exists to prevent. Returning is additive; callers that ignore it are unchanged. Verified by running the smoke both ways against a real browser: with the provider all five panes render clean text, and without it the run now stops immediately with "the smoke page threw before rendering, so no pane exists to check: `Tooltip` must be used within `TooltipProvider`". The four checks still red after this are the ones unslothai#11404 fixes.
…unnel CORS origin, identify Colab's proxy (unslothai#11398) * Studio: rate limit and unblock POST /api/auth/desktop-login The route takes no credential, and any body whose secret starts with the "desktop-" prefix reaches a 100,000 iteration PBKDF2 round plus a SQLite transaction before the constant time comparison can reject it. Two bounds its siblings have were missing. It was declared async def, so that work ran on the single uvicorn event loop rather than the threadpool, which is the one thread serving every other request. /identity is already a sync def for exactly this reason. Locally, three unauthenticated clients took the median latency of a trivial GET /api/auth/status from 1.95 ms to 340.92 ms. It also consulted no rate limiter, while /login puts every failure into a per IP bucket first. Failed desktop logins now count against the same unknown user bucket, so an attempt that is already blocked is answered 429 with Retry-After before any KDF runs, and a successful one clears the bucket so a shell holding a stale secret is not locked out by its own retry. The success path is unchanged. * Studio: keep the install path out of the login failure body POST /api/auth/login needs no credential and its 401 interpolates _reset_password_command(), which builds an absolute path from os.path.dirname(os.path.abspath(sys.executable)). On a normal user install that string is the home directory, so the body reads "Incorrect password. To reset it, run this in your terminal: /home/<name>/unsloth/.venv/bin/unsloth studio reset-password". The browser served default resolves CORS to ["*"], which Starlette applies by reflecting the caller's Origin, so any page the user has open can read it with one cross origin fetch, well inside the rate limiter's first five attempts. The hint is now given in its PATH form, which the function already produced as its fallback and which is just as actionable. The absolute form is unchanged for the banner and the console, where the audience is the local user. The 429 beside this one already withholds the client IP on the same grounds. * Studio: admit the tunnel's own origin, not every origin RemoteAccessCORSMiddleware.is_allowed_origin returned True for any origin whenever app.state.cloudflare_url was set, so the origin argument was unused on that branch. In a plain --api-only launch, which is the desktop shell's own launch mode, the startup allowlist is the five Tauri origins; turning on Settings > Remote access replaced that at request time with unconditional per origin reflection and Access-Control-Allow-Credentials: true, on every listener including the loopback socket. Any page the user visited while remote access was on could then read http://127.0.0.1:<port> responses it previously could not: /api/auth/status and its bootstrap deadline, the unauthenticated /api/health fields, /api/auth/identity, and /api/auth/login as a readable guessing oracle. The "null" origin was reflected too. The published URL is now the source of the one origin that needs admitting, compared canonically through _canonical_origin, and everything else falls through to the startup list. Legitimate tunnel use is unaffected: the UI served over the tunnel calls the API on relative URLs and so is same origin, the desktop app keeps its Tauri origins in both states, and non browser clients send no Origin at all. The default browser served mode was already ["*"] and is untouched. test_api_only_cors_tracks_published_public_url pinned the old behaviour with an unrelated origin, so it now pins the tunnel origin and asserts the refusal. * Studio: identify Colab's proxy instead of excluding one tunnel vendor _should_inject_bootstrap decides whether the seeded admin passphrase is embedded in index.html as window.__UNSLOTH_BOOTSTRAP__. Off Colab the test is strict: loopback peer, loopback Host, and none of the five headers in _PROXIED_CLIENT_HEADERS. On Colab the branch returned early and applied one test, that cf-connecting-ip was absent, skipping the peer check, the Host check and four of the five headers. The relaxation itself is right, because Colab's notebook proxy is a remote forwarded-header ingress, which is why run.py gives uvicorn proxy_headers there. Naming a single tunnel vendor is not: ngrok, localtunnel, bore, localhost.run and ssh -R set none of cf-connecting-ip, so publishing the Colab port through any of them read as the local browser and an unauthenticated GET / handed the visitor the plaintext admin credential in the page source. The module said as much already, "never a public tunnel (sets cf-connecting-ip)" here and the same warning in colab.py, and only the tunnel Studio manages itself was covered. The Colab branch now identifies the notebook proxy positively, by its own authority on Host plus the shared header denylist, tolerating only the x-forwarded-for its proxy sets. Anything it cannot attribute falls through to the ordinary loopback refusal, which also means a browser inside the notebook VM keeps its autofill. The window closes at the first password change either way, and the startup banner still prints the credential. The existing Colab test asserted injection for an arbitrary off-loopback Host, which is the defect, so it now uses a real proxy authority, and a new case covers all five headers plus a header-free raw forward. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: do not spend the desktop-login throttle on the desktop shell's own probes The rate limit added to POST /api/auth/desktop-login counted the compatibility probes the shipped desktop shell posts on purpose. preflight/backend.rs and desktop_backend_owner.rs both POST a deliberately invalid secret and read the 401 as proof the backend is one they can manage, and both literals carry the desktop- prefix, so validate_desktop_secret_with_credential spent the full 100000-iteration PBKDF2 on them and the route then recorded a failure. The shell emits those probes on every preflight, on every 15 second watchdog tick, once per live candidate port across 8888-8908, and around every install mutation, so thirty in a sixty second window is ordinary against a limit of five. Worse, every preflight that finds owner metadata sends the real secret immediately after an invalid probe on the same bucket, and the 429 is raised before validation, so the valid exchange cannot recover it. The shell maps that 429 to desktop_auth_secret_probe_http_429, then Unmanageable, then ExternalConflict: the app reports its own healthy backend as someone else's. Gated on shape instead, before the bucket is read and before the KDF. create_desktop_secret has minted DESKTOP_SECRET_PREFIX + token_urlsafe(48), exactly 64 URL-safe characters, since the credential was introduced, the CLI mints the same shape, and nothing else writes the stored hash, so a candidate of any other shape cannot be the secret and is rejected for free. Both probe literals are 31 and 37 characters. A well-formed guess still pays the KDF and still fills the bucket, which is what the limit was for. The check lives in storage beside the minter, so the shell health probe in main.py gets it too. Two tests in this PR pinned the wrong candidate: they used desktop-invalid and desktop-stale, which are exactly the shapes that must not be counted. They now use a well-formed wrong secret and a rotated real one. * Studio: keep /login's per-IP throttle out of a desktop-secret exchange A successful POST /api/auth/desktop-login called _clear_login_bucket, which pops the per-IP aggregate and its overflow entry as well as the route's own bucket. That aggregate is what stops password spraying across many usernames, none of which reaches its own per-account limit, so clearing it hands every account behind the same address a fresh thirty-failure budget. The desktop secret is not proof that anyone signed in. In multi-user mode the route says so itself: it returns login_required and no session, because the secret proves the shell owns the backend and nothing about which account is using it. It was clearing other users' password-failure history on the way to saying that. Reproduced: twenty-nine sprayed guesses, one desktop exchange, aggregate 29 to 0, response {"login_required":true,"login_mode":"multi"}. _clear_login_bucket takes ip_aggregate now, and desktop-login passes False, so it still clears the bucket its own misses filled and the shell is still not locked out by its own earlier miss. /login is untouched: a password success there proves an account, and it already reset the aggregate before this PR. On merge-base this route touched no bucket at all, so the coupling arrived with the throttle in this PR rather than predating it. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: skip the POSIX reset-password assertion on Windows test_posix_is_untouched spoofs os.name = posix, then builds its expected command from tmp_path. On Windows that path is a real Windows path, so shlex.quote escapes its backslashes and the test compares POSIX quoting against a Windows path: - C:\Users\runneradmin\...\bin\unsloth studio reset-password + 'C:\Users\runneradmin\...\bin\unsloth' studio reset-password Pre-existing and independent of this PR: the file is byte identical through that assertion at the merge base, and the failure depends only on the runner's path separator. It surfaced here because this PR is the first to run studio/backend/tests/test_reset_password_command.py on a Windows runner. The POSIX branch cannot be exercised with a Windows path, since the command builder stats the file it names, so there is no POSIX-shaped path to hand it on that host. Skipped with the reason rather than weakened, and the Windows branches keep their own coverage in test_windows_*. * Studio: give desktop-login its own throttle slot, not /login's unknown-user one /login 429s on max(its own account bucket, the unknown-user bucket) but never writes the second one: an unknown username is recorded per name, deliberately, so the shared slot is not an existence oracle. At the merge base that bucket had no writer at all, only a read and a clear. The throttle added here made desktop-login its first, so five unauthenticated desktop attempts rejected every account's correct password for the next sixty seconds, renewably at five requests a minute. Behind a published tunnel that is not per attacker. UNSLOTH_STUDIO_TRUST_FORWARDED is off by default, so _client_ip falls back to request.client.host and every tunnel visitor arrives as the same cloudflared peer: one caller locks out the whole installation. Reproduced on the previous head: a correct password returns 200, five unauthenticated POSTs to /api/auth/desktop-login with a well formed wrong secret, the same correct password returns 429 with 59 seconds to wait. Desktop-login now uses its own sentinel and still contributes to the shared per-IP aggregate, exactly as /login does, so cross-route spray accounting is unchanged and only the five-in-a-minute amplification through a bucket nothing else writes is gone. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: tighten the comments added by this PR Comment lines only, AST verified: six multi-line blocks collapsed where the extra lines restated the one above rather than carrying their own fact. Every surviving line names a mistake the next reader would otherwise make, which is the bar for keeping one. * Studio: give desktop-login its own per-IP aggregate too, not just its own account slot The distinct sentinel stopped desktop failures from filling the bucket /login reads. It did not stop the reverse: _login_blocked also consults the shared _LOGIN_IP_BUCKETS aggregate and its overflow shard, both of which /login fills, so thirty password guesses across thirty usernames still put the shell's VALID secret exchange at 429. That is one address, not two. cloudflared reaches the backend over loopback and so does the desktop shell, and UNSLOTH_STUDIO_TRUST_FORWARDED is off by default, so a remote tunnel visitor and the local shell share request.client.host. A visitor spraying once a minute keeps the shell locked out of its own backend, which it reads as ExternalConflict, exactly the failure the first fix in this branch removed. Reproduced on the previous head: valid secret 200, thirty password guesses from the same peer, same valid secret 429 with 59 seconds to wait. The address in the desktop key is suffixed as well as the username, so the aggregate and the overflow shard are this route's own in both directions, with no change to the limiter's signatures. /login keeps its aggregate and is still throttled by it, which the same test asserts. On merge base this route consulted no bucket at all, so both couplings arrived with the throttle rather than predating it. * Studio: let a desktop success clear its own IP aggregate again The ip_aggregate flag was added when the desktop key still shared /login's address, where clearing the aggregate would have handed every account behind the same NAT a fresh password-guessing budget. Suffixing the address removed that reason: the desktop aggregate is now its own entry, and clearing it cannot touch /login's. Leaving the skip in place was a leak. Failures accumulated in a bucket nothing ever cleared, so thirty rotate-then-reconnect cycles inside one window reached _LOGIN_IP_MAX_FAILS and put a VALID secret at 429. The flag had one caller and no reason left, so it is gone rather than set to True. test_a_desktop_success_clears_its_own_ip_aggregate runs _LOGIN_IP_MAX_FAILS miss-then-success cycles and fails with assert 429 == 200 without this. The isolation guard is unchanged and still passes, which is the point: what separates the two routes is the suffixed address, not a flag on the clear, and it now asserts that directly. * Studio: print the absolute reset command on the console, keep it out of the 401 Splitting the reset hint left _reset_password_command() with no production caller at all, so the absolute form it exists to build was printed nowhere and the only recovery instruction any user saw was the bare PATH form. Studio launched from a managed or custom virtual environment need not have an unsloth shim on PATH, and then that hint does not resolve, or resolves to a different installation. Putting the path back in the 401 is the leak this branch exists to close: that body is produced before any credential is verified and the browser-served default resolves CORS to ["*"], so it is readable by any page the user has open. The two forms go to two different audiences instead. run.py's public-bind and reachable-bind warnings now print the absolute command. Both are stderr on the host, read by the person sitting at the machine, which is exactly where naming the install is the point and where a bare unsloth may not resolve. Local imports, matching the existing routes.inference imports in the same file. The 401 keeps the PATH form and now says which environment to run it in, which costs no disclosure and answers the case where a bare unsloth is not on PATH. test_the_console_warnings_name_the_absolute_command holds the wiring, so the helper cannot quietly go dead again. This also makes true a sentence the description had been carrying since the split: the absolute form is for the console banner, and now there is one. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Backend CI and Frontend CI have been failing on main since this morning, so every open PR inherits them. Four separate causes, none of which is a defect in the behaviour being guarded. tests/test_source_read_encoding.py, two offenders. unslothai#11398 added a read of run.py in test_reset_password_command.py and unslothai#11402 added a read of the llama prebuilt module in test_selection_logic.py, both with the platform default encoding, which breaks on Windows the moment either file gains a non-ASCII byte. The guard is right and the reads are wrong. Both now pass encoding = "utf-8". test_sidebar_exposes_queue_activity_for_each_thread pinned the literal "{showWorkSpinner && (". unslothai#11408 moved the working row's spinner to the trailing column and wrote the same gate as "{showWorkSpinner ? (", which mounts the same element under the same condition, so a correct change failed. It now asks gates_the_markup whether showWorkSpinner conditions mounted markup, which reads both spellings and rejects the inverted ternary that only looks like a guard. That is stricter than the old literal in the way that matters here: showWorkSpinner also picks class strings in this file, so a plain substring search would have gone on passing after the spinner stopped being rendered at all. The ANSI browser smoke failed with "element(s) not found". The real cause is that unslothai#11425 gave the transcript code cell an icon button with a tooltip, and CodeExecutionResultOutput renders it. Tooltip throws outside TooltipProvider, which takes the whole React root down, so every pane on the page went missing. The app mounts these components inside the provider tree in app/provider.tsx; the smoke page mounts them bare and had no provider of its own. It does now. The second half of that one is the reason it was hard to read. echo_browser_errors printed the pageerror and nothing acted on it, so the run failed fifteen seconds later on a locator timeout, with the real message sitting further up a log that otherwise looked fine. It now returns the uncaught errors and the smoke fails with them, which is what its own docstring says it exists to prevent. Returning is additive; callers that ignore it are unchanged. Verified by running the smoke both ways against a real browser: with the provider all five panes render clean text, and without it the run now stops immediately with "the smoke page threw before rendering, so no pane exists to check: `Tooltip` must be used within `TooltipProvider`". The four checks still red after this are the ones unslothai#11404 fixes.
Four findings in the Studio backend, each verified against the live code before anything was
changed, each with a regression test that fails without the change.
1.
POST /api/auth/desktop-loginran PBKDF2 unthrottled, on the event loopdesktop_logintook noRequest, called no throttle, and invokedstorage.validate_desktop_secret_with_credentialsynchronously from anasync def. Thatfunction rejects only on the
desktop-prefix and then computes_pbkdf2_desktop_secretbefore it reads the stored hash, so every attempt, including aguess, paid a 100000-iteration KDF on the loop thread. The sibling
/loginraises 429before any KDF, and
/identityis a deliberate sync def with the reason in a commentbeside it. This route had neither.
It is now a sync def taking
Request, and it reuses the exact bucket/loginalready usesfor unknown usernames (
_unknown_user_key,_login_blocked,_record_login_failure,_clear_login_bucket) rather than adding a second limiter. The success path is unchanged,and a success clears the bucket.
2. The 401 body named the install path
_login_failure_detailinterpolated_reset_password_command(), which returns an absolutepath under the interpreter directory on POSIX and the absolute interpreter path on Windows.
The default browser-served CORS mode is
["*"], so that body is readable cross-origin.The function's own existing PATH-form fallback is now factored out as
_reset_password_command_on_path()and used for the HTTP body._reset_password_command()is byte for byte unchanged. The 401 still names an actionable
unsloth studio reset-password.The split initially left
_reset_password_command()with no production caller: it had exactlytwo on
main, both inside_login_failure_detail, and the banners inrun.pyandunsloth_cli/commands/studio.pyused hardcoded literals. That is fixed in section 7 below, whichis where the absolute form now goes.
3. A published tunnel admitted every origin
RemoteAccessCORSMiddleware.is_allowed_originwasThe
originargument is genuinely unused on that branch, and the middleware is wired withallow_credentials = True,allow_methods = ["*"],allow_headers = ["*"]. While a tunnelwas up, any website the user visited could call the API with credentials.
It now derives the single tunnel origin from
cloudflare_urland falls through tosuper()otherwise. Trailing slash and an explicit
:443both normalise to the same origin.This is a narrowing rather than a refusal, and what makes that safe is worth stating: the
frontend leaves
apiBase = ''outside Tauri, so the UI served over the tunnel calls the APIon relative URLs and is same-origin, which Starlette does not apply CORS to at all. The same
holds for the LAN listener via
setup_frontend(..., tunnel_only = True). The only genuinelycross-origin browser client is the Tauri app, whose origins are in the startup list in both
states, and non-browser API clients send no
Origin. The one behaviour removed is athird-party web app that the user deliberately pointed at their tunnel URL cross-origin,
which is outside the model this code states for itself.
4. The Colab bootstrap branch skipped every proxy check
_should_inject_bootstrapwas, on Colab,return request.headers.get("cf-connecting-ip") is None.That excludes one tunnel vendor by name and skips
_is_local_bootstrap_requestentirely, sothe peer check, the Host check and four of the five
_PROXIED_CLIENT_HEADERSnever ran.It now identifies Colab's proxy positively, by the Colab authority on
Hostplus the sharedproxied-header denylist with only
x-forwarded-fortolerated, and otherwise falls throughto
_is_local_bootstrap_requestin every mode.The Colab host suffix list (
colab.googleusercontent.com,.googleusercontent.com,.colab.dev) is taken from this repository's own CSP, which already widensscript-srcandconnect-srcto*.prod.colab.devand*.googleusercontent.com, and from the documentedproxy URL shape. It is not something that could be observed from here. If it is wrong the
failure is fail-closed and cosmetic: the login form is not pre-filled on Colab and
bootstrap_banner_linesstill prints the credential. Worth a real Colab smoke test beforerelease.
Tests
Four existing test files extended, none created. Demonstrated both ways over the same
85-file, 2750-test selection: patched 32 failed (all pre-existing, identical on
main),unpatched 37 failed, the same 32 plus exactly these five:
test_desktop_auth.py::test_desktop_login_validates_off_the_event_looptest_desktop_auth.py::test_desktop_login_throttles_unauthenticated_attemptstest_reset_password_command.py::test_the_unauthenticated_401_body_names_no_host_pathtest_index_bootstrap_loopback.py::test_colab_withholds_from_every_relay_not_just_cloudflaretest_middleware.py::TestRemoteAccessCORS::test_a_published_tunnel_does_not_admit_an_arbitrary_originA set difference both directions shows no regressions. Each fix also carries a non-hostile
case that passes on both trees: the real desktop shell is still admitted after a miss, both
401 bodies still carry an actionable command, the tunnel's own origin is admitted, the Tauri
origins are unaffected, the browser-served default is unchanged, and Colab's notebook proxy
is served while a shareable tunnel is not.
ruff checkis clean,scripts/verify_import_hoist.pypasses andscripts/lint_duplicate_definitions.pyis clean.Two existing tests changed on purpose
test_secure_tunnel_gate.py::test_api_only_cors_tracks_published_public_urlasserted that anarbitrary
https://browser-client.examplegets a 200 preflight while a tunnel is up, andtest_index_bootstrap_loopback.py::test_colab_allows_notebook_proxy_but_not_shareable_tunnelasserted injection for an arbitrary off-loopback Host. Both pinned the defective behaviour.
test_api_only_cors_tracks_published_public_urlnow asserts the intended invariant and failsif the CORS hunk is reverted.
test_colab_allows_notebook_proxy_but_not_shareable_tunneldoesnot: it still passes against the old
cf-connecting-ipbranch, so it is a preservation case,not a guard. The guard for that fix is
test_colab_withholds_from_every_relay_not_just_cloudflare.5. The throttle in (1) counted the desktop shell's own probes
d4c66f06. The shipped Tauri shell POSTs a deliberately invalid secret to this route and readsthe 401 as proof the backend is one it can manage:
desktop-preflight-invalid-secretinstudio/src-tauri/src/preflight/backend.rs:210-214,286-292anddesktop-owner-adoption-invalid-secretinstudio/src-tauri/src/desktop_backend_owner.rs:989-1004.Both carry the
desktop-prefix, sovalidate_desktop_secret_with_credentialspent the full KDFon them and the new limiter recorded a failure.
The rate is not a handful per launch. The health watchdog probes every 15s
(
commands.rs:11to:765) withrequire_desktop_secret = false, so a live app emits fouruncounterbalanced probes a minute. The preflight poll during an install runs every 5s for up to
five minutes (
use-tauri-backend.ts:84-87), the backend-start wait loop backs off 250ms to 5s(
process.rs:3829-3884), andprobe_backend_portswalks 8888-8908. Thirty to forty-five invalidPOSTs in a sixty second window is ordinary, against
_LOGIN_MAX_FAILS = 5on a bucket keyed by IPalone. And it is unrecoverable: every preflight that finds owner metadata sends the real secret
immediately after a probe on the same bucket, the 429 precedes validation, and only a success
clears it. The shell maps that 429 to
desktop_auth_secret_probe_http_429, thenUnmanageable,then
ExternalConflict, so the app reports its own healthy backend as someone else's.Already shipped binaries cannot be changed, so the gate is on shape, before the bucket is read and
before the KDF.
create_desktop_secrethas mintedDESKTOP_SECRET_PREFIX + token_urlsafe(48),exactly 64 URL-safe characters, since
a5eb2e3d5; the CLI mints the same shape and nothing elsewrites the stored hash. Over 200000 samples
token_urlsafe(48)is always exactly 64 characters and200000 minted secrets are all accepted, so an older build's secret still passes here and a new
build's secret still passes an older build. Both probe literals are 31 and 37 characters. Before
the bucket is read, not merely before it is written, because the shell cannot tell a throttled
backend from an incompatible one. A well formed guess still pays the KDF and still throttles at
five: measured, 2.52 ms for a malformed candidate against 24.90 ms for a well formed one. Both 401
branches are byte identical on the wire, headers included.
6. A desktop exchange reset
/login's per-IP throttlead385533. A successful desktop-login called_clear_login_bucket, which pops the per-IPaggregate and its overflow entry as well as the route's own bucket. That aggregate is what stops
password spraying across many usernames, none of which reaches its own per-account limit.
The desktop secret is not proof that anyone signed in. In multi-user mode the route says so
itself: it returns
login_requiredand no session, because the secret proves the shell owns thebackend and nothing about which account is using it. It was clearing other users' failure history
on the way to saying that. Reproduced: twenty-nine sprayed guesses, one desktop exchange, aggregate
29 to 0, response
{"login_required":true,"login_mode":"multi"}._clear_login_buckettakesip_aggregatenow and desktop-login passesFalse, so the shell is still not locked out by itsown earlier miss.
/loginis untouched, where a password success does prove an account andalready reset the aggregate before this PR. On
mainthis route touched no bucket at all, so thecoupling arrived with the throttle here rather than predating it.
Simulation
Base
770f4a47, submittedf28e61de, headad385533.sys.settrace: 9 of 9, 0 never run.is_allowed_originenumerated over 3 allowlists x 7 published values x 21 origins = 441 cells:286 identical, 155 narrowed, 0 widened, 0 raised. The rows where the tunnel's own origin is
refused all need a scheme-less or unparseable
cloudflare_url, whichcloudflare_tunnel._URL_REcannot produce.
_should_inject_bootstrapenumerated over 2 x 21 hosts x 7 header sets x 4 clients = 1176 cells:834 identical, 342 narrowed, 0 widened, 0 raised.
is_allowed_originis the only changed predicate on a per-request path, +2.08 us worstcase and only while a tunnel is up, 200000 calls x 7 repeats. Nothing changed is in a per-token
or per-layer path. No device detection and no prompt or chat template is touched.
pyproject.tomlactually pins, spanning a Starlette major: python3.13.14 / fastapi 0.141.1 / starlette 1.6.0 and python 3.9.21 / fastapi 0.128.8 / starlette
0.49.3, 9 of 9 each, including that the CORS override really is what preflight routes through
and that the sync route runs on an AnyIO worker thread rather than the loop.
<kernel>-<session>-<port>-colab.googleusercontent.com, which is why the first suffix has noleading dot. Still not observed live; if Colab sets any proxied header beyond
x-forwarded-forthe gate fails closed and the only loss is the pre-filled login form.7. The absolute reset command had nowhere left to be printed
a8c0e83c. After (2) the 401 carries only the PATH form, which is right, but_reset_password_command()then had no production caller, so the absolute form was printednowhere. A Studio launched from a managed or custom virtual environment need not have an
unslothshim on
PATH, and then the only recovery instruction any user sees does not resolve, or resolvesto a different installation.
Putting the path back in the 401 is the leak this branch exists to close, so the two forms go to
two different audiences instead:
run.py's public-bind and reachable-bind warnings print the absolute command. Both are stderr onthe host, read by the person at the machine, which is exactly where naming the install is the
point. Local imports, matching the existing
from routes.inference import ...in the same file.The argparse help string is left alone, being static text rather than a runtime instruction. The
401 keeps the PATH form and now names the environment, which costs no disclosure.
8. The new throttle wrote a bucket
/loginreads32645f5d./login429s onmax(_login_blocked(key), _login_blocked(unknown_key))but neverwrites the second: an unknown username is recorded per name, deliberately, so the shared slot is
not an existence oracle. At the merge base that bucket had no writer at all. The throttle in (1)
made
/desktop-loginits first, so five unauthenticated attempts rejected every account's correctpassword for sixty seconds, renewably at five requests a minute.
UNSLOTH_STUDIO_TRUST_FORWARDEDis off by default, so behind a tunnel every visitor arrives as the same cloudflared peer: one
caller, whole installation.
/desktop-loginhas its own sentinel now.9. And it read the per-IP aggregate
/loginfills070100c6anda38cb557. The sentinel closed one direction._login_blockedalso reads_LOGIN_IP_BUCKETSand its overflow shard, which/loginfills, and cloudflared and the desktopshell both reach the backend over loopback, so they are one address: thirty password guesses a
minute kept the shell's VALID secret at 429, which it reads as
ExternalConflict. The address inthe desktop key is suffixed as well as the username, so the aggregate and the shard are this
route's own in both directions, with no change to the limiter's signatures.
That made an earlier flag of mine obsolete and harmful.
ip_aggregate = Falsehad stopped adesktop success clearing an aggregate that was then shared; once the address was suffixed it only
leaked, letting thirty rotate-then-reconnect cycles reach the cap and 429 a valid secret. The flag
had one caller and no reason left, so it is gone and
_clear_login_bucketis back to its originalshape. What isolates the two routes is the suffixed address, and the test asserts that directly.
What this changes on screen
auth-form.tsxrenders the 401'sdetailverbatim (if (errorPayload?.detail) message = errorPayload.detail), so fix 2 is visible on the login card every Studio user meets when they mistype their password. Two isolated installs, BEFORE at the merge base770f4a474and AFTER at4f39f4328, one scene driven against both, identity verified on each side.detailIncorrect password. To reset it, run this in your terminal: <home>/unsloth_studio/bin/unsloth studio reset-passwordIncorrect password. To reset it, run this in your terminal: unsloth studio reset-passwordThe two installs necessarily sit at different paths, so "the paths differ" would prove nothing. The claim asserted per side is categorical: whether that side's own install directory appears in the body at all. It does on the left and does not on the right.
The full login card, for context:
Nothing else in the PR changes what the UI shows: fixes 1, 5 and 6 are status codes on a route only the desktop shell calls, fix 3 is a CORS header, and fix 4 changes whether a password is pre-filled on Colab, which this host cannot reproduce.