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.

SAC probe: verify Studio identity before sending a password (#12176)

Daniel Han741ea5c03422
diff --git a/scripts/windows_sac_probe/studio_scenario.py b/scripts/windows_sac_probe/studio_scenario.py
index 3a49549d464..880b86133f5 100644
--- a/scripts/windows_sac_probe/studio_scenario.py
+++ b/scripts/windows_sac_probe/studio_scenario.py
@@ -5,8 +5,13 @@
from __future__ import annotations
import argparse
+import base64
+import hashlib
+import hmac
import json
import os
+import secrets
+import sqlite3
import statistics
import sys
import threading
@@ -268,6 +273,59 @@ def resolve_studio_home(value: str) -> Path:
return home
+class _NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ raise urllib.error.HTTPError(
+ req.full_url, code, f"refusing redirect to {newurl}", headers, fp
+ )
+
+
+def studio_identity_error(
+ base_url: str,
+ home: Path,
+ timeout: float = 10,
+) -> Optional[str]:
+ """None when `base_url` signs our nonce with this home's secret (storage.compute_identity_proof), else why not.
+ /api/liveness is public, so anything holding the port can claim to be Studio."""
+ nonce = secrets.token_bytes(32)
+ url = f"{base_url}/api/auth/identity?nonce={base64.urlsafe_b64encode(nonce).decode()}"
+ start = time.monotonic()
+ try:
+ # No redirects: one could relay a real Studio's proof.
+ with urllib.request.build_opener(_NoRedirect).open(url, timeout = timeout) as response:
+ proof = json.loads(response.read(65536)).get("proof")
+ TIMED.record("GET", "/api/auth/identity", (time.monotonic() - start) * 1000.0, 200)
+ except Exception as exc: # noqa: BLE001 - any failure means unverified
+ TIMED.record(
+ "GET",
+ "/api/auth/identity",
+ (time.monotonic() - start) * 1000.0,
+ "error",
+ str(exc)[:400],
+ )
+ return f"/api/auth/identity did not answer ({str(exc)[:200]})"
+ # Read after the challenge: Studio creates the secret on the first one it answers.
+ db = home / "auth" / "auth.db"
+ try:
+ conn = sqlite3.connect(f"{db.resolve().as_uri()}?mode=rw", uri = True, timeout = 10)
+ try:
+ row = conn.execute(
+ "SELECT value FROM app_secrets WHERE key = 'studio_identity_secret'"
+ ).fetchone()
+ finally:
+ conn.close()
+ secret = bytes.fromhex(row[0])
+ except Exception as exc: # noqa: BLE001
+ return f"could not read the identity secret from {db} ({str(exc)[:200]}); pass --home"
+ host, _, port = base_url.rpartition("//")[2].rpartition(":")
+ expected = hmac.new(
+ secret, b"|".join([nonce, host.encode(), port.encode()]), hashlib.sha256
+ ).hexdigest()
+ if not isinstance(proof, str) or not hmac.compare_digest(proof, expected):
+ return "its identity proof does not match this installation"
+ return None
+
+
def authenticate(base_url: str, home: Path, password: Optional[str]) -> Credentials:
"""Log in, rotating the bootstrap credential when this home has never been used."""
boot_file = home / "auth" / ".bootstrap_password"
@@ -277,6 +335,13 @@ def authenticate(base_url: str, home: Path, password: Optional[str]) -> Credenti
"Studio that has never been opened it becomes the account password, on one "
"that has it must be the password you sign in with."
)
+ # Before any password is sent: the port may be held by something other than Studio.
+ reason = studio_identity_error(base_url, home)
+ if reason:
+ raise SystemExit(
+ f"refusing to send a password to {base_url}: {reason}. It may not be this "
+ f"machine's Unsloth Studio (home {home})."
+ )
# An EMPTY file is a rotated installation
bootstrap = boot_file.read_text(encoding = "utf-8").strip() if boot_file.exists() else ""
if bootstrap:
diff --git a/tests/studio/test_windows_sac_probe.py b/tests/studio/test_windows_sac_probe.py
index e137c0df719..caa993b229d 100644
--- a/tests/studio/test_windows_sac_probe.py
+++ b/tests/studio/test_windows_sac_probe.py
@@ -148,7 +148,10 @@ def _load_scenario():
@pytest.fixture
def s():
- return _load_scenario()
+ module = _load_scenario()
+ # The fakes below stand in for a verified Studio; the check itself is tested against a real socket.
+ module.studio_identity_error = lambda *a, **k: None
+ return module
TOOL_START = {"type": "tool_start", "tool_name": "web_search"}
@@ -381,6 +384,84 @@ def test_the_poller_abandons_a_read_at_the_frontend_timeout_and_measures_the_sta
assert [round(x) for x in poller.stalls_ms()] == [205, 50]
+def _identity_server(proof):
+ import base64
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+ from urllib.parse import parse_qs, urlparse
+
+ posts: list[bytes] = []
+
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def _reply(self, code, obj):
+ body = json.dumps(obj).encode()
+ self.send_response(code)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ url = urlparse(self.path)
+ if url.path == "/api/liveness":
+ return self._reply(200, {"service": "Unsloth UI Backend"})
+ nonce = base64.urlsafe_b64decode(parse_qs(url.query)["nonce"][0])
+ self._reply(200, {"proof": proof(nonce, *self.server.server_address[:2])})
+
+ def do_POST(self):
+ posts.append(self.rfile.read(int(self.headers.get("Content-Length") or 0)))
+ self._reply(401, {"detail": "no"})
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ threading.Thread(target = server.serve_forever, daemon = True).start()
+ return server, posts
+
+
[email protected]("bootstrap", ["", "boot-secret"])
+def test_a_port_squatter_never_receives_a_password(tmp_path, bootstrap):
+ """/api/liveness is public: only the /api/auth/identity HMAC over auth.db's secret proves Studio."""
+ import hashlib
+ import hmac
+ import sqlite3
+
+ s = _load_scenario()
+ (tmp_path / "auth").mkdir()
+ (tmp_path / "auth" / ".bootstrap_password").write_text(bootstrap, encoding = "utf-8")
+ secret = bytes(range(32))
+ conn = sqlite3.connect(tmp_path / "auth" / "auth.db")
+ conn.execute("CREATE TABLE app_secrets (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
+ conn.execute("INSERT INTO app_secrets VALUES ('studio_identity_secret', ?)", (secret.hex(),))
+ conn.commit()
+ conn.close()
+
+ def real(nonce, host, port):
+ return hmac.new(
+ secret, b"|".join([nonce, host.encode(), str(port).encode()]), hashlib.sha256
+ ).hexdigest()
+
+ for proof in (lambda *a: "0" * 64, lambda n, h, p: real(n, h, p + 1)):
+ server, posts = _identity_server(proof)
+ try:
+ with pytest.raises(SystemExit, match = "refusing to send a password"):
+ s.authenticate(
+ f"http://127.0.0.1:{server.server_address[1]}", tmp_path, "operators-choice"
+ )
+ finally:
+ server.shutdown()
+ assert posts == []
+
+ server, posts = _identity_server(real)
+ try:
+ with pytest.raises(SystemExit, match = "login failed"):
+ s.authenticate(
+ f"http://127.0.0.1:{server.server_address[1]}", tmp_path, "operators-choice"
+ )
+ finally:
+ server.shutdown()
+ assert len(posts) == 1
+
+
def test_an_empty_bootstrap_file_means_rotated(s, tmp_path, monkeypatch):
"""Studio truncates .bootstrap_password on Windows when it cannot delete it, so an existence check picked the empty string over the operator's password."""
posted = _bootstrap(s, tmp_path, monkeypatch, "")