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: API keys run tools in the sandbox; Full access needs the Unsloth UI (#14345)
Daniel Han17ecb2e9f14f
diff --git a/studio/backend/auth/authentication.py b/studio/backend/auth/authentication.pyindex bb5503dae53..7a87108fda4 100644--- a/studio/backend/auth/authentication.py+++ b/studio/backend/auth/authentication.py@@ -11,7 +11,7 @@ from fastapi.security.utils import get_authorization_scheme_paramimport jwtfrom starlette.concurrency import run_in_threadpool-from utils.account_context import OWNER, AccountContext, bind_account+from utils.account_context import OWNER, AccountContext, as_api_caller, bind_accountfrom .storage import (get_account,@@ -190,8 +190,8 @@ class _BearerOrKeyless(HTTPBearer):security = _BearerOrKeyless(scheme_name = "HTTPBearer")-def _bind_owner() -> None:- bind_account(OWNER)+def _bind_owner(*, via_api_key: bool = False) -> None:+ bind_account(as_api_caller(OWNER) if via_api_key else OWNER)def _get_secret_for_subject(subject: str) -> str:@@ -470,7 +470,7 @@ async def _get_current_credential(credentials must bind their write to it, or a reset landing mid-request would bless what it justrevoked. Credential reads run in the threadpool so stalled SQLite cannot block the event loop."""if credentials.scheme == KEYLESS_SCHEME:- _bind_owner()+ _bind_owner(via_api_key = True)return await run_in_threadpool(_admin_credential)if credentials.scheme == KEYLESS_FALLBACK_SCHEME:@@ -481,7 +481,7 @@ async def _get_current_credential(status_code = status.HTTP_401_UNAUTHORIZED,detail = "Invalid authentication credentials",)- _bind_owner()+ _bind_owner(via_api_key = True)return await run_in_threadpool(_admin_credential)token = credentials.credentials@@ -495,7 +495,11 @@ async def _get_current_credential()record, secret = verified# A second lookup by username would bind whoever owns that name after a delete and re-create.- bind_account(AccountContext(record["account_id"], record["username"], record["role"]))+ bind_account(+ AccountContext(+ record["account_id"], record["username"], record["role"], via_api_key = True+ )+ )return record["username"], credential_generation(secret)subject = _decode_subject_without_verification(token)diff --git a/studio/backend/auth/policy.py b/studio/backend/auth/policy.pyindex 6fe46b095de..b195c35b9ef 100644--- a/studio/backend/auth/policy.py+++ b/studio/backend/auth/policy.py@@ -6,6 +6,7 @@from __future__ import annotationsimport contextlib+import osimport threadingfrom typing import Optional@@ -101,6 +102,13 @@ def full_access_permitted() -> bool:return is_owner_context()+def api_full_access_refused() -> bool:+ """An API key (or keyless API access) asked for full access: like a local stdio MCP command, running+ outside the sandbox is the Unsloth UI's to choose, unless the operator sets the env opt-in."""+ from utils.account_context import via_api_key_context+ return via_api_key_context() and os.environ.get("UNSLOTH_STUDIO_ALLOW_API_FULL_ACCESS") != "1"++def _forbid(detail: str) -> HTTPException:return HTTPException(status_code = status.HTTP_403_FORBIDDEN, detail = detail)diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex fe960e39595..614350b2942 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -2889,7 +2889,7 @@ class ChatCompletionRequest(BaseModel):)bypass_permissions: Optional[bool] = Field(False,- description = "[x-unsloth] Bypass Permissions: when true, skip the tool-call confirmation gate AND disable the python/terminal execution sandbox (safety checks, command blocklist, resource limits). edit_file is likewise unconfined: an absolute path resolves as written and edits the real file there, instead of being held to the conversation's working directory. Secret env vars are still stripped. Takes precedence over confirm_tool_calls.",+ description = "[x-unsloth] Bypass Permissions: when true, skip the tool-call confirmation gate AND disable the python/terminal execution sandbox (safety checks, command blocklist, resource limits). edit_file is likewise unconfined: an absolute path resolves as written and edits the real file there, instead of being held to the conversation's working directory. Secret env vars are still stripped. Takes precedence over confirm_tool_calls. Refused (400) for API keys and keyless API access unless the server sets UNSLOTH_STUDIO_ALLOW_API_FULL_ACCESS=1.",)permission_mode: Optional[str] = Field(None,diff --git a/studio/backend/routes/chat_generation_runs.py b/studio/backend/routes/chat_generation_runs.pyindex 9c933bd2502..614a5d7c67e 100644--- a/studio/backend/routes/chat_generation_runs.py+++ b/studio/backend/routes/chat_generation_runs.py@@ -165,12 +165,14 @@ def _sanitize_request(payload: CreateChatGenerationRun) -> dict[str, Any]:) from exc# Without this an unservable part is queued at 202 and fails where the caller cannot see it.from routes.inference import (+ _admit_tool_access,_messages_have_embedded_image,_messages_have_input_audio,_reject_unsupported_content_parts,_request_has_video,)+ _admit_tool_access(request)_reject_unsupported_content_parts(request)# Message content/reasoning are user-authored data, not routing configuration. Scan everydiff --git a/studio/backend/state/tool_policy.py b/studio/backend/state/tool_policy.pyindex 32ecff7174a..545f74dc042 100644--- a/studio/backend/state/tool_policy.py+++ b/studio/backend/state/tool_policy.py@@ -48,7 +48,7 @@ def require_tool_access() -> None:if permission_mode != "full" and not bypass_permissions and not disable_sandbox:return- from auth.policy import full_access_permitted+ from auth.policy import api_full_access_refused, full_access_permittedfrom fastapi import HTTPExceptionif not full_access_permitted():@@ -56,6 +56,13 @@ def require_tool_access(status_code = 400,detail = "Full access is only available to the installation owner.",)+ if api_full_access_refused():+ raise HTTPException(+ status_code = 400,+ detail = "Full access (bypass_permissions, permission_mode 'full', disable_sandbox) is off for "+ "API keys: tools run in the sandbox. Use permission_mode 'auto', 'ask' or 'off', or set "+ "UNSLOTH_STUDIO_ALLOW_API_FULL_ACCESS=1 on the server to allow it.",+ )def normalize_tool_permissions(diff --git a/studio/backend/tests/test_api_key_full_access.py b/studio/backend/tests/test_api_key_full_access.pynew file mode 100644index 00000000000..631c45f0158--- /dev/null+++ b/studio/backend/tests/test_api_key_full_access.py@@ -0,0 +1,170 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Full access (no sandbox) is the Unsloth UI's to grant: an API key or keyless caller is refused unless the operator opts in."""++import asyncio+import secrets++import pytest+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClient++from auth import authentication, policy, storage+from auth.authentication import get_current_subject+from routes import inference+from state.tool_policy import require_tool_access+from utils.account_context import OWNER, as_api_caller, bind_account, current_account, reset_account++_OPT_IN = "UNSLOTH_STUDIO_ALLOW_API_FULL_ACCESS"+_FLAGS = [{"bypass_permissions": True}, {"permission_mode": "full"}, {"disable_sandbox": True}]++[email protected](autouse = True)+def no_opt_in(monkeypatch):+ monkeypatch.delenv(_OPT_IN, raising = False)+++def 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)+ policy.invalidate_account_cache()+ storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(32))+ yield storage+ policy.invalidate_account_cache()+++def _gate_under(credentials):+ """Authenticate like a request, then ask for full access in that same context."""+ from utils.account_context import _current # noqa: PLC0415++ before = _current.get()++ async def go():+ await authentication._get_current_credential(credentials, allow_password_change = False)+ bound = current_account()+ try:+ require_tool_access(None, bypass_permissions = True)+ except HTTPException as exc:+ return bound, exc+ return bound, None++ try:+ return asyncio.run(go())+ finally:+ _current.set(before)+++def _bearer(token):+ return authentication.HTTPAuthorizationCredentials(scheme = "Bearer", credentials = token)+++def test_owner_api_key_is_refused_full_access(auth_db):+ raw = storage.create_api_key("unsloth", name = "client")[0]+ bound, refused = _gate_under(_bearer(raw))+ assert bound == OWNER and bound.via_api_key+ assert refused is not None and refused.status_code == 400+ assert _OPT_IN in refused.detail+++def test_owner_ui_session_keeps_full_access(auth_db):+ _salt, _hash, secret, _must_change = storage.get_user_and_secret("unsloth")+ token = authentication.create_access_token("unsloth", secret = secret)+ bound, refused = _gate_under(_bearer(token))+ assert bound == OWNER and not bound.via_api_key+ assert refused is None+++def test_operator_opt_in_restores_api_key_full_access(auth_db, monkeypatch):+ monkeypatch.setenv(_OPT_IN, "1")+ raw = storage.create_api_key("unsloth", name = "client")[0]+ _bound, refused = _gate_under(_bearer(raw))+ assert refused is None+++def test_keyless_caller_counts_as_an_api_caller(auth_db):+ keyless = authentication.HTTPAuthorizationCredentials(+ scheme = authentication.KEYLESS_SCHEME, credentials = ""+ )+ bound, refused = _gate_under(keyless)+ assert bound == OWNER and bound.via_api_key+ assert refused is not None and refused.status_code == 400++[email protected]("mode", [None, "auto", "ask", "off"])+def test_sandboxed_modes_stay_open_to_api_keys(mode):+ token = bind_account(as_api_caller(OWNER))+ try:+ require_tool_access(mode)+ finally:+ reset_account(token)+++def _client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.include_router(inference.router, prefix = "/v1")+ return TestClient(app)+++_REQUESTS = {+ "/v1/chat/completions": {"model": "m", "messages": [{"role": "user", "content": "hi"}]},+ "/v1/responses": {"model": "m", "input": "hi"},+ "/v1/messages": {+ "model": "m",+ "max_tokens": 8,+ "messages": [{"role": "user", "content": "hi"}],+ },+}++[email protected]("path", sorted(_REQUESTS))[email protected]("flags", _FLAGS)[email protected]("api", [True, False], ids = ["api_key", "ui_session"])+def test_the_door_refuses_only_api_key_full_access(monkeypatch, path, flags, api):+ def backend(*_args, **_kwargs):+ raise HTTPException(status_code = 503, detail = "no backend in this test")++ monkeypatch.setattr(inference, "get_llama_cpp_backend", backend)+ monkeypatch.setattr(inference, "produce_openai_chat_completions", backend)+ with _client_for(as_api_caller(OWNER) if api else OWNER) as client:+ response = client.post(path, json = {**_REQUESTS[path], **flags})+ if api:+ assert response.status_code == 400, response.text+ assert _OPT_IN in response.json()["detail"]+ else:+ assert response.status_code == 503, response.text++[email protected]("flags", _FLAGS[:2])[email protected]("api", [True, False], ids = ["api_key", "ui_session"])+def test_durable_chat_runs_refuse_api_key_full_access_before_queueing(flags, api):+ from routes import chat_generation_runs as runs++ payload = runs.CreateChatGenerationRun(+ runId = "r1",+ threadId = "t1",+ userMessageId = "u1",+ assistantMessageId = "a1",+ requestPayload = {"messages": [{"role": "user", "content": "hi"}], **flags},+ )+ token = bind_account(as_api_caller(OWNER) if api else OWNER)+ try:+ if api:+ with pytest.raises(HTTPException) as refused:+ runs._sanitize_request(payload)+ assert refused.value.status_code == 400 and _OPT_IN in refused.value.detail+ else:+ runs._sanitize_request(payload)+ finally:+ reset_account(token)diff --git a/studio/backend/utils/account_context.py b/studio/backend/utils/account_context.pyindex 4f1c946a99d..b18d5bfb1a7 100644--- a/studio/backend/utils/account_context.py+++ b/studio/backend/utils/account_context.py@@ -7,7 +7,7 @@ from __future__ import annotationsimport threadingfrom contextvars import ContextVar, Token-from dataclasses import dataclass+from dataclasses import dataclass, field, replacefrom typing import Any, Awaitable, Callable, TypeVarOWNER_ACCOUNT_ID = "owner"@@ -25,6 +25,8 @@ class AccountContext:account_id: strusername: strrole: str = ROLE_USER+ # An sk-unsloth key or keyless API access admitted the request, not a UI session; not part of identity.+ via_api_key: bool = field(default = False, compare = False)@propertydef is_owner(self) -> bool:@@ -48,6 +50,14 @@ def is_owner_context() -> bool:return _current.get().is_owner+def via_api_key_context() -> bool:+ return _current.get().via_api_key+++def as_api_caller(account: AccountContext) -> AccountContext:+ return replace(account, via_api_key = True)++def bind_account(account: AccountContext) -> Token[AccountContext]:if not isinstance(account, AccountContext) or not account.account_id:raise ValueError("bind_account needs an AccountContext with an account_id")