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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Docker: print the Studio admin password in docker logs, add UNSLOTH_STUDIO_PASSWORD (#10344)
Daniel Han6816025b41fe
diff --git a/README.md b/README.mdindex f260e724c3a..029549e637a 100644--- a/README.md+++ b/README.md@@ -155,11 +155,11 @@ Use our [Docker image](https://hub.docker.com/r/unsloth/unsloth) ```unsloth/unsl```bashdocker run -d --gpus all --ipc=host \-p 8000:8000 -p 8888:8888 \- -e JUPYTER_PASSWORD="mypassword" \+ -e UNSLOTH_STUDIO_PASSWORD="mypassword" -e JUPYTER_PASSWORD="mypassword" \-v "$PWD":/workspace/host \unsloth/unsloth```-Studio is at `http://localhost:8000`, JupyterLab at `http://localhost:8888`. Tags (`unsloth/unsloth:core` for notebooks only), GPU support and options: [Docker Hub](https://hub.docker.com/r/unsloth/unsloth).+Follow startup with `docker logs -f`. Studio is at `http://localhost:8000` (user `unsloth`), JupyterLab at `http://localhost:8888`. Tags (`unsloth/unsloth:core` for notebooks only), GPU support and options: [Docker Hub](https://hub.docker.com/r/unsloth/unsloth).#### Remote HTTPS & LAN AccessServer-side tools are on by default - so **be careful**! Keep your password safe, or use `--disable-tools` when exposing Unsloth.diff --git a/docker/.dockerignore b/docker/.dockerignoreindex 18ff6a52eb6..1d759153e33 100644--- a/docker/.dockerignore+++ b/docker/.dockerignore@@ -5,6 +5,8 @@!fetch_llama_prebuilt.py!supervisord.conf!studio_launch.sh+!studio_password.sh+!studio_run.sh!unsloth_studio_update.sh!unsloth_llama_update.sh!unsloth_jupyter_tunnel.shdiff --git a/docker/DOCKERHUB.md b/docker/DOCKERHUB.mdindex d026153ae39..070cca211fc 100644--- a/docker/DOCKERHUB.md+++ b/docker/DOCKERHUB.md@@ -23,13 +23,14 @@ Requires the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/clouddocker run -d --gpus all --ipc=host \--ulimit memlock=-1 --ulimit stack=67108864 \-p 8000:8000 -p 8888:8888 \+ -e UNSLOTH_STUDIO_PASSWORD="choose-a-password" \-e JUPYTER_PASSWORD="choose-a-password" \-v "$PWD":/workspace/host \-v "$HOME/.cache/huggingface":/workspace/.cache/huggingface \unsloth/unsloth```-Then open Studio at `http://localhost:8000` and JupyterLab at `http://localhost:8888`. Studio prints its first-boot admin password in `docker logs <container>`. If `JUPYTER_PASSWORD` is not set, a random one is generated and printed there too.+`docker run -d` returns at once; follow the startup with `docker logs -f <container>`, which ends with a ready block once both services answer (Studio takes about a minute). Then open Studio at `http://localhost:8000` (user `unsloth`) and JupyterLab at `http://localhost:8888`. Leave either password variable unset and a random one is generated and printed in that log.The `docker/run.sh` helper in the repository sets these flags for you:@@ -90,6 +91,7 @@ Turing has no bfloat16; Unsloth falls back to float16 there. AMD GPUs are not su| Variable | Effect ||---|---|+| `UNSLOTH_STUDIO_PASSWORD` | Initial Studio admin password for user `unsloth`; ignored once a password is stored. Unset: generated once and printed in the logs, and Studio stops after an hour unless it is changed (`UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT=0` disables). || `JUPYTER_PASSWORD` | JupyterLab password. Unset: generated once and printed in the logs. || `JUPYTER_PORT` | JupyterLab port inside the container. Default `8888`. || `SSH_KEY` or `PUBLIC_KEY` | OpenSSH public key for root login. Enables sshd on port 22. Password login is never enabled. |diff --git a/docker/Dockerfile.studio b/docker/Dockerfile.studioindex 30c0b0dc151..11e49b8deb6 100644--- a/docker/Dockerfile.studio+++ b/docker/Dockerfile.studio@@ -9,9 +9,9 @@# docker run --rm --gpus all -p 8000:8000 -p 8888:8888 \# -v $HOME/.cache/huggingface:/workspace/.cache/huggingface unsloth/unsloth:studio#-# Studio on :8000 (first-boot admin password in the logs, persisted under-# /opt/unsloth-studio/auth/); JupyterLab on :8888 (JUPYTER_PASSWORD env, else a-# random one is printed). Without GPU passthrough add -e UNSLOTH_ALLOW_CPU=1:+# Studio on :8000 (user unsloth; UNSLOTH_STUDIO_PASSWORD env, else a generated one+# is printed in the logs; persisted under /opt/unsloth-studio/auth/); JupyterLab on+# :8888 (JUPYTER_PASSWORD env, else a random one is printed). Without GPU passthrough add -e UNSLOTH_ALLOW_CPU=1:# training is unavailable but Studio chat / Data Recipes / GGUF / Jupyter work.# CI pins BASE_IMAGE to the published base digest so both images ship the same stack.@@ -152,6 +152,8 @@ RUN set -eux \COPY supervisord.conf /etc/supervisor/supervisord.confCOPY studio_launch.sh /usr/local/bin/unsloth-studio-launch+COPY studio_password.sh /usr/local/bin/unsloth-studio-password+COPY studio_run.sh /usr/local/bin/unsloth-studio-run# In-place updaters (no image pull):# unsloth-studio-update refresh Studio packages (backend + frontend) and restart# unsloth-llama-update swap the baked llama.cpp prebuilt to the latest release@@ -207,6 +209,8 @@ RUN SP="$(/opt/unsloth-venv/bin/python -c 'import sysconfig; print(sysconfig.get&& rm -rf /tmp/unsloth-branding-guard \&& /opt/unsloth-venv/bin/python -m unsloth_branding --verifyRUN chmod +x /usr/local/bin/unsloth-studio-launch \+ /usr/local/bin/unsloth-studio-password \+ /usr/local/bin/unsloth-studio-run \/usr/local/bin/unsloth-studio-update \/usr/local/bin/unsloth-llama-update \/usr/local/bin/unsloth-jupyter-tunneldiff --git a/docker/run.sh b/docker/run.shindex f033941ae06..9941f147593 100755--- a/docker/run.sh+++ b/docker/run.sh@@ -110,6 +110,8 @@ declare -a ENV_FORWARD=(-e HF_HUB_ENABLE_HF_TRANSFER=1)[[ -n "${UNSLOTH_ALLOW_CPU:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_ALLOW_CPU)# read by studio_launch.sh; without these it uses a random password and no sshd[[ -n "${JUPYTER_PASSWORD:-}" ]] && ENV_FORWARD+=(-e JUPYTER_PASSWORD)+[[ -n "${UNSLOTH_STUDIO_PASSWORD:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_STUDIO_PASSWORD)+[[ -n "${UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT)[[ -n "${PUBLIC_KEY:-}" ]] && ENV_FORWARD+=(-e PUBLIC_KEY)[[ -n "${SSH_KEY:-}" ]] && ENV_FORWARD+=(-e SSH_KEY)[[ -n "${UNSLOTH_JUPYTER_CLOUDFLARE:-}" ]] && ENV_FORWARD+=(-e UNSLOTH_JUPYTER_CLOUDFLARE)diff --git a/docker/studio_launch.sh b/docker/studio_launch.shindex 3b157c8904d..ab9c4ed9c3a 100644--- a/docker/studio_launch.sh+++ b/docker/studio_launch.sh@@ -2,7 +2,8 @@# Default CMD of the full Unsloth image (Dockerfile.studio).## Bootstraps the three services managed by supervisord:-# studio port 8000 first-boot admin password printed in `docker logs`+# studio port 8000 user unsloth; password from UNSLOTH_STUDIO_PASSWORD, or+# the generated one printed in `docker logs` (studio-password)# jupyter port 8888 password from JUPYTER_PASSWORD, or a random one# printed in `docker logs` when unset# sshd port 22 key-only; enabled when PUBLIC_KEY / SSH_KEY is set@@ -10,6 +11,8 @@# Environment:# JUPYTER_PORT Jupyter port inside the container (default 8888)# JUPYTER_PASSWORD Jupyter login password (unset: generated and printed)+# UNSLOTH_STUDIO_PASSWORD initial Studio admin password (unset: generated and+# printed); ignored once a password is stored# PUBLIC_KEY/SSH_KEY OpenSSH public key for root login; sshd stays disabled# when neither is set (nothing to authenticate with --# password login is never enabled for root)@@ -104,7 +107,28 @@ if [[ "${UNSLOTH_SKIP_BRANDING_CHECK:-0}" != "1" ]]; thenfifi-echo "Unsloth Studio -> http://localhost:8000 (first-boot password below)"+export UNSLOTH_JUPYTER_NOTE="${JUPYTER_NOTE}" # for the ready summary (studio-password)+# UNSLOTH_STUDIO_PASSWORD only sets the initial admin password, and `unsloth studio`+# exits 1 when handed one after that. So it goes to a root-only file that+# unsloth-studio-run consumes while nothing is stored, and never into supervisord's+# environment, where every respawn of the studio program would see it again.+INITIAL_FILE="${UNSLOTH_STUDIO_INITIAL_PASSWORD_FILE:-/run/unsloth/studio-initial-password}"+rm -f "$INITIAL_FILE"+if unsloth-studio-run --stored; then+ STUDIO_NOTE="user unsloth, password set on an earlier boot"+ UNSLOTH_STUDIO_PASSWORD_STATE=stored+elif [[ -n "${UNSLOTH_STUDIO_PASSWORD:-}" ]]; then+ mkdir -p "$(dirname "$INITIAL_FILE")"+ (umask 077 && printf '%s' "$UNSLOTH_STUDIO_PASSWORD" > "$INITIAL_FILE")+ STUDIO_NOTE="user unsloth, password from UNSLOTH_STUDIO_PASSWORD env"+ UNSLOTH_STUDIO_PASSWORD_STATE=initial+else+ STUDIO_NOTE="user unsloth, generated password printed below once Studio is up"+ UNSLOTH_STUDIO_PASSWORD_STATE=generated+fi+unset UNSLOTH_STUDIO_PASSWORD+export UNSLOTH_STUDIO_PASSWORD_STATE # read by unsloth-studio-password+echo "Unsloth Studio -> http://localhost:8000 (${STUDIO_NOTE})"echo "JupyterLab -> http://localhost:${JUPYTER_PORT} (${JUPYTER_NOTE})"if [[ "${UNSLOTH_JUPYTER_CLOUDFLARE}" == "1" ]]; thenecho "JupyterLab tunnel-> enabled; public trycloudflare URL appears below once it is up"diff --git a/docker/studio_password.sh b/docker/studio_password.shnew file mode 100755index 00000000000..3d940da49be--- /dev/null+++ b/docker/studio_password.sh@@ -0,0 +1,109 @@+#!/usr/bin/env bash+# One-shot supervisord program (studio-password): prints how to sign in to Studio,+# then a ready summary once Studio and JupyterLab answer. Studio itself only writes+# the generated first-boot password to a file, so without this the log names the+# file and nothing else, and nothing marks the point where the container is usable.+#+# Environment:+# UNSLOTH_STUDIO_PASSWORD_STATE from the launcher: initial | stored | generated+# UNSLOTH_STUDIO_HOME where Studio keeps auth/ (default /opt/unsloth-studio)+# UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT Studio's own change-it-or-shut-down window, seconds+# UNSLOTH_STUDIO_PASSWORD_WAIT how long to wait for the file, seconds (default 600)+# UNSLOTH_STUDIO_READY_WAIT how long to wait for both services, seconds (default 900)+# JUPYTER_PORT, UNSLOTH_JUPYTER_NOTE from the launcher, for the summary+set -euo pipefail++AUTH_DIR="${UNSLOTH_STUDIO_HOME:-/opt/unsloth-studio}/auth"+FILE="${AUTH_DIR}/.bootstrap_password"+WAIT="${UNSLOTH_STUDIO_PASSWORD_WAIT:-600}"+READY_WAIT="${UNSLOTH_STUDIO_READY_WAIT:-900}"+JUPYTER_PORT="${JUPYTER_PORT:-8888}"+STATE="${UNSLOTH_STUDIO_PASSWORD_STATE:-}"+[[ -z "$STATE" && -n "${UNSLOTH_STUDIO_PASSWORD:-}" ]] && STATE=initial++# Same rules as studio/backend/auth/bootstrap_timeout.py: unset, blank or malformed+# means the 3600 s default (a typo must not hide the note), 0 or negative disables.+# Only the surrounding whitespace is stripped, as int() does: "- 5" is malformed,+# "1_000" is 1000 (single underscores between digits).+raw="${UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT:-}"+raw="${raw#"${raw%%[![:space:]]*}"}"+raw="${raw%"${raw##*[![:space:]]}"}"+if [[ "$raw" =~ ^[+-]?[0-9]+(_[0-9]+)*$ ]]; then+ digits="${raw#[+-]}"+ digits="${digits//_/}"+ if [[ "$raw" == -* ]]; then TIMEOUT=0; else TIMEOUT=$(( 10#$digits )); fi+else+ TIMEOUT=3600+fi++# Mirrors _format_duration there: seconds under a minute, else minutes and a remainder.+plural() { echo "$1 $2$([[ "$1" == 1 ]] || echo s)"; }+duration() {+ local s=$1+ if (( s < 60 )); then plural "$s" second; return; fi+ local text; text="$(plural $(( s / 60 )) minute)"+ (( s % 60 )) && text="$text $(plural $(( s % 60 )) second)"+ echo "$text"+}++case "$STATE" in+ initial)+ STUDIO_LINE="username: unsloth password: from UNSLOTH_STUDIO_PASSWORD" ;;+ stored)+ STUDIO_LINE="username: unsloth password: already set on an earlier boot (inside the container: unsloth studio reset-password)" ;;+ *)+ deadline=$(( $(date +%s) + WAIT ))+ STUDIO_LINE=""+ # The file alone is not enough: the CLI writes it before committing the admin+ # row, so a launch interrupted between the two leaves a file the next launch+ # replaces. Wait for the row, and read the file after it.+ while [[ ! -s "$FILE" ]] || ! unsloth-studio-run --initialized; do+ if (( $(date +%s) >= deadline )); then+ STUDIO_LINE="the first-boot password did not appear in ${WAIT}s; check the studio log above"+ break+ fi+ sleep 1+ done+ if [[ -z "$STUDIO_LINE" ]]; then+ # LF-terminated on every OS; strip only that, a password may end in a space+ password="$(tr -d '\r\n' < "$FILE")"+ note=""+ if (( TIMEOUT > 0 )); then+ note=" (change it on first sign-in: Studio stops after $(duration "$TIMEOUT") with the default password; UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT=0 disables)"+ fi+ STUDIO_LINE="username: unsloth password: ${password}${note}"+ fi ;;+esac+echo "Unsloth Studio login -> ${STUDIO_LINE}"++# The summary waits for real answers: Studio's socket opens before torch is loaded,+# and /api/health only turns 200 once the app is serving.+studio_ok=""; jupyter_ok=""+deadline=$(( $(date +%s) + READY_WAIT ))+while :; do+ if [[ -z "$studio_ok" ]] && curl -sf -o /dev/null --max-time 3 http://127.0.0.1:8000/api/health; then+ studio_ok=1+ fi+ if [[ -z "$jupyter_ok" ]] && curl -sf -o /dev/null --max-time 3 "http://127.0.0.1:${JUPYTER_PORT}/login"; then+ jupyter_ok=1+ fi+ { [[ -n "$studio_ok" && -n "$jupyter_ok" ]] || (( $(date +%s) >= deadline )); } && break+ sleep 2+done++if [[ -n "$studio_ok" && -n "$jupyter_ok" ]]; then+ title="Unsloth container ready"+else+ title="Unsloth container: startup incomplete after ${READY_WAIT}s, see the log above"+fi+studio_text="not answering"+[[ -n "$studio_ok" ]] && studio_text="$STUDIO_LINE"+jupyter_text="not answering"+[[ -n "$jupyter_ok" ]] && jupyter_text="${UNSLOTH_JUPYTER_NOTE:-password from JUPYTER_PASSWORD env}"+rule="$(printf '=%.0s' $(seq 1 72))"+echo "$rule"+echo " ${title}"+echo " Studio http://localhost:8000 ${studio_text}"+echo " JupyterLab http://localhost:${JUPYTER_PORT} ${jupyter_text}"+echo " Ports are the container's: use the host side of your -p flags, or an SSH tunnel to a remote host."+echo "$rule"diff --git a/docker/studio_run.sh b/docker/studio_run.shnew file mode 100644index 00000000000..8efebc02296--- /dev/null+++ b/docker/studio_run.sh@@ -0,0 +1,72 @@+#!/usr/bin/env bash+# supervisord's studio program. Applies the initial admin password only while none+# is stored: `unsloth studio` exits 1 when handed one afterwards, so a restart of the+# program (crash, unsloth-studio-update, docker restart) would park Studio in FATAL.+# The launcher leaves the value in a root-only file, never in supervisord's+# environment, and this decides at every spawn.+#+# unsloth-studio-run start Studio+# unsloth-studio-run --stored exit 0 when an admin password is stored+# unsloth-studio-run --initialized exit 0 when the admin row is committed+set -euo pipefail++STUDIO_HOME="${UNSLOTH_STUDIO_HOME:-/opt/unsloth-studio}"+INITIAL="${UNSLOTH_STUDIO_INITIAL_PASSWORD_FILE:-/run/unsloth/studio-initial-password}"++admin_initialized() {+ # The bootstrap file is written before the admin row commits, so an interrupted+ # first launch can leave a file whose password the next launch replaces.+ python3 - "${STUDIO_HOME}/auth/auth.db" <<'PY'+import sqlite3, sys+from urllib.parse import quote+try:+ # quoted: a ? or # in the path would otherwise end the URI early and point+ # both checks at a database that does not exist; read-only so a missing+ # auth.db is never created here+ conn = sqlite3.connect(f"file:{quote(sys.argv[1])}?mode=ro", uri = True)+ row = conn.execute("SELECT 1 FROM auth_user WHERE username = 'unsloth'").fetchone()+except sqlite3.Error:+ row = None+sys.exit(0 if row is not None else 1)+PY+}++password_stored() {+ # The admin row with must_change_password=0. A bare auth.db from an interrupted+ # first launch, or a seeded row nobody changed, still accepts an initial password.+ # A row from before that column existed counts as stored: the CLI migrates it+ # with default 0 and then rejects an initial password.+ python3 - "${STUDIO_HOME}/auth/auth.db" <<'PY'+import sqlite3, sys+from urllib.parse import quote+try:+ # quoted: a ? or # in the path would otherwise end the URI early and point+ # both checks at a database that does not exist; read-only so a missing+ # auth.db is never created here+ conn = sqlite3.connect(f"file:{quote(sys.argv[1])}?mode=ro", uri = True)+ row = conn.execute("SELECT 1 FROM auth_user WHERE username = 'unsloth'").fetchone()+ if row is not None:+ cols = {r[1] for r in conn.execute("PRAGMA table_info(auth_user)")}+ if "must_change_password" in cols:+ row = conn.execute(+ "SELECT must_change_password FROM auth_user WHERE username = 'unsloth'"+ ).fetchone()+ row = None if row is None or row[0] else row+except sqlite3.Error:+ row = None+sys.exit(0 if row is not None else 1)+PY+}++case "${1:-}" in+ --stored) if password_stored; then exit 0; else exit 1; fi ;;+ --initialized) if admin_initialized; then exit 0; else exit 1; fi ;;+esac++unset UNSLOTH_STUDIO_PASSWORD+if [[ -s "$INITIAL" ]] && ! password_stored; then+ # byte for byte: $(<file) would drop a trailing newline the CLI is meant to see+ IFS= read -r -d '' UNSLOTH_STUDIO_PASSWORD < "$INITIAL" || true+ export UNSLOTH_STUDIO_PASSWORD+fi+exec "${STUDIO_HOME}/bin/unsloth" studio -H 0.0.0.0 -p 8000diff --git a/docker/supervisord.conf b/docker/supervisord.confindex 9f7b5e7579f..7d01f1e407f 100644--- a/docker/supervisord.conf+++ b/docker/supervisord.conf@@ -3,8 +3,8 @@# jupyter JupyterLab for the notebooks port $JUPYTER_PORT (default 8888)# sshd key-only SSH for cloud hosts port 22#-# All three log to stdout/stderr so `docker logs` shows Studio's first-boot password-# and Jupyter's startup line.+# All log to stdout/stderr so `docker logs` shows Jupyter's startup line and, via the+# one-shot studio-password program, the Studio admin password.[unix_http_server]file=/run/supervisor.sock@@ -24,10 +24,16 @@ logfile_maxbytes=0loglevel=info[program:studio]-command=%(ENV_UNSLOTH_STUDIO_HOME)s/bin/unsloth studio -H 0.0.0.0 -p 8000+; the wrapper applies the initial password only while none is stored, so respawns+; (crash, unsloth-studio-update, docker restart) never hand the CLI a rejected one+command=/usr/local/bin/unsloth-studio-rundirectory=/workspaceautostart=true-autorestart=true+; a clean exit (0) stays down: that is the bootstrap timeout shutting Studio off+; because the default password was never changed, or /api/shutdown; a restart would+; hand out the same credential with a fresh timer. Crashes still restart.+autorestart=unexpected+exitcodes=0startretries=3startsecs=5environment=HOME="/root",USER="root"@@ -36,6 +42,19 @@ stdout_logfile_maxbytes=0stderr_logfile=/dev/stderrstderr_logfile_maxbytes=0+; One shot: prints the Studio admin credential once Studio has written it.+[program:studio-password]+command=/usr/local/bin/unsloth-studio-password+autostart=true+autorestart=false+startsecs=0+exitcodes=0+environment=HOME="/root",USER="root"+stdout_logfile=/dev/stdout+stdout_logfile_maxbytes=0+stderr_logfile=/dev/stderr+stderr_logfile_maxbytes=0+[program:jupyter]command=jupyter lab --no-browser --ip=0.0.0.0 --port=%(ENV_JUPYTER_PORT)s --allow-root --notebook-dir=/workspacedirectory=/workspacediff --git a/tests/python/test_docker_hub_readme.py b/tests/python/test_docker_hub_readme.pyindex 20bd5a23cc7..b66156ad4d0 100644--- a/tests/python/test_docker_hub_readme.py+++ b/tests/python/test_docker_hub_readme.py@@ -35,10 +35,18 @@ def test_the_hub_readme_describes_the_shipped_images():"/workspace/host","/workspace/.cache/huggingface","sm_75 sm_80 sm_86 sm_90 sm_100 sm_120",+ "UNSLOTH_STUDIO_PASSWORD",):assert needle in text, f"the Hub README no longer mentions {needle!r}"# the previous image's conventions, none of which exist in this one- for stale in ("USER_PASSWORD", "/workspace/work", "2222:22", "localhot"):+ # Studio writes the generated password to a file and does not print it itself+ for stale in (+ "USER_PASSWORD",+ "/workspace/work",+ "2222:22",+ "localhot",+ "prints its first-boot",+ ):assert stale not in text, f"the Hub README still carries {stale!r} from the old image"diff --git a/tests/python/test_docker_studio_password_banner.py b/tests/python/test_docker_studio_password_banner.pynew file mode 100644index 00000000000..e1ac9d37d63--- /dev/null+++ b/tests/python/test_docker_studio_password_banner.py@@ -0,0 +1,471 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-Present the Unsloth team. See /studio/LICENSE.AGPL-3.0++"""`docker logs` must show how to sign in to Studio, and a preset password must+survive restarts.++Studio writes its generated first-boot password to a file and prints only the+path, so a launcher banner saying "password below" left users with nothing to+type. The one-shot `studio-password` supervisord program prints the credential+once the file exists, or says why there is none, then a ready block once both+services answer. `unsloth studio` exits 1 when handed an initial password after+one is stored, so `unsloth-studio-run` applies UNSLOTH_STUDIO_PASSWORD only while+nothing is stored and the launcher keeps it out of supervisord's environment.+These run the shipped scripts against a fake Studio home.+"""++from __future__ import annotations++import os+import shutil+import sqlite3+import subprocess+import threading+import time+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+DOCKER = REPO_ROOT / "docker"+SCRIPT = DOCKER / "studio_password.sh"+RUN = DOCKER / "studio_run.sh"+LAUNCH = DOCKER / "studio_launch.sh"+SUPERVISORD = DOCKER / "supervisord.conf"+DOCKERFILE = DOCKER / "Dockerfile.studio"++behavioural = pytest.mark.skipif(shutil.which("bash") is None, reason = "needs bash")+++def _stub(bin_dir: Path, name: str, body: str) -> None:+ bin_dir.mkdir(exist_ok = True)+ path = bin_dir / name+ path.write_text("#!/usr/bin/env bash\n" + body, encoding = "utf-8")+ path.chmod(0o755)+++def _clean_env(bin_dir: Path) -> dict:+ e = {k: v for k, v in os.environ.items() if not k.startswith("UNSLOTH_STUDIO")}+ e["PATH"] = f"{bin_dir}{os.pathsep}" + e["PATH"]+ return e+++def _auth_db(+ home: Path,+ *,+ must_change: int | None,+ legacy: bool = False,+) -> None:+ """auth.db as the backend creates it; None = the file exists but no admin row;+ legacy = the schema from before must_change_password existed."""+ auth = home / "auth"+ auth.mkdir(exist_ok = True)+ conn = sqlite3.connect(auth / "auth.db")+ conn.execute(+ "CREATE TABLE IF NOT EXISTS auth_user (id INTEGER PRIMARY KEY, username TEXT UNIQUE NOT NULL, "+ "password_salt TEXT NOT NULL, password_hash TEXT NOT NULL, jwt_secret TEXT NOT NULL"+ + (")" if legacy else ", must_change_password INTEGER NOT NULL DEFAULT 0)")+ )+ if legacy:+ conn.execute(+ "INSERT INTO auth_user (username, password_salt, password_hash, jwt_secret) "+ "VALUES ('unsloth', 's', 'h', 'j')"+ )+ elif must_change is not None:+ conn.execute(+ "INSERT INTO auth_user (username, password_salt, password_hash, jwt_secret, must_change_password) "+ "VALUES ('unsloth', 's', 'h', 'j', ?)",+ (must_change,),+ )+ conn.commit()+ conn.close()+++# --- studio-password: the login line and the ready summary -----------------------+++def _run(+ home: Path,+ *,+ env: dict | None = None,+ wait: str = "3",+ services_up: bool = True,+) -> subprocess.CompletedProcess:+ """Run the shipped script against *home*, with curl stubbed: the ready probes+ must never reach a real Studio on the test host."""+ bin_dir = home / "stub-bin"+ _stub(bin_dir, "curl", "exit 0\n" if services_up else "exit 7\n")+ # the admin row is "committed" unless the test parks a not-initialized marker+ _stub(+ bin_dir, "unsloth-studio-run", f'[[ -e "{home / "not-initialized"}" ]] && exit 1\nexit 0\n'+ )+ e = _clean_env(bin_dir)+ e.update(+ UNSLOTH_STUDIO_HOME = str(home),+ UNSLOTH_STUDIO_PASSWORD_WAIT = wait,+ UNSLOTH_STUDIO_READY_WAIT = "2",+ )+ e.update(env or {})+ return subprocess.run(["bash", str(SCRIPT)], capture_output = True, text = True, env = e, timeout = 60)+++@behavioural+def test_the_generated_password_is_printed_once_studio_writes_it(tmp_path: Path):+ auth = tmp_path / "auth"+ auth.mkdir()++ def _studio_writes_it_later():+ time.sleep(1.0)+ (auth / ".bootstrap_password").write_bytes(b"s3cret pass\n")++ threading.Thread(target = _studio_writes_it_later).start()+ res = _run(tmp_path, env = {"UNSLOTH_STUDIO_PASSWORD_STATE": "generated"})+ assert res.returncode == 0, res.stderr+ assert "username: unsloth" in res.stdout+ assert "password: s3cret pass" in res.stdout, res.stdout+ assert "60 minutes" in res.stdout, "the change-it-or-shut-down window is not explained"+ assert "Unsloth container ready" in res.stdout+ assert (+ "Studio http://localhost:8000 username: unsloth password: s3cret pass"+ in res.stdout+ )+++@behavioural+def test_a_stale_file_from_an_interrupted_launch_is_not_printed(tmp_path: Path):+ """The CLI writes the bootstrap file before committing the admin row. A launch+ interrupted between the two leaves a file whose password the next launch+ replaces, so the file is read only once the row exists."""+ auth = tmp_path / "auth"+ auth.mkdir()+ (auth / ".bootstrap_password").write_bytes(b"stale one\n")+ (tmp_path / "not-initialized").touch()++ def _next_launch_replaces_it():+ time.sleep(1.2)+ (auth / ".bootstrap_password").write_bytes(b"fresh one\n")+ (tmp_path / "not-initialized").unlink()++ threading.Thread(target = _next_launch_replaces_it).start()+ res = _run(tmp_path, env = {"UNSLOTH_STUDIO_PASSWORD_STATE": "generated"}, wait = "10")+ assert "password: fresh one" in res.stdout, res.stdout+ assert "stale one" not in res.stdout+++@behavioural+def test_the_summary_carries_the_jupyter_note_and_port(tmp_path: Path):+ res = _run(+ tmp_path,+ env = {+ "UNSLOTH_STUDIO_PASSWORD_STATE": "initial",+ "JUPYTER_PORT": "9999",+ "UNSLOTH_JUPYTER_NOTE": "generated password: abc123",+ },+ )+ assert (+ "JupyterLab http://localhost:9999 generated password: abc123" in res.stdout+ ), res.stdout+ assert res.stdout.rstrip().endswith("=" * 72)+++@behavioural+def test_services_that_never_answer_are_reported_not_hidden(tmp_path: Path):+ res = _run(tmp_path, env = {"UNSLOTH_STUDIO_PASSWORD_STATE": "initial"}, services_up = False)+ assert res.returncode == 0+ assert "startup incomplete" in res.stdout, res.stdout+ assert res.stdout.count("not answering") == 2+++@behavioural+def test_a_crlf_file_does_not_leak_the_cr_into_the_credential(tmp_path: Path):+ auth = tmp_path / "auth"+ auth.mkdir()+ (auth / ".bootstrap_password").write_bytes(b"abc\r\n")+ res = _run(tmp_path)+ assert "password: abc (" in res.stdout, repr(res.stdout)+++@behavioural[email protected]("value", ["0", "-5", " -1 "])+def test_a_disabled_timeout_drops_the_shutdown_note(tmp_path: Path, value: str):+ auth = tmp_path / "auth"+ auth.mkdir()+ (auth / ".bootstrap_password").write_bytes(b"abc\n")+ res = _run(tmp_path, env = {"UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT": value})+ assert "Unsloth Studio login -> username: unsloth password: abc\n" in res.stdout, repr(+ res.stdout+ )+ assert "change it on first sign-in" not in res.stdout+++@behavioural[email protected]("value", ["abc", "", " ", "1.5", "- 5", "1 000"])+def test_a_malformed_timeout_keeps_the_note_like_the_backend_does(tmp_path: Path, value: str):+ """bootstrap_timeout.py strips only the surrounding whitespace and falls back+ to 3600 on a typo rather than disabling, so Studio still stops after an hour;+ the note must not vanish. "- 5" and "1 000" are typos, not numbers."""+ auth = tmp_path / "auth"+ auth.mkdir()+ (auth / ".bootstrap_password").write_bytes(b"abc\n")+ res = _run(tmp_path, env = {"UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT": value})+ assert "60 minutes" in res.stdout, repr(res.stdout)+++@behavioural+ ("value", "text"),+ [+ ("+0900", "15 minutes"),+ ("30", "30 seconds"),+ ("90", "1 minute 30 seconds"),+ ("61", "1 minute 1 second"),+ ("1_000", "16 minutes 40 seconds"),+ ],+)+def test_the_timeout_is_reported_like_the_backend_formats_it(tmp_path: Path, value: str, text: str):+ auth = tmp_path / "auth"+ auth.mkdir()+ (auth / ".bootstrap_password").write_bytes(b"abc\n")+ res = _run(tmp_path, env = {"UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT": value})+ assert f"stops after {text} with" in res.stdout, repr(res.stdout)+++@behavioural+def test_an_initial_password_is_never_echoed(tmp_path: Path):+ res = _run(+ tmp_path,+ env = {+ "UNSLOTH_STUDIO_PASSWORD_STATE": "initial",+ "UNSLOTH_STUDIO_PASSWORD": "hunter22hunter",+ },+ )+ assert res.returncode == 0+ assert "hunter22hunter" not in res.stdout+ assert "from UNSLOTH_STUDIO_PASSWORD" in res.stdout+++@behavioural+def test_a_stored_password_is_reported_at_once(tmp_path: Path):+ started = time.monotonic()+ res = _run(tmp_path, env = {"UNSLOTH_STUDIO_PASSWORD_STATE": "stored"}, wait = "600")+ assert time.monotonic() - started < 20+ assert "already set on an earlier boot" in res.stdout, res.stdout+ assert "reset-password" in res.stdout+++# --- unsloth-studio-run: the initial password is applied only while none is stored+++def _run_wrapper(+ home: Path,+ *,+ args: list[str] = (),+ env: dict | None = None,+) -> subprocess.CompletedProcess:+ bin_dir = home / "bin"+ # what supervisord would spawn: prints what the CLI would have been handed+ _stub(bin_dir, "unsloth", 'printf "%s|%s\\n" "${UNSLOTH_STUDIO_PASSWORD:-<unset>}" "$*"\n')+ e = _clean_env(home / "stub-bin")+ (home / "stub-bin").mkdir(exist_ok = True)+ e["UNSLOTH_STUDIO_HOME"] = str(home)+ e["UNSLOTH_STUDIO_INITIAL_PASSWORD_FILE"] = str(home / "initial")+ e.update(env or {})+ return subprocess.run(+ ["bash", str(RUN), *args], capture_output = True, text = True, env = e, timeout = 60+ )+++@behavioural+ ("db", "stored"),+ [("none", False), ("empty", False), ("seeded", False), ("changed", True), ("legacy", True)],+)+def test_stored_means_an_admin_row_whose_password_was_changed(+ tmp_path: Path, db: str, stored: bool+):+ """A bare auth.db from an interrupted first launch, or a seeded row nobody+ changed, still accepts an initial password; only must_change_password=0 is+ "stored"."""+ if db == "empty":+ _auth_db(tmp_path, must_change = None)+ elif db == "seeded":+ _auth_db(tmp_path, must_change = 1)+ elif db == "changed":+ _auth_db(tmp_path, must_change = 0)+ elif db == "legacy":+ # the CLI migrates this row with default 0 and then rejects an initial password+ _auth_db(tmp_path, must_change = None, legacy = True)+ res = _run_wrapper(tmp_path, args = ["--stored"])+ assert (res.returncode == 0) is stored, res.stderr+++@behavioural+ ("db", "initialized"),+ [("none", False), ("empty", False), ("seeded", True), ("changed", True), ("legacy", True)],+)+def test_initialized_means_the_admin_row_is_committed(tmp_path: Path, db: str, initialized: bool):+ if db == "empty":+ _auth_db(tmp_path, must_change = None)+ elif db == "seeded":+ _auth_db(tmp_path, must_change = 1)+ elif db == "changed":+ _auth_db(tmp_path, must_change = 0)+ elif db == "legacy":+ _auth_db(tmp_path, must_change = None, legacy = True)+ res = _run_wrapper(tmp_path, args = ["--initialized"])+ assert (res.returncode == 0) is initialized, res.stderr+++@behavioural+def test_a_home_with_uri_characters_still_finds_the_database(tmp_path: Path):+ """The read-only open goes through SQLite's URI syntax, where an unquoted ? or #+ in the path ends the filename early and both checks then see no database."""+ home = tmp_path / "studio?x#y"+ home.mkdir()+ _auth_db(home, must_change = 0)+ assert _run_wrapper(home, args = ["--stored"]).returncode == 0+ assert _run_wrapper(home, args = ["--initialized"]).returncode == 0+++@behavioural+def test_the_first_spawn_applies_the_initial_password(tmp_path: Path):+ (tmp_path / "initial").write_text("hunter22hunter", encoding = "utf-8")+ res = _run_wrapper(tmp_path)+ assert res.stdout.strip() == "hunter22hunter|studio -H 0.0.0.0 -p 8000", res.stdout + res.stderr+++@behavioural+def test_a_respawn_after_the_password_is_stored_gets_no_initial_password(tmp_path: Path):+ """The file is still there (the launcher writes it once per boot) and even a+ stray UNSLOTH_STUDIO_PASSWORD in the environment must not reach the CLI."""+ (tmp_path / "initial").write_text("hunter22hunter", encoding = "utf-8")+ _auth_db(tmp_path, must_change = 0)+ res = _run_wrapper(tmp_path, env = {"UNSLOTH_STUDIO_PASSWORD": "hunter22hunter"})+ assert res.stdout.strip() == "<unset>|studio -H 0.0.0.0 -p 8000", res.stdout + res.stderr+++@behavioural+def test_a_respawn_while_the_seeded_password_is_still_active_retries_it(tmp_path: Path):+ (tmp_path / "initial").write_text("hunter22hunter", encoding = "utf-8")+ _auth_db(tmp_path, must_change = 1)+ res = _run_wrapper(tmp_path)+ assert res.stdout.startswith("hunter22hunter|"), res.stdout + res.stderr+++@behavioural+def test_the_staged_password_reaches_the_cli_byte_for_byte(tmp_path: Path):+ """A secret injector may append a newline; the CLI, not the wrapper, decides what+ to make of it."""+ (tmp_path / "initial").write_text("hunter22\n", encoding = "utf-8")+ res = _run_wrapper(tmp_path)+ assert res.stdout == "hunter22\n|studio -H 0.0.0.0 -p 8000\n", repr(res.stdout)+++@behavioural+def test_no_file_means_no_initial_password(tmp_path: Path):+ res = _run_wrapper(tmp_path, env = {"UNSLOTH_STUDIO_PASSWORD": "hunter22hunter"})+ assert res.stdout.startswith("<unset>|"), res.stdout + res.stderr+++# --- the launcher: where the initial password goes -------------------------------+++def _launcher_banner_block() -> str:+ """The banner decision, verbatim from studio_launch.sh."""+ source = LAUNCH.read_text(encoding = "utf-8")+ start = source.index("INITIAL_FILE=")+ end = source.index('echo "Unsloth Studio ->', start)+ return source[start:end]+++def _banner(tmp_path: Path, *, env_password: str | None, stored: bool) -> dict:+ bin_dir = tmp_path / "stub-bin"+ _stub(+ bin_dir,+ "unsloth-studio-run",+ f'[[ "$1" == --stored ]] && exit {0 if stored else 1}\nexit 0\n',+ )+ initial = tmp_path / "run" / "initial"+ script = (+ "set -euo pipefail\n"+ + _launcher_banner_block()+ + 'printf "%s\\n%s\\n%s\\n" "$STUDIO_NOTE" "${UNSLOTH_STUDIO_PASSWORD:-<unset>}" "$UNSLOTH_STUDIO_PASSWORD_STATE"\n'+ )+ env = _clean_env(bin_dir)+ env["UNSLOTH_STUDIO_HOME"] = str(tmp_path)+ env["UNSLOTH_STUDIO_INITIAL_PASSWORD_FILE"] = str(initial)+ if env_password is not None:+ env["UNSLOTH_STUDIO_PASSWORD"] = env_password+ res = subprocess.run(+ ["bash", "-c", script], capture_output = True, text = True, env = env, timeout = 30+ )+ assert res.returncode == 0, res.stderr+ note, inherited, state = res.stdout.rstrip("\n").split("\n")+ return {+ "note": note,+ "inherited": inherited,+ "state": state,+ "file": initial.read_text(encoding = "utf-8") if initial.exists() else None,+ "mode": (initial.stat().st_mode & 0o777) if initial.exists() else None,+ }+++@behavioural+def test_the_initial_password_goes_to_a_private_file_not_supervisord(tmp_path: Path):+ """supervisord keeps its environment for every respawn of the studio program,+ and `unsloth studio` exits 1 when handed an initial password after one is+ stored; a crash or unsloth-studio-update restart then parked Studio in FATAL."""+ got = _banner(tmp_path, env_password = "hunter22hunter", stored = False)+ assert got["inherited"] == "<unset>"+ assert got["file"] == "hunter22hunter"+ assert got["mode"] == 0o600+ assert got["state"] == "initial"+ assert "from UNSLOTH_STUDIO_PASSWORD" in got["note"]+++@behavioural+def test_a_stored_password_wins_over_the_env(tmp_path: Path):+ got = _banner(tmp_path, env_password = "hunter22hunter", stored = True)+ assert got["inherited"] == "<unset>"+ assert got["file"] is None+ assert got["state"] == "stored"+ assert "set on an earlier boot" in got["note"]+++@behavioural+def test_a_fresh_home_without_the_env_generates(tmp_path: Path):+ got = _banner(tmp_path, env_password = None, stored = False)+ assert got["inherited"] == "<unset>"+ assert got["file"] is None+ assert got["state"] == "generated"+ assert "generated password printed below" in got["note"]+++def test_the_image_wires_the_scripts_in():+ conf = SUPERVISORD.read_text(encoding = "utf-8")+ assert "[program:studio-password]" in conf+ block = conf.split("[program:studio-password]", 1)[1].split("[program:", 1)[0]+ assert "autorestart=false" in block and "stdout_logfile=/dev/stdout" in block+ studio = conf.split("[program:studio]", 1)[1].split("[program:", 1)[0]+ assert "command=/usr/local/bin/unsloth-studio-run" in studio+ # the bootstrap timeout ends Studio with exit 0; autorestart=true would bring it+ # straight back with the same default credential and a fresh timer+ assert "autorestart=unexpected" in studio and "exitcodes=0" in studio+ dockerfile = DOCKERFILE.read_text(encoding = "utf-8")+ # the Studio build uses context ./docker behind a deny-all .dockerignore+ allow = (DOCKER / ".dockerignore").read_text(encoding = "utf-8").splitlines()+ for script, target in (+ ("studio_password.sh", "unsloth-studio-password"),+ ("studio_run.sh", "unsloth-studio-run"),+ ):+ assert f"COPY {script} /usr/local/bin/{target}" in dockerfile+ assert (+ f"/usr/local/bin/{target}" in dockerfile.split("RUN chmod +x", 1)[1].split("\n\n", 1)[0]+ )+ assert f"!{script}" in allow, f"COPY {script} has no source in the build context"+ launch = LAUNCH.read_text(encoding = "utf-8")+ assert (+ "first-boot password below" not in launch+ ), "the banner promises what Studio no longer prints"+ assert "unset UNSLOTH_STUDIO_PASSWORD" in launch