Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Daniel Han6c07765aaf5e
diff --git a/README.md b/README.md
index 9c9a99fb1fd..a39b9626916 100644
--- a/README.md
+++ b/README.md
@@ -178,6 +178,16 @@ Headless starts:
```bash
UNSLOTH_STUDIO_PASSWORD='your-strong-password' unsloth studio --secure # via env var
```
+If you do not supply one, a public launch (`--secure`, `--cloudflare`, or Colab)
+generates a strong admin password and shows it once. On a terminal launch it goes
+to the console only, and the Studio server never writes it to disk or to the
+server log. In Colab it is rendered into the notebook cell instead, and Colab
+saves cell output with the notebook, so clear that cell before sharing or
+exporting the notebook. Copy it when it appears: it is not shown again, and
+recovering from a lost one means `unsloth studio reset-password`. A launch with
+no console at all (a detached service with redirected output) refuses to start
+rather than rotate a password nobody could read, as does a relaunch after a
+generated password was committed but never reached you.
Reset your password:
```bash
unsloth studio reset-password
diff --git a/studio/Unsloth_Studio_Colab.ipynb b/studio/Unsloth_Studio_Colab.ipynb
index 065250b9dce..765c29572b2 100644
--- a/studio/Unsloth_Studio_Colab.ipynb
+++ b/studio/Unsloth_Studio_Colab.ipynb
@@ -72,7 +72,11 @@
"id": "3e1771a9"
},
"source": [
- "### Start Unsloth Studio"
+ "### Start Unsloth Studio\n",
+ "\n",
+ "On Colab, `start()` auto-opens a shareable Cloudflare link because the in-cell proxy iframe often stays blank. Open Unsloth with that link above the ready card. To skip the tunnel and try the in-notebook proxy iframe only, use `start(cloudflare=False)`.\n",
+ "\n",
+ "A shareable link needs a login so it is not open to everyone. If you do not set a password, Unsloth auto-generates a strong one and shows it once in the cell output below as `username: unsloth` and `password: ...`. Copy that password into the Unsloth login page. The server keeps it out of its own logs and out of the shared link, but a notebook SAVES its cell output: Colab autosaves to Drive, and an exported or shared copy carries that output with it. So treat the password as part of this notebook until you clear the output of the cell below (or change the password with `unsloth studio reset-password`). To choose your own instead, set the `UNSLOTH_STUDIO_PASSWORD` environment variable before calling `start()`."
],
"id": "3e1771a9"
},
@@ -88,10 +92,17 @@
"\n",
"# On Colab, start() auto-opens a Cloudflare link and prints admin login credentials.\n",
"# Use the Cloudflare link above the ready card to open Unsloth (in-cell iframes often stay blank).\n",
+ "# If no password is set, a strong one is auto-generated and shown once below\n",
+ "# (username: unsloth); it never goes into the shared link or the server logs.\n",
+ "# This notebook saves cell output, so copy the password, then clear the output\n",
+ "# of this cell before saving or sharing the notebook.\n",
"start()\n",
"\n",
"# To skip the Cloudflare tunnel and try the in-notebook proxy iframe only:\n",
- "# start(cloudflare=False)"
+ "# start(cloudflare=False)\n",
+ "# To choose your own admin password instead of the auto-generated one, run this\n",
+ "# before start():\n",
+ "# import os; os.environ[\"UNSLOTH_STUDIO_PASSWORD\"] = \"your-password\""
],
"execution_count": null,
"outputs": [],
diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.py
index 2756e334154..d9d22ff04c3 100644
--- a/studio/backend/auth/storage.py
+++ b/studio/backend/auth/storage.py
@@ -29,6 +29,9 @@ MIN_PASSWORD_LENGTH = 8
# change so the credential never lingers on disk.
_BOOTSTRAP_PW_PATH = DB_PATH.parent / ".bootstrap_password"
+# Hash of an auto-generated password awaiting delivery, committed with auth_user.
+_CREDENTIAL_UNDELIVERED_KEY = "credential_undelivered_password_hash"
+
# In-process cache to avoid re-reading the file on every HTML serve.
_bootstrap_password: Optional[str] = None
@@ -212,6 +215,82 @@ def clear_bootstrap_password() -> None:
print(message, file = sys.stderr, flush = True)
+def mark_credential_undelivered(username: str) -> None:
+ """Mark the current credential pending delivery.
+
+ New auto-generation code must prefer ``update_password(...,
+ mark_credential_undelivered=True)`` so the password and marker commit
+ atomically. This helper remains for callers that need to mark an already-live
+ credential, but it uses the same database state rather than a fallible sidecar
+ file.
+ """
+ conn = get_connection()
+ try:
+ row = conn.execute(
+ "SELECT password_hash FROM auth_user WHERE username = ?",
+ (username,),
+ ).fetchone()
+ if row is None:
+ conn.rollback()
+ return
+ conn.execute(
+ "INSERT OR REPLACE INTO app_secrets (key, value) VALUES (?, ?)",
+ (_CREDENTIAL_UNDELIVERED_KEY, row["password_hash"]),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+
+def clear_credential_undelivered(conn: Optional[sqlite3.Connection] = None) -> None:
+ """Clear transactional delivery state after the credential is displayed."""
+ if conn is not None:
+ conn.execute("DELETE FROM app_secrets WHERE key = ?", (_CREDENTIAL_UNDELIVERED_KEY,))
+ return
+ conn = get_connection()
+ try:
+ clear_credential_undelivered(conn)
+ conn.commit()
+ finally:
+ conn.close()
+
+
+def credential_undelivered(username: str) -> bool:
+ """True when the live admin password is one that was committed but never shown.
+
+ Requires both the pending row and a hash match, so it answers "is the CURRENT
+ password the undelivered one?" rather than "did a delivery ever fail?". The
+ marker is written in the same transaction as an auto-generated password;
+ database errors propagate so a launch cannot fail open on unreadable state.
+ """
+ conn = get_connection()
+ try:
+ pending = conn.execute(
+ """
+ SELECT s.value AS pending_hash,
+ (SELECT password_hash FROM auth_user WHERE username = ?) AS current_hash
+ FROM app_secrets AS s
+ WHERE s.key = ?
+ """,
+ (username, _CREDENTIAL_UNDELIVERED_KEY),
+ ).fetchone()
+ if pending is None:
+ return False
+ pending_hash = pending["pending_hash"]
+ current_hash = pending["current_hash"]
+ if pending_hash and current_hash and hmac.compare_digest(pending_hash, current_hash):
+ return True
+ # Heal older databases without deleting a concurrent launcher's marker.
+ conn.execute(
+ "DELETE FROM app_secrets WHERE key = ? AND value = ?",
+ (_CREDENTIAL_UNDELIVERED_KEY, pending_hash),
+ )
+ conn.commit()
+ return False
+ finally:
+ conn.close()
+
+
def _hash_token(token: str) -> str:
"""SHA-256 hash helper for refresh token storage.
@@ -769,6 +848,8 @@ def update_password(
*,
revoke_refresh_tokens: bool = False,
expect_password_hash: Optional[str] = None,
+ require_must_change: bool = False,
+ mark_credential_undelivered: bool = False,
preserve_desktop_secret: bool = False,
) -> Optional[str]:
"""Update password, clear first-login requirement, rotate JWT secret.
@@ -784,46 +865,91 @@ def update_password(
``expect_password_hash`` makes the write conditional on the credential the
caller verified still being current, so a request that checked the old
password cannot overwrite a reset that landed while it was in flight.
- Returns False when the credential moved underneath it.
+ Returns None when the credential moved underneath it.
+
+ ``require_must_change`` makes it conditional on the account still holding a
+ seeded credential. Auto-generated launch credentials use it so a user who
+ completes /change-password in another tab between a
+ ``requires_password_change()`` read and this call is not silently overwritten
+ (and no already-replaced generated password is displayed).
+
+ Both guards ride the SAME statement 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 guard that rejects the
+ write commits NOTHING -- no revocation, no rotation -- because the credential
+ a rejected caller would be revoking belongs to the writer that won.
+
+ (``expect_password_hash`` strictly subsumes ``require_must_change``: every
+ write rehashes with a fresh salt, so any concurrent change trips it too. The
+ two are kept separate because they state different policies -- "the credential
+ I verified is still current" versus "only ever replace a never-set credential"
+ -- and the auto-generate callers hold no credential to pass. Collapsing them
+ is a follow-up, not a rebase.)
+
+ ``mark_credential_undelivered`` stores the newly committed password hash in
+ ``app_secrets`` before this transaction commits. A launcher can therefore
+ safely rotate first and display second: every other process observes either
+ the old password with no pending marker, or the new password with its matching
+ marker. Ordinary password changes delete any older pending marker in this same
+ transaction.
``preserve_desktop_secret`` keeps the local desktop credential valid. It is
for a caller that already authenticated as the desktop app: revoking the
secret it is currently using would break desktop auto-auth for a change the
desktop itself made.
+
+ The desktop secret (unless preserved) is revoked in this same transaction. It
+ authenticates as this user without the password and is keyed off the JWT
+ secret rotated below, so it has to die with the rotation. A post-commit
+ ``clear_desktop_secret()`` opens a SECOND connection and can raise
+ ``sqlite3.OperationalError`` on a busy database, leaving a pre-change desktop
+ credential live against the new password, and would propagate that error to a
+ caller whose new password is already committed. The only remaining post-commit
+ step is the best-effort bootstrap FILE removal, which cannot join a SQL
+ transaction and never fails the change.
"""
from .hashing import hash_password
salt, pwd_hash = hash_password(new_password)
jwt_secret = secrets.token_urlsafe(64)
+
+ # Values remain bound parameters. Parameter order is SET, username, then guard.
+ guards = ""
+ params = [salt, pwd_hash, jwt_secret, username]
+ if require_must_change:
+ guards += " AND must_change_password = 1"
+ if expect_password_hash is not None:
+ guards += " AND password_hash = ?"
+ params.append(expect_password_hash)
+
conn = get_connection()
try:
- if expect_password_hash is None:
- cursor = conn.execute(
- """
- UPDATE auth_user
- SET password_salt = ?, password_hash = ?, jwt_secret = ?, must_change_password = 0
- WHERE username = ?
- """,
- (salt, pwd_hash, jwt_secret, username),
+ cursor = conn.execute(
+ f"""
+ UPDATE auth_user
+ SET password_salt = ?, password_hash = ?, jwt_secret = ?, must_change_password = 0
+ WHERE username = ?{guards}
+ """,
+ tuple(params),
+ )
+ if cursor.rowcount == 0:
+ # The user or guard failed; roll back before revoking anything.
+ conn.rollback()
+ return None
+ if not preserve_desktop_secret:
+ clear_desktop_secret(conn)
+ if revoke_refresh_tokens:
+ conn.execute("DELETE FROM refresh_tokens WHERE username = ?", (username,))
+ if mark_credential_undelivered:
+ conn.execute(
+ "INSERT OR REPLACE INTO app_secrets (key, value) VALUES (?, ?)",
+ (_CREDENTIAL_UNDELIVERED_KEY, pwd_hash),
)
else:
- cursor = conn.execute(
- """
- UPDATE auth_user
- SET password_salt = ?, password_hash = ?, jwt_secret = ?, must_change_password = 0
- WHERE username = ? AND password_hash = ?
- """,
- (salt, pwd_hash, jwt_secret, username, expect_password_hash),
- )
- if revoke_refresh_tokens and cursor.rowcount > 0:
- conn.execute("DELETE FROM refresh_tokens WHERE username = ?", (username,))
+ clear_credential_undelivered(conn)
conn.commit()
- if cursor.rowcount > 0:
- clear_bootstrap_password()
- if not preserve_desktop_secret:
- clear_desktop_secret()
- return jwt_secret
- return None
+ clear_bootstrap_password()
+ return jwt_secret
finally:
conn.close()
@@ -1018,8 +1144,21 @@ def validate_desktop_secret(raw_secret: str) -> Optional[str]:
return verified[0] if verified else None
-def clear_desktop_secret() -> None:
- """Remove backend-side desktop auth state."""
+def clear_desktop_secret(conn: Optional[sqlite3.Connection] = None) -> None:
+ """Remove backend-side desktop auth state.
+
+ Given an open *conn*, the delete joins the CALLER's transaction and the caller
+ commits it (``update_password`` revokes the desktop secret in the same atomic
+ write as the password rotation, so a failure cannot leave a pre-change desktop
+ credential able to authenticate without the password). Otherwise it runs
+ standalone on its own connection.
+ """
+ if conn is not None:
+ conn.execute(
+ "DELETE FROM app_secrets WHERE key IN (?, ?)",
+ (_DESKTOP_SECRET_HASH_KEY, _DESKTOP_SECRET_CREATED_AT_KEY),
+ )
+ return
conn = get_connection()
try:
conn.execute(
diff --git a/studio/backend/colab.py b/studio/backend/colab.py
index 81458d253b4..ca2f65ed424 100644
--- a/studio/backend/colab.py
+++ b/studio/backend/colab.py
@@ -3,6 +3,7 @@
"""Colab helpers for Unsloth Studio. Uses Colab's built-in proxy."""
+import os
from pathlib import Path
import sys
@@ -17,6 +18,7 @@ import _platform_compat # noqa: F401
from loggers import get_logger
logger = get_logger(__name__)
+_DELIVERY_MARKER_CLEAR_ATTEMPTS = 3
def get_colab_url(port: int = 8888) -> str:
@@ -104,27 +106,66 @@ def _load_colab_login_credentials() -> "tuple[str, str] | None":
"""Return stored Colab admin credentials from a previous ``start()`` run, if any."""
path = _colab_login_credentials_path()
try:
- if not path.is_file():
- return None
+ cache_stat = path.stat()
+ except FileNotFoundError:
+ return None
+ except OSError as e:
+ logger.info(f"Could not inspect Colab login credentials ({e}).")
+ raise _ColabCredentialHandoffFailed("cached admin credentials could not be loaded") from e
+ if cache_stat.st_size == 0:
+ return None
+ try:
lines = path.read_text(encoding = "utf-8").splitlines()
if len(lines) >= 2 and lines[0] and lines[1]:
return lines[0], lines[1]
except (OSError, UnicodeDecodeError) as e:
logger.info(f"Could not load Colab login credentials ({e}).")
- return None
+ raise _ColabCredentialHandoffFailed("cached admin credentials could not be loaded") from e
+ raise _ColabCredentialHandoffFailed("cached admin credentials are malformed")
-def _clear_colab_login_credentials() -> None:
- """Drop the cached Colab credentials once they no longer authenticate."""
+def _clear_colab_login_credentials() -> bool:
+ """Remove all plaintext from the legacy Colab credential cache.
+
+ Prefer deleting the cache outright, then fall back to truncating it for
+ filesystems where unlink is temporarily unavailable. Return True only after
+ verifying that the path is absent or contains no bytes.
+ """
path = _colab_login_credentials_path()
try:
path.unlink(missing_ok = True)
except OSError as e:
- logger.info(f"Could not clear Colab login credentials ({e}).")
+ logger.info(f"Could not delete Colab login credentials ({e}); clearing the file.")
+ try:
+ path.stat()
+ except FileNotFoundError:
+ return True
+ except OSError as e:
+ # Path.exists() suppresses all OSError subclasses on Python 3.14, so a
+ # False result cannot distinguish an absent file from an inaccessible
+ # live credential. Try to clear it, then verify with stat() below.
+ logger.info(
+ f"Could not verify Colab login credentials were deleted ({e}); clearing the file."
+ )
+ try:
+ path.write_text("", encoding = "utf-8")
+ except OSError as e:
+ logger.warning(f"Could not delete or clear Colab login credentials ({e}).")
+ return False
+ try:
+ if path.stat().st_size == 0:
+ return True
+ logger.warning("Could not clear Colab login credentials: plaintext remains on disk.")
+ return False
+ except FileNotFoundError:
+ return True
+ except OSError as e:
+ logger.warning(f"Could not verify Colab login credentials were cleared ({e}).")
+ return False
-def _colab_credentials_still_valid(username: str, password: str) -> bool:
- """True when *password* still matches the stored admin hash.
+def _colab_credentials_still_valid(username: str, password: str) -> "bool | None":
+ """Return True/False for a proven match/mismatch, or None on validation error.
Guards against redisplaying a cached first-run password after the user has
changed the admin password through the app, which would print credentials
@@ -135,7 +176,7 @@ def _colab_credentials_still_valid(username: str, password: str) -> bool:
from auth.hashing import verify_password
except Exception as e:
logger.info(f"Could not load auth to validate cached Colab credentials ({e}).")
- return False
+ return None
try:
row = get_user_and_secret(username)
if not row:
@@ -144,7 +185,31 @@ def _colab_credentials_still_valid(username: str, password: str) -> bool:
return bool(verify_password(password, salt, pwd_hash))
except Exception as e:
logger.info(f"Could not validate cached Colab credentials ({e}).")
- return False
+ return None
+
+
+class _ColabCredentialHandoffFailed(RuntimeError):
+ """A live credential could not be safely handed to the notebook operator."""
+
+
+def _handoff_or_purge_legacy_colab_credentials() -> None:
+ """Remove the pre-#7392 plaintext cache without losing a live credential."""
+ cached = _load_colab_login_credentials()
+ if cached is None:
+ return
+ valid = _colab_credentials_still_valid(*cached)
+ if valid is None:
+ raise _ColabCredentialHandoffFailed("cached admin credentials could not be validated")
+ if valid is True and (
+ not _display_channel_active()
+ or not _display_admin_credentials(*cached, final_cached_copy = True)
+ ):
+ raise _ColabCredentialHandoffFailed("cached admin credentials could not be shown")
+ if not _clear_colab_login_credentials():
+ description = "live " if valid else "stale "
+ raise _ColabCredentialHandoffFailed(
+ f"the {description}plaintext credential cache could not be removed"
+ )
def _colab_wants_cloudflare(cloudflare: "bool | None") -> bool:
@@ -188,8 +253,14 @@ def _finalize_colab_admin_password() -> "tuple[str, str] | None":
username = DEFAULT_ADMIN_USERNAME
if not requires_password_change(username):
creds = _load_colab_login_credentials()
- if creds is not None and _colab_credentials_still_valid(username, creds[1]):
- return creds
+ if creds is not None:
+ valid = _colab_credentials_still_valid(username, creds[1])
+ if valid is True:
+ return creds
+ if valid is None:
+ # A transient validation error is not evidence that this
+ # recovery credential is stale. Retain it for the next run.
+ return None
# The admin password was changed through the app after the first run,
# so the cached copy is stale; drop it instead of printing dead credentials.
_clear_colab_login_credentials()
@@ -366,13 +437,372 @@ def _bootstrap_password_pending() -> bool:
return True
+def _display_channel_active() -> bool:
+ """True only where IPython.display actually renders a card to the operator.
+
+ display() does NOT raise outside a notebook, so a non-raising call is no proof
+ the credential was seen: with no InteractiveShell it just prints repr(obj)
+ ("<IPython.core.display.HTML object>") and a terminal shell renders only the
+ text/plain repr. Treating that as success would publish the shared link after
+ rotating to a password nobody ever read. Only an ipykernel-backed shell
+ (Jupyter, and Colab whose google.colab._shell.Shell subclasses it) publishes
+ display_data out of band on iopub, so require one: the `kernel` attribute is
+ set on the shell by ipykernel and, unlike comparing __class__.__name__ to
+ "ZMQInteractiveShell", it is also true under Colab's subclass.
+ """
+ try:
+ from IPython import get_ipython
+ except Exception:
+ return False
+ try:
+ shell = get_ipython()
+ except Exception:
+ return False
+ if shell is None:
+ return False
+ if getattr(shell, "kernel", None) is not None:
+ return True
+ try:
+ from ipykernel.zmqshell import ZMQInteractiveShell
+ except Exception:
+ return False
+ return isinstance(shell, ZMQInteractiveShell)
+
+
+def _auto_generate_colab_admin_password() -> "str | None":
+ """Secure a Colab public (Cloudflare) launch that has no admin password set.
+
+ While the admin still owes its bootstrap-password change, a shared link would
+ leak admin access, so today the tunnel is refused. Instead auto-generate a
+ strong password and commit it via the normal update path (which clears the
+ must-change flag, rotates the JWT secret, revokes refresh tokens, and deletes
+ the on-disk bootstrap password), then return it for one-time display in the
+ cell. Returns None when a password is already set (nothing to do) or on error.
+ The value is never persisted to disk or placed on argv.
+
+ The commit is a compare-and-set on ``must_change_password``: another tab can
+ finish /change-password against the reused server between the check below and
+ the write, and an unconditional update would either discard the password the
+ user just chose or display a generated one that has already been replaced,
+ publishing the tunnel under credentials nobody can use. Losing that race means
+ a password is now set, so we return None exactly as if one always had been.
+
+ Entering this path also purges the pre-#7392 ``.colab_notebook_login`` cache:
+ the removed finalize flow wrote the admin username and password there in
+ plaintext, and an upgraded runtime must not keep a readable copy of a
+ credential this flow promises is never persisted (CWE-256).
+
+ The display channel is resolved BEFORE rotating (mirroring run.py's
+ _one_time_secret_stream preflight): a runtime that cannot render the card is
+ refused here, while the seeded recovery credential is still intact.
+ """
+ try:
+ from auth.storage import (
+ DEFAULT_ADMIN_USERNAME,
+ ensure_default_admin,
+ requires_password_change,
+ update_password,
+ )
+ except Exception as e:
+ logger.warning(f"Could not load auth storage to secure the public link ({e}).")
+ return None
+ try:
+ ensure_default_admin()
+ if not requires_password_change(DEFAULT_ADMIN_USERNAME):
+ # Show a valid pre-#7392 cached credential once before removing it. This
+ # preserves recovery access while closing the CWE-256 plaintext cache.
+ _handoff_or_purge_legacy_colab_credentials()
+ return None
+ _clear_colab_login_credentials()
+ if not _display_channel_active():
+ # Refuse before rotating when the recovery credential cannot be shown.
+ logger.warning(
+ "No notebook display channel to show a one-time admin password, so the "
+ "admin password is left unchanged. Set one with `unsloth studio "
+ "reset-password` (or log in locally and change it), then re-run start()."
+ )
+ return None
+ import secrets
+
+ generated = secrets.token_urlsafe(24)
+ try:
+ # Keep only whether the guarded update succeeded, never the JWT secret.
+ committed = (
+ update_password(
+ DEFAULT_ADMIN_USERNAME,
+ generated,
+ revoke_refresh_tokens = True,
+ require_must_change = True,
+ mark_credential_undelivered = True,
+ )
+ is not None
+ )
+ except Exception as e:
+ # Cleanup may raise after commit, so verify which password is live before
+ # deciding whether the link can be published.
+ logger.warning(f"Admin password commit reported an error ({e}); checking what landed.")
+ committed = _colab_credentials_still_valid(DEFAULT_ADMIN_USERNAME, generated)
+ if committed is None:
+ raise _ColabCredentialHandoffFailed(
+ "the generated admin credential could not be verified after commit"
+ ) from e
+ if not committed:
+ # A concurrent password won; do not show a credential that cannot authenticate.
+ logger.info("An admin password was set concurrently; keeping it for the public link.")
+ return None
+ return generated
+ except _ColabCredentialHandoffFailed:
+ raise
+ except Exception as e:
+ logger.warning(f"Could not auto-generate an admin password for the public link ({e}).")
+ return None
+
+
+def _display_admin_credentials(
+ username: str,
+ password: str,
+ *,
+ final_cached_copy: bool = False,
+) -> bool:
+ """Show an admin credential once, in the notebook cell.
+
+ ``final_cached_copy`` re-displays a credential recovered from the pre-#7392
+ ``.colab_notebook_login`` cache on an upgraded runtime, immediately before
+ that cache is deleted. It is not newly generated, so the card says so and
+ tells the user this is the last time it will appear.
+
+ Renders a branded HTML card with a plain-text fallback. Both paths publish
+ through the IPython display channel (iopub display_data), NOT sys.stdout, so
+ the credential never reaches the server's tee'd session log on disk (see
+ run._setup_server_disk_logging) and is never logged; if no display channel is
+ available we intentionally show nothing rather than fall back to
+ stdout/logging, which would retain the password in the log file.
+
+ The cell is the only surface a notebook has, and a notebook SAVES its cell
+ output: Colab autosaves to Drive, and an exported or shared .ipynb carries the
+ output with it, so this password lives in the notebook document until the
+ output is cleared or the password is changed. The card says exactly that
+ instead of promising the value is never written to disk -- readers who get the
+ notebook must be assumed to have the credential.
+
+ Returns True only when the credential was published to the display channel, and
+ False when no channel is available or every publish raised, so the caller can
+ fail closed rather than expose a shared link under a password nobody ever saw.
+ """
+ try:
+ from IPython.display import HTML, display
+ except Exception:
+ return False
+ _lede = (
+ "This is your existing admin password, recovered from the credential file an "
+ "older Unsloth cached on this runtime. That file has now been removed, so this "
+ "is the last time it will be shown."
+ if final_cached_copy
+ else "Auto-generated for this public launch."
+ )
+ try:
+ display(
+ HTML(f"""
+ <div style="display: inline-block; padding: 18px 20px; background: #fff8e1; border: 2px solid #000000;
+ border-radius: 12px; margin: 10px 0; font-family: system-ui, -apple-system, sans-serif;">
+ <h3 style="color:#000;margin:0 0 8px 0;font-size:18px;font-weight:800;">Unsloth Studio admin login</h3>
+ <p style="margin:2px 0;font-size:14px;color:#000;">Username: <b style="font-family:monospace;">{username}</b></p>
+ <p style="margin:2px 0;font-size:14px;color:#000;">Password: <b style="font-family:monospace;">{password}</b></p>
+ <p style="margin:10px 0 0 0;font-size:12px;color:#333;">
+ {_lede} The server never writes it to its logs, but
+ this notebook saves cell output: copy the password now, then clear this cell's output
+ before you share, export or download the notebook. Change it any time in Settings, or
+ with <b style="font-family:monospace;">unsloth studio reset-password</b>.
+ </p>
+ </div>
+ """)
+ )
+ return True
+ except Exception:
+ # Fall back through the same iopub channel, never stdout or the server log.
+ try:
+ display(
+ {
+ "text/plain": (
+ "Unsloth Studio admin login "
+ f"username: {username} password: {password} "
+ f"({_lede} this cell's output is saved "
+ "with the notebook, so clear it before sharing or exporting)"
+ )
+ },
+ raw = True,
+ )
+ return True
+ except Exception:
+ return False
+
+
+def _clear_displayed_credential_marker(username: str) -> bool:
+ """Retry marker cleanup only after the one-time card was confirmed displayed."""
+ from auth.storage import clear_credential_undelivered, credential_undelivered
+
+ for _attempt in range(_DELIVERY_MARKER_CLEAR_ATTEMPTS):
+ try:
+ clear_credential_undelivered()
+ if not credential_undelivered(username):
+ return True
+ except Exception:
+ continue
+ return False
+
+
+# Literal on purpose: the strip below must run even if importing auth fails, so it
+# cannot depend on auth.terminal_prompt.SUPPLIED_PASSWORD_ENV being importable. A
+# test asserts the two stay equal.
+_SUPPLIED_PASSWORD_ENV = "UNSLOTH_STUDIO_PASSWORD"
+
+
+def _consume_supplied_password_on_reuse(supplied: "str | None" = None) -> None:
+ """Apply-or-strip ``UNSLOTH_STUDIO_PASSWORD`` on start()'s server-reuse path.
+
+ A normal launch goes through ``run_server`` -> ``run._apply_supplied_password``,
+ which reads the variable and then unconditionally pops it, so no child process
+ inherits the plaintext. The fast path (a re-run cell reusing an already-healthy
+ server) never calls ``run_server``, so without this the variable is still set
+ when ``start_cloudflare_tunnel`` spawns cloudflared, and every process spawned
+ from the kernel afterwards inherits the admin password through its environment
+ (CWE-214/CWE-526: readable via ``/proc/<pid>/environ`` and crash dumps for
+ anything running as this user, including Studio's own code-execution tools).
+
+ So the variable is popped FIRST and unconditionally, even when the auth imports
+ or the update fail. If a value was supplied and the admin still owes its
+ bootstrap change, it is then applied through the same compare-and-set update the
+ normal path uses, so the password the user asked for is the one that protects
+ the shared link instead of being silently replaced by an auto-generated one.
+ An already-set password is never overwritten (that is `reset-password`'s job),
+ and a value that fails validation (including one equal to the bootstrap
+ password) is ignored, leaving ``start_cloudflare_tunnel`` to auto-generate and
+ display one. Never logs the value, and never exits the process: this runs inside
+ a notebook cell.
+ """
+ if supplied is None:
+ supplied = os.environ.pop(_SUPPLIED_PASSWORD_ENV, None) or None
+ else:
+ os.environ.pop(_SUPPLIED_PASSWORD_ENV, None)
+ if not supplied:
+ return
+ try:
+ from auth.storage import (
+ DEFAULT_ADMIN_USERNAME,
+ MIN_PASSWORD_LENGTH,
+ ensure_default_admin,
+ get_user_and_secret,
+ requires_password_change,
+ update_password,
+ )
+ from auth.hashing import verify_password
+
+ ensure_default_admin()
+ if not requires_password_change(DEFAULT_ADMIN_USERNAME):
+ logger.info(
+ f"An admin password is already set, so {_SUPPLIED_PASSWORD_ENV} was "
+ "ignored (it only sets the initial password). Change it with "
+ "`unsloth studio reset-password`."
+ )
+ return
+ if len(supplied) < MIN_PASSWORD_LENGTH or any(ch.isspace() for ch in supplied):
+ logger.warning(
+ f"Ignoring {_SUPPLIED_PASSWORD_ENV}: a password must be at least "
+ f"{MIN_PASSWORD_LENGTH} characters and contain no spaces. A strong "
+ "one will be generated and shown in this cell instead."
+ )
+ return
+ record = get_user_and_secret(DEFAULT_ADMIN_USERNAME)
+ if record is None:
+ logger.warning(
+ f"Ignoring {_SUPPLIED_PASSWORD_ENV}: the current admin credential "
+ "could not be verified. A strong password will be generated and shown "
+ "in this cell instead."
+ )
+ return
+ if verify_password(supplied, record[0], record[1]):
+ logger.warning(
+ f"Ignoring {_SUPPLIED_PASSWORD_ENV}: the new password must differ from "
+ "the current bootstrap password. A strong password will be generated "
+ "and shown in this cell instead."
+ )
+ return
+ if update_password(
+ DEFAULT_ADMIN_USERNAME,
+ supplied,
+ revoke_refresh_tokens = True,
+ require_must_change = True,
+ ):
+ logger.info(f"Applied the admin password supplied in {_SUPPLIED_PASSWORD_ENV}.")
+ else:
+ # A concurrent password won the compare-and-set; keep it.
+ logger.info("An admin password was set concurrently; keeping it.")
+ except Exception as e:
+ # Never log the value; the tunnel will auto-generate or refuse.
+ logger.warning(f"Could not apply the supplied admin password ({e}).")
+
+
def start_cloudflare_tunnel(port: int) -> "str | None":
"""Open a shareable Cloudflare quick tunnel to localhost:*port*, or None.
- run_server suppresses the tunnel on Colab, so we start it directly. Refused while the
- bootstrap password is pending; any failure collapses to None (Colab proxy still works).
+ run_server suppresses the tunnel on Colab by design, so we start it directly.
+ When no admin password is set, one is auto-generated and shown in the cell so
+ the shareable link is never published under the default bootstrap credential;
+ any failure collapses to None and the Colab proxy still works. As a backstop it
+ is still refused while the bootstrap password is pending.
"""
+ from auth.storage import (
+ DEFAULT_ADMIN_USERNAME,
+ credential_undelivered,
+ )
+
+ if credential_undelivered(DEFAULT_ADMIN_USERNAME):
+ # A prior rotation was never shown; keep the link closed until reset.
+ logger.warning(
+ "Cloudflare link not started: the admin password generated by an earlier "
+ "run was committed but never shown, so the shared link would be unusable. "
+ "Reset it with `unsloth studio reset-password`, then re-run "
+ "start(cloudflare=True)."
+ )
+ return None
+ try:
+ generated = _auto_generate_colab_admin_password()
+ except _ColabCredentialHandoffFailed as e:
+ logger.warning(f"Cloudflare link not started: {e}.")
+ return None
+ if generated is None and credential_undelivered(DEFAULT_ADMIN_USERNAME):
+ # A concurrent auto-launch has not proved delivery. User-selected
+ # passwords clear this marker transactionally.
+ logger.warning(
+ "Cloudflare link not started: another launch auto-generated the admin "
+ "password but has not confirmed that it was shown. Retry after that launch "
+ "completes, or reset it with `unsloth studio reset-password`."
+ )
+ return None
+ displayed = generated is not None and _display_admin_credentials(
+ DEFAULT_ADMIN_USERNAME, generated
+ )
+ if generated is not None and not displayed:
+ # The committed password could not be shown. Keep the tunnel closed and
+ # never fall back to logged stdout; require a credential reset.
+ logger.warning(
+ "Cloudflare link not started: the auto-generated admin password could not "
+ "be shown in this notebook, so the shared link would be unusable. Reset it "
+ "with `unsloth studio reset-password`, then re-run start(cloudflare=True)."
+ )
+ return None
+ if generated is not None:
+ # Clear the marker only after display. If retries fail, retain it and keep
+ # the tunnel closed.
+ if not _clear_displayed_credential_marker(DEFAULT_ADMIN_USERNAME):
+ logger.warning(
+ "Cloudflare link not started: the admin password was shown, but its "
+ "delivery state could not be saved after retrying. The link remains "
+ "closed; retry after the database is writable, or reset the password."
+ )
+ return None
if _bootstrap_password_pending():
+ # Auto-generation failed; fail closed without a shared link.
logger.warning(
"Cloudflare link not started: the admin account still has its temporary "
"bootstrap password, which is exposed to anyone who can load the page. "
@@ -514,6 +944,7 @@ def _embed_html_iframe(url: str, port: int) -> bool:
return False
short_url = _short_colab_url(url, port)
+ iframe_src = url
iframe_id = f"unsloth-studio-{port}"
try:
display(
@@ -528,7 +959,7 @@ def _embed_html_iframe(url: str, port: int) -> bool:
</div>
<iframe
id="{iframe_id}"
- src="{url}"
+ src="{iframe_src}"
style="width:100%;height:82vh;min-height:600px;max-height:1100px;border:none;display:block;box-sizing:border-box;"
allow="clipboard-read; clipboard-write"
></iframe>
@@ -599,7 +1030,9 @@ def _show_and_embed(
if _is_colab_runtime() and cloudflare_url:
return
- # Real Colab: kernel helper needs only the port (works when eval_js failed).
+ # Real Colab: kernel helper needs only the port (works when eval_js failed). It
+ # cannot carry a query token, so the opt-in same-tab link token applies only to the
+ # HTML iframe fallback below.
if _is_colab_runtime():
if _embed_kernel_port_iframe(port):
return
@@ -613,7 +1046,12 @@ def start(port: int = 8888, *, cloudflare: "bool | None" = None):
port: Port to bind/serve on.
cloudflare: Shareable Cloudflare HTTPS link. ``None`` (default) auto-enables on
real Colab because the in-cell proxy embed is often blank; pass ``False`` to
- skip the tunnel or ``True`` to force it on other runtimes.
+ skip the tunnel or ``True`` to force it on other runtimes. The shared link is
+ protected: when the admin still owes its bootstrap password one is
+ auto-generated and shown in the cell, and the tunnel fails closed if that
+ credential cannot be surfaced, so the link is never published under the
+ default credential. The cell output is saved with the notebook, so clear
+ it before sharing or exporting (the card says so too).
Usage:
start() # Cloudflare link on Colab (auto); proxy iframe elsewhere
@@ -622,20 +1060,32 @@ def start(port: int = 8888, *, cloudflare: "bool | None" = None):
"""
import time
+ # Remove plaintext before spawning anything; apply the captured value explicitly.
+ supplied_password = os.environ.pop(_SUPPLIED_PASSWORD_ENV, None) or None
logger.info("🦥 Starting Unsloth Studio...")
use_cloudflare = _colab_wants_cloudflare(cloudflare)
+ # Migrate the pre-#7392 cache even without Cloudflare, showing a live value once.
+ try:
+ _handoff_or_purge_legacy_colab_credentials()
+ except _ColabCredentialHandoffFailed as e:
+ logger.warning(
+ f"Could not safely remove legacy Colab credentials ({e}); refusing to start."
+ )
+ return
# Fast path: already running (cell re-run); re-show link/iframe instead of rebinding the port.
if _is_studio_healthy(port):
logger.info(f" Unsloth is already running on port {port} — reusing existing server.")
+ # run_server is skipped, so apply or strip UNSLOTH_STUDIO_PASSWORD before
+ # cloudflared can inherit it.
+ _consume_supplied_password_on_reuse(supplied_password)
# try/finally: tear the tunnel down even if interrupted mid-start/render.
try:
- colab_login = _finalize_colab_admin_password() if use_cloudflare else None
+ # The tunnel owns one-time credential generation and delivery.
cf_url = start_cloudflare_tunnel(port) if use_cloudflare else None
_show_and_embed(
port,
cloudflare_url = cf_url,
- colab_login = colab_login,
cloudflare_requested = use_cloudflare,
)
for _ in range(10000):
@@ -666,6 +1116,7 @@ def start(port: int = 8888, *, cloudflare: "bool | None" = None):
frontend_path = frontend_path,
silent = True,
cloudflare = False,
+ password = supplied_password,
)
except SystemExit as exc:
logger.error(f"❌ Unsloth Studio failed to start: {exc}")
@@ -698,14 +1149,13 @@ def start(port: int = 8888, *, cloudflare: "bool | None" = None):
)
return
- # Server healthy: finalize Colab auth, open the tunnel, publish URL, tear down on interrupt.
+ # Server healthy: secure Colab auth, open the tunnel, publish URL, tear down on interrupt.
try:
- colab_login = _finalize_colab_admin_password() if use_cloudflare else None
+ # The tunnel owns one-time credential generation and delivery.
cf_url = start_cloudflare_tunnel(actual_port) if use_cloudflare else None
_show_and_embed(
actual_port,
cloudflare_url = cf_url,
- colab_login = colab_login,
cloudflare_requested = use_cloudflare,
)
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 62c617a7b2d..8265fa8213a 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -2064,10 +2064,240 @@ def _stream_isatty(stream) -> bool:
"""
try:
return stream.isatty()
- except (AttributeError, ValueError):
+ except (AttributeError, OSError, ValueError):
return False
+def _console_only_stream(stream):
+ """Return the real console stream behind a _TeeStream session-log wrapper.
+
+ run_server() calls _setup_server_disk_logging() early, which replaces
+ sys.stdout/stderr with _TeeStream so diagnostics are mirrored into a retained
+ logs/server/server-*.log. A one-time secret (the auto-generated admin
+ password) must reach the operator's console but MUST NOT land in that
+ persisted file (OWASP CWE-532: never write credentials to logs). Writing to
+ the underlying stream shows the banner on the console while bypassing the tee.
+
+ Unwraps RECURSIVELY: run_server() can run twice in one process (e.g. a local
+ run followed by a public one), and each call re-wraps the already-wrapped
+ sys.stdout/stderr, so the tees nest. Peeling one layer would return an inner
+ _TeeStream -- which forwards isatty() to the real console and so passes the
+ TTY check -- and the credential would be mirrored into the older run's
+ retained server-*.log. The depth bound keeps a pathological self-referential
+ wrapper from looping forever; a stream still wrapped after it is reported as
+ unusable (None) so the caller fails closed rather than tee a credential.
+ """
+ for _ in range(64):
+ if not isinstance(stream, _TeeStream):
+ return stream
+ stream = stream._stream
+ return None
+
+
+def _one_time_secret_stream(*, skip = None):
+ """Return an interactive-terminal stream to surface a one-time secret, or None.
+
+ Prefers sys.stderr, then sys.stdout, unwrapping the _TeeStream session-log
+ wrapper (see _console_only_stream) so the secret bypasses the retained
+ logs/server/server-*.log (CWE-532: never write credentials to log files).
+
+ Requires the underlying stream to be a real TTY. A writable non-tty stream --
+ a `> file` shell redirect, nohup.out, a systemd-journald socket, a Docker
+ logging pipe -- is NOT an ephemeral console: writing the one-time credential
+ there PERSISTS the plaintext to a file/journal/pipe that log consumers can
+ read (CWE-532), which breaks the banner's "shown once, not written to disk"
+ promise. Only a TTY is a transient surface, so a non-tty stream is skipped and
+ the caller MUST fail closed (refuse to rotate the only recovery credential).
+
+ Returns None when neither stream is a usable TTY -- e.g. a Windows
+ pythonw/service wrapper (both None), a closed/non-writable inherited stream, or
+ a fully headless (nohup/systemd) launch whose stderr/stdout is redirected. The
+ caller then fails closed: print(file=None) would fall back to the tee'd
+ sys.stdout and persist the credential, and printing to a redirected stream
+ persists it just the same -- AFTER the seeded credential was already rotated --
+ so neither may be treated as usable. Mirrors the CLI's
+ _one_time_secret_console_stream tty/closed/writable preflight so the direct
+ `python run.py` path makes the same fail-closed decision before rotating.
+
+ *skip* excludes an already-resolved console (identity match on the unwrapped
+ stream) so a delivery that RAISED on it can retry the other one; see
+ _deliver_one_time_credential. The remaining candidate still has to pass every
+ check above, so the retry can never downgrade to a tee'd or non-tty surface.
+ """
+ for candidate in (sys.stderr, sys.stdout):
+ raw = _console_only_stream(candidate)
+ if raw is None:
+ continue
+ if skip is not None and raw is skip:
+ continue
+ try:
+ if getattr(raw, "closed", False):
+ continue
+ if not callable(getattr(raw, "write", None)):
+ continue
+ except (AttributeError, ValueError):
+ continue
+ # Reject redirected streams that would persist the credential (CWE-532).
+ if not _stream_isatty(raw):
+ continue
+ return raw
+ return None
+
+
+def _tunnel_binary_confirmed_unavailable() -> bool:
+ """True only if cloudflared is provably unavailable (absent from PATH and the
+ Unsloth cache AND a download attempt failed), so a --secure tunnel cannot start.
+
+ On --secure the bind is loopback, so the tunnel is the ONLY public exposure:
+ rotating the seeded recovery password before a public URL that never comes up
+ can lock out supervisor/nohup launches that do not preserve the one-time
+ stderr banner. Mirrors the CLI's _tunnel_binary_confirmed_unavailable so the
+ direct `python run.py --secure` path makes the same decision. Returns False on
+ ANY uncertainty: a possible credential leak outweighs a recoverable lockout, so
+ the caller keeps rotating unless the tunnel is provably dead.
+ """
+ try:
+ from cloudflare_tunnel import ensure_cloudflared
+ return ensure_cloudflared() is None
+ except Exception:
+ return False
+
+
+def _generated_password_is_live(admin_username: str, candidate: str) -> bool:
+ """True when *candidate* is the password the stored admin hash now accepts.
+
+ Only used to resolve a partial success: ``update_password`` commits the row
+ before its remaining best-effort cleanup, so a raise from that cleanup still
+ leaves the new password live. Any failure to read or verify answers False, so
+ the caller fails closed instead of assuming the write landed. Comparison runs
+ through ``verify_password`` (PBKDF2 + ``hmac.compare_digest``).
+ """
+ from auth import hashing as _auth_hashing
+ from auth import storage as _auth_storage
+
+ try:
+ record = _auth_storage.get_user_and_secret(admin_username)
+ if record is None:
+ return False
+ salt, pwd_hash = record[0], record[1]
+ return bool(_auth_hashing.verify_password(candidate, salt, pwd_hash))
+ except Exception:
+ return False
+
+
+def _auto_generate_admin_password(admin_username: str, *, out = None) -> "Optional[str]":
+ """Generate a strong random admin password and commit it for a headless
+ public launch that supplied none.
+
+ Uses the existing ``update_password`` path, so it clears
+ ``must_change_password`` (no interactive prompt is then needed), rotates the
+ JWT secret, revokes refresh tokens, and deletes the on-disk bootstrap
+ password. The value is returned once for display; it is NEVER written to disk
+ or placed on argv.
+
+ The commit is a compare-and-set on ``must_change_password``: another Studio
+ process or tab sharing this auth DB can complete /change-password between the
+ gate's read and this write, and an unconditional update would overwrite the
+ password the user just chose. Returns None when that guard rejects the write,
+ so the caller shows nothing rather than a credential that never took effect.
+
+ ``update_password`` commits the row BEFORE its remaining best-effort cleanup
+ (removing the on-disk bootstrap password file), so that cleanup can still
+ raise -- e.g. printing its own warning to a stderr the launcher has closed --
+ with the new password already live and the seeded recovery credential already
+ gone. Propagating there would abort the launch behind a password nobody has
+ ever seen, an unrecoverable lockout short of `unsloth studio reset-password`.
+ So an exception is resolved against the stored hash, exactly as the Colab path
+ does: return the generated value when it is the live one, and re-raise when it
+ is not (nothing was committed, the seeded credential still works, and the
+ caller must fail closed rather than publish under an unknown state).
+ """
+ import secrets as _secrets
+
+ from auth import storage as _auth_storage
+
+ generated = _secrets.token_urlsafe(24)
+ try:
+ # Returns the rotated JWT secret, or None when the compare-and-set lost.
+ committed = (
+ _auth_storage.update_password(
+ admin_username,
+ generated,
+ revoke_refresh_tokens = True,
+ require_must_change = True,
+ mark_credential_undelivered = True,
+ )
+ is not None
+ )
+ except Exception as e:
+ if not _generated_password_is_live(admin_username, generated):
+ raise
+ if out is not None:
+ # Report cleanup failure on the console, never the session log.
+ try:
+ print(
+ "Warning: the admin password commit reported an error after it "
+ f"was applied ({e}); the password below is the live one.",
+ file = out,
+ flush = True,
+ )
+ except Exception:
+ pass
+ return generated
+ return generated if committed else None
+
+
+def _print_auto_generated_credentials(username: str, password: str, *, out) -> None:
+ """Surface an auto-generated admin credential once, in the startup banner.
+
+ Printed to the given stream (stderr for CLI launches); never logged elsewhere
+ and never persisted. Colab prints its own copy into the notebook cell.
+ """
+ line = "=" * 70
+ print(
+ f"\n{line}\n"
+ " Unsloth Studio admin login (auto-generated for this public launch)\n"
+ f" Username: {username}\n"
+ f" Password: {password}\n"
+ " Save this now: it is shown once, not written to disk, and not in the\n"
+ " process list. Rotate later with `unsloth studio reset-password`.\n"
+ f"{line}\n",
+ file = out,
+ flush = True,
+ )
+
+
+def _deliver_one_time_credential(username: str, password: str, *, out) -> bool:
+ """Write the one-time credential to *out*, retrying once on the other console.
+
+ The stream checks in _one_time_secret_stream run BEFORE the rotation, but the
+ write happens after ``update_password`` has already committed the generated
+ password and deleted the seeded bootstrap credential. A terminal that goes
+ away in between (an SSH session that drops, a closed terminal window: writes
+ to the orphaned pty raise OSError EIO) would make ``print`` raise, and letting
+ that propagate aborts the launch with the new password live and never shown,
+ locking the operator out of the account until `unsloth studio reset-password`.
+
+ So a failed write is not fatal by itself: retry once on the other console
+ (resolved through the same tty/closed/writable/no-tee preflight, so the retry
+ cannot land the credential in the retained session log or a redirected file),
+ and report whether the credential reached a console at all. Returns False only
+ when every console failed, and the caller must then fail closed -- there is no
+ third surface, and logging or printing the value would persist it (CWE-532).
+ """
+ fallback = _one_time_secret_stream(skip = out)
+ # Never retry the stream that just failed (a stubbed resolver could return it).
+ for stream in (out, fallback if fallback is not out else None):
+ if stream is None:
+ continue
+ try:
+ _print_auto_generated_credentials(username, password, out = stream)
+ return True
+ except Exception:
+ continue
+ return False
+
+
def _terminal_password_gate(
*,
tunnel_will_start: bool,
@@ -2104,10 +2334,6 @@ def _terminal_password_gate(
from auth import hashing as _auth_hashing
from auth import storage as _auth_storage
- from auth.bootstrap_timeout import (
- bootstrap_timeout_seconds,
- should_arm_bootstrap_timeout,
- )
from auth.terminal_prompt import (
prompt_for_password_change,
should_prompt_password_change,
@@ -2116,8 +2342,25 @@ def _terminal_password_gate(
_admin = _auth_storage.DEFAULT_ADMIN_USERNAME
# Gate can run before lifespan: seed the admin row here (idempotent).
_auth_storage.ensure_default_admin()
+ # A prior generated password was never shown. Fail closed until it is reset.
+ if _auth_storage.credential_undelivered(_admin):
+ logger.error(
+ "Refusing to publish Unsloth: the admin password auto-generated by an "
+ "earlier launch was committed but never displayed, so no one can log in. "
+ "Reset it with `unsloth studio reset-password`, then relaunch."
+ )
+ return False, False
requires_change = _auth_storage.requires_password_change(_admin)
if not requires_change:
+ # Recheck after the password read to catch a concurrent pending delivery.
+ if _auth_storage.credential_undelivered(_admin):
+ logger.error(
+ "Refusing to publish Unsloth: another launch auto-generated the "
+ "admin password but has not confirmed that it was displayed. Retry "
+ "after that launch completes, or reset the credential with `unsloth "
+ "studio reset-password`."
+ )
+ return False, False
return True, False
if not should_prompt_password_change(
@@ -2126,46 +2369,48 @@ def _terminal_password_gate(
stdin_isatty = _stream_isatty(sys.stdin),
stderr_isatty = _stream_isatty(sys.stderr),
):
- # No terminal: only proceed if the bootstrap deadline will arm; api-only
- # and TIMEOUT=0 never arm it, leaving the default credential public.
- deadline_arms = should_arm_bootstrap_timeout(
- host = host,
- secure = secure,
- api_only = api_only,
- frontend_served = frontend_served,
- is_colab = is_colab,
- requires_change = True,
- timeout_seconds = bootstrap_timeout_seconds(),
- )
- if not deadline_arms:
+ # Headless public launches replace the seeded password and show it once.
+ # Resolve a real TTY before rotation so the secret cannot reach the tee'd
+ # session log or another persistent stream (CWE-532).
+ out = _one_time_secret_stream()
+ if out is None:
+ return False, False
+ # Without cloudflared, keep the seeded credential for local recovery.
+ if secure and _tunnel_binary_confirmed_unavailable():
print(
- "Refusing to publish Unsloth on a public Cloudflare URL: the "
- "default admin password was never changed, no terminal is "
- "attached to change it here, and the bootstrap shutdown "
- "deadline does not apply to this launch (api-only, or "
- "UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT=0). Change the password "
- "first (run `unsloth studio` locally and log in, or re-run "
- "with a terminal attached), then retry.",
- file = sys.stderr,
+ "Error: refusing to expose Unsloth: the Cloudflare tunnel binary "
+ "(cloudflared) is unavailable and could not be downloaded, so no "
+ "secure link can be published. Your admin password is unchanged.",
+ file = out,
flush = True,
)
return False, False
- # The public page won't auto-fill the bootstrap credential (suppressed
- # below) and the seeded file may already be gone, so point recovery at a
- # terminal-attached run / reset-password instead of reading it from disk.
- print(
- " WARNING: the default admin password is still active while "
- "Unsloth is about to be published on a public Cloudflare URL, and "
- "no terminal is attached to change it here. The public page will "
- "NOT auto-fill the bootstrap credential. Set a new password by "
- "running `unsloth studio` locally with a terminal attached, or "
- "`unsloth studio reset-password`. Unsloth shuts down after the "
- "bootstrap deadline (UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT, default 1h) "
- "unless the password is changed.",
- file = sys.stderr,
- flush = True,
- )
- # Never serve the default credential in HTML over a public URL.
+ generated = _auto_generate_admin_password(_admin, out = out)
+ if generated is None:
+ # Inspect the compare-and-set winner; another auto-launch may still be
+ # delivering its password.
+ if _auth_storage.credential_undelivered(_admin):
+ logger.error(
+ "Refusing to publish Unsloth: another launch auto-generated the "
+ "admin password but has not confirmed that it was displayed. Retry "
+ "after that launch completes, or reset the credential with `unsloth "
+ "studio reset-password`."
+ )
+ return False, False
+ return True, True
+ # Write only to the raw console, never the retained server log. If delivery
+ # fails after commit, the transactional marker keeps later launches closed.
+ if not _deliver_one_time_credential(_admin, generated, out = out):
+ logger.error(
+ "The auto-generated Unsloth admin password could not be shown: the "
+ "console went away after the pre-rotation check. It is now the live "
+ "password but was never displayed, so nothing can recover it. Reset "
+ "the credential with `unsloth studio reset-password`, then relaunch."
+ )
+ return False, False
+ _auth_storage.clear_credential_undelivered()
+ # Password is no longer the default; still suppress any HTML injection of a
+ # stale bootstrap credential over the public URL.
return True, True
def _is_current_password(candidate: str) -> bool:
diff --git a/studio/backend/tests/test_colab_secure_autopassword.py b/studio/backend/tests/test_colab_secure_autopassword.py
new file mode 100644
index 00000000000..47aec32f8d6
--- /dev/null
+++ b/studio/backend/tests/test_colab_secure_autopassword.py
@@ -0,0 +1,1146 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Colab public-launch auto-password + opt-in same-tab link token.
+
+start(cloudflare=True) with no admin password set auto-generates one, shows it in
+the cell, and lets the shared link proceed; a supplied password is respected. The
+opt-in link token is appended to the SAME-TAB URL only. Imports the backend
+directly, so run under the Unsloth venv."""
+
+from __future__ import annotations
+
+import secrets
+import sys
+from pathlib import Path
+
+import pytest
+
+_BACKEND = Path(__file__).resolve().parents[1]
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+import colab # noqa: E402
+from auth import storage # noqa: E402
+
+
[email protected](autouse = True)
+def isolated_auth_db(tmp_path, monkeypatch):
+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")
+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")
+ monkeypatch.setattr(storage, "_bootstrap_password", None)
+ monkeypatch.setattr(storage, "_api_key_pbkdf2_salt_cache", None)
+ yield
+
+
+# Captured before the autouse stub below replaces it, so the probe itself can be
+# exercised for real.
+_REAL_DISPLAY_CHANNEL_ACTIVE = colab._display_channel_active
+
+
[email protected](autouse = True)
+def _display_channel_available(monkeypatch):
+ # Rotation is now gated on a real notebook display channel (pytest has none),
+ # so default it to available; the dedicated tests below flip it to exercise the
+ # fail-closed refusal.
+ monkeypatch.setattr(colab, "_display_channel_active", lambda: True)
+
+
+def _seed_admin(*, must_change_password: bool) -> str:
+ storage.create_initial_user(
+ username = storage.DEFAULT_ADMIN_USERNAME,
+ password = "bootstrap-secret-123",
+ jwt_secret = secrets.token_urlsafe(64),
+ must_change_password = must_change_password,
+ )
+ return storage.DEFAULT_ADMIN_USERNAME
+
+
+# ── auto-generate on the public path ─────────────────────────────────
+
+
+def test_auto_generate_sets_password_and_clears_must_change():
+ admin = _seed_admin(must_change_password = True)
+ assert storage.requires_password_change(admin) is True
+
+ generated = colab._auto_generate_colab_admin_password()
+
+ assert isinstance(generated, str) and len(generated) >= storage.MIN_PASSWORD_LENGTH
+ # Committed: must_change cleared and the new password verifies.
+ assert storage.requires_password_change(admin) is False
+ salt, pwd_hash, _jwt, _mc = storage.get_user_and_secret(admin)
+ from auth import hashing
+
+ assert hashing.verify_password(generated, salt, pwd_hash) is True
+
+
+def test_auto_generate_noop_when_password_already_set():
+ admin = _seed_admin(must_change_password = False)
+ # A supplied/changed password must NOT be overwritten.
+ assert colab._auto_generate_colab_admin_password() is None
+ assert storage.requires_password_change(admin) is False
+ from auth import hashing
+
+ salt, pwd_hash, _jwt, _mc = storage.get_user_and_secret(admin)
+ assert hashing.verify_password("bootstrap-secret-123", salt, pwd_hash) is True
+
+
+def test_auto_generate_loses_race_to_a_concurrent_password_change(monkeypatch):
+ # Another tab can complete /change-password against the reused Colab server
+ # between the requires_password_change() read and the rotation. The commit is a
+ # compare-and-set on must_change_password, so the user's chosen password
+ # survives and no already-replaced generated value is returned for display
+ # (publishing the shared link under it would lock everyone out).
+ admin = _seed_admin(must_change_password = True)
+ real_update = storage.update_password
+ real_requires = storage.requires_password_change
+ raced = []
+
+ def _racing_requires_password_change(username):
+ # Report "still pending", then let the other tab commit before we write.
+ if not raced:
+ raced.append(True)
+ real_update(username, "user-chosen-password-1", revoke_refresh_tokens = True)
+ return True
+
+ monkeypatch.setattr(storage, "requires_password_change", _racing_requires_password_change)
+
+ assert colab._auto_generate_colab_admin_password() is None
+ assert raced == [True]
+
+ monkeypatch.setattr(storage, "requires_password_change", real_requires)
+ from auth import hashing
+
+ salt, pwd_hash, _jwt, _mc = storage.get_user_and_secret(admin)
+ # The concurrently chosen password is intact; the generated one never landed.
+ assert hashing.verify_password("user-chosen-password-1", salt, pwd_hash) is True
+ assert storage.requires_password_change(admin) is False
+
+
+def test_tunnel_race_refuses_an_undelivered_auto_generated_winner(monkeypatch):
+ admin = _seed_admin(must_change_password = True)
+ real_update = storage.update_password
+ raced: list[str] = []
+
+ def _racing_update(username, new_password, **kwargs):
+ if not raced:
+ raced.append("auto")
+ assert (
+ real_update(
+ username,
+ "concurrent-auto-password-1",
+ revoke_refresh_tokens = True,
+ require_must_change = True,
+ mark_credential_undelivered = True,
+ )
+ is not None
+ )
+ return real_update(username, new_password, **kwargs)
+
+ monkeypatch.setattr(storage, "update_password", _racing_update)
+ monkeypatch.setattr(colab, "_display_channel_active", lambda: True)
+ import cloudflare_tunnel
+
+ started = {"called": False}
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "start_studio_tunnel",
+ lambda port, **_kwargs: started.update(called = True) or "https://example.invalid",
+ )
+
+ assert colab.start_cloudflare_tunnel(8888) is None
+ assert raced == ["auto"]
+ assert storage.credential_undelivered(admin) is True
+ assert started["called"] is False
+
+
+def test_tunnel_race_proceeds_with_a_concurrent_user_selected_winner(monkeypatch):
+ admin = _seed_admin(must_change_password = True)
+ real_update = storage.update_password
+ raced: list[str] = []
+
+ def _racing_update(username, new_password, **kwargs):
+ if not raced:
+ raced.append("user")
+ assert (
+ real_update(
+ username,
+ "concurrent-user-password-2",
+ revoke_refresh_tokens = True,
+ require_must_change = True,
+ )
+ is not None
+ )
+ return real_update(username, new_password, **kwargs)
+
+ monkeypatch.setattr(storage, "update_password", _racing_update)
+ monkeypatch.setattr(colab, "_display_channel_active", lambda: True)
+ import cloudflare_tunnel
+
+ started = {"called": False}
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "start_studio_tunnel",
+ lambda port, **_kwargs: started.update(called = True) or "https://example.trycloudflare.com",
+ )
+
+ assert colab.start_cloudflare_tunnel(8888) == "https://example.trycloudflare.com"
+ assert raced == ["user"]
+ assert storage.credential_undelivered(admin) is False
+ assert started["called"] is True
+
+
+def test_stale_marker_cleanup_preserves_concurrent_generated_winner(monkeypatch):
+ # An older process can leave a stale marker. If another launcher replaces the
+ # password and marker while this process validates that stale value, cleanup
+ # must not delete the winner's pending-delivery guard.
+ admin = _seed_admin(must_change_password = True)
+ real_get_connection = storage.get_connection
+ seed_conn = real_get_connection()
+ try:
+ seed_conn.execute(
+ "INSERT OR REPLACE INTO app_secrets (key, value) VALUES (?, ?)",
+ (storage._CREDENTIAL_UNDELIVERED_KEY, "legacy-stale-password-hash"),
+ )
+ seed_conn.commit()
+ finally:
+ seed_conn.close()
+
+ primary_conn = real_get_connection()
+ raced = []
+
+ class _RacingConnection:
+ def execute(
+ self,
+ sql,
+ params = (),
+ ):
+ if not raced and "password_hash" in sql:
+ raced.append(True)
+ assert storage.update_password(
+ admin,
+ "concurrent-generated-password",
+ revoke_refresh_tokens = True,
+ require_must_change = True,
+ mark_credential_undelivered = True,
+ )
+ return primary_conn.execute(sql, params)
+
+ def commit(self):
+ return primary_conn.commit()
+
+ def close(self):
+ return primary_conn.close()
+
+ first_connection = True
+
+ def _routed_connection():
+ nonlocal first_connection
+ if first_connection:
+ first_connection = False
+ return _RacingConnection()
+ return real_get_connection()
+
+ monkeypatch.setattr(storage, "get_connection", _routed_connection)
+
+ assert storage.credential_undelivered(admin) is True
+ assert raced == [True]
+ check_conn = real_get_connection()
+ try:
+ marker = check_conn.execute(
+ "SELECT value FROM app_secrets WHERE key = ?",
+ (storage._CREDENTIAL_UNDELIVERED_KEY,),
+ ).fetchone()["value"]
+ current_hash = check_conn.execute(
+ "SELECT password_hash FROM auth_user WHERE username = ?",
+ (admin,),
+ ).fetchone()["password_hash"]
+ assert marker == current_hash
+ finally:
+ check_conn.close()
+
+
+def test_update_password_compare_and_set_guard():
+ # Storage unit: the guarded update writes only while must_change_password = 1.
+ admin = _seed_admin(must_change_password = True)
+ assert (
+ storage.update_password(admin, "first-generated-pw-1", require_must_change = True) is not None
+ )
+ # must_change is now 0, so a second guarded write is refused (rowcount 0)...
+ assert storage.update_password(admin, "second-generated-pw-2", require_must_change = True) is None
+ from auth import hashing
+
+ salt, pwd_hash, _jwt, _mc = storage.get_user_and_secret(admin)
+ assert hashing.verify_password("first-generated-pw-1", salt, pwd_hash) is True
+ # ...while the unguarded path (an explicit reset/change) still applies.
+ assert storage.update_password(admin, "explicit-change-pw-3") is not None
+ salt, pwd_hash, _jwt, _mc = storage.get_user_and_secret(admin)
+ assert hashing.verify_password("explicit-change-pw-3", salt, pwd_hash) is True
+
+
+def test_auto_generate_purges_legacy_plaintext_credential_cache():
+ # Upgrade path: the pre-#7392 Colab flow persisted the admin username and
+ # password in plaintext in .colab_notebook_login and re-read it on every
+ # re-run. Nothing calls that flow now, so an upgraded runtime would keep a
+ # readable credential on disk forever (CWE-256) while this flow promises the
+ # credential is never persisted. Entering the public-auth path purges it, in
+ # BOTH branches (rotating, and already-has-a-password).
+ _seed_admin(must_change_password = True)
+ legacy = colab._colab_login_credentials_path()
+ colab._store_colab_login_credentials("unsloth", "legacy-plaintext-pw")
+ assert legacy.is_file()
+
+ assert isinstance(colab._auto_generate_colab_admin_password(), str)
+ assert not legacy.exists()
+
+ # Already-set branch: still purged.
+ colab._store_colab_login_credentials("unsloth", "legacy-plaintext-pw")
+ assert colab._auto_generate_colab_admin_password() is None
+ assert not legacy.exists()
+
+
+def test_start_cloudflare_tunnel_autogenerates_then_proceeds(monkeypatch):
+ admin = _seed_admin(must_change_password = True)
+ shown = {}
+
+ def _fake_display(u, p):
+ shown.update(user = u, pw = p)
+ return True
+
+ monkeypatch.setattr(colab, "_display_admin_credentials", _fake_display)
+ # start_cloudflare_tunnel does `from cloudflare_tunnel import start_studio_tunnel`;
+ # patch the module attribute so no real cloudflared is spawned.
+ import cloudflare_tunnel
+
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "start_studio_tunnel",
+ # **_kwargs: the real start_studio_tunnel takes managed_by/admission, and
+ # start_cloudflare_tunnel passes managed_by = "colab".
+ lambda port, **_kwargs: "https://example.trycloudflare.com",
+ )
+
+ url = colab.start_cloudflare_tunnel(8888)
+
+ assert url == "https://example.trycloudflare.com"
+ assert shown["user"] == admin
+ assert storage.requires_password_change(admin) is False
+
+
+def test_auto_generate_refuses_without_a_display_channel(monkeypatch):
+ # display() does not raise outside a notebook: with no InteractiveShell it
+ # prints repr(obj) and a terminal shell renders only text/plain, so the HTML
+ # card degrades to "<IPython.core.display.HTML object>" and the password is
+ # never seen. start(cloudflare=True) is documented to work on any runtime, so
+ # resolve the channel BEFORE rotating -- otherwise the seeded recovery
+ # credential is destroyed for a password nobody could read.
+ admin = _seed_admin(must_change_password = True)
+ monkeypatch.setattr(colab, "_display_channel_active", lambda: False)
+ rotations = []
+ # Mirrors the real contract: the rotated JWT secret on success, None on a
+ # rejected guard. Returning a bool here would make `False` read as committed.
+ monkeypatch.setattr(
+ storage, "update_password", lambda *a, **k: rotations.append(a) or "rotated-secret"
+ )
+
+ assert colab._auto_generate_colab_admin_password() is None
+
+ assert rotations == [] # nothing was rotated
+ assert storage.requires_password_change(admin) is True
+
+
+def test_start_cloudflare_tunnel_refuses_without_a_display_channel(monkeypatch):
+ # End to end: no display channel -> no rotation, and the pending-bootstrap
+ # backstop then refuses to publish the shared link.
+ admin = _seed_admin(must_change_password = True)
+ monkeypatch.setattr(colab, "_display_channel_active", lambda: False)
+ import cloudflare_tunnel
+
+ started = {"called": False}
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "start_studio_tunnel",
+ lambda port, **_kwargs: started.update(called = True) or "https://example.trycloudflare.com",
+ )
+
+ assert colab.start_cloudflare_tunnel(8888) is None
+ assert started["called"] is False
+ assert storage.requires_password_change(admin) is True
+
+
+def test_start_cloudflare_tunnel_refuses_after_an_undelivered_rotation(monkeypatch):
+ # The retry case. A previous run rotated the password and then failed to
+ # render the card, so it refused. must_change_password is 0 now, so every
+ # other check in this path passes and the link would go up for an account
+ # whose password nobody -- operator included -- has ever seen. The sentinel
+ # is the only thing that can still tell.
+ admin = _seed_admin(must_change_password = True)
+ monkeypatch.setattr(colab, "_display_admin_credentials", lambda *a, **k: False)
+ import cloudflare_tunnel
+
+ started = {"called": False}
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "start_studio_tunnel",
+ lambda port, **_kwargs: started.update(called = True) or "https://example.trycloudflare.com",
+ )
+
+ assert colab.start_cloudflare_tunnel(8888) is None # first run: refuses
+ assert storage.requires_password_change(admin) is False # ...but it committed
+ assert storage.credential_undelivered(admin) is True
+
+ assert colab.start_cloudflare_tunnel(8888) is None # retry: still refuses
+ assert started["called"] is False
+
+
+def test_transient_marker_clear_retries_before_opening_tunnel(monkeypatch):
+ admin = _seed_admin(must_change_password = True)
+ monkeypatch.setattr(colab, "_display_admin_credentials", lambda *a, **k: True)
+ clears: list[int] = []
+
+ def _transient_clear():
+ clears.append(1)
+ if len(clears) == 1:
+ raise OSError("database is locked")
+ conn = storage.get_connection()
+ try:
+ conn.execute(
+ "DELETE FROM app_secrets WHERE key = ?",
+ (storage._CREDENTIAL_UNDELIVERED_KEY,),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+ monkeypatch.setattr(storage, "clear_credential_undelivered", _transient_clear)
+ import cloudflare_tunnel
+
+ started = {"called": False}
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "start_studio_tunnel",
+ lambda port, **_kwargs: started.update(called = True) or "https://example.trycloudflare.com",
+ )
+
+ assert colab.start_cloudflare_tunnel(8888) == "https://example.trycloudflare.com"
+ assert len(clears) == 2
+ assert storage.credential_undelivered(admin) is False
+ assert started["called"] is True
+
+
+def test_marker_clear_exhaustion_retains_guard_and_keeps_tunnel_closed(monkeypatch):
+ admin = _seed_admin(must_change_password = True)
+ monkeypatch.setattr(colab, "_display_admin_credentials", lambda *a, **k: True)
+ clears: list[int] = []
+
+ def _persistent_clear_failure():
+ clears.append(1)
+ raise OSError("database is locked")
+
+ monkeypatch.setattr(
+ storage,
+ "clear_credential_undelivered",
+ _persistent_clear_failure,
+ )
+ import cloudflare_tunnel
+
+ started = {"called": False}
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "start_studio_tunnel",
+ lambda port, **_kwargs: started.update(called = True) or "https://example.trycloudflare.com",
+ )
+
+ assert colab.start_cloudflare_tunnel(8888) is None
+ assert len(clears) == colab._DELIVERY_MARKER_CLEAR_ATTEMPTS
+ assert storage.credential_undelivered(admin) is True
+ assert started["called"] is False
+
+
+def test_undelivered_sentinel_clears_on_the_next_password_change(monkeypatch):
+ # Self-healing is what keeps the guard from bricking the install: it matches
+ # on the committed hash, so `unsloth studio reset-password` releases it even
+ # if the sentinel file itself could not be removed.
+ admin = _seed_admin(must_change_password = True)
+ monkeypatch.setattr(colab, "_display_admin_credentials", lambda *a, **k: False)
+ assert colab.start_cloudflare_tunnel(8888) is None
+ assert storage.credential_undelivered(admin) is True
+
+ storage.update_password(admin, "operator-chosen-123", revoke_refresh_tokens = True)
+ assert storage.credential_undelivered(admin) is False
+
+
+def test_undelivered_sentinel_ignores_a_hash_it_does_not_match():
+ # A leftover marker naming a superseded password must not refuse a launch: it
+ # no longer describes the live credential, so it is stale, not a warning.
+ admin = _seed_admin(must_change_password = False)
+ storage.mark_credential_undelivered(admin)
+ assert storage.credential_undelivered(admin) is True
+
+ storage.update_password(admin, "operator-chosen-123", revoke_refresh_tokens = True)
+ conn = storage.get_connection()
+ try:
+ conn.execute(
+ "INSERT OR REPLACE INTO app_secrets (key, value) VALUES (?, ?)",
+ (storage._CREDENTIAL_UNDELIVERED_KEY, "deadbeef" * 8),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+ assert storage.credential_undelivered(admin) is False
+ conn = storage.get_connection()
+ try:
+ assert (
+ conn.execute(
+ "SELECT 1 FROM app_secrets WHERE key = ?",
+ (storage._CREDENTIAL_UNDELIVERED_KEY,),
+ ).fetchone()
+ is None
+ )
+ finally:
+ conn.close()
+
+
+def test_display_channel_active_false_without_a_kernel():
+ # The real probe under pytest: IPython may be importable, but there is no
+ # ipykernel-backed shell, so the channel must read as inactive.
+ assert _REAL_DISPLAY_CHANNEL_ACTIVE() is False
+
+
+def test_auto_generate_keeps_credential_when_post_commit_cleanup_raises(monkeypatch):
+ # update_password commits the row and only then runs its best-effort cleanup
+ # (clear_bootstrap_password, which can still raise on a read-only auth dir or a
+ # closed stderr). A raise there used to discard the
+ # generated password even though it was already live, and the caller would then
+ # publish the link (must_change is 0) under a credential nobody holds.
+ admin = _seed_admin(must_change_password = True)
+ real_update = storage.update_password
+
+ def _update_then_explode(username, new_password, **kwargs):
+ real_update(username, new_password, **kwargs)
+ raise OSError("database is locked") # post-commit cleanup failure
+
+ monkeypatch.setattr(storage, "update_password", _update_then_explode)
+
+ generated = colab._auto_generate_colab_admin_password()
+
+ assert isinstance(generated, str) and generated
+ from auth import hashing
+
+ salt, pwd_hash, _jwt, _mc = storage.get_user_and_secret(admin)
+ # The returned value is exactly the committed one, so the card shows a
+ # password that actually authenticates.
+ assert hashing.verify_password(generated, salt, pwd_hash) is True
+
+
+def test_auto_generate_drops_credential_when_the_commit_itself_fails(monkeypatch):
+ # The converse: the write never landed, so nothing may be displayed -- showing
+ # it would publish the link under a password that does not authenticate.
+ admin = _seed_admin(must_change_password = True)
+
+ def _explode(username, new_password, **kwargs):
+ raise OSError("database is locked")
+
+ monkeypatch.setattr(storage, "update_password", _explode)
+
+ assert colab._auto_generate_colab_admin_password() is None
+ assert storage.requires_password_change(admin) is True
+
+
+def test_start_cloudflare_tunnel_refuses_if_autogen_fails(monkeypatch):
+ _seed_admin(must_change_password = True)
+ # Simulate auto-generation failing (e.g. DB error): the pending gate then still
+ # refuses the shared link (fail safe), returning None.
+ monkeypatch.setattr(colab, "_auto_generate_colab_admin_password", lambda: None)
+ assert colab.start_cloudflare_tunnel(8888) is None
+
+
+# ── credential display never persists to disk ────────────────────────
+
+
+def ipython_display(monkeypatch):
+ """Stub IPython.display: CI has no IPython, so importing it would error out.
+
+ Mocks the `IPython` parent too, since `from IPython.display import ...`
+ resolves the package first.
+ """
+ import types
+
+ module = types.ModuleType("IPython.display")
+ module.HTML = lambda html: types.SimpleNamespace(data = html)
+ module.display = lambda *a, **k: None
+ package = types.ModuleType("IPython")
+ package.display = module
+ monkeypatch.setitem(sys.modules, "IPython", package)
+ monkeypatch.setitem(sys.modules, "IPython.display", module)
+ return module
+
+
+def test_display_admin_credentials_warns_that_output_is_saved(monkeypatch, ipython_display):
+ # The cell is the only surface a notebook has, and a notebook SAVES its output:
+ # Colab autosaves to Drive and an exported/shared .ipynb carries the password
+ # with it. The card must say so rather than claim the value is never written to
+ # disk, so the operator knows to clear the output (or change the password).
+ captured = []
+ monkeypatch.setattr(ipython_display, "display", lambda *a, **k: captured.append((a, k)))
+
+ colab._display_admin_credentials("unsloth", "Saved-Output-Pw-42")
+
+ rendered = "".join(str(getattr(obj, "data", obj)) for args, _k in captured for obj in args)
+ assert "saves cell output" in rendered
+ assert "clear this cell's output" in rendered
+ assert "not written to disk" not in rendered # the old, false promise
+ assert "reset-password" in rendered
+
+
+def test_display_admin_credentials_plaintext_fallback_warns_too(monkeypatch, ipython_display):
+ # The text/plain fallback carries the same warning; it is the branch a broken
+ # HTML renderer falls back to.
+ published = []
+
+ def _display(*args, **kwargs):
+ if not kwargs.get("raw"):
+ raise RuntimeError("HTML render failed")
+ published.append(args)
+
+ monkeypatch.setattr(ipython_display, "display", _display)
+
+ assert colab._display_admin_credentials("unsloth", "Fallback-Pw-7") is True
+ rendered = "".join(str(a) for args in published for a in args)
+ assert "Fallback-Pw-7" in rendered
+ assert "saved" in rendered and "clear it before sharing" in rendered
+ assert "not saved to disk" not in rendered
+
+
+def test_display_admin_credentials_never_writes_to_stdout(monkeypatch, capsys, ipython_display):
+ # The auto-generated password must reach the notebook cell only through the
+ # IPython display channel (iopub display_data), never sys.stdout/stderr or a
+ # logger, because the server tees stdout/stderr to a retained on-disk session
+ # log (run._setup_server_disk_logging). Writing it there would persist the
+ # credential, contradicting the one-time / non-persistent flow.
+ captured = []
+ monkeypatch.setattr(ipython_display, "display", lambda *a, **k: captured.append((a, k)))
+
+ secret_pw = "Sup3r-Secret-Pw-Token-xyz"
+ colab._display_admin_credentials("unsloth", secret_pw)
+
+ out = capsys.readouterr()
+ assert secret_pw not in out.out
+ assert secret_pw not in out.err
+
+ # It IS shown via the display channel (HTML card carries it in .data; a raw
+ # text/plain fallback carries it in the mimebundle dict).
+ shown = False
+ for args, _kwargs in captured:
+ for obj in args:
+ data = getattr(obj, "data", obj)
+ if secret_pw in str(data):
+ shown = True
+ assert shown, "credential was not surfaced through the IPython display channel"
+
+
+def test_display_admin_credentials_no_display_channel_is_silent(monkeypatch, capsys):
+ # If IPython is unavailable, we must NOT fall back to stdout/logging (which the
+ # server would tee to disk); showing nothing is the safe outcome.
+ import builtins
+
+ real_import = builtins.__import__
+
+ def _blocked_import(name, *args, **kwargs):
+ if name == "IPython.display" or name.startswith("IPython"):
+ raise ImportError("simulated: IPython unavailable")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", _blocked_import)
+ displayed = colab._display_admin_credentials("unsloth", "Another-Secret-Pw-999")
+ assert displayed is False # no channel -> caller must fail closed
+ out = capsys.readouterr()
+ assert "Another-Secret-Pw-999" not in out.out
+ assert "Another-Secret-Pw-999" not in out.err
+
+
+def test_display_admin_credentials_returns_true_on_success(monkeypatch, ipython_display):
+ # A successful publish through the display channel reports True so the caller
+ # may proceed to publish the shared link.
+ monkeypatch.setattr(ipython_display, "display", lambda *a, **k: None)
+ assert colab._display_admin_credentials("unsloth", "Shown-Pw-123") is True
+
+
+def test_display_admin_credentials_returns_false_when_display_raises(monkeypatch, ipython_display):
+ # Both the HTML and the plain-text publish raise (e.g. a broken display hook):
+ # nothing was shown, so report False and never fall back to stdout/logging.
+ def _boom(*_a, **_k):
+ raise RuntimeError("display channel is broken")
+
+ monkeypatch.setattr(ipython_display, "display", _boom)
+ assert colab._display_admin_credentials("unsloth", "Never-Shown-Pw-9") is False
+
+
+def test_start_cloudflare_tunnel_fails_closed_when_display_fails(monkeypatch):
+ # The password is rotated and committed, but it cannot be surfaced in the
+ # notebook (display returns False). Publishing the shared link would expose it
+ # under a password nobody ever saw, so fail closed: no tunnel is started.
+ _seed_admin(must_change_password = True)
+ monkeypatch.setattr(colab, "_display_admin_credentials", lambda u, p: False)
+
+ import cloudflare_tunnel
+
+ started = {"called": False}
+
+ def _spy(port):
+ started["called"] = True
+ return "https://example.trycloudflare.com"
+
+ monkeypatch.setattr(cloudflare_tunnel, "start_studio_tunnel", _spy)
+
+ assert colab.start_cloudflare_tunnel(8888) is None
+ assert started["called"] is False # link never published
+
+
+# ── opt-in same-tab link token ───────────────────────────────────────
+
+
+def _patch_start_for_cloudflare(monkeypatch, *, finalize_calls, embed_kwargs):
+ """Stub start()'s side effects so it runs to the keepalive loop, then bails.
+
+ Records any call to _finalize_colab_admin_password (the #7349 bootstrap-finalize +
+ plaintext disk-cache path) and the kwargs passed to _show_and_embed.
+ """
+ import time
+
+ monkeypatch.setattr(colab, "_is_studio_healthy", lambda port: True)
+ monkeypatch.setattr(colab, "_is_colab_runtime", lambda: True)
+ monkeypatch.setattr(
+ colab,
+ "_finalize_colab_admin_password",
+ lambda: finalize_calls.append("finalize") or ("unsloth", "secret"),
+ )
+ monkeypatch.setattr(
+ colab, "start_cloudflare_tunnel", lambda port: "https://share.trycloudflare.com"
+ )
+ monkeypatch.setattr(colab, "_publish_cloudflare_url", lambda url: None)
+ monkeypatch.setattr(
+ colab, "_show_and_embed", lambda port, **kwargs: embed_kwargs.update(kwargs)
+ )
+ monkeypatch.setattr(colab, "_stop_cloudflare_tunnel", lambda: None)
+ monkeypatch.setattr(time, "sleep", lambda _: (_ for _ in ()).throw(KeyboardInterrupt))
+
+
+def test_start_cloudflare_never_finalizes_or_caches_credentials(monkeypatch):
+ # Post-merge invariant: on the shared-link path start() must NOT call the #7349
+ # finalize/disk-cache flow. Doing so would clear the must-change gate before
+ # start_cloudflare_tunnel runs (defeating the auto-generate rotation) and would
+ # persist the admin password in plaintext on disk, both of which #7392 forbids.
+ finalize_calls: list[str] = []
+ embed_kwargs: dict = {}
+ _patch_start_for_cloudflare(
+ monkeypatch, finalize_calls = finalize_calls, embed_kwargs = embed_kwargs
+ )
+
+ colab.start(cloudflare = True)
+
+ assert finalize_calls == [] # credential handled by start_cloudflare_tunnel only
+ assert "colab_login" not in embed_kwargs or embed_kwargs["colab_login"] is None
+
+
+def test_start_without_cloudflare_purges_legacy_plaintext_cache(monkeypatch):
+ # Cache migration is independent of tunnel selection: an upgraded runtime
+ # using the documented proxy-only path must not retain the old plaintext.
+ admin = _seed_admin(must_change_password = False)
+ colab._store_colab_login_credentials(admin, "bootstrap-secret-123")
+ cache = colab._colab_login_credentials_path()
+ assert cache.exists()
+ finalize_calls: list[str] = []
+ embed_kwargs: dict = {}
+ _patch_start_for_cloudflare(
+ monkeypatch,
+ finalize_calls = finalize_calls,
+ embed_kwargs = embed_kwargs,
+ )
+ monkeypatch.setattr(colab, "_display_admin_credentials", lambda *args, **kwargs: True)
+
+ colab.start(cloudflare = False)
+
+ assert not cache.exists()
+
+
+def test_start_scrubs_supplied_password_before_migration_failure(monkeypatch):
+ # The environment value must not survive any start() return path: later
+ # notebook subprocesses would otherwise inherit the plaintext credential.
+ import os
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_PASSWORD", "notebook-supplied-password")
+ monkeypatch.setattr(
+ colab,
+ "_handoff_or_purge_legacy_colab_credentials",
+ lambda: (_ for _ in ()).throw(
+ colab._ColabCredentialHandoffFailed("legacy cache unreadable")
+ ),
+ )
+
+ colab.start(cloudflare = False)
+
+ assert "UNSLOTH_STUDIO_PASSWORD" not in os.environ
+
+
+def test_notebook_text_warns_that_cell_output_is_saved():
+ # The runtime card already says the notebook saves its output; the notebook's
+ # own intro cell and code comment must not contradict it by promising the
+ # credential is never written to disk. Colab autosaves to Drive and a shared or
+ # exported copy carries the cell output -- and the password with it.
+ import json
+
+ notebook = Path(__file__).resolve().parents[2] / "Unsloth_Studio_Colab.ipynb"
+ cells = json.loads(notebook.read_text(encoding = "utf-8"))["cells"]
+ text = "".join("".join(cell.get("source", [])) for cell in cells)
+
+ assert "never written to disk" not in text # the old, false promise
+ assert "SAVES its cell output" in text # intro cell
+ assert "This notebook saves cell output" in text # code-cell comment
+ assert text.count("clear the output") >= 2
+
+
+# ── server-reuse fast path: UNSLOTH_STUDIO_PASSWORD ──────────────────
+
+
+def test_supplied_password_env_name_matches_the_backend_constant():
+ # colab.py hardcodes the name so the strip still runs when the auth import
+ # fails; keep it identical to the one run.py/the CLI resolve.
+ from auth.terminal_prompt import SUPPLIED_PASSWORD_ENV
+ assert colab._SUPPLIED_PASSWORD_ENV == SUPPLIED_PASSWORD_ENV
+
+
+def test_start_reuse_applies_supplied_password_before_the_tunnel(monkeypatch):
+ # Regression (Codex 3651035062, P2): the fast path never calls run_server, so
+ # run._apply_supplied_password never runs. The supplied password was ignored
+ # while the bootstrap one was still pending (an auto-generated one replaced
+ # it), and the plaintext was still in os.environ when cloudflared was spawned,
+ # so the child inherited it through the process environment (CWE-214/CWE-526).
+ import os
+
+ admin = _seed_admin(must_change_password = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_PASSWORD", "notebook-supplied-pw-1")
+ seen: dict = {}
+ finalize_calls: list[str] = []
+ embed_kwargs: dict = {}
+ _patch_start_for_cloudflare(
+ monkeypatch, finalize_calls = finalize_calls, embed_kwargs = embed_kwargs
+ )
+
+ def _tunnel(port):
+ seen["env_at_spawn"] = os.environ.get("UNSLOTH_STUDIO_PASSWORD")
+ seen["must_change"] = storage.requires_password_change(admin)
+ return "https://share.trycloudflare.com"
+
+ monkeypatch.setattr(colab, "start_cloudflare_tunnel", _tunnel)
+
+ colab.start(cloudflare = True)
+
+ # Stripped BEFORE the subprocess spawn, and applied rather than discarded.
+ assert seen["env_at_spawn"] is None
+ assert seen["must_change"] is False
+ from auth import hashing
+
+ salt, pwd_hash, _jwt, _mc = storage.get_user_and_secret(admin)
+ assert hashing.verify_password("notebook-supplied-pw-1", salt, pwd_hash) is True
+ assert "UNSLOTH_STUDIO_PASSWORD" not in os.environ
+
+
+def test_start_reuse_strips_supplied_password_when_one_is_already_set(monkeypatch):
+ # The common re-run: a password is already set, so the variable only sets the
+ # INITIAL password and must not overwrite it -- but it must still be removed
+ # from the environment before anything is spawned.
+ import os
+
+ admin = _seed_admin(must_change_password = False)
+ monkeypatch.setenv("UNSLOTH_STUDIO_PASSWORD", "notebook-supplied-pw-2")
+ seen: dict = {}
+ finalize_calls: list[str] = []
+ embed_kwargs: dict = {}
+ _patch_start_for_cloudflare(
+ monkeypatch, finalize_calls = finalize_calls, embed_kwargs = embed_kwargs
+ )
+
+ def _tunnel(port):
+ seen["env_at_spawn"] = os.environ.get("UNSLOTH_STUDIO_PASSWORD")
+ return "https://share.trycloudflare.com"
+
+ monkeypatch.setattr(colab, "start_cloudflare_tunnel", _tunnel)
+
+ colab.start(cloudflare = True)
+
+ assert seen["env_at_spawn"] is None
+ from auth import hashing
+
+ salt, pwd_hash, _jwt, _mc = storage.get_user_and_secret(admin)
+ # The existing password still authenticates; the supplied one did not win.
+ assert hashing.verify_password("bootstrap-secret-123", salt, pwd_hash) is True
+ assert hashing.verify_password("notebook-supplied-pw-2", salt, pwd_hash) is False
+
+
+def test_consume_supplied_password_rejects_invalid_values_but_still_strips(monkeypatch):
+ # Too short / whitespace fails the same rules the CLI enforces. In a notebook
+ # we cannot exit the process, so the value is ignored (the tunnel path then
+ # auto-generates and shows one) -- but never left in the environment.
+ import os
+ admin = _seed_admin(must_change_password = True)
+ for bad in ("short", "has space in it"):
+ monkeypatch.setenv("UNSLOTH_STUDIO_PASSWORD", bad)
+ colab._consume_supplied_password_on_reuse()
+ assert "UNSLOTH_STUDIO_PASSWORD" not in os.environ
+ # Left pending, so start_cloudflare_tunnel still secures the link itself.
+ assert storage.requires_password_change(admin) is True
+
+
+def test_consume_supplied_password_rejects_the_current_bootstrap_password(monkeypatch):
+ import os
+
+ admin = _seed_admin(must_change_password = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_PASSWORD", "bootstrap-secret-123")
+
+ colab._consume_supplied_password_on_reuse()
+
+ assert "UNSLOTH_STUDIO_PASSWORD" not in os.environ
+ assert storage.requires_password_change(admin) is True
+ from auth import hashing
+
+ salt, pwd_hash, _jwt, _mc = storage.get_user_and_secret(admin)
+ assert hashing.verify_password("bootstrap-secret-123", salt, pwd_hash) is True
+
+
+def test_consume_supplied_password_never_logs_the_value(monkeypatch, caplog):
+ # The password must not reach the logger: the server tees stdout/stderr into a
+ # retained session log on disk (run._setup_server_disk_logging).
+ import logging
+ import os
+
+ _seed_admin(must_change_password = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_PASSWORD", "notebook-supplied-pw-3")
+ with caplog.at_level(logging.DEBUG):
+ colab._consume_supplied_password_on_reuse()
+
+ assert "notebook-supplied-pw-3" not in caplog.text
+ assert "UNSLOTH_STUDIO_PASSWORD" not in os.environ
+
+
+def test_upgrade_rerun_hands_back_the_cached_credential_before_purging(monkeypatch):
+ # An existing Colab user upgrades and re-runs start(). Their password is
+ # already set, so nothing is rotated -- but the pre-#7392 flow re-displayed
+ # the cached credential on every re-run, and that cache was the only copy a
+ # user who cleared their earlier cell output still had. Purging it silently
+ # would leave a working password nobody can discover, so hand it back once
+ # and THEN remove the file: the CWE-256 fix without the lockout.
+ admin = _seed_admin(must_change_password = True)
+ existing = "existing-colab-password-from-last-run"
+ assert storage.update_password(admin, existing) is not None
+ colab._store_colab_login_credentials(admin, existing)
+ cache = colab._colab_login_credentials_path()
+ assert cache.exists()
+
+ shown: list = []
+ monkeypatch.setattr(
+ colab,
+ "_display_admin_credentials",
+ lambda u, p, **kw: shown.append((u, p, kw)) or True,
+ )
+ monkeypatch.setattr(colab, "_display_channel_active", lambda: True)
+
+ assert colab._auto_generate_colab_admin_password() is None # nothing rotated
+ assert not cache.exists(), "the plaintext cache must still be purged"
+ assert len(shown) == 1, shown
+ user, pw, kwargs = shown[0]
+ assert (user, pw) == (admin, existing)
+ assert kwargs.get("final_cached_copy") is True
+ # and the credential it handed back is the one that actually works
+ from auth import hashing
+
+ salt, pwd_hash, _jwt, _mc = storage.get_user_and_secret(admin)
+ assert hashing.verify_password(existing, salt, pwd_hash) is True
+
+
+def test_upgrade_rerun_retains_live_cache_and_refuses_tunnel_when_display_fails(monkeypatch):
+ admin = _seed_admin(must_change_password = True)
+ existing = "existing-colab-password-display-failure"
+ assert storage.update_password(admin, existing) is not None
+ colab._store_colab_login_credentials(admin, existing)
+ cache = colab._colab_login_credentials_path()
+ monkeypatch.setattr(colab, "_display_admin_credentials", lambda *a, **k: False)
+
+ import cloudflare_tunnel
+
+ started = {"called": False}
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "start_studio_tunnel",
+ lambda port, **_kwargs: started.update(called = True) or "https://example.invalid",
+ )
+
+ assert colab.start_cloudflare_tunnel(8888) is None
+ assert started["called"] is False
+ assert cache.read_text(encoding = "utf-8").splitlines() == [admin, existing]
+
+
+def test_upgrade_rerun_retains_cache_and_refuses_tunnel_on_validation_error(monkeypatch):
+ admin = _seed_admin(must_change_password = True)
+ existing = "existing-colab-password-validation-error"
+ assert storage.update_password(admin, existing) is not None
+ colab._store_colab_login_credentials(admin, existing)
+ cache = colab._colab_login_credentials_path()
+ monkeypatch.setattr(colab, "_colab_credentials_still_valid", lambda *a: None)
+
+ import cloudflare_tunnel
+
+ started = {"called": False}
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "start_studio_tunnel",
+ lambda port, **_kwargs: started.update(called = True) or "https://example.invalid",
+ )
+
+ assert colab.start_cloudflare_tunnel(8888) is None
+ assert started["called"] is False
+ assert cache.read_text(encoding = "utf-8").splitlines() == [admin, existing]
+
+
+def test_clear_legacy_cache_truncates_and_verifies_when_unlink_fails(monkeypatch):
+ _seed_admin(must_change_password = False)
+ colab._store_colab_login_credentials("unsloth", "legacy-plaintext-password")
+ cache = colab._colab_login_credentials_path()
+ cache_type = type(cache)
+ real_unlink = cache_type.unlink
+
+ def _unlink(self, *args, **kwargs):
+ if self == cache:
+ raise OSError("unlink denied")
+ return real_unlink(self, *args, **kwargs)
+
+ monkeypatch.setattr(cache_type, "unlink", _unlink)
+
+ assert colab._clear_colab_login_credentials() is True
+ assert cache.is_file()
+ assert cache.stat().st_size == 0
+ assert colab._load_colab_login_credentials() is None
+
+
+def test_clear_legacy_cache_does_not_claim_uncheckable_path_is_absent(monkeypatch):
+ # Python 3.14 Path.exists() returns False for inaccessible paths. If unlink
+ # and stat both fail, that False is not proof that the plaintext file is gone.
+ _seed_admin(must_change_password = False)
+ colab._store_colab_login_credentials("unsloth", "legacy-plaintext-password")
+ cache = colab._colab_login_credentials_path()
+ original = cache.read_text(encoding = "utf-8")
+ cache_type = type(cache)
+ real_unlink = cache_type.unlink
+ real_exists = cache_type.exists
+ real_stat = cache_type.stat
+ real_write_text = cache_type.write_text
+
+ def _unlink(self, *args, **kwargs):
+ if self == cache:
+ raise PermissionError("unlink denied")
+ return real_unlink(self, *args, **kwargs)
+
+ def _exists(self):
+ if self == cache:
+ return False
+ return real_exists(self)
+
+ def _stat(self, *args, **kwargs):
+ if self == cache:
+ raise PermissionError("stat denied")
+ return real_stat(self, *args, **kwargs)
+
+ def _write_text(self, *args, **kwargs):
+ if self == cache:
+ raise PermissionError("truncate denied")
+ return real_write_text(self, *args, **kwargs)
+
+ monkeypatch.setattr(cache_type, "unlink", _unlink)
+ monkeypatch.setattr(cache_type, "exists", _exists)
+ monkeypatch.setattr(cache_type, "stat", _stat)
+ monkeypatch.setattr(cache_type, "write_text", _write_text)
+
+ assert colab._clear_colab_login_credentials() is False
+ assert cache.read_text(encoding = "utf-8") == original
+
+
+def test_legacy_cache_read_failure_blocks_migration(monkeypatch):
+ admin = _seed_admin(must_change_password = False)
+ colab._store_colab_login_credentials(admin, "bootstrap-secret-123")
+ cache = colab._colab_login_credentials_path()
+ cache_type = type(cache)
+ real_read_text = cache_type.read_text
+
+ def _read_text(self, *args, **kwargs):
+ if self == cache:
+ raise PermissionError("read denied")
+ return real_read_text(self, *args, **kwargs)
+
+ monkeypatch.setattr(cache_type, "read_text", _read_text)
+
+ with pytest.raises(colab._ColabCredentialHandoffFailed, match = "could not be loaded"):
+ colab._handoff_or_purge_legacy_colab_credentials()
+ assert cache.exists()
+
+
+def test_upgrade_rerun_refuses_tunnel_when_live_cache_cannot_be_cleared(monkeypatch):
+ admin = _seed_admin(must_change_password = True)
+ existing = "existing-colab-password-purge-failure"
+ assert storage.update_password(admin, existing) is not None
+ colab._store_colab_login_credentials(admin, existing)
+ cache = colab._colab_login_credentials_path()
+ original = cache.read_text(encoding = "utf-8")
+ cache_type = type(cache)
+ real_unlink = cache_type.unlink
+ real_write_text = cache_type.write_text
+
+ def _unlink(self, *args, **kwargs):
+ if self == cache:
+ raise OSError("unlink denied")
+ return real_unlink(self, *args, **kwargs)
+
+ def _write_text(self, *args, **kwargs):
+ if self == cache:
+ raise OSError("truncate denied")
+ return real_write_text(self, *args, **kwargs)
+
+ monkeypatch.setattr(cache_type, "unlink", _unlink)
+ monkeypatch.setattr(cache_type, "write_text", _write_text)
+ monkeypatch.setattr(colab, "_display_admin_credentials", lambda *a, **k: True)
+
+ import cloudflare_tunnel
+
+ started = {"called": False}
+ monkeypatch.setattr(
+ cloudflare_tunnel,
+ "start_studio_tunnel",
+ lambda port, **_kwargs: started.update(called = True) or "https://example.invalid",
+ )
+
+ assert colab.start_cloudflare_tunnel(8888) is None
+ assert started["called"] is False
+ assert cache.read_text(encoding = "utf-8") == original
+
+
+def test_upgrade_rerun_purges_a_cached_credential_that_no_longer_works(monkeypatch):
+ # Same path, but the cached copy is stale (the user changed the password in
+ # the app). Showing it would print a credential that does not authenticate,
+ # so it is dropped without being displayed.
+ admin = _seed_admin(must_change_password = True)
+ colab._store_colab_login_credentials(admin, "stale-cached-password")
+ assert storage.update_password(admin, "the-real-current-password") is not None
+ cache = colab._colab_login_credentials_path()
+ assert cache.exists()
+
+ shown: list = []
+ monkeypatch.setattr(
+ colab,
+ "_display_admin_credentials",
+ lambda u, p, **kw: shown.append((u, p, kw)) or True,
+ )
+ monkeypatch.setattr(colab, "_display_channel_active", lambda: True)
+
+ assert colab._auto_generate_colab_admin_password() is None
+ assert not cache.exists()
+ assert shown == [], "a credential that no longer authenticates must not be shown"
diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.py
index 2c23e6204cc..fe5e5749f8b 100644
--- a/studio/backend/tests/test_desktop_auth.py
+++ b/studio/backend/tests/test_desktop_auth.py
@@ -1038,6 +1038,109 @@ def test_update_password_clears_desktop_secret():
assert storage.validate_desktop_secret(raw) is None
+def test_update_password_marks_credential_undelivered_in_database():
+ seed_user(must_change_password = True)
+
+ changed = storage.update_password(
+ storage.DEFAULT_ADMIN_USERNAME,
+ "generated-public-password",
+ require_must_change = True,
+ mark_credential_undelivered = True,
+ )
+
+ assert changed is not None
+ assert storage.credential_undelivered(storage.DEFAULT_ADMIN_USERNAME) is True
+ conn = storage.get_connection()
+ try:
+ pending = conn.execute(
+ "SELECT value FROM app_secrets WHERE key = ?",
+ (storage._CREDENTIAL_UNDELIVERED_KEY,),
+ ).fetchone()
+ current = conn.execute(
+ "SELECT password_hash FROM auth_user WHERE username = ?",
+ (storage.DEFAULT_ADMIN_USERNAME,),
+ ).fetchone()
+ finally:
+ conn.close()
+ assert pending is not None and current is not None
+ assert pending["value"] == current["password_hash"]
+
+
+def test_ordinary_password_change_clears_pending_delivery_state():
+ seed_user(must_change_password = True)
+ assert storage.update_password(
+ storage.DEFAULT_ADMIN_USERNAME,
+ "generated-public-password",
+ require_must_change = True,
+ mark_credential_undelivered = True,
+ )
+ assert storage.credential_undelivered(storage.DEFAULT_ADMIN_USERNAME) is True
+
+ assert storage.update_password(storage.DEFAULT_ADMIN_USERNAME, "operator-chosen-password")
+
+ assert storage.credential_undelivered(storage.DEFAULT_ADMIN_USERNAME) is False
+
+
+def test_pending_delivery_write_failure_rolls_back_password_rotation():
+ seed_user(must_change_password = True)
+ before = storage.get_user_and_secret(storage.DEFAULT_ADMIN_USERNAME)
+ assert before is not None
+ conn = storage.get_connection()
+ try:
+ conn.execute(
+ f"""
+ CREATE TRIGGER fail_pending_delivery
+ BEFORE INSERT ON app_secrets
+ WHEN NEW.key = '{storage._CREDENTIAL_UNDELIVERED_KEY}'
+ BEGIN
+ SELECT RAISE(ABORT, 'pending delivery unavailable');
+ END
+ """
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+ with pytest.raises(sqlite3.IntegrityError, match = "pending delivery unavailable"):
+ storage.update_password(
+ storage.DEFAULT_ADMIN_USERNAME,
+ "must-not-land",
+ require_must_change = True,
+ mark_credential_undelivered = True,
+ )
+
+ after = storage.get_user_and_secret(storage.DEFAULT_ADMIN_USERNAME)
+ assert after is not None
+ assert after == before
+ assert storage.credential_undelivered(storage.DEFAULT_ADMIN_USERNAME) is False
+
+
+def test_update_password_revokes_desktop_secret_in_the_same_transaction(monkeypatch):
+ # The desktop secret authenticates as this user WITHOUT the password, so it has
+ # to die in the SAME transaction as the rotation. It used to be revoked after
+ # the commit, on a second connection: anything that failed in between (a locked
+ # or busy database, or the bootstrap-file cleanup raising first, as simulated
+ # here) left a pre-change desktop credential live against the new password.
+ seed_user()
+ raw = storage.create_desktop_secret()
+ assert storage.validate_desktop_secret(raw) == storage.DEFAULT_ADMIN_USERNAME
+
+ def _boom():
+ raise OSError("auth dir is read-only")
+
+ monkeypatch.setattr(storage, "clear_bootstrap_password", _boom)
+
+ with pytest.raises(OSError):
+ storage.update_password(storage.DEFAULT_ADMIN_USERNAME, "new-admin-password")
+
+ # The rotation committed, and the desktop secret went with it.
+ assert storage.validate_desktop_secret(raw) is None
+ salt, pwd_hash, _jwt, _must_change = storage.get_user_and_secret(storage.DEFAULT_ADMIN_USERNAME)
+ from auth import hashing
+
+ assert hashing.verify_password("new-admin-password", salt, pwd_hash) is True
+
+
def test_update_password_on_unknown_user_leaves_desktop_secret_intact():
seed_user()
raw = storage.create_desktop_secret()
@@ -1113,3 +1216,74 @@ def test_the_router_stub_covers_every_router_main_imports():
f"main.py imports from routes.{{{','.join(unstubbed)}}}, which this file never "
f"registers in sys.modules, so the real package would be imported instead"
)
+
+
+def test_update_password_discards_the_rotation_if_desktop_revocation_raises(monkeypatch):
+ """A failing desktop revoke must roll the password back, not commit half of it.
+
+ Moving clear_desktop_secret INSIDE the transaction changed this case. 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 --
+ a credential that authenticates as this user without the password, still valid
+ against the new one. Now the raise unwinds the whole transaction: old password,
+ old desktop secret, consistent either way. Fail closed beats half-applied.
+ """
+ seed_user()
+ raw = storage.create_desktop_secret()
+ assert storage.validate_desktop_secret(raw) == storage.DEFAULT_ADMIN_USERNAME
+ salt_before, hash_before, _jwt_before, _mc = storage.get_user_and_secret(
+ storage.DEFAULT_ADMIN_USERNAME
+ )
+
+ def _boom(conn = None):
+ raise sqlite3.OperationalError("database is locked")
+
+ monkeypatch.setattr(storage, "clear_desktop_secret", _boom)
+
+ with pytest.raises(sqlite3.OperationalError):
+ storage.update_password(storage.DEFAULT_ADMIN_USERNAME, "should-not-land")
+
+ salt_after, hash_after, _jwt_after, _mc2 = storage.get_user_and_secret(
+ storage.DEFAULT_ADMIN_USERNAME
+ )
+ assert (salt_after, hash_after) == (
+ salt_before,
+ hash_before,
+ ), "the password was committed even though the transaction could not finish"
+ from auth import hashing
+
+ assert hashing.verify_password("should-not-land", salt_after, hash_after) is False
+ # The desktop secret is still the pre-change one, matching the un-rotated password.
+ assert storage.validate_desktop_secret(raw) == storage.DEFAULT_ADMIN_USERNAME
+
+
+def test_update_password_still_applies_when_desktop_secret_is_preserved(monkeypatch):
+ """preserve_desktop_secret must skip the revoke entirely, not merely tolerate it.
+
+ The desktop app authenticates WITH that secret and then sets its first
+ password; revoking it would break the auto-auth for a change the desktop
+ itself made. If the in-transaction move ever stopped honouring the flag, the
+ revoke would run and this would fail.
+ """
+ seed_user()
+ raw = storage.create_desktop_secret()
+
+ called = []
+ real = storage.clear_desktop_secret
+ monkeypatch.setattr(
+ storage,
+ "clear_desktop_secret",
+ lambda conn = None: called.append(conn) or real(conn),
+ )
+ _salt, pwd_hash, _jwt, _mc = storage.get_user_and_secret(storage.DEFAULT_ADMIN_USERNAME)
+ assert (
+ storage.update_password(
+ storage.DEFAULT_ADMIN_USERNAME,
+ "desktop-chosen-password",
+ expect_password_hash = pwd_hash,
+ preserve_desktop_secret = True,
+ )
+ is not None
+ )
+ assert called == [], "clear_desktop_secret ran despite preserve_desktop_secret"
+ assert storage.validate_desktop_secret(raw) == storage.DEFAULT_ADMIN_USERNAME
diff --git a/studio/backend/tests/test_password_prompt_backstop.py b/studio/backend/tests/test_password_prompt_backstop.py
index ef4179e5743..0bf2eb3d317 100644
--- a/studio/backend/tests/test_password_prompt_backstop.py
+++ b/studio/backend/tests/test_password_prompt_backstop.py
@@ -31,6 +31,16 @@ _GATE_KWARGS = dict(
)
[email protected](autouse = True)
+def _tunnel_available_by_default(monkeypatch):
+ # The headless auto-generate branch now consults the real cloudflared binary on
+ # the --secure path (a missing tunnel means no public URL, so rotating the only
+ # recovery password would strip it behind a droppable one-time banner). Default
+ # to "available" so the existing auto-generate tests never touch the network;
+ # the dedicated test below flips this to exercise the fail-closed refusal.
+ monkeypatch.setattr(run, "_tunnel_binary_confirmed_unavailable", lambda: False)
+
+
# ── pure decision matrix ─────────────────────────────────────────────
@@ -86,11 +96,24 @@ def _patch_streams(monkeypatch, *, tty: bool) -> _Stream:
return stderr
+def _patch_streams_autogen(monkeypatch) -> _Stream:
+ # The auto-generate branch fires when the interactive prompt is unavailable
+ # (stdin not a tty) but a real terminal still exists to surface the one-time
+ # credential on an EPHEMERAL console: stdin non-tty, stderr a tty. A fully
+ # redirected launch (stderr also non-tty) instead fails closed -- see
+ # test_gate_fails_closed_when_console_is_redirected_file.
+ stderr = _Stream(isatty = True)
+ monkeypatch.setattr(sys, "stdin", _Stream(isatty = False))
+ monkeypatch.setattr(sys, "stderr", stderr)
+ return stderr
+
+
def _patch_seeded_admin(monkeypatch, *, requires_change: bool) -> None:
# The gate seeds the admin row itself (it can run before lifespan startup);
# tests fake both the seeding no-op and the flag.
monkeypatch.setattr(auth_storage, "ensure_default_admin", lambda: False)
monkeypatch.setattr(auth_storage, "requires_password_change", lambda u: requires_change)
+ monkeypatch.setattr(auth_storage, "credential_undelivered", lambda u: False)
def test_gate_skips_when_tunnel_off(monkeypatch):
@@ -114,8 +137,32 @@ def test_gate_skips_when_password_already_changed(monkeypatch):
assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (True, False)
-def test_gate_warns_and_proceeds_without_tty_when_deadline_arms(monkeypatch):
- stderr = _patch_streams(monkeypatch, tty = False)
+def _stub_update_password(monkeypatch, *, committed: bool = True) -> list:
+ """Record update_password calls so the auto-generate path can be asserted
+ without touching the real auth DB.
+
+ Returns what the real function returns -- the rotated JWT secret on a write,
+ None when a guard rejected it -- so `committed = False` really does read as a
+ lost compare-and-set at the call site. A stub that returned the bool itself
+ would make the lost case look committed, since `False is not None`.
+ """
+ calls = []
+
+ def _update(u, p, **kw):
+ calls.append((u, p, kw))
+ return "rotated-secret" if committed else None
+
+ monkeypatch.setattr(auth_storage, "update_password", _update)
+ return calls
+
+
+def test_gate_autogenerates_password_on_tty_console(monkeypatch):
+ # No interactive prompt (stdin not a tty) and no supplied password, but a real
+ # terminal (stderr) is present to surface the credential ephemerally: the gate
+ # auto-generates a strong admin password, commits it (clearing must_change so
+ # the tunnel proceeds headlessly), and surfaces it once. The public HTML must
+ # still not auto-fill any stale bootstrap credential (drop_bootstrap True).
+ stderr = _patch_streams_autogen(monkeypatch)
_patch_seeded_admin(monkeypatch, requires_change = True)
monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
monkeypatch.setattr(
@@ -123,47 +170,397 @@ def test_gate_warns_and_proceeds_without_tty_when_deadline_arms(monkeypatch):
"prompt_for_password_change",
lambda **k: pytest.fail("prompt must not run without a tty"),
)
- # Proceeds, but the public HTML must not auto-fill the default credential.
+ calls = _stub_update_password(monkeypatch)
+ assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (True, True)
+ admin = auth_storage.DEFAULT_ADMIN_USERNAME
+ # Committed via the route-equivalent atomic update (refresh tokens revoked in
+ # the same transaction).
+ assert len(calls) == 1, calls
+ username, password, kwargs = calls[0]
+ assert username == admin
+ assert isinstance(password, str) and len(password) >= auth_storage.MIN_PASSWORD_LENGTH
+ # Compare-and-set: the write lands only while must_change_password is still 1,
+ # so a password chosen elsewhere in the meantime is never overwritten.
+ assert kwargs == {
+ "revoke_refresh_tokens": True,
+ "require_must_change": True,
+ "mark_credential_undelivered": True,
+ }
+ out = stderr.getvalue()
+ assert "auto-generated" in out
+ assert admin in out
+ assert password in out # the credential is printed exactly once
+
+
+def test_gate_autogenerated_credential_stays_out_of_session_log(monkeypatch):
+ # run_server() installs a _TeeStream over sys.stderr (see
+ # _setup_server_disk_logging) that mirrors everything into a RETAINED
+ # logs/server/server-*.log. The one-time auto-generated admin password must
+ # reach the operator's console but must NEVER land in that persisted log
+ # (OWASP CWE-532: no credentials in log files). The gate writes it to the raw
+ # stream behind the tee, so the log copy stays clean.
+ console = _Stream(isatty = True)
+ log_fh = io.StringIO()
+ tee = run._TeeStream(console, log_fh)
+ monkeypatch.setattr(sys, "stdin", _Stream(isatty = False))
+ monkeypatch.setattr(sys, "stderr", tee)
+ _patch_seeded_admin(monkeypatch, requires_change = True)
+ monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
+ calls = _stub_update_password(monkeypatch)
+
+ assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (True, True)
+ assert len(calls) == 1, calls
+ _username, password, _kwargs = calls[0]
+
+ console_out = console.getvalue()
+ log_out = log_fh.getvalue()
+ # The operator sees the banner and the credential on the console...
+ assert "auto-generated" in console_out
+ assert password in console_out
+ # ...but nothing was mirrored into the retained on-disk session log.
+ assert password not in log_out
+ assert "auto-generated" not in log_out
+
+
+def test_console_only_stream_unwraps_tee():
+ # Unit: _console_only_stream returns the raw stream behind a _TeeStream and is
+ # a no-op for a plain stream, so a secret written through it never reaches the
+ # log file handle the tee mirrors into.
+ console = io.StringIO()
+ log_fh = io.StringIO()
+ tee = run._TeeStream(console, log_fh)
+ assert run._console_only_stream(tee) is console
+ plain = io.StringIO()
+ assert run._console_only_stream(plain) is plain
+
+
+def test_console_only_stream_unwraps_nested_tees(monkeypatch):
+ # run_server() can run twice in one process (a local run, then a public one),
+ # and each call re-wraps the already-wrapped sys.stdout/stderr, so the tees
+ # nest. Peeling a single layer returned the INNER _TeeStream -- which forwards
+ # isatty() to the console and so passes the tty check -- and the one-time
+ # credential was mirrored into the first run's retained server-*.log
+ # (CWE-532). Every layer must be unwrapped.
+ console = _Stream(isatty = True)
+ first_log, second_log = io.StringIO(), io.StringIO()
+ nested = run._TeeStream(run._TeeStream(console, first_log), second_log)
+ assert run._console_only_stream(nested) is console
+
+ # End to end: the secret reaches the console and neither retained log.
+ monkeypatch.setattr(sys, "stderr", nested)
+ monkeypatch.setattr(sys, "stdout", nested)
+ out = run._one_time_secret_stream()
+ assert out is console
+ run._print_auto_generated_credentials("unsloth", "Nested-Tee-Pw-1", out = out)
+ assert "Nested-Tee-Pw-1" in console.getvalue()
+ assert "Nested-Tee-Pw-1" not in first_log.getvalue()
+ assert "Nested-Tee-Pw-1" not in second_log.getvalue()
+
+
+def test_gate_does_not_show_password_when_rotation_loses_the_race(monkeypatch):
+ # Another Studio process/tab sharing this auth DB can finish /change-password
+ # between the gate's must_change read and the rotation. The guarded update then
+ # writes nothing, so the generated value never took effect: it must not be
+ # displayed (it would not authenticate), and the launch proceeds under the
+ # password that did land.
+ stderr = _patch_streams_autogen(monkeypatch)
+ _patch_seeded_admin(monkeypatch, requires_change = True)
+ monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
+ calls = _stub_update_password(monkeypatch, committed = False)
+
assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (True, True)
+
+ assert len(calls) == 1, calls
+ _username, password, kwargs = calls[0]
+ assert kwargs["require_must_change"] is True
out = stderr.getvalue()
- assert "default admin password is still active" in out
- assert "UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT" in out
- # The seeded file may already be gone (the CLI parent deletes it before
- # re-exec), so the warning must point at the reset-password recovery path
- # instead of promising a file to read.
- assert "reset-password" in out
- assert ".bootstrap_password" not in out
-
-
-def test_gate_fails_closed_without_tty_when_deadline_cannot_arm(monkeypatch):
- # api-only launches never arm the bootstrap deadline, so a headless public
- # launch with the default password has NO safeguard: refuse to start.
- stderr = _patch_streams(monkeypatch, tty = False)
+ assert password not in out
+ assert "auto-generated" not in out
+
+
+def test_gate_fails_closed_when_rotation_loses_to_an_undelivered_auto_launch(monkeypatch):
+ stderr = _patch_streams_autogen(monkeypatch)
_patch_seeded_admin(monkeypatch, requires_change = True)
monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
+ calls = _stub_update_password(monkeypatch, committed = False)
+ marker_checks = iter((False, True))
+ monkeypatch.setattr(
+ auth_storage,
+ "credential_undelivered",
+ lambda _username: next(marker_checks),
+ )
+
+ assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (
+ False,
+ False,
+ )
+
+ assert len(calls) == 1
+ generated = calls[0][1]
+ assert generated not in stderr.getvalue()
+
+
+def test_gate_autogenerates_even_when_deadline_cannot_arm(monkeypatch):
+ # api-only launches never armed the bootstrap deadline and used to fail closed;
+ # now a strong password is set instead, so the launch proceeds with real
+ # protection rather than being refused.
+ _patch_streams_autogen(monkeypatch)
+ _patch_seeded_admin(monkeypatch, requires_change = True)
+ monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
+ calls = _stub_update_password(monkeypatch)
kwargs = dict(_GATE_KWARGS)
kwargs["api_only"] = True
kwargs["frontend_served"] = False
- assert run._terminal_password_gate(tunnel_will_start = True, **kwargs) == (False, False)
- assert "Refusing to publish" in stderr.getvalue()
+ assert run._terminal_password_gate(tunnel_will_start = True, **kwargs) == (True, True)
+ assert len(calls) == 1, calls
-def test_gate_fails_closed_without_tty_when_deadline_disabled(monkeypatch):
- stderr = _patch_streams(monkeypatch, tty = False)
+def test_gate_autogenerates_when_deadline_disabled(monkeypatch):
+ # UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT=0 disables the deadline; the auto-generated
+ # password is the safeguard now, so the launch still proceeds.
+ _patch_streams_autogen(monkeypatch)
_patch_seeded_admin(monkeypatch, requires_change = True)
monkeypatch.setenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", "0")
+ calls = _stub_update_password(monkeypatch)
+ assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (True, True)
+ assert len(calls) == 1, calls
+
+
+def test_gate_refuses_secure_when_tunnel_binary_unavailable(monkeypatch):
+ # --secure exposes ONLY the loopback-bound tunnel. When cloudflared is provably
+ # unavailable no public URL can come up, so the gate must NOT rotate the seeded
+ # recovery password (which a headless launch may only surface on a droppable
+ # one-time banner, locking the operator out). Mirrors the CLI: fail closed with
+ # the credential untouched, matching run_server's later secure-tunnel guard.
+ stderr = _patch_streams_autogen(monkeypatch)
+ _patch_seeded_admin(monkeypatch, requires_change = True)
+ monkeypatch.setattr(run, "_tunnel_binary_confirmed_unavailable", lambda: True)
+ calls = _stub_update_password(monkeypatch)
+ assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (False, False)
+ # No rotation happened: the existing recovery credential is intact.
+ assert calls == []
+ # And nothing that looks like a credential was surfaced.
+ assert "auto-generated" not in stderr.getvalue()
+
+
+def test_gate_non_secure_still_rotates_when_tunnel_unavailable(monkeypatch):
+ # A --cloudflare wildcard bind (NOT --secure) still serves the raw 0.0.0.0 port
+ # even if the tunnel fails, so the default credential must be replaced: the
+ # tunnel-availability refusal is scoped to --secure only.
+ _patch_streams_autogen(monkeypatch)
+ _patch_seeded_admin(monkeypatch, requires_change = True)
+ monkeypatch.setattr(run, "_tunnel_binary_confirmed_unavailable", lambda: True)
+ monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
+ calls = _stub_update_password(monkeypatch)
+ kwargs = dict(_GATE_KWARGS)
+ kwargs["secure"] = False
+ kwargs["host"] = "0.0.0.0"
+ assert run._terminal_password_gate(tunnel_will_start = True, **kwargs) == (True, True)
+ assert len(calls) == 1, calls
+
+
+def test_gate_credential_falls_back_to_stdout_when_stderr_absent(monkeypatch):
+ # A GUI/service wrapper can leave sys.stderr's raw stream absent (None) while
+ # _setup_server_disk_logging() still tees sys.stdout into a retained log. The
+ # one-time credential must fall back to the raw console behind the stdout tee,
+ # NEVER to print(file=None) which would write it into that log (CWE-532).
+ log_fh = io.StringIO()
+ stderr_tee = run._TeeStream(None, log_fh) # raw console absent behind the tee
+ console = _Stream(isatty = True)
+ stdout_tee = run._TeeStream(console, log_fh)
+ monkeypatch.setattr(sys, "stdin", _Stream(isatty = False))
+ monkeypatch.setattr(sys, "stderr", stderr_tee)
+ monkeypatch.setattr(sys, "stdout", stdout_tee)
+ _patch_seeded_admin(monkeypatch, requires_change = True)
+ monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
+ calls = _stub_update_password(monkeypatch)
+
+ assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (True, True)
+ assert len(calls) == 1, calls
+ _username, password, _kwargs = calls[0]
+ # Surfaced on the real console (behind the stdout tee)...
+ assert password in console.getvalue()
+ assert "auto-generated" in console.getvalue()
+ # ...but never mirrored into the retained on-disk session log.
+ assert password not in log_fh.getvalue()
+ assert "auto-generated" not in log_fh.getvalue()
+
+
+def test_gate_fails_closed_when_no_console_stream(monkeypatch):
+ # A Windows pythonw/service wrapper can leave BOTH sys.stderr and sys.stdout
+ # absent (None) even while a session log is tee'd. There is then no real console
+ # to surface the one-time credential without persisting it, so the gate must
+ # fail closed WITHOUT rotating the only recovery credential -- rather than let
+ # print(file=None) fall back to the tee'd stdout and write it to disk.
+ log_fh = io.StringIO()
+ monkeypatch.setattr(sys, "stdin", _Stream(isatty = False))
+ monkeypatch.setattr(sys, "stderr", run._TeeStream(None, log_fh))
+ monkeypatch.setattr(sys, "stdout", run._TeeStream(None, log_fh))
+ _patch_seeded_admin(monkeypatch, requires_change = True)
+ monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
+ calls = _stub_update_password(monkeypatch)
+
+ assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (False, False)
+ # No rotation, and nothing written into the retained on-disk session log.
+ assert calls == []
+ assert log_fh.getvalue() == ""
+
+
+def test_one_time_secret_stream_prefers_stderr_then_stdout():
+ # Unit: prefer stderr, fall back to stdout, unwrap the tee, None when neither
+ # has a usable raw stream. The real console behind the tee must be a tty -- only
+ # a terminal is an ephemeral surface for the one-time secret.
+ real_err, real_out, log = _Stream(isatty = True), _Stream(isatty = True), io.StringIO()
+ import contextlib
+
+ @contextlib.contextmanager
+ def _streams(stderr, stdout):
+ old_err, old_out = sys.stderr, sys.stdout
+ sys.stderr, sys.stdout = stderr, stdout
+ try:
+ yield
+ finally:
+ sys.stderr, sys.stdout = old_err, old_out
+
+ with _streams(run._TeeStream(real_err, log), run._TeeStream(real_out, log)):
+ assert run._one_time_secret_stream() is real_err # stderr wins
+ with _streams(run._TeeStream(None, log), run._TeeStream(real_out, log)):
+ assert run._one_time_secret_stream() is real_out # falls back past absent stderr
+ with _streams(run._TeeStream(None, log), run._TeeStream(None, log)):
+ assert run._one_time_secret_stream() is None # no real console anywhere
+
+
+def test_one_time_secret_stream_skips_closed_and_nonwritable(monkeypatch):
+ # A headless launch can inherit a stderr/stdout whose raw stream is a CLOSED
+ # or non-writable stream (not None). Printing the one-time credential to it
+ # raises ValueError -- but only AFTER _auto_generate_admin_password already
+ # rotated the seeded recovery credential, locking the operator out. The stream
+ # selector must treat such streams as unusable and skip them, mirroring the CLI
+ # _one_time_secret_console_stream closed/writable preflight.
+ log = io.StringIO()
+
+ class _NonWritable:
+ closed = False
+ write = None # not callable -> unusable
+
+ def isatty(self):
+ return True
+
+ closed_err = io.StringIO()
+ closed_err.close()
+ real_out = _Stream(isatty = True)
+
+ # A closed raw stderr behind the tee is skipped; falls back to the usable stdout.
+ monkeypatch.setattr(sys, "stderr", run._TeeStream(closed_err, log))
+ monkeypatch.setattr(sys, "stdout", run._TeeStream(real_out, log))
+ assert run._one_time_secret_stream() is real_out
+
+ # A non-writable raw stderr is skipped too.
+ monkeypatch.setattr(sys, "stderr", run._TeeStream(_NonWritable(), log))
+ monkeypatch.setattr(sys, "stdout", run._TeeStream(real_out, log))
+ assert run._one_time_secret_stream() is real_out
+
+ # Closed on both -> no usable console anywhere -> None (caller fails closed).
+ closed_out = io.StringIO()
+ closed_out.close()
+ monkeypatch.setattr(sys, "stderr", run._TeeStream(closed_err, log))
+ monkeypatch.setattr(sys, "stdout", run._TeeStream(closed_out, log))
+ assert run._one_time_secret_stream() is None
+
+
+def test_one_time_secret_stream_requires_tty(monkeypatch):
+ # A headless launch with stderr/stdout redirected to a file (`> log 2>&1`),
+ # nohup.out, or a systemd-journald socket inherits a stream that is open and
+ # writable but NOT a tty. Writing the one-time credential there PERSISTS the
+ # plaintext (CWE-532), breaking the banner's "not written to disk" promise, so
+ # the selector must skip a non-tty stream and prefer a real terminal.
+ log = io.StringIO()
+ redirected_err = _Stream(isatty = False) # e.g. `> server.log 2>&1`
+ tty_out = _Stream(isatty = True)
+
+ # A non-tty (redirected) stderr is skipped; falls back to the tty stdout.
+ monkeypatch.setattr(sys, "stderr", run._TeeStream(redirected_err, log))
+ monkeypatch.setattr(sys, "stdout", run._TeeStream(tty_out, log))
+ assert run._one_time_secret_stream() is tty_out
+
+ # Both streams redirected (fully headless) -> no ephemeral surface -> None, so
+ # the caller fails closed rather than persist the credential.
+ monkeypatch.setattr(sys, "stderr", run._TeeStream(_Stream(isatty = False), log))
+ monkeypatch.setattr(sys, "stdout", run._TeeStream(_Stream(isatty = False), log))
+ assert run._one_time_secret_stream() is None
+
+
+def test_one_time_secret_stream_falls_back_when_isatty_raises_oserror(monkeypatch):
+ """A detached PTY is unusable, but must not hide a healthy second console."""
+ log = io.StringIO()
+
+ class _DetachedPty(_Stream):
+ def isatty(self):
+ raise OSError(5, "Input/output error")
+
+ tty_out = _Stream(isatty = True)
+ monkeypatch.setattr(sys, "stderr", run._TeeStream(_DetachedPty(isatty = True), log))
+ monkeypatch.setattr(sys, "stdout", run._TeeStream(tty_out, log))
+
+ assert run._one_time_secret_stream() is tty_out
+
+
+def test_gate_fails_closed_when_console_is_redirected_file(monkeypatch):
+ # Regression (Codex 3644549779, P1): a headless `python run.py --secure` with
+ # stderr/stdout redirected to a file/journal (nohup, systemd, `> log 2>&1`) has
+ # a writable but non-tty console. Auto-generating there would write the admin
+ # password into that RETAINED file, leaking the only credential to log consumers
+ # despite the no-persistence guarantee. The gate must fail closed WITHOUT
+ # rotating -- the operator supplies --password for a truly headless launch.
+ redirected = _Stream(isatty = False) # simulates `> server.log 2>&1`
+ monkeypatch.setattr(sys, "stdin", _Stream(isatty = False))
+ monkeypatch.setattr(sys, "stderr", redirected)
+ monkeypatch.setattr(sys, "stdout", _Stream(isatty = False))
+ _patch_seeded_admin(monkeypatch, requires_change = True)
+ monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
+ calls = _stub_update_password(monkeypatch)
+
assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (False, False)
- assert "Refusing to publish" in stderr.getvalue()
+ # No rotation, and nothing that looks like a credential written to the file.
+ assert calls == []
+ assert "auto-generated" not in redirected.getvalue()
+
+
+def test_gate_fails_closed_when_console_stream_closed(monkeypatch):
+ # Regression: a headless `python run.py --secure` launch whose raw stderr is a
+ # CLOSED stream (and stdout absent) must NOT rotate the seeded recovery
+ # credential. Previously _one_time_secret_stream only checked for None, so it
+ # returned the closed stream; the gate committed the generated password (clearing
+ # the bootstrap credential) and then _print_auto_generated_credentials raised
+ # ValueError on the closed stream, so the operator never received the only new
+ # password and was locked out. It must fail closed WITHOUT rotating.
+ log_fh = io.StringIO()
+ closed_err = io.StringIO()
+ closed_err.close()
+ monkeypatch.setattr(sys, "stdin", _Stream(isatty = False))
+ monkeypatch.setattr(sys, "stderr", run._TeeStream(closed_err, log_fh))
+ monkeypatch.setattr(sys, "stdout", run._TeeStream(None, log_fh))
+ _patch_seeded_admin(monkeypatch, requires_change = True)
+ monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
+ calls = _stub_update_password(monkeypatch)
+
+ assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (False, False)
+ # No rotation, and nothing written into the retained on-disk session log.
+ assert calls == []
+ assert log_fh.getvalue() == ""
def test_gate_treats_broken_streams_as_non_interactive(monkeypatch):
- # A closed/None stdin must take the headless path, not blow up.
- stderr = _Stream(isatty = False)
+ # A closed/None stdin must take the headless path (auto-generate), not blow up.
+ # stderr is a real terminal, so the one-time credential is surfaced ephemerally.
+ stderr = _Stream(isatty = True)
monkeypatch.setattr(sys, "stdin", _BrokenStream())
monkeypatch.setattr(sys, "stderr", stderr)
_patch_seeded_admin(monkeypatch, requires_change = True)
monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
+ calls = _stub_update_password(monkeypatch)
assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (True, True)
+ assert len(calls) == 1, calls
def test_gate_refusal_fails_closed(monkeypatch):
@@ -409,3 +806,237 @@ def test_apply_supplied_password_strips_env_even_when_literal_wins(monkeypatch):
monkeypatch.setenv(terminal_prompt.SUPPLIED_PASSWORD_ENV, "env-should-be-stripped")
run._apply_supplied_password("literal-new-password")
assert terminal_prompt.SUPPLIED_PASSWORD_ENV not in run.os.environ
+
+
+# ── partial-success recovery on the direct-server path ───────────────
+
+
+def real_auth_db(tmp_path, monkeypatch):
+ """Point auth storage at a throwaway DB for the tests that need the REAL
+ update_password commit (the stubs above never touch SQLite)."""
+ monkeypatch.setattr(auth_storage, "DB_PATH", tmp_path / "auth.db")
+ monkeypatch.setattr(auth_storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")
+ monkeypatch.setattr(auth_storage, "_bootstrap_password", None)
+ monkeypatch.setattr(auth_storage, "_api_key_pbkdf2_salt_cache", None)
+ return tmp_path
+
+
+def _seed_real_admin(*, must_change_password: bool = True) -> str:
+ import secrets as _secrets
+ auth_storage.create_initial_user(
+ username = auth_storage.DEFAULT_ADMIN_USERNAME,
+ password = "bootstrap-secret-123",
+ jwt_secret = _secrets.token_urlsafe(64),
+ must_change_password = must_change_password,
+ )
+ return auth_storage.DEFAULT_ADMIN_USERNAME
+
+
+def _commit_then_raise(monkeypatch, exc: Exception) -> None:
+ """Make update_password commit for real and only then raise, reproducing a
+ failure in the post-commit cleanup that runs outside the transaction."""
+ real_update = auth_storage.update_password
+
+ def _update(username, new_password, **kwargs):
+ real_update(username, new_password, **kwargs)
+ raise exc
+
+ monkeypatch.setattr(auth_storage, "update_password", _update)
+
+
+def test_auto_generate_keeps_credential_when_post_commit_cleanup_raises(real_auth_db, monkeypatch):
+ # update_password commits the row BEFORE its best-effort bootstrap-file
+ # cleanup, so a raise there leaves the generated password live while the
+ # seeded recovery credential is already gone. Discarding it (the exception
+ # used to propagate out of the gate) aborted the launch behind a password
+ # nobody had ever seen -- an unrecoverable lockout. Resolve the partial
+ # success against the stored hash instead, as the Colab path does.
+ admin = _seed_real_admin()
+ _commit_then_raise(monkeypatch, OSError("database is locked"))
+ console = _Stream(isatty = True)
+
+ generated = run._auto_generate_admin_password(admin, out = console)
+
+ assert isinstance(generated, str) and generated
+ from auth import hashing as _hashing
+
+ salt, pwd_hash, _jwt, _mc = auth_storage.get_user_and_secret(admin)
+ # The returned value is exactly the one that landed, so the banner shows a
+ # password that actually authenticates.
+ assert _hashing.verify_password(generated, salt, pwd_hash) is True
+ assert auth_storage.requires_password_change(admin) is False
+ notice = console.getvalue()
+ assert "reported an error" in notice
+ assert generated not in notice # the notice never repeats the credential
+
+
+def test_auto_generate_reraises_when_the_commit_itself_fails(real_auth_db, monkeypatch):
+ # The converse: nothing was committed, so the seeded credential is still the
+ # live one. Returning None here would tell the gate "someone else set a
+ # password" and publish the tunnel; re-raise so the launch fails closed.
+ admin = _seed_real_admin()
+
+ def _explode(username, new_password, **kwargs):
+ raise OSError("database is locked")
+
+ monkeypatch.setattr(auth_storage, "update_password", _explode)
+
+ with pytest.raises(OSError):
+ run._auto_generate_admin_password(admin)
+ assert auth_storage.requires_password_change(admin) is True
+ from auth import hashing as _hashing
+
+ salt, pwd_hash, _jwt, _mc = auth_storage.get_user_and_secret(admin)
+ assert _hashing.verify_password("bootstrap-secret-123", salt, pwd_hash) is True
+
+
+def test_auto_generate_returns_none_when_the_compare_and_set_loses(real_auth_db, monkeypatch):
+ # No exception, just a lost CAS (another tab completed /change-password): the
+ # generated value was never written, so it must not be shown.
+ admin = _seed_real_admin(must_change_password = False)
+ assert run._auto_generate_admin_password(admin) is None
+
+
+def test_gate_rechecks_delivery_marker_after_password_state_race(real_auth_db, monkeypatch):
+ # Another headless launcher can commit its generated password and pending-
+ # delivery marker after this gate's first marker read but before its password
+ # state read. The already-set fast path must observe that marker and refuse.
+ admin = _seed_real_admin()
+ real_requires_password_change = auth_storage.requires_password_change
+
+ def _race_with_winning_launcher(username):
+ assert auth_storage.update_password(
+ username,
+ "concurrent-generated-password",
+ revoke_refresh_tokens = True,
+ require_must_change = True,
+ mark_credential_undelivered = True,
+ )
+ return real_requires_password_change(username)
+
+ monkeypatch.setattr(
+ auth_storage,
+ "requires_password_change",
+ _race_with_winning_launcher,
+ )
+
+ assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (
+ False,
+ False,
+ )
+ assert auth_storage.credential_undelivered(admin) is True
+
+
+def test_gate_surfaces_the_password_when_post_commit_cleanup_raises(real_auth_db, monkeypatch):
+ # End to end on the direct `python run.py --secure` path: the gate must still
+ # proceed and print the live credential instead of aborting after the rotation.
+ _seed_real_admin()
+ stderr = _patch_streams_autogen(monkeypatch)
+ monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
+ _commit_then_raise(monkeypatch, OSError("database is locked"))
+
+ assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (True, True)
+
+ admin = auth_storage.DEFAULT_ADMIN_USERNAME
+ out = stderr.getvalue()
+ assert "auto-generated" in out
+ printed = re.search(r"Password: (\S+)", out)
+ assert printed is not None, out
+ from auth import hashing as _hashing
+
+ salt, pwd_hash, _jwt, _mc = auth_storage.get_user_and_secret(admin)
+ assert _hashing.verify_password(printed.group(1), salt, pwd_hash) is True
+
+
+def test_gate_aborts_when_the_rotation_never_landed(real_auth_db, monkeypatch):
+ # Same shape, but the commit failed outright: the gate must not swallow it and
+ # publish under the seeded credential.
+ admin = _seed_real_admin()
+ _patch_streams_autogen(monkeypatch)
+ monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
+
+ def _explode(username, new_password, **kwargs):
+ raise OSError("database is locked")
+
+ monkeypatch.setattr(auth_storage, "update_password", _explode)
+
+ with pytest.raises(OSError):
+ run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS)
+ assert auth_storage.requires_password_change(admin) is True
+
+
+class _DyingStream(_Stream):
+ """A terminal that passes the preflight and then raises on write.
+
+ Models the console going away between _one_time_secret_stream()'s checks and
+ the post-commit banner: an SSH session that drops, or a closed terminal window
+ whose orphaned pty fails writes with OSError EIO.
+ """
+
+ def __init__(self, isatty: bool = True):
+ super().__init__(isatty = isatty)
+ self.writes = 0
+
+ def write(self, data):
+ self.writes += 1
+ raise OSError(5, "Input/output error")
+
+
+def test_delivery_retries_the_other_console_when_the_first_write_dies(monkeypatch):
+ # Regression (Codex 3651035060, P2): the banner is written AFTER
+ # update_password committed the generated password and deleted the seeded
+ # bootstrap credential, so a write failure there used to propagate and abort
+ # the launch with a live password nobody had ever seen. Retry the other real
+ # terminal instead of losing the only copy.
+ dying = _DyingStream()
+ alive = _Stream(isatty = True)
+ monkeypatch.setattr(sys, "stderr", dying)
+ monkeypatch.setattr(sys, "stdout", alive)
+
+ assert run._deliver_one_time_credential("unsloth", "Retry-Console-Pw-1", out = dying) is True
+ assert dying.writes >= 1 # the dead console was tried first
+ assert "Retry-Console-Pw-1" in alive.getvalue()
+
+
+def test_delivery_never_falls_back_to_a_tee_or_a_redirected_stream(monkeypatch):
+ # The retry must not downgrade the surface: the only other candidates here are
+ # a tee'd session log (retained on disk) and a redirected non-tty file, both of
+ # which would PERSIST the plaintext (CWE-532). Report failure instead.
+ log_fh = io.StringIO()
+ dying = _DyingStream()
+ redirected = _Stream(isatty = False) # `> server.log`
+ monkeypatch.setattr(sys, "stderr", run._TeeStream(dying, log_fh))
+ monkeypatch.setattr(sys, "stdout", run._TeeStream(redirected, log_fh))
+
+ assert run._deliver_one_time_credential("unsloth", "No-Tee-Pw-2", out = dying) is False
+ assert log_fh.getvalue() == ""
+ assert redirected.getvalue() == ""
+
+
+def test_gate_fails_closed_when_the_credential_cannot_be_delivered(real_auth_db, monkeypatch):
+ # End to end: every console dies after the preflight. The gate must not raise
+ # (an unhandled OSError aborted startup with an opaque traceback); it fails
+ # closed with a secret-free message so the operator knows to run
+ # `unsloth studio reset-password`.
+ admin = _seed_real_admin()
+ monkeypatch.setattr(sys, "stdin", _Stream(isatty = False))
+ monkeypatch.setattr(sys, "stderr", _DyingStream())
+ monkeypatch.setattr(sys, "stdout", _DyingStream())
+ monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
+ logged: list[str] = []
+ monkeypatch.setattr(run.logger, "error", lambda msg, *a, **k: logged.append(str(msg)))
+
+ assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (False, False)
+
+ assert logged and "reset-password" in logged[0]
+ # The message names no credential: it is written through the logger, which the
+ # session-log tee persists.
+ assert "Password:" not in logged[0]
+ assert auth_storage.credential_undelivered(admin) is True
+ # A retry refuses before touching either dead console because the pending
+ # state committed atomically with the generated password.
+ assert run._terminal_password_gate(tunnel_will_start = True, **_GATE_KWARGS) == (
+ False,
+ False,
+ )
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 884807e0a48..2c2140e67ef 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -153,6 +153,7 @@ DESKTOP_SECRET_PREFIX = "desktop-"
API_KEY_PBKDF2_SALT_KEY = "api_key_pbkdf2_salt"
DESKTOP_SECRET_HASH_KEY = "desktop_secret_hash"
DESKTOP_SECRET_CREATED_AT_KEY = "desktop_secret_created_at"
+CREDENTIAL_UNDELIVERED_PASSWORD_HASH_KEY = "credential_undelivered_password_hash"
PBKDF2_ITERATIONS = 100_000
_START_API_KEY_MARKER_ENV = "_UNSLOTH_START_API_KEY_MARKER"
_CLOUDFLARE_INTENT_ENV = "_UNSLOTH_CLOUDFLARE_INTENT"
@@ -1169,24 +1170,86 @@ def _prompt_streams_interactive() -> bool:
"""The prompt needs a real terminal for input and for the masked echo."""
try:
return sys.stdin.isatty() and sys.stderr.isatty()
- except (AttributeError, ValueError):
+ except (AttributeError, OSError, ValueError):
return False
-def _bootstrap_deadline_active() -> bool:
- """Whether the backend's bootstrap shutdown deadline will arm.
+def _clear_credential_undelivered(conn: sqlite3.Connection) -> None:
+ """Clear the durable delivery guard in its own transaction."""
+ with conn:
+ conn.execute(
+ "DELETE FROM app_secrets WHERE key = ?",
+ (CREDENTIAL_UNDELIVERED_PASSWORD_HASH_KEY,),
+ )
- Mirror of studio/backend/auth/bootstrap_timeout.py bootstrap_timeout_seconds:
- unset/blank/malformed UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT falls back to the 1h
- default (a typo must not remove protection); 0 or negative disables it.
+
+def _credential_undelivered(conn: sqlite3.Connection) -> bool:
+ """True when the current password's hash belongs to a password never shown.
+
+ Matching on the hash (not mere existence) is what makes this self-healing:
+ `unsloth studio reset-password` rewrites the row and atomically clears the
+ pending state. A stale value is removed rather than refusing a launch
+ unprovably.
"""
- raw = os.environ.get("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", "").strip()
- if not raw:
- return True
- try:
- return int(raw) > 0
- except ValueError:
+ row = conn.execute(
+ """
+ SELECT s.value,
+ (SELECT password_hash FROM auth_user WHERE username = ?)
+ FROM app_secrets AS s
+ WHERE s.key = ?
+ """,
+ (DEFAULT_ADMIN_USERNAME, CREDENTIAL_UNDELIVERED_PASSWORD_HASH_KEY),
+ ).fetchone()
+ if row is None:
+ return False
+ recorded, current_hash = row
+ if recorded and current_hash and hmac.compare_digest(recorded, current_hash):
return True
+ # Delete only the observed value, preserving any concurrent launcher's guard.
+ with conn:
+ conn.execute(
+ "DELETE FROM app_secrets WHERE key = ? AND value = ?",
+ (CREDENTIAL_UNDELIVERED_PASSWORD_HASH_KEY, recorded),
+ )
+ return False
+
+
+def _one_time_secret_console_stream(*, skip = None):
+ """Return an interactive-terminal stream to surface a one-time secret, or None.
+
+ Mirrors run.py's ``_one_time_secret_stream`` fail-closed contract for the CLI
+ parent: the auto-generated admin password must reach the operator's terminal
+ BEFORE we rotate away the seeded bootstrap credential. Prefers stderr, then
+ stdout, and requires a real TTY. A writable non-tty stream -- a ``> file``
+ redirect, nohup.out, a systemd-journald pipe -- is NOT an ephemeral console:
+ surfacing the credential there PERSISTS the plaintext where log consumers can
+ read it (CWE-532), so it is skipped. Returns None when neither stream is a
+ usable TTY -- a Windows pythonw/service wrapper (both absent), a closed stream,
+ or a headless (nohup/systemd) launch with redirected output -- in which case
+ the caller fails closed rather than rotate away and lose (or leak) the only
+ credential. The CLI parent has no session-log tee, so no _TeeStream unwrapping
+ is needed here.
+
+ *skip* excludes an already-resolved console so a delivery that RAISED on it can
+ retry the other one (see _deliver_auto_generated_credentials). The remaining
+ candidate still has to pass every check above, so the retry cannot downgrade to
+ a redirected, non-tty surface.
+ """
+ for candidate in (sys.stderr, sys.stdout):
+ try:
+ if candidate is None or getattr(candidate, "closed", False):
+ continue
+ if skip is not None and candidate is skip:
+ continue
+ if not callable(getattr(candidate, "write", None)):
+ continue
+ # Reject redirected streams that would persist the credential (CWE-532).
+ if not candidate.isatty():
+ continue
+ except (AttributeError, OSError, ValueError):
+ continue
+ return candidate
+ return None
def _generate_reset_password() -> str:
@@ -1206,24 +1269,56 @@ def _cli_update_password(
new_password: str,
*,
revoke_api_keys: bool = False,
-) -> None:
+ require_must_change: bool = False,
+ mark_credential_undelivered: bool = False,
+) -> bool:
"""CLI mirror of backend update_password + change-password route effects.
One transaction: rehash, rotate the JWT secret, clear must_change_password,
- revoke refresh tokens (PR #6651 finding), drop the desktop secret, and (for a
- reset) the API keys the old credential could have minted. File cleanup happens
- after commit; a failed unlink must not roll the change back.
+ persist or clear the undelivered-credential guard, revoke refresh tokens
+ (PR #6651 finding), revoke outstanding one-time link tokens, drop the desktop
+ secret, and (for a reset) the API keys the old credential could have minted.
+ File cleanup happens after commit; a failed unlink must not roll the change
+ back. Returns whether the row was written.
+
+ ``require_must_change`` makes it a compare-and-set on must_change_password,
+ mirroring backend storage.update_password: an auto-generated launch credential
+ must not overwrite a password a user chose in a Studio tab between the
+ must_change read and this write. Returns False when that guard rejects the
+ update, and then NOTHING else is revoked -- the password that won the race
+ belongs to another writer, and its sessions, link tokens, desktop secret and
+ API keys are not ours to destroy. That is why the early return sits above
+ ``if revoke_api_keys:`` in particular: that DELETE has no WHERE clause and
+ would wipe every key for every user while leaving the password as the winner
+ set it. The guard stays spelled ``require_must_change and rowcount == 0``
+ rather than a bare rowcount check, because the unguarded callers
+ (``reset_password``, ``_apply_supplied_password_before_launch``) rely on the
+ revocations running even when the UPDATE matches nothing, e.g. a renamed
+ admin row.
"""
password_salt, password_hash = _hash_password(new_password)
+ guard = " AND must_change_password = 1" if require_must_change else ""
with conn:
- conn.execute(
- """
+ cursor = conn.execute(
+ f"""
UPDATE auth_user
SET password_salt = ?, password_hash = ?, jwt_secret = ?, must_change_password = 0
- WHERE username = ?
+ WHERE username = ?{guard}
""",
(password_salt, password_hash, secrets.token_urlsafe(64), username),
)
+ if require_must_change and cursor.rowcount == 0:
+ return False
+ if mark_credential_undelivered:
+ conn.execute(
+ "INSERT OR REPLACE INTO app_secrets (key, value) VALUES (?, ?)",
+ (CREDENTIAL_UNDELIVERED_PASSWORD_HASH_KEY, password_hash),
+ )
+ else:
+ conn.execute(
+ "DELETE FROM app_secrets WHERE key = ?",
+ (CREDENTIAL_UNDELIVERED_PASSWORD_HASH_KEY,),
+ )
conn.execute("DELETE FROM refresh_tokens WHERE username = ?", (username,))
conn.execute(
"DELETE FROM app_secrets WHERE key IN (?, ?)",
@@ -1248,18 +1343,102 @@ def _cli_update_password(
except OSError:
cleared = False
if cleared:
- typer.echo(
+ warning = (
f"Warning: could not remove stale {stale} file ({exc}); cleared its "
- "contents so the old credential cannot be reused.",
- err = True,
+ "contents so the old credential cannot be reused."
)
else:
- typer.echo(
+ warning = (
f"Warning: could not remove or clear stale {stale} file ({exc}); the "
"old credential is still on disk. Remove it manually to prevent reuse "
- "after a reset.",
+ "after a reset."
+ )
+ try:
+ typer.echo(
+ warning,
err = True,
)
+ except Exception:
+ # Warning failure must not prevent delivery on the other console.
+ pass
+ return True
+
+
+def _echo_auto_generated_credentials(
+ username: str,
+ password: str,
+ *,
+ out = None,
+) -> None:
+ """Surface an auto-generated admin credential once, on the parent's console.
+
+ Writes to the pre-resolved *out* stream (the one the caller verified was usable
+ before it rotated the seeded recovery password) so the credential lands on the
+ exact console the fail-closed preflight checked; falls back to ``typer.echo`` on
+ stderr for callers that do not resolve one. Mirrors run.py's
+ ``_print_auto_generated_credentials``. Never logged elsewhere and never
+ persisted; the re-exec'd child then sees must_change=0 and no-ops.
+ """
+ line = "=" * 70
+ banner = (
+ f"\n{line}\n"
+ " Unsloth Studio admin login (auto-generated for this public launch)\n"
+ f" Username: {username}\n"
+ f" Password: {password}\n"
+ " Save this now: it is shown once, not written to disk, and not in the\n"
+ " process list. Rotate later with `unsloth studio reset-password`.\n"
+ f"{line}"
+ )
+ if out is None:
+ typer.echo(banner, err = True)
+ else:
+ print(banner, file = out, flush = True)
+
+
+def _deliver_auto_generated_credentials(username: str, password: str, *, out) -> bool:
+ """Echo the one-time credential to *out*, retrying once on the other console.
+
+ Mirrors run.py's ``_deliver_one_time_credential``. The console preflight runs
+ before the rotation, but this write happens after ``_cli_update_password`` has
+ committed the generated password and removed the seeded bootstrap credential.
+ A terminal that disappears in between (a dropped SSH session; writes to the
+ orphaned pty raise OSError EIO) would make the echo raise, aborting the launch
+ with a live password nobody has ever seen. Retry once on the other console
+ (re-resolved through the same tty/closed/writable preflight, so the retry can
+ never land the credential in a redirected file or journal), and report whether
+ it reached a console at all so the caller can fail closed instead of crashing.
+ """
+ fallback = _one_time_secret_console_stream(skip = out)
+ # Never retry the stream that just failed (a stubbed resolver could return it).
+ for stream in (out, fallback if fallback is not out else None):
+ if stream is None:
+ continue
+ try:
+ _echo_auto_generated_credentials(username, password, out = stream)
+ return True
+ except Exception:
+ continue
+ return False
+
+
+def _log_secret_free_delivery_failure() -> None:
+ """Explain an undeliverable one-time credential, WITHOUT echoing the secret.
+
+ Reached only when every console refused the banner, so this message may itself
+ fail to land; it is best-effort and deliberately carries no password (writing
+ the value anywhere else would persist it, CWE-532). The non-zero exit is the
+ part the caller can always rely on.
+ """
+ try:
+ typer.echo(
+ "Error: the auto-generated Unsloth admin password could not be shown: "
+ "the console went away after the pre-rotation check. It is now the live "
+ "password but was never displayed, so nothing can recover it. Reset the "
+ "credential with `unsloth studio reset-password`, then relaunch.",
+ err = True,
+ )
+ except Exception:
+ pass
def _apply_supplied_password_before_launch(supplied_password: "str | None") -> None:
@@ -1590,49 +1769,24 @@ def _enforce_password_change_before_exposure(
)
_strip_seeded_bootstrap_password_or_exit(context = "auth DB row unreadable")
return
+ if row and _credential_undelivered(conn):
+ # A prior generated password was never shown. Fail closed until it is reset.
+ typer.echo(
+ "Error: refusing to publish Unsloth on a public Cloudflare URL: the "
+ "admin password auto-generated by an earlier launch was committed but "
+ "never displayed, so no one can log in. Reset it with `unsloth studio "
+ "reset-password`, then relaunch.",
+ err = True,
+ )
+ raise typer.Exit(1)
if not row or not row[2]:
return
if not _prompt_streams_interactive():
- # Only proceed headless if the bootstrap shutdown deadline will protect
- # the launch: it never arms for api-only, and TIMEOUT=0 disables it.
- if api_only or not _bootstrap_deadline_active():
- typer.echo(
- "Error: refusing to publish Unsloth on a public Cloudflare "
- "URL: the default admin password was never changed, no "
- "terminal is attached to change it here, and the bootstrap "
- "shutdown deadline does not apply to this launch (api-only, "
- "or UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT=0). Change the "
- "password first (run `unsloth studio` locally and log in, "
- "or re-run with a terminal attached), then retry.",
- err = True,
- )
- raise typer.Exit(1)
- if child_self_suppresses:
- # The child is this install's own backend, whose pre-bind gate sets
- # app.state.suppress_bootstrap_injection, so the seeded credential
- # is never served publicly even with the file on disk. Skip the
- # strip: unnecessary here, and it would lock the user out if the
- # tunnel never comes up (e.g. a --secure loopback whose tunnel
- # fails). Keep the file for LOCAL recovery; must_change stays set
- # and the deadline arms.
- typer.echo(
- "Warning: Unsloth is being exposed publicly while the admin "
- "account still uses its auto-generated bootstrap password. The "
- "login page forces a change and the credential is never served "
- "on the public page. Set a new password by running `unsloth "
- "studio` locally with a terminal attached, or `unsloth studio "
- "reset-password`; Unsloth shuts down after ~1h if the password "
- "stays unchanged (UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT).",
- err = True,
- )
- return
- # The strip permanently removes the only plaintext recovery credential.
- # On --secure the bind is loopback, so the tunnel is the ONLY public
+ # On --secure the loopback bind means the tunnel is the only public
# exposure: if cloudflared is provably unavailable no public URL can
- # start, so stripping would just lock the user out. Refuse with the
- # credential preserved. (A wildcard --cloudflare bind is public
- # regardless of the tunnel, so it still strips below, as does any
- # uncertainty.)
+ # ever come up, so refuse rather than rotate the recovery credential
+ # for a launch that will not start. (A wildcard --cloudflare bind is
+ # public regardless of the tunnel, so it still proceeds below.)
if secure and _tunnel_binary_confirmed_unavailable():
typer.echo(
"Error: refusing to expose Unsloth: the Cloudflare tunnel binary "
@@ -1644,22 +1798,49 @@ def _enforce_password_change_before_exposure(
err = True,
)
raise typer.Exit(1)
- # Mixed-version safety: an OLD studio-venv child (predating this gate)
- # has no pre-bind suppression and would read the seeded credential back
- # from disk and inject it into the public HTML until the deadline.
- # Delete the file here, in the parent, so a fresh child of ANY version
- # reads None. must_change_password stays set, so the login page still
- # forces a change and the timer still arms; only the on-disk copy goes.
- _strip_seeded_bootstrap_password_or_exit(context = "no terminal to change it")
- typer.echo(
- "Warning: Unsloth is being exposed publicly while the admin account "
- "still uses its auto-generated bootstrap password. The seeded password "
- "file has been removed so it is not served on the public page. Set a new "
- "password by running `unsloth studio` locally with a terminal attached, "
- "or `unsloth studio reset-password`; Unsloth shuts down after ~1h if the "
- "password stays unchanged (UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT).",
- err = True,
- )
+ # Rotate through the normal update path and show the password before re-exec,
+ # keeping it off child argv. Resolve a usable console before rotation so a
+ # headless launch cannot lose the only recovery credential.
+ out = _one_time_secret_console_stream()
+ if out is None:
+ typer.echo(
+ "Error: refusing to rotate the Unsloth admin password: no usable "
+ "console (stderr/stdout) to show the auto-generated credential, so "
+ "it would be lost. The seeded bootstrap password is preserved; "
+ "change the password first (`unsloth studio` locally with a "
+ "terminal attached, or `unsloth studio reset-password`).",
+ err = True,
+ )
+ raise typer.Exit(1)
+ generated = secrets.token_urlsafe(24)
+ if not _cli_update_password(
+ conn,
+ DEFAULT_ADMIN_USERNAME,
+ generated,
+ require_must_change = True,
+ mark_credential_undelivered = True,
+ ):
+ # A concurrent password won; launch with it and do not show ours.
+ winner = conn.execute(
+ "SELECT password_hash FROM auth_user WHERE username = ?",
+ (DEFAULT_ADMIN_USERNAME,),
+ ).fetchone()
+ if winner and _credential_undelivered(conn):
+ # A concurrent launcher has not delivered its password; keep closed.
+ typer.echo(
+ "Error: refusing to publish Unsloth on a public Cloudflare URL: "
+ "a concurrent launch committed an auto-generated admin password "
+ "that has not been displayed yet. Retry after that launch shows "
+ "the credential, or reset it with `unsloth studio reset-password`.",
+ err = True,
+ )
+ raise typer.Exit(1)
+ return
+ # Delivery follows commit; retry the other console, then fail closed.
+ if not _deliver_auto_generated_credentials(DEFAULT_ADMIN_USERNAME, generated, out = out):
+ _log_secret_free_delivery_failure()
+ raise typer.Exit(1)
+ _clear_credential_undelivered(conn)
return
password_salt, password_hash = row[0], row[1]
diff --git a/unsloth_cli/tests/test_studio_cloudflare_flag.py b/unsloth_cli/tests/test_studio_cloudflare_flag.py
index cf150b9e137..66c4b63ee05 100644
--- a/unsloth_cli/tests/test_studio_cloudflare_flag.py
+++ b/unsloth_cli/tests/test_studio_cloudflare_flag.py
@@ -68,13 +68,15 @@ def _install_run_reexec_capture(monkeypatch, *, platform = "linux"):
monkeypatch.setattr(sys, "prefix", "/nonexistent/outer/venv")
fake_venv = Path("/fake/studio/venv/unsloth_studio")
- monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_venv / "bin" / "python")
+ host_is_windows = studio_mod.platform.system() == "Windows"
+ fake_python = fake_venv / ("Scripts/python.exe" if host_is_windows else "bin/python")
+ monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_python)
# A built frontend dist is present so the public-launch UI check passes
# deterministically (independent of whether the repo dist was built).
monkeypatch.setattr(
studio_mod, "_find_frontend_dist", lambda: Path("/fake/studio/frontend/dist")
)
- fake_bin = fake_venv / "bin" / "unsloth"
+ fake_bin = fake_python.parent / ("unsloth.exe" if host_is_windows else "unsloth")
real_is_file = Path.is_file
monkeypatch.setattr(
Path,
@@ -88,6 +90,13 @@ def _install_run_reexec_capture(monkeypatch, *, platform = "linux"):
"resolve_tool_policy",
lambda host, flag, yes, silent: False if flag is None else bool(flag),
)
+ # This suite asserts what reaches the re-exec'd child's argv. The pre-exposure
+ # password gate is not part of that: on a headless launch it now rotates the
+ # admin password against the real STUDIO_HOME (which this helper does not
+ # isolate) and fails closed under CliRunner's non-tty streams. Neutralise it
+ # here; it has a dedicated suite in test_studio_password_prompt.py.
+ monkeypatch.setattr(studio_mod, "_enforce_password_change_before_exposure", lambda **_kw: None)
+
monkeypatch.setattr(sys, "platform", platform)
def fake_execvp(file, argv):
@@ -164,6 +173,13 @@ def _invoke_studio_default(
monkeypatch.setattr(
studio_mod, "_find_frontend_dist", lambda: Path("/fake/studio/frontend/dist")
)
+ # This suite asserts what reaches the re-exec'd child's argv. The pre-exposure
+ # password gate is not part of that: on a headless launch it now rotates the
+ # admin password against the real STUDIO_HOME (which this helper does not
+ # isolate) and fails closed under CliRunner's non-tty streams. Neutralise it
+ # here; it has a dedicated suite in test_studio_password_prompt.py.
+ monkeypatch.setattr(studio_mod, "_enforce_password_change_before_exposure", lambda **_kw: None)
+
monkeypatch.setattr(sys, "platform", platform)
def fake_execvp(file, argv):
diff --git a/unsloth_cli/tests/test_studio_password_prompt.py b/unsloth_cli/tests/test_studio_password_prompt.py
index 1761afc04e9..94338426a57 100644
--- a/unsloth_cli/tests/test_studio_password_prompt.py
+++ b/unsloth_cli/tests/test_studio_password_prompt.py
@@ -141,6 +141,13 @@ def _install_prompt_env(
# proceeds without a real download; the unavailable-tunnel guard has its own
# dedicated test that overrides this.
monkeypatch.setattr(studio_mod, "_tunnel_binary_confirmed_unavailable", lambda: False)
+ # The one-time-secret selector now requires a real tty (a redirected/persisted
+ # stream would leak the credential -- see _one_time_secret_console_stream and
+ # test_one_time_secret_console_stream_requires_tty). CliRunner's captured stderr
+ # is not a tty, so provide a usable console here: these tests exercise the
+ # rotation/re-exec logic given a surface, not the tty preflight. Tests for the
+ # no-console fail-closed path override this back to None afterwards.
+ monkeypatch.setattr(studio_mod, "_one_time_secret_console_stream", lambda **_kw: sys.stderr)
def fake_prompt(verify_current, out = None):
events.append(("prompt", verify_current))
@@ -177,14 +184,16 @@ def _install_run_reexec(monkeypatch, events):
studio_mod = _studio()
monkeypatch.setattr(sys, "prefix", "/nonexistent/outer/venv")
fake_venv = Path("/fake/studio/venv/unsloth_studio")
- monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_venv / "bin" / "python")
+ host_is_windows = studio_mod.platform.system() == "Windows"
+ fake_python = fake_venv / ("Scripts/python.exe" if host_is_windows else "bin/python")
+ monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_python)
# A built frontend dist is present by default so the public-launch UI check
# passes deterministically (independent of whether the repo dist was built);
# the missing-dist lockout guard has its own dedicated test.
monkeypatch.setattr(
studio_mod, "_find_frontend_dist", lambda: Path("/fake/studio/frontend/dist")
)
- fake_bin = fake_venv / "bin" / "unsloth"
+ fake_bin = fake_python.parent / ("unsloth.exe" if host_is_windows else "unsloth")
real_is_file = Path.is_file
monkeypatch.setattr(
Path,
@@ -518,7 +527,10 @@ def test_studio_default_prompt_rejects_current_password(monkeypatch, tmp_path):
assert verify_current("something-else-entirely") is False
-def test_studio_default_non_tty_warns_and_proceeds(monkeypatch, tmp_path):
+def test_studio_default_non_tty_autogenerates_and_proceeds(monkeypatch, tmp_path):
+ # No terminal + seeded default password: auto-generate a strong admin
+ # password, commit it (clears must_change so the child launches cleanly), and
+ # print it once before re-exec.
studio_mod = _studio()
events = _install_prompt_env(monkeypatch, tmp_path, interactive = False)
_seed_auth(studio_mod)
@@ -528,16 +540,16 @@ def test_studio_default_non_tty_warns_and_proceeds(monkeypatch, tmp_path):
kinds = [kind for kind, _ in events]
assert kinds == ["exec"], events
combined = (result.output or "") + (getattr(result, "stderr", "") or "")
- assert "bootstrap password" in combined
- assert _auth_state(studio_mod)["must_change_password"] == 1
+ assert "auto-generated" in combined.lower()
+ state = _auth_state(studio_mod)
+ assert state["must_change_password"] == 0
+ assert state["n_refresh"] == 0 # refresh tokens revoked in the same transaction
def test_studio_default_non_tty_deletes_bootstrap_password_file(monkeypatch, tmp_path):
- # Mixed-version safety: a headless public launch must delete the seeded
- # plaintext credential before re-exec so a fresh child of ANY version reads
- # None from disk and never injects it into the public HTML. The launch still
- # proceeds (re-exec captured), and the DB flag stays set so the login page
- # still forces a change and the bootstrap shutdown timer still arms.
+ # Auto-generation commits a new password and deletes the seeded plaintext
+ # credential before re-exec, so a fresh child of ANY version reads None from
+ # disk and never injects it into the public HTML. The launch still proceeds.
studio_mod = _studio()
events = _install_prompt_env(monkeypatch, tmp_path, interactive = False)
_seed_auth(studio_mod)
@@ -549,17 +561,135 @@ def test_studio_default_non_tty_deletes_bootstrap_password_file(monkeypatch, tmp
assert not bootstrap_file.exists()
kinds = [kind for kind, _ in events]
assert kinds == ["exec"], events
- assert _auth_state(studio_mod)["must_change_password"] == 1
+ assert _auth_state(studio_mod)["must_change_password"] == 0
-def test_studio_default_reexec_outer_runpy_keeps_bootstrap_for_local_recovery(
- monkeypatch, tmp_path
-):
- # Regression (Codex 3572165931): when the re-exec target is THIS install's own
- # run.py, the child's pre-bind gate sets suppress_bootstrap_injection and never
- # serves the seeded credential publicly, so the parent strip is unnecessary.
- # Skipping it means a --secure launch whose tunnel later fails to connect does
- # not lock the user out, and .bootstrap_password stays for local recovery.
+def test_one_time_secret_console_stream_prefers_stderr_then_stdout(monkeypatch):
+ # Unit: prefer stderr, fall back to stdout, None when neither is usable (absent
+ # or closed). Mirrors run._one_time_secret_stream so the CLI parent never rotates
+ # the recovery credential when there is nowhere to surface the replacement.
+ studio_mod = _studio()
+
+ class _Stream:
+ def __init__(
+ self,
+ *,
+ closed = False,
+ tty = True,
+ ):
+ self.closed = closed
+ self._tty = tty
+
+ def write(self, *_a, **_k):
+ pass
+
+ def isatty(self):
+ return self._tty
+
+ real_err, real_out = _Stream(), _Stream()
+
+ monkeypatch.setattr(sys, "stderr", real_err)
+ monkeypatch.setattr(sys, "stdout", real_out)
+ assert studio_mod._one_time_secret_console_stream() is real_err # stderr wins
+
+ monkeypatch.setattr(sys, "stderr", None)
+ assert studio_mod._one_time_secret_console_stream() is real_out # falls back
+
+ monkeypatch.setattr(sys, "stderr", _Stream(closed = True))
+ monkeypatch.setattr(sys, "stdout", _Stream(closed = True))
+ assert studio_mod._one_time_secret_console_stream() is None # no usable console
+
+ monkeypatch.setattr(sys, "stderr", None)
+ monkeypatch.setattr(sys, "stdout", None)
+ assert studio_mod._one_time_secret_console_stream() is None # pythonw wrapper
+
+
+def test_one_time_secret_console_stream_requires_tty(monkeypatch):
+ # Regression (Codex 3644671925, P1): a headless CLI launch (nohup / systemd /
+ # `> log 2>&1`) inherits a stderr/stdout that is open and writable but NOT a
+ # tty. Surfacing the auto-generated password there PERSISTS the plaintext to
+ # the file/journal (CWE-532), so the selector must skip a non-tty stream and
+ # fall back to a real terminal, returning None when neither is a tty.
+ studio_mod = _studio()
+
+ class _Stream:
+ def __init__(self, *, tty):
+ self.closed = False
+ self._tty = tty
+
+ def write(self, *_a, **_k):
+ pass
+
+ def isatty(self):
+ return self._tty
+
+ redirected_err, tty_out = _Stream(tty = False), _Stream(tty = True)
+ monkeypatch.setattr(sys, "stderr", redirected_err)
+ monkeypatch.setattr(sys, "stdout", tty_out)
+ # Redirected stderr is skipped; falls back to the tty stdout.
+ assert studio_mod._one_time_secret_console_stream() is tty_out
+
+ # Both redirected (fully headless) -> None, so the caller fails closed rather
+ # than write the credential into a retained file/journal.
+ monkeypatch.setattr(sys, "stderr", _Stream(tty = False))
+ monkeypatch.setattr(sys, "stdout", _Stream(tty = False))
+ assert studio_mod._one_time_secret_console_stream() is None
+
+
+def test_one_time_secret_console_stream_survives_isatty_oserror(monkeypatch):
+ studio_mod = _studio()
+
+ class _BrokenConsole:
+ closed = False
+
+ def write(self, *_a, **_k):
+ pass
+
+ def isatty(self):
+ raise OSError(5, "Input/output error")
+
+ class _LiveConsole(_BrokenConsole):
+ def isatty(self):
+ return True
+
+ broken, live = _BrokenConsole(), _LiveConsole()
+ monkeypatch.setattr(sys, "stderr", broken)
+ monkeypatch.setattr(sys, "stdout", live)
+ assert studio_mod._one_time_secret_console_stream() is live
+
+ monkeypatch.setattr(sys, "stdout", _BrokenConsole())
+ assert studio_mod._one_time_secret_console_stream() is None
+
+
+def test_studio_default_non_tty_no_console_preserves_bootstrap(monkeypatch, tmp_path):
+ # Non-interactive launch with no usable console (a Windows pythonw/service
+ # wrapper leaves stderr/stdout absent): the auto-generated password could never
+ # be shown, so rotating the seeded recovery credential would lock the operator
+ # out. Fail closed WITHOUT rotating -- the bootstrap password and must_change
+ # flag are preserved, and the launch aborts before any re-exec.
+ studio_mod = _studio()
+ events = _install_prompt_env(monkeypatch, tmp_path, interactive = False)
+ before = _seed_auth(studio_mod)
+ bootstrap_file = tmp_path / "auth" / studio_mod.BOOTSTRAP_PASSWORD_FILE
+ assert bootstrap_file.exists()
+ monkeypatch.setattr(studio_mod, "_one_time_secret_console_stream", lambda **_kw: None)
+
+ result = _invoke_studio_default(monkeypatch, events, ["--secure"])
+
+ assert result.exit_code == 1, result.output
+ # No rotation and no re-exec: recovery credential intact.
+ assert bootstrap_file.exists()
+ after = _auth_state(studio_mod)
+ assert after["must_change_password"] == 1
+ assert after["password_hash"] == before["password_hash"]
+ assert after["jwt_secret"] == before["jwt_secret"]
+ assert "exec" not in [k for k, _ in events], events
+
+
+def test_studio_default_reexec_outer_runpy_autogenerates(monkeypatch, tmp_path):
+ # Even when the re-exec target is THIS install's own run.py (self-suppressing),
+ # the parent auto-generates and commits a strong password so it is surfaced
+ # once here and the child sees must_change=0 and no-ops.
import typer as _typer
studio_mod = _studio()
@@ -569,7 +699,6 @@ def test_studio_default_reexec_outer_runpy_keeps_bootstrap_for_local_recovery(
assert bootstrap_file.exists()
_install_studio_default_reexec(monkeypatch, events)
- # Re-exec target IS this install's outer run.py -> child self-suppresses.
outer_run_py = studio_mod._PACKAGE_ROOT / "studio" / "backend" / "run.py"
monkeypatch.setattr(studio_mod, "_find_run_py", lambda: outer_run_py)
@@ -577,36 +706,32 @@ def test_studio_default_reexec_outer_runpy_keeps_bootstrap_for_local_recovery(
app.command()(studio_mod.studio_default)
result = CliRunner().invoke(app, ["--secure"], catch_exceptions = True)
- # Strip skipped: file preserved, must_change still set, launch still re-execs.
- assert bootstrap_file.exists(), result.output
- assert _auth_state(studio_mod)["must_change_password"] == 1
+ assert not bootstrap_file.exists(), result.output
+ assert _auth_state(studio_mod)["must_change_password"] == 0
assert "exec" in [k for k, _ in events], events
def test_studio_default_non_tty_persists_seeded_admin_on_fresh_home(monkeypatch, tmp_path):
# Fresh STUDIO_HOME (no pre-seed): the gate's own _ensure_cli_default_admin
- # does the INSERT. It must COMMIT that seed before re-exec, or conn.close()
- # rolls it back and an OLD child would find no admin, regenerate a fresh
- # bootstrap password + file, and inject THAT -- defeating the file deletion.
+ # does the INSERT, then auto-generation commits a strong password over it. The
+ # committed change persists (must_change=0) and the launch re-execs.
studio_mod = _studio()
events = _install_prompt_env(monkeypatch, tmp_path, interactive = False)
# Deliberately NO _seed_auth(): exercise the gate seeding a fresh DB itself.
_invoke_studio_default(monkeypatch, events, ["--secure"])
- # The seeded admin persists (committed) so an old child sees it and does not
- # regenerate; the bootstrap file stays deleted; the launch still re-execs.
state = _auth_state(studio_mod)
- assert state["must_change_password"] == 1
+ assert state["must_change_password"] == 0
assert not (tmp_path / "auth" / studio_mod.BOOTSTRAP_PASSWORD_FILE).exists()
kinds = [kind for kind, _ in events]
assert kinds == ["exec"], events
-def test_studio_default_non_tty_fails_closed_when_bootstrap_removal_fails(monkeypatch, tmp_path):
- # Removing .bootstrap_password IS the protection on this path. If unlink
- # fails (locked file / read-only auth dir) the credential is still on disk
- # for an old child to inject, so the launch must fail closed, not publish.
+def test_studio_default_non_tty_autogen_survives_locked_bootstrap_file(monkeypatch, tmp_path):
+ # The new password is already committed before the seeded file is removed, so a
+ # locked/undeletable .bootstrap_password (Windows AV / read-only dir) must NOT
+ # fail the launch: it is truncated instead and the launch proceeds.
import pathlib
studio_mod = _studio()
@@ -627,13 +752,12 @@ def test_studio_default_non_tty_fails_closed_when_bootstrap_removal_fails(monkey
result = _invoke_studio_default(monkeypatch, events, ["--secure"])
kinds = [kind for kind, _ in events]
- assert "exec" not in kinds, events
- assert result.exit_code == 1, result.output
- combined = (result.output or "") + (getattr(result, "stderr", "") or "")
- assert "refusing to publish" in combined.lower()
- # The file remains (removal failed) and the DB flag is untouched.
- assert bootstrap_file.exists()
- assert _auth_state(studio_mod)["must_change_password"] == 1
+ assert kinds == ["exec"], events
+ assert result.exit_code == 0, result.output
+ # Password rotated (must_change cleared); the locked file is truncated so its
+ # stale plaintext cannot be reused.
+ assert _auth_state(studio_mod)["must_change_password"] == 0
+ assert bootstrap_file.read_text() == ""
class _FailingSelectConn:
@@ -882,7 +1006,9 @@ def test_studio_default_in_venv_broken_backend_exits_before_stripping_bootstrap(
bootstrap_file = tmp_path / "auth" / studio_mod.BOOTSTRAP_PASSWORD_FILE
assert bootstrap_file.exists()
- # Pretend we are already inside the studio venv, with a broken backend.
+ # Pretend we are already inside the studio venv, with a broken backend. The
+ # servable-frontend guard runs first (and would otherwise exit on the missing
+ # dist), so stub it satisfied to isolate the backend-load guard under test.
monkeypatch.setattr(sys, "prefix", str(tmp_path / "unsloth_studio"))
# A built dist is not present in a fresh clone. The missing-frontend gate
# runs first and has its own test below; stub it so this one reaches the
@@ -1116,7 +1242,7 @@ def test_run_secure_prompts_and_updates_before_reexec(monkeypatch, tmp_path):
assert after["n_refresh"] == 0
-def test_run_non_tty_warns_and_proceeds(monkeypatch, tmp_path):
+def test_run_non_tty_autogenerates_and_proceeds(monkeypatch, tmp_path):
studio_mod = _studio()
events = _install_prompt_env(monkeypatch, tmp_path, interactive = False)
_seed_auth(studio_mod)
@@ -1126,13 +1252,14 @@ def test_run_non_tty_warns_and_proceeds(monkeypatch, tmp_path):
kinds = [kind for kind, _ in events]
assert kinds == ["exec"], events
combined = (result.output or "") + (getattr(result, "stderr", "") or "")
- assert "bootstrap password" in combined
+ assert "auto-generated" in combined.lower()
+ assert _auth_state(studio_mod)["must_change_password"] == 0
def test_run_non_tty_deletes_bootstrap_password_file(monkeypatch, tmp_path):
- # Same mixed-version safety for the `unsloth studio run` re-exec path (which
- # cannot fail-close an old child via a CLI flag): the seeded credential file
- # is deleted before re-exec, the launch still proceeds, and the DB flag holds.
+ # Auto-generation on the `unsloth studio run` re-exec path commits a new
+ # password and deletes the seeded credential file before re-exec, so a fresh
+ # child of ANY version reads None from disk. The launch still proceeds.
studio_mod = _studio()
events = _install_prompt_env(monkeypatch, tmp_path, interactive = False)
_seed_auth(studio_mod)
@@ -1144,7 +1271,7 @@ def test_run_non_tty_deletes_bootstrap_password_file(monkeypatch, tmp_path):
assert not bootstrap_file.exists()
kinds = [kind for kind, _ in events]
assert kinds == ["exec"], events
- assert _auth_state(studio_mod)["must_change_password"] == 1
+ assert _auth_state(studio_mod)["must_change_password"] == 0
def test_run_missing_frontend_exits_before_stripping_bootstrap(monkeypatch, tmp_path):
@@ -1227,25 +1354,24 @@ def test_run_reexec_forwards_resolved_frontend_on_public_launch(monkeypatch, tmp
def test_run_non_tty_persists_seeded_admin_on_fresh_home(monkeypatch, tmp_path):
- # Fresh STUDIO_HOME on the `run` re-exec path: the seeded admin must be
- # committed before re-exec so an old console-script child does not regenerate
- # and inject a fresh bootstrap credential.
+ # Fresh STUDIO_HOME on the `run` re-exec path: the gate seeds the admin, then
+ # auto-generation commits a strong password over it (must_change=0) before
+ # re-exec, so no old console-script child ever serves a default credential.
studio_mod = _studio()
events = _install_prompt_env(monkeypatch, tmp_path, interactive = False)
_invoke_run(monkeypatch, events, _BASE + ["--secure"])
state = _auth_state(studio_mod)
- assert state["must_change_password"] == 1
+ assert state["must_change_password"] == 0
assert not (tmp_path / "auth" / studio_mod.BOOTSTRAP_PASSWORD_FILE).exists()
kinds = [kind for kind, _ in events]
assert kinds == ["exec"], events
-def test_run_non_tty_api_only_fails_closed(monkeypatch, tmp_path):
- # api-only serving never arms the bootstrap shutdown deadline, so a
- # headless public launch with the default password has no safeguard at
- # all: the CLI must refuse rather than promise a shutdown that never comes.
+def test_run_non_tty_api_only_autogenerates(monkeypatch, tmp_path):
+ # api-only headless public serving used to fail closed for lack of a deadline;
+ # now a strong password is auto-generated instead, so the launch proceeds.
studio_mod = _studio()
events = _install_prompt_env(monkeypatch, tmp_path, interactive = False)
_seed_auth(studio_mod)
@@ -1253,16 +1379,16 @@ def test_run_non_tty_api_only_fails_closed(monkeypatch, tmp_path):
result = _invoke_run(monkeypatch, events, _BASE + ["--secure", "--api-only"])
kinds = [kind for kind, _ in events]
- assert "exec" not in kinds, events
- assert result.exit_code == 1, result.output
+ assert kinds == ["exec"], events
+ assert result.exit_code == 0, result.output
combined = (result.output or "") + (getattr(result, "stderr", "") or "")
- assert "refusing to publish" in combined.lower()
- assert _auth_state(studio_mod)["must_change_password"] == 1
+ assert "auto-generated" in combined.lower()
+ assert _auth_state(studio_mod)["must_change_password"] == 0
-def test_studio_default_non_tty_disabled_deadline_fails_closed(monkeypatch, tmp_path):
- # UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT=0 disables the deadline; headless +
- # default password + public tunnel then has no protection -> refuse.
+def test_studio_default_non_tty_disabled_deadline_autogenerates(monkeypatch, tmp_path):
+ # UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT=0 disables the deadline; the auto-generated
+ # password is the safeguard now, so the launch still proceeds.
studio_mod = _studio()
events = _install_prompt_env(monkeypatch, tmp_path, interactive = False)
_seed_auth(studio_mod)
@@ -1271,31 +1397,10 @@ def test_studio_default_non_tty_disabled_deadline_fails_closed(monkeypatch, tmp_
result = _invoke_studio_default(monkeypatch, events, ["--secure"])
kinds = [kind for kind, _ in events]
- assert "exec" not in kinds, events
- assert result.exit_code == 1, result.output
+ assert kinds == ["exec"], events
combined = (result.output or "") + (getattr(result, "stderr", "") or "")
- assert "refusing to publish" in combined.lower()
-
-
- "raw,expected",
- [
- (None, True), # unset -> default 1h
- ("", True),
- ("garbage", True), # malformed must not remove protection
- ("3600", True),
- ("1", True),
- ("0", False),
- ("-5", False),
- ],
-)
-def test_bootstrap_deadline_active_mirrors_backend_parsing(monkeypatch, raw, expected):
- studio_mod = _studio()
- if raw is None:
- monkeypatch.delenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raising = False)
- else:
- monkeypatch.setenv("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", raw)
- assert studio_mod._bootstrap_deadline_active() is expected
+ assert "auto-generated" in combined.lower()
+ assert _auth_state(studio_mod)["must_change_password"] == 0
def _reset_password_cli(studio_mod):
@@ -1492,6 +1597,318 @@ def test_cli_update_password_truncates_locked_bootstrap_after_change(monkeypatch
assert bootstrap_file.read_text() == ""
+def test_stale_file_warning_failure_does_not_prevent_generated_password_delivery(
+ monkeypatch, tmp_path
+):
+ # The credential and its pending-delivery marker commit before stale-file
+ # cleanup. If the warning channel then disappears, delivery must still retry
+ # the preflighted console instead of abandoning a live password nobody saw.
+ import pathlib
+
+ studio_mod = _studio()
+ _install_prompt_env(monkeypatch, tmp_path, interactive = False)
+ _seed_auth(studio_mod)
+ bootstrap_file = tmp_path / "auth" / studio_mod.BOOTSTRAP_PASSWORD_FILE
+ real_unlink = pathlib.Path.unlink
+
+ def _locked_bootstrap(self, *args, **kwargs):
+ if self == bootstrap_file:
+ raise OSError("locked")
+ return real_unlink(self, *args, **kwargs)
+
+ class _Console:
+ closed = False
+
+ def __init__(self):
+ self.text = ""
+
+ def write(self, value):
+ self.text += value
+ return len(value)
+
+ def flush(self):
+ pass
+
+ def isatty(self):
+ return True
+
+ console = _Console()
+ warnings = []
+
+ def _warning_channel_died(message, **_kwargs):
+ warnings.append(str(message))
+ raise OSError("stderr disappeared")
+
+ monkeypatch.setattr(pathlib.Path, "unlink", _locked_bootstrap)
+ monkeypatch.setattr(studio_mod, "_one_time_secret_console_stream", lambda **_kw: console)
+ monkeypatch.setattr(studio_mod.typer, "echo", _warning_channel_died)
+
+ studio_mod._enforce_password_change_before_exposure(
+ cloudflare = None,
+ host = "127.0.0.1",
+ secure = True,
+ api_only = False,
+ )
+
+ assert warnings and "could not remove stale" in warnings[0]
+ assert "Password:" not in warnings[0]
+ generated = next(
+ line.split("Password:", 1)[1].strip()
+ for line in console.text.splitlines()
+ if "Password:" in line
+ )
+ assert _password_works(studio_mod, generated)
+ assert bootstrap_file.read_text(encoding = "utf-8") == ""
+ conn = studio_mod._connect_auth_db()
+ try:
+ assert (
+ conn.execute(
+ "SELECT 1 FROM app_secrets WHERE key = ?",
+ (studio_mod.CREDENTIAL_UNDELIVERED_PASSWORD_HASH_KEY,),
+ ).fetchone()
+ is None
+ )
+ finally:
+ conn.close()
+
+
+def test_cli_update_password_compare_and_set_guard(monkeypatch, tmp_path):
+ # Mirror backend storage.update_password: the auto-generated launch credential
+ # is committed only while must_change_password is still 1. A user finishing
+ # /change-password in a Studio tab between the must_change read and this write
+ # must not be silently overwritten, and nothing else may be revoked when the
+ # guard rejects the update.
+ studio_mod = _studio()
+ monkeypatch.setattr(studio_mod, "STUDIO_HOME", tmp_path)
+ _seed_auth(studio_mod)
+
+ conn = studio_mod._connect_auth_db()
+ admin = studio_mod.DEFAULT_ADMIN_USERNAME
+ assert (
+ studio_mod._cli_update_password(
+ conn, admin, "first-generated-pw-1", require_must_change = True
+ )
+ is True
+ )
+ before = conn.execute(
+ "SELECT password_hash, jwt_secret FROM auth_user WHERE username = ?", (admin,)
+ ).fetchone()
+ # Two credentials a rejected write must NOT destroy. api_keys is the one that
+ # matters most: _cli_update_password deletes it with no WHERE clause, so a
+ # revocation that ran past a failed compare-and-set would wipe every key for
+ # every user while leaving the password exactly as the winning writer set it.
+ conn.execute(
+ "INSERT INTO refresh_tokens (token_hash, username, expires_at) VALUES (?, ?, ?)",
+ ("refresh-hash-guarded", admin, "2099-01-01T00:00:00"),
+ )
+ conn.execute(
+ "INSERT INTO api_keys (username, key_prefix, key_hash, name, created_at) "
+ "VALUES (?, ?, ?, ?, ?)",
+ (admin, "sk-unsloth-", "api-key-hash-guarded", "guarded", "2026-01-01T00:00:00"),
+ )
+ conn.commit()
+
+ # must_change is 0 now, so the guarded write is refused and changes nothing.
+ assert (
+ studio_mod._cli_update_password(
+ conn, admin, "second-generated-pw-2", require_must_change = True
+ )
+ is False
+ )
+ after = conn.execute(
+ "SELECT password_hash, jwt_secret FROM auth_user WHERE username = ?", (admin,)
+ ).fetchone()
+ remaining_refresh = conn.execute("SELECT COUNT(*) FROM refresh_tokens").fetchone()[0]
+ remaining_keys = conn.execute("SELECT COUNT(*) FROM api_keys").fetchone()[0]
+
+ # An explicit (unguarded) change still applies.
+ assert studio_mod._cli_update_password(conn, admin, "explicit-change-pw-3") is True
+ conn.close()
+
+ assert tuple(after) == tuple(before) # password and JWT secret untouched
+ # No collateral revocation on a rejected write.
+ assert remaining_refresh == 1
+ assert remaining_keys == 1
+
+
[email protected]("winner_pending", [True, False], ids = ["launcher", "user"])
+def test_autogeneration_cas_loser_checks_winners_delivery_state(
+ monkeypatch, tmp_path, winner_pending
+):
+ # A concurrent launcher leaves an atomic pending marker until its generated
+ # credential is displayed, so this losing process must not publish first. A
+ # user-selected password clears that marker transactionally and may launch.
+ studio_mod = _studio()
+ _install_prompt_env(monkeypatch, tmp_path, interactive = False)
+ _seed_auth(studio_mod)
+ real_update = studio_mod._cli_update_password
+ raced = []
+
+ def _race_with_winner(conn, username, generated, **kwargs):
+ if not raced:
+ raced.append(True)
+ winner_conn = studio_mod._connect_auth_db()
+ try:
+ assert real_update(
+ winner_conn,
+ username,
+ "concurrent-winning-password",
+ require_must_change = True,
+ mark_credential_undelivered = winner_pending,
+ )
+ finally:
+ winner_conn.close()
+ return real_update(conn, username, generated, **kwargs)
+
+ monkeypatch.setattr(studio_mod, "_cli_update_password", _race_with_winner)
+
+ def _enforce():
+ studio_mod._enforce_password_change_before_exposure(
+ cloudflare = None,
+ host = "127.0.0.1",
+ secure = True,
+ api_only = False,
+ )
+
+ if winner_pending:
+ with pytest.raises(studio_mod.typer.Exit):
+ _enforce()
+ else:
+ _enforce()
+
+ assert raced == [True]
+ assert _password_works(studio_mod, "concurrent-winning-password")
+ conn = studio_mod._connect_auth_db()
+ try:
+ assert studio_mod._credential_undelivered(conn) is winner_pending
+ finally:
+ conn.close()
+
+
+def test_initial_marker_check_uses_current_password_hash(monkeypatch, tmp_path):
+ # A concurrent launcher can replace the password and write its pending-
+ # delivery marker after this process reads the auth row. The marker check
+ # must compare against the current row, not that caller-cached hash.
+ studio_mod = _studio()
+ _install_prompt_env(monkeypatch, tmp_path, interactive = False)
+ _seed_auth(studio_mod)
+ real_update = studio_mod._cli_update_password
+ real_credential_undelivered = studio_mod._credential_undelivered
+ raced = []
+
+ def _race_before_marker_read(conn):
+ if not raced:
+ raced.append(True)
+ winner_conn = studio_mod._connect_auth_db()
+ try:
+ assert real_update(
+ winner_conn,
+ studio_mod.DEFAULT_ADMIN_USERNAME,
+ "concurrent-winning-password",
+ require_must_change = True,
+ mark_credential_undelivered = True,
+ )
+ finally:
+ winner_conn.close()
+ return real_credential_undelivered(conn)
+
+ monkeypatch.setattr(
+ studio_mod,
+ "_credential_undelivered",
+ _race_before_marker_read,
+ )
+
+ with pytest.raises(studio_mod.typer.Exit):
+ studio_mod._enforce_password_change_before_exposure(
+ cloudflare = None,
+ host = "127.0.0.1",
+ secure = True,
+ api_only = False,
+ )
+
+ assert raced == [True]
+ conn = studio_mod._connect_auth_db()
+ try:
+ marker = conn.execute(
+ "SELECT value FROM app_secrets WHERE key = ?",
+ (studio_mod.CREDENTIAL_UNDELIVERED_PASSWORD_HASH_KEY,),
+ ).fetchone()
+ current_hash = conn.execute(
+ "SELECT password_hash FROM auth_user WHERE username = ?",
+ (studio_mod.DEFAULT_ADMIN_USERNAME,),
+ ).fetchone()[0]
+ assert marker == (current_hash,)
+ finally:
+ conn.close()
+
+
+def test_cli_update_password_marks_undelivered_in_same_transaction(monkeypatch, tmp_path):
+ studio_mod = _studio()
+ monkeypatch.setattr(studio_mod, "STUDIO_HOME", tmp_path)
+ _seed_auth(studio_mod)
+
+ conn = studio_mod._connect_auth_db()
+ admin = studio_mod.DEFAULT_ADMIN_USERNAME
+ before = conn.execute(
+ "SELECT password_hash FROM auth_user WHERE username = ?", (admin,)
+ ).fetchone()[0]
+ conn.execute(
+ """
+ CREATE TRIGGER reject_undelivered_marker
+ BEFORE INSERT ON app_secrets
+ WHEN NEW.key = 'credential_undelivered_password_hash'
+ BEGIN
+ SELECT RAISE(ABORT, 'marker rejected');
+ END
+ """
+ )
+ conn.commit()
+
+ with pytest.raises(sqlite3.IntegrityError, match = "marker rejected"):
+ studio_mod._cli_update_password(
+ conn,
+ admin,
+ "generated-but-undelivered-1",
+ require_must_change = True,
+ mark_credential_undelivered = True,
+ )
+
+ after = conn.execute(
+ "SELECT password_hash, must_change_password FROM auth_user WHERE username = ?", (admin,)
+ ).fetchone()
+ conn.close()
+ assert after[0] == before
+ assert after[1] == 1
+
+
+def test_cli_update_password_persists_and_clears_undelivered_state(monkeypatch, tmp_path):
+ studio_mod = _studio()
+ monkeypatch.setattr(studio_mod, "STUDIO_HOME", tmp_path)
+ _seed_auth(studio_mod)
+
+ conn = studio_mod._connect_auth_db()
+ admin = studio_mod.DEFAULT_ADMIN_USERNAME
+ assert studio_mod._cli_update_password(
+ conn,
+ admin,
+ "generated-undelivered-2",
+ require_must_change = True,
+ mark_credential_undelivered = True,
+ )
+ conn.close()
+
+ conn = studio_mod._connect_auth_db()
+ assert studio_mod._credential_undelivered(conn) is True
+
+ assert studio_mod._cli_update_password(conn, admin, "operator-chosen-password-3")
+ pending = conn.execute(
+ "SELECT value FROM app_secrets WHERE key = ?",
+ (studio_mod.CREDENTIAL_UNDELIVERED_PASSWORD_HASH_KEY,),
+ ).fetchone()
+ conn.close()
+ assert pending is None
+
+
def test_connect_auth_db_creates_private_files(monkeypatch, tmp_path):
# Fresh install: the CLI gate writes the password hash + JWT secret before
# the backend ever runs, so this path must apply the same 0700/0600 modes
@@ -1706,3 +2123,98 @@ def test_studio_default_password_applies_on_headless_wildcard_no_tunnel(monkeypa
assert after["must_change_password"] == 0
assert after["password_hash"] != before["password_hash"]
assert "--password" not in _exec_argv(events)
+
+
+class _DyingConsole:
+ """A terminal that passes the preflight and then raises on write.
+
+ Models the console going away between _one_time_secret_console_stream()'s
+ checks and the post-commit banner (a dropped SSH session leaves an orphaned
+ pty whose writes fail with OSError EIO).
+ """
+
+ closed = False
+
+ def __init__(self):
+ self.writes = 0
+
+ def write(self, *_a, **_k):
+ self.writes += 1
+ raise OSError(5, "Input/output error")
+
+ def flush(self, *_a, **_k):
+ pass
+
+ def isatty(self):
+ return True
+
+
+class _LiveConsole:
+ closed = False
+
+ def __init__(self):
+ self.text = ""
+
+ def write(self, data):
+ self.text += data
+ return len(data)
+
+ def flush(self, *_a, **_k):
+ pass
+
+ def isatty(self):
+ return True
+
+
+def test_credential_delivery_retries_the_other_console(monkeypatch):
+ # Regression (Codex 3651035060, P2): _echo_auto_generated_credentials runs
+ # AFTER _cli_update_password committed the generated password and removed the
+ # seeded bootstrap file, so a raise there used to abort the launch with a live
+ # password nobody had ever seen. Retry the other terminal instead.
+ studio_mod = _studio()
+ dying, alive = _DyingConsole(), _LiveConsole()
+ monkeypatch.setattr(sys, "stderr", dying)
+ monkeypatch.setattr(sys, "stdout", alive)
+
+ delivered = studio_mod._deliver_auto_generated_credentials(
+ "unsloth", "Cli-Retry-Pw-1", out = dying
+ )
+
+ assert delivered is True
+ assert dying.writes >= 1
+ assert "Cli-Retry-Pw-1" in alive.text
+
+
+def test_credential_delivery_reports_failure_without_a_usable_console(monkeypatch):
+ # No console accepts the write, and a redirected non-tty stream must NOT be
+ # used as a fallback (it would persist the plaintext, CWE-532). The caller
+ # then exits non-zero with a secret-free message instead of a traceback.
+ studio_mod = _studio()
+ dying = _DyingConsole()
+
+ class _Redirected(_LiveConsole):
+ def isatty(self):
+ return False
+
+ redirected = _Redirected()
+ monkeypatch.setattr(sys, "stderr", dying)
+ monkeypatch.setattr(sys, "stdout", redirected)
+
+ assert (
+ studio_mod._deliver_auto_generated_credentials("unsloth", "Cli-Lost-Pw-2", out = dying)
+ is False
+ )
+ assert redirected.text == ""
+
+
+def test_delivery_failure_message_carries_no_credential(monkeypatch):
+ # The advisory printed after an undeliverable credential must name the
+ # recovery command and nothing else; it can reach a log the password may not.
+ studio_mod = _studio()
+ printed: list[str] = []
+ monkeypatch.setattr(studio_mod.typer, "echo", lambda msg, **k: printed.append(str(msg)))
+
+ studio_mod._log_secret_free_delivery_failure()
+
+ assert printed and "reset-password" in printed[0]
+ assert "Password:" not in printed[0]
diff --git a/unsloth_cli/tests/test_studio_run_parallel_flag.py b/unsloth_cli/tests/test_studio_run_parallel_flag.py
index 558bb6203a2..e1b4ecc3edc 100644
--- a/unsloth_cli/tests/test_studio_run_parallel_flag.py
+++ b/unsloth_cli/tests/test_studio_run_parallel_flag.py
@@ -14,7 +14,9 @@ canonicaliser and the legacy `-m` / `-hfr` / `-f` shim.
from __future__ import annotations
import contextlib
+import io
import json
+import sqlite3
import sys
from io import BytesIO
from pathlib import Path
@@ -915,19 +917,44 @@ def test_reexec_forwards_api_only(monkeypatch, extra, present):
assert ("--api-only" in argv) is present, argv
-def test_secure_api_only_is_refused_before_any_reexec(monkeypatch, tmp_path):
- """`--secure --api-only` used to re-exec; the pre-exposure gate now refuses
- it, because api-only has no login page and the bootstrap deadline does not
- apply, so the seeded password could never be changed."""
+def test_secure_api_only_autogenerates_then_reexecs(monkeypatch, tmp_path):
+ """`--secure --api-only` proceeds again, on an auto-generated admin password.
+
+ It used to be refused outright: 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 that premise rather than
+ working around it -- the gate rotates the seeded credential and prints the new
+ one once BEFORE any re-exec, so nothing public is ever reachable under a
+ default password and there is no deadline left to depend on.
+ """
studio_mod = _load_run_command()
monkeypatch.setattr(studio_mod, "STUDIO_HOME", tmp_path)
+ monkeypatch.setattr(studio_mod, "_tunnel_binary_confirmed_unavailable", lambda: False)
+ # CliRunner's captured stderr is not a tty and the one-time-secret selector
+ # refuses to write a credential to a non-tty; hand it a console so this test
+ # reaches the rotation rather than stopping at the preflight (which has its own
+ # test, test_studio_password_prompt.py).
+ shown = io.StringIO()
+ monkeypatch.setattr(studio_mod, "_one_time_secret_console_stream", lambda **_kw: shown)
result, captured = _invoke_run(monkeypatch, _BASE + ["--secure", "--api-only"])
- assert captured == [], captured
- assert result.exit_code != 0
- combined = (result.output or "") + (getattr(result, "stderr", "") or "")
- assert "default admin password was never changed" in combined.lower()
+ assert result.exit_code == 0, result.output
+ assert len(captured) == 1, captured
+ banner = shown.getvalue()
+ assert "auto-generated for this public launch" in banner.lower()
+
+ # The seeded default is gone: must_change cleared, bootstrap file removed.
+ with sqlite3.connect(tmp_path / "auth" / "auth.db") as conn:
+ must_change = conn.execute(
+ "SELECT must_change_password FROM auth_user WHERE username = ?",
+ (studio_mod.DEFAULT_ADMIN_USERNAME,),
+ ).fetchone()[0]
+ assert must_change == 0
+ assert not (tmp_path / "auth" / studio_mod.BOOTSTRAP_PASSWORD_FILE).exists()
+
+ # The credential never crosses to the child on argv.
+ assert not any("password" in tok.lower() for tok in captured[0]["argv"]), captured[0]["argv"]
@pytest.mark.parametrize("extra,expected", [(["--api-only"], True), ([], False)])
diff --git a/unsloth_cli/tests/test_studio_secure_flag.py b/unsloth_cli/tests/test_studio_secure_flag.py
index 70f579a9bf5..19b3f8cfcbb 100644
--- a/unsloth_cli/tests/test_studio_secure_flag.py
+++ b/unsloth_cli/tests/test_studio_secure_flag.py
@@ -73,13 +73,15 @@ def _install_run_reexec_capture(monkeypatch):
captured = []
monkeypatch.setattr(sys, "prefix", "/nonexistent/outer/venv")
fake_venv = Path("/fake/studio/venv/unsloth_studio")
- monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_venv / "bin" / "python")
+ host_is_windows = studio_mod.platform.system() == "Windows"
+ fake_python = fake_venv / ("Scripts/python.exe" if host_is_windows else "bin/python")
+ monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_python)
# A built frontend dist is present so the public-launch UI check passes
# deterministically (independent of whether the repo dist was built).
monkeypatch.setattr(
studio_mod, "_find_frontend_dist", lambda: Path("/fake/studio/frontend/dist")
)
- fake_bin = fake_venv / "bin" / "unsloth"
+ fake_bin = fake_python.parent / ("unsloth.exe" if host_is_windows else "unsloth")
real_is_file = Path.is_file
monkeypatch.setattr(
Path,
@@ -93,6 +95,13 @@ def _install_run_reexec_capture(monkeypatch):
"resolve_tool_policy",
lambda host, flag, yes, silent: False if flag is None else bool(flag),
)
+ # This suite asserts what reaches the re-exec'd child's argv. The pre-exposure
+ # password gate is not part of that: on a headless launch it now rotates the
+ # admin password against the real STUDIO_HOME (which this helper does not
+ # isolate) and fails closed under CliRunner's non-tty streams. Neutralise it
+ # here; it has a dedicated suite in test_studio_password_prompt.py.
+ monkeypatch.setattr(studio_mod, "_enforce_password_change_before_exposure", lambda **_kw: None)
+
monkeypatch.setattr(sys, "platform", "linux")
def fake_execvp(file, argv):
@@ -130,6 +139,13 @@ def _invoke_studio_default(monkeypatch, args):
monkeypatch.setattr(
studio_mod, "_find_frontend_dist", lambda: Path("/fake/studio/frontend/dist")
)
+ # This suite asserts what reaches the re-exec'd child's argv. The pre-exposure
+ # password gate is not part of that: on a headless launch it now rotates the
+ # admin password against the real STUDIO_HOME (which this helper does not
+ # isolate) and fails closed under CliRunner's non-tty streams. Neutralise it
+ # here; it has a dedicated suite in test_studio_password_prompt.py.
+ monkeypatch.setattr(studio_mod, "_enforce_password_change_before_exposure", lambda **_kw: None)
+
monkeypatch.setattr(sys, "platform", "linux")
def fake_execvp(file, argv):
@@ -337,13 +353,15 @@ def test_run_secure_resolves_tools_against_loopback(monkeypatch):
studio_mod = _studio()
monkeypatch.setattr(sys, "prefix", "/nonexistent/outer/venv")
fake_venv = Path("/fake/studio/venv/unsloth_studio")
- monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_venv / "bin" / "python")
+ host_is_windows = studio_mod.platform.system() == "Windows"
+ fake_python = fake_venv / ("Scripts/python.exe" if host_is_windows else "bin/python")
+ monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: fake_python)
# A built frontend dist is present so the public-launch UI check passes
# deterministically (independent of whether the repo dist was built).
monkeypatch.setattr(
studio_mod, "_find_frontend_dist", lambda: Path("/fake/studio/frontend/dist")
)
- fake_bin = fake_venv / "bin" / "unsloth"
+ fake_bin = fake_python.parent / ("unsloth.exe" if host_is_windows else "unsloth")
real_is_file = Path.is_file
monkeypatch.setattr(
Path,
@@ -351,6 +369,9 @@ def test_run_secure_resolves_tools_against_loopback(monkeypatch):
lambda self: True if str(self) == str(fake_bin) else real_is_file(self),
)
monkeypatch.setattr(sys, "platform", "linux")
+ # Same reason as _install_run_reexec_capture: this asserts which host the tool
+ # policy is resolved against, not the pre-exposure password gate.
+ monkeypatch.setattr(studio_mod, "_enforce_password_change_before_exposure", lambda **_kw: None)
from unsloth_cli import _tool_policy as _tp_mod