Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: admit a bearer that carries no token under keyless API access (#10423)
Long Yixingacad3f00f6be
diff --git a/studio/backend/auth/authentication.py b/studio/backend/auth/authentication.pyindex a107b916aad..8a4f13923bd 100644--- a/studio/backend/auth/authentication.py+++ b/studio/backend/auth/authentication.py@@ -91,7 +91,11 @@ def admitted_without_credential(credentials: Optional[HTTPAuthorizationCredentiadef _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+ from utils.keyless_api_access import (+ APPROVED_DUMMY_BEARERS,+ is_empty_bearer,+ keyless_request_allowed,+ )if not keyless_request_allowed(request):return False@@ -108,6 +112,8 @@ def _request_would_use_keyless(request: Any) -> bool:return Trueif len(values) != 1:return False+ if is_empty_bearer(values[0]):+ return Truescheme, token = get_authorization_scheme_param(values[0])return scheme.lower() == "bearer" and token in APPROVED_DUMMY_BEARERS@@ -145,6 +151,7 @@ class _BearerOrKeyless(HTTPBearer):async def __call__(self, request: Request) -> Optional[HTTPAuthorizationCredentials]:from utils.keyless_api_access import (APPROVED_DUMMY_BEARERS,+ is_empty_bearer,keyless_request_allowed,mark_keyless_admission,request_was_admitted_keyless,@@ -171,7 +178,7 @@ class _BearerOrKeyless(HTTPBearer):if recorded is Noneelse recorded)- if not authorization and eligible:+ if (not authorization or is_empty_bearer(header)) and eligible:mark_keyless_admission(request, True)return _KEYLESS_CREDENTIALSdummy = eligible and usable_bearer and token in APPROVED_DUMMY_BEARERS@@ -365,6 +372,9 @@ async def credentials_for_token("""from utils.keyless_api_access import APPROVED_DUMMY_BEARERS, keyless_request_allowed+ # /api/health slices the bearer out itself, so a blank one arrives as "", not as None.+ if token is not None and not token.strip():+ token = None# Settings/listener reads hit SQLite and DNS, so keep them off the event loop.if token and token not in APPROVED_DUMMY_BEARERS:return HTTPAuthorizationCredentials(scheme = "Bearer", credentials = token)diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex eebe2aafc52..13563e463ac 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -3387,11 +3387,10 @@ async def _authenticate_header_or_query(request: Request, token: Optional[str])Routed through ``credentials_for_token`` so a scope that covers this path serves itwithout 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:]- else:- jwt_token = token or None+ auth_header = request.headers.get("authorization") or ""+ header_token = auth_header[7:] if auth_header.lower().startswith("bearer ") else ""+ # A blank header is the absent header, so the `?token=` an <img src> sends is still owed.+ jwt_token = header_token.strip() or token or Nonefrom auth.authentication import credentials_for_tokencreds = await credentials_for_token(request, jwt_token)diff --git a/studio/backend/tests/test_keyless_api_access.py b/studio/backend/tests/test_keyless_api_access.pyindex 9cd98877338..11f0476ac0b 100644--- a/studio/backend/tests/test_keyless_api_access.py+++ b/studio/backend/tests/test_keyless_api_access.py@@ -23,6 +23,7 @@ from auth.authentication import (admitted_without_credential,admitted_without_session,create_access_token,+ credentials_for_token,get_current_subject,security,)@@ -775,16 +776,20 @@ 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"):+ for token in ("not-needed", "lm-studio", "ollama", "no-key-required"):assert resolve(bearer_request(token)).scheme == KEYLESS_FALLBACK_SCHEMEset_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"):+ for header in ("Bearer arbitrary", "garbage", "Basic abc"):with pytest.raises(HTTPException):subject_of(request_for(headers = {"Authorization": header}))+ for header in ("Bearer", "Bearer ", "bearer "):+ blank = request_for(headers = {"Authorization": header})+ assert resolve(blank).scheme == KEYLESS_SCHEME+ assert subject_of(blank) == storage.DEFAULT_ADMIN_USERNAMEduplicate = asgi_scope()duplicate["headers"] = [(b"authorization", b"Bearer not-needed"),@@ -833,6 +838,28 @@ def _middleware_policy(scope):return observed+def test_a_blank_bearer_is_the_missing_header_on_routes_that_read_it_themselves():+ """A blank header must not suppress the `?token=` credential, turning its 401 into a pass."""+ from routes.inference import _authenticate_header_or_query++ seed_user()+ set_keyless_api_access("full")+ stale = create_access_token(+ storage.DEFAULT_ADMIN_USERNAME, expires_delta = timedelta(seconds = -60))+ for headers in (None, {"Authorization": "Bearer "}, {"Authorization": "Bearer"}):+ sandbox = lambda token: _authenticate_header_or_query(+ request_for(path = "/v1/sandbox/x", headers = headers), token)+ with pytest.raises(HTTPException):+ asyncio.run(sandbox(stale))+ assert asyncio.run(sandbox(None)) == storage.DEFAULT_ADMIN_USERNAME+ # /api/health has no query credential to fall back on, so "" must resolve the way None does.+ for token in (None, "", " "):+ credentials = asyncio.run(credentials_for_token(request_for(path = "/api/health"), token))+ assert credentials is not None and credentials.scheme == KEYLESS_SCHEME, token+ set_keyless_api_access("off")+ assert asyncio.run(credentials_for_token(request_for(path = "/api/health"), "")) is None++def test_tool_policy_and_api_identity(monkeypatch):from core.inference.llama_keepwarm import _carries_bearer_credentialsfrom routes import inference@@ -844,6 +871,8 @@ def test_tool_policy_and_api_identity(monkeypatch):assert request.state.keyless_api_admitted is Trueassert admitted_without_credential(resolve(request)) is Trueassert admitted_without_session(request) is True+ # Same verdict before one is recorded: read as credentialed, it would skip the keyless guards.+ assert admitted_without_session(request_for(headers = {"Authorization": "Bearer "})) is Trueassert inference._request_has_api_key(request) is Trueassert inference._request_used_api_key(request) is Trueassert inference._request_is_saved_credential_workflow(request) is Falsediff --git a/studio/backend/tests/test_keyless_api_access_adversarial.py b/studio/backend/tests/test_keyless_api_access_adversarial.pyindex 3d95da9832e..2ae4baa50b6 100644--- a/studio/backend/tests/test_keyless_api_access_adversarial.py+++ b/studio/backend/tests/test_keyless_api_access_adversarial.py@@ -128,13 +128,18 @@ def test_scope_off_is_refused_by_the_security_dependency_not_only_the_predicate(with pytest.raises(HTTPException) as caught:resolve(request_for())assert caught.value.status_code in (401, 403)- # ...and the dummy bearers must not resurrect it either.- for dummy in ("not-needed", "lm-studio", "ollama"):+ # ...and neither the dummy bearers nor an empty one may resurrect it.+ for header in (+ "Bearer not-needed",+ "Bearer lm-studio",+ "Bearer ollama",+ "Bearer no-key-required",+ "Bearer",+ "Bearer ",+ ):with pytest.raises(HTTPException):asyncio.run(- get_current_subject(- resolve(request_for(headers = {"Authorization": f"Bearer {dummy}"}))- )+ get_current_subject(resolve(request_for(headers = {"Authorization": header}))))@@ -400,9 +405,18 @@ def test_the_asgi_twin_agrees_with_the_dependency_on_header_shapes():({"Authorization": "Bearer not-needed"}, True),({"Authorization": "Bearer lm-studio"}, True),({"Authorization": "Bearer ollama"}, True),+ # What hermes-agent sends with no key: the SDK refuses an empty one, so it+ # substitutes this literal rather than the blank header above.+ ({"Authorization": "Bearer no-key-required"}, True),+ # Still a credential we do not know, so still refused.+ ({"Authorization": "Bearer sk-no-key-required"}, False),({"Authorization": "Bearer sk-unsloth-nope"}, False),- ({"Authorization": "Bearer"}, False),+ # What a harness that always sends the header emits with no key: the missing header.+ ({"Authorization": "Bearer"}, True),+ ({"Authorization": "Bearer "}, True),+ ({"Authorization": "bearer "}, True),({"Authorization": "Basic bm90LW5lZWRlZA=="}, False),+ ({"Authorization": "Basic"}, False),# A doubled space after the scheme. This is the shape the two implementations# used to disagree on: the dependency collapsed it and admitted the dummy while# the twin did not, so the request was keyless to every route but not-keyless todiff --git a/studio/backend/utils/keyless_api_access.py b/studio/backend/utils/keyless_api_access.pyindex ec4eb6deeb0..4299bfad274 100644--- a/studio/backend/utils/keyless_api_access.py+++ b/studio/backend/utils/keyless_api_access.py@@ -40,7 +40,11 @@ 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"})+APPROVED_DUMMY_BEARERS = frozenset(+ # ``no-key-required`` is what hermes-agent substitutes when no key is configured,+ # because the OpenAI SDK refuses an empty one (hermes_cli/runtime_provider_backends.py).+ {"not-needed", "lm-studio", "ollama", "no-key-required"}+)KEYLESS_ADMISSION_STATE_KEY = "keyless_api_admitted"# Named by method and normalized path: /v1 also aliases model loading, media,@@ -65,6 +69,14 @@ _INFERENCE_ROUTES = frozenset()+def is_empty_bearer(header: str) -> bool:+ """Whether ``header`` is a bearer with no token: what a harness sends with no key set."""+ from fastapi.security.utils import get_authorization_scheme_param++ scheme, token = get_authorization_scheme_param(header)+ return scheme.lower() == "bearer" and not token++def _coerce_scope(value: Any) -> Optional[str]:if isinstance(value, str) and value.strip().lower() in KEYLESS_SCOPES:return value.strip().lower()@@ -698,5 +710,7 @@ def asgi_request_is_keyless(asgi_scope, settings: Optional[tuple[str, bool]] = N# making a shape keyless to every route but not-keyless to the middleware that clamps the tool grant.from fastapi.security.utils import get_authorization_scheme_param+ if is_empty_bearer(authorization[0]):+ return Truescheme, token = get_authorization_scheme_param(authorization[0])return bool(scheme.lower() == "bearer" and token in APPROVED_DUMMY_BEARERS)