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: per-account model allowlist for multi-user installs (#13359)

Daniel Han8bf274b98fcb
diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.py
index 28eb36822e7..8750e124a53 100644
--- a/studio/backend/auth/storage.py
+++ b/studio/backend/auth/storage.py
@@ -9,6 +9,7 @@ from contextlib import contextmanager
import hashlib
import hmac
import ipaddress
+import json
import os
import re
import secrets
@@ -378,6 +379,8 @@ _ACCOUNT_COLUMNS = (
("account_password_salt", "TEXT"),
("account_password_hash", "TEXT"),
("account_jwt_secret", "TEXT"),
+ # JSON list of repo ids / ``org/*`` patterns; NULL = every model (#11650).
+ ("model_allowlist", "TEXT"),
)
@@ -614,6 +617,48 @@ def validate_account_username(username: str) -> str:
return username
+MAX_MODEL_ALLOWLIST_ENTRIES = 500
+# ``org/name``, ``org/*``, or a legacy top-level id such as ``gpt2``.
+_MODEL_ALLOWLIST_ENTRY = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,95}(?:/[A-Za-z0-9._*-]{1,96})?")
+_HUB_URL_PREFIX = re.compile(r"^(?:https?://)?(?:www\.)?(?:hf\.co|huggingface\.co)/", re.IGNORECASE)
+
+
+def normalize_model_allowlist(entries) -> Optional[list[str]]:
+ """Repo ids or ``org/*`` patterns, lowercased and deduplicated; empty means unrestricted."""
+ if entries is None:
+ return None
+ normalized: list[str] = []
+ for entry in entries:
+ if not isinstance(entry, str):
+ raise ValueError("Model access entries must be strings")
+ entry = _HUB_URL_PREFIX.sub("", entry.strip()).split(":", 1)[0].strip("/")
+ if not entry:
+ continue
+ if _MODEL_ALLOWLIST_ENTRY.fullmatch(entry) is None:
+ raise ValueError(
+ f"{entry!r} is not a Hugging Face model id such as unsloth/Qwen3-4B-GGUF or unsloth/*"
+ )
+ entry = entry.lower()
+ if entry not in normalized:
+ normalized.append(entry)
+ if len(normalized) > MAX_MODEL_ALLOWLIST_ENTRIES:
+ raise ValueError(f"At most {MAX_MODEL_ALLOWLIST_ENTRIES} models can be listed")
+ return normalized or None
+
+
+def _decode_model_allowlist(raw) -> Optional[list[str]]:
+ if raw is None:
+ return None
+ try:
+ value = json.loads(raw)
+ except (TypeError, ValueError):
+ # A corrupt row must not silently grant every model.
+ return []
+ if not isinstance(value, list):
+ return []
+ return [entry for entry in value if isinstance(entry, str)]
+
+
def _public_account(row) -> dict:
return {
"account_id": row["account_id"],
@@ -622,6 +667,11 @@ def _public_account(row) -> dict:
"is_active": bool(row["is_active"]),
"created_at": row["created_at"],
"setup_code_pending": bool(row["setup_code_hash"]),
+ "model_allowlist": (
+ _decode_model_allowlist(row["model_allowlist"])
+ if "model_allowlist" in row.keys()
+ else None
+ ),
}
@@ -818,6 +868,42 @@ def set_account_active(account_id: str, is_active: bool) -> dict:
return result
+def set_account_model_allowlist(account_id: str, allowlist: Optional[list[str]]) -> dict:
+ from auth.policy import account_mutation
+
+ allowlist = normalize_model_allowlist(allowlist)
+ with account_mutation():
+ conn = get_connection()
+ try:
+ with conn:
+ conn.execute("BEGIN IMMEDIATE")
+ _managed_account(conn, account_id)
+ conn.execute(
+ "UPDATE auth_user SET model_allowlist = ? WHERE account_id = ?",
+ (None if allowlist is None else json.dumps(allowlist), account_id),
+ )
+ result = _public_account(_managed_account(conn, account_id))
+ finally:
+ conn.close()
+ return result
+
+
+def account_model_allowlist(account_id: str) -> Optional[tuple[str, ...]]:
+ """``None`` = every model. The owner is never restricted."""
+ conn = get_connection()
+ try:
+ row = conn.execute(
+ "SELECT role, model_allowlist FROM auth_user WHERE account_id = ?", (account_id,)
+ ).fetchone()
+ finally:
+ conn.close()
+ # A deleted account is fenced by credential revocation, not here.
+ if row is None or row["role"] == "owner":
+ return None
+ allowlist = _decode_model_allowlist(row["model_allowlist"])
+ return None if allowlist is None else tuple(allowlist)
+
+
def delete_account(account_id: str, retire) -> None:
"""Revoke, retire files, then drop the identity under a write lock. ``retire()`` must not write
auth.db under that lock; a failed retire leaves the account disabled for a retry."""
diff --git a/studio/backend/core/training/account_jobs.py b/studio/backend/core/training/account_jobs.py
index b0b40aa0813..f548f126d27 100644
--- a/studio/backend/core/training/account_jobs.py
+++ b/studio/backend/core/training/account_jobs.py
@@ -141,8 +141,12 @@ def require_explicit_credentials(values: dict) -> None:
def validate_job_paths(values: dict, *, cached_resources: bool = False) -> None:
if not managed_account():
return
+ from hub.services.models import account_access
+
for key in ("model_name", "base_model", "base_model_id", "hf_dataset"):
account_path(values.get(key), reference = True)
+ for key in ("model_name", "base_model", "base_model_id"):
+ account_access.require_model_allowed(values.get(key))
for key, repo_type in (
("model_local_path", "model"),
("dataset_local_path", "dataset"),
@@ -161,7 +165,6 @@ def validate_job_paths(values: dict, *, cached_resources: bool = False) -> None:
reference = values.get(key)
# A cached claim pins the shared cache, so the caller's token never authorizes it.
if values.get(claimed) and reference:
- from hub.services.models import account_access
account_access.require_model_access(str(reference), repo_type)
for key in (
"checkpoint_path",
diff --git a/studio/backend/hub/services/models/account_access.py b/studio/backend/hub/services/models/account_access.py
index b391d0a0525..5344985a910 100644
--- a/studio/backend/hub/services/models/account_access.py
+++ b/studio/backend/hub/services/models/account_access.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import re
import json
import os
+from fnmatch import fnmatchcase
import sqlite3
import sys
import threading
@@ -362,9 +363,25 @@ def restore_resident_metadata(modality: str) -> bool:
return restored
+def _resident_outside_allowlist(modality: str | None) -> bool:
+ """A resident the owner has since taken off the caller's list is no longer the caller's."""
+ if modality is None or model_allowlist() is None:
+ return False
+ recorded = _resident_accounts.get(modality)
+ for reference in recorded[1] if recorded is not None else ():
+ # Labels without a slash name a native local file, not a Hub repo.
+ if isinstance(reference, str) and "/" in reference:
+ repo_id = _reference_repo_id(reference.strip())
+ if repo_id is not None and not model_allowed(repo_id):
+ return True
+ return False
+
+
def resident_hidden(modality: str | None = None, reference: str | None = None) -> bool:
if not managed_account():
return False
+ if _resident_outside_allowlist(modality):
+ return True
if modality is not None and resident_shared_with(modality, current_account_id()):
return False
from core.inference import gpu_arbiter
@@ -756,6 +773,52 @@ def _write_grant(path: Path, key: str) -> None:
)
+MODEL_NOT_ALLOWED = "This model is not enabled for your account. Ask the Studio owner to allow it."
+
+_allowlists: dict[str, tuple[int, tuple[str, ...] | None]] = {}
+_allowlists_lock = threading.Lock()
+
+
+def model_allowlist() -> tuple[str, ...] | None:
+ """The caller's owner-set allowlist (#11650); ``None`` = every model, as before."""
+ if not managed_account():
+ return None
+ account_id = current_account_id()
+ generation = policy.account_generation()
+ with _allowlists_lock:
+ cached = _allowlists.get(account_id)
+ if cached is not None and cached[0] == generation:
+ return cached[1]
+ from auth import storage
+
+ try:
+ allowlist = storage.account_model_allowlist(account_id)
+ except Exception: # noqa: BLE001 - never cached, so a transient error does not stick
+ return ()
+ with _allowlists_lock:
+ if len(_allowlists) >= 256:
+ _allowlists.clear()
+ _allowlists[account_id] = (generation, allowlist)
+ return allowlist
+
+
+def model_allowed(repo_id: str) -> bool:
+ allowlist = model_allowlist()
+ if allowlist is None:
+ return True
+ repo_id = repo_id.strip().lower()
+ return any(fnmatchcase(repo_id, pattern) for pattern in allowlist)
+
+
+def _reference_repo_id(reference: str) -> str | None:
+ path = Path(reference).expanduser()
+ if path.is_absolute() or reference.startswith(("./", "../", "~")) or path.exists():
+ cached = _cached_repo(path)
+ return cached[0] if cached is not None and cached[1] == "model" else None
+ parts = reference.split(":", 1)[0].split("/")
+ return "/".join(parts[:2]) if all(parts[:2]) else None
+
+
def repo_visible(
repo_id: str,
repo_type: str = "model",
@@ -767,6 +830,8 @@ def repo_visible(
return True
if not repo_id:
return False
+ if repo_type == "model" and not model_allowed(repo_id):
+ return False
granted = model_grants() if grants is None else grants
return _grant_key(repo_id, repo_type) in granted or (
repo_is_public(repo_id, repo_type, offline = True)
@@ -836,9 +901,20 @@ def require_model_access(
) -> None:
access_options = {"offline": True} if offline else {}
if not model_visible(reference, repo_type = repo_type, **access_options):
+ if repo_type == "model":
+ require_model_allowed(reference)
raise HTTPException(status_code = 404, detail = "Model not found")
+def require_model_allowed(reference) -> None:
+ """The allowlist alone, for routes that fetch a Hub model without the visibility gate."""
+ if not isinstance(reference, str) or model_allowlist() is None:
+ return
+ repo_id = _reference_repo_id(reference.strip())
+ if repo_id is not None and not model_allowed(repo_id):
+ raise HTTPException(status_code = 403, detail = MODEL_NOT_ALLOWED)
+
+
def _row_reference(row):
get = row.get if isinstance(row, dict) else lambda key, default = None: getattr(row, key, default)
return get("path") or get("local_path") or get("repo_id") or get("model_id") or get("id")
@@ -879,6 +955,8 @@ def authorize_download(repo_id: str, repo_type: str, hf_token) -> None:
"""A cache hit is not proof the requester may read private Hub content."""
if not managed_account():
return
+ if repo_type == "model" and not model_allowed(repo_id or ""):
+ raise HTTPException(status_code = 403, detail = MODEL_NOT_ALLOWED)
if not _source_speaks_for_the_cache():
raise HTTPException(
status_code = 403,
diff --git a/studio/backend/models/auth.py b/studio/backend/models/auth.py
index 5f027671557..76e2d370d6e 100644
--- a/studio/backend/models/auth.py
+++ b/studio/backend/models/auth.py
@@ -7,7 +7,11 @@ from typing import Optional
from pydantic import BaseModel, Field, field_validator
-from auth.storage import MIN_PASSWORD_LENGTH, validate_account_username
+from auth.storage import (
+ MIN_PASSWORD_LENGTH,
+ normalize_model_allowlist,
+ validate_account_username,
+)
class AuthLoginRequest(BaseModel):
@@ -136,6 +140,18 @@ class AccountActiveRequest(BaseModel):
is_active: bool
+class AccountModelAccessRequest(BaseModel):
+ model_allowlist: Optional[list[str]] = Field(
+ None,
+ description = "Hugging Face repo ids or org/* patterns; null or empty allows every model",
+ )
+
+ @field_validator("model_allowlist")
+ @classmethod
+ def validate_model_allowlist(cls, value: Optional[list[str]]) -> Optional[list[str]]:
+ return normalize_model_allowlist(value)
+
+
class AccountResponse(BaseModel):
account_id: str
username: str
@@ -143,6 +159,7 @@ class AccountResponse(BaseModel):
is_active: bool
created_at: str
setup_code_pending: bool
+ model_allowlist: Optional[list[str]] = None
class AccountListResponse(BaseModel):
diff --git a/studio/backend/routes/accounts.py b/studio/backend/routes/accounts.py
index a507acf2e0a..4b5f5db297c 100644
--- a/studio/backend/routes/accounts.py
+++ b/studio/backend/routes/accounts.py
@@ -15,6 +15,7 @@ from auth.authentication import get_current_subject
from models.auth import (
AccountActiveRequest,
AccountListResponse,
+ AccountModelAccessRequest,
AccountResponse,
AccountSetupResponse,
CreateAccountRequest,
@@ -163,6 +164,15 @@ def set_account_active(account_id: str, payload: AccountActiveRequest):
return result
[email protected]("/{account_id}/model-access", response_model = AccountResponse)
+def set_account_model_access(account_id: str, payload: AccountModelAccessRequest):
+ with _account_errors():
+ result = storage.set_account_model_allowlist(account_id, payload.model_allowlist)
+ # A shared resident it may no longer use needs a fresh, gated load to join again.
+ account_access.retire_resident_shares(account_id)
+ return result
+
+
@router.delete("/{account_id}", status_code = status.HTTP_204_NO_CONTENT)
def delete_account(account_id: str):
from core.training.account_jobs import AccountRetirementError
diff --git a/studio/backend/tests/multi_account/factories_providers.py b/studio/backend/tests/multi_account/factories_providers.py
index 6422b98e3b4..11899eef690 100644
--- a/studio/backend/tests/multi_account/factories_providers.py
+++ b/studio/backend/tests/multi_account/factories_providers.py
@@ -367,6 +367,15 @@ FACTORIES = {
self_expected = (400,),
reason = _ACCOUNTS_SELF_REASON,
),
+ "routes.accounts:PUT:/{account_id}/model-access": Factory(
+ "prov-account",
+ {"model_allowlist": ["unsloth/*"]},
+ owner = (200,),
+ right = (403,),
+ wrong = (403,),
+ self_expected = (400,),
+ reason = _ACCOUNTS_SELF_REASON,
+ ),
}
SKIPPED = {
diff --git a/studio/backend/tests/test_account_lifecycle.py b/studio/backend/tests/test_account_lifecycle.py
index 4060dc99438..ee287756a43 100644
--- a/studio/backend/tests/test_account_lifecycle.py
+++ b/studio/backend/tests/test_account_lifecycle.py
@@ -89,7 +89,8 @@ def db_rows(table):
@pytest.mark.parametrize("actor", ["unsloth", "alice", "bob"])
@pytest.mark.parametrize(
- "operation", ["list", "create", "setup-code", "deactivate", "reactivate", "delete"]
+ "operation",
+ ["list", "create", "setup-code", "deactivate", "reactivate", "model-access", "delete"],
)
@pytest.mark.parametrize("target", ["unsloth", "alice", "bob"])
def test_owner_alice_bob_endpoint_matrix(matrix, actor, operation, target):
@@ -103,6 +104,10 @@ def test_owner_alice_bob_endpoint_matrix(matrix, actor, operation, target):
response = client.post("/api/accounts", headers = headers(actor), json = {"username": "carol"})
elif operation == "setup-code":
response = client.post(url + "/setup-code", headers = headers(actor))
+ elif operation == "model-access":
+ response = client.put(
+ url + "/model-access", headers = headers(actor), json = {"model_allowlist": ["unsloth/*"]}
+ )
elif operation in ("deactivate", "reactivate"):
response = client.patch(
url, headers = headers(actor), json = {"is_active": operation == "reactivate"}
@@ -122,7 +127,15 @@ def test_owner_alice_bob_endpoint_matrix(matrix, actor, operation, target):
assert {r["username"] for r in response.json()["accounts"]} == {"unsloth", "alice", "bob"}
assert all(
set(row)
- == {"account_id", "username", "role", "is_active", "created_at", "setup_code_pending"}
+ == {
+ "account_id",
+ "username",
+ "role",
+ "is_active",
+ "created_at",
+ "setup_code_pending",
+ "model_allowlist",
+ }
for row in response.json()["accounts"]
)
@@ -134,6 +147,7 @@ def test_owner_alice_bob_endpoint_matrix(matrix, actor, operation, target):
("POST", "", {"username": "carol"}),
("POST", "/missing/setup-code", None),
("PATCH", "/missing", {"is_active": False}),
+ ("PUT", "/missing/model-access", {"model_allowlist": None}),
("DELETE", "/missing", None),
],
)
diff --git a/studio/backend/tests/test_account_model_allowlist.py b/studio/backend/tests/test_account_model_allowlist.py
new file mode 100644
index 00000000000..fb1889e94a0
--- /dev/null
+++ b/studio/backend/tests/test_account_model_allowlist.py
@@ -0,0 +1,280 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Owner-set per-account model allowlists (#11650)."""
+
+import importlib.util
+import secrets
+import sqlite3
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import FastAPI, HTTPException
+from fastapi.testclient import TestClient
+
+from auth import authentication, policy, storage
+from hub.services.models import account_access as access
+from state import active_generations
+from utils.account_context import OWNER, bind_account, reset_account, run_as
+from utils.paths import storage_roots
+
+
+def _load_route(name):
+ path = Path(__file__).resolve().parents[1] / "routes" / f"{name}.py"
+ spec = importlib.util.spec_from_file_location(f"_allowlist_{name}", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def env(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))
+ monkeypatch.setattr(storage_roots.tempfile, "gettempdir", lambda: str(tmp_path / "tmp"))
+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "studio" / "auth" / "auth.db")
+ monkeypatch.setattr(
+ storage, "_BOOTSTRAP_PW_PATH", storage.DB_PATH.parent / ".bootstrap_password"
+ )
+ monkeypatch.setattr(storage, "_bootstrap_password", None)
+ monkeypatch.setattr(storage, "_api_key_pbkdf2_salt_cache", None)
+ monkeypatch.setattr(access, "_public_repos", {})
+ monkeypatch.setattr(access, "_allowlists", {})
+ # Every repo is public and readable, so only the allowlist can refuse.
+ monkeypatch.setattr(
+ access,
+ "HfApi",
+ lambda **_k: SimpleNamespace(
+ repo_info = lambda *a, **k: SimpleNamespace(private = False, gated = False),
+ auth_check = lambda *a, **k: None,
+ ),
+ )
+ storage._reset_api_key_hash_cache()
+ token = bind_account(OWNER)
+ policy.invalidate_account_cache()
+ active_generations.reset_for_tests()
+ storage.create_initial_user("unsloth", "owner-password", secrets.token_urlsafe(64))
+ for username in ("alice", "bob"):
+ storage.create_initial_user(username, f"{username}-password", secrets.token_urlsafe(64))
+ accounts = _load_route("accounts")
+ app = FastAPI()
+ app.include_router(accounts.router, prefix = "/api/accounts")
+ with TestClient(app) as client:
+ yield client
+ active_generations.reset_for_tests()
+ reset_account(token)
+ policy.invalidate_account_cache()
+ storage._reset_api_key_hash_cache()
+
+
+def headers(username = "unsloth"):
+ return {"Authorization": "Bearer " + authentication.create_access_token(username)}
+
+
+def put_access(
+ client,
+ target,
+ allowlist,
+ actor = "unsloth",
+):
+ account = storage.get_account(target)
+ return client.put(
+ f"/api/accounts/{account.account_id}/model-access",
+ headers = headers(actor),
+ json = {"model_allowlist": allowlist},
+ )
+
+
+def as_user(username, fn, *args, **kwargs):
+ return run_as(storage.get_account(username), fn, *args, **kwargs)
+
+
+def test_normalize_accepts_ids_urls_quants_and_patterns():
+ assert storage.normalize_model_allowlist(None) is None
+ assert storage.normalize_model_allowlist([]) is None
+ assert storage.normalize_model_allowlist(["", " "]) is None
+ assert storage.normalize_model_allowlist(
+ [
+ " Unsloth/Qwen3-4B-GGUF ",
+ "https://huggingface.co/unsloth/qwen3-4b-gguf",
+ "unsloth/Qwen3-4B-GGUF:Q4_K_M",
+ "meta-llama/*",
+ "GPT2",
+ ]
+ ) == ["unsloth/qwen3-4b-gguf", "meta-llama/*", "gpt2"]
+ for bad in ("*", "../etc/passwd", "*/model", "a/b/c", "org/na me"):
+ with pytest.raises(ValueError):
+ storage.normalize_model_allowlist([bad])
+
+
+def test_schema_upgrade_is_idempotent_and_defaults_to_unrestricted(env):
+ conn = storage.get_connection()
+ try:
+ columns = [row[1] for row in conn.execute("PRAGMA table_info(auth_user)")]
+ finally:
+ conn.close()
+ assert columns.count("model_allowlist") == 1
+ # A pre-existing install: drop the column, reopen twice, data intact and unrestricted.
+ raw = sqlite3.connect(storage.DB_PATH)
+ raw.execute("ALTER TABLE auth_user DROP COLUMN model_allowlist")
+ raw.commit()
+ raw.close()
+ storage._auth_schema_ready.clear()
+ for _ in range(2):
+ storage.get_connection().close()
+ accounts = {row["username"]: row for row in storage.list_accounts()}
+ assert set(accounts) == {"unsloth", "alice", "bob"}
+ assert all(row["model_allowlist"] is None for row in accounts.values())
+ assert storage.account_model_allowlist(storage.get_account("alice").account_id) is None
+
+
[email protected]("actor", ["alice", "bob"])
+def test_only_the_owner_can_set_model_access(env, actor):
+ response = put_access(env, "alice", ["unsloth/*"], actor = actor)
+ assert response.status_code == 403
+ assert storage.account_model_allowlist(storage.get_account("alice").account_id) is None
+
+
+def test_owner_cannot_be_restricted_and_bad_input_is_refused(env):
+ assert put_access(env, "unsloth", ["unsloth/*"]).status_code == 400
+ assert put_access(env, "alice", ["not a repo"]).status_code == 422
+ response = env.put(
+ "/api/accounts/missing/model-access", headers = headers(), json = {"model_allowlist": None}
+ )
+ assert response.status_code == 404
+
+
+def test_set_is_idempotent_and_listed(env):
+ for _ in range(2):
+ response = put_access(env, "alice", ["Unsloth/*", "unsloth/*"])
+ assert response.status_code == 200
+ assert response.json()["model_allowlist"] == ["unsloth/*"]
+ listed = {
+ row["username"]: row
+ for row in env.get("/api/accounts", headers = headers()).json()["accounts"]
+ }
+ assert listed["alice"]["model_allowlist"] == ["unsloth/*"]
+ assert listed["bob"]["model_allowlist"] is None
+ assert put_access(env, "alice", []).json()["model_allowlist"] is None
+
+
+def test_allowlist_gates_listing_loading_and_downloading(env):
+ assert put_access(env, "alice", ["unsloth/*", "google/gemma-3-1b-it"]).status_code == 200
+ for repo in ("unsloth/Qwen3-4B-GGUF", "Google/Gemma-3-1B-it"):
+ assert as_user("alice", access.repo_visible, repo)
+ as_user("alice", access.require_model_access, repo)
+ as_user("alice", access.authorize_download, repo, "model", None)
+ as_user("alice", access.require_model_access, "unsloth/Qwen3-4B-GGUF:Q4_K_M")
+
+ assert not as_user("alice", access.repo_visible, "meta-llama/Llama-3.2-1B")
+ for gate in (
+ lambda: as_user("alice", access.require_model_access, "meta-llama/Llama-3.2-1B"),
+ lambda: as_user(
+ "alice", access.authorize_download, "meta-llama/Llama-3.2-1B", "model", None
+ ),
+ ):
+ with pytest.raises(HTTPException) as refused:
+ gate()
+ assert refused.value.status_code == 403
+ assert refused.value.detail == access.MODEL_NOT_ALLOWED
+
+ rows = [{"id": "unsloth/Qwen3-4B-GGUF"}, {"id": "meta-llama/Llama-3.2-1B"}]
+ assert as_user("alice", access.filter_model_rows, rows) == rows[:1]
+ # Datasets are not models; the allowlist leaves them alone.
+ assert as_user("alice", access.repo_visible, "meta-llama/some-dataset", "dataset")
+ # Other accounts and the owner are unaffected.
+ assert as_user("bob", access.filter_model_rows, rows) == rows
+ assert run_as(OWNER, access.filter_model_rows, rows) == rows
+
+
+def test_allowlist_applies_to_cached_snapshot_paths(env, tmp_path, monkeypatch):
+ cache = tmp_path / "hub"
+ snapshot = cache / "models--meta-llama--Llama-3.2-1B" / "snapshots" / "abc"
+ snapshot.mkdir(parents = True)
+ monkeypatch.setattr("utils.hf_cache_settings.known_hf_hub_caches", lambda: [cache])
+ assert as_user("alice", access.model_visible, str(snapshot))
+ assert put_access(env, "alice", ["unsloth/*"]).status_code == 200
+ assert not as_user("alice", access.model_visible, str(snapshot))
+ with pytest.raises(HTTPException) as refused:
+ as_user("alice", access.require_model_access, str(snapshot))
+ assert refused.value.status_code == 403
+
+
+def test_changes_apply_on_the_next_request(env):
+ rows = [{"id": "meta-llama/Llama-3.2-1B"}]
+ assert as_user("alice", access.filter_model_rows, rows) == rows
+ put_access(env, "alice", ["unsloth/*"])
+ assert as_user("alice", access.filter_model_rows, rows) == []
+ put_access(env, "alice", None)
+ assert as_user("alice", access.filter_model_rows, rows) == rows
+
+
+def test_a_grant_from_an_earlier_download_does_not_outrank_the_allowlist(env):
+ as_user("alice", access.record_model_grant, "meta-llama/Llama-3.2-1B")
+ assert as_user("alice", access.repo_visible, "meta-llama/Llama-3.2-1B")
+ put_access(env, "alice", ["unsloth/*"])
+ assert not as_user("alice", access.repo_visible, "meta-llama/Llama-3.2-1B")
+
+
+def test_setting_access_drops_resident_shares(env):
+ alice = storage.get_account("alice").account_id
+ access._resident_sharers["chat"] = {alice, "someone-else"}
+ try:
+ put_access(env, "alice", ["unsloth/*"])
+ assert access._resident_sharers["chat"] == {"someone-else"}
+ finally:
+ access._resident_sharers.pop("chat", None)
+
+
+def test_training_jobs_refuse_a_base_model_outside_the_allowlist(env):
+ from core.training import account_jobs as jobs
+
+ put_access(env, "alice", ["unsloth/*"])
+ as_user("alice", jobs.validate_job_paths, {"model_name": "unsloth/Qwen3-4B", "hf_token": "t"})
+ for key, model in (
+ ("model_name", "meta-llama/Llama-3.2-1B"),
+ ("model_name", "gpt2"),
+ ("base_model", "meta-llama/Llama-3.2-1B"),
+ ("base_model_id", "meta-llama/Llama-3.2-1B"),
+ ):
+ with pytest.raises(HTTPException) as refused:
+ as_user("alice", jobs.validate_job_paths, {key: model, "hf_token": "t"})
+ assert refused.value.status_code == 403
+ as_user(
+ "bob", jobs.validate_job_paths, {"model_name": "meta-llama/Llama-3.2-1B", "hf_token": "t"}
+ )
+ # A local model is named by its path, which is not a Hub fetch.
+ local = run_as(storage.get_account("alice"), storage_roots.workspace_root) / "outputs" / "run1"
+ local.mkdir(parents = True)
+ as_user("alice", jobs.validate_job_paths, {"model_name": str(local), "hf_token": "t"})
+ # A cache hint does not exempt the Hub id it names: an unusable hint falls back to a download.
+ with pytest.raises(HTTPException) as refused:
+ as_user(
+ "alice",
+ jobs.validate_job_paths,
+ {
+ "model_name": "meta-llama/Llama-3.2-1B",
+ "model_local_path": str(local),
+ "hf_token": "t",
+ },
+ )
+ assert refused.value.status_code == 403
+
+
+def test_a_loaded_model_taken_off_the_list_stops_serving_its_loader(env):
+ alice = storage.get_account("alice").account_id
+ access._resident_accounts["chat"] = (alice, frozenset({"meta-llama/Llama-3.2-1B", "label"}))
+ access._resident_sharers["chat"] = {alice}
+ try:
+ assert not as_user("alice", access.resident_hidden, "chat")
+ put_access(env, "alice", ["meta-llama/*"])
+ access._resident_sharers["chat"] = {alice}
+ assert not as_user("alice", access.resident_hidden, "chat")
+ put_access(env, "alice", ["unsloth/*"])
+ access._resident_sharers["chat"] = {alice}
+ assert as_user("alice", access.resident_hidden, "chat")
+ assert as_user("alice", access.joins_resident_runtime, "chat")
+ finally:
+ access._resident_accounts.pop("chat", None)
+ access._resident_sharers.pop("chat", None)
diff --git a/studio/frontend/src/features/settings/api/accounts.ts b/studio/frontend/src/features/settings/api/accounts.ts
index 1a18b8394d1..df12a2e05b1 100644
--- a/studio/frontend/src/features/settings/api/accounts.ts
+++ b/studio/frontend/src/features/settings/api/accounts.ts
@@ -12,6 +12,8 @@ export interface StudioAccount {
role: "owner" | "user";
is_active: boolean;
created_at: string;
+ // null = every model; set by the owner per account.
+ model_allowlist?: string[] | null;
}
export interface AccountSetupCode {
account_id: string;
@@ -89,3 +91,13 @@ export async function deleteAccount(accountId: string): Promise<void> {
await accountsRequest(accountPath(accountId), { method: "DELETE" });
await refreshAccountPolicy();
}
+export async function setAccountModelAllowlist(
+ accountId: string,
+ allowlist: string[] | null,
+): Promise<void> {
+ await accountsRequest(`${accountPath(accountId)}/model-access`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model_allowlist: allowlist }),
+ });
+}
diff --git a/studio/frontend/src/features/settings/tabs/accounts-tab.tsx b/studio/frontend/src/features/settings/tabs/accounts-tab.tsx
index 391b99b8bb6..f44518d8aeb 100644
--- a/studio/frontend/src/features/settings/tabs/accounts-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/accounts-tab.tsx
@@ -6,6 +6,7 @@ import {
Add01Icon,
Search01Icon,
Copy01Icon,
+ CubeIcon,
Delete02Icon,
Key01Icon,
MoreHorizontalIcon,
@@ -28,6 +29,7 @@ import { UserAvatar } from "@/features/profile";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { Textarea } from "@/components/ui/textarea";
import {
AlertDialog,
AlertDialogAction,
@@ -54,6 +56,7 @@ import {
fetchAccounts,
regenerateSetupCode,
setAccountActive,
+ setAccountModelAllowlist,
type AccountSetupCode,
type StudioAccount,
} from "../api/accounts";
@@ -79,6 +82,8 @@ function OwnerAccountsTab() {
const [copied, setCopied] = useState(false);
const [resetting, setResetting] = useState<StudioAccount | null>(null);
const [retiring, setRetiring] = useState<StudioAccount | null>(null);
+ const [modelAccess, setModelAccess] = useState<StudioAccount | null>(null);
+ const [allowlistText, setAllowlistText] = useState("");
const [busy, setBusy] = useState(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -221,7 +226,7 @@ function OwnerAccountsTab() {
</Button>
</div>
- {error && !confirming && !editorOpen && (
+ {error && !confirming && !editorOpen && !modelAccess && (
<div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-destructive/20 bg-destructive/5 p-3">
<p
role="alert"
@@ -299,6 +304,12 @@ function OwnerAccountsTab() {
? t("settings.accounts.owner")
: t("settings.accounts.privateAccount")}
</p>
+ {account.role !== "owner" &&
+ account.model_allowlist?.length ? (
+ <p className="text-xs text-muted-foreground">
+ {t("settings.accounts.modelAccessLimited")}
+ </p>
+ ) : null}
<p className="text-xs text-muted-foreground sm:hidden">
{createdDate(account)}
</p>
@@ -366,6 +377,23 @@ function OwnerAccountsTab() {
if (confirming) event.preventDefault();
}}
>
+ <DropdownMenuItem
+ disabled={busy}
+ onSelect={() => {
+ setError(null);
+ setAllowlistText(
+ (account.model_allowlist ?? []).join("\n"),
+ );
+ setModelAccess(account);
+ }}
+ >
+ <HugeiconsIcon
+ icon={CubeIcon}
+ className="size-4"
+ aria-hidden="true"
+ />
+ {t("settings.accounts.modelAccess")}
+ </DropdownMenuItem>
<DropdownMenuItem
disabled={busy}
onSelect={() => {
@@ -569,6 +597,100 @@ function OwnerAccountsTab() {
)}
</DialogContent>
</Dialog>
+ <Dialog
+ open={modelAccess !== null}
+ onOpenChange={(open) => {
+ if (open || busy) return;
+ setModelAccess(null);
+ setError(null);
+ }}
+ >
+ <DialogContent
+ className="sm:max-w-md max-sm:max-w-[calc(100%-2rem)]"
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ const trigger = actionTrigger.current;
+ (trigger?.isConnected && !trigger.disabled
+ ? trigger
+ : createTrigger.current
+ )?.focus({ preventScroll: true });
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle className="break-words">
+ {t("settings.accounts.modelAccessTitle", {
+ username: modelAccess?.username ?? "",
+ })}
+ </DialogTitle>
+ <DialogDescription>
+ {t("settings.accounts.modelAccessDescription")}
+ </DialogDescription>
+ </DialogHeader>
+ <form
+ className="space-y-6"
+ onSubmit={(event) => {
+ event.preventDefault();
+ const target = modelAccess;
+ if (busy || !target) return;
+ const entries = allowlistText
+ .split(/[\s,]+/)
+ .map((entry) => entry.trim())
+ .filter(Boolean);
+ void perform(async () => {
+ await setAccountModelAllowlist(
+ target.account_id,
+ entries.length ? entries : null,
+ );
+ setModelAccess(null);
+ });
+ }}
+ >
+ <div className="space-y-2">
+ <Label htmlFor="account-model-allowlist" className="text-xs">
+ {t("settings.accounts.modelAccessLabel")}
+ </Label>
+ <Textarea
+ id="account-model-allowlist"
+ value={allowlistText}
+ onChange={(event) => setAllowlistText(event.target.value)}
+ placeholder={"unsloth/Qwen3-4B-GGUF\nunsloth/*"}
+ autoComplete="off"
+ autoCapitalize="none"
+ spellCheck={false}
+ readOnly={busy}
+ rows={6}
+ fieldSizing="fixed"
+ className="font-mono text-xs md:text-xs"
+ />
+ <p className="text-xs text-muted-foreground">
+ {t("settings.accounts.modelAccessHint")}
+ </p>
+ </div>
+ {error && (
+ <p role="alert" className="break-words text-xs text-destructive">
+ {error}
+ </p>
+ )}
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="ghost"
+ disabled={busy}
+ onClick={() => {
+ setModelAccess(null);
+ setError(null);
+ }}
+ >
+ {t("settings.accounts.cancel")}
+ </Button>
+ <Button type="submit" variant="dark" disabled={busy}>
+ {busy && <Spinner label={t("common.loading")} />}
+ {t("settings.accounts.modelAccessSave")}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
<AlertDialog
open={confirming !== null}
onOpenChange={(open) => {
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 3f0ed542d06..d12517d89f1 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -813,6 +813,13 @@ export const ar = {
status: "الحالة",
loginHint: "سجّل الدخول باسم {username} مستخدمًا هذا الرمز ككلمة مرور، ثم اختر كلمة مرور جديدة.",
privateAccount: "حساب خاص",
+ modelAccess: "الوصول إلى النماذج",
+ modelAccessTitle: "الوصول إلى النماذج لـ {username}",
+ modelAccessDescription: "اختر نماذج Hugging Face التي يمكن لهذا الحساب رؤيتها وتنزيلها وتحميلها واستخدامها عبر مفاتيح API الخاصة به.",
+ modelAccessLabel: "النماذج المسموح بها",
+ modelAccessHint: "نموذج واحد في كل سطر، مثل unsloth/Qwen3-4B-GGUF، أو unsloth/* لمؤسسة كاملة. اتركه فارغًا للسماح بكل النماذج.",
+ modelAccessSave: "حفظ",
+ modelAccessLimited: "وصول محدود إلى النماذج",
empty: "لا توجد حسابات أخرى بعد",
setupCode: "رمز الإعداد",
setupFor: "رمز الإعداد لـ {username}",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index b892f7b5ab8..6719b7eb322 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -817,6 +817,13 @@ export const de = {
status: "Status",
loginHint: "Melden Sie sich als {username} mit diesem Code als Passwort an und wählen Sie dann ein neues Passwort.",
privateAccount: "Privates Konto",
+ modelAccess: "Modellzugriff",
+ modelAccessTitle: "Modellzugriff für {username}",
+ modelAccessDescription: "Lege fest, welche Hugging Face Modelle dieses Konto sehen, herunterladen, laden und über seine API-Schlüssel nutzen kann.",
+ modelAccessLabel: "Erlaubte Modelle",
+ modelAccessHint: "Ein Modell pro Zeile, zum Beispiel unsloth/Qwen3-4B-GGUF, oder unsloth/* für eine ganze Organisation. Leer lassen, um alle Modelle zu erlauben.",
+ modelAccessSave: "Speichern",
+ modelAccessLimited: "Eingeschränkter Modellzugriff",
empty: "Noch keine weiteren Konten",
setupCode: "Einrichtungscode",
setupFor: "Einrichtungscode für {username}",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 697e5fa8994..9591f991c11 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -859,6 +859,13 @@ export const en = {
status: "Status",
loginHint: "Sign in as {username} with this code as the password, then choose a new password.",
privateAccount: "Private account",
+ modelAccess: "Model access",
+ modelAccessTitle: "Model access for {username}",
+ modelAccessDescription: "Choose which Hugging Face models this account can see, download, load and use through its API keys.",
+ modelAccessLabel: "Allowed models",
+ modelAccessHint: "One model per line, for example unsloth/Qwen3-4B-GGUF, or unsloth/* for a whole organization. Leave empty to allow every model.",
+ modelAccessSave: "Save",
+ modelAccessLimited: "Limited model access",
empty: "No other accounts yet",
setupCode: "Setup code",
setupFor: "Setup code for {username}",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 2c72af79f1e..edf42039945 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -816,6 +816,13 @@ export const es = {
status: "Estado",
loginHint: "Inicia sesión como {username} con este código como contraseña y luego elige una nueva.",
privateAccount: "Cuenta privada",
+ modelAccess: "Acceso a modelos",
+ modelAccessTitle: "Acceso a modelos de {username}",
+ modelAccessDescription: "Elige qué modelos de Hugging Face puede ver, descargar, cargar y usar esta cuenta mediante sus claves de API.",
+ modelAccessLabel: "Modelos permitidos",
+ modelAccessHint: "Un modelo por línea, por ejemplo unsloth/Qwen3-4B-GGUF, o unsloth/* para toda una organización. Déjalo vacío para permitir todos los modelos.",
+ modelAccessSave: "Guardar",
+ modelAccessLimited: "Acceso a modelos limitado",
empty: "Aún no hay otras cuentas",
setupCode: "Código de configuración",
setupFor: "Código de configuración para {username}",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 4150777afcf..c07db5a6658 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -817,6 +817,13 @@ export const fr = {
status: "Statut",
loginHint: "Connectez-vous en tant que {username} avec ce code comme mot de passe, puis choisissez un nouveau mot de passe.",
privateAccount: "Compte privé",
+ modelAccess: "Accès aux modèles",
+ modelAccessTitle: "Accès aux modèles pour {username}",
+ modelAccessDescription: "Choisissez les modèles Hugging Face que ce compte peut voir, télécharger, charger et utiliser avec ses clés API.",
+ modelAccessLabel: "Modèles autorisés",
+ modelAccessHint: "Un modèle par ligne, par exemple unsloth/Qwen3-4B-GGUF, ou unsloth/* pour toute une organisation. Laissez vide pour autoriser tous les modèles.",
+ modelAccessSave: "Enregistrer",
+ modelAccessLimited: "Accès aux modèles limité",
empty: "Aucun autre compte pour l'instant",
setupCode: "Code de configuration",
setupFor: "Code de configuration pour {username}",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index 2ec7c8f0907..b86a7ffd62f 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -880,6 +880,13 @@ export const he = {
loginHint:
"התחבר בתור {username} עם קוד זה כסיסמה, ולאחר מכן בחר סיסמה חדשה.",
privateAccount: "חשבון פרטי",
+ modelAccess: "גישה למודלים",
+ modelAccessTitle: "גישה למודלים עבור {username}",
+ modelAccessDescription: "בחרו אילו מודלים של Hugging Face החשבון הזה יכול לראות, להוריד, לטעון ולהשתמש בהם דרך מפתחות ה-API שלו.",
+ modelAccessLabel: "מודלים מותרים",
+ modelAccessHint: "מודל אחד בכל שורה, למשל unsloth/Qwen3-4B-GGUF, או unsloth/* לארגון שלם. השאירו ריק כדי לאפשר את כל המודלים.",
+ modelAccessSave: "שמירה",
+ modelAccessLimited: "גישה מוגבלת למודלים",
empty: "אין עדיין חשבונות נוספים",
setupCode: "קוד הגדרה",
setupFor: "קוד הגדרה עבור {username}",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 2b7bccf10b9..a0bbbd42021 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -816,6 +816,13 @@ export const hi = {
status: "स्थिति",
loginHint: "इस कोड को पासवर्ड के रूप में इस्तेमाल करके {username} के रूप में साइन इन करें, फिर नया पासवर्ड चुनें।",
privateAccount: "निजी खाता",
+ modelAccess: "मॉडल एक्सेस",
+ modelAccessTitle: "{username} के लिए मॉडल एक्सेस",
+ modelAccessDescription: "चुनें कि यह खाता कौन से Hugging Face मॉडल देख, डाउनलोड, लोड और अपनी API कुंजियों से उपयोग कर सकता है।",
+ modelAccessLabel: "अनुमत मॉडल",
+ modelAccessHint: "हर पंक्ति में एक मॉडल, जैसे unsloth/Qwen3-4B-GGUF, या पूरे संगठन के लिए unsloth/*। सभी मॉडल की अनुमति देने के लिए खाली छोड़ें।",
+ modelAccessSave: "सहेजें",
+ modelAccessLimited: "सीमित मॉडल एक्सेस",
empty: "अभी कोई अन्य खाता नहीं",
setupCode: "सेटअप कोड",
setupFor: "{username} के लिए सेटअप कोड",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 775a56e2a70..4dd30e3294c 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -773,6 +773,13 @@ export const it = {
status: "Stato",
loginHint: "Accedi come {username} usando questo codice come password, poi scegli una nuova password.",
privateAccount: "Account privato",
+ modelAccess: "Accesso ai modelli",
+ modelAccessTitle: "Accesso ai modelli per {username}",
+ modelAccessDescription: "Scegli quali modelli Hugging Face questo account può vedere, scaricare, caricare e usare tramite le sue chiavi API.",
+ modelAccessLabel: "Modelli consentiti",
+ modelAccessHint: "Un modello per riga, ad esempio unsloth/Qwen3-4B-GGUF, oppure unsloth/* per un'intera organizzazione. Lascia vuoto per consentire tutti i modelli.",
+ modelAccessSave: "Salva",
+ modelAccessLimited: "Accesso ai modelli limitato",
empty: "Nessun altro account",
setupCode: "Codice di configurazione",
setupFor: "Codice di configurazione per {username}",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index e13e3d63e24..ee345118a7e 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -815,6 +815,13 @@ export const ja = {
status: "状態",
loginHint: "{username} としてこのコードをパスワードに使ってサインインし、新しいパスワードを設定してください。",
privateAccount: "個別アカウント",
+ modelAccess: "モデルへのアクセス",
+ modelAccessTitle: "{username} のモデルへのアクセス",
+ modelAccessDescription: "このアカウントが表示、ダウンロード、読み込み、API キーでの利用ができる Hugging Face モデルを選択します。",
+ modelAccessLabel: "許可するモデル",
+ modelAccessHint: "1 行に 1 モデルずつ入力します。例: unsloth/Qwen3-4B-GGUF、組織全体なら unsloth/*。空欄にするとすべてのモデルを許可します。",
+ modelAccessSave: "保存",
+ modelAccessLimited: "モデルへのアクセスを制限中",
empty: "ほかのアカウントはまだありません",
setupCode: "セットアップコード",
setupFor: "{username} のセットアップコード",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 09c8937c828..974837cd9b5 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -813,6 +813,13 @@ export const ko = {
status: "상태",
loginHint: "{username}(으)로 이 코드를 비밀번호 삼아 로그인한 뒤 새 비밀번호를 정하세요.",
privateAccount: "개별 계정",
+ modelAccess: "모델 접근",
+ modelAccessTitle: "{username}의 모델 접근",
+ modelAccessDescription: "이 계정이 보고, 다운로드하고, 불러오고, API 키로 사용할 수 있는 Hugging Face 모델을 선택합니다.",
+ modelAccessLabel: "허용된 모델",
+ modelAccessHint: "한 줄에 모델 하나씩 입력합니다. 예: unsloth/Qwen3-4B-GGUF, 조직 전체는 unsloth/*. 비워 두면 모든 모델을 허용합니다.",
+ modelAccessSave: "저장",
+ modelAccessLimited: "모델 접근 제한됨",
empty: "아직 다른 계정이 없습니다",
setupCode: "설정 코드",
setupFor: "{username}의 설정 코드",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 6158fd1a21b..dba47a7e755 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -815,6 +815,13 @@ export const ptBR = {
status: "Status",
loginHint: "Entre como {username} usando este código como senha e depois escolha uma nova senha.",
privateAccount: "Conta privada",
+ modelAccess: "Acesso a modelos",
+ modelAccessTitle: "Acesso a modelos de {username}",
+ modelAccessDescription: "Escolha quais modelos do Hugging Face esta conta pode ver, baixar, carregar e usar pelas chaves de API.",
+ modelAccessLabel: "Modelos permitidos",
+ modelAccessHint: "Um modelo por linha, por exemplo unsloth/Qwen3-4B-GGUF, ou unsloth/* para uma organização inteira. Deixe vazio para permitir todos os modelos.",
+ modelAccessSave: "Salvar",
+ modelAccessLimited: "Acesso a modelos limitado",
empty: "Ainda não há outras contas",
setupCode: "Código de configuração",
setupFor: "Código de configuração para {username}",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 3f115dbfd8b..a0cb37d6f29 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -815,6 +815,13 @@ export const ru = {
status: "Статус",
loginHint: "Войдите как {username}, указав этот код в качестве пароля, затем задайте новый пароль.",
privateAccount: "Отдельная учётная запись",
+ modelAccess: "Доступ к моделям",
+ modelAccessTitle: "Доступ к моделям для {username}",
+ modelAccessDescription: "Выберите, какие модели Hugging Face эта учётная запись может видеть, скачивать, загружать и использовать через свои API-ключи.",
+ modelAccessLabel: "Разрешённые модели",
+ modelAccessHint: "По одной модели в строке, например unsloth/Qwen3-4B-GGUF, или unsloth/* для всей организации. Оставьте пустым, чтобы разрешить все модели.",
+ modelAccessSave: "Сохранить",
+ modelAccessLimited: "Ограниченный доступ к моделям",
empty: "Других учётных записей пока нет",
setupCode: "Код настройки",
setupFor: "Код настройки для {username}",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index f6826f16b9d..4e52051d430 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -899,6 +899,13 @@ export const sv = {
loginHint:
"Logga in som {username} med den här koden som lösenord och välj sedan ett nytt lösenord.",
privateAccount: "Privat konto",
+ modelAccess: "Modellåtkomst",
+ modelAccessTitle: "Modellåtkomst för {username}",
+ modelAccessDescription: "Välj vilka Hugging Face-modeller det här kontot kan se, ladda ner, läsa in och använda via sina API-nycklar.",
+ modelAccessLabel: "Tillåtna modeller",
+ modelAccessHint: "En modell per rad, till exempel unsloth/Qwen3-4B-GGUF, eller unsloth/* för en hel organisation. Lämna tomt för att tillåta alla modeller.",
+ modelAccessSave: "Spara",
+ modelAccessLimited: "Begränsad modellåtkomst",
empty: "Inga andra konton ännu",
setupCode: "Konfigurationskod",
setupFor: "Konfigurationskod för {username}",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index c90e2c5c321..c14df4bce5e 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -811,6 +811,13 @@ export const zhCN = {
status: "状态",
loginHint: "以 {username} 身份用此设置码作为密码登录,然后设置新密码。",
privateAccount: "独立账户",
+ modelAccess: "模型访问权限",
+ modelAccessTitle: "{username} 的模型访问权限",
+ modelAccessDescription: "选择此账户可以查看、下载、加载以及通过其 API 密钥使用的 Hugging Face 模型。",
+ modelAccessLabel: "允许的模型",
+ modelAccessHint: "每行一个模型,例如 unsloth/Qwen3-4B-GGUF,或使用 unsloth/* 表示整个组织。留空则允许所有模型。",
+ modelAccessSave: "保存",
+ modelAccessLimited: "模型访问受限",
empty: "暂无其他账户",
setupCode: "设置码",
setupFor: "{username} 的设置码",
diff --git a/studio/frontend/tests/account-settings-ui.test.ts b/studio/frontend/tests/account-settings-ui.test.ts
index 34c486665c2..1b11065fd98 100644
--- a/studio/frontend/tests/account-settings-ui.test.ts
+++ b/studio/frontend/tests/account-settings-ui.test.ts
@@ -122,6 +122,7 @@ function tab(
"@/components/ui/button": { Button: "Button" },
"@/components/ui/input": { Input: "Input" },
"@/components/ui/label": { Label: "Label" },
+ "@/components/ui/textarea": { Textarea: "Textarea" },
"@/components/ui/alert-dialog": Object.fromEntries(
[
"AlertDialog",
@@ -181,6 +182,13 @@ function tab(
calls.push(`delete:${accountId}`);
accounts.splice(1);
},
+ setAccountModelAllowlist: async (
+ accountId: string,
+ allowlist: string[] | null,
+ ) => {
+ calls.push(`models:${accountId}:${JSON.stringify(allowlist)}`);
+ accounts[1].model_allowlist = allowlist;
+ },
},
});
const render = () => {
@@ -487,3 +495,46 @@ test("an account the API reports without a creation date shows a dash, not the e
"a real timestamp must still render",
);
});
+
+test("model access edits one account's allowlist and an empty list restores every model", async () => {
+ const view = tab();
+ let tree = await view.initialize();
+ assert.ok(!content(tree).includes(en.settings.accounts.modelAccessLimited));
+ await click(tree, en.settings.accounts.modelAccess);
+ tree = view.render();
+ assert.ok(
+ content(tree).includes(
+ translate("settings.accounts.modelAccessTitle", { username: "alice" }),
+ ),
+ );
+ const textarea = () => nodes(view.render()).find((node) => node.type === "Textarea");
+ const submit = async () => {
+ const form = nodes(view.render()).find(
+ (node) =>
+ node.type === "form" &&
+ nodes(node.props.children).some((child) => child.type === "Textarea"),
+ );
+ assert.ok(form);
+ (form.props.onSubmit as (event: unknown) => void)({ preventDefault() {} });
+ await tick();
+ await tick();
+ };
+ (textarea()!.props.onChange as (event: unknown) => void)({
+ target: { value: " unsloth/* \nGoogle/gemma-3-1b-it, " },
+ });
+ await submit();
+ tree = view.render();
+ assert.ok(content(tree).includes(en.settings.accounts.modelAccessLimited));
+ await click(tree, en.settings.accounts.modelAccess);
+ assert.equal(textarea()!.props.value, "unsloth/*\nGoogle/gemma-3-1b-it");
+ (textarea()!.props.onChange as (event: unknown) => void)({ target: { value: " " } });
+ await submit();
+ assert.deepEqual(
+ view.calls.filter((call) => call.startsWith("models:")),
+ [
+ 'models:alice-id:["unsloth/*","Google/gemma-3-1b-it"]',
+ "models:alice-id:null",
+ ],
+ );
+ assert.ok(!content(view.render()).includes(en.settings.accounts.modelAccessLimited));
+});
diff --git a/studio/frontend/tests/accounts-api.test.ts b/studio/frontend/tests/accounts-api.test.ts
index e14b4f6c3e5..ccc1bbf0df6 100644
--- a/studio/frontend/tests/accounts-api.test.ts
+++ b/studio/frontend/tests/accounts-api.test.ts
@@ -146,3 +146,18 @@ test("a rejected username reports the field error FastAPI sends as an array", as
/username: Value error, Username must contain 3 to 32 letters/,
);
});
+
+test("model access is set with PUT on the account and null clears it", async () => {
+ const c = client(() => Response.json({}));
+ await c.api.setAccountModelAllowlist("alice/id", ["unsloth/*"]);
+ await c.api.setAccountModelAllowlist("alice/id", null);
+ const put = (allowlist: string[] | null) => ({
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ model_allowlist: allowlist }),
+ });
+ assert.deepEqual(c.requests, [
+ { path: "/api/accounts/alice%2Fid/model-access", init: put(["unsloth/*"]) },
+ { path: "/api/accounts/alice%2Fid/model-access", init: put(null) },
+ ]);
+});