Skip to content

Studio: add an opt-in one-time link token for the Colab same-tab URL - #9850

Closed
danielhanchen wants to merge 7 commits into
unslothai:mainfrom
danielhanchen:feat/studio-colab-one-time-link-token
Closed

danielhanchen wants to merge 7 commits into
unslothai:mainfrom
danielhanchen:feat/studio-colab-one-time-link-token

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

Split out of #7392 so the headless auto-password path can land on its own, per review.

Draft on purpose. Two things below must land before this is mergeable.

Summary

A one-time, ~10 minute HMAC-signed link token for the Colab same-tab proxy URL only, never the shared Cloudflare link. It is signed with a key derived from the admin's JWT secret and domain-separated with a distinct label, so a link token can never validate on the bearer access-token path; it is single-use via a link_tokens nonce table, constant-time verified, expiry-enforced, bound to the admin identity, and never logged.

  • New backend endpoint POST /api/auth/link-exchange consumes a valid unexpired unused token exactly once and returns the same JWT + refresh pair the login path issues.
  • storage.update_password deletes outstanding link_tokens in the same transaction as the rotation, so an exchange that read the pre-rotation key cannot still consume its jti.
  • Auth request bodies are capped at 64 KiB and the token itself at 4096 chars.
  • The Colab helper appends ?link_token=... to the same-tab URL only, behind start(link_token=True) or UNSLOTH_STUDIO_COLAB_LINK_TOKEN=1. Default off.

Why this is a draft

1. The frontend does not consume the token yet. Until it reads the value, POSTs it to /link-exchange and scrubs the URL with history.replaceState, opting in emits a bearer credential that buys nothing while adding an unauthenticated exchange surface. "Opt-in and default off" limits exposure but is not on its own a reason to merge an unused authentication endpoint.

2. The token should ride a URL fragment, not a query parameter. A fragment is never sent in the initial HTTP request, so it cannot reach server access logs or a Referer header. Colab persists cell output, so the iframe src is saved with the notebook either way, but the fragment removes the server-side and referrer paths.

Follow-up worth doing here

main grew credential_generation / credential_generation_guard and a refresh_tokens.secret_gen stamp (#9102). The secret_at_exchange rebind in link_exchange is a hand-rolled version of the same idea and should be re-expressed on top of that mechanism.

Note that credential_generation_guard itself cannot wrap update_password: it opens its own connection, runs BEGIN IMMEDIATE and holds that write transaction across the yield, so a nested SQLite write blocks on the RESERVED lock for busy_timeout and then raises database is locked. Its only production caller wraps a non-SQLite write for exactly that reason.

Tests

studio/backend/tests/test_link_token.py: mint/exchange round-trip, single-use rejection, expiry, tampered signature, tampered payload, unknown subject, malformed and oversized input, nesting-bomb rejection, and the /link-exchange route issuing once then rejecting the replay. Plus the body-cap guard in test_middleware.py and the CLI revocation case in test_studio_password_prompt.py.

Local run against the Backend CI invocation: no new failures versus the same command on main.

Stacking

Branched off #7392, so the diff shown here is #7392 + this change (19 files). GitHub will not accept a fork branch as a base, so it cannot be narrowed to the residual diff until #7392 merges; once it does, rebase this on main and the diff drops to the 12 files that are actually this change:

studio/backend/auth/authentication.py, studio/backend/models/auth.py, studio/backend/routes/auth.py, studio/backend/main.py, studio/backend/tests/test_link_token.py, studio/backend/tests/test_middleware.py, studio/backend/tests/test_colab_embed.py, plus the link-token blocks in colab.py, auth/storage.py, unsloth_cli/commands/studio.py and two test files.

To review only this change in the meantime: git diff feat/studio-secure-auto-password..feat/studio-colab-one-time-link-token.

A public launch with no supplied password (--secure, --cloudflare producing a
public tunnel, or Colab start(cloudflare=True)) used to depend on the seeded
bootstrap credential staying live behind a 1 hour shutdown deadline, and refused
outright where that deadline could not arm. When no password is supplied and the
admin still holds the seeded must-change credential, the launch now:

- generates secrets.token_urlsafe(24),
- commits it through update_password, which clears must_change_password, rotates
  the JWT secret, revokes refresh tokens and deletes .bootstrap_password,
- prints the username and password once to a real console, never to the tee'd
  session log, never to argv, never to the auth DB.

Because must_change_password becomes 0, run.py's terminal gate returns without
prompting and Colab's pending check passes, so the tunnel proceeds headlessly
instead of failing closed. The unsloth_cli studio parent gate mirrors the same
behaviour before re-exec. An interactive terminal still gets the masked prompt,
and a supplied --password is respected and never overwritten.

This also replaces colab.py's _finalize_colab_admin_password, which promoted the
plaintext bootstrap password to the real admin password and cached it on disk at
.colab_notebook_login. That cache is now purged rather than written.

storage.update_password gains require_must_change, composed into the same
statement as the existing expect_password_hash guard so exactly one of two racing
writers can win; a rejected guard now rolls back rather than committing. The
desktop secret joins that transaction (gated on preserve_desktop_secret) so a
post-commit failure cannot leave a pre-change desktop credential live against the
new password.

Scope notes: "not written to disk" is a statement about the Studio server, not
about Colab cell output, which the notebook saves; the notebook text now says so.
"Headless" means non-interactive stdin with a real console still attached; a fully
detached service with redirected streams fails closed rather than losing the
credential. --secure with a provably unavailable tunnel still refuses early.

--secure --api-only is no longer refused. That refusal existed because the
bootstrap deadline cannot arm for api-only, so the seeded default would have
stayed live on a public URL; auto-generation removes the premise.

The opt-in one-time Colab link token that this branch previously carried is split
out into its own branch.
pre-commit-ci Bot and others added 3 commits August 27, 2026 09:51
Found by simulating an existing Colab user upgrading and re-running start().

_auto_generate_colab_admin_password purged the pre-unslothai#7392 .colab_notebook_login
cache unconditionally, before the requires_password_change check. For a runtime
that already had a password set, that meant: delete the cache, rotate nothing
(the guard correctly refuses), display nothing, return None.

The removed finalize flow re-displayed that cache on every cell re-run, so it
was a standing recovery surface. Deleting it silently leaves a working password
that the user cannot discover if they cleared their earlier cell output. The
simulation confirmed it: on main the re-run shows the credential; before this
change the upgraded runtime showed nothing and had no remaining copy.

Now the already-set branch loads the cache, and if it still authenticates hands
it back ONCE through the normal one-time card -- labelled as recovered, not
generated, and as the last time it will appear -- and only then removes the file.
A cached copy that no longer authenticates is dropped without being shown, since
displaying it would print a credential that does not work. The CWE-256 fix is
unchanged: the plaintext file goes either way, which is still better than main,
where it persists indefinitely.

Two regression tests cover both branches (valid cache handed back then purged;
stale cache purged silently).

Also documents the auto-generate behaviour in the README, including that the
printed credential is shown once and that a launch with no console refuses
rather than rotating a password nobody could read.
…evoke

Moving clear_desktop_secret inside update_password's transaction changed one
case that nothing covered: a revoke that RAISES.

It used to run post-commit on a second connection, so an OperationalError from a
busy database left the password changed and a pre-change desktop credential live
against it -- a credential that authenticates as this user without the password.
Now the raise unwinds the whole transaction, leaving the old password and the old
desktop secret, which is consistent. Fail closed beats half-applied, but it is a
real behaviour change on a busy WAL database and was asserted nowhere.

Two tests: the raising revoke rolls the rotation back, and preserve_desktop_secret
skips the revoke entirely rather than merely tolerating it (the desktop sets its
first password while authenticated WITH that secret, so revoking it would break
the auto-auth for a change the desktop itself made).
@danielhanchen
danielhanchen force-pushed the feat/studio-colab-one-time-link-token branch from 8a66533 to 7700b67 Compare August 27, 2026 10:39
@danielhanchen

Copy link
Copy Markdown
Member Author

Rebased onto the updated #7392 branch, which picked up a Colab upgrade fix and a pre-commit autofix. The four rebase conflicts were all pre-commit reformatting on the #7392 side colliding with additions here; resolved by keeping this branch's additions.

Verified alongside the parent: the link_tokens table is created by this branch only, an old backend opens a DB containing it without trouble (rollback-safe), and update_password's link-token revocation does not fire collaterally on a rejected compare-and-set. tests/test_link_token.py plus the middleware and CLI cases pass, and the full backend suite shows no new failures against main.

Still draft for the two reasons in the description: the frontend does not consume or scrub the token yet, and it should ride a URL fragment rather than a query parameter.

pre-commit-ci Bot and others added 3 commits August 27, 2026 10:53
…nyone

The headless/Colab auto-password path commits the generated credential before
it writes it to a console, so a terminal that dies in between leaves a live
password nobody has seen. That launch correctly refuses. The next one did not:
must_change_password is 0 by then, so the gate returned early, and the retry
published a public URL for an account no one -- operator included -- could log
into. Verified against main, which still had the seeded credential to fall back
on in the same scenario, so this was a regression introduced with the feature.

Record a sentinel beside auth.db between the commit and a confirmed delivery,
in all three entry points (run.py's terminal gate, the CLI's pre-exec gate, and
the Colab tunnel path). A relaunch that sees it refuses and points at
`unsloth studio reset-password`.

The sentinel stores the committed password_hash rather than being a bare flag,
so any later password change makes it stop matching. That is what keeps it from
bricking an install: on a machine where the file cannot be unlinked (Windows AV,
read-only auth dir) reset-password still releases the guard. A stale, empty or
unreadable sentinel is removed and ignored rather than refusing a launch that
cannot be justified.

No routes, schema, tables, or installer/updater contracts change; the auth route
table stays byte-identical to main. Also correct the README's disk-persistence
claim: it holds for terminal launches, but Colab saves cell output with the
notebook, so the generated password does land in the saved file there.
Split out of the headless auto-password branch so that change can land on its own.

A one-time, ~10 minute HMAC-signed link token for the Colab SAME-TAB proxy URL
only, never the shared Cloudflare link. It is signed with a key derived from the
admin's JWT secret and domain-separated with a distinct label, so a link token can
never validate on the bearer access-token path; it is single-use via a link_tokens
nonce table, constant-time verified, expiry-enforced, bound to the admin identity,
and never logged.

- POST /api/auth/link-exchange consumes a valid unexpired unused token exactly
  once and returns the same JWT + refresh pair the login path issues.
- storage.update_password deletes outstanding link_tokens in the same transaction
  as the rotation, so an exchange that read the pre-rotation key cannot still
  consume its jti.
- Auth request bodies are capped at 64 KiB and the token itself at 4096 chars.
- The Colab helper appends ?link_token=... to the same-tab URL only, behind
  start(link_token=True) or UNSLOTH_STUDIO_COLAB_LINK_TOKEN=1. Default off.

Deliberately a draft. Two things must land before this is mergeable:

1. The frontend does not yet consume the token. Until it reads the value, POSTs it
   to /link-exchange and scrubs the URL with history.replaceState, opting in
   emits a bearer credential that buys nothing while adding an unauthenticated
   exchange surface. "Opt-in and default off" is not sufficient justification on
   its own.
2. The token should ride a URL fragment rather than a query parameter, so it is
   never in the initial HTTP request line and cannot reach server access logs or
   a Referer header. Colab persists cell output, so the iframe src is saved with
   the notebook either way.

Follow-up worth doing here: main grew credential_generation / credential_generation_guard
and a refresh_tokens.secret_gen stamp. The secret_at_exchange rebind in
link_exchange is a hand-rolled version of the same idea and should be re-expressed
on top of that mechanism. Note that credential_generation_guard itself cannot wrap
update_password: it holds its own BEGIN IMMEDIATE across the yield, so a nested
SQLite write would block on the RESERVED lock and raise "database is locked".
@danielhanchen
danielhanchen force-pushed the feat/studio-colab-one-time-link-token branch from 7700b67 to b6278c0 Compare August 27, 2026 11:16
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 27, 2026
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Sep 7, 2026
Re-cut of the link-token half of unslothai#9850 onto current main, carrying only the
token machinery and none of the auto-generated-password work it was stacked on.

- create_link_token / exchange_link_token_with_secret: HMAC-SHA256 over a
  base64url {sub, jti, exp} payload, keyed off the subject's JWT secret with a
  distinct domain-separation label so a link token can never validate on the
  bearer access-token path. Canonical base64 decode, constant-time compare.
- link_tokens nonce table. Consumption is a single WHERE-qualified DELETE
  checked by rowcount, so two concurrent exchanges cannot both succeed.
- update_password deletes outstanding link tokens in the same transaction as
  the rotation: a link token authenticates without the password and is keyed
  off the secret being rotated, so it must not outlive it.
- POST /api/auth/link-exchange consumes a token exactly once and returns the
  same JWT and refresh pair /login issues, rate limited through the existing
  login buckets, with the exchange bound to the JWT secret it validated
  against so a consume-before-rotation race cannot mint a surviving session.
- Auth request bodies capped at 64 KiB, tokens at 4096 chars.

Nothing mints a token yet, so this changes no behaviour on its own.

The expiry check now also catches TypeError. It only caught ValueError, so a
signed but timezone-naive "exp" would have escaped the function rather than
being rejected.

The Colab same-tab URL wiring from unslothai#9850 is deliberately left out: it depends
on the auto-password context and is default-off, so it can land separately on
top of this.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant