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
Studio: reuse the named CLI API key across studio run (#10608)
Chaitanya Laxman1b0a2e4197a0
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 3e25ad9f3eb..603ffd7ee4f 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -114,6 +114,8 @@ def _ensure_studio_env_exported() -> None:BOOTSTRAP_PASSWORD_FILE = ".bootstrap_password"DESKTOP_SECRET_FILE = ".desktop_secret"+# Cached raw CLI API key; the full name carries a digest: ".cli_api_key_cli_<digest>".+CLI_API_KEY_FILE_PREFIX = ".cli_api_key_"DEFAULT_ADMIN_USERNAME = "unsloth"DESKTOP_SECRET_PREFIX = "desktop-"API_KEY_PBKDF2_SALT_KEY = "api_key_pbkdf2_salt"@@ -681,15 +683,56 @@ def _wait_for_server(return False+def _cli_api_key_secret_path(name: str) -> Path:+ """Cache path for the raw API key named *name*.++ Identity is the digest; the stem is only so a human can tell the files apart.+ Sharing a stem would hand one label's credential to another (`foo/bar` vs+ `foo?bar`, past the 64-char cut, `cli` vs `CLI` on APFS/NTFS). ASCII-only+ keeps 64 chars at 64 bytes: NAME_MAX is 255 BYTES, so multibyte alnums made a+ 282-byte name that failed to cache and re-minted every launch (#10595 again).+ """+ safe = "".join(+ ch if (ch.isascii() and ch.isalnum()) or ch in "-_" else "_" for ch in name+ ).strip("_")+ if not safe:+ safe = "cli"+ digest = hashlib.sha256(name.encode("utf-8")).hexdigest()[:12]+ return STUDIO_HOME / "auth" / f"{CLI_API_KEY_FILE_PREFIX}{safe[:64]}_{digest}"+++def _read_cli_api_key_secret(name: str) -> str:+ try:+ return _cli_api_key_secret_path(name).read_text(encoding = "utf-8").strip()+ except (OSError, ValueError):+ return ""++def _create_api_key_inprocess(name: str) -> str:- """Create an API key via direct storage call, bypassing the ``must_change_password`` gate that+ """Return a raw API key for *name*, minting only when the cached one is dead.++ Uses a direct storage call, bypassing the ``must_change_password`` gate thatblocks HTTP POST /api/auth/api-keys on fresh installs."""storage = _load_backend_auth_storage()+ cached = _read_cli_api_key_secret(name)+ if cached and storage.validate_api_key_with_credential(cached, touch = False):+ return cachedraw_key, _row = storage.create_api_key(username = storage.DEFAULT_ADMIN_USERNAME,name = name,)+ # Best-effort: the key is already committed and the caller shuts the server+ # down on any exception, so raising here would kill a healthy launch and+ # re-mint on every retry. Same trade-off as start.py's _write_private_json.+ try:+ _write_auth_secret(_cli_api_key_secret_path(name), raw_key)+ except OSError as exc:+ typer.echo(+ f"Warning: could not cache the {name} API key ({exc}); this launch is "+ "unaffected, but the next one will create another key.",+ err = True,+ )return raw_key@@ -1040,7 +1083,17 @@ def _cli_update_password()if revoke_api_keys:conn.execute("DELETE FROM api_keys")- for stale in (BOOTSTRAP_PASSWORD_FILE, DESKTOP_SECRET_FILE):+ stale_files = [BOOTSTRAP_PASSWORD_FILE, DESKTOP_SECRET_FILE]+ if revoke_api_keys:+ # Reset only: the rows are gone, so each cached key is now plaintext for a+ # dead credential. An ordinary change keeps the rows, so its cache stays valid.+ try:+ stale_files += sorted(+ p.name for p in (STUDIO_HOME / "auth").glob(f"{CLI_API_KEY_FILE_PREFIX}*")+ )+ except OSError:+ pass+ for stale in stale_files:stale_path = STUDIO_HOME / "auth" / staletry:stale_path.unlink(missing_ok = True)@@ -2028,7 +2081,7 @@ def run("cli","--api-key-name",rich_help_panel = _RUN_PANEL_ADVANCED,- help = "Label for the auto-generated API key",+ help = "Label for the API key reused across runs",),port: int = typer.Option(8888, "--port", "-p", rich_help_panel = _RUN_PANEL_SERVER),host: str = typer.Option("127.0.0.1", "--host", "-H", rich_help_panel = _RUN_PANEL_SERVER),diff --git a/unsloth_cli/tests/test_studio_cli_api_key.py b/unsloth_cli/tests/test_studio_cli_api_key.pynew file mode 100644index 00000000000..83ef95de2f0--- /dev/null+++ b/unsloth_cli/tests/test_studio_cli_api_key.py@@ -0,0 +1,195 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Reuse the named CLI API key across `unsloth studio run` (#10595)."""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_REPO_ROOT = Path(__file__).resolve().parents[2]+if str(_REPO_ROOT) not in sys.path:+ sys.path.insert(0, str(_REPO_ROOT))+++def _studio():+ from unsloth_cli.commands import studio as _studio_mod+ return _studio_mod+++class _FakeStorage:+ DEFAULT_ADMIN_USERNAME = "unsloth"++ def __init__(self):+ self.created: list[str] = []+ self.keys: dict[str, dict] = {}+ self.next_id = 1++ def create_api_key(self, username, name):+ raw = f"sk-unsloth-{self.next_id:032x}"+ row = {"id": self.next_id, "name": name, "is_active": 1}+ self.next_id += 1+ self.created.append(name)+ self.keys[raw] = row+ return raw, row++ def validate_api_key_with_credential(+ self,+ raw_key,+ *,+ touch = True,+ ):+ row = self.keys.get(raw_key)+ if row and row["is_active"]:+ return (self.DEFAULT_ADMIN_USERNAME, "secret")+ return None+++def studio_home(monkeypatch, tmp_path):+ studio_mod = _studio()+ monkeypatch.setattr(studio_mod, "STUDIO_HOME", tmp_path)+ return studio_mod, tmp_path+++def test_second_run_reuses_the_same_cli_key(studio_home, monkeypatch):+ studio_mod, tmp_path = studio_home+ storage = _FakeStorage()+ monkeypatch.setattr(studio_mod, "_load_backend_auth_storage", lambda: storage)++ first = studio_mod._create_api_key_inprocess("cli")+ second = studio_mod._create_api_key_inprocess("cli")++ assert first == second+ assert storage.created == ["cli"]+ secret = studio_mod._cli_api_key_secret_path("cli").read_text(encoding = "utf-8")+ assert secret.strip() == first+ assert (tmp_path / "auth") in studio_mod._cli_api_key_secret_path("cli").parents+++def test_revoked_cached_key_mints_once_and_drops_the_old_row(studio_home, monkeypatch):+ studio_mod, _tmp_path = studio_home+ storage = _FakeStorage()+ monkeypatch.setattr(studio_mod, "_load_backend_auth_storage", lambda: storage)++ first = studio_mod._create_api_key_inprocess("cli")+ storage.keys[first]["is_active"] = 0+ second = studio_mod._create_api_key_inprocess("cli")++ assert second != first+ assert storage.created == ["cli", "cli"]+ assert storage.keys[first]["is_active"] == 0+ assert storage.keys[second]["is_active"] == 1+++def test_corrupt_secret_file_mints_instead_of_aborting(studio_home, monkeypatch):+ studio_mod, tmp_path = studio_home+ storage = _FakeStorage()+ monkeypatch.setattr(studio_mod, "_load_backend_auth_storage", lambda: storage)+ path = studio_mod._cli_api_key_secret_path("cli")+ path.parent.mkdir(parents = True)+ path.write_bytes(b"\xff\xfe not utf-8")++ minted = studio_mod._create_api_key_inprocess("cli")++ assert minted.startswith("sk-unsloth-")+ assert storage.created == ["cli"]+++def test_different_names_keep_separate_keys(studio_home, monkeypatch):+ studio_mod, _tmp_path = studio_home+ storage = _FakeStorage()+ monkeypatch.setattr(studio_mod, "_load_backend_auth_storage", lambda: storage)++ cli = studio_mod._create_api_key_inprocess("cli")+ other = studio_mod._create_api_key_inprocess("other")++ assert cli != other+ assert storage.created == ["cli", "other"]+++ "first_name, second_name",+ [+ ("foo/bar", "foo?bar"), # punctuation collapses to the same "_"+ ("my key", "my_key"), # space vs underscore+ ("k" * 70 + "A", "k" * 70 + "B"), # differ only past the 64-char cut+ ("///", "cli"), # sanitizes to empty, falls back to "cli"+ ("cli", "CLI"), # collides on APFS / NTFS case folding+ ("中文", "日本"), # non-ASCII stems both fold to "_", so only the digest separates them+ ],+)+def test_distinct_names_never_share_a_cache_file(studio_home, monkeypatch, first_name, second_name):+ """A run asking for one label must never be handed the key minted for another."""+ studio_mod, _tmp_path = studio_home+ storage = _FakeStorage()+ monkeypatch.setattr(studio_mod, "_load_backend_auth_storage", lambda: storage)++ first_path = studio_mod._cli_api_key_secret_path(first_name)+ second_path = studio_mod._cli_api_key_secret_path(second_name)+ # .lower(): on a case-insensitive filesystem the two would be one file.+ assert first_path.name.lower() != second_path.name.lower()++ first = studio_mod._create_api_key_inprocess(first_name)+ second = studio_mod._create_api_key_inprocess(second_name)+ assert first != second+ assert storage.created == [first_name, second_name]+++ "name",+ [+ "cli",+ "my key",+ "café",+ "k" * 200,+ "..",+ "-",+ "x/y",+ # isalnum() but multibyte: 64 chars was 282 bytes, over the 255-BYTE+ # NAME_MAX, so the cache missed with ENAMETOOLONG and re-minted every launch.+ "\U0001d7d8" * 64,+ "中文" * 100,+ "\U0001f600" * 80,+ ],+)+def test_cache_path_is_a_safe_filename_inside_auth(studio_home, name):+ studio_mod, tmp_path = studio_home+ path = studio_mod._cli_api_key_secret_path(name)++ assert path.parent == tmp_path / "auth"+ assert path.name.startswith(studio_mod.CLI_API_KEY_FILE_PREFIX)+ assert "/" not in path.name and ".." not in path.name+ assert len(path.name.encode("utf-8")) <= 255+++ "exc",+ [+ OSError(30, "Read-only file system"),+ PermissionError(13, "locked by another process"), # Windows AV / indexer+ IsADirectoryError(21, "Is a directory"),+ ],+)+def test_cache_write_failure_does_not_abort_the_launch(studio_home, monkeypatch, capsys, exc):+ """The key is committed before the cache write, and the caller shuts the server+ down on any exception, so a failed write must cost the NEXT launch, not this one."""+ studio_mod, _tmp_path = studio_home+ storage = _FakeStorage()+ monkeypatch.setattr(studio_mod, "_load_backend_auth_storage", lambda: storage)++ def _boom(path, secret):+ raise exc++ monkeypatch.setattr(studio_mod, "_write_auth_secret", _boom)++ minted = studio_mod._create_api_key_inprocess("cli")++ assert minted.startswith("sk-unsloth-")+ assert storage.created == ["cli"]+ err = capsys.readouterr().err+ assert "could not cache" in err+ assert minted not in err, "the warning must not print the key"diff --git a/unsloth_cli/tests/test_studio_password_prompt.py b/unsloth_cli/tests/test_studio_password_prompt.pyindex 6f7dbaa5d54..c2a7117d0f6 100644--- a/unsloth_cli/tests/test_studio_password_prompt.py+++ b/unsloth_cli/tests/test_studio_password_prompt.py@@ -1610,6 +1610,44 @@ def test_cli_update_password_truncates_locked_bootstrap_after_change(monkeypatchassert bootstrap_file.read_text() == ""+def test_reset_clears_cached_cli_api_keys(monkeypatch, tmp_path):+ # reset-password DELETEs every api_keys row, so a cached key is left as+ # plaintext for a credential that no longer exists.+ studio_mod = _studio()+ monkeypatch.setattr(studio_mod, "STUDIO_HOME", tmp_path)+ _seed_auth(studio_mod)+ for name in ("cli", "my key"):+ studio_mod._write_auth_secret(+ studio_mod._cli_api_key_secret_path(name), "sk-unsloth-" + "0" * 32+ )+ auth_dir = tmp_path / "auth"+ assert len(list(auth_dir.glob(f"{studio_mod.CLI_API_KEY_FILE_PREFIX}*"))) == 2++ conn = studio_mod._connect_auth_db()+ studio_mod._cli_update_password(+ conn, studio_mod.DEFAULT_ADMIN_USERNAME, "fresh-new-pw-123", revoke_api_keys = True+ )+ conn.close()++ assert list(auth_dir.glob(f"{studio_mod.CLI_API_KEY_FILE_PREFIX}*")) == []+++def test_ordinary_password_change_keeps_cached_cli_api_keys(monkeypatch, tmp_path):+ # Without revoke_api_keys the api_keys rows survive, so the cached key is+ # still valid and deleting it would just force a pointless re-mint.+ studio_mod = _studio()+ monkeypatch.setattr(studio_mod, "STUDIO_HOME", tmp_path)+ _seed_auth(studio_mod)+ path = studio_mod._cli_api_key_secret_path("cli")+ studio_mod._write_auth_secret(path, "sk-unsloth-" + "0" * 32)++ conn = studio_mod._connect_auth_db()+ studio_mod._cli_update_password(conn, studio_mod.DEFAULT_ADMIN_USERNAME, "fresh-new-pw-123")+ conn.close()++ assert path.exists()++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