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 auth and bootstrap gates: throttle desktop-login, narrow the tunnel CORS origin, identify Colab's proxy (#11398)

Daniel Handa77eb80eea7
diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.py
index 7b8d9dabf5e..a5bda2acc41 100644
--- a/studio/backend/auth/storage.py
+++ b/studio/backend/auth/storage.py
@@ -1029,6 +1029,24 @@ _API_KEY_PBKDF2_ITERATIONS = 100_000
DESKTOP_SECRET_PREFIX = "desktop-"
_DESKTOP_SECRET_HASH_KEY = "desktop_secret_hash"
_DESKTOP_SECRET_CREATED_AT_KEY = "desktop_secret_created_at"
+# `token_urlsafe(48)` is exactly 64 unpadded URL-safe characters, and no other shape can be behind a
+# stored hash. Keep in sync with the CLI minter (unsloth_cli/commands/studio.py) and the `desktop-`
+# alternation in core/inference/tool_loop_controller.py.
+_DESKTOP_SECRET_BODY = re.compile(r"\A[A-Za-z0-9_-]{64}\Z")
+
+
+def desktop_secret_is_well_formed(raw_secret: str) -> bool:
+ """Whether a candidate has the one shape :func:`create_desktop_secret` mints.
+
+ Syntactic only: a candidate that passes this still has to match the stored hash. It is separate
+ from validation, and cheap, because the desktop shell posts a deliberately invalid secret to
+ /api/auth/desktop-login to learn from the 401 that the backend is one it can manage. That probe
+ must cost no KDF and no rate-limit budget, or a live app throttles itself out of its own
+ backend.
+ """
+ if not isinstance(raw_secret, str) or not raw_secret.startswith(DESKTOP_SECRET_PREFIX):
+ return False
+ return _DESKTOP_SECRET_BODY.match(raw_secret[len(DESKTOP_SECRET_PREFIX) :]) is not None
def _pbkdf2_api_key(raw_key: str) -> str:
@@ -1479,7 +1497,9 @@ def validate_desktop_secret_with_credential(raw_secret: str) -> Optional[Tuple[s
transaction so the returned secret is the credential version the desktop secret was checked
against; a reset landing mid-request then invalidates the tokens minted from it rather than
blessing them."""
- if not raw_secret.startswith(DESKTOP_SECRET_PREFIX):
+ # Shape before KDF: this runs for unauthenticated callers, so anything spent before an
+ # attacker-chosen string can be rejected is theirs to spend.
+ if not desktop_secret_is_well_formed(raw_secret):
return None
secret_hash = _pbkdf2_desktop_secret(raw_secret)
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 794b66949a7..718f02c3b36 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -1539,16 +1539,23 @@ from utils.host_policy import cors_origins_for_mode # noqa: E402
class RemoteAccessCORSMiddleware(CORSMiddleware):
- """Allow remote browser origins only while a Cloudflare URL is published."""
+ """Admit the published Cloudflare origin, on top of the startup allowlist."""
def __init__(self, cors_app, *, remote_access_state, **kwargs):
self.remote_access_state = remote_access_state
super().__init__(cors_app, **kwargs)
def is_allowed_origin(self, origin: str) -> bool:
- return bool(
- getattr(self.remote_access_state, "cloudflare_url", None)
- ) or super().is_allowed_origin(origin)
+ # The tunnel names ONE origin to admit, it is not a switch admitting every origin: api-only is
+ # locked to the Tauri app (run.py) and Settings > Remote access must not hand that lock to any
+ # open page. The tunnel-served UI calls relative URLs and is already same-origin; this is for a
+ # browser that does reach the API cross-origin from the tunnel's own document.
+ published = getattr(self.remote_access_state, "cloudflare_url", None)
+ if published:
+ tunnel_origin = _origin_of(published)
+ if tunnel_origin is not None and tunnel_origin == _origin_of(origin):
+ return True
+ return super().is_allowed_origin(origin)
_cors_origins = cors_origins_for_mode(
@@ -2537,6 +2544,17 @@ def _canonical_origin(scheme: str, netloc: str) -> Optional[tuple[str, str, int]
return (scheme, host, port)
+def _origin_of(url: Optional[str]) -> Optional[tuple[str, str, int]]:
+ """Canonical origin of a URL or of an Origin header value, or ``None`` when it is neither."""
+ if not url:
+ return None
+ try:
+ parsed = urlparse(url)
+ except ValueError:
+ return None
+ return _canonical_origin(parsed.scheme, parsed.netloc)
+
+
def _is_loopback_ip(host: Optional[str]) -> bool:
"""Return whether ``host`` is a loopback IP, including IPv4-mapped IPv6."""
if not host or "%" in host: # a scope id (::1%eth0) is never a plain loopback
@@ -2618,13 +2636,44 @@ def _is_same_origin_request(request: Request) -> bool:
return origin_canon == self_canon
+# Colab's proxy is itself a forwarded-header ingress, invisible to the loopback tests, so it is identified
+# positively by its own authority: naming one tunnel vendor instead leaves every other relay (ngrok,
+# localtunnel, bore, ssh -R) reading as the local browser.
+_COLAB_PROXY_HOST_SUFFIXES = ("colab.googleusercontent.com", ".googleusercontent.com", ".colab.dev")
+# The proxy relays the notebook owner and only the notebook owner, so it sets x-forwarded-for (which is why
+# run.py runs uvicorn with proxy_headers there). The other four mark a relay we cannot attribute to it.
+_COLAB_TOLERATED_PROXY_HEADERS = frozenset({"x-forwarded-for"})
+
+
+def _host_header_is_colab_proxy(host_header: Optional[str]) -> bool:
+ """Whether the Host authority belongs to Colab's own port proxy."""
+ if not host_header:
+ return False
+ host = host_header.strip()
+ if host.startswith("["): # bracketed IPv6 is never a Colab proxy authority
+ return False
+ if host.count(":") == 1: # host:port
+ host = host.split(":", 1)[0]
+ host = host.lower().rstrip(".")
+ return host.endswith(_COLAB_PROXY_HOST_SUFFIXES)
+
+
+def _is_colab_notebook_request(request: Request) -> bool:
+ """Allow bootstrap injection through Colab's single-user notebook proxy, and nothing else."""
+ for header in _PROXIED_CLIENT_HEADERS:
+ if header in _COLAB_TOLERATED_PROXY_HEADERS:
+ continue
+ if request.headers.get(header) is not None:
+ return False
+ return _host_header_is_colab_proxy(request.headers.get("host"))
+
+
def _should_inject_bootstrap(request: Request) -> bool:
"""Whether to embed the seeded bootstrap password in index.html."""
if not _is_same_origin_request(request):
return False
- if _IS_COLAB:
- # Single-user notebook proxy: allow autofill, but never a public tunnel (sets cf-connecting-ip).
- return request.headers.get("cf-connecting-ip") is None
+ if _IS_COLAB and _is_colab_notebook_request(request):
+ return True
return _is_local_bootstrap_request(request)
diff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.py
index d3389183d5f..11697e5e842 100644
--- a/studio/backend/routes/auth.py
+++ b/studio/backend/routes/auth.py
@@ -94,6 +94,17 @@ def _cli_is_inside(prefix: str) -> bool:
return False
+def _reset_password_command_on_path() -> str:
+ """The reset command in its PATH form, naming nothing about this host.
+
+ The absolute forms below are for the person sitting at the machine. This one is the only
+ shape safe to put in a response body, since an unauthenticated 401 is readable by any origin.
+ """
+ if os.name == "nt":
+ return "unsloth.cmd studio reset-password"
+ return "unsloth studio reset-password"
+
+
def _reset_password_command() -> str:
"""Shell command shown in the 'incorrect password' hint.
@@ -132,9 +143,7 @@ def _reset_password_command() -> str:
return f"{shlex.quote(exe)} studio reset-password"
except Exception:
pass
- if os.name == "nt":
- return "unsloth.cmd studio reset-password"
- return "unsloth studio reset-password"
+ return _reset_password_command_on_path()
# Per-(ip, username) bucket + per-IP aggregate. Account bucket stops one user's typos from blocking others; the
@@ -209,6 +218,10 @@ def _overflow_take(ip: str, now: float) -> tuple[int, float]:
# Unrepresentable as a real username (leading NUL); folds unknown-user attempts
# into one slot so attacker cardinality can't blow the bucket dict.
_UNKNOWN_LOGIN_USER = "\x00unknown-user"
+# /desktop-login's own slot, NOT _UNKNOWN_LOGIN_USER: /login 429s on that bucket, so sharing it lets an
+# unauthenticated caller lock out every account with five attempts a minute, and behind a tunnel every
+# visitor is the same cloudflared peer.
+_DESKTOP_LOGIN_USER = "\x00desktop-login"
def _trust_forwarded_for() -> bool:
@@ -280,6 +293,14 @@ def _unknown_user_key(request: Request | None) -> tuple[str, str]:
return (_client_ip(request), _UNKNOWN_LOGIN_USER)
+def _desktop_login_key(request: Request | None) -> tuple[str, str]:
+ # The address is suffixed as well as the username, so the per-IP aggregate and its overflow shard are
+ # this route's own too. Sharing those with /login couples them in the direction that matters most:
+ # cloudflared and the desktop shell both reach the backend over loopback, so they are ONE address, and
+ # thirty password guesses through the tunnel would 429 the shell's valid secret exchange.
+ return (_client_ip(request) + _DESKTOP_LOGIN_USER, _DESKTOP_LOGIN_USER)
+
+
def _prune_bucket(bucket: deque, now: float) -> None:
while bucket and now - bucket[0] > _LOGIN_WINDOW_SECONDS:
bucket.popleft()
@@ -433,16 +454,24 @@ def auth_status() -> AuthStatusResponse:
def _login_failure_detail() -> str:
- """Recovery hint for a rejected login. The name shown is a placeholder, not the submitted."""
+ """Recovery hint for a rejected login. The name shown is a placeholder, not the submitted.
+
+ PATH form only: this body is produced before any credential is verified and the browser-served
+ default resolves CORS to ["*"], so an absolute path built from ``sys.executable`` would hand the
+ local account name and the install layout to any page the user happens to have open. The 429
+ beside this one withholds the client IP for the same reason. A bare ``unsloth`` does not resolve
+ from every shell, so the hint says which environment to run it in; the exact absolute command is
+ printed on the host's own console by run.py, where naming the install is the point.
+ """
+ command = _reset_password_command_on_path()
+ where = "in the environment Unsloth is installed in"
if policy.installation_is_multi_user():
return (
"Incorrect username, password or setup code. Ask the installation owner to reset "
- f"the account, by running this on the Unsloth Studio host: {_reset_password_command()} "
+ f"the account, by running this on the Unsloth Studio host {where}: {command} "
"--username <name>"
)
- return (
- f"Incorrect password. To reset it, run this in your terminal: {_reset_password_command()}"
- )
+ return f"Incorrect password. To reset it, run this in your terminal, {where}: {command}"
@router.post("/login", response_model = Token)
@@ -520,16 +549,46 @@ async def logout(
return Response(status_code = status.HTTP_204_NO_CONTENT)
+# Sync def (not async), as /identity is: validating the secret spends a 100k-iteration PBKDF2 and a
+# SQLite transaction, and on the event loop that is the thread serving every other request.
@router.post("/desktop-login", response_model = Token)
-async def desktop_login(payload: DesktopLoginRequest) -> Token | Response:
- """Exchange a local desktop secret for normal admin-subject tokens."""
+def desktop_login(payload: DesktopLoginRequest, request: Request) -> Token | Response:
+ """Exchange a local desktop secret for normal admin-subject tokens. Per-IP rate-limited.
+
+ Throttled because the route takes no credential and the KDF runs before an attacker-chosen
+ secret can be rejected, so without it one unauthenticated request buys unbounded work. On its
+ own account bucket, contributing to the shared per-IP aggregate exactly as /login does.
+ """
+ # Before the bucket is READ, not just before it is written: the shipped shell probes this route with a
+ # deliberately invalid secret on every preflight, every 15s watchdog tick and once per live candidate
+ # port, and reads anything but 401 as a backend it cannot manage (src-tauri/src/preflight/backend.rs,
+ # src-tauri/src/desktop_backend_owner.rs).
+ if not storage.desktop_secret_is_well_formed(payload.secret):
+ raise HTTPException(
+ status_code = status.HTTP_401_UNAUTHORIZED,
+ detail = "Desktop authentication failed",
+ )
+
+ key = _desktop_login_key(request)
+ blocked_for = _login_blocked(key)
+ if blocked_for > 0:
+ raise HTTPException(
+ status_code = status.HTTP_429_TOO_MANY_REQUESTS,
+ detail = (f"Too many failed login attempts. " f"Try again in {blocked_for} seconds."),
+ headers = {"Retry-After": str(blocked_for)},
+ )
+
verified = storage.validate_desktop_secret_with_credential(payload.secret)
if verified is None:
+ _record_login_failure(key)
raise HTTPException(
status_code = status.HTTP_401_UNAUTHORIZED,
detail = "Desktop authentication failed",
)
username, jwt_secret = verified
+ # Safe to clear the aggregate as well now that the address is suffixed: it is this route's own entry,
+ # not /login's, so a desktop success cannot hand anyone a fresh password-guessing budget.
+ _clear_login_bucket(key)
from auth.policy import installation_is_multi_user
diff --git a/studio/backend/run.py b/studio/backend/run.py
index d3da78db36a..e5a3136cbfe 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -2116,13 +2116,17 @@ def _terminal_password_gate(
return False, False
# The public page will not auto-fill the bootstrap credential and the seeded file may already be gone,
# so point recovery at a terminal-attached run / reset-password instead of reading it from disk.
+ # The ABSOLUTE form here: this line is stderr on the host, where naming the install is the point and
+ # a bare `unsloth` may not be on PATH. The 401 body deliberately carries only the PATH form.
+ from routes.auth import _reset_password_command
+
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 "
+ f"`{_reset_password_command()}`. Unsloth shuts down after the "
"bootstrap deadline (UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT, default 1h) "
"unless the password is changed.",
file = sys.stderr,
@@ -2186,10 +2190,12 @@ def _terminal_password_gate(
"(UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT=0), so nothing will stop it "
"serving that credential."
)
+ from routes.auth import _reset_password_command
+
print(
" WARNING: continuing with the auto-generated admin password on a bind "
f"that is reachable from the network. {tail} Change it by logging in, or "
- "with `unsloth studio reset-password`.",
+ f"with `{_reset_password_command()}`.",
file = sys.stderr,
flush = True,
)
diff --git a/studio/backend/tests/test_desktop_auth.py b/studio/backend/tests/test_desktop_auth.py
index e6f232f66fa..5dccb80ddef 100644
--- a/studio/backend/tests/test_desktop_auth.py
+++ b/studio/backend/tests/test_desktop_auth.py
@@ -40,13 +40,18 @@ def seed_user(*, must_change_password = False):
)
-def auth_client():
+def auth_route_module():
+ """A fresh copy of routes/auth.py, so its in-memory rate-limit buckets start empty."""
route_path = Path(__file__).resolve().parents[1] / "routes" / "auth.py"
spec = importlib.util.spec_from_file_location("_desktop_auth_route", route_path)
auth_route = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(auth_route)
+ return auth_route
+
+def auth_client(auth_route = None):
+ auth_route = auth_route or auth_route_module()
app = FastAPI()
app.include_router(auth_route.router, prefix = "/api/auth")
return TestClient(app)
@@ -1116,3 +1121,350 @@ 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_desktop_login_validates_off_the_event_loop():
+ """A sync def hands the 100k-iteration PBKDF2 to the threadpool.
+
+ As an ``async def`` the KDF ran on the single uvicorn event loop, so unauthenticated callers
+ could stall every other request the server was serving. /identity is sync for the same reason.
+ """
+ auth_route = auth_route_module()
+
+ assert not asyncio.iscoroutinefunction(auth_route.desktop_login)
+
+
+# The two secrets the shipped desktop shell posts to this route on purpose, to learn from the 401
+# that the backend is one it can manage. studio/src-tauri/src/preflight/backend.rs and
+# studio/src-tauri/src/desktop_backend_owner.rs; neither binary can be changed from here.
+_SHIPPED_PROBE_SECRETS = (
+ "desktop-preflight-invalid-secret",
+ "desktop-owner-adoption-invalid-secret",
+)
+
+
+def well_formed_wrong_secret(body = "A"):
+ """A candidate shaped exactly like a real secret, and not one. What a KDF flood would send."""
+ return storage.DESKTOP_SECRET_PREFIX + body * 64
+
+
+def test_desktop_login_throttles_unauthenticated_attempts():
+ """The route takes no credential and pays the KDF before it can reject the secret."""
+ seed_user(must_change_password = False)
+ auth_route = auth_route_module()
+ client = auth_client(auth_route)
+
+ secret = well_formed_wrong_secret()
+ codes = [
+ client.post("/api/auth/desktop-login", json = {"secret": secret}).status_code
+ for _ in range(auth_route._LOGIN_MAX_FAILS + 3)
+ ]
+
+ assert codes[0] == 401
+ assert 429 in codes
+ blocked = client.post("/api/auth/desktop-login", json = {"secret": secret})
+ assert blocked.status_code == 429
+ assert blocked.headers["Retry-After"]
+
+
+def test_desktop_login_still_admits_the_real_shell_after_a_miss():
+ """A stale secret from a restarted shell must not lock the retry out."""
+ seed_user(must_change_password = False)
+ auth_route = auth_route_module()
+ client = auth_client(auth_route)
+
+ stale = storage.create_desktop_secret()
+ raw = storage.create_desktop_secret() # rotation makes the first one a real, well formed miss
+ assert client.post("/api/auth/desktop-login", json = {"secret": stale}).status_code == 401
+ admitted = client.post("/api/auth/desktop-login", json = {"secret": raw})
+ assert admitted.status_code == 200
+ assert admitted.json()["access_token"]
+ # The success clears the bucket, so the shell is not throttled by its own earlier miss.
+ assert client.post("/api/auth/desktop-login", json = {"secret": raw}).status_code == 200
+
+
[email protected]("probe", _SHIPPED_PROBE_SECRETS)
+def test_the_shipped_desktop_probes_never_consume_the_login_budget(probe):
+ """The desktop app's own compatibility probes must not be read as attempts on the credential.
+
+ The shell posts one of these on every preflight, on every 15s watchdog tick, once per candidate
+ port it finds alive, and around every install mutation. Thirty in a minute is ordinary. Counting
+ them means the next probe, and the valid secret exchange that follows it, both get a 429, which
+ the shell reads as its own healthy backend being unmanageable.
+ """
+ seed_user(must_change_password = False)
+ auth_route = auth_route_module()
+ client = auth_client(auth_route)
+
+ codes = [
+ client.post("/api/auth/desktop-login", json = {"secret": probe}).status_code
+ for _ in range(auth_route._LOGIN_MAX_FAILS * 3)
+ ]
+
+ assert codes == [401] * len(codes)
+ assert not auth_route._LOGIN_BUCKETS
+ assert not auth_route._LOGIN_IP_BUCKETS
+ raw = storage.create_desktop_secret()
+ assert client.post("/api/auth/desktop-login", json = {"secret": raw}).status_code == 200
+
+
+def test_the_shipped_desktop_probe_is_answered_during_a_real_lockout():
+ """A lockout earned by real guesses must still not turn a probe's 401 into a 429.
+
+ The shell cannot tell a throttled backend from an incompatible one: anything but 401 is
+ ``desktop_login_not_found`` or ``desktop_login_probe_failed``. So the shape check has to come
+ before the bucket is read, not just before it is written.
+ """
+ seed_user(must_change_password = False)
+ auth_route = auth_route_module()
+ client = auth_client(auth_route)
+ guess = well_formed_wrong_secret()
+
+ for _ in range(auth_route._LOGIN_MAX_FAILS):
+ client.post("/api/auth/desktop-login", json = {"secret": guess})
+ assert client.post("/api/auth/desktop-login", json = {"secret": guess}).status_code == 429
+
+ for probe in _SHIPPED_PROBE_SECRETS:
+ assert client.post("/api/auth/desktop-login", json = {"secret": probe}).status_code == 401
+ # And the probes did not clear the lockout they were answered through.
+ assert client.post("/api/auth/desktop-login", json = {"secret": guess}).status_code == 429
+
+
+def test_a_malformed_desktop_secret_never_reaches_the_kdf(monkeypatch):
+ """A candidate that cannot be the stored secret is rejected on shape, before the 100k PBKDF2.
+
+ This is what makes the probes free rather than merely uncounted: the route is unauthenticated,
+ so anything it spends before it can reject an attacker-chosen string, an attacker can spend.
+ """
+ seed_user(must_change_password = False)
+ auth_route = auth_route_module()
+ client = auth_client(auth_route)
+
+ def no_kdf(raw_secret):
+ raise AssertionError(f"PBKDF2 ran for a malformed candidate: {raw_secret!r}")
+
+ monkeypatch.setattr(storage, "_pbkdf2_desktop_secret", no_kdf)
+
+ malformed = [
+ *_SHIPPED_PROBE_SECRETS,
+ "",
+ "desktop-",
+ "not-a-desktop-secret",
+ storage.DESKTOP_SECRET_PREFIX + "A" * 63,
+ storage.DESKTOP_SECRET_PREFIX + "A" * 65,
+ storage.DESKTOP_SECRET_PREFIX + "A" * 63 + "\n",
+ storage.DESKTOP_SECRET_PREFIX + "A" * 63 + "=",
+ storage.DESKTOP_SECRET_PREFIX + "é" * 64,
+ ]
+ for secret in malformed:
+ response = client.post("/api/auth/desktop-login", json = {"secret": secret})
+ assert response.status_code == 401, secret
+ assert response.json()["detail"] == "Desktop authentication failed", secret
+
+
+def test_a_well_formed_guess_still_pays_the_kdf_and_still_throttles(monkeypatch):
+ """The DoS fix is preserved: a shaped guess costs a KDF, and stops costing one once blocked."""
+ seed_user(must_change_password = False)
+ storage.create_desktop_secret()
+ auth_route = auth_route_module()
+ client = auth_client(auth_route)
+
+ real_kdf = storage._pbkdf2_desktop_secret
+ calls = []
+
+ def counting_kdf(raw_secret):
+ calls.append(raw_secret)
+ return real_kdf(raw_secret)
+
+ monkeypatch.setattr(storage, "_pbkdf2_desktop_secret", counting_kdf)
+
+ guess = well_formed_wrong_secret()
+ codes = [
+ client.post("/api/auth/desktop-login", json = {"secret": guess}).status_code
+ for _ in range(auth_route._LOGIN_MAX_FAILS + 3)
+ ]
+
+ assert codes[: auth_route._LOGIN_MAX_FAILS] == [401] * auth_route._LOGIN_MAX_FAILS
+ assert codes[auth_route._LOGIN_MAX_FAILS :] == [429, 429, 429]
+ # The KDF stopped being spent the moment the bucket filled.
+ assert len(calls) == auth_route._LOGIN_MAX_FAILS
+
+
+def test_a_minute_of_watchdog_ticks_does_not_lock_the_shell_out():
+ """The shell's real order over one window, and the order that has no success to rescue it.
+
+ The health watchdog runs every 15s (commands.rs) and probes with ``require_desktop_secret =
+ false``, so a live app emits four uncounterbalanced probes a minute and nothing clears the
+ bucket. The preflight that follows is the one that sends the real secret, and it is the one
+ that has to still work.
+ """
+ seed_user(must_change_password = False)
+ raw = storage.create_desktop_secret()
+ auth_route = auth_route_module()
+ client = auth_client(auth_route)
+
+ for _ in range(8): # two windows' worth of watchdog ticks, no success in between
+ probe = _SHIPPED_PROBE_SECRETS[1]
+ assert client.post("/api/auth/desktop-login", json = {"secret": probe}).status_code == 401
+
+ admitted = client.post("/api/auth/desktop-login", json = {"secret": raw})
+ assert admitted.status_code == 200, "the shell's own valid secret was throttled out"
+ assert admitted.json()["access_token"]
+
+
+def test_desktop_login_failures_do_not_lock_everyone_out_of_login():
+ """/desktop-login must not fill the bucket /login reads for every account.
+
+ /login 429s on max(its own account bucket, the unknown-user bucket), but it never WRITES the
+ unknown-user one: an unknown username is recorded per name, deliberately, so the shared slot
+ is not an existence oracle. Nothing filled it before this route did. Sharing it means five
+ unauthenticated desktop attempts a minute reject every account's correct password, and behind
+ a tunnel UNSLOTH_STUDIO_TRUST_FORWARDED is off by default, so every visitor arrives as the
+ same cloudflared peer and one caller locks out the whole installation.
+ """
+ seed_user(must_change_password = False)
+ auth_route = auth_route_module()
+ client = auth_client(auth_route)
+ good = {"username": storage.DEFAULT_ADMIN_USERNAME, "password": "human-password-123"}
+
+ assert client.post("/api/auth/login", json = good).status_code == 200
+
+ guess = well_formed_wrong_secret()
+ for _ in range(auth_route._LOGIN_MAX_FAILS + 1):
+ client.post("/api/auth/desktop-login", json = {"secret": guess})
+
+ assert (
+ client.post("/api/auth/login", json = good).status_code == 200
+ ), "unauthenticated desktop-login attempts rejected a correct password"
+ # Its own throttle still works, on its own slot.
+ assert client.post("/api/auth/desktop-login", json = {"secret": guess}).status_code == 429
+ assert auth_route._desktop_login_key(None)[1] != auth_route._unknown_user_key(None)[1]
+
+
+def test_a_password_spray_does_not_lock_the_desktop_shell_out():
+ """The other direction: /login's per-IP aggregate must not withhold the shell's own secret.
+
+ cloudflared and the desktop shell both reach the backend over loopback, and
+ UNSLOTH_STUDIO_TRUST_FORWARDED is off by default, so every tunnel visitor and the shell are
+ ONE address. Sharing the aggregate lets a remote visitor spray thirty password guesses a
+ minute and keep the shell's valid exchange at 429, which it reads as its own healthy backend
+ being unmanageable. On main this route consulted no bucket at all, so the coupling arrived
+ with the throttle.
+ """
+ seed_user(must_change_password = False)
+ raw = storage.create_desktop_secret()
+ auth_route = auth_route_module()
+ client = auth_client(auth_route)
+
+ assert client.post("/api/auth/desktop-login", json = {"secret": raw}).status_code == 200
+
+ for i in range(auth_route._LOGIN_IP_MAX_FAILS):
+ client.post("/api/auth/login", json = {"username": f"sprayed{i}", "password": "wrong-pw-1"})
+
+ admitted = client.post("/api/auth/desktop-login", json = {"secret": raw})
+ assert admitted.status_code == 200, "a password spray locked the shell out of its own backend"
+ assert admitted.json()["access_token"]
+ # /login is still throttled by its own aggregate, which is the point of that aggregate.
+ blocked = client.post(
+ "/api/auth/login", json = {"username": "sprayed0", "password": "wrong-pw-1"}
+ )
+ assert blocked.status_code == 429
+
+
+def test_a_desktop_exchange_does_not_reset_the_shared_password_throttle():
+ """The desktop secret proves the shell owns the backend, not that anyone signed in.
+
+ /login's per-IP aggregate is what stops password spraying across many usernames, none of which
+ reaches its own per-account limit. Letting /desktop-login clear it hands one holder of the local
+ secret a fresh aggregate budget for every account behind the same NAT, and in multi-user mode it
+ does so while returning no session at all.
+ """
+ seed_user(must_change_password = False)
+ raw = storage.create_desktop_secret()
+ auth_route = auth_route_module()
+ client = auth_client(auth_route)
+
+ sprayed = auth_route._LOGIN_IP_MAX_FAILS - 1
+ for i in range(sprayed):
+ client.post("/api/auth/login", json = {"username": f"sprayed{i}", "password": "wrong"})
+ ip = next(iter(auth_route._LOGIN_IP_BUCKETS))
+ assert len(auth_route._LOGIN_IP_BUCKETS[ip]) == sprayed
+
+ assert client.post("/api/auth/desktop-login", json = {"secret": raw}).status_code == 200
+
+ assert (
+ len(auth_route._LOGIN_IP_BUCKETS.get(ip, [])) == sprayed
+ ), "a desktop exchange cleared /login's per-IP aggregate"
+ # Its own buckets are cleared, both of them: the shell must not be locked out by its own earlier
+ # miss, and what isolates the two routes is the suffixed address, not a flag on the clear.
+ assert auth_route._desktop_login_key(None)[1] not in {k[1] for k in auth_route._LOGIN_BUCKETS}
+ assert auth_route._desktop_login_key(None)[0] != ip
+ assert auth_route._desktop_login_key(None)[0] not in auth_route._LOGIN_IP_BUCKETS
+
+
+def test_a_desktop_success_clears_its_own_ip_aggregate():
+ """Misses interleaved with successes must not accumulate into a lockout.
+
+ The desktop aggregate is this route's own entry, so clearing it cannot reset /login's
+ password-spray budget, and leaving it would let repeated rotate-then-reconnect cycles reach
+ _LOGIN_IP_MAX_FAILS and 429 a valid secret.
+ """
+ seed_user(must_change_password = False)
+ auth_route = auth_route_module()
+ client = auth_client(auth_route)
+
+ for _ in range(auth_route._LOGIN_IP_MAX_FAILS):
+ stale = storage.create_desktop_secret()
+ raw = storage.create_desktop_secret() # rotation makes `stale` a real well formed miss
+ assert client.post("/api/auth/desktop-login", json = {"secret": stale}).status_code == 401
+ assert client.post("/api/auth/desktop-login", json = {"secret": raw}).status_code == 200
+
+ assert auth_route._desktop_login_key(None)[0] not in auth_route._LOGIN_IP_BUCKETS
+
+
+def test_multi_user_desktop_exchange_grants_no_session_and_clears_no_aggregate(monkeypatch):
+ """The sharpest case: multi-user returns login_required, so nothing was authenticated at all."""
+ seed_user(must_change_password = False)
+ raw = storage.create_desktop_secret()
+ auth_route = auth_route_module()
+ monkeypatch.setattr(auth_route.policy, "installation_is_multi_user", lambda: True)
+ import auth.policy as auth_policy
+
+ monkeypatch.setattr(auth_policy, "installation_is_multi_user", lambda: True)
+ client = auth_client(auth_route)
+
+ sprayed = auth_route._LOGIN_IP_MAX_FAILS - 1
+ for i in range(sprayed):
+ client.post("/api/auth/login", json = {"username": f"sprayed{i}", "password": "wrong"})
+ ip = next(iter(auth_route._LOGIN_IP_BUCKETS))
+
+ response = client.post("/api/auth/desktop-login", json = {"secret": raw})
+ assert response.json() == {"login_required": True, "login_mode": "multi"}
+ assert len(auth_route._LOGIN_IP_BUCKETS.get(ip, [])) == sprayed
+
+
+def test_storage_rejects_a_malformed_desktop_secret_before_the_kdf(monkeypatch):
+ """The shape gate lives in storage, so every caller of the validator gets it.
+
+ main.py's shell health probe validates the same secret on a separate path.
+ """
+ seed_user(must_change_password = False)
+ storage.create_desktop_secret()
+
+ def no_kdf(raw_secret):
+ raise AssertionError(f"PBKDF2 ran for a malformed candidate: {raw_secret!r}")
+
+ monkeypatch.setattr(storage, "_pbkdf2_desktop_secret", no_kdf)
+
+ for probe in _SHIPPED_PROBE_SECRETS:
+ assert storage.validate_desktop_secret_with_credential(probe) is None
+ assert storage.validate_desktop_secret(probe) is None
+
+
+def test_every_minted_desktop_secret_is_well_formed():
+ """The gate is keyed to the one shape the minters produce, so it has to track them."""
+ seed_user(must_change_password = False)
+ for _ in range(16):
+ assert storage.desktop_secret_is_well_formed(storage.create_desktop_secret())
+ for probe in _SHIPPED_PROBE_SECRETS:
+ assert not storage.desktop_secret_is_well_formed(probe)
diff --git a/studio/backend/tests/test_index_bootstrap_loopback.py b/studio/backend/tests/test_index_bootstrap_loopback.py
index 87abace22c8..aea89bb7224 100644
--- a/studio/backend/tests/test_index_bootstrap_loopback.py
+++ b/studio/backend/tests/test_index_bootstrap_loopback.py
@@ -107,13 +107,51 @@ def test_colab_allows_notebook_proxy_but_not_shareable_tunnel(monkeypatch):
import main
monkeypatch.setattr(main, "_IS_COLAB", True)
- # In-notebook proxy: same-origin, no tunnel header, injects off-loopback too.
- assert main._should_inject_bootstrap(_request("10.0.0.2", "colab.proxy")) is True
+ # In-notebook proxy: same-origin, its own authority, injects off-loopback too.
+ notebook = _request(
+ "10.0.0.2",
+ "abc123-496ff2e9c6d22116-8888-colab.googleusercontent.com",
+ headers = {"x-forwarded-for": "10.0.0.2"},
+ )
+ assert main._should_inject_bootstrap(notebook) is True
# Shareable Cloudflare link marks visitors with cf-connecting-ip; withhold.
tunnel = _request("127.0.0.1", "localhost", headers = {"cf-connecting-ip": "203.0.113.7"})
assert main._should_inject_bootstrap(tunnel) is False
+def test_colab_withholds_from_every_relay_not_just_cloudflare(monkeypatch):
+ """Any relay, not only the one that sets cf-connecting-ip, is remote on the Colab branch.
+
+ The branch used to test cf-connecting-ip alone, so an ngrok / localtunnel / bore / ssh -R
+ publication of the notebook port was served the plaintext admin password by GET /.
+ """
+ import main
+
+ monkeypatch.setattr(main, "_IS_COLAB", True)
+ for header in main._PROXIED_CLIENT_HEADERS:
+ relayed = _request("127.0.0.1", "abc.ngrok-free.app", headers = {header: "203.0.113.7"})
+ assert main._should_inject_bootstrap(relayed) is False, header
+
+ # A raw TCP forward (bore, ssh -R) sets no header at all; the authority is still not Colab's.
+ assert main._should_inject_bootstrap(_request("127.0.0.1", "abc.ngrok-free.app")) is False
+
+ # Nor can a relay claim the authority: x-forwarded-for is tolerated, its companions are not.
+ spoofed = _request(
+ "127.0.0.1",
+ "abc123-8888-colab.googleusercontent.com",
+ headers = {"x-forwarded-host": "abc.ngrok-free.app"},
+ )
+ assert main._should_inject_bootstrap(spoofed) is False
+
+
+def test_colab_still_serves_a_direct_loopback_browser(monkeypatch):
+ """A browser inside the notebook VM keeps its autofill: Colab only widens, never narrows."""
+ import main
+
+ monkeypatch.setattr(main, "_IS_COLAB", True)
+ assert main._should_inject_bootstrap(_request("127.0.0.1", "localhost")) is True
+
+
def test_non_colab_gate_requires_local_client(monkeypatch):
"""Outside Colab the gate injects only for a direct loopback client."""
import main
diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.py
index 0eba6df5b11..91b41e75791 100644
--- a/studio/backend/tests/test_middleware.py
+++ b/studio/backend/tests/test_middleware.py
@@ -1368,3 +1368,87 @@ class TestCspHfEndpoints:
lan = TestClient(main_module.app, client = ("192.168.1.50", 40000))
lan_expected = "https://huggingface.co" if "127.0.0.1" in endpoint else endpoint
assert lan.get("/api/health").json()["hf_endpoint"] == lan_expected
+
+
+class TestRemoteAccessCORS:
+ """Publishing a tunnel must admit the tunnel, not every origin.
+
+ In plain --api-only (the desktop shell's own launch mode) the startup allowlist is the five
+ Tauri origins. Turning on Settings > Remote access used to replace that at request time with
+ unconditional reflection plus Access-Control-Allow-Credentials, on the loopback socket too, so
+ any page the user had open could read the local API's unauthenticated responses.
+ """
+
+ TUNNEL = "https://demo-abc.trycloudflare.com"
+
+ @staticmethod
+ def _client(main_module, allow_origins):
+ from utils.host_policy import cors_origins_for_mode
+
+ app = FastAPI()
+ app.state.cloudflare_url = None
+
+ @app.get("/api/auth/status")
+ async def _status():
+ return {"ok": True}
+
+ app.add_middleware(
+ main_module.RemoteAccessCORSMiddleware,
+ remote_access_state = app.state,
+ allow_origins = allow_origins or cors_origins_for_mode(api_only = True, secure = False),
+ allow_credentials = True,
+ allow_methods = ["*"],
+ allow_headers = ["*"],
+ max_age = 60,
+ )
+ return app, TestClient(app)
+
+ def _allowed(self, client, origin):
+ response = client.get("/api/auth/status", headers = {"Origin": origin})
+ return response.headers.get("access-control-allow-origin")
+
+ def _preflight(self, client, origin):
+ return client.options(
+ "/api/auth/status",
+ headers = {
+ "Origin": origin,
+ "Access-Control-Request-Method": "GET",
+ "Access-Control-Request-Headers": "authorization",
+ },
+ ).status_code
+
+ def test_a_published_tunnel_does_not_admit_an_arbitrary_origin(self, main_module):
+ app, client = self._client(main_module, None)
+ app.state.cloudflare_url = self.TUNNEL
+
+ for origin in ("https://evil.example", "null", "http://127.0.0.1:9999"):
+ assert self._allowed(client, origin) is None, origin
+ assert self._preflight(client, origin) == 400, origin
+
+ def test_the_tunnel_origin_itself_is_admitted(self, main_module):
+ app, client = self._client(main_module, None)
+ app.state.cloudflare_url = self.TUNNEL + "/"
+
+ # Default port and trailing slash are canonicalised, as _canonical_origin documents.
+ for origin in (self.TUNNEL, self.TUNNEL + ":443"):
+ assert self._allowed(client, origin) == origin, origin
+ assert self._preflight(client, origin) == 200, origin
+
+ app.state.cloudflare_url = None
+ assert self._allowed(client, self.TUNNEL) is None
+
+ def test_the_desktop_app_keeps_its_origin_either_way(self, main_module):
+ app, client = self._client(main_module, None)
+
+ for published in (None, self.TUNNEL):
+ app.state.cloudflare_url = published
+ assert self._allowed(client, "tauri://localhost") == "tauri://localhost"
+ assert self._preflight(client, "tauri://localhost") == 200
+
+ def test_the_browser_served_default_is_unchanged(self, main_module):
+ """Outside plain api-only the startup list is already ["*"]; nothing here narrows it."""
+ app, client = self._client(main_module, ["*"])
+
+ for published in (None, self.TUNNEL):
+ app.state.cloudflare_url = published
+ assert self._allowed(client, "https://evil.example") == "https://evil.example"
diff --git a/studio/backend/tests/test_reset_password_command.py b/studio/backend/tests/test_reset_password_command.py
index 7be94783a35..c190534f314 100644
--- a/studio/backend/tests/test_reset_password_command.py
+++ b/studio/backend/tests/test_reset_password_command.py
@@ -13,6 +13,7 @@ from __future__ import annotations
import ast
import importlib.util
+import os
import sys
from pathlib import Path
@@ -138,6 +139,11 @@ def test_the_prefix_check_locates_rather_than_imports(auth, tmp_path, monkeypatc
assert not auth._cli_is_inside(str(tmp_path / "venv"))
+ os.name == "nt",
+ reason = "spoofs os.name=posix, but tmp_path is then a real Windows path and shlex.quote "
+ "escapes its backslashes, so the assertion compares POSIX quoting against a Windows path",
+)
def test_posix_is_untouched(auth, monkeypatch, tmp_path):
"""The console script is what a POSIX user should run; nothing here changes."""
monkeypatch.setattr(auth.os, "name", "posix")
@@ -147,3 +153,54 @@ def test_posix_is_untouched(auth, monkeypatch, tmp_path):
monkeypatch.setattr(auth.sys, "executable", str(bin_dir / "python"))
assert auth._reset_password_command() == f"{bin_dir / 'unsloth'} studio reset-password"
+
+
+def test_the_console_warnings_name_the_absolute_command(monkeypatch, tmp_path):
+ """The absolute form has to be printed somewhere, and stderr on the host is that somewhere.
+
+ Without a production caller `_reset_password_command()` is dead, and a user whose shell has no
+ `unsloth` on PATH is left with a hint they cannot run. These two warnings go to the host's own
+ console, so naming the install there costs nothing and is the point.
+ """
+ run_py = (Path(__file__).resolve().parents[1] / "run.py").read_text()
+
+ tree = ast.parse(run_py)
+ calls = sum(
+ isinstance(node, ast.ImportFrom)
+ and node.module == "routes.auth"
+ and any(a.name == "_reset_password_command" for a in node.names)
+ for node in ast.walk(tree)
+ )
+ assert calls >= 2, (
+ "run.py's public-bind and reachable-bind warnings must print the absolute reset command; "
+ "without a production caller the helper is dead and the 401's PATH form is the only hint "
+ "a user ever sees"
+ )
+ assert (
+ "`unsloth studio reset-password`. Unsloth shuts down" not in run_py
+ ), "the public-bind warning is back to the bare PATH form"
+
+
+def test_the_unauthenticated_401_body_names_no_host_path(auth, monkeypatch, tmp_path):
+ """The console hint may name the install; the login failure body may not.
+
+ POST /api/auth/login takes no credential and the browser-served default resolves CORS to
+ ["*"], so any page the user has open can read this body. An absolute path built from
+ sys.executable hands it the OS account name and the install layout.
+ """
+ monkeypatch.setattr(auth.os, "name", "posix")
+ bin_dir = tmp_path / "home" / "alice" / "unsloth" / ".venv" / "bin"
+ bin_dir.mkdir(parents = True)
+ (bin_dir / "unsloth").write_text("", encoding = "utf-8")
+ monkeypatch.setattr(auth.sys, "executable", str(bin_dir / "python"))
+
+ # The console form is unchanged: that is the one the person at the machine reads.
+ assert str(bin_dir) in auth._reset_password_command()
+
+ for multi_user in (False, True):
+ monkeypatch.setattr(auth.policy, "installation_is_multi_user", lambda: multi_user)
+ detail = auth._login_failure_detail()
+ assert str(bin_dir) not in detail, multi_user
+ assert "alice" not in detail, multi_user
+ # Still actionable, which is the whole point of the hint.
+ assert "unsloth studio reset-password" in detail, multi_user
diff --git a/studio/backend/tests/test_secure_tunnel_gate.py b/studio/backend/tests/test_secure_tunnel_gate.py
index 0b6ef8ee0da..2396eb91eb5 100644
--- a/studio/backend/tests/test_secure_tunnel_gate.py
+++ b/studio/backend/tests/test_secure_tunnel_gate.py
@@ -312,20 +312,29 @@ def test_api_only_cors_tracks_published_public_url():
allow_methods = ["*"],
allow_headers = ["*"],
)
- request = Headers(
- {
- "origin": "https://browser-client.example",
- "access-control-request-method": "POST",
- "access-control-request-headers": "authorization,content-type",
- }
- )
- assert middleware.preflight_response(request).status_code == 400
- state.cloudflare_url = "https://public.trycloudflare.com"
- response = middleware.preflight_response(request)
+
+ def _preflight(origin):
+ return middleware.preflight_response(
+ Headers(
+ {
+ "origin": origin,
+ "access-control-request-method": "POST",
+ "access-control-request-headers": "authorization,content-type",
+ }
+ )
+ )
+
+ published = "https://public.trycloudflare.com"
+ assert _preflight(published).status_code == 400
+ state.cloudflare_url = published
+ response = _preflight(published)
assert response.status_code == 200
- assert response.headers["access-control-allow-origin"] == "https://browser-client.example"
+ assert response.headers["access-control-allow-origin"] == published
+ # The tunnel is the one origin that needs admitting, not a switch that admits all of them:
+ # plain api-only stays locked to the Tauri app for everyone else.
+ assert _preflight("https://browser-client.example").status_code == 400
state.cloudflare_url = None
- assert middleware.preflight_response(request).status_code == 400
+ assert _preflight(published).status_code == 400
def test_run_server_exports_secure_env_for_cors():
@@ -378,7 +387,7 @@ def test_cors_preflight_cache_window_is_short():
response = middleware.preflight_response(
Headers(
{
- "origin": "https://browser-client.example",
+ "origin": "https://x.trycloudflare.com",
"access-control-request-method": "POST",
"access-control-request-headers": "authorization",
}