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: confine native dataset drops to the account workspace; cap child API key expiry (#13273)

Daniel Hana7bddd7dd880
diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.py
index a5bda2acc41..4ff3bc00d6f 100644
--- a/studio/backend/auth/storage.py
+++ b/studio/backend/auth/storage.py
@@ -1817,6 +1817,7 @@ def validate_api_key_account(raw_key: str, *, touch: bool = True) -> Optional[Tu
"username": row["username"],
"role": row["role"],
"is_active": int(row["account_active"]),
+ "expires_at": row["expires_at"],
}
return record, secret
finally:
diff --git a/studio/backend/hub/services/datasets/local.py b/studio/backend/hub/services/datasets/local.py
index 7dc3f9001e9..a5995eff046 100644
--- a/studio/backend/hub/services/datasets/local.py
+++ b/studio/backend/hub/services/datasets/local.py
@@ -324,6 +324,7 @@ def _upload_destination(filename: str) -> tuple[str, Path, int, str]:
def _native_upload_dataset_response(native_path_lease: str) -> UploadDatasetResponse:
+ from core.training.account_jobs import account_path
from utils.native_path_leases import NativePathLeaseError, verify_native_path_lease
try:
@@ -337,6 +338,8 @@ def _native_upload_dataset_response(native_path_lease: str) -> UploadDatasetResp
except NativePathLeaseError as exc:
raise HTTPException(status_code = 400, detail = str(exc)) from exc
+ # A managed account may only import files inside its own workspace, as the RAG/seed/library drops check.
+ account_path(grant.canonical_path)
filename, stored_path, max_bytes, max_label = _upload_destination(grant.canonical_path.name)
if grant.size_bytes is not None and grant.size_bytes > max_bytes:
raise _upload_too_large(max_label)
diff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.py
index ba946959d70..cf38319fea0 100644
--- a/studio/backend/routes/auth.py
+++ b/studio/backend/routes/auth.py
@@ -4,6 +4,7 @@
"""Authentication API routes."""
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
+from fastapi.security import HTTPAuthorizationCredentials
import base64
import importlib.util
@@ -16,6 +17,7 @@ import time
from collections import deque
from datetime import datetime, timedelta, timezone
from pathlib import Path
+from typing import Optional
from models.auth import (
ApiKeyListResponse,
@@ -40,7 +42,9 @@ from auth.authentication import (
get_current_credential,
get_current_subject,
get_current_subject_allow_password_change,
+ is_keyless,
refresh_access_token,
+ security,
)
router = APIRouter()
@@ -804,6 +808,7 @@ def _key_account_scope() -> "str | None":
async def create_api_key(
payload: CreateApiKeyRequest,
credential: tuple = Depends(get_current_credential),
+ credentials: Optional[HTTPAuthorizationCredentials] = Depends(security),
_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."""
@@ -813,6 +818,14 @@ async def create_api_key(
expires_at = (
datetime.now(timezone.utc) + timedelta(days = payload.expires_in_days)
).isoformat()
+ # A key minted with an expiring key expires no later than it, so a leaked short-lived key cannot
+ # be turned into a permanent one.
+ parent_expires_at = _api_key_caller_expiry(credentials)
+ if parent_expires_at is not None and (
+ expires_at is None
+ or datetime.fromisoformat(expires_at) > datetime.fromisoformat(parent_expires_at)
+ ):
+ expires_at = parent_expires_at
try:
raw_key, row = storage.create_api_key(
@@ -833,6 +846,23 @@ async def create_api_key(
)
+def _api_key_caller_expiry(credentials: Optional[HTTPAuthorizationCredentials]) -> Optional[str]:
+ """Expiry of the sk-unsloth key that authenticated this request, or None (UI session, keyless
+ caller, or a key that never expires)."""
+ if credentials is None or is_keyless(credentials):
+ return None
+ raw = credentials.credentials or ""
+ if not raw.startswith(storage.API_KEY_PREFIX):
+ return None
+ validated = storage.validate_api_key_account(raw, touch = False)
+ if validated is None:
+ # Expired or revoked since it authenticated: no cap to apply, so refuse rather than mint uncapped.
+ raise HTTPException(
+ status_code = status.HTTP_401_UNAUTHORIZED, detail = "Invalid or expired token"
+ )
+ return validated[0].get("expires_at")
+
+
@router.get("/api-keys", response_model = ApiKeyListResponse)
def list_api_keys(
current_subject: str = Depends(get_current_subject),
diff --git a/studio/backend/tests/test_api_key_expiry_inheritance.py b/studio/backend/tests/test_api_key_expiry_inheritance.py
new file mode 100644
index 00000000000..3b98abb7960
--- /dev/null
+++ b/studio/backend/tests/test_api_key_expiry_inheritance.py
@@ -0,0 +1,92 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A key minted with an expiring API key expires no later than that key, so it cannot outlive it."""
+
+import importlib.util
+import secrets
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from auth import storage
+
+
[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)
+ monkeypatch.setattr(storage, "_credential_encryption_key_cache", None)
+ storage.create_initial_user(
+ username = storage.DEFAULT_ADMIN_USERNAME,
+ password = "human-password-123",
+ jwt_secret = secrets.token_urlsafe(64),
+ )
+ yield
+
+
+def client():
+ route_path = Path(__file__).resolve().parents[1] / "routes" / "auth.py"
+ spec = importlib.util.spec_from_file_location("_api_key_expiry_auth_route", route_path)
+ auth_route = importlib.util.module_from_spec(spec)
+ assert spec.loader is not None
+ spec.loader.exec_module(auth_route)
+ app = FastAPI()
+ app.include_router(auth_route.router, prefix = "/api/auth")
+ return TestClient(app)
+
+
+def _parent(expires_at):
+ raw, _row = storage.create_api_key(
+ storage.DEFAULT_ADMIN_USERNAME, name = "parent", expires_at = expires_at
+ )
+ return raw
+
+
+def _mint(client, raw, **body):
+ response = client.post(
+ "/api/auth/api-keys",
+ headers = {"Authorization": f"Bearer {raw}"},
+ json = {"name": "child", **body},
+ )
+ assert response.status_code == 200, response.text
+ return response.json()["api_key"]["expires_at"]
+
+
+def test_child_of_an_expiring_key_inherits_its_expiry(client):
+ parent_expiry = (datetime.now(timezone.utc) + timedelta(hours = 2)).isoformat()
+ raw = _parent(parent_expiry)
+ assert datetime.fromisoformat(_mint(client, raw)) == datetime.fromisoformat(parent_expiry)
+ assert datetime.fromisoformat(_mint(client, raw, expires_in_days = 30)) == datetime.fromisoformat(
+ parent_expiry
+ )
+
+
+def test_a_shorter_requested_expiry_is_kept(client):
+ raw = _parent((datetime.now(timezone.utc) + timedelta(days = 10)).isoformat())
+ child = datetime.fromisoformat(_mint(client, raw, expires_in_days = 1))
+ assert child < datetime.now(timezone.utc) + timedelta(days = 2)
+
+
+def test_child_of_a_non_expiring_key_is_unchanged(client):
+ raw = _parent(None)
+ assert _mint(client, raw) is None
+
+
+def test_a_parent_key_revoked_mid_request_mints_nothing(client, monkeypatch):
+ raw = _parent((datetime.now(timezone.utc) + timedelta(hours = 2)).isoformat())
+ # Authentication passed; the key is gone by the time the cap is read.
+ monkeypatch.setattr(storage, "validate_api_key_account", lambda key, touch = True: None)
+ response = client.post(
+ "/api/auth/api-keys", headers = {"Authorization": f"Bearer {raw}"}, json = {"name": "child"}
+ )
+ assert response.status_code == 401
+ assert [row["name"] for row in storage.list_api_keys(storage.DEFAULT_ADMIN_USERNAME)] == [
+ "parent"
+ ]
diff --git a/studio/backend/tests/test_dataset_native_import_account.py b/studio/backend/tests/test_dataset_native_import_account.py
new file mode 100644
index 00000000000..19f5cd3337f
--- /dev/null
+++ b/studio/backend/tests/test_dataset_native_import_account.py
@@ -0,0 +1,93 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A native dataset drop is confined to a managed account's workspace, like the RAG/seed/library drops."""
+
+import base64
+import hashlib
+import hmac
+import json
+import os
+import time
+from pathlib import Path
+
+import pytest
+from fastapi import HTTPException
+
+import utils.native_path_leases as leases
+from auth import policy
+from hub.services.datasets import local
+from utils.account_context import OWNER, AccountContext, run_as
+from utils.paths import workspace_root
+
+SECRET = b"d" * 32
+ALICE = AccountContext("alice-dataset-account", "alice")
+
+
[email protected](autouse = True)
+def _setup(tmp_path, monkeypatch):
+ monkeypatch.setenv(leases.LEASE_SECRET_ENV, _b64(SECRET))
+ monkeypatch.setattr(leases, "_CACHED_LEASE_SECRET", None, raising = False)
+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)
+ store = tmp_path / "store"
+ store.mkdir()
+ monkeypatch.setattr(local, "DATASET_UPLOAD_DIR", store)
+ yield store
+ monkeypatch.setattr(leases, "_CACHED_LEASE_SECRET", None, raising = False)
+
+
+def _b64(raw: bytes) -> str:
+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
+
+
+def _sign(path: Path) -> str:
+ st = os.stat(path)
+ now_ms = int(time.time() * 1000)
+ payload = {
+ "version": 1,
+ "operation": "dataset-import",
+ "canonical_path": str(path),
+ "path_kind": "dataset",
+ "path_type": "file",
+ "source_kind": "drop",
+ "token_id_hash": hashlib.sha256(b"path_token").hexdigest(),
+ "issued_at_ms": now_ms,
+ "expires_at_ms": now_ms + 120_000,
+ "nonce": os.urandom(16).hex(),
+ "display_label": path.name,
+ "size_bytes": st.st_size,
+ "modified_ms": int(st.st_mtime_ns // 1_000_000),
+ "device_id": format(st.st_dev, "x"),
+ "file_id": format(st.st_ino, "x"),
+ }
+ payload_b64 = _b64(json.dumps(payload).encode("utf-8"))
+ signature = hmac.new(SECRET, payload_b64.encode("ascii"), hashlib.sha256).digest()
+ return f"{payload_b64}.{_b64(signature)}"
+
+
+def _csv(directory: Path) -> Path:
+ directory.mkdir(parents = True, exist_ok = True)
+ path = directory / "rows.csv"
+ path.write_bytes(b"a,b\n1,2\n")
+ return path
+
+
+def test_managed_account_cannot_import_a_file_outside_its_workspace(tmp_path, _setup):
+ outside = _csv(tmp_path / "outside")
+ with pytest.raises(HTTPException) as exc:
+ run_as(ALICE, local._native_upload_dataset_response, _sign(outside))
+ assert exc.value.status_code == 403
+ assert list(_setup.iterdir()) == []
+
+
+def test_managed_account_imports_a_file_inside_its_workspace(_setup):
+ inside = _csv(run_as(ALICE, workspace_root) / "drops")
+ response = run_as(ALICE, local._native_upload_dataset_response, _sign(inside))
+ assert Path(response.stored_path).read_bytes() == b"a,b\n1,2\n"
+
+
+def test_owner_import_is_unchanged(tmp_path):
+ outside = _csv(tmp_path / "outside")
+ response = run_as(OWNER, local._native_upload_dataset_response, _sign(outside))
+ assert response.filename == "rows.csv"
+ assert Path(response.stored_path).read_bytes() == b"a,b\n1,2\n"