Skip to content

Studio: auto-generate an admin password for headless public launches - #7392

Merged
Etherll merged 23 commits into
unslothai:mainfrom
danielhanchen:feat/studio-secure-auto-password
Sep 1, 2026
Merged

Etherll merged 23 commits into
unslothai:mainfrom
danielhanchen:feat/studio-secure-auto-password

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Rebased onto current main and scoped to the headless auto-password path only. The opt-in one-time link token that this branch used to carry is split into its own branch, per review.

A public launch (--secure, --cloudflare producing a public tunnel, or Colab start(cloudflare=True)) that supplies no password 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 such a launch has no supplied password (no --password / UNSLOTH_STUDIO_PASSWORD / stdin) and the admin still holds the seeded must-change credential, it now:

  • generates a strong secrets.token_urlsafe(24) password,
  • 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.

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 so the two stay in sync. An interactive terminal still gets the masked prompt, and a supplied --password is respected and never overwritten. On --secure with a provably unavailable tunnel the launch still refuses early, since there is no point rotating a recovery credential for a launch that cannot start.

What this also removes

On main today, colab.py _finalize_colab_admin_password promotes the plaintext bootstrap password to the real admin password and caches it to disk at .colab_notebook_login (_store_colab_login_credentials). This branch replaces that path and explicitly purges the legacy cache. That is a bigger change than the original description claimed, so calling it out directly.

storage.update_password

main grew expect_password_hash (compare-and-set on the verified credential, #9102) and now returns the rotated JWT secret rather than a bool. This branch adds require_must_change and composes both guards into the same UPDATE rather than branching per guard: SQLite applies the whole WHERE atomically, so exactly one of two racing writers sees rowcount > 0 no matter which guard the loser tripped. A rejected guard now rolls back rather than committing, so a failed compare-and-set commits nothing at all.

The desktop secret joins that transaction, gated on preserve_desktop_secret. It authenticates as the user without the password and is keyed off the secret being rotated, so a post-commit clear_desktop_secret() on a second connection can raise on a busy database and leave a pre-change desktop credential live against the new password.

require_must_change is technically subsumed by expect_password_hash (every write rehashes with a fresh salt). They are kept separate because they state different policies, and because the auto-generate callers hold no credential to pass; collapsing them is noted in the docstring as follow-up. Routing this through credential_generation_guard() would not work: it holds its own BEGIN IMMEDIATE across the yield, so a nested SQLite write blocks on the RESERVED lock and raises database is locked.

Scope of the claims, stated precisely

  • "Never written to disk" holds for the Studio server's storage, logs, argv and environment. It does not hold for Colab cell output, which is saved with the notebook. The notebook text and the runtime card both say so now.
  • "Headless" means non-interactive stdin with a real console still attached. A fully detached service with redirected stdout/stderr fails closed rather than losing the credential.
  • One-shot recovery. If rotation succeeds, the password is printed, and the tunnel then fails, a retry finds must_change_password already false and will not generate or print again. Recovery is unsloth studio reset-password. Documenting this as the intended model rather than leaving it unstated.

Behaviour change worth flagging

--secure --api-only is no longer refused. That refusal existed because api-only has no login page, so the bootstrap shutdown deadline never armed and the seeded default would have stayed live on a public URL indefinitely. Auto-generation removes the premise rather than working around it: the gate rotates the seeded credential and prints the new one before any re-exec.

Rebase notes

Reconstructed as one commit on current main rather than replaying 23 commits of merges and fixups. Six files conflicted on the old branch; splitting the link token out removed two of them entirely, including a 162-line collision with #9102's keyless-auth block. Several test doubles had drifted and were repaired rather than papered over:

  • _stub_update_password returned a bool. Since update_password now returns Optional[str], False is not None, so the lost-race test passed while the gate displayed a password that would not authenticate. The stub now returns the secret or None.
  • start_studio_tunnel stubs were lambda port:; main added managed_by / admission after the fork.
  • Three reset_password tests encoded the pre-Studio: reset-password rotates the credential in place instead of deleting auth.db #7573 "delete auth.db" contract that main replaced with in-place rotation. Removed; main's seven replacements cover it.
  • Ten flag-forwarding tests asserted argv plumbing but were tripping the new gate, which rotates against the real STUDIO_HOME and fails closed under CliRunner's non-tty streams. The gate is stubbed in those helpers; it has its own suite.

Tests

  • studio/backend/tests/test_colab_secure_autopassword.py: auto-generate sets and clears must-change, no-op when a password is already set, compare-and-set guard, post-commit-cleanup and commit-failure boundaries, start_cloudflare_tunnel auto-generates then proceeds, and never finalizes or caches credentials.
  • studio/backend/tests/test_password_prompt_backstop.py and unsloth_cli/tests/test_studio_password_prompt.py updated to the headless auto-generate contract, including the console tty preflight and the fail-closed no-console path.
  • test_cli_update_password_compare_and_set_guard now also asserts no collateral api_keys revocation on a rejected write. That DELETE has no WHERE clause, so running it past a failed compare-and-set would wipe every key for every user while leaving the password as the winner set it.

Local run against the Backend CI invocation: no new failures versus the same command on main (identical 175-failure baseline, all from optional CI extras absent locally).

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2bdc68ecce

ℹ️ 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".

Comment thread studio/backend/colab.py Outdated
Comment on lines +396 to +397
# Same-tab URL may carry the one-time token; the shared link never does.
same_tab_url = _append_link_token(url, same_tab_link_token)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Complete the enabled link-token handoff

With start(link_token=True) or the environment opt-in, this appends a bearer token to the iframe URL but no frontend source consumes link_token or calls /api/auth/link-exchange (the TODO immediately above confirms this). Consequently users still get the normal login page, while the unused credential remains in the page URL/history until expiry instead of being exchanged and scrubbed; either wire the frontend exchange/scrub before exposing the option or do not mint/append the token.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

link_token is an explicit opt-in, default OFF (start(link_token=True) or UNSLOTH_STUDIO_COLAB_LINK_TOKEN=1); the frontend TODO is documented in _show_and_embed and the start() docstring. On the default path nothing is minted or appended, so there is no leak for a normal user. When opted in, the token rides only the same-tab proxy URL in the operator's own browser (never the shared Cloudflare link) and is single-use with a short TTL. Keeping this as the tracked TODO rather than changing behavior: the frontend exchange + history scrub lands with the same opt-in.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 6e4430875e

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6757025f35

ℹ️ 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".

Comment thread studio/backend/colab.py Outdated
Comment on lines +765 to +768
if _is_colab_runtime():
if _embed_kernel_port_iframe(port):
return
_embed_html_iframe(url, port)
_embed_html_iframe(url, port, same_tab_url = same_tab_url)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Attach the link token on the normal Colab path

When start(link_token=True) runs on real Colab, the token-bearing URL is passed only to this HTML fallback. The default Cloudflare flow returns earlier at line 760, while cloudflare=False normally returns after serve_kernel_port_as_iframe() succeeds, so the documented opt-in never loads or displays a URL containing the token in either normal Colab flow; it works only when the kernel helper fails or outside Colab. Provide a token-capable same-tab navigation path rather than discarding it on the standard embed paths.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a defect, this is the documented opt-in TODO. link_token defaults to OFF and the docstring in _show_and_embed states plainly that the built UI does not yet read ?link_token, POST it to /api/auth/link-exchange, store the JWT and scrub the query with history.replaceState, so the token is emitted but unused everywhere today, not just on the kernel-helper and Cloudflare paths. The backend half (mint, single-use exchange, expiry, rate limit, secret binding) landed first deliberately; wiring the frontend handoff is the follow-up that will consume it. Adding a token-capable same-tab navigation path now would put a bearer credential on a URL for a UI that ignores it, which is exposure without benefit. serve_kernel_port_as_iframe takes only a port and cannot carry a query string, and the shared Cloudflare link must never carry the token by design.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 25, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6dd73e4f8f

ℹ️ 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".

Comment thread studio/backend/routes/auth.py Outdated
headers = {"Retry-After": str(blocked_for)},
)

exchanged = exchange_link_token_with_secret(payload.link_token)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Commit token consumption together with session issuance

When a valid exchange encounters a transient failure after this call—such as create_refresh_token() timing out on the auth database or the final password-state lookup raising—the JTI deletion has already been committed by consume_link_token(). The endpoint therefore returns 500 while permanently destroying the one-time credential, and retrying the same link receives 401 even though no session was delivered. Consume the link token and persist the issued refresh token in one transaction so either the complete exchange commits or the token remains retryable.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declining this one. Burning the jti on a partial failure is the intended direction for a single-use credential: after consume_link_token commits, the only safe assumption is that the token may have been used, so leaving it retryable would reopen exactly the replay window the route documents (consume-before-rotation, cf. Keycloak CVE-2026-1035). The user is not stranded either, the same-tab login page still works and the token expires in 10 minutes. The proposed remedy also conflicts with the security property already in place: issuance is deliberately performed AFTER the consume and is then rechecked against the JWT secret the token validated with, revoking the just-minted refresh token if a password change rotated it. Folding consume plus refresh-token insert into one transaction would require threading a shared connection through consume_link_token, save_refresh_token and the rotation recheck, which is a redesign of the auth storage layer for a nicety on a path that only triggers when the auth DB is already failing, and it would trade a fail-closed error for a fail-open one.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f23a1acaea

ℹ️ 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".

Comment thread studio/backend/routes/auth.py Outdated
Comment on lines +492 to +501
exchanged = exchange_link_token_with_secret(payload.link_token)
if exchanged is None:
_record_login_failure(ip_key)
raise HTTPException(
status_code = status.HTTP_401_UNAUTHORIZED,
detail = "Invalid, expired, or already-used link token",
)
username, secret_at_exchange = exchanged
access_token = create_access_token(subject = username)
refresh_token = create_refresh_token(subject = username)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Consume the link token only after session issuance succeeds

exchange_link_token_with_secret() deletes and commits the one-time nonce before this route creates either session token. If the subsequent JWT-secret lookup or save_refresh_token() encounters a transient SQLite error, the endpoint returns a 500 but the link token has already been irreversibly consumed; retrying the same URL then returns 401, leaving the user without the promised session. Make nonce consumption and refresh-token insertion atomic, or otherwise preserve a safe retry path when issuance fails.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declining again, same rationale as the earlier round on this endpoint.

Burning the jti before issuance is the intended direction for a single-use credential. The token is the whole credential here (the endpoint is unauthenticated), so the failure we optimise for is replay, not retry: on any doubt the nonce must be gone. A 500 after consumption costs the user one re-login through the normal form, which is always available; leaving the nonce live so a 500 can be retried would also leave it live for anyone who captured the URL out of a shell history, a proxy log or a saved notebook.

Making consumption and refresh-token insertion one transaction is also not compatible with the binding this route deliberately keeps: exchange_link_token_with_secret returns the JWT secret the token validated against, and issuance is only accepted if storage.get_jwt_secret still matches after the consume. That consume-then-recheck ordering is what stops a pre-change link token from minting a session that survives a concurrent password change (update_password rotates the secret and deletes link_tokens in its own transaction). Folding the consume into the issuance transaction would either hold a write lock across token minting or reorder the recheck ahead of the consume, reopening that TOCTOU. No change.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 82e7570951

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 1, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 1, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 1, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 1, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 1, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: c05bf367ab

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 94aa020ac8

ℹ️ 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".

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@Etherll

Etherll commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

@codex review

1 similar comment
@Etherll

Etherll commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: dc1097a098

ℹ️ 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".

@Etherll Etherll left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM ! tested in colab

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.

2 participants