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: add secure keyless localhost and private-LAN API access (#9102)

Maheswar Kumar55efa1eb67b2
diff --git a/studio/backend/auth/authentication.py b/studio/backend/auth/authentication.py
index 492622ad467..a12a3f8d6b0 100644
--- a/studio/backend/auth/authentication.py
+++ b/studio/backend/auth/authentication.py
@@ -3,15 +3,17 @@
import secrets
from datetime import datetime, timedelta, timezone
-from typing import Optional, Tuple
+from typing import Any, Optional, Tuple
-from fastapi import Depends, HTTPException, status
+from fastapi import Depends, HTTPException, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
+from fastapi.security.utils import get_authorization_scheme_param
import jwt
from starlette.concurrency import run_in_threadpool
from .storage import (
API_KEY_PREFIX,
+ DEFAULT_ADMIN_USERNAME,
credential_generation,
get_jwt_secret,
get_user_and_secret,
@@ -25,7 +27,167 @@ ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60
REFRESH_TOKEN_EXPIRE_DAYS = 7
-security = HTTPBearer() # Reads Authorization: Bearer <token>
+# internal schemes, never sent by a client: no token at all, and a token to ignore if unusable
+KEYLESS_SCHEME = "Keyless"
+KEYLESS_FALLBACK_SCHEME = "KeylessBearer"
+_KEYLESS_CREDENTIALS = HTTPAuthorizationCredentials(
+ scheme = KEYLESS_SCHEME,
+ credentials = "",
+)
+
+
+def is_keyless(credentials: Optional[HTTPAuthorizationCredentials]) -> bool:
+ """True when the keyless API access setting had a hand in admitting this caller."""
+ return credentials is not None and credentials.scheme in (
+ KEYLESS_SCHEME,
+ KEYLESS_FALLBACK_SCHEME,
+ )
+
+
+def _names_a_session(token: str) -> bool:
+ """Whether this bearer claims a Studio sign-in this install actually knows.
+
+ A session token stays authoritative even under keyless API access: letting an
+ expired one through would leave the app running as the admin instead of prompting
+ for a sign-in. The subject is confirmed against storage because the claim itself is
+ unverified here, so a token merely shaped like a JWT -- which is a legal value for
+ the ``api_key`` the OpenAI SDKs always send -- is treated as the credential it is.
+ """
+ subject = _decode_subject_without_verification(token)
+ return subject is not None and get_user_and_secret(subject) is not None
+
+
+def bearer_names_a_session(token: str) -> bool:
+ """Public form of the session check, for callers that only have the raw token."""
+ return _names_a_session(token)
+
+
+def bearer_is_valid_api_key(token: str) -> bool:
+ """Whether this bearer is an sk-unsloth key this install still accepts.
+
+ Such a key authenticates as itself even while keyless API access is on, so the
+ callers below must not treat it as a credential the setting had to stand in for.
+ Asked ahead of the real validation, so it leaves ``last_used_at`` to that one.
+ """
+ return (
+ token.startswith(API_KEY_PREFIX)
+ and validate_api_key_with_credential(token, touch = False) is not None
+ )
+
+
+def admitted_without_credential(credentials: Optional[HTTPAuthorizationCredentials]) -> bool:
+ """True when the keyless setting alone let this caller in.
+
+ Narrower than ``is_keyless``, which also covers a working API key that happened
+ to arrive while the setting was on. Routes whose effect outlives the setting need
+ this stricter form: turning keyless access back off has to undo what it allowed.
+ """
+ if credentials is None:
+ return False
+ if credentials.scheme == KEYLESS_SCHEME:
+ return True
+ return credentials.scheme == KEYLESS_FALLBACK_SCHEME
+
+
+def _request_would_use_keyless(request: Any) -> bool:
+ """Classify a request before the security dependency has recorded its result."""
+ from utils.keyless_api_access import APPROVED_DUMMY_BEARERS, keyless_request_allowed
+
+ if not keyless_request_allowed(request):
+ return False
+ try:
+ raw_headers = getattr(request, "scope", {}).get("headers") or ()
+ values = [
+ bytes(value).decode("latin-1")
+ for name, value in raw_headers
+ if bytes(name).lower() == b"authorization"
+ ]
+ except Exception:
+ return False
+ if not values:
+ return True
+ if len(values) != 1:
+ return False
+ scheme, token = get_authorization_scheme_param(values[0])
+ return scheme.lower() == "bearer" and token in APPROVED_DUMMY_BEARERS
+
+
+def request_admitted_without_credential(request: Request) -> bool:
+ """``admitted_without_credential`` for a caller that holds only the request.
+
+ Costs a key validation, so ask it late: past the cheap disqualifiers, next to the
+ effect being guarded.
+ """
+ from utils.keyless_api_access import request_was_admitted_keyless
+
+ recorded = request_was_admitted_keyless(request)
+ return _request_would_use_keyless(request) if recorded is None else recorded
+
+
+def admitted_without_session(request: Any) -> bool:
+ """True when keyless API access lets this request through with no Studio sign-in.
+
+ The single predicate behind both the auth dependency below and the route-level
+ checks that ask whether a caller is the Unsloth UI or a programmatic client.
+ """
+ from utils.keyless_api_access import request_was_admitted_keyless
+
+ recorded = request_was_admitted_keyless(request)
+ return _request_would_use_keyless(request) if recorded is None else recorded
+
+
+class _BearerOrKeyless(HTTPBearer):
+ """Read ``Authorization: Bearer <token>``, admitting a caller without one.
+
+ When the setting is off this behaves exactly like ``HTTPBearer``, errors included.
+ """
+
+ async def __call__(self, request: Request) -> Optional[HTTPAuthorizationCredentials]:
+ from utils.keyless_api_access import (
+ APPROVED_DUMMY_BEARERS,
+ keyless_request_allowed,
+ mark_keyless_admission,
+ request_was_admitted_keyless,
+ )
+
+ raw_headers = getattr(request, "scope", {}).get("headers") or ()
+ authorization = [
+ bytes(value).decode("latin-1")
+ for name, value in raw_headers
+ if bytes(name).lower() == b"authorization"
+ ]
+ if len(authorization) > 1:
+ mark_keyless_admission(request, False)
+ raise HTTPException(
+ status_code = status.HTTP_403_FORBIDDEN,
+ detail = "Invalid authentication credentials",
+ )
+ header = authorization[0] if authorization else ""
+ scheme, token = get_authorization_scheme_param(header)
+ usable_bearer = bool(scheme.lower() == "bearer" and token)
+ recorded = request_was_admitted_keyless(request)
+ eligible = (
+ await run_in_threadpool(keyless_request_allowed, request)
+ if recorded is None
+ else recorded
+ )
+ if not authorization and eligible:
+ mark_keyless_admission(request, True)
+ return _KEYLESS_CREDENTIALS
+ dummy = eligible and usable_bearer and token in APPROVED_DUMMY_BEARERS
+ mark_keyless_admission(request, dummy)
+ if dummy:
+ return HTTPAuthorizationCredentials(
+ scheme = KEYLESS_FALLBACK_SCHEME,
+ credentials = token,
+ )
+ if usable_bearer:
+ return HTTPAuthorizationCredentials(scheme = scheme, credentials = token)
+ return await super().__call__(request)
+
+
+# scheme_name pinned so the OpenAPI securitySchemes entry keeps its published name
+security = _BearerOrKeyless(scheme_name = "HTTPBearer") # Reads Authorization: Bearer <token>
def _get_secret_for_subject(subject: str) -> str:
@@ -182,11 +344,49 @@ async def authenticated_via_api_key(
"""True when the caller used an sk-unsloth API key, not a UI session JWT.
Lets routes treat programmatic API callers differently from the Unsloth UI
- (e.g. refuse a teardown the UI would allow).
+ (e.g. refuse a teardown the UI would allow). A keyless caller counts as an API
+ caller too: it is the same programmatic surface, only without the key, so every
+ guard an API key faces still applies to it.
"""
+ if is_keyless(credentials):
+ return True
return bool(credentials and credentials.credentials.startswith(API_KEY_PREFIX))
+async def credentials_for_token(
+ request: Any, token: Optional[str]
+) -> Optional[HTTPAuthorizationCredentials]:
+ """What ``security`` would resolve for a bearer the route read for itself.
+
+ Routes that take the token from somewhere the dependency cannot see, such as the
+ ``?token=`` query param an ``<img src>`` has to use, would otherwise miss keyless
+ API access entirely and answer 401 on a scope that covers them. None means no
+ usable credential and no setting to stand in for one.
+ """
+ from utils.keyless_api_access import APPROVED_DUMMY_BEARERS, keyless_request_allowed
+
+ # A real token is authoritative and never needs keyless classification. The
+ # remaining settings/listener reads use SQLite and DNS, so keep them off the
+ # event loop just like the normal credential lookup path.
+ if token and token not in APPROVED_DUMMY_BEARERS:
+ return HTTPAuthorizationCredentials(scheme = "Bearer", credentials = token)
+ eligible = await run_in_threadpool(keyless_request_allowed, request)
+ keyless = eligible and (token is None or token in APPROVED_DUMMY_BEARERS)
+ if token:
+ return HTTPAuthorizationCredentials(
+ scheme = KEYLESS_FALLBACK_SCHEME if keyless else "Bearer",
+ credentials = token,
+ )
+ return _KEYLESS_CREDENTIALS if keyless else None
+
+
+async def authenticated_without_credential(
+ credentials: HTTPAuthorizationCredentials = Depends(security),
+) -> bool:
+ """Dependency form of ``admitted_without_credential``."""
+ return admitted_without_credential(credentials)
+
+
def require_ui_session_for_local_commands(via_api_key: bool) -> None:
"""Refuse an sk-unsloth API key that asks to define a local (stdio) MCP command.
@@ -250,6 +450,23 @@ def _invalid_api_key_detail(token: str) -> str:
return "Invalid or expired API key"
+def _admin_credential(*, allow_password_change: bool) -> Tuple[str, Optional[str]]:
+ """Resolve the local admin for a caller admitted by the keyless API access setting."""
+ record = get_user_and_secret(DEFAULT_ADMIN_USERNAME)
+ if record is None:
+ raise HTTPException(
+ status_code = status.HTTP_401_UNAUTHORIZED,
+ detail = "Invalid or expired token",
+ )
+ _salt, _pwd_hash, jwt_secret, must_change_password = record
+ if must_change_password and not allow_password_change:
+ raise HTTPException(
+ status_code = status.HTTP_403_FORBIDDEN,
+ detail = "Password change required",
+ )
+ return DEFAULT_ADMIN_USERNAME, credential_generation(jwt_secret)
+
+
async def _get_current_credential(
credentials: HTTPAuthorizationCredentials, *, allow_password_change: bool
) -> Tuple[str, Optional[str]]:
@@ -261,6 +478,22 @@ async def _get_current_credential(
Credential reads run in the threadpool so stalled SQLite cannot block the event loop.
"""
+ if credentials.scheme == KEYLESS_SCHEME:
+ return await run_in_threadpool(
+ _admin_credential, allow_password_change = allow_password_change
+ )
+
+ if credentials.scheme == KEYLESS_FALLBACK_SCHEME:
+ from utils.keyless_api_access import APPROVED_DUMMY_BEARERS
+ if credentials.credentials not in APPROVED_DUMMY_BEARERS:
+ raise HTTPException(
+ status_code = status.HTTP_401_UNAUTHORIZED,
+ detail = "Invalid authentication credentials",
+ )
+ return await run_in_threadpool(
+ _admin_credential, allow_password_change = allow_password_change
+ )
+
token = credentials.credentials
# --- API key path (sk-unsloth-...) ---
diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.py
index e286198654c..a4f43d60523 100644
--- a/studio/backend/auth/storage.py
+++ b/studio/backend/auth/storage.py
@@ -1240,20 +1240,28 @@ def validate_api_key(raw_key: str) -> Optional[str]:
return verified[0] if verified else None
-def validate_api_key_with_credential(raw_key: str) -> Optional[Tuple[str, str]]:
+def validate_api_key_with_credential(
+ raw_key: str, *, touch: bool = True
+) -> Optional[Tuple[str, str]]:
"""Validate *raw_key* and return ``(username, jwt_secret)``, or ``None``.
Also updates ``last_used_at`` on success. The key check and the credential
read share one write transaction, so the returned version is the one the key
was actually valid under: a reset committing right after cannot have its new
generation handed to a request the key it revoked authenticated.
+
+ ``touch=False`` drops that stamp, and with it the write transaction, for a caller
+ that only asks whether the key authenticates and never binds a write to the
+ generation. One request must not count as two uses, and on sqlite the write lock
+ is global, so an advisory check has no business taking it.
"""
cache_id = _api_key_cache_id(raw_key)
cached_hash = _api_key_hash_cache.get(cache_id)
key_hash = cached_hash if cached_hash is not None else _pbkdf2_api_key(raw_key)
conn = get_connection()
try:
- conn.execute("BEGIN IMMEDIATE")
+ if touch:
+ conn.execute("BEGIN IMMEDIATE")
cur = conn.execute(
"SELECT id, username, is_active, expires_at FROM api_keys WHERE key_hash = ?",
(key_hash,),
@@ -1280,11 +1288,12 @@ def validate_api_key_with_credential(raw_key: str) -> Optional[Tuple[str, str]]:
secret = _current_secret(conn, row["username"])
if secret is None:
return None
- conn.execute(
- "UPDATE api_keys SET last_used_at = ? WHERE id = ?",
- (datetime.now(timezone.utc).isoformat(), row["id"]),
- )
- conn.commit()
+ if touch:
+ conn.execute(
+ "UPDATE api_keys SET last_used_at = ? WHERE id = ?",
+ (datetime.now(timezone.utc).isoformat(), row["id"]),
+ )
+ conn.commit()
return row["username"], secret
finally:
conn.rollback()
diff --git a/studio/backend/core/inference/llama_keepwarm.py b/studio/backend/core/inference/llama_keepwarm.py
index 8f0fd5dc9d8..0470e84a0d6 100644
--- a/studio/backend/core/inference/llama_keepwarm.py
+++ b/studio/backend/core/inference/llama_keepwarm.py
@@ -283,8 +283,8 @@ def _as_bytes(value) -> bytes:
return value if isinstance(value, bytes) else str(value).encode("utf-8", "replace")
-def _carries_bearer_credentials(scope) -> bool:
- """Whether this request carries the ``Authorization: Bearer`` its route demands.
+def _carries_bearer_credentials(scope, path: str = "") -> bool:
+ """Whether this request carries the credentials its route demands.
Every tracked media route depends on ``get_current_subject`` (HTTPBearer), so a request
without one is refused before any handler runs. Counting it anyway would still pin the
@@ -292,8 +292,16 @@ def _carries_bearer_credentials(scope) -> bool:
opens the POST and then withholds its body produces no response status either, so the
401/403 exclusion below never gets to run. One such connection, replaced as it times
out, would keep a multi-GB pipeline resident for good. Real clients always send the
- header, so requiring it costs a legitimate generation nothing.
+ header, so requiring it costs a legitimate generation nothing. Keyless API access is
+ the one case where a route demands no bearer at all. Its outer admission middleware
+ records that decision before keep-warm runs, so reuse the snapshot instead of
+ repeating settings, listener, and DNS work on this loop.
"""
+ from utils.keyless_api_access import KEYLESS_ADMISSION_STATE_KEY
+
+ state = scope.get("state")
+ if path and isinstance(state, dict) and state.get(KEYLESS_ADMISSION_STATE_KEY) is True:
+ return True
headers = scope.get("headers")
if headers is None:
# A real ASGI server always populates headers; a caller that does not is not a
@@ -328,7 +336,7 @@ class LlamaKeepWarmMiddleware:
from core.inference import media_keepwarm
media_owner = media_keepwarm.owner_for_path(path)
- if media_owner is not None and not _carries_bearer_credentials(scope):
+ if media_owner is not None and not _carries_bearer_credentials(scope, path):
# Cannot reach the backend, so it must not hold it warm (see the helper). The
# chat count keeps its own rule: /p/{run}/v1/chat/completions is public by
# design, so a missing bearer there is not proof of anything.
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 0dc4038d950..84fa25166a7 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -804,6 +804,7 @@ app = FastAPI(
redoc_url = None,
swagger_ui_oauth2_redirect_url = None,
)
+app.state.secure = os.environ.get("UNSLOTH_SECURE") == "1"
# The MCP surface is opt-in: it can start GPU jobs and write model artifacts.
if os.environ.get("UNSLOTH_STUDIO_ENABLE_MCP") == "1":
@@ -1346,6 +1347,10 @@ app.add_middleware(
max_age = 60,
)
+from utils.keyless_api_access import KeylessToolPolicyMiddleware # noqa: E402
+
+app.add_middleware(KeylessToolPolicyMiddleware)
+
from utils.remote_access_settings import RemoteAccessStopResponseMiddleware # noqa: E402
app.add_middleware(RemoteAccessStopResponseMiddleware)
@@ -1696,13 +1701,15 @@ async def health_check(request: Request):
# Nothing is detecting until a hardware-dependent operation runs; say so instead of making clients poll.
base["hardware_detection_deferred"] = True
auth = request.headers.get("authorization", "")
- if not auth.lower().startswith("bearer "):
- return base
+ bearer = auth.split(" ", 1)[1] if auth.lower().startswith("bearer ") else None
try:
+ from auth.authentication import credentials_for_token
from auth.authentication import get_current_subject as _gcs
- from fastapi.security import HTTPAuthorizationCredentials
- creds = HTTPAuthorizationCredentials(scheme = "Bearer", credentials = auth.split(" ", 1)[1])
+ # resolved rather than built, so a scope covering this route answers it in full
+ creds = await credentials_for_token(request, bearer)
+ if creds is None:
+ return base
# Must await: a bare coroutine is truthy and would skip the auth check
subject = await _gcs(creds)
except HTTPException:
diff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.py
index fce53ac08d9..53857403ea0 100644
--- a/studio/backend/routes/auth.py
+++ b/studio/backend/routes/auth.py
@@ -33,6 +33,7 @@ from models.users import Token
from auth import storage, hashing
from auth.authentication import (
authenticated_via_desktop_jwt,
+ authenticated_without_credential,
create_access_token,
create_refresh_token,
get_current_credential,
@@ -44,6 +45,24 @@ from auth.authentication import (
router = APIRouter()
+def _require_a_credential_of_its_own(what: str):
+ """Refuse a caller that nothing but keyless API access let in.
+
+ For effects that outlive the setting: turning keyless access back off does not
+ withdraw a key it handed out, restore one it destroyed, or undo a sign-out it
+ forced. Listing keys is refused with them because it names the key to revoke.
+ """
+
+ def dependency(no_credential: bool = Depends(authenticated_without_credential)) -> None:
+ if no_credential:
+ raise HTTPException(
+ status_code = status.HTTP_403_FORBIDDEN,
+ detail = f"{what} can only be done from the Unsloth UI or with an existing API key.",
+ )
+
+ return dependency
+
+
# Byte-identical to _WINDOWS_CLI_ENTRYPOINT in unsloth_cli/commands/studio.py and to
# the bootstrap unsloth_cli/__main__.py documents for user-site installs.
_CLI_BOOTSTRAP = (
@@ -479,7 +498,9 @@ async def login(payload: AuthLoginRequest, request: Request) -> Token:
@router.post("/logout", status_code = status.HTTP_204_NO_CONTENT)
async def logout(
- request: Request, current_subject: str = Depends(get_current_subject_allow_password_change)
+ request: Request,
+ current_subject: str = Depends(get_current_subject_allow_password_change),
+ _own_credential: None = Depends(_require_a_credential_of_its_own("Signing out")),
) -> Response:
"""Revoke refresh tokens for the subject; the access token is stateless and expires on its own."""
try:
@@ -610,6 +631,7 @@ async def change_password(
request: Request,
current_subject: str = Depends(get_current_subject_allow_password_change),
is_desktop: bool = Depends(authenticated_via_desktop_jwt),
+ _own_credential: None = Depends(_require_a_credential_of_its_own("Changing passwords")),
) -> Token:
"""Allow the authenticated user to replace the default password."""
record = storage.get_user_and_secret(current_subject)
@@ -692,7 +714,9 @@ def _row_to_api_key_response(row: dict) -> ApiKeyResponse:
@router.post("/api-keys", response_model = CreateApiKeyResponse)
async def create_api_key(
- payload: CreateApiKeyRequest, credential: tuple = Depends(get_current_credential)
+ payload: CreateApiKeyRequest,
+ credential: tuple = Depends(get_current_credential),
+ _own_credential: None = Depends(_require_a_credential_of_its_own("Managing API keys")),
) -> CreateApiKeyResponse:
"""Create a new API key. The raw key is returned once and cannot be retrieved later."""
current_subject, generation = credential
@@ -721,7 +745,10 @@ async def create_api_key(
@router.get("/api-keys", response_model = ApiKeyListResponse)
-def list_api_keys(current_subject: str = Depends(get_current_subject)) -> ApiKeyListResponse:
+def list_api_keys(
+ current_subject: str = Depends(get_current_subject),
+ _own_credential: None = Depends(_require_a_credential_of_its_own("Managing API keys")),
+) -> ApiKeyListResponse:
"""List all API keys for the authenticated user (raw keys are never exposed)."""
rows = storage.list_api_keys(current_subject)
return ApiKeyListResponse(
@@ -730,7 +757,11 @@ def list_api_keys(current_subject: str = Depends(get_current_subject)) -> ApiKey
@router.delete("/api-keys/{key_id}")
-async def revoke_api_key(key_id: int, current_subject: str = Depends(get_current_subject)) -> dict:
+async def revoke_api_key(
+ key_id: int,
+ current_subject: str = Depends(get_current_subject),
+ _own_credential: None = Depends(_require_a_credential_of_its_own("Managing API keys")),
+) -> dict:
"""Revoke (soft-delete) an API key."""
if not storage.revoke_api_key(current_subject, key_id):
raise HTTPException(
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 1ea9ed08087..bc1ddd84304 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2552,8 +2552,16 @@ def _request_api_key_token(request: Any) -> Optional[str]:
def _request_has_api_key(request: Any) -> bool:
- """Whether the request used any API key rather than an interactive session JWT."""
- return _request_api_key_token(request) is not None
+ """Whether the request used any API key rather than an interactive session JWT.
+
+ A keyless caller counts too: it sends no session either, so the saved-credential
+ rules that hold back an sk-unsloth key must hold it back the same way.
+ """
+ if _request_api_key_token(request) is not None:
+ return True
+ from auth.authentication import admitted_without_session
+
+ return admitted_without_session(request)
def _request_is_internal_workflow(request: Any) -> bool:
@@ -2617,7 +2625,9 @@ def _request_used_api_key(request: Any) -> bool:
# _request_is_internal_workflow where a Studio workflow needs its own connection.
token = _request_api_key_token(request)
if token is None:
- return False
+ # keyless traffic is someone using Unsloth as an API server too
+ from auth.authentication import admitted_without_session
+ return admitted_without_session(request)
try:
return not auth_storage.is_internal_api_key(token)
except Exception:
@@ -2806,20 +2816,23 @@ _ARTIFACT_PREVIEW_FRAME_HTML = """<!doctype html>
async def _authenticate_header_or_query(request: Request, token: Optional[str]) -> str:
"""Resolve the bearer token from the Authorization header or the ``?token=``
query param (needed for <img src> / <iframe>, which can't send custom
- headers), validate it, and return the subject. Raises 401 when absent."""
+ headers), validate it, and return the subject. Raises 401 when absent.
+
+ Routed through ``credentials_for_token`` so a scope that covers this path serves it
+ without a key, the way the routes behind ``security`` already do."""
auth_header = request.headers.get("authorization")
if auth_header and auth_header.lower().startswith("bearer "):
jwt_token = auth_header[7:]
- elif token:
- jwt_token = token
else:
+ jwt_token = token or None
+ from auth.authentication import credentials_for_token
+
+ creds = await credentials_for_token(request, jwt_token)
+ if creds is None:
raise HTTPException(
status_code = status.HTTP_401_UNAUTHORIZED,
detail = "Missing authentication token",
)
- from fastapi.security import HTTPAuthorizationCredentials
-
- creds = HTTPAuthorizationCredentials(scheme = "Bearer", credentials = jwt_token)
return await get_current_subject(creds)
@@ -6653,7 +6666,19 @@ async def _maybe_auto_switch_model(
warm_index_soon()
return
+ from auth.authentication import request_admitted_without_credential
+
+ keyless_caller = request_admitted_without_credential(fastapi_request)
+ # the keyless dialog offers the loaded model, so a stranger swaps or fetches nothing
+ if auto_switch_on and keyless_caller:
+ auto_switch_on = False
+ if not idle_unload_is_configured():
+ await _reject_unservable_model(requested_model, fastapi_request)
+ return
+
async def _resolve_and_switch() -> None:
+ from core.inference.openai_auto_download import looks_like_quant, split_model_ref
+
# Off the loop: a cold-cache rebuild walks several model dirs + HF caches.
# With auto-switch off (or an omitted-model reload-only request), skip the
# resolve so only the reload-stash path runs and no name is ever matched.
@@ -6698,6 +6723,19 @@ async def _maybe_auto_switch_model(
else: # pre-3-tuple stash: fall back to the path as the override key
target_id, variant = last
override_id = target_id
+ # A credential-less caller may restore only the model it explicitly
+ # named (or the reload-only sentinel used when the model is omitted).
+ # Check before loading so an unrelated name cannot trigger an expensive
+ # stash restore and only then receive the normal mismatch response.
+ if keyless_caller and not reload_only:
+ requested_base, requested_variant = split_model_ref(requested_model)
+ if not _matches_any(
+ requested_base, (target_id, override_id, public_model_id(target_id))
+ ) or (
+ looks_like_quant(requested_variant)
+ and (not variant or requested_variant.lower() != variant.lower())
+ ):
+ return
else:
# load_path is a concrete local path (never the bare repo id), so /load
# takes the local branch and cannot trigger a download. override_id is the
@@ -6706,8 +6744,6 @@ async def _maybe_auto_switch_model(
backend = get_llama_cpp_backend()
# A bare model id (no :VARIANT) is satisfied by any loaded quant of that
# repo, so it never reloads a different local quant that already serves it.
- from core.inference.openai_auto_download import looks_like_quant, split_model_ref
-
# A tag that names no quant (":latest", ":8b") means the repo, as
# _loaded_satisfies and the resolver read it. Treating it as a quant tears down
# a serving Q8 to load the preferred Q4 for a request either satisfies.
@@ -15072,6 +15108,14 @@ async def openai_chat_completions(
# ── External provider routing ────────────────────────────────
# encrypted_api_key is optional -- local providers (llama.cpp / vLLM / Ollama) may run without auth.
if payload.provider_id or payload.provider_type:
+ from auth.authentication import request_admitted_without_credential
+
+ # caller-chosen egress from this host, which is not the loaded model on offer
+ if request_admitted_without_credential(request):
+ raise HTTPException(
+ status_code = 403,
+ detail = "External providers can only be used from the Unsloth UI or with an API key.",
+ )
# External provider: this request won't touch the local GGUF, so drop it
# from the keep-warm count or its in-flight stream would falsely block a
# concurrent local model switch from proceeding.
@@ -27192,6 +27236,17 @@ async def openai_image_generations(
"Streaming image generation is not supported.", status = 400, param = "stream"
),
)
+ if body.response_format != "b64_json":
+ from auth.authentication import request_admitted_without_credential
+ if request_admitted_without_credential(request):
+ raise HTTPException(
+ status_code = 403,
+ detail = openai_error_body(
+ "URL image responses require an API key. Use response_format='b64_json' for keyless access.",
+ status = 403,
+ param = "response_format",
+ ),
+ )
try:
width, height = _parse_openai_image_size(body.size)
except ValueError as exc:
diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.py
index f02e90945e4..d1c2c6b526a 100644
--- a/studio/backend/routes/mcp_servers.py
+++ b/studio/backend/routes/mcp_servers.py
@@ -13,6 +13,7 @@ from fastapi import APIRouter, Depends, HTTPException
from auth.authentication import (
authenticated_via_api_key,
get_current_subject,
+ request_admitted_without_credential,
require_ui_session_for_local_commands,
)
from core.inference.mcp_client import (
@@ -52,6 +53,7 @@ router = APIRouter()
# Annotated, not a Depends default: these routes are also called directly by the
# tests, where a Depends object is truthy and would read as "API key".
ViaApiKey = Annotated[bool, Depends(authenticated_via_api_key)]
+WithoutCredential = Annotated[bool, Depends(request_admitted_without_credential)]
def _looks_like_command(value: str) -> bool:
@@ -116,12 +118,12 @@ def _normalize_headers(headers: dict[str, str] | None) -> dict[str, str] | None:
return out or None
-def _row_to_response(row: dict) -> McpServerResponse:
+def _row_to_response(row: dict, *, include_headers: bool = True) -> McpServerResponse:
return McpServerResponse(
id = row["id"],
display_name = row["display_name"],
url = row["url"],
- headers = parse_server_headers(row) or {},
+ headers = (parse_server_headers(row) or {}) if include_headers else {},
is_enabled = bool(row["is_enabled"]),
use_oauth = bool(row.get("use_oauth")),
created_at = row["created_at"],
@@ -132,15 +134,17 @@ def _row_to_response(row: dict) -> McpServerResponse:
# FastAPI offloads sync reads; mutations stay on-loop to preserve atomic sequences.
@router.get("/", response_model = list[McpServerResponse])
def list_mcp_servers(
- current_subject: str = Depends(get_current_subject), via_api_key: ViaApiKey = False
+ current_subject: str = Depends(get_current_subject),
+ via_api_key: ViaApiKey = False,
+ no_credential: WithoutCredential = False,
):
rows = mcp_servers_db.list_servers()
- if via_api_key:
+ if via_api_key or no_credential:
# Drop the row, not just its fields: `url` is the argv (carries
# credentials), `headers` is the subprocess env, and a blanked url would
# round-trip into update as a bogus command.
rows = [row for row in rows if not is_stdio(row["url"])]
- return [_row_to_response(row) for row in rows]
+ return [_row_to_response(row, include_headers = not no_credential) for row in rows]
@router.post("/", response_model = McpServerResponse, status_code = 201)
@@ -207,6 +211,7 @@ async def update_mcp_server(
payload: McpServerUpdate,
current_subject: str = Depends(get_current_subject),
via_api_key: ViaApiKey = False,
+ no_credential: WithoutCredential = False,
):
old = mcp_servers_db.get_server(server_id)
if not old:
@@ -257,7 +262,7 @@ async def update_mcp_server(
# Narrow to this row's env: another server row sharing the command but
# with a different env keeps its live sessions.
await asyncio.to_thread(close_stdio_sessions, old["url"], parse_server_headers(old))
- return _row_to_response(mcp_servers_db.get_server(server_id))
+ return _row_to_response(mcp_servers_db.get_server(server_id), include_headers = not no_credential)
@router.delete("/{server_id}", status_code = 204)
diff --git a/studio/backend/routes/preview.py b/studio/backend/routes/preview.py
index 06ccb6b4db2..0ef732220cc 100644
--- a/studio/backend/routes/preview.py
+++ b/studio/backend/routes/preview.py
@@ -14,7 +14,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
from loggers import get_logger
-from auth.authentication import get_current_subject
+from auth.authentication import authenticated_without_credential, get_current_subject
from auth.storage import DEFAULT_ADMIN_USERNAME
from models.inference import ChatCompletionRequest, LoadRequest
from routes.inference import (
@@ -182,9 +182,13 @@ async def _serve_chat(
@router.get("")
-async def list_previews(request: Request, current_subject: str = Depends(get_current_subject)):
+async def list_previews(
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
+ no_credential: bool = Depends(authenticated_without_credential),
+):
base = str(request.base_url)
- sharing_on = get_preview_sharing_enabled()
+ sharing_on = get_preview_sharing_enabled() and not no_credential
previews = []
for target in list_preview_targets():
ref = quote(target["ref"], safe = "/")
diff --git a/studio/backend/routes/rag.py b/studio/backend/routes/rag.py
index 596e54a85bc..c01c251b87f 100644
--- a/studio/backend/routes/rag.py
+++ b/studio/backend/routes/rag.py
@@ -26,13 +26,13 @@ import sqlite3
import time
import uuid
from contextlib import contextmanager
-from typing import Iterator
+from typing import Annotated, Iterator
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFile
from fastapi.responses import FileResponse, StreamingResponse
from pydantic import BaseModel, Field
-from auth.authentication import get_current_subject
+from auth.authentication import get_current_subject, request_admitted_without_credential
from core.rag import config, folder_sync, ingestion, retrieval, store
from storage import rag_db
from utils.paths import ensure_dir, rag_uploads_root
@@ -1036,8 +1036,17 @@ def preview_target(
@router.get("/documents/{document_id}/file-url")
-def document_file_url(document_id: str, subject: str = Depends(get_current_subject)) -> dict:
+def document_file_url(
+ document_id: str,
+ subject: str = Depends(get_current_subject),
+ no_credential: Annotated[bool, Depends(request_admitted_without_credential)] = False,
+) -> dict:
"""Mint a short-lived signed URL for the source file."""
+ if no_credential:
+ raise HTTPException(
+ status_code = 403,
+ detail = "Document links can only be created from the Unsloth UI or with an API key.",
+ )
_require_rag()
conn = _rag_connection()
try:
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 5482a2f7a59..925e5924510 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -97,6 +97,11 @@ from utils.openai_auto_switch_settings import (
set_model_override,
set_openai_auto_switch,
)
+from utils.keyless_api_access import (
+ access_exposure,
+ get_keyless_api_access_settings,
+ set_keyless_api_access,
+)
from utils.preview_sharing_settings import (
DEFAULT_PREVIEW_SHARING_ENABLED,
get_preview_sharing_enabled,
@@ -2007,6 +2012,17 @@ def rotate_preview_links(
return PreviewLinkRotateResponse(rotated = True)
+class KeylessApiAccessPayload(BaseModel):
+ scope: Literal["off", "inference", "full"]
+ tools: Optional[StrictBool] = None
+
+
+class KeylessApiAccessResponse(BaseModel):
+ scope: Literal["off", "inference", "full"]
+ tools: bool
+ exposure: Optional[Literal["colab", "public_url", "private_lan", "network"]] = None
+
+
class PreviewSharingPayload(BaseModel):
enabled: bool
@@ -2123,6 +2139,9 @@ class LanAccessResponse(BaseModel):
can_stop: bool
block_reason: Optional[str] = None
serves_web_ui: bool = True
+ keyless_lan_eligible: bool = False
+ keyless_scope: Literal["off", "inference", "full"] = "off"
+ keyless_tools: bool = False
def _lan_access_response(request: Request) -> LanAccessResponse:
@@ -2210,6 +2229,57 @@ def update_preview_sharing(
return PreviewSharingResponse(enabled = enabled)
+def _require_ui_session_for_keyless(via_api_key: bool = Depends(authenticated_via_api_key)) -> None:
+ """Only a signed-in UI session may change who needs a key.
+
+ An sk-unsloth key must not be able to switch authentication off for the whole
+ install, and a keyless caller must not be able to widen its own scope; both are
+ ``authenticated_via_api_key``, so one check covers them.
+ """
+ if via_api_key:
+ raise HTTPException(
+ status_code = 403,
+ detail = "Keyless API access can only be changed from the Unsloth UI.",
+ )
+
+
+def _keyless_api_access_response(request: Request) -> KeylessApiAccessResponse:
+ scope, tools = get_keyless_api_access_settings()
+ return KeylessApiAccessResponse(
+ scope = scope,
+ tools = tools,
+ exposure = access_exposure(request.app.state),
+ )
+
+
[email protected]("/keyless-api-access", response_model = KeylessApiAccessResponse)
+def get_keyless_api_access(
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
+ _ui_session: None = Depends(_require_ui_session_for_keyless),
+) -> KeylessApiAccessResponse:
+ return _keyless_api_access_response(request)
+
+
[email protected]("/keyless-api-access", response_model = KeylessApiAccessResponse)
+def update_keyless_api_access(
+ request: Request,
+ payload: KeylessApiAccessPayload,
+ current_subject: str = Depends(get_current_subject),
+ _ui_session: None = Depends(_require_ui_session_for_keyless),
+) -> KeylessApiAccessResponse:
+ """Choose which routes are served without an API key, and whether tools come too."""
+ scope, tools = set_keyless_api_access(payload.scope, tools = payload.tools)
+ logger.info(
+ "settings.keyless_api_access_updated subject=%s scope=%s tools=%s exposure=%s",
+ current_subject,
+ scope,
+ tools,
+ access_exposure(request.app.state),
+ )
+ return _keyless_api_access_response(request)
+
+
def _is_bundled_avatar_url(value: str) -> bool:
parsed = urlsplit(value)
if parsed.scheme or parsed.netloc:
diff --git a/studio/backend/routes/training_history.py b/studio/backend/routes/training_history.py
index 9f0dea2dc19..aecda1dc94d 100644
--- a/studio/backend/routes/training_history.py
+++ b/studio/backend/routes/training_history.py
@@ -15,7 +15,7 @@ from typing import Literal, Optional, Union
from fastapi import APIRouter, Depends, HTTPException, Query
from loggers import get_logger
-from auth.authentication import get_current_subject
+from auth.authentication import authenticated_without_credential, get_current_subject
from core.training.resume import artifacts_present, can_resume_run
from models import (
TrainingRunDeleteResponse,
@@ -282,10 +282,11 @@ async def list_training_runs(
limit: int = Query(50, ge = 1, le = 200),
offset: int = Query(0, ge = 0),
current_subject: str = Depends(get_current_subject),
+ no_credential: bool = Depends(authenticated_without_credential),
):
"""List training runs, newest first."""
result = list_runs(limit = limit, offset = offset)
- sharing_on = get_preview_sharing_enabled()
+ sharing_on = get_preview_sharing_enabled() and not no_credential
runs = await asyncio.to_thread(
_summaries_from_rows,
result["runs"],
@@ -298,7 +299,11 @@ async def list_training_runs(
@router.get("/runs/{run_id}", response_model = TrainingRunDetailResponse)
-async def get_training_run_detail(run_id: str, current_subject: str = Depends(get_current_subject)):
+async def get_training_run_detail(
+ run_id: str,
+ current_subject: str = Depends(get_current_subject),
+ no_credential: bool = Depends(authenticated_without_credential),
+):
"""Get a single training run with full config and metrics."""
run = get_run(run_id)
if run is None:
@@ -315,7 +320,7 @@ async def get_training_run_detail(run_id: str, current_subject: str = Depends(ge
summary = await asyncio.to_thread(
_summary_from_row,
run,
- get_preview_sharing_enabled(),
+ get_preview_sharing_enabled() and not no_credential,
)
return TrainingRunDetailResponse(
run = summary,
@@ -329,6 +334,7 @@ async def update_training_run(
run_id: str,
payload: TrainingRunUpdateRequest,
current_subject: str = Depends(get_current_subject),
+ no_credential: bool = Depends(authenticated_without_credential),
):
"""Update mutable fields on a training run (currently only display_name)."""
run = get_run(run_id)
@@ -347,7 +353,7 @@ async def update_training_run(
return await asyncio.to_thread(
_summary_from_row,
refreshed,
- get_preview_sharing_enabled(),
+ get_preview_sharing_enabled() and not no_credential,
)
diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.py
index 8ffdfe9cf1b..ee544b4a986 100644
--- a/studio/backend/routes/video.py
+++ b/studio/backend/routes/video.py
@@ -22,12 +22,12 @@ import hashlib as _hashlib
import hmac as _hmac
import secrets as _secrets
import time as _time
-from typing import Optional
+from typing import Annotated, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from pydantic import ValidationError
-from auth.authentication import get_current_subject
+from auth.authentication import get_current_subject, request_admitted_without_credential
from hub.dependencies import get_hf_token
from loggers import get_logger
from models.inference import (
@@ -612,11 +612,19 @@ def _verify_video_link_token(token: str) -> Optional[str]:
@router.get("/video/gallery/{video_id}/signed-url")
async def get_gallery_video_signed_url(
- video_id: str, current_subject: str = Depends(get_current_subject)
+ video_id: str,
+ current_subject: str = Depends(get_current_subject),
+ no_credential: Annotated[bool, Depends(request_admitted_without_credential)] = False,
):
"""A directly playable, range-capable link for one clip (bearer-gated to mint, HMAC to use).
Returned as a relative URL so it works behind any proxy the page itself is served through."""
+ if no_credential:
+ raise HTTPException(
+ status_code = 403,
+ detail = "Video links can only be created from the Unsloth UI or with an API key.",
+ )
+
from core.inference import video_gallery
path = await asyncio.to_thread(video_gallery.owned_video_path, video_id)
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 6f938009109..58bcb21f68a 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -2620,6 +2620,8 @@ def run_server(
app.state.server_url = f"http://{_url_host(_direct_host)}:{port}"
else:
app.state.server_url = None
+ # raw bind address: the keyless exposure warning must tell loopback from a wildcard bind
+ app.state.bind_host = host
app.state.secure = secure
app.state.llama_parallel_slots = llama_parallel_slots
diff --git a/studio/backend/tests/test_auth_lookup_off_event_loop.py b/studio/backend/tests/test_auth_lookup_off_event_loop.py
index c7cbaa6e6df..19caaedcfc0 100644
--- a/studio/backend/tests/test_auth_lookup_off_event_loop.py
+++ b/studio/backend/tests/test_auth_lookup_off_event_loop.py
@@ -58,10 +58,24 @@ def _desktop_case(monkeypatch, threads):
return authentication.authenticated_via_desktop_jwt(_credentials("token"))
+async def _keyless_case(monkeypatch, threads):
+ monkeypatch.setattr(
+ authentication, "get_user_and_secret", _record_thread(threads, ("s", "h", SECRET, False))
+ )
+ await authentication.get_current_subject(authentication._KEYLESS_CREDENTIALS)
+ from utils import keyless_api_access as keyless
+
+ monkeypatch.setattr(keyless, "keyless_request_allowed", _record_thread(threads, True))
+ await authentication.credentials_for_token(object(), None)
+ monkeypatch.setattr(keyless, "get_keyless_api_tools_enabled", _record_thread(threads, True))
+ await keyless.KeylessToolPolicyMiddleware(lambda *_args: asyncio.sleep(0))(
+ {"type": "http"}, None, None
+ )
+
+
@pytest.mark.parametrize(
"build_call",
- [_jwt_case, _api_key_case, _desktop_case],
- ids = ["session-jwt", "api-key", "desktop-jwt"],
+ [_jwt_case, _api_key_case, _desktop_case, _keyless_case],
)
def test_the_dependency_reads_off_the_event_loop_thread(monkeypatch, build_call):
threads: list[int] = []
@@ -73,7 +87,7 @@ def test_the_dependency_reads_off_the_event_loop_thread(monkeypatch, build_call)
loop_thread = asyncio.run(_drive())
assert threads, "the credential read never ran"
- assert threads[0] != loop_thread, "credential read ran on the event loop thread"
+ assert all(thread != loop_thread for thread in threads), "credential read ran on event loop"
def test_the_status_route_reads_off_the_event_loop_thread(monkeypatch):
diff --git a/studio/backend/tests/test_config_mutations_on_event_loop.py b/studio/backend/tests/test_config_mutations_on_event_loop.py
index 74abd7f61ab..05ff6758de4 100644
--- a/studio/backend/tests/test_config_mutations_on_event_loop.py
+++ b/studio/backend/tests/test_config_mutations_on_event_loop.py
@@ -155,6 +155,8 @@ def _drive(monkeypatch, case: _Case):
app.dependency_overrides[get_current_subject] = lambda: "u"
app.dependency_overrides[get_current_subject_allow_password_change] = lambda: "u"
app.dependency_overrides[authenticated_via_api_key] = lambda: False
+ app.dependency_overrides[auth_routes.authenticated_without_credential] = lambda: False
+ app.dependency_overrides[mcp_routes.request_admitted_without_credential] = lambda: False
app.dependency_overrides[get_current_credential] = lambda: ("u", None)
loop_threads: list[int] = []
diff --git a/studio/backend/tests/test_keyless_api_access.py b/studio/backend/tests/test_keyless_api_access.py
new file mode 100644
index 00000000000..f60084c59a3
--- /dev/null
+++ b/studio/backend/tests/test_keyless_api_access.py
@@ -0,0 +1,402 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import asyncio
+import secrets
+import threading
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException
+from starlette.requests import Request
+
+from auth import storage
+from auth.authentication import (
+ KEYLESS_FALLBACK_SCHEME,
+ KEYLESS_SCHEME,
+ admitted_without_credential,
+ admitted_without_session,
+ create_access_token,
+ get_current_subject,
+ security,
+)
+from utils.keyless_api_access import (
+ KeylessToolPolicyMiddleware,
+ KEYLESS_ADMISSION_STATE_KEY,
+ KEYLESS_API_ACCESS_SETTING_KEY,
+ _reset_scope_cache,
+ access_exposure,
+ asgi_request_is_keyless,
+ get_keyless_api_access_scope,
+ get_keyless_api_access_settings,
+ get_keyless_api_tools_enabled,
+ keyless_request_allowed,
+ scope_covers,
+ set_keyless_api_access,
+)
+
+
+# Keep this security matrix compact enough for the PR test-line budget.
+# fmt: off
[email protected](autouse = True)
+def isolated_auth_db(tmp_path, monkeypatch):
+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")
+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")
+ monkeypatch.setattr(storage, "_bootstrap_password", None)
+ monkeypatch.setattr(storage, "_api_key_pbkdf2_salt_cache", None)
+ storage._reset_api_key_hash_cache()
+ _reset_scope_cache()
+ yield
+ storage._reset_api_key_hash_cache()
+ _reset_scope_cache()
+
+
+def seed_user():
+ storage.create_initial_user(username = storage.DEFAULT_ADMIN_USERNAME,
+ password = "human-password-123", jwt_secret = secrets.token_urlsafe(64))
+
+
+def app_state(**overrides):
+ state = SimpleNamespace(bind_host = "127.0.0.1", secure = False,
+ remote_access_is_colab = False, lan_access_is_colab = False,
+ lan_access_secure_launch = False, cloudflare_url = None)
+ for name, value in overrides.items():
+ setattr(state, name, value)
+ return state
+
+
+def asgi_scope(*, path = "/v1/chat/completions", method = None, root_path = "",
+ headers = None, state = None, server = ("127.0.0.1", 8000),
+ client = ("127.0.0.1", 50000),):
+ return {
+ "type": "http",
+ "method": method or ("GET" if path.startswith("/v1/models") else "POST"),
+ "path": path,
+ "root_path": root_path,
+ "query_string": b"",
+ "scheme": "http",
+ "server": server,
+ "client": client,
+ "headers": [
+ (name.lower().encode(), value.encode()) for name, value in (headers or {}).items()
+ ],
+ "app": SimpleNamespace(state = state or app_state()),
+ }
+
+
+def request_for(**kwargs):
+ return Request(asgi_scope(**kwargs))
+
+
+def bearer_request(token, **kwargs):
+ return request_for(headers = {"Authorization": f"Bearer {token}"}, **kwargs)
+
+
+def resolve(request):
+ return asyncio.run(security(request))
+
+
+def subject_of(request):
+ return asyncio.run(get_current_subject(resolve(request)))
+
+
+def test_exact_route_matrix_matches_registered_topology():
+ from routes.inference import router
+
+ allowed_posts = "/v1/chat/completions /v1/chat/count_tokens /v1/completions /v1/embeddings /v1/messages /v1/messages/count_tokens /v1/responses".split()
+ denied_posts = "/v1/load /v1/unload /v1/validate /v1/generate/stream /v1/audio/speech /v1/images/generations /v1/external/openai/containers/create /v1x/chat".split()
+ allowed = {("POST", path) for path in allowed_posts} | {
+ ("GET", "/v1/models"), ("GET", "/v1/models/unsloth/model")}
+ denied = {("POST", path) for path in denied_posts} | {
+ ("POST", "/v1/models"), ("GET", "/v1/chat/completions"), ("GET", "/v1/sandbox/abc")}
+ assert all(scope_covers("inference", method, path) for method, path in allowed)
+ assert not any(scope_covers("inference", method, path) for method, path in denied)
+ assert scope_covers("inference", "GET", "/studio/v1/models/", "/studio/")
+ assert not scope_covers("inference", "GET", "/studio-v2/v1/models", "/studio")
+ assert not scope_covers("off", "POST", "/v1/chat/completions")
+ assert scope_covers("full", "POST", "/api/train/start")
+
+ registered = {(method, route.path) for route in router.routes
+ for method in getattr(route, "methods", set())}
+ intended = {("POST", path.removeprefix("/v1")) for path in allowed_posts} | {
+ ("GET", "/models"), ("GET", "/models/{model_id:path}")}
+ assert intended <= registered
+
+
+def test_settings_are_immediate_and_fail_closed(monkeypatch):
+ import storage.studio_db as studio_db
+
+ set_keyless_api_access("full", tools = True)
+ assert keyless_request_allowed(request_for()) is True
+ assert get_keyless_api_tools_enabled() is True
+ set_keyless_api_access("off")
+ assert keyless_request_allowed(request_for()) is False
+ assert get_keyless_api_tools_enabled() is False
+
+ set_keyless_api_access("full", tools = True)
+ monkeypatch.setattr(studio_db, "get_app_setting",
+ lambda *_a, **_k: (_ for _ in ()).throw(OSError("db unavailable")))
+ _reset_scope_cache()
+ assert (get_keyless_api_access_scope(), get_keyless_api_tools_enabled()) == ("off", False)
+
+
+def test_stale_refresh_cannot_reopen_a_closed_scope(monkeypatch):
+ import utils.keyless_api_access as keyless
+
+ set_keyless_api_access("full", tools = True)
+ _reset_scope_cache()
+ read_done, write_done = threading.Event(), threading.Event()
+ real_read = keyless._read_settings
+ observed = []
+
+ def delayed_read():
+ value = real_read()
+ read_done.set()
+ assert write_done.wait(timeout = 10)
+ return value
+
+ monkeypatch.setattr(keyless, "_read_settings", delayed_read)
+ reader = threading.Thread(target = lambda: observed.append(keyless._settings()))
+ reader.start()
+ try:
+ assert read_done.wait(timeout = 10)
+ set_keyless_api_access("off", tools = False)
+ finally:
+ write_done.set()
+ reader.join(timeout = 10)
+ assert observed == [("off", False)]
+
+
+def test_overlapping_writes_publish_in_commit_order(monkeypatch):
+ import storage.studio_db as studio_db
+
+ first_committed = threading.Event()
+ release_first = threading.Event()
+ second_committed = threading.Event()
+ real_upsert = studio_db.upsert_app_settings
+
+ def delayed_upsert(settings):
+ result = real_upsert(settings)
+ if settings[KEYLESS_API_ACCESS_SETTING_KEY] == "full":
+ first_committed.set()
+ assert release_first.wait(timeout = 10)
+ else:
+ second_committed.set()
+ return result
+
+ monkeypatch.setattr(studio_db, "upsert_app_settings", delayed_upsert)
+ first = threading.Thread(target = set_keyless_api_access,
+ args = ("full",), kwargs = {"tools": True})
+ second = threading.Thread(target = set_keyless_api_access,
+ args = ("off",), kwargs = {"tools": False})
+ first.start()
+ assert first_committed.wait(timeout = 10)
+ second.start()
+ try:
+ assert not second_committed.wait(timeout = 0.1)
+ finally:
+ release_first.set()
+ first.join(timeout = 10)
+ second.join(timeout = 10)
+
+ assert not first.is_alive() and not second.is_alive()
+ assert get_keyless_api_access_settings() == ("off", False)
+
+
+def test_full_scope_is_loopback_only():
+ set_keyless_api_access("full")
+ for server, client, bind_host in (
+ (("127.0.0.1", 8000), ("127.0.0.1", 50000), "127.0.0.1"),
+ (("::1", 8000), ("::1", 50000), "::1"),
+ (("::ffff:127.0.0.1", 8000), ("::ffff:127.0.0.1", 50000), "::1"),
+ (("localhost", 8000), ("localhost", 50000), "localhost"),
+ ):
+ assert keyless_request_allowed(request_for(
+ server = server, client = client, state = app_state(bind_host = bind_host)))
+
+
+def test_public_browser_and_private_lan_boundaries(monkeypatch):
+ import lan_access
+ from utils import host_policy
+
+ set_keyless_api_access("inference")
+ for overrides in ({"remote_access_is_colab": True}, {"secure": True},
+ {"cloudflare_url": "https://x.trycloudflare.com"}):
+ assert not keyless_request_allowed(request_for(state = app_state(**overrides)))
+ assert not keyless_request_allowed(request_for(headers = {"Origin": "https://evil.example"}))
+ assert access_exposure(app_state(
+ bind_host = "studio.lan", lan_access_launch_managed = True,
+ lan_access_launch_addresses = ("192.168.1.24",),
+ )) == "private_lan"
+
+ monkeypatch.setattr(lan_access, "lan_listener_status",
+ lambda: {"running": True, "port": 8888,
+ "addresses": ["192.168.1.24"]})
+ monkeypatch.setattr(host_policy, "_lan_connector_active", True)
+ assert access_exposure(app_state()) == "private_lan"
+ monkeypatch.setattr(lan_access, "lan_listener_status",
+ lambda: {"addresses": ["100.64.0.10"]})
+ assert access_exposure(app_state()) == "network"
+ monkeypatch.setattr(lan_access, "lan_listener_status",
+ lambda: {"running": True, "port": 8888,
+ "addresses": ["192.168.1.24"]})
+ monkeypatch.setattr(host_policy, "_remote_connector_active", True)
+ lan_request = request_for(method = "GET", path = "/v1/models",
+ server = ("192.168.1.24", 8888), client = ("192.168.1.90", 54321))
+ assert keyless_request_allowed(lan_request)
+ set_keyless_api_access("full")
+ assert not keyless_request_allowed(lan_request)
+ assert not keyless_request_allowed(request_for(state = app_state(bind_host = "0.0.0.0")))
+
+
+def test_credentials_never_downgrade_to_keyless():
+ seed_user()
+ set_keyless_api_access("full")
+ assert resolve(request_for()).scheme == KEYLESS_SCHEME
+ for token in ("not-needed", "lm-studio", "ollama"):
+ assert resolve(bearer_request(token)).scheme == KEYLESS_FALLBACK_SCHEME
+ set_keyless_api_access("inference")
+ with pytest.raises(HTTPException):
+ subject_of(bearer_request("not-needed", path = "/v1/load"))
+ set_keyless_api_access("full")
+
+ for header in ("Bearer arbitrary", "garbage", "Basic abc", "Bearer"):
+ with pytest.raises(HTTPException):
+ subject_of(request_for(headers = {"Authorization": header}))
+ duplicate = asgi_scope()
+ duplicate["headers"] = [
+ (b"authorization", b"Bearer not-needed"),
+ (b"authorization", b"Bearer not-needed"),
+ ]
+ with pytest.raises(HTTPException):
+ subject_of(Request(duplicate))
+
+ session = create_access_token(storage.DEFAULT_ADMIN_USERNAME)
+ assert subject_of(bearer_request(session)) == storage.DEFAULT_ADMIN_USERNAME
+ expired_session = create_access_token(
+ storage.DEFAULT_ADMIN_USERNAME, expires_delta = timedelta(seconds = -60))
+ with pytest.raises(HTTPException):
+ subject_of(bearer_request(expired_session))
+
+ valid, _ = storage.create_api_key(
+ username = storage.DEFAULT_ADMIN_USERNAME, name = "valid", expires_at = None)
+ assert subject_of(bearer_request(valid)) == storage.DEFAULT_ADMIN_USERNAME
+ for name, expires in (
+ ("expired", (datetime.now(timezone.utc) - timedelta(days = 1)).isoformat()),
+ ("revoked", None),
+ ):
+ raw, row = storage.create_api_key(
+ username = storage.DEFAULT_ADMIN_USERNAME, name = name, expires_at = expires
+ )
+ if name == "revoked":
+ storage.revoke_api_key(storage.DEFAULT_ADMIN_USERNAME, row["id"])
+ with pytest.raises(HTTPException):
+ subject_of(bearer_request(raw))
+
+
+def _middleware_policy(scope):
+ from state.tool_policy import get_tool_policy, reset_tool_policy, set_tool_policy
+
+ observed = []
+
+ async def downstream(*_args):
+ observed.append(get_tool_policy())
+
+ set_tool_policy(True)
+ try:
+ asyncio.run(KeylessToolPolicyMiddleware(downstream)(
+ scope, lambda: None, lambda _message: None))
+ finally:
+ reset_tool_policy()
+ return observed
+
+
+def test_tool_policy_and_api_identity(monkeypatch):
+ from core.inference.llama_keepwarm import _carries_bearer_credentials
+ from routes import inference
+
+ seed_user()
+ set_keyless_api_access("inference", tools = False)
+ request = request_for()
+ assert subject_of(request) == storage.DEFAULT_ADMIN_USERNAME
+ assert request.state.keyless_api_admitted is True
+ assert admitted_without_credential(resolve(request)) is True
+ assert admitted_without_session(request) is True
+ assert inference._request_has_api_key(request) is True
+ assert inference._request_used_api_key(request) is True
+ assert inference._request_is_saved_credential_workflow(request) is False
+ scope = asgi_scope(state = app_state())
+ scope["state"] = {KEYLESS_ADMISSION_STATE_KEY: True}
+ assert _carries_bearer_credentials(scope, "/v1/chat/completions") is True
+ assert _middleware_policy(asgi_scope()) == [False]
+
+ set_keyless_api_access("inference", tools = True)
+ assert _middleware_policy(asgi_scope()) == [True]
+ key, _ = storage.create_api_key(
+ username = storage.DEFAULT_ADMIN_USERNAME, name = "tools", expires_at = None)
+ set_keyless_api_access("inference", tools = False)
+ assert _middleware_policy(asgi_scope(headers = {"Authorization": f"Bearer {key}"})) == [True]
+
+ set_keyless_api_access("off")
+
+ async def enabled_between_layers(scope, *_args):
+ set_keyless_api_access("inference")
+ with pytest.raises(HTTPException):
+ await security(Request(scope))
+
+ asyncio.run(KeylessToolPolicyMiddleware(enabled_between_layers)(
+ asgi_scope(), lambda: None, lambda _message: None))
+
+
+def test_protected_side_effect_guards_remain_wired():
+ import inspect
+ from routes import auth, inference, mcp_servers, preview, rag, training_history, video
+
+ auth_source = inspect.getsource(auth)
+ assert auth_source.count("_require_a_credential_of_its_own(") >= 6
+ assert "_require_a_credential_of_its_own" in inspect.getsource(auth.change_password)
+ assert all(
+ "request_admitted_without_credential" in inspect.getsource(handler)
+ for handler in (inference._maybe_auto_switch_model, inference.openai_chat_completions)
+ )
+ assert all(
+ "authenticated_without_credential" in inspect.getsource(handler)
+ and "not no_credential" in inspect.getsource(handler)
+ for handler in (
+ preview.list_previews,
+ training_history.list_training_runs,
+ training_history.get_training_run_detail,
+ training_history.update_training_run,
+ )
+ )
+ assert all(
+ "request_admitted_without_credential" in inspect.getsource(handler)
+ for handler in (video.get_gallery_video_signed_url, rag.document_file_url)
+ )
+ assert "request_admitted_without_credential" in inspect.getsource(
+ inference.openai_image_generations
+ )
+ assert all(
+ "no_credential" in inspect.getsource(handler)
+ for handler in (mcp_servers.list_mcp_servers, mcp_servers.update_mcp_server)
+ )
+ main_source = (Path(__file__).parents[1] / "main.py").read_text(encoding = "utf-8")
+ assert 'app.state.secure = os.environ.get("UNSLOTH_SECURE") == "1"' in main_source
+ assert security.scheme_name == "HTTPBearer"
+
+
+def test_keyless_idle_restore_requires_the_requested_model(monkeypatch):
+ from core.inference import llama_keepwarm as kw; import auth.authentication as authentication
+ from studio.backend.tests import test_openai_auto_switch as auto
+ backend = auto._FakeBackend(None); rec = auto._LoadRecorder(backend)
+ auto._wire(monkeypatch, enabled = False, resolves_to = None, backend = backend, recorder = rec)
+ monkeypatch.setattr(auto.settings, "idle_unload_is_configured", lambda: True)
+ monkeypatch.setattr(kw, "_last_unloaded_model", ("/cache/snap/A", "Q4_K_M", "org/A-GGUF"))
+ monkeypatch.setattr(authentication, "request_admitted_without_credential", lambda _r: True)
+ auto._run_hook("org/B-GGUF"); assert rec.calls == []
+ auto._run_hook("org/A-GGUF:Q4_K_M"); assert len(rec.calls) == 1
+# fmt: on
diff --git a/studio/backend/tests/test_lan_access_settings.py b/studio/backend/tests/test_lan_access_settings.py
index e3c472af012..abef23b2403 100644
--- a/studio/backend/tests/test_lan_access_settings.py
+++ b/studio/backend/tests/test_lan_access_settings.py
@@ -113,6 +113,125 @@ def test_configure_reads_launch_ownership_from_the_bind_host(bind_host, launch_m
assert state.lan_access_ready is False
+def _transport_request(
+ *,
+ server = ("192.168.1.24", 8888),
+ client = ("192.168.1.90", 54321),
+ state = None,
+ headers = None,
+):
+ return Request(
+ {
+ "type": "http",
+ "method": "GET",
+ "path": "/v1/models",
+ "root_path": "",
+ "query_string": b"",
+ "headers": [
+ (name.lower().encode(), value.encode()) for name, value in (headers or {}).items()
+ ],
+ "server": server,
+ "client": client,
+ "app": SimpleNamespace(state = state or SimpleNamespace()),
+ }
+ )
+
+
+def _listener(
+ address = "192.168.1.24",
+ *,
+ running = True,
+ port = 8888,
+):
+ return {"running": running, "port": port, "addresses": [address]}
+
+
+ "server,client,listener,expected",
+ [
+ (("192.168.1.24", 8888), ("10.0.0.90", 54321), _listener(), True),
+ (("fd00::24", 8888), ("fe80::90", 54321), _listener("fd00::24"), True),
+ (("::ffff:192.168.1.24", 8888), ("::ffff:192.168.1.90", 54321), _listener(), True),
+ (("192.168.1.24", 8889), ("192.168.1.90", 54321), _listener(), False),
+ (("192.168.1.25", 8888), ("192.168.1.90", 54321), _listener(), False),
+ (("192.168.1.24", 8888), ("192.168.1.90", 54321), _listener(running = False), False),
+ (("64.227.100.5", 8888), ("192.168.1.90", 54321), _listener("64.227.100.5"), False),
+ (("192.168.1.24", 8888), ("8.8.8.8", 54321), _listener(), False),
+ (("192.168.1.24", 8888), ("127.0.0.1", 54321), _listener(), False),
+ (("127.0.0.1", 8888), ("192.168.1.90", 54321), _listener("127.0.0.1"), False),
+ (("192.168.1.24", 8888), None, None, False),
+ ],
+)
+def test_private_lan_live_listener_matrix(monkeypatch, server, client, listener, expected):
+ monkeypatch.setattr(lan_access, "lan_listener_status", lambda: listener)
+ assert (
+ lan_settings.request_on_lan_access(_transport_request(server = server, client = client))
+ is expected
+ )
+
+
+def test_private_lan_ignores_forwarding_headers(monkeypatch):
+ monkeypatch.setattr(lan_access, "lan_listener_status", lambda: _listener())
+ headers = dict.fromkeys(("host", "forwarded", "x-forwarded-for", "origin"), "192.168.1.90")
+ assert not lan_settings.request_on_lan_access(
+ _transport_request(
+ server = ("127.0.0.1", 8888),
+ client = ("127.0.0.1", 54321),
+ headers = headers,
+ )
+ )
+
+
+ "bind_host,resolved,server,secure,is_colab,expected",
+ [
+ ("192.168.1.24", None, "192.168.1.24", False, False, True),
+ ("0.0.0.0", None, "192.168.1.24", False, False, True),
+ ("::", None, "fd00::24", False, False, True),
+ ("studio.lan", "192.168.1.24", "192.168.1.24", False, False, True),
+ ("studio.lan", "127.0.0.1", "127.0.0.1", False, False, False),
+ ("studio.lan", "64.227.100.5", "64.227.100.5", False, False, False),
+ ("studio.lan", "error", "192.168.1.24", False, False, False),
+ ("192.168.1.24", None, "192.168.1.24", True, False, False),
+ ("192.168.1.24", None, "192.168.1.24", False, True, False),
+ ],
+)
+def test_private_lan_launch_managed_matrix(
+ monkeypatch, bind_host, resolved, server, secure, is_colab, expected
+):
+ def resolve(_host, port, **_kwargs):
+ if resolved == "error":
+ raise OSError("dns unavailable")
+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (resolved, port))]
+
+ if resolved is not None:
+ monkeypatch.setattr(socket, "getaddrinfo", resolve)
+ monkeypatch.setattr(
+ lan_access,
+ "lan_listener_status",
+ lambda: {"running": False, "port": None, "addresses": []},
+ )
+ state = SimpleNamespace()
+ lan_settings.configure_lan_access(
+ state,
+ port = 8888,
+ bind_host = bind_host,
+ secure = secure,
+ is_colab = is_colab,
+ frontend_served = True,
+ )
+ assert (
+ lan_settings.request_on_lan_access(
+ _transport_request(
+ server = (server, 8888),
+ client = ("192.168.1.90", 54321),
+ state = state,
+ )
+ )
+ is expected
+ )
+
+
# ── status ──
@@ -122,6 +241,22 @@ def test_a_loopback_launch_offers_a_startable_off_state():
assert status["block_reason"] is None
assert status["can_start"] is True and status["can_stop"] is False
assert status["urls"] == []
+ assert status["keyless_lan_eligible"] is False
+
+
+def test_lan_status_uses_one_fail_closed_keyless_state(monkeypatch):
+ import utils.keyless_api_access as keyless
+
+ monkeypatch.setattr(keyless, "get_keyless_api_access_settings", lambda: ("inference", True))
+ status = lan_settings.lan_access_status(_app())
+ assert (status["keyless_scope"], status["keyless_tools"]) == ("inference", True)
+
+ def unreadable():
+ raise OSError("settings unavailable")
+
+ monkeypatch.setattr(keyless, "get_keyless_api_access_settings", unreadable)
+ status = lan_settings.lan_access_status(_app())
+ assert (status["keyless_scope"], status["keyless_tools"]) == ("off", False)
@pytest.mark.parametrize(
@@ -150,6 +285,7 @@ def test_a_specific_host_launch_reports_the_address_it_was_given():
status = lan_settings.lan_access_status(_app(lan_access_launch_managed = True))
assert status["state"] == "online" and status["managed_by"] == "launch"
assert status["urls"] == ["http://192.168.1.24:8888"]
+ assert status["keyless_lan_eligible"] is True
assert status["can_stop"] is False
@@ -189,6 +325,7 @@ def test_a_publicly_routable_bind_is_flagged_so_the_ui_can_warn(monkeypatch):
status = lan_settings.lan_access_status(_app())
assert status["urls"] == ["http://192.168.1.24:8888", "http://64.227.100.5:8888"]
assert status["public_urls"] == ["http://64.227.100.5:8888"]
+ assert status["keyless_lan_eligible"] is True
@pytest.mark.parametrize(
@@ -214,7 +351,21 @@ def test_a_private_bind_carries_no_public_warning(monkeypatch):
"lan_listener_status",
lambda: {"running": True, "addresses": ["192.168.1.24"], "port": 8888, "error": None},
)
- assert lan_settings.lan_access_status(_app())["public_urls"] == []
+ status = lan_settings.lan_access_status(_app())
+ assert status["public_urls"] == []
+ assert status["keyless_lan_eligible"] is True
+
+
+def test_a_cgnat_bind_is_not_reported_as_keyless_lan(monkeypatch):
+ monkeypatch.setattr(
+ lan_access,
+ "lan_listener_status",
+ lambda: {"running": True, "addresses": ["100.64.0.10"], "port": 8888, "error": None},
+ )
+ status = lan_settings.lan_access_status(_app())
+ assert status["state"] == "online"
+ assert status["public_urls"] == []
+ assert status["keyless_lan_eligible"] is False
def test_api_only_launches_advertise_that_the_web_ui_is_not_served():
diff --git a/studio/backend/tests/test_mcp_stdio_api_key_gate.py b/studio/backend/tests/test_mcp_stdio_api_key_gate.py
index 73bea0ab489..fb247820cf3 100644
--- a/studio/backend/tests/test_mcp_stdio_api_key_gate.py
+++ b/studio/backend/tests/test_mcp_stdio_api_key_gate.py
@@ -216,21 +216,30 @@ def test_update_regates_after_the_oauth_clear_await(tmp_path, monkeypatch, stdio
assert mcp_servers_db.get_server("s1")["headers_json"] is None
-def test_update_allows_http_row_from_api_key(tmp_path, monkeypatch, stdio_on):
+def test_update_allows_http_row_but_redacts_saved_headers_from_keyless(
+ tmp_path, monkeypatch, stdio_on
+):
import routes.mcp_servers as routes_mcp
from models.mcp_servers import McpServerUpdate
_reset_db(tmp_path, monkeypatch)
- mcp_servers_db.create_server(id = "s1", display_name = "A", url = "https://a/mcp")
+ mcp_servers_db.create_server(
+ id = "s1",
+ display_name = "A",
+ url = "https://a/mcp",
+ headers_json = '{"Authorization": "Bearer t"}',
+ )
resp = asyncio.run(
routes_mcp.update_mcp_server(
"s1",
McpServerUpdate(display_name = "B"),
current_subject = "api-key-user",
via_api_key = True,
+ no_credential = True,
)
)
assert resp.display_name == "B"
+ assert resp.headers == {}
# ── refresh ─────────────────────────────────────────────────────────
@@ -447,6 +456,12 @@ def test_list_hides_stdio_rows_from_api_keys(tmp_path, monkeypatch, stdio_on):
# http(s) MCP stays fully usable from a key, headers included.
assert keyed[0].headers == {"Authorization": "Bearer t"}
+ keyless = routes_mcp.list_mcp_servers(
+ current_subject = "u", via_api_key = False, no_credential = True
+ )
+ assert [row.id for row in keyless] == ["http1"]
+ assert keyless[0].headers == {}
+
def test_list_shows_stdio_rows_to_a_ui_session(tmp_path, monkeypatch, stdio_on):
import routes.mcp_servers as routes_mcp
diff --git a/studio/backend/tests/test_mcp_tool_read_off_event_loop.py b/studio/backend/tests/test_mcp_tool_read_off_event_loop.py
index 9e6e7416056..7897b00ca5b 100644
--- a/studio/backend/tests/test_mcp_tool_read_off_event_loop.py
+++ b/studio/backend/tests/test_mcp_tool_read_off_event_loop.py
@@ -152,7 +152,7 @@ def test_the_cached_row_and_tools_are_one_snapshot_during_an_edit(monkeypatch):
monkeypatch.setattr(mcp_routes.mcp_servers_db, "update_server", _update_server)
monkeypatch.setattr(mcp_routes, "invalidate_tool_cache", _invalidate)
monkeypatch.setattr(mcp_routes, "close_stdio_sessions", lambda *_args, **_kwargs: None)
- monkeypatch.setattr(mcp_routes, "_row_to_response", lambda row: row)
+ monkeypatch.setattr(mcp_routes, "_row_to_response", lambda row, **_kwargs: row)
async def _read_snapshot():
async with mcp_client.mcp_server_snapshot_guard():
@@ -200,7 +200,7 @@ def test_queued_updates_recheck_the_stdio_api_key_gate(monkeypatch):
monkeypatch.setattr(mcp_routes.mcp_servers_db, "update_server", _update_server)
monkeypatch.setattr(mcp_routes, "invalidate_tool_cache", lambda _server_id: None)
monkeypatch.setattr(mcp_routes, "close_stdio_sessions", lambda *_args, **_kwargs: None)
- monkeypatch.setattr(mcp_routes, "_row_to_response", lambda row: row)
+ monkeypatch.setattr(mcp_routes, "_row_to_response", lambda row, **_kwargs: row)
async def _drive():
async with mcp_client.mcp_server_snapshot_guard():
diff --git a/studio/backend/tests/test_openai_images_generations_route.py b/studio/backend/tests/test_openai_images_generations_route.py
index af01b6c954b..814ca9107d6 100644
--- a/studio/backend/tests/test_openai_images_generations_route.py
+++ b/studio/backend/tests/test_openai_images_generations_route.py
@@ -251,6 +251,23 @@ def test_b64_response_shape(client):
assert item["b64_json"] == "QUJD"
+def test_keyless_caller_must_use_b64_response_format(client, monkeypatch):
+ import auth.authentication as authentication
+
+ monkeypatch.setattr(authentication, "request_admitted_without_credential", lambda _r: True)
+ refused = _post(client, {"prompt": "a sloth", "size": "256x256"})
+ assert refused.status_code == 403
+ assert refused.json()["error"]["param"] == "response_format"
+ assert client.backend.calls == []
+
+ allowed = _post(
+ client,
+ {"prompt": "a sloth", "size": "256x256", "response_format": "b64_json"},
+ )
+ assert allowed.status_code == 200
+ assert allowed.json()["data"][0]["b64_json"] == "QUJD"
+
+
def test_local_load_uses_base_repo_for_defaults(monkeypatch):
# repo_id is a local path naming no model; base_repo identifies FLUX.1-dev, so the route picks 28 steps / 3.5 guidance, not the 9/0 fallback.
backend = _FakeBackend(repo_id = "/models/my-flux", base_repo = "black-forest-labs/FLUX.1-dev")
diff --git a/studio/backend/tests/test_preview_routes.py b/studio/backend/tests/test_preview_routes.py
index 2bd55df328f..bad8ac2032e 100644
--- a/studio/backend/tests/test_preview_routes.py
+++ b/studio/backend/tests/test_preview_routes.py
@@ -102,6 +102,7 @@ def client(tmp_path, monkeypatch, captured):
app = FastAPI()
app.include_router(preview.router, prefix = "/p")
app.dependency_overrides[preview.get_current_subject] = lambda: "admin"
+ app.dependency_overrides[preview.authenticated_without_credential] = lambda: False
# raise_server_exceptions=False so a 5xx surfaces as a response, not a throw.
return TestClient(app, raise_server_exceptions = False)
@@ -181,6 +182,18 @@ def test_list_previews_omits_capability_when_sharing_disabled(client, monkeypatc
assert body["data"][0]["share_url"] is None
+def test_list_previews_omits_capability_for_keyless_caller(client, monkeypatch):
+ monkeypatch.setattr(
+ preview,
+ "list_preview_targets",
+ lambda: [{"ref": "demorun", "is_latest": True}],
+ )
+ client.app.dependency_overrides[preview.authenticated_without_credential] = lambda: True
+ body = client.get("/p").json()
+ assert body["data"][0]["key"] is None
+ assert body["data"][0]["share_url"] is None
+
+
# ── Path traversal / containment ────────────────────────────────────────────
diff --git a/studio/backend/tests/test_rag_preview.py b/studio/backend/tests/test_rag_preview.py
index 0ff27897bdf..89710f3ecec 100644
--- a/studio/backend/tests/test_rag_preview.py
+++ b/studio/backend/tests/test_rag_preview.py
@@ -129,6 +129,11 @@ def test_preview_routes_and_signed_file(rag_home, stub_embeddings):
== 401
)
+ from auth.authentication import request_admitted_without_credential
+
+ app.dependency_overrides[request_admitted_without_credential] = lambda: True
+ assert c.get(f"/api/rag/documents/{doc_id}/file-url").status_code == 403
+
def test_norm_token_decomposes_ligatures():
# NFKC folds ligature glyphs to ASCII so anchors match (search_for misses these).
diff --git a/studio/backend/tests/test_video_routes.py b/studio/backend/tests/test_video_routes.py
index 941178fb2a8..8d0e22e70bf 100644
--- a/studio/backend/tests/test_video_routes.py
+++ b/studio/backend/tests/test_video_routes.py
@@ -1208,6 +1208,22 @@ def test_signed_video_link_streams_without_a_bearer(client):
assert len(ranged.content) == 4
+def test_keyless_caller_cannot_mint_a_signed_video_link(client):
+ from routes import video as video_routes
+
+ client.post(
+ "/api/inference/video/load",
+ json = {"model_path": "unsloth/LTX-2.3-GGUF", "gguf_filename": "q.gguf"},
+ )
+ video_id = _generate_and_wait(client, {"prompt": "a"})["id"]
+ client.app.dependency_overrides[video_routes.request_admitted_without_credential] = lambda: True
+
+ response = client.get(f"/api/inference/video/gallery/{video_id}/signed-url")
+
+ assert response.status_code == 403
+ assert "API key" in response.json()["detail"]
+
+
def test_signed_video_link_rejects_tampering_and_other_ids(client):
client.post(
"/api/inference/video/load",
diff --git a/studio/backend/utils/host_policy.py b/studio/backend/utils/host_policy.py
index 0c6d40adce2..138d7fc51fc 100644
--- a/studio/backend/utils/host_policy.py
+++ b/studio/backend/utils/host_policy.py
@@ -106,6 +106,16 @@ def set_lan_connector_active(active: bool) -> None:
_lan_connector_active = bool(active)
+def tunnel_connector_active() -> bool:
+ """True while a tunnel is publishing this server past the local network."""
+ return _remote_connector_active
+
+
+def lan_connector_active() -> bool:
+ """True while a runtime LAN listener is serving the local network."""
+ return _lan_connector_active
+
+
def remote_connector_active() -> bool:
"""True while any connector can carry a request from beyond loopback."""
return _remote_connector_active or _lan_connector_active
diff --git a/studio/backend/utils/keyless_api_access.py b/studio/backend/utils/keyless_api_access.py
new file mode 100644
index 00000000000..fae6a2b7c69
--- /dev/null
+++ b/studio/backend/utils/keyless_api_access.py
@@ -0,0 +1,422 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Fail-closed admission policy for serving Studio without an API key.
+
+Off by default. When an admin turns it on, a request that sends no usable
+credential authenticates as the local admin, so ``curl`` and the OpenAI SDKs reach
+this server the way they reach LM Studio and Ollama.
+
+Two scopes, so opening up chat does not also open up training:
+
+``inference``
+ The OpenAI-compatible endpoints only, named one by one in
+ ``_INFERENCE_ROUTES``. Everything else keeps needing a key.
+``full``
+ Every route, but only for callers arriving and connecting over loopback.
+
+Server-side tools (python, terminal, web search) stay off for a keyless caller
+whatever the scope, until the admin ticks them on separately: ``/v1/chat/completions``
+runs that tool loop on this machine, so it is a bigger grant than chat itself.
+
+Public tunnels and Colab never receive keyless access. Private-LAN inference is
+accepted only through a live settings listener or the launch-managed bind that
+matches the ASGI accepting address and port. Signing in to Unsloth is unaffected.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from typing import Any, Optional
+
+KEYLESS_API_ACCESS_SETTING_KEY = "keyless_api_access_scope"
+KEYLESS_API_TOOLS_SETTING_KEY = "keyless_api_access_tools"
+DEFAULT_KEYLESS_API_TOOLS_ENABLED = False
+KEYLESS_SCOPE_OFF = "off"
+KEYLESS_SCOPE_INFERENCE = "inference"
+KEYLESS_SCOPE_FULL = "full"
+KEYLESS_SCOPES = (KEYLESS_SCOPE_OFF, KEYLESS_SCOPE_INFERENCE, KEYLESS_SCOPE_FULL)
+DEFAULT_KEYLESS_API_ACCESS_SCOPE = KEYLESS_SCOPE_OFF
+APPROVED_DUMMY_BEARERS = frozenset({"not-needed", "lm-studio", "ollama"})
+KEYLESS_ADMISSION_STATE_KEY = "keyless_api_admitted"
+
+# Named by method and normalized path: /v1 also aliases model loading, media,
+# sandbox, validation, and streaming side-effect routes.
+_INFERENCE_ROUTES = frozenset(
+ {
+ ("POST", "/v1/chat/completions"),
+ ("POST", "/v1/chat/count_tokens"),
+ ("POST", "/v1/completions"),
+ ("POST", "/v1/embeddings"),
+ ("POST", "/v1/messages"),
+ ("POST", "/v1/messages/count_tokens"),
+ ("GET", "/v1/models"),
+ ("POST", "/v1/responses"),
+ }
+)
+
+
+def _coerce_scope(value: Any) -> Optional[str]:
+ if isinstance(value, str) and value.strip().lower() in KEYLESS_SCOPES:
+ return value.strip().lower()
+ return None
+
+
+def _coerce_bool(value: Any) -> Optional[bool]:
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str):
+ normalized = value.strip().lower()
+ if normalized in {"1", "true", "yes", "on"}:
+ return True
+ if normalized in {"0", "false", "no", "off", ""}:
+ return False
+ return None
+
+
+# each read opens its own sqlite connection (~0.5ms), so hold the answer for a moment
+_SETTINGS_CACHE_TTL_S = 1.0
+_cached_settings: Optional[tuple[float, str, bool]] = None
+# bumped by every write, so a refresh can tell whether its read still describes the db
+_settings_generation = 0
+_cache_lock = threading.Lock()
+_write_lock = threading.Lock()
+
+
+def _reset_scope_cache() -> None:
+ """Test hook: forget settings cached before the DB was written directly."""
+ global _cached_settings
+ with _cache_lock:
+ _cached_settings = None
+
+
+def _read_settings() -> tuple[str, bool]:
+ try:
+ from storage.studio_db import get_app_setting
+ scope = _coerce_scope(get_app_setting(KEYLESS_API_ACCESS_SETTING_KEY, None))
+ tools = _coerce_bool(get_app_setting(KEYLESS_API_TOOLS_SETTING_KEY, None))
+ except Exception:
+ return KEYLESS_SCOPE_OFF, False
+ return (
+ scope or DEFAULT_KEYLESS_API_ACCESS_SCOPE,
+ DEFAULT_KEYLESS_API_TOOLS_ENABLED if tools is None else tools,
+ )
+
+
+def _settings() -> tuple[str, bool]:
+ """Read the persisted scope and tool grant; anything unreadable counts as off.
+
+ Unlike a normal setting these remove an authentication requirement, so a damaged
+ settings DB must never resolve to an open scope, and neither may a refresh that
+ read the DB before a write closed it: sqlite reads block, so a request can be
+ holding the old answer when the setting is turned off, and publishing it would
+ keep the server open for the rest of the TTL. The generation counter dates each
+ read against the writes, so only a read that still describes the DB is published.
+ """
+ global _cached_settings
+ now = time.monotonic()
+ with _cache_lock:
+ cached = _cached_settings
+ if cached is not None and now - cached[0] < _SETTINGS_CACHE_TTL_S:
+ return cached[1], cached[2]
+ generation = _settings_generation
+ scope, tools = _read_settings()
+ with _cache_lock:
+ if generation != _settings_generation:
+ published = _cached_settings
+ if published is not None:
+ return published[1], published[2]
+ else:
+ _cached_settings = (now, scope, tools)
+ return scope, tools
+
+
+def get_keyless_api_access_scope() -> str:
+ return _settings()[0]
+
+
+def get_keyless_api_access_settings() -> tuple[str, bool]:
+ """Return the canonical scope and tool grant from one settings generation."""
+ return _settings()
+
+
+def get_keyless_api_tools_enabled() -> bool:
+ """Whether a keyless caller may drive the server-side tool loop."""
+ return _settings()[1]
+
+
+def set_keyless_api_access(value: Any, *, tools: Any = None) -> tuple[str, bool]:
+ """Persist which routes are served without a key, and whether tools come with them."""
+ global _cached_settings, _settings_generation
+ scope = _coerce_scope(value)
+ if scope is None:
+ raise ValueError(f"Keyless API access scope must be one of: {', '.join(KEYLESS_SCOPES)}.")
+ with _write_lock:
+ allow_tools = get_keyless_api_tools_enabled() if tools is None else _coerce_bool(tools)
+ if allow_tools is None:
+ raise ValueError("Keyless tool access must be true or false.")
+ # tools are meaningless without a scope, and leaving them ticked would surprise
+ # whoever turns keyless back on later
+ allow_tools = allow_tools and scope != KEYLESS_SCOPE_OFF
+
+ from storage.studio_db import upsert_app_settings
+
+ upsert_app_settings(
+ {
+ KEYLESS_API_ACCESS_SETTING_KEY: scope,
+ KEYLESS_API_TOOLS_SETTING_KEY: allow_tools,
+ }
+ )
+ with _cache_lock:
+ _settings_generation += 1
+ _cached_settings = (time.monotonic(), scope, allow_tools)
+ return scope, allow_tools
+
+
+def access_exposure(app_state: Any) -> Optional[str]:
+ """How far this server reaches beyond the machine, or None for localhost only.
+
+ Advisory: it decides how bluntly the UI words the warning, never whether the
+ setting may be used. An unknown bind host is reported as network-reachable.
+ """
+ from utils.host_policy import (
+ is_external_host,
+ lan_connector_active,
+ tunnel_connector_active,
+ )
+
+ if bool(getattr(app_state, "remote_access_is_colab", False)):
+ return "colab"
+ if bool(getattr(app_state, "secure", False)):
+ return "public_url"
+ if getattr(app_state, "cloudflare_url", None) or tunnel_connector_active():
+ return "public_url"
+ if lan_connector_active():
+ from lan_access import lan_listener_status
+ from utils.lan_access_settings import _normalized_ip, _private_non_loopback
+
+ try:
+ addresses = tuple(_normalized_ip(value) for value in lan_listener_status()["addresses"])
+ except Exception:
+ return "network"
+ return (
+ "private_lan"
+ if addresses
+ and all(address is not None and _private_non_loopback(address) for address in addresses)
+ else "network"
+ )
+ if bool(getattr(app_state, "lan_access_launch_managed", False)):
+ from utils.lan_access_settings import _normalized_ip, _private_non_loopback
+ addresses = tuple(
+ _normalized_ip(value)
+ for value in (getattr(app_state, "lan_access_launch_addresses", ()) or ())
+ )
+ if addresses and all(
+ address is not None and _private_non_loopback(address) for address in addresses
+ ):
+ return "private_lan"
+ bind_host = getattr(app_state, "bind_host", None)
+ if not isinstance(bind_host, str) or is_external_host(bind_host):
+ return "network"
+ return None
+
+
+def normalize_request_path(path: str, root_path: str = "") -> str:
+ """Normalize trailing slash and an ASGI/FastAPI mount root."""
+ if not isinstance(path, str) or not path.startswith("/"):
+ return ""
+ root = root_path.rstrip("/") if isinstance(root_path, str) else ""
+ if root and root.startswith("/"):
+ if path == root:
+ path = "/"
+ elif path.startswith(f"{root}/"):
+ path = path[len(root) :]
+ return path.rstrip("/") or "/"
+
+
+def scope_covers(
+ scope: str,
+ method: str,
+ path: str,
+ root_path: str = "",
+) -> bool:
+ """Whether ``scope`` includes this exact method and normalized route."""
+ normalized = normalize_request_path(path, root_path)
+ normalized_method = method.upper() if isinstance(method, str) else ""
+ if scope == KEYLESS_SCOPE_FULL:
+ return bool(normalized and normalized_method)
+ if scope != KEYLESS_SCOPE_INFERENCE:
+ return False
+ if (normalized_method, normalized) in _INFERENCE_ROUTES:
+ return True
+ # The router intentionally exposes one dynamic retrieval template. Its method
+ # is still explicit; an empty id and every non-GET alias remain denied.
+ return normalized_method == "GET" and normalized.startswith("/v1/models/")
+
+
+def _request_app_state(request: Any):
+ try:
+ return request.app.state
+ except Exception:
+ return None
+
+
+def _hosted_mode_forbidden(app_state: Any) -> bool:
+ """Whether the whole launch mode forbids keyless admission."""
+ if app_state is None:
+ return True
+ if bool(getattr(app_state, "remote_access_is_colab", False)) or bool(
+ getattr(app_state, "lan_access_is_colab", False)
+ ):
+ return True
+ if bool(getattr(app_state, "secure", False)) or bool(
+ getattr(app_state, "lan_access_secure_launch", False)
+ ):
+ return True
+ return False
+
+
+def _public_tunnel_active(app_state: Any) -> bool:
+ """Whether loopback transport may actually be carrying a public tunnel request."""
+ if getattr(app_state, "cloudflare_url", None):
+ return True
+ try:
+ from utils.host_policy import tunnel_connector_active
+ return tunnel_connector_active()
+ except Exception:
+ return True
+
+
+def _full_scope_transport_allowed(request: Any, app_state: Any) -> bool:
+ from utils.lan_access_settings import _all_addresses_are, request_is_loopback
+
+ if not request_is_loopback(request):
+ return False
+ bind_host = getattr(app_state, "bind_host", None)
+ scope = getattr(request, "scope", {})
+ server = scope.get("server")
+ if not isinstance(bind_host, str) or bind_host in ("0.0.0.0", "::"):
+ return False
+ if not isinstance(server, (tuple, list)) or len(server) < 2:
+ return False
+ port = server[1]
+ return isinstance(port, int) and _all_addresses_are(
+ bind_host, port, lambda address: address.is_loopback
+ )
+
+
+def keyless_transport_allowed(request: Any, scope: str) -> bool:
+ """Enforce the loopback/private-LAN boundary from authoritative ASGI state."""
+ try:
+ if request.headers.get("origin") is not None:
+ return False
+ except Exception:
+ return False
+ app_state = _request_app_state(request)
+ if _hosted_mode_forbidden(app_state):
+ return False
+ if scope == KEYLESS_SCOPE_FULL:
+ if _public_tunnel_active(app_state):
+ return False
+ return _full_scope_transport_allowed(request, app_state)
+ if scope != KEYLESS_SCOPE_INFERENCE:
+ return False
+ from utils.lan_access_settings import request_is_loopback, request_on_lan_access
+
+ if request_on_lan_access(request):
+ return True
+ if _public_tunnel_active(app_state):
+ return False
+ return request_is_loopback(request)
+
+
+def keyless_request_allowed(request: Any) -> bool:
+ """Whether the route and transport are eligible for keyless authentication."""
+ scope = get_keyless_api_access_scope()
+ if scope == KEYLESS_SCOPE_OFF:
+ return False
+ asgi_scope = getattr(request, "scope", {})
+ method = asgi_scope.get("method", "")
+ path = asgi_scope.get("path", "")
+ root_path = asgi_scope.get("root_path", "")
+ if not scope_covers(scope, method, path, root_path):
+ return False
+ return keyless_transport_allowed(request, scope)
+
+
+def mark_keyless_admission(request: Any, admitted: bool) -> None:
+ """Publish the authoritative admission result for downstream policy decisions."""
+ try:
+ setattr(request.state, KEYLESS_ADMISSION_STATE_KEY, bool(admitted))
+ except Exception:
+ pass
+
+
+def request_was_admitted_keyless(request: Any) -> Optional[bool]:
+ """Return a recorded admission decision, or None before auth has classified it."""
+ try:
+ value = getattr(request.state, KEYLESS_ADMISSION_STATE_KEY)
+ except Exception:
+ return None
+ return value if isinstance(value, bool) else None
+
+
+class KeylessToolPolicyMiddleware:
+ """Hard-disable server-side tools for a keyless caller that was not granted them.
+
+ ``/v1/chat/completions`` runs python and terminal on this machine through the
+ tool loop, and ``unsloth studio run`` turns tools on by default, so serving that
+ route without a key would otherwise hand the loop to anyone who can reach it.
+ Mirrors what routes/preview.py does for the public ``/p`` surface.
+ """
+
+ def __init__(self, app):
+ self.app = app
+
+ async def __call__(self, asgi_scope, receive, send):
+ if asgi_scope.get("type") != "http":
+ await self.app(asgi_scope, receive, send)
+ return
+ from starlette.concurrency import run_in_threadpool
+
+ admitted = await run_in_threadpool(asgi_request_is_keyless, asgi_scope)
+ asgi_scope.setdefault("state", {})[KEYLESS_ADMISSION_STATE_KEY] = admitted
+ if not admitted:
+ await self.app(asgi_scope, receive, send)
+ return
+ if await run_in_threadpool(get_keyless_api_tools_enabled):
+ await self.app(asgi_scope, receive, send)
+ return
+ from state.tool_policy import tools_force_disabled
+
+ with tools_force_disabled():
+ await self.app(asgi_scope, receive, send)
+
+
+def asgi_request_is_keyless(asgi_scope) -> bool:
+ """Whether this ASGI request is admitted by the setting rather than by a credential.
+
+ Middleware-side twin of ``auth.authentication.admitted_without_credential``, reading
+ the raw scope because it runs before the request object exists. A Studio session and
+ a working API key both authenticate as themselves, so neither is keyless: applying
+ the tool restriction to an existing API client would take away tools it already had.
+ """
+ try:
+ from starlette.requests import Request
+ request = Request(asgi_scope)
+ except Exception:
+ return False
+ if not keyless_request_allowed(request):
+ return False
+ authorization = [
+ bytes(value).decode("latin-1")
+ for name, value in asgi_scope.get("headers") or ()
+ if bytes(name).lower() == b"authorization"
+ ]
+ if not authorization:
+ return True
+ if len(authorization) != 1:
+ return False
+ scheme, separator, token = authorization[0].partition(" ")
+ return bool(separator and scheme.lower() == "bearer" and token in APPROVED_DUMMY_BEARERS)
diff --git a/studio/backend/utils/lan_access_settings.py b/studio/backend/utils/lan_access_settings.py
index e19b75ef198..2c94b75c72d 100644
--- a/studio/backend/utils/lan_access_settings.py
+++ b/studio/backend/utils/lan_access_settings.py
@@ -10,6 +10,8 @@ answer across restarts.
from __future__ import annotations
+import ipaddress
+import socket
from typing import Any, Optional
from loggers import get_logger
@@ -19,6 +21,153 @@ logger = get_logger(__name__)
LAN_ACCESS_AUTO_START_KEY = "lan_access_auto_start"
DEFAULT_LAN_ACCESS_AUTO_START = False
+_PRIVATE_LAN_NETWORKS = (
+ ipaddress.ip_network("10.0.0.0/8"),
+ ipaddress.ip_network("172.16.0.0/12"),
+ ipaddress.ip_network("192.168.0.0/16"),
+ ipaddress.ip_network("169.254.0.0/16"),
+ ipaddress.ip_network("fc00::/7"),
+ ipaddress.ip_network("fe80::/10"),
+)
+
+
+def _normalized_ip(address: str):
+ """Parse one literal address, normalizing IPv4-mapped IPv6."""
+ if not isinstance(address, str):
+ return None
+ value = address.strip().strip("[]")
+ if "%" in value:
+ value = value.split("%", 1)[0]
+ try:
+ parsed = ipaddress.ip_address(value)
+ except ValueError:
+ return None
+ if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped is not None:
+ return parsed.ipv4_mapped
+ return parsed
+
+
+def _resolve_host_addresses(host: str, port: int) -> tuple:
+ """Resolve a literal or hostname to normalized transport addresses."""
+ literal = _normalized_ip(host)
+ if literal is not None:
+ return (literal,)
+ if not isinstance(host, str) or not isinstance(port, int) or port <= 0:
+ return ()
+ try:
+ infos = socket.getaddrinfo(host, port, type = socket.SOCK_STREAM)
+ except OSError:
+ return ()
+ addresses = []
+ for _family, _kind, _protocol, _name, sockaddr in infos:
+ if not sockaddr:
+ continue
+ parsed = _normalized_ip(sockaddr[0])
+ if parsed is not None and parsed not in addresses:
+ addresses.append(parsed)
+ return tuple(addresses)
+
+
+def _private_non_loopback(address) -> bool:
+ return not address.is_loopback and any(address in network for network in _PRIVATE_LAN_NETWORKS)
+
+
+def _all_addresses_are(host: str, port: int, predicate) -> bool:
+ addresses = _resolve_host_addresses(host, port)
+ return bool(addresses) and all(predicate(address) for address in addresses)
+
+
+def request_is_loopback(request) -> bool:
+ """Whether both authoritative transport endpoints are loopback."""
+ scope = getattr(request, "scope", {})
+ server = scope.get("server")
+ client = scope.get("client")
+ if not isinstance(server, (tuple, list)) or len(server) < 2:
+ return False
+ if not isinstance(client, (tuple, list)) or len(client) < 1:
+ return False
+ server_host, server_port = server[0], server[1]
+ client_host = client[0]
+ if not isinstance(server_host, str) or not isinstance(server_port, int):
+ return False
+ if not isinstance(client_host, str):
+ return False
+ return _all_addresses_are(server_host, server_port, lambda address: address.is_loopback) and (
+ _all_addresses_are(client_host, server_port, lambda address: address.is_loopback)
+ )
+
+
+def _addresses_match(host: str, port: int, candidates) -> bool:
+ request_addresses = set(_resolve_host_addresses(host, port))
+ if not request_addresses:
+ return False
+ configured = set()
+ for candidate in candidates or ():
+ if isinstance(candidate, str):
+ configured.update(_resolve_host_addresses(candidate, port))
+ return bool(request_addresses & configured)
+
+
+def request_on_lan_access(request) -> bool:
+ """Classify a request from ASGI socket state, never client-controlled headers.
+
+ Both the accepting endpoint and peer must be private and non-loopback. The
+ accepting endpoint must also match either the exact live settings listener or
+ the launch-managed bind and port published at startup.
+ """
+ from lan_access import lan_listener_status
+
+ scope = getattr(request, "scope", {})
+ server = scope.get("server")
+ client = scope.get("client")
+ if not isinstance(server, (tuple, list)) or len(server) < 2:
+ return False
+ if not isinstance(client, (tuple, list)) or len(client) < 1:
+ return False
+ server_host, server_port = server[0], server[1]
+ client_host = client[0]
+ if not isinstance(server_host, str) or not isinstance(server_port, int):
+ return False
+ if not isinstance(client_host, str):
+ return False
+ if not _all_addresses_are(server_host, server_port, _private_non_loopback):
+ return False
+ if not _all_addresses_are(client_host, server_port, _private_non_loopback):
+ return False
+
+ try:
+ listener = lan_listener_status()
+ except Exception:
+ return False
+ if not isinstance(listener, dict):
+ return False
+ if (
+ listener.get("running") is True
+ and listener.get("port") == server_port
+ and _addresses_match(server_host, server_port, listener.get("addresses"))
+ ):
+ return True
+
+ try:
+ app_state = request.app.state
+ except Exception:
+ return False
+ if bool(getattr(app_state, "lan_access_is_colab", False)):
+ return False
+ if bool(getattr(app_state, "lan_access_secure_launch", False)):
+ return False
+ if not bool(getattr(app_state, "lan_access_launch_managed", False)):
+ return False
+ if getattr(app_state, "lan_access_port", None) != server_port:
+ return False
+ if bool(getattr(app_state, "lan_access_wildcard_bind", False)):
+ return True
+ return _addresses_match(
+ server_host,
+ server_port,
+ getattr(app_state, "lan_access_launch_addresses", ()),
+ )
+
def _coerce_bool(value: Any) -> Optional[bool]:
return value if isinstance(value, bool) else None
@@ -56,12 +205,19 @@ def configure_lan_access(
app_state, *, port: int, bind_host: str, secure: bool, is_colab: bool, frontend_served: bool
) -> None:
"""Publish immutable launch policy used by every settings request."""
- from utils.host_policy import is_external_host
-
app_state.lan_access_port = port
app_state.lan_access_wildcard_bind = bind_host in ("0.0.0.0", "::")
- app_state.lan_access_launch_managed = app_state.lan_access_wildcard_bind or is_external_host(
- bind_host
+ app_state.lan_access_bind_host = bind_host
+ app_state.lan_access_launch_addresses = tuple(
+ str(address) for address in _resolve_host_addresses(bind_host, port)
+ )
+ resolved_loopback = bool(app_state.lan_access_launch_addresses) and all(
+ _normalized_ip(address).is_loopback for address in app_state.lan_access_launch_addresses
+ )
+ # An unresolved hostname is launch-managed but never trusted for keyless LAN
+ # admission: request_on_lan_access requires its resolved address set.
+ app_state.lan_access_launch_managed = (
+ app_state.lan_access_wildcard_bind or not resolved_loopback
)
# --secure forces the loopback bind precisely so the raw port is never exposed
app_state.lan_access_secure_launch = bool(secure)
@@ -96,13 +252,36 @@ def _listener_urls(addresses, port: Optional[int]) -> list[str]:
return [f"http://{address}:{port}" for address in addresses]
-def _public_urls(urls: list[str]) -> list[str]:
+def _public_urls(urls: list[str], resolved_addresses: tuple[str, ...] = ()) -> list[str]:
"""The subset reachable from the internet rather than only this network."""
from urllib.parse import urlparse
- from lan_access import is_public_address
-
- return [url for url in urls if is_public_address(urlparse(url).hostname or "")]
+ resolved = []
+ for address in resolved_addresses:
+ parsed = _normalized_ip(address)
+ if parsed is not None:
+ resolved.append(parsed)
+ if any(address.is_global for address in resolved):
+ return list(urls)
+ public = []
+ for url in urls:
+ parsed = urlparse(url)
+ port = parsed.port or 80
+ addresses = _resolve_host_addresses(parsed.hostname or "", port)
+ if addresses and any(address.is_global for address in addresses):
+ public.append(url)
+ return public
+
+
+def _has_keyless_lan_url(urls: list[str]) -> bool:
+ from urllib.parse import urlparse
+ for url in urls:
+ parsed = urlparse(url)
+ if parsed.hostname and _all_addresses_are(
+ parsed.hostname, parsed.port or 80, _private_non_loopback
+ ):
+ return True
+ return False
def lan_access_status(app) -> dict:
@@ -142,10 +321,18 @@ def lan_access_status(app) -> dict:
urls, managed_by = [], None
controllable = block_reason is None
+ try:
+ from utils.keyless_api_access import get_keyless_api_access_settings
+ keyless_scope, keyless_tools = get_keyless_api_access_settings()
+ except Exception:
+ keyless_scope, keyless_tools = "off", False
return {
"state": state,
"urls": urls,
- "public_urls": _public_urls(urls),
+ "public_urls": _public_urls(
+ urls,
+ getattr(app_state, "lan_access_launch_addresses", ()) if launch_managed else (),
+ ),
"error": listener["error"],
"auto_start": get_lan_access_auto_start(),
"managed_by": managed_by,
@@ -153,6 +340,9 @@ def lan_access_status(app) -> dict:
"can_stop": controllable and running,
"block_reason": block_reason,
"serves_web_ui": frontend_served,
+ "keyless_lan_eligible": _has_keyless_lan_url(urls),
+ "keyless_scope": keyless_scope,
+ "keyless_tools": keyless_tools,
}
diff --git a/studio/frontend/src/features/settings/api/keyless-api-access.ts b/studio/frontend/src/features/settings/api/keyless-api-access.ts
new file mode 100644
index 00000000000..a7d43867ffd
--- /dev/null
+++ b/studio/frontend/src/features/settings/api/keyless-api-access.ts
@@ -0,0 +1,81 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { authFetch } from "@/features/auth";
+import { readFastApiError } from "@/lib/format-fastapi-error";
+
+export type KeylessApiAccessScope = "off" | "inference" | "full";
+export type KeylessApiAccessExposure =
+ | "colab"
+ | "public_url"
+ | "private_lan"
+ | "network";
+
+export type KeylessApiAccessSettings = {
+ scope: KeylessApiAccessScope;
+ tools: boolean;
+ exposure: KeylessApiAccessExposure | null;
+};
+
+type ApiKeylessApiAccessSettings = {
+ scope: KeylessApiAccessScope;
+ tools: boolean;
+ exposure?: KeylessApiAccessExposure | null;
+};
+
+function fromApi(
+ settings: ApiKeylessApiAccessSettings,
+): KeylessApiAccessSettings {
+ return {
+ scope: settings.scope,
+ tools: settings.tools,
+ exposure: settings.exposure ?? null,
+ };
+}
+
+export async function loadKeylessApiAccess(): Promise<KeylessApiAccessSettings> {
+ const res = await authFetch("/api/settings/keyless-api-access");
+ if (!res.ok) {
+ throw new Error(
+ await readFastApiError(res, "Failed to load keyless API access settings"),
+ );
+ }
+ return fromApi(await res.json());
+}
+
+export async function updateKeylessApiAccess(
+ scope: KeylessApiAccessScope,
+ tools?: boolean,
+): Promise<KeylessApiAccessSettings> {
+ const res = await authFetch("/api/settings/keyless-api-access", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ scope, tools: tools ?? null }),
+ });
+ if (!res.ok) {
+ throw new Error(
+ await readFastApiError(
+ res,
+ "Failed to update keyless API access settings",
+ ),
+ );
+ }
+ return fromApi(await res.json());
+}
+
+/** who can reach this server once a scope is on */
+export function keylessAudience(
+ exposure: KeylessApiAccessExposure | null,
+): string {
+ switch (exposure) {
+ case "public_url":
+ return "Anyone with your public URL";
+ case "network":
+ case "private_lan":
+ return "Anyone on your network";
+ case "colab":
+ return "Anyone who can reach this Colab runtime";
+ default:
+ return "Anything running on this computer";
+ }
+}
diff --git a/studio/frontend/src/features/settings/api/lan-access-state.ts b/studio/frontend/src/features/settings/api/lan-access-state.ts
index 800bb57c5ed..3b5bf57f4d3 100644
--- a/studio/frontend/src/features/settings/api/lan-access-state.ts
+++ b/studio/frontend/src/features/settings/api/lan-access-state.ts
@@ -3,6 +3,7 @@
export type LanAccessState = "off" | "online" | "error";
export type LanAccessOwner = "launch" | "settings" | null;
+export type LanKeylessScope = "off" | "inference" | "full";
export type LanAccessStatus = {
state: LanAccessState;
@@ -15,6 +16,9 @@ export type LanAccessStatus = {
canStop: boolean;
blockReason: string | null;
servesWebUi: boolean;
+ keylessLanEligible: boolean;
+ keylessScope: LanKeylessScope;
+ keylessTools: boolean;
};
export type ApiLanAccessStatus = {
@@ -35,11 +39,22 @@ export type ApiLanAccessStatus = {
block_reason?: string | null;
// biome-ignore lint/style/useNamingConvention: API schema
serves_web_ui?: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ keyless_lan_eligible?: boolean | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ keyless_scope?: LanKeylessScope | string | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ keyless_tools?: boolean | null;
};
+function normalizeKeylessScope(value: unknown): LanKeylessScope {
+ return value === "inference" || value === "full" ? value : "off";
+}
+
export function normalizeLanAccessStatus(
status: ApiLanAccessStatus,
): LanAccessStatus {
+ const keylessScope = normalizeKeylessScope(status.keyless_scope);
return {
state: status.state,
urls: Array.isArray(status.urls) ? status.urls : [],
@@ -52,9 +67,36 @@ export function normalizeLanAccessStatus(
blockReason: status.block_reason ?? null,
// absent on a backend that predates the field, where the web UI is served
servesWebUi: status.serves_web_ui !== false,
+ keylessLanEligible: status.keyless_lan_eligible === true,
+ keylessScope,
+ keylessTools: keylessScope !== "off" && status.keyless_tools === true,
};
}
+export function keylessLanAccessDescription(
+ status: LanAccessStatus | null,
+): string {
+ if (!status || status.keylessScope === "off") {
+ return "Authentication is required for LAN API requests.";
+ }
+ if (status.blockReason === "colab") {
+ return "Colab never receives keyless access, regardless of the saved scope.";
+ }
+ if (status.keylessScope === "full") {
+ return "Full keyless access is localhost-only and is never granted over LAN or public URLs.";
+ }
+ const tools = status.keylessTools
+ ? " Agent tools are separately enabled."
+ : " Agent tools remain off unless separately granted.";
+ if (status.keylessLanEligible && status.publicUrls.length > 0) {
+ return `Inference can be keyless on localhost and an active private LAN, but never through the listed public URL.${tools}`;
+ }
+ if (status.keylessLanEligible) {
+ return `Inference can be keyless on localhost and this active private LAN.${tools}`;
+ }
+ return `Inference is keyless on localhost; LAN callers require an active private listener.${tools}`;
+}
+
// start and stop are synchronous socket work, so there is no transition to chase
export const LAN_ACCESS_POLL_MS = 5000;
diff --git a/studio/frontend/src/features/settings/components/keyless-api-access-section.tsx b/studio/frontend/src/features/settings/components/keyless-api-access-section.tsx
new file mode 100644
index 00000000000..44dfcd7f253
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/keyless-api-access-section.tsx
@@ -0,0 +1,295 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Switch } from "@/components/ui/switch";
+import { usePlatformStore } from "@/config/env";
+import {
+ type KeylessApiAccessScope,
+ type KeylessApiAccessSettings,
+ loadKeylessApiAccess,
+ updateKeylessApiAccess,
+} from "@/features/settings/api/keyless-api-access";
+import { cn } from "@/lib/utils";
+import { LaptopIcon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useEffect, useState } from "react";
+import { SettingsRow } from "./settings-row";
+
+type PendingGrant = Exclude<KeylessApiAccessScope, "off"> | "tools";
+
+function activeExposureWarning(
+ exposure: KeylessApiAccessSettings["exposure"],
+): string {
+ if (exposure === "public_url") {
+ return " A public URL or tunnel is active, so keyless access remains disabled, including on localhost, until it is stopped.";
+ }
+ if (exposure === "colab") {
+ return " This Colab runtime cannot receive keyless access.";
+ }
+ return "";
+}
+
+const CONFIRM_COPY: Record<
+ PendingGrant,
+ {
+ title: string;
+ body: (exposure: KeylessApiAccessSettings["exposure"]) => string;
+ action: string;
+ }
+> = {
+ inference: {
+ title: "Allow chat without a key?",
+ body: (exposure) =>
+ `Inference will work without a key on localhost and an active private LAN listener. Public URLs and Colab always require authentication; training, files and settings still require it.${activeExposureWarning(exposure)}`,
+ action: "Allow chat",
+ },
+ full: {
+ title: "Allow full localhost access without a key?",
+ body: (exposure) =>
+ `Localhost callers will be able to chat, start training runs, and read, change and delete files and settings. Full keyless access is never honored over LAN, a public bind or URL, a tunnel, or Colab.${activeExposureWarning(exposure)}`,
+ action: "Allow everything",
+ },
+ tools: {
+ title: "Let keyless callers run tools?",
+ body: (exposure) =>
+ `Eligible keyless callers will also be able to run Python, terminal and web-search tools through the model. This is a separate grant from API access.${activeExposureWarning(exposure)}`,
+ action: "Allow tools",
+ },
+};
+
+export function KeylessApiAccessSection({
+ onSettingsChange,
+}: {
+ /** fires on load and after every save, so the usage examples can follow */
+ onSettingsChange?: (settings: {
+ scope: KeylessApiAccessScope;
+ tools: boolean;
+ exposure: KeylessApiAccessSettings["exposure"];
+ }) => void;
+}) {
+ const cloudflareUrl = usePlatformStore((state) => state.cloudflareUrl);
+ const [settings, setSettings] = useState<KeylessApiAccessSettings | null>(
+ null,
+ );
+ const [error, setError] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+ const [pending, setPending] = useState<PendingGrant | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ loadKeylessApiAccess()
+ .then((next) => {
+ if (!cancelled) {
+ setSettings(next);
+ setError(null);
+ onSettingsChange?.({
+ scope: next.scope,
+ tools: next.tools,
+ exposure: next.exposure,
+ });
+ }
+ })
+ .catch((cause: unknown) => {
+ if (!cancelled) {
+ setError(
+ cause instanceof Error
+ ? cause.message
+ : "Couldn't load keyless API access.",
+ );
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [cloudflareUrl, onSettingsChange]);
+
+ const save = async (next: KeylessApiAccessScope, tools?: boolean) => {
+ setSaving(true);
+ setError(null);
+ try {
+ const saved = await updateKeylessApiAccess(next, tools);
+ setSettings(saved);
+ onSettingsChange?.({
+ scope: saved.scope,
+ tools: saved.tools,
+ exposure: saved.exposure,
+ });
+ } catch (cause: unknown) {
+ setError(
+ cause instanceof Error
+ ? cause.message
+ : "Couldn't update keyless API access.",
+ );
+ } finally {
+ setSaving(false);
+ setPending(null);
+ }
+ };
+
+ // re-read who the dialog names, held busy so no second click lands during the round trip
+ const confirm = async (confirmAs: PendingGrant) => {
+ setSaving(true);
+ try {
+ const refreshed = await loadKeylessApiAccess();
+ setSettings(refreshed);
+ onSettingsChange?.({
+ scope: refreshed.scope,
+ tools: refreshed.tools,
+ exposure: refreshed.exposure,
+ });
+ } catch {
+ // keep the exposure already on screen; the dialog still states the scope
+ } finally {
+ setSaving(false);
+ }
+ setPending(confirmAs);
+ };
+
+ const scope = settings?.scope ?? "off";
+ const tools = settings?.tools === true;
+ const busy = settings === null || saving;
+
+ const request = (next: KeylessApiAccessScope, confirmAs: PendingGrant) => {
+ if (next === "off" || scope === "full") {
+ void save(next);
+ return;
+ }
+ void confirm(confirmAs);
+ };
+
+ const requestTools = (on: boolean) => {
+ if (!on) {
+ void save(scope, false);
+ return;
+ }
+ void confirm("tools");
+ };
+
+ const applyPending = () => {
+ if (pending === "tools") {
+ void save(scope, true);
+ return;
+ }
+ if (pending) {
+ void save(pending);
+ }
+ };
+
+ return (
+ <section
+ data-settings-label="Keyless API access"
+ className="overflow-hidden rounded-lg border border-border/70"
+ >
+ <div className="flex items-center justify-between gap-4 bg-muted/30 p-4">
+ <div className="flex min-w-0 items-start gap-3">
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-md border border-border/70 bg-muted/40">
+ <HugeiconsIcon
+ icon={LaptopIcon}
+ className="size-4 text-foreground"
+ />
+ </div>
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <h2 className="text-base font-semibold font-heading text-foreground">
+ Keyless API access
+ </h2>
+ <p className="text-xs text-muted-foreground leading-relaxed">
+ Use Unsloth from other apps without creating an API key. Signing
+ in is unchanged; public URLs and Colab always require a key.
+ </p>
+ </div>
+ </div>
+ </div>
+
+ {error ? (
+ <p className="border-t border-border/60 px-4 py-2.5 text-xs leading-snug text-destructive">
+ {error}
+ </p>
+ ) : null}
+
+ <div className="border-t border-border/60 px-4 py-1">
+ <SettingsRow
+ label="Chat and inference"
+ description="Serve the approved OpenAI and Anthropic inference endpoints on localhost and an active private LAN."
+ alignTop={true}
+ >
+ <Switch
+ checked={scope !== "off"}
+ disabled={busy}
+ onCheckedChange={(on) =>
+ request(on ? "inference" : "off", "inference")
+ }
+ aria-label="Chat and inference"
+ />
+ </SettingsRow>
+
+ <SettingsRow
+ label="Everything else"
+ description="Also serve training, files and settings, but only to local loopback callers."
+ alignTop={true}
+ >
+ <Switch
+ checked={scope === "full"}
+ disabled={busy}
+ onCheckedChange={(on) => request(on ? "full" : "inference", "full")}
+ aria-label="Everything else"
+ />
+ </SettingsRow>
+
+ <SettingsRow
+ label="Allow tools"
+ description="Let keyless callers use the built-in Python, terminal and web search tools. Off unless you turn it on."
+ alignTop={true}
+ >
+ <Switch
+ checked={tools}
+ disabled={busy || scope === "off"}
+ onCheckedChange={requestTools}
+ aria-label="Allow tools"
+ />
+ </SettingsRow>
+ </div>
+
+ <Dialog
+ open={pending !== null}
+ onOpenChange={(open) => !open && setPending(null)}
+ >
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>
+ {pending ? CONFIRM_COPY[pending].title : ""}
+ </DialogTitle>
+ <DialogDescription>
+ {pending
+ ? CONFIRM_COPY[pending].body(settings?.exposure ?? null)
+ : ""}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setPending(null)}>
+ Cancel
+ </Button>
+ <Button
+ disabled={saving}
+ className={cn(
+ (pending === "full" || pending === "tools") &&
+ "bg-destructive hover:bg-destructive/90 text-destructive-foreground",
+ )}
+ onClick={applyPending}
+ >
+ {pending ? CONFIRM_COPY[pending].action : ""}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </section>
+ );
+}
diff --git a/studio/frontend/src/features/settings/components/lan-access-section.tsx b/studio/frontend/src/features/settings/components/lan-access-section.tsx
index db0af7769e1..6937617fb2a 100644
--- a/studio/frontend/src/features/settings/components/lan-access-section.tsx
+++ b/studio/frontend/src/features/settings/components/lan-access-section.tsx
@@ -20,6 +20,7 @@ import {
import {
LAN_ACCESS_POLL_MS,
type LanAccessStatus,
+ keylessLanAccessDescription,
lanAccessAutoStartReadOnly,
lanAccessBlockMessage,
lanAccessErrorMessage,
@@ -359,6 +360,18 @@ export function LanAccessSection() {
<LanUrlPanel status={status} />
<div className="border-t border-border/60 px-4 py-1">
+ <SettingsRow
+ label="Keyless API status"
+ description={keylessLanAccessDescription(status)}
+ >
+ <span className="text-xs font-medium text-muted-foreground">
+ {status?.keylessScope === "inference"
+ ? "Inference"
+ : status?.keylessScope === "full"
+ ? "Local full"
+ : "Off"}
+ </span>
+ </SettingsRow>
<SettingsRow
label="Start automatically"
description="Put Unsloth on the network each time it starts. Stopping LAN access now won’t turn this off."
diff --git a/studio/frontend/src/features/settings/components/usage-examples.tsx b/studio/frontend/src/features/settings/components/usage-examples.tsx
index 12eaafb71cb..fcb0e643f53 100644
--- a/studio/frontend/src/features/settings/components/usage-examples.tsx
+++ b/studio/frontend/src/features/settings/components/usage-examples.tsx
@@ -29,10 +29,18 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { useEffect, useMemo, useRef, useState } from "react";
import { Streamdown } from "streamdown";
import { loadCodingAgents } from "../api/coding-agents";
+import type {
+ KeylessApiAccessExposure,
+ KeylessApiAccessScope,
+} from "../api/keyless-api-access";
import { loadOpenAIAutoSwitchSettings } from "../api/openai-auto-switch";
import { type OpenAIModel, listOpenAIModels } from "../api/openai-models";
import { useSettingsPanelPrefsStore } from "../stores/settings-panel-prefs-store";
-import { buildAgentCommand, isLoopbackHost, normalizeHost } from "./agent-command";
+import {
+ buildAgentCommand,
+ isLoopbackHost,
+ normalizeHost,
+} from "./agent-command";
type ExampleType =
| "curl"
@@ -107,19 +115,16 @@ const DOC_LINKS = [
{ label: "Codex", href: "https://unsloth.ai/docs/basics/codex" },
{ label: "OpenClaw", href: "https://unsloth.ai/docs/integrations/openclaw" },
{ label: "OpenCode", href: "https://unsloth.ai/docs/integrations/opencode" },
- { label: "Hermes Agent", href: "https://unsloth.ai/docs/integrations/hermes-agent" },
+ {
+ label: "Hermes Agent",
+ href: "https://unsloth.ai/docs/integrations/hermes-agent",
+ },
];
// Fallback until the backend's installed-CLI check resolves. Mirrors
// CODING_AGENTS in studio/backend/utils/coding_agents.py, minus HIDDEN_AGENTS
// (see ../api/coding-agents.ts).
-const DEFAULT_AGENTS = [
- "claude",
- "codex",
- "openclaw",
- "opencode",
- "hermes",
-];
+const DEFAULT_AGENTS = ["claude", "codex", "openclaw", "opencode", "hermes"];
// The agent selection resets to this whenever an auto-pick is no longer
// trustworthy (leaving loopback, or the only compatible detected agent
// stops being compatible) rather than lingering on a stale choice.
@@ -285,9 +290,11 @@ function javascriptSnippet(
options.push(` top_k: ${ADV.top_k},`);
options.push(` min_p: ${ADV.min_p},`);
options.push(` repetition_penalty: ${ADV.repetition_penalty},`);
+ // biome-ignore lint/style/noUnusedTemplateLiteral: keep generated options visually uniform
options.push(` enable_thinking: true,`);
}
if (variant !== "plain") {
+ // biome-ignore lint/style/noUnusedTemplateLiteral: keep generated options visually uniform
options.push(` enable_tools: true,`);
options.push(` enabled_tools: [${toolsJson}],`);
}
@@ -312,9 +319,11 @@ for await (const chunk of response) {
}`;
}
+// every variant but "plain" asks for the server-side tools, so it needs its own key
function buildSnippets(
base: string,
key: string,
+ toolsKey: string,
model: string,
os: Os,
): Record<ExampleType, string> {
@@ -323,16 +332,18 @@ function buildSnippets(
curl: curl(base, key, model, "plain"),
python: pythonSnippet(base, key, model, "plain"),
javascript: javascriptSnippet(base, key, model, "plain"),
- curlTools: curl(base, key, model, "tools"),
- pythonTools: pythonSnippet(base, key, model, "tools"),
- javascriptTools: javascriptSnippet(base, key, model, "tools"),
- curlAdvanced: curl(base, key, model, "advanced"),
- pythonAdvanced: pythonSnippet(base, key, model, "advanced"),
- javascriptAdvanced: javascriptSnippet(base, key, model, "advanced"),
+ curlTools: curl(base, toolsKey, model, "tools"),
+ pythonTools: pythonSnippet(base, toolsKey, model, "tools"),
+ javascriptTools: javascriptSnippet(base, toolsKey, model, "tools"),
+ curlAdvanced: curl(base, toolsKey, model, "advanced"),
+ pythonAdvanced: pythonSnippet(base, toolsKey, model, "advanced"),
+ javascriptAdvanced: javascriptSnippet(base, toolsKey, model, "advanced"),
};
}
const KEY_PLACEHOLDER = "sk-unsloth-YOUR_KEY";
+// the openai sdks require some api_key, so name one rather than leave it blank
+const KEYLESS_KEY_PLACEHOLDER = "not-needed";
const USE_TUNNEL_KEY = "unsloth_api_use_tunnel";
// Slow retry while /v1 has nothing to name: a download or load moves no store state.
const CATALOG_RETRY_MS = 15000;
@@ -373,22 +384,23 @@ function looksLikePath(id: string): boolean {
// Same model, ignoring any ":quant" a caller pinned.
function sameBaseModelId(a: string, b: string): boolean {
const base = (id: string) => id.trim().toLowerCase().split(":")[0];
- return a.trim().toLowerCase() === b.trim().toLowerCase() || base(a) === base(b);
+ return (
+ a.trim().toLowerCase() === b.trim().toLowerCase() || base(a) === base(b)
+ );
}
// The model the examples name: always an id /v1 resolves against, null when there is none.
-function useExampleModelName(): string | null {
+function useExampleModelName(keylessOnly: boolean): string | null {
const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);
const ggufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);
// null until /v1/models answers: "not asked yet" must not read as "holds nothing".
const [catalog, setCatalog] = useState<OpenAIModel[] | null>(null);
// A downloaded but unloaded model is only runnable when switching is on.
const [autoSwitch, setAutoSwitch] = useState(false);
- // Idle-unload on its own (UNSLOTH_MODEL_IDLE_TTL, switching off) reloads exactly
- // what it freed: the stored checkpoint only, never an arbitrary catalog entry.
- const [idleReload, setIdleReload] = useState(false);
const usableCheckpoint =
- !!checkpoint && !checkpoint.startsWith("external::") && !looksLikePath(checkpoint);
+ !!checkpoint &&
+ !checkpoint.startsWith("external::") &&
+ !looksLikePath(checkpoint);
// Always: a stored checkpoint can stop being servable without the store changing.
// biome-ignore lint/correctness/useExhaustiveDependencies: a load or unload must refetch the servable ids
@@ -403,17 +415,17 @@ function useExampleModelName(): string | null {
void Promise.all([
listOpenAIModels().catch(() => null),
loadOpenAIAutoSwitchSettings()
- .then((s) => [s.enabled, s.idleUnloadActive] as const)
+ .then((s) => s.enabled)
.catch(() => null),
])
.then(([models, settings]) => {
if (cancelled) return true;
if (models !== null) setCatalog(models);
if (settings !== null) {
- setAutoSwitch(settings[0]);
- setIdleReload(settings[1]);
+ setAutoSwitch(settings);
}
// Resident only slows the polling; it never stops it.
+ // biome-ignore lint/complexity/useOptionalChain: keep the explicit failed-refresh branch
return models !== null && models.some((m) => m.loaded);
})
.then((resolved) => {
@@ -436,7 +448,8 @@ function useExampleModelName(): string | null {
// Name something held here, with its quant to pin the file on disk.
const fromCatalog = (): string | null => {
const pick =
- catalog?.find((m) => m.loaded) ?? (autoSwitch ? catalog?.[0] : undefined);
+ catalog?.find((m) => m.loaded) ??
+ (!keylessOnly && autoSwitch ? catalog?.[0] : undefined);
if (!pick) {
return null;
}
@@ -450,7 +463,8 @@ function useExampleModelName(): string | null {
// /v1/models has not answered, which is not evidence against it.
const entry = catalog?.find((m) => sameBaseModelId(m.id, checkpoint ?? ""));
const backed =
- catalog === null || (!!entry && (entry.loaded || autoSwitch || idleReload));
+ (!keylessOnly && catalog === null) ||
+ (!!entry && (entry.loaded || (!keylessOnly && autoSwitch)));
if (usableCheckpoint && checkpoint && backed) {
if (checkpoint.includes(":")) {
return checkpoint;
@@ -462,7 +476,14 @@ function useExampleModelName(): string | null {
return quant ? `${checkpoint}:${quant}` : checkpoint;
}
return fromCatalog();
- }, [autoSwitch, catalog, checkpoint, ggufVariant, idleReload, usableCheckpoint]);
+ }, [
+ autoSwitch,
+ catalog,
+ checkpoint,
+ ggufVariant,
+ keylessOnly,
+ usableCheckpoint,
+ ]);
}
// Backend PATH detection is only safe in the desktop app, where the UI owns
@@ -476,6 +497,46 @@ function canUseLocalAgentDetection(base: string): boolean {
}
}
+function isPrivateLanHost(hostname: string): boolean {
+ const host = normalizeHost(hostname).toLowerCase();
+ if (host.startsWith("::ffff:")) {
+ return isPrivateLanHost(host.slice("::ffff:".length));
+ }
+ const ipv4 = host.split(".").map(Number);
+ if (
+ ipv4.length === 4 &&
+ ipv4.every((part) => Number.isInteger(part) && part >= 0 && part <= 255)
+ ) {
+ return (
+ ipv4[0] === 10 ||
+ (ipv4[0] === 172 && ipv4[1] >= 16 && ipv4[1] <= 31) ||
+ (ipv4[0] === 192 && ipv4[1] === 168) ||
+ (ipv4[0] === 169 && ipv4[1] === 254)
+ );
+ }
+ return /^f[cd][0-9a-f]*:/i.test(host) || /^fe[89ab][0-9a-f]*:/i.test(host);
+}
+
+function keylessBaseEligible(
+ base: string,
+ scope: KeylessApiAccessScope,
+ exposure: KeylessApiAccessExposure | null,
+): boolean {
+ if (scope === "off" || exposure === "colab" || exposure === "public_url") {
+ return false;
+ }
+ try {
+ const host = normalizeHost(new URL(base).hostname);
+ if (isLoopbackHost(host)) return true;
+ return (
+ scope === "inference" &&
+ (isPrivateLanHost(host) || exposure === "private_lan")
+ );
+ } catch {
+ return false;
+ }
+}
+
const SHIKI_THEMES = [unslothLightTheme, unslothDarkTheme] as [
typeof unslothLightTheme,
typeof unslothDarkTheme,
@@ -512,7 +573,20 @@ function HighlightedCode({
);
}
-export function UsageExamples({ apiKey }: { apiKey?: string | null }) {
+export function UsageExamples({
+ apiKey,
+ keylessScope = "off",
+ keylessTools = false,
+ keylessExposure = null,
+}: {
+ apiKey?: string | null;
+ /** which routes keyless api access serves, so a placeholder is only used where it works */
+ keylessScope?: KeylessApiAccessScope;
+ /** whether a keyless caller may drive the server-side tool loop */
+ keylessTools?: boolean;
+ /** public tunnels and Colab never accept the dummy bearer */
+ keylessExposure?: KeylessApiAccessExposure | null;
+}) {
const t = useT();
const deviceType = usePlatformStore((s) => s.deviceType);
const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);
@@ -526,7 +600,8 @@ export function UsageExamples({ apiKey }: { apiKey?: string | null }) {
// read once: these seed the controls, which write back through the handlers.
const [storedPrefs] = useState(() => useSettingsPanelPrefsStore.getState());
const [lang, setLang] = useState<ExampleType>(
- storedPrefs.apiExampleLang && EXAMPLE_TYPE_IDS.has(storedPrefs.apiExampleLang)
+ storedPrefs.apiExampleLang &&
+ EXAMPLE_TYPE_IDS.has(storedPrefs.apiExampleLang)
? (storedPrefs.apiExampleLang as ExampleType)
: "curl",
);
@@ -608,7 +683,13 @@ export function UsageExamples({ apiKey }: { apiKey?: string | null }) {
agentPickedByUserRef.current = false;
setStoredAgent(null);
setAgent(DEFAULT_AGENT);
- }, [agent, agentsLoaded, availableAgents, localAgentDetection, setStoredAgent]);
+ }, [
+ agent,
+ agentsLoaded,
+ availableAgents,
+ localAgentDetection,
+ setStoredAgent,
+ ]);
// Single source of truth for the auto-picked agent, re-derived whenever
// the detected list or the loaded model's GGUF-ness changes -- in either
@@ -629,13 +710,17 @@ export function UsageExamples({ apiKey }: { apiKey?: string | null }) {
// path a model can be GGUF through, matching the same is_gguf-or-equivalent
// check hasGgufSource applies to a staged pick.
const activeGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);
- const activeNativePathToken = useChatRuntimeStore((s) => s.activeNativePathToken);
+ const activeNativePathToken = useChatRuntimeStore(
+ (s) => s.activeNativePathToken,
+ );
const ggufContextLength = useChatRuntimeStore((s) => s.ggufContextLength);
useEffect(() => {
if (agentPickedByUserRef.current) return;
if (detectedAgents.length === 0) return;
const isGguf =
- activeGgufVariant != null || activeNativePathToken != null || ggufContextLength != null;
+ activeGgufVariant != null ||
+ activeNativePathToken != null ||
+ ggufContextLength != null;
const preferred = detectedAgents.find((a) => a !== "codex" || isGguf);
if (preferred) {
setAgent(preferred);
@@ -646,20 +731,38 @@ export function UsageExamples({ apiKey }: { apiKey?: string | null }) {
// of leaving a codex command unsloth_cli will reject.
setAgent(DEFAULT_AGENT);
}
- }, [agent, detectedAgents, activeGgufVariant, activeNativePathToken, ggufContextLength]);
+ }, [
+ agent,
+ detectedAgents,
+ activeGgufVariant,
+ activeNativePathToken,
+ ggufContextLength,
+ ]);
- const model = useExampleModelName();
- const key = apiKey || KEY_PLACEHOLDER;
+ const keylessBase =
+ !(useTunnel && cloudflareUrl) &&
+ keylessBaseEligible(base, keylessScope, keylessExposure);
+ const model = useExampleModelName(keylessBase && !apiKey);
+ // The approved SDK dummy is printed only for a transport the backend can admit.
+ const key =
+ apiKey || (keylessBase ? KEYLESS_KEY_PLACEHOLDER : KEY_PLACEHOLDER);
+ // a keyless caller gets no tools until the admin grants them, so this names a real key
+ const toolsKey =
+ apiKey ||
+ (keylessBase && keylessTools ? KEYLESS_KEY_PLACEHOLDER : KEY_PLACEHOLDER);
+ // agent tools are client-side schemas sent through the admitted inference routes.
+ const agentKey =
+ apiKey || (keylessBase ? KEYLESS_KEY_PLACEHOLDER : KEY_PLACEHOLDER);
// Null model: nothing is servable, so there is no snippet worth copying.
const snippets = useMemo(
- () => (model ? buildSnippets(base, key, model, os) : null),
- [base, key, model, os],
+ () => (model ? buildSnippets(base, key, toolsKey, model, os) : null),
+ [base, key, toolsKey, model, os],
);
// Agent command must target the server the panel shows, not the :8888 default.
const agentCommand = useMemo(
- () => buildAgentCommand(base, key, os, agent),
- [base, key, os, agent],
+ () => buildAgentCommand(base, agentKey, os, agent),
+ [base, agentKey, os, agent],
);
const osAware = OS_AWARE[lang];
diff --git a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
index 8a82ad4def5..cb5f042fca7 100644
--- a/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/api-keys-tab.tsx
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
@@ -9,17 +10,21 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
import { translate, useT } from "@/i18n";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useCallback, useEffect, useState } from "react";
-import { fetchApiKeys, revokeApiKey, type ApiKey } from "../api/api-keys";
-import { MonitorLink } from "../components/monitor-link";
+import { type ApiKey, fetchApiKeys, revokeApiKey } from "../api/api-keys";
+import type {
+ KeylessApiAccessExposure,
+ KeylessApiAccessScope,
+} from "../api/keyless-api-access";
import { ApiKeyRow } from "../components/api-key-row";
import { CreateKeyForm } from "../components/create-key-form";
-import { ModelAutoSwitchSection } from "../components/model-auto-switch-section";
import { KeyRevealCard } from "../components/key-reveal-card";
+import { KeylessApiAccessSection } from "../components/keyless-api-access-section";
import { LanAccessSection } from "../components/lan-access-section";
+import { ModelAutoSwitchSection } from "../components/model-auto-switch-section";
+import { MonitorLink } from "../components/monitor-link";
import { RemoteAccessSection } from "../components/remote-access-section";
import { UsageExamples } from "../components/usage-examples";
@@ -31,6 +36,11 @@ export function ApiKeysTab() {
const [revokeTarget, setRevokeTarget] = useState<ApiKey | null>(null);
const [revoking, setRevoking] = useState(false);
const [revealed, setRevealed] = useState<string | null>(null);
+ const [keyless, setKeyless] = useState<{
+ scope: KeylessApiAccessScope;
+ tools: boolean;
+ exposure: KeylessApiAccessExposure | null;
+ }>({ scope: "off", tools: false, exposure: null });
const reduced = useReducedMotion();
const transition = reduced
? { duration: 0 }
@@ -116,10 +126,7 @@ export function ApiKeysTab() {
exit={{ opacity: 0, y: -4 }}
transition={transition}
>
- <KeyRevealCard
- rawKey={revealed}
- onDone={() => setRevealed(null)}
- />
+ <KeyRevealCard rawKey={revealed} onDone={() => setRevealed(null)} />
</motion.div>
) : (
<motion.div
@@ -174,6 +181,8 @@ export function ApiKeysTab() {
<MonitorLink />
+ <KeylessApiAccessSection onSettingsChange={setKeyless} />
+
{/* Also on the Remote & LAN tab. One panel mounts at a time, so only one polls. */}
<RemoteAccessSection />
@@ -181,9 +190,17 @@ export function ApiKeysTab() {
<ModelAutoSwitchSection />
- <UsageExamples apiKey={revealed} />
-
- <Dialog open={revokeTarget !== null} onOpenChange={(o) => !o && setRevokeTarget(null)}>
+ <UsageExamples
+ apiKey={revealed}
+ keylessScope={keyless.scope}
+ keylessTools={keyless.tools}
+ keylessExposure={keyless.exposure}
+ />
+
+ <Dialog
+ open={revokeTarget !== null}
+ onOpenChange={(o) => !o && setRevokeTarget(null)}
+ >
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>
diff --git a/studio/frontend/src/features/settings/tabs/remote-lan-tab.tsx b/studio/frontend/src/features/settings/tabs/remote-lan-tab.tsx
index c837216d901..ad17101c8fa 100644
--- a/studio/frontend/src/features/settings/tabs/remote-lan-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/remote-lan-tab.tsx
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useT } from "@/i18n";
+import { KeylessApiAccessSection } from "../components/keyless-api-access-section";
import { LanAccessSection } from "../components/lan-access-section";
import { RemoteAccessSection } from "../components/remote-access-section";
@@ -30,6 +31,8 @@ export function RemoteLanTab() {
<RemoteAccessSection />
<LanAccessSection />
+
+ <KeylessApiAccessSection />
</div>
);
}
diff --git a/studio/frontend/tests/lan-access-state.test.ts b/studio/frontend/tests/lan-access-state.test.ts
index 725bbfda29f..edc406f6794 100644
--- a/studio/frontend/tests/lan-access-state.test.ts
+++ b/studio/frontend/tests/lan-access-state.test.ts
@@ -7,6 +7,7 @@ import test from "node:test";
// lan-access-section.tsx pulls in hugeicons, so only its pure helpers are tested here
import {
type ApiLanAccessStatus,
+ keylessLanAccessDescription,
lanAccessAutoStartReadOnly,
lanAccessBlockMessage,
lanAccessErrorMessage,
@@ -51,6 +52,8 @@ test("normalize maps every snake_case field onto its camelCase name", () => {
block_reason: null,
// biome-ignore lint/style/useNamingConvention: API schema
serves_web_ui: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ keyless_lan_eligible: true,
}),
);
assert.deepEqual(s, {
@@ -64,6 +67,9 @@ test("normalize maps every snake_case field onto its camelCase name", () => {
canStop: true,
blockReason: null,
servesWebUi: true,
+ keylessLanEligible: true,
+ keylessScope: "off",
+ keylessTools: false,
});
});
@@ -75,6 +81,58 @@ test("normalize defaults the optional fields an older backend may omit", () => {
assert.equal(s.managedBy, null);
assert.equal(s.blockReason, null);
assert.equal(s.servesWebUi, true);
+ assert.equal(s.keylessLanEligible, false);
+ assert.equal(s.keylessScope, "off");
+ assert.equal(s.keylessTools, false);
+});
+
+test("keyless state and messaging preserve every security boundary", () => {
+ const unknown = normalizeLanAccessStatus(
+ apiStatus({ keyless_scope: "unknown", keyless_tools: true }),
+ );
+ assert.deepEqual(
+ [unknown.keylessScope, unknown.keylessTools],
+ ["off", false],
+ );
+ assert.ok(
+ keylessLanAccessDescription(null).includes("Authentication is required"),
+ );
+ const cases: [Partial<ApiLanAccessStatus>, string][] = [
+ [
+ {
+ state: "online",
+ keyless_lan_eligible: false,
+ keyless_scope: "inference",
+ },
+ "active private listener",
+ ],
+ [
+ {
+ state: "online",
+ keyless_lan_eligible: true,
+ keyless_scope: "inference",
+ },
+ "this active private LAN",
+ ],
+ [
+ {
+ state: "online",
+ public_urls: [PUBLIC],
+ keyless_lan_eligible: true,
+ keyless_scope: "inference",
+ },
+ "never through the listed public URL",
+ ],
+ [{ keyless_scope: "full" }, "never granted over LAN or public URLs"],
+ [
+ { block_reason: "colab", keyless_scope: "inference" },
+ "Colab never receives keyless access",
+ ],
+ ];
+ for (const [overrides, fragment] of cases) {
+ const status = normalizeLanAccessStatus(apiStatus(overrides));
+ assert.ok(keylessLanAccessDescription(status).includes(fragment));
+ }
});
test("urls survives a null or non-array payload without throwing", () => {
diff --git a/tests/studio/test_usage_examples_model_source_contract.py b/tests/studio/test_usage_examples_model_source_contract.py
index 0fb2d57f002..3580a10d849 100644
--- a/tests/studio/test_usage_examples_model_source_contract.py
+++ b/tests/studio/test_usage_examples_model_source_contract.py
@@ -12,17 +12,19 @@ SETTINGS = REPO / "studio/frontend/src/features/settings"
USAGE_EXAMPLES_TSX = SETTINGS / "components/usage-examples.tsx"
OPENAI_MODELS_TS = SETTINGS / "api/openai-models.ts"
API_KEYS_TAB_TSX = SETTINGS / "tabs/api-keys-tab.tsx"
+KEYLESS_SECTION_TSX = SETTINGS / "components/keyless-api-access-section.tsx"
def test_examples_name_a_model_the_server_can_serve():
# A hardcoded repo id made copied curls 404; read the servable ids from /v1/models.
src = USAGE_EXAMPLES_TSX.read_text(encoding = "utf-8")
assert 'from "../api/openai-models"' in src
- assert "function useExampleModelName(): string" in src
+ assert "function useExampleModelName(keylessOnly: boolean): string" in src
hook = src[src.find("function useExampleModelName") : src.find("// Backend PATH detection")]
assert "listOpenAIModels()" in hook
# Precedence: live checkpoint, then a loaded entry, then any entry if switching is on.
- assert "catalog?.find((m) => m.loaded) ?? (autoSwitch ? catalog?.[0] : undefined)" in hook
+ assert "catalog?.find((m) => m.loaded) ??" in hook
+ assert "(!keylessOnly && autoSwitch ? catalog?.[0] : undefined)" in hook
# The snippet pins the quant so the request names the file on disk.
assert "`${pick.id}:${pick.quant}`" in hook
@@ -37,10 +39,10 @@ def test_examples_never_print_a_hardcoded_model_id():
assert "MODEL_FALLBACK" not in src
# No repo-shaped literal anywhere: a snippet may only name what /v1 returns.
assert re.search(r'"unsloth/[^"]+"', src) is None
- assert "function useExampleModelName(): string | null" in src
+ assert "function useExampleModelName(keylessOnly: boolean): string | null" in src
assert "useState<OpenAIModel[] | null>(null)" in src
# Nothing servable means nothing is built, so there is nothing to copy.
- assert "(model ? buildSnippets(base, key, model, os) : null)" in src
+ assert "(model ? buildSnippets(base, key, toolsKey, model, os) : null)" in src
assert "if (!snippets) return;" in src
assert "{snippets ? (" in src
assert 't("settings.apiKeys.usageNoModel")' in src
@@ -72,23 +74,17 @@ def test_a_stored_checkpoint_needs_catalog_evidence():
src = USAGE_EXAMPLES_TSX.read_text(encoding = "utf-8")
hook = src[src.find("function useExampleModelName") : src.find("// Backend PATH detection")]
assert 'const entry = catalog?.find((m) => sameBaseModelId(m.id, checkpoint ?? ""));' in hook
- # Resident, or downloaded with something able to reload it. Never the setting alone.
- assert "(!!entry && (entry.loaded || autoSwitch || idleReload))" in hook
+ # resident, or downloaded with switching able to load this exact catalog entry.
+ assert "entry.loaded || (!keylessOnly && autoSwitch)" in hook
assert "autoSwitch ||\n" not in hook
-def test_standalone_idle_unload_still_names_the_stored_checkpoint():
- # UNSLOTH_MODEL_IDLE_TTL without auto-switch reloads exactly what it freed, so the
- # stored checkpoint stays runnable and the panel must keep showing it. The stash
- # restores only that model, so it can never pick catalog[0].
+def test_idle_unload_does_not_guess_the_stashed_checkpoint():
+ # the idle stash is process-wide, but the browser checkpoint is not.
src = USAGE_EXAMPLES_TSX.read_text(encoding = "utf-8")
hook = src[src.find("function useExampleModelName") : src.find("// Backend PATH detection")]
- assert "const [idleReload, setIdleReload] = useState(false);" in hook
- assert "setIdleReload(settings[1])" in hook
- assert "s.idleUnloadActive" in hook
- # fromCatalog stays gated on auto-switch alone.
- assert "?? (autoSwitch ? catalog?.[0] : undefined)" in hook
- assert "idleReload ? catalog" not in hook
+ assert "idleReload" not in hook
+ assert "idleUnloadActive" not in hook
def test_a_failed_refresh_does_not_erase_what_the_server_holds():
@@ -213,3 +209,27 @@ def test_auto_download_copy_warns_about_api_key_holders():
assert start != -1
description = en[start : en.find("\n", en.find('",', start))]
assert "API key" in description
+
+
+def test_keyless_examples_match_transport_tool_and_full_scope_policy():
+ src = USAGE_EXAMPLES_TSX.read_text(encoding = "utf-8")
+ builder = src[src.find("function buildSnippets") : src.find("const KEY_PLACEHOLDER")]
+ variants = ("curlTools", "pythonTools", "javascriptTools", "curlAdvanced")
+ assert all(
+ "toolsKey"
+ in next(row for row in builder.splitlines() if row.strip().startswith(f"{variant}:"))
+ for variant in variants
+ )
+ assert "keylessBase && keylessTools" in src
+ assert "apiKey || (keylessBase ? KEYLESS_KEY_PLACEHOLDER : KEY_PLACEHOLDER)" in src
+ assert 'const KEYLESS_KEY_PLACEHOLDER = "not-needed"' in src
+ assert 'exposure === "colab" || exposure === "public_url"' in src
+ assert "if (isLoopbackHost(host)) return true;" in src
+ assert 'exposure === "private_lan"' in src
+ assert "!(useTunnel && cloudflareUrl)" in src
+ assert "useExampleModelName(keylessBase && !apiKey)" in src
+ section = KEYLESS_SECTION_TSX.read_text(encoding = "utf-8")
+ assert "[cloudflareUrl, onSettingsChange]" in section
+ assert "delete" in section[section.find(" full: {") : section.find(" tools: {")]
+ assert "including on localhost" in section
+ assert "read the files and settings in Unsloth" not in section