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: verify Hub credentials before cache-backed reads (#10264)

Sourav Rajvi6b26c24fd829
diff --git a/studio/backend/core/inference/diffusion_compat.py b/studio/backend/core/inference/diffusion_compat.py
index 9fa63c33748..302ed895b1f 100644
--- a/studio/backend/core/inference/diffusion_compat.py
+++ b/studio/backend/core/inference/diffusion_compat.py
@@ -34,6 +34,7 @@ from typing import Any, Optional
from hub.utils.hf_tokens import (
ANONYMOUS_CACHE_IDENTITY,
+ qualify_cache_identity,
HfTokenArg,
is_anonymous,
normalize_token,
@@ -84,7 +85,9 @@ def _token_fingerprint(token: HfTokenArg) -> str:
return ANONYMOUS_CACHE_IDENTITY
if not token:
return ""
- return hashlib.sha256(token.encode("utf-8", "replace")).hexdigest()[:16]
+ return qualify_cache_identity(
+ token, hashlib.sha256(token.encode("utf-8", "replace")).hexdigest()[:16]
+ )
def _file_identity(path: Optional[str]) -> Optional[tuple]:
diff --git a/studio/backend/hub/services/datasets/formatting.py b/studio/backend/hub/services/datasets/formatting.py
index 7881947b6b4..8c455691888 100644
--- a/studio/backend/hub/services/datasets/formatting.py
+++ b/studio/backend/hub/services/datasets/formatting.py
@@ -35,6 +35,7 @@ from hub.utils.dataset_cache import (
load_cached_hf_dataset as _shared_load_cached_hf_dataset,
split_label_matches as _split_label_matches,
)
+from hub.utils.dataset_cache import refuse_unauthorized_dataset_preview
from hub.utils import download_registry
from hub.utils.dataset_format import check_dataset_format, format_dataset_preview
from hub.utils.hf_errors import hf_error_status
@@ -43,8 +44,7 @@ from hub.utils.paths import (
normalize_path,
resolve_dataset_path,
)
-from hub.utils.hf_tokens import is_anonymous
-from utils.utils import anonymous_and_offline
+from hub.utils.hf_tokens import cached_read_refused
from utils.datasets.audio_decode import ensure_audio_decoding
from utils.paths.path_utils import drop_shadowed_appledouble_names
@@ -309,21 +309,34 @@ def _load_any_cached_hf_preview_slice(
):
# Both paths return real rows off disk without asking the Hub: the raw slice reads the
# snapshot, the processed one loads with local_files_only=True and drops the falsy
- # sentinel. Refuse the whole disk route here; the handler then answers 404.
- if is_anonymous(hf_token):
- return None
+ # sentinel. Neither reaches the network, so read first and gate the answer: reading our
+ # own disk is not the leak, handing it back is. Gating first probed /auth-check for a
+ # prefer-local request that had ruled the network out and then missed the cache anyway.
cached_preview = _load_cached_hf_preview_slice(request, preview_size)
- if cached_preview is not None:
- return cached_preview
- try:
- return _load_processed_hf_preview_slice(request, preview_size, hf_token)
- except Exception as exc:
- logger.debug(
- "Processed dataset cache preview failed for %s: %s",
- request.dataset_name,
- exc,
- )
+ if cached_preview is None:
+ try:
+ cached_preview = _load_processed_hf_preview_slice(request, preview_size, hf_token)
+ except Exception as exc:
+ logger.debug(
+ "Processed dataset cache preview failed for %s: %s",
+ request.dataset_name,
+ exc,
+ )
+ return None
+ if cached_preview is None:
+ return None
+ # The shared gate, not the raw check: the outer guard has already let a cached PUBLIC
+ # dataset through for the anonymous sentinel, and vetoing it again here turned that into
+ # a local-cache-miss 404 for a preview the caller was entitled to. is_cached is True
+ # because the rows are in hand by now.
+ if cached_read_refused(
+ hf_token,
+ repo_id = request.dataset_name,
+ repo_type = "dataset",
+ is_cached = lambda: True,
+ ):
return None
+ return cached_preview
def check_format_response(
@@ -363,12 +376,15 @@ def check_format_response(
if not dataset_exists and _is_local_dataset_ref(request.dataset_name):
raise HTTPException(status_code = 404, detail = _MISSING_DATASET_DETAIL)
- # Offline `datasets` answers a streaming load from its cache without authorizing,
- # and Tier 2 runs on the default prefer_local_cache=false, ahead of that guard.
- if anonymous_and_offline(hf_token) and not dataset_exists:
- raise HTTPException(
- status_code = 404,
- detail = "This request cannot be authorized without network access.",
+ # Both streaming tiers run on the default prefer_local_cache=false, ahead of the
+ # guarded cache reader below, so the gate stands in front of them.
+ if not dataset_exists:
+ refuse_unauthorized_dataset_preview(
+ hf_token,
+ request.dataset_name,
+ # A prefer-local request reads the cache or 404s below, either way without
+ # the network, so the probe would be a round trip it had ruled out.
+ offline = bool(request.prefer_local_cache),
)
if dataset_exists:
train_split = request.train_split or "train"
diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.py
index 16624318f3d..b8a1ee5a463 100644
--- a/studio/backend/hub/services/models/gguf_variants.py
+++ b/studio/backend/hub/services/models/gguf_variants.py
@@ -23,7 +23,7 @@ from hub.utils import download_manifest
from hub.utils import download_registry
from hub.utils import inventory_scan as hf_cache_scan
from hub.utils.hf_errors import hf_error_status
-from hub.utils.hf_tokens import is_anonymous
+from hub.utils.hf_tokens import cached_read_refused as hub_cached_read_refused
from hub.utils.hf_cache_state import (
incomplete_blob_hash,
iter_destructive_repo_cache_dirs,
@@ -1004,6 +1004,9 @@ class VariantsAnswer(NamedTuple):
response: GgufVariantsResponse
context_source: Optional[str]
+ # False when the caller may not read this repo's caches, for a reader that falls back
+ # to the repo id rather than ``context_source``.
+ cache_authorized: bool = True
def _default_variant_candidates(variants) -> list[str]:
@@ -1041,6 +1044,8 @@ async def get_gguf_variants_answer(
# A repo-shaped id resolving to a directory is answered by that directory alone, not the HF cache
# of the same-named repo, else a GGUF-less directory could evict the resident model.
answered_locally = [False]
+ # Read by the route before its own cache walk, which this listing does not cover.
+ cache_authorized = [True]
def _compute() -> GgufVariantsResponse:
repo_cache_dir = (
@@ -1274,7 +1279,17 @@ async def get_gguf_variants_answer(
# The HF cache answers from disk without authorizing, so a denied caller could name
# a cached private repo and read back its filenames, sizes and vision flag. A
# local_path the caller named itself is not the Hub cache and stays available.
- cache_reads_authorized = not is_anonymous(hf_token)
+ # `offline` passed in: a cache-only request must not pay a probe it will not use.
+ # The shared gate rather than the raw check, so the forced-anonymous sentinel keeps
+ # a cached PUBLIC repo instead of falling through to the network for one it was
+ # always entitled to.
+ # is_cached is True rather than a directory probe. Every narrower predicate here
+ # has to consult one of the cache accessors below, which are the reads this gate
+ # exists to withhold, and the lister has a cache path of its own that no predicate
+ # can see before it runs. The cost is one memoized probe per repo and token.
+ cache_reads_authorized = not hub_cached_read_refused(
+ hf_token, repo_id = repo_id, is_cached = lambda: True, offline = bool(offline)
+ )
def _scoped_local_response():
"""The pinned snapshot's own answer, or None when it holds nothing."""
@@ -1396,7 +1411,10 @@ async def get_gguf_variants_answer(
# so shared blobs are not double-counted, and keys are lowercased since cache casing can differ.
cached_filenames_by_snapshot: list[dict[str, int]] = []
cached_quant_bytes_by_snapshot: list[dict[str, int]] = []
- if _is_valid_repo_id(repo_id):
+ # A gated repo can list its files publicly, so reaching here is not authorization:
+ # everything below reads the local caches, and would report `downloaded`, `partial`
+ # and remaining bytes for the operator's copy to a caller the other paths refuse.
+ if _is_valid_repo_id(repo_id) and cache_reads_authorized:
# A pinned row resolves inside one directory, so nothing else counts as downloaded.
scoped_snapshots = (
[snapshot_scope]
@@ -1519,16 +1537,24 @@ async def get_gguf_variants_answer(
partial_quants: set[str] = set()
partial_quant_transports: dict[str, Optional[str]] = {}
- try:
- incomplete_hashes = download_registry.incomplete_blob_hashes(
- "model",
- repo_id,
- active_only = True,
- root = hub_cache,
- )
- except Exception as e:
- logger.warning(f"Failed to compute partial GGUF variants for {repo_id}: {e}")
- incomplete_hashes = set()
+ # The rest of this accounting reads the operator's disk too: the download registry,
+ # the snapshot markers and manifests, and the local blobs. The snapshot walk above
+ # is gated and this was not, so a caller who can still list a gated repo's PUBLIC
+ # metadata was handed `partial`, `partial_transport` and the remaining byte count
+ # for a download it cannot see. Same authorization, one variable.
+ partial_scan_variants = variants if cache_reads_authorized else ()
+ incomplete_hashes: set = set()
+ if cache_reads_authorized:
+ try:
+ incomplete_hashes = download_registry.incomplete_blob_hashes(
+ "model",
+ repo_id,
+ active_only = True,
+ root = hub_cache,
+ )
+ except Exception as e:
+ logger.warning(f"Failed to compute partial GGUF variants for {repo_id}: {e}")
+ incomplete_hashes = set()
scan_snapshot_dir = snapshot_scope or hf_cache_scan.resolve_snapshot_dir_for_scan(
"model",
repo_id,
@@ -1553,7 +1579,7 @@ async def get_gguf_variants_answer(
# Manifest + marker + main incomplete-blob check: catches variants whose download was cancelled or whose
# expected shards are missing/undersized.
- for variant in variants:
+ for variant in partial_scan_variants:
try:
requirement = requirements_by_quant.get(variant.quant.lower())
variant_hashes = requirement.main_hashes if requirement is not None else None
@@ -1586,7 +1612,7 @@ async def get_gguf_variants_answer(
)
# Same attribution as above: a pinned snapshot is not judged by a newer attempt's blobs.
if incomplete_hashes:
- for variant in variants:
+ for variant in partial_scan_variants:
requirement = requirements_by_quant.get(variant.quant.lower())
if requirement is None or not _repo_signals_apply_to(variant.quant):
continue
@@ -1608,7 +1634,11 @@ async def get_gguf_variants_answer(
),
)
- local_blobs_by_quant = _local_main_gguf_blobs_by_quant(repo_id, repo_cache_dir)
+ local_blobs_by_quant = (
+ _local_main_gguf_blobs_by_quant(repo_id, repo_cache_dir)
+ if cache_reads_authorized
+ else {}
+ )
def _variant_detail(v) -> GgufVariantDetail:
is_partial = v.quant in partial_quants
@@ -1654,10 +1684,19 @@ async def get_gguf_variants_answer(
def _compute_with_cleanables() -> VariantsAnswer:
# Returned with the answer, not read from the closure afterwards: coalesced callers share one
# computation and must all see the copy it answered from.
- return VariantsAnswer(_compute_response(), answered_from[0])
+ return VariantsAnswer(_compute_response(), answered_from[0], cache_authorized[0])
def _compute_response() -> GgufVariantsResponse:
skip = is_local_path(repo_id) or not _is_valid_repo_id(repo_id)
+ # The enrichment reads this repo's cache dir, so it takes the same authorization:
+ # else the except branch returns 200 labelled with an empty quant folder, which is
+ # the existence of a cached private repo. Remote valid ids only, and memoized.
+ if not skip and hub_cached_read_refused(
+ hf_token, repo_id = repo_id, is_cached = lambda: True, offline = bool(offline)
+ ):
+ skip = True
+ # Carried out: the route's context-length fallback walks these same caches.
+ cache_authorized[0] = False
try:
response = _compute()
except Exception:
diff --git a/studio/backend/hub/utils/dataset_cache.py b/studio/backend/hub/utils/dataset_cache.py
index 80d2374c7c1..1aaac1a36be 100644
--- a/studio/backend/hub/utils/dataset_cache.py
+++ b/studio/backend/hub/utils/dataset_cache.py
@@ -599,3 +599,58 @@ def cached_dataset_candidates(
)
return sorted(files, key = score)
+
+
+def dataset_cache_can_answer(repo_id: str) -> bool:
+ """True if some cached copy of *repo_id* could satisfy a preview without the Hub.
+
+ Both caches count. ``datasets`` answers a streaming load from its own PREPARED cache,
+ which is where the measured leak was, while the hub snapshot backs the file-level
+ readers.
+ """
+ if not repo_id:
+ return False
+ try:
+ if latest_processed_dataset_cache_path(repo_id) is not None:
+ return True
+ return latest_cached_dataset_snapshot(repo_id) is not None
+ except Exception:
+ # Never let the guard's own failure open the path it guards.
+ return True
+
+
+def refuse_unauthorized_dataset_preview(
+ hf_token,
+ dataset_name: str,
+ *,
+ offline: bool = False,
+) -> None:
+ """Raise 404 when a cached dataset preview would be served to a caller who cannot reach it.
+
+ ``datasets`` satisfies a load from its own prepared cache without consulting the
+ credential, so an explicit token that cannot reach the repo is a leak online as well as
+ off. Both preview routes spelled this out separately, and not equivalently, under
+ comments claiming they mirrored each other; stating it once removes that trap.
+
+ The anonymous sentinel was refused only under a declared offline env, which left the
+ case that matters: a Hub merely unreachable is not a Hub declared absent, and the load
+ then falls back to the prepared cache all the same. It is now refused whenever the repo
+ is not public, which ``cached_read_refused`` answers for every reader alike.
+
+ ``offline`` is the caller's own cache-only intent, forwarded so a prefer-local request
+ does not put its credential and repo id on the wire for a branch that will not use them.
+ """
+ from fastapi import HTTPException
+ from hub.utils.hf_tokens import cached_read_refused
+
+ if cached_read_refused(
+ hf_token,
+ repo_id = dataset_name,
+ repo_type = "dataset",
+ is_cached = lambda: dataset_cache_can_answer(dataset_name),
+ offline = offline,
+ ):
+ raise HTTPException(
+ status_code = 404,
+ detail = "Dataset preview is not available without Hub authorization.",
+ )
diff --git a/studio/backend/hub/utils/hf_errors.py b/studio/backend/hub/utils/hf_errors.py
index b2569758c6f..69b4215ffa2 100644
--- a/studio/backend/hub/utils/hf_errors.py
+++ b/studio/backend/hub/utils/hf_errors.py
@@ -9,7 +9,7 @@ from typing import Optional
def hf_error_status(exc: Exception) -> Optional[int]:
- # Client-side HF errors should surface as 4xx, not a generic 500.
+ # Client-side HF errors should surface as the status they mean, not a generic 500.
name = type(exc).__name__
if name in (
"RepositoryNotFoundError",
@@ -17,6 +17,11 @@ def hf_error_status(exc: Exception) -> Optional[int]:
"EntryNotFoundError",
):
return 404
+ # "I could not ask" is not "it is not there": these two say the Hub was unreachable or
+ # offline was forced, which is transient and retryable. Answering 404 told callers the
+ # repository was missing, and openai_auto_download caches that verdict for ten minutes.
+ if name in ("LocalEntryNotFoundError", "OfflineModeIsEnabled"):
+ return 503
if name == "GatedRepoError":
return 403
if name == "HFValidationError":
diff --git a/studio/backend/hub/utils/hf_tokens.py b/studio/backend/hub/utils/hf_tokens.py
index 97299adc393..d9fda750abd 100644
--- a/studio/backend/hub/utils/hf_tokens.py
+++ b/studio/backend/hub/utils/hf_tokens.py
@@ -5,6 +5,9 @@
from __future__ import annotations
+import hashlib
+import threading
+import time
from typing import Literal, MutableMapping, Optional, Union
HfTokenArg = Optional[Union[str, Literal[False]]]
@@ -12,13 +15,25 @@ HfTokenArg = Optional[Union[str, Literal[False]]]
# Anonymous-sentinel cache identity, kept apart from ``None``'s: a slot filled under the
# ambient token must not be served to an API key denied it. Not hex, so no digest collides.
ANONYMOUS_CACHE_IDENTITY = "anon"
+# Prefixes a UI session's cache identity. Kept short because it lands in dict keys.
+UI_CACHE_IDENTITY_PREFIX = "ui:"
+
+
+class AmbientAuthorizedToken(str):
+ """A UI session's own saved token: entitled to ambient, so never behind the probe.
+
+ Only ``allow_ambient_token`` tells it from an API key's token. ``str`` subclass so every
+ consumer sees the string it is; sending your own credential must not buy less than none.
+ """
+
+ __slots__ = ()
def hf_token_arg(hf_token: Optional[str], *, allow_ambient_token: bool) -> HfTokenArg:
"""Return the explicit token, or choose ambient versus anonymous access."""
token = (hf_token or "").strip()
if token:
- return token
+ return AmbientAuthorizedToken(token) if allow_ambient_token else token
return None if allow_ambient_token else False
@@ -34,6 +49,9 @@ _HF_TOKEN_ENV_KEYS = (
"HF_OIDC_RESOURCE",
)
+# auth_check takes no timeout, nor the session under it (0.x: none; 1.30: Timeout(None)).
+_REPO_ACCESS_PROBE_TIMEOUT_S = 10.0
+
def apply_token_to_child_env(env: MutableMapping[str, str], hf_token: HfTokenArg) -> None:
"""Grant a spawned probe exactly its caller's credential.
@@ -60,9 +78,354 @@ def normalize_token(hf_token: HfTokenArg) -> HfTokenArg:
"""Trim an explicit token without laundering ``False`` into ``None`` (= ambient)."""
if is_anonymous(hf_token):
return False
- return (hf_token or "").strip() or None
+ trimmed = (hf_token or "").strip() or None
+ # str.strip returns a plain str, which would demote a UI session to an API key.
+ if trimmed is not None and isinstance(hf_token, AmbientAuthorizedToken):
+ return AmbientAuthorizedToken(trimmed)
+ return trimmed
def is_anonymous(hf_token: HfTokenArg) -> bool:
"""Named because a bare ``is False`` invites a ``not hf_token`` "simplification"."""
return hf_token is False
+
+
+def qualify_cache_identity(hf_token: HfTokenArg, digest: str) -> str:
+ """Tag a token digest with the caller class that produced it.
+
+ Same token value, different authorization: a UI session is entitled to ambient, an
+ sk-unsloth API key is not. On the bare digest they collide, so a cache hands one the
+ other's verdict and a coalescer merges their scans into whichever arrived first.
+ """
+ return (
+ f"{UI_CACHE_IDENTITY_PREFIX}{digest}"
+ if isinstance(hf_token, AmbientAuthorizedToken)
+ else digest
+ )
+
+
+# Both signs: a revoked token must not keep reading, a flapping Hub must not be re-dialled.
+_REPO_ACCESS_TTL_S = 60.0
+# Says nothing about the credential. MUST exceed the probe timeout or every caller re-stalls.
+_REPO_ACCESS_UNREACHABLE_TTL_S = 30.0
+_REPO_ACCESS_CACHE_MAX = 1024
+_repo_access_cache: dict[tuple[str, str, str], tuple[float, bool]] = {}
+_repo_access_lock = threading.Lock()
+# One probe per key: the probe runs outside _repo_access_lock, so a cold key would
+# otherwise open a connection per caller.
+_repo_access_inflight: dict[tuple[str, str, str], threading.Lock] = {}
+
+
+class _ProbeTimedOut(Exception):
+ """Raised when /auth-check could not be asked at all, rather than answering."""
+
+
+# By name, so neither client is imported. A refusal or dead proxy is "could not ask" too.
+_UNREACHABLE_EXC_NAMES = frozenset(
+ {
+ "Timeout",
+ "ReadTimeout",
+ "ConnectTimeout",
+ "ConnectError",
+ "ConnectionError",
+ "ProxyError",
+ "NetworkError",
+ "TransportError",
+ "NameResolutionError",
+ }
+)
+_UNREACHABLE_PACKAGES = frozenset({"requests", "httpx", "urllib3"})
+
+
+def _is_probe_timeout(exc: BaseException) -> bool:
+ """Could not ask, as opposed to asked and told no. Named for its original narrow case."""
+ for cls in type(exc).__mro__:
+ name = cls.__name__
+ # Builtin ConnectionError is a real transport failure; looser names need a package.
+ if name in {"Timeout", "ReadTimeout", "ConnectTimeout", "ConnectionError"}:
+ return True
+ module = getattr(cls, "__module__", "") or ""
+ # Top-level package, not "httpx.": that prefix matched none of httpx's own.
+ if module.split(".", 1)[0] in _UNREACHABLE_PACKAGES and (
+ "Timeout" in name or name in _UNREACHABLE_EXC_NAMES
+ ):
+ return True
+ return False
+
+
+def reset_repo_access_cache() -> None:
+ """Drop memoized Hub access answers. Tests only."""
+ with _repo_access_lock:
+ _repo_access_cache.clear()
+ _repo_access_inflight.clear()
+
+
+def cache_reads_authorized(
+ hf_token: HfTokenArg,
+ *,
+ repo_id: str,
+ repo_type: str = "model",
+ offline: bool = False,
+) -> bool:
+ """Whether this caller may read the host Hub disk cache for *repo_id*.
+
+ ``is_anonymous`` authenticates the caller CLASS, not the credential, so any token-shaped
+ string leaves the sentinel and takes the disk fast paths. ``repo_info`` cannot replace
+ the probe: gated public metadata still returns for an invalid token.
+
+ ``True`` does not mean the token is valid. /auth-check answers "is this repo reachable",
+ which a public repo answers 200 for any string; it discriminates on private and gated
+ repos, which is where the cached reads are.
+
+ Offline, an explicit token is denied without a memoized probe (fail closed) while ambient
+ ``None`` still reads. ``offline`` is the CALLER's own flag: without it a cache-only
+ request put its token on the wire and could stall for the probe timeout first.
+ """
+ if is_anonymous(hf_token):
+ return False
+ # Deny by default: `not isinstance(str)` gave the ambient answer to True, 1, b"...".
+ if hf_token is None:
+ return True
+ if not isinstance(hf_token, str):
+ return False
+ if not hf_token:
+ return True
+ if isinstance(hf_token, AmbientAuthorizedToken):
+ # Same caller class reads the cache tokenless from the None branch above.
+ return True
+ repo = (repo_id or "").strip()
+ if not repo:
+ return False
+ if _is_local_path(repo):
+ # Unvalidated in the URL, so probing puts the caller's path on the wire with their
+ # bearer token, for an answer that can only be no.
+ return False
+ return _explicit_token_reaches_repo(repo, hf_token, repo_type, offline = offline)
+
+
+def public_cache_read_authorized(
+ *,
+ repo_id: str,
+ repo_type: str = "model",
+ offline: bool = False,
+) -> bool:
+ """Whether serving *repo_id* from the cache to a caller with NO credential leaks anything.
+
+ The sentinel can never authorize itself, which is right for a private repo and wrong for
+ a public one. An unauthenticated /auth-check is exactly that difference. Fail closed when
+ it cannot be asked.
+ """
+ repo = (repo_id or "").strip()
+ if not repo or _is_local_path(repo):
+ return False
+ return _explicit_token_reaches_repo(repo, None, repo_type, offline = offline)
+
+
+def cached_read_refused(
+ hf_token: HfTokenArg,
+ *,
+ repo_id: str,
+ is_cached,
+ repo_type: str = "model",
+ offline: bool = False,
+) -> bool:
+ """Refuse a read only where the operator's disk could answer it AND this caller may not.
+
+ An uncached repo has nothing to leak: refusing it protects nothing and costs a legitimate
+ caller its answer whenever the probe is merely unavailable rather than negative (a mirror
+ without the undocumented /auth-check, one transient failure). ``is_cached`` is asked FIRST
+ so nothing on disk means no probe, and must fail closed or the guard's own failure opens
+ the path it guards. Each reader passes its own predicate: a file at a revision, a dataset
+ in either cache, a repo dir.
+
+ "May not read it" is not "cannot authorize itself", which is where the sentinel sits: a
+ public repo is one it was always entitled to read. Asked here so every reader shares the
+ rule; the dataset preview used to be the only one asking.
+ """
+ if not is_cached():
+ return False
+ if cache_reads_authorized(hf_token, repo_id = repo_id, repo_type = repo_type, offline = offline):
+ return False
+ return not (
+ is_anonymous(hf_token)
+ and public_cache_read_authorized(repo_id = repo_id, repo_type = repo_type, offline = offline)
+ )
+
+
+def _is_local_path(repo_id: str) -> bool:
+ """Lazy: hub.utils.paths pulls in the path stack, this module is imported beneath it."""
+ try:
+ from hub.utils.paths import is_local_path
+ return is_local_path(repo_id)
+ except Exception:
+ return False
+
+
+def _hub_offline() -> bool:
+ try:
+ from utils.utils import hf_env_offline
+ return hf_env_offline()
+ except Exception:
+ # Fail open on the offline question only; authorization still needs a live probe.
+ import logging
+ logging.getLogger(__name__).debug(
+ "Could not determine Hub offline state; assuming online", exc_info = True
+ )
+ return False
+
+
+def _cached_repo_access(key: tuple[str, str, str], now: float) -> Optional[bool]:
+ cached = _repo_access_cache.get(key)
+ if cached is not None and cached[0] > now:
+ return cached[1]
+ return None
+
+
+def _explicit_token_reaches_repo(
+ repo_id: str,
+ token: Optional[str],
+ repo_type: str,
+ offline: bool = False,
+) -> bool:
+ # None asks the public question, under its own key: a public repo answers 200 for every
+ # token, so a shared key would let any string claim that verdict.
+ key = (
+ repo_id.casefold(),
+ repo_type,
+ hashlib.sha256(token.encode()).hexdigest()[:16] if token else "anonymous",
+ )
+ cached = _cached_repo_access(key, time.monotonic())
+ if cached is not None:
+ return cached
+ if offline or _hub_offline():
+ return False
+
+ with _inflight_lock(key):
+ cached = _cached_repo_access(key, time.monotonic())
+ if cached is not None:
+ return cached
+ started = time.monotonic()
+ try:
+ allowed = _probe_repo_access(repo_id, token, repo_type)
+ timed_out = False
+ except _ProbeTimedOut:
+ allowed = False
+ timed_out = True
+ # AFTER the probe: `start + TTL` memoizes an expired entry when the Hub stalls.
+ finished = time.monotonic()
+ if not timed_out:
+ timed_out = not allowed and (finished - started) >= _REPO_ACCESS_PROBE_TIMEOUT_S
+ expiry = finished + (_REPO_ACCESS_UNREACHABLE_TTL_S if timed_out else _REPO_ACCESS_TTL_S)
+ with _repo_access_lock:
+ if len(_repo_access_cache) >= _REPO_ACCESS_CACHE_MAX:
+ _evict_repo_access_locked()
+ _repo_access_cache[key] = (expiry, allowed)
+ return allowed
+
+
+def _evict_repo_access_locked() -> None:
+ """Caller holds ``_repo_access_lock``. Drop what has expired before anything live."""
+ now = time.monotonic()
+ for expired in [k for k, (deadline, _) in _repo_access_cache.items() if deadline <= now]:
+ _repo_access_cache.pop(expired, None)
+ if len(_repo_access_cache) >= _REPO_ACCESS_CACHE_MAX:
+ _repo_access_cache.clear()
+
+
+def _inflight_lock(key: tuple[str, str, str]) -> threading.Lock:
+ with _repo_access_lock:
+ lock = _repo_access_inflight.get(key)
+ if lock is None:
+ if len(_repo_access_inflight) >= _REPO_ACCESS_CACHE_MAX:
+ _repo_access_inflight.clear()
+ lock = threading.Lock()
+ _repo_access_inflight[key] = lock
+ return lock
+
+
+def _probe_endpoint() -> str:
+ """The endpoint the rest of the backend means, not the raw env value.
+
+ ``HfApi().endpoint`` returns ``HF_ENDPOINT`` verbatim, so a scheme-less mirror builds a
+ URL both clients reject and every probe on that machine is denied. ``hf_endpoint_url``
+ is where the backend already normalises it; falls back since this module sits beneath.
+ """
+ try:
+ from utils.utils import hf_endpoint_url
+ return hf_endpoint_url().rstrip("/")
+ except Exception:
+ from huggingface_hub import HfApi
+ return HfApi().endpoint
+
+
+def _same_probe_target(answered: str, asked: str) -> bool:
+ """Whether two URLs address the same endpoint, up to the spellings a client may change.
+
+ Case in the host and a default port carry no meaning; the path, query and everything
+ else do, so a redirect to ``?next=login`` on the same path is still a different target.
+ """
+ from urllib.parse import urlsplit
+
+ def _parts(url: str):
+ parsed = urlsplit(url)
+ scheme = (parsed.scheme or "").lower()
+ port = parsed.port or {"http": 80, "https": 443}.get(scheme)
+ return (
+ scheme,
+ (parsed.hostname or "").lower(),
+ port,
+ parsed.path.rstrip("/"),
+ parsed.query,
+ )
+
+ try:
+ return _parts(answered) == _parts(asked)
+ except ValueError:
+ # An unparseable final URL is not proof that the right repo answered.
+ return False
+
+
+def _probe_repo_access(repo_id: str, token: Optional[str], repo_type: str) -> bool:
+ try:
+ from huggingface_hub import constants
+ from huggingface_hub.utils import build_hf_headers, get_session, hf_raise_for_status
+
+ if repo_type not in constants.REPO_TYPES:
+ return False
+ # A raw "?" or "#" ends the path early at /api/{type}s/{id}, which answers 200 with
+ # public metadata for a gated repo.
+ from urllib.parse import quote
+
+ # quote keeps "/", so ".." survives and dot-segment removal probes a different repo
+ # than the one memoized.
+ if any(segment in {".", ".."} for segment in repo_id.split("/")):
+ return False
+ path = f"{_probe_endpoint()}/api/{repo_type}s/{quote(repo_id, safe = '/')}/auth-check"
+ response = get_session().get(
+ path,
+ # False, not None: None falls back to the ambient login, asking the public
+ # question with the operator's own credential.
+ headers = build_hf_headers(token = token if token else False),
+ timeout = _REPO_ACCESS_PROBE_TIMEOUT_S,
+ )
+ hf_raise_for_status(response)
+ # hf_raise_for_status passes 3xx: without this a bare 307 reads as authorized.
+ if 300 <= getattr(response, "status_code", 0) < 400:
+ return False
+ # And get_session DOES follow them (httpx.Client(follow_redirects=True)), so the
+ # check above never fires: a redirect to a login page returns an approving 200 for
+ # somewhere else. Only the repo we asked about may answer for it.
+ if getattr(response, "history", None):
+ return False
+ # Belt and braces for a client that does not record history. Compared on parts, not
+ # as strings: httpx canonicalises response.url (lower-cases the host, drops an
+ # explicit :443) while the configured HF_ENDPOINT keeps its spelling, so a raw
+ # comparison denied every mirror written as HF-MIRROR.example or with the port.
+ final_url = getattr(response, "url", None)
+ if final_url is not None and not _same_probe_target(str(final_url), path):
+ return False
+ return True
+ except Exception as exc:
+ if _is_probe_timeout(exc):
+ raise _ProbeTimedOut from exc
+ return False
diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.py
index 4eb6ab87239..c9c2a204ce2 100644
--- a/studio/backend/hub/utils/inventory_scan.py
+++ b/studio/backend/hub/utils/inventory_scan.py
@@ -36,7 +36,12 @@ from hub.utils.gguf import (
is_mmproj_filename,
is_mtp_drafter_path,
)
-from hub.utils.hf_tokens import ANONYMOUS_CACHE_IDENTITY, HfTokenArg, is_anonymous
+from hub.utils.hf_tokens import (
+ ANONYMOUS_CACHE_IDENTITY,
+ HfTokenArg,
+ is_anonymous,
+ qualify_cache_identity,
+)
from hub.utils.state_dir import RepoType
from hub.utils.hf_cache_state import (
@@ -453,7 +458,9 @@ def token_fingerprint(hf_token: HfTokenArg) -> str:
return ANONYMOUS_CACHE_IDENTITY
if not hf_token:
return ""
- return hashlib.sha256(hf_token.encode()).hexdigest()[:16]
+ # Same token value, different cache authorization: on the bare digest either caller
+ # reads back the other's verdict.
+ return qualify_cache_identity(hf_token, hashlib.sha256(hf_token.encode()).hexdigest()[:16])
def resolve_hf_cache_realpath(repo_dir: Path) -> Optional[str]:
diff --git a/studio/backend/picker/service.py b/studio/backend/picker/service.py
index 079710fd89d..9a901e7b620 100644
--- a/studio/backend/picker/service.py
+++ b/studio/backend/picker/service.py
@@ -10,7 +10,7 @@ import re
from pathlib import Path
from typing import Optional
-from hub.utils.hf_tokens import is_anonymous
+from hub.utils.hf_tokens import cache_reads_authorized, cached_read_refused
from hub.services.models.folder_browser import (
_build_browse_allowlist,
_is_path_inside_allowlist,
@@ -367,19 +367,25 @@ def read_default_chat_template(
# The walk returns a private repo's raw template without asking the Hub, so a denied
# caller goes to the Hub and is refused there. A UI session keeps the cache.
- if not is_anonymous(hf_token):
- try:
- # Resolve within each cached revision, newest first. A revision's sidecar
- # supersedes its own embedded GGUF copy, but must not override a newer
- # revision, so precedence stays per-snapshot rather than global.
- for snapshot in iter_snapshots_preferring_whole(resolved, gguf_variant):
- template = _chat_template_from_dir(snapshot, gguf_variant)
- if template:
- return template
- except Exception as exc:
- logger.debug("Could not read cached chat template for %s: %s", resolved, exc)
+ # Walk first, authorize the answer: the walk is local, and with nothing cached there is
+ # no disk-backed answer to protect, so probing would spend up to the probe timeout to
+ # decide a question that no longer has a subject. Same order as the per-file gate below.
+ cached_template = None
+ try:
+ # Resolve within each cached revision, newest first. A revision's sidecar
+ # supersedes its own embedded GGUF copy, but must not override a newer
+ # revision, so precedence stays per-snapshot rather than global.
+ for snapshot in iter_snapshots_preferring_whole(resolved, gguf_variant):
+ cached_template = _chat_template_from_dir(snapshot, gguf_variant)
+ if cached_template:
+ break
+ except Exception as exc:
+ logger.debug("Could not read cached chat template for %s: %s", resolved, exc)
+ cached_template = None
+ if cached_template and cache_reads_authorized(hf_token, repo_id = resolved):
+ return cached_template
- if is_anonymous(hf_token) and hf_env_offline():
+ if hf_env_offline() and not cache_reads_authorized(hf_token, repo_id = resolved):
# Offline, hf_hub_download serves the cached copy without checking the credential,
# so the fallback would hand back the template the walk just refused. The route
# forces offline whenever the Hub looks unreachable.
@@ -390,12 +396,44 @@ def read_default_chat_template(
_api = HfApi(token = hf_token)
+ def _this_file_is_cached(rel: str) -> bool:
+ """THIS file at this revision, not merely a directory for the repo.
+
+ What the download could serve from disk is the one candidate template, so a
+ snapshot holding only weights can answer nothing and refusing it costs an
+ authorized caller a template the Hub would have given it. Fails closed.
+ """
+ try:
+ from huggingface_hub import try_to_load_from_cache
+
+ # The same cache the download below names: without it this asks the library
+ # default while the read it guards happens in the operator's chosen root, so
+ # a template living only there reported a miss and opened the gate.
+ return isinstance(
+ try_to_load_from_cache(
+ repo_id = resolved, filename = rel, cache_dir = active_hf_hub_cache()
+ ),
+ str,
+ )
+ except Exception:
+ return True
+
def _remote_worth_downloading(rel: str) -> bool:
+ # hf_hub_download returns the cached pointer for ANY failed head call, a 403 as
+ # much as an unreachable Hub, before it re-raises. So a successful metadata
+ # lookup is no more proof than the offline gate was: a gated repo can publish
+ # file metadata publicly. Asked once, ahead of both.
+ if cached_read_refused(
+ hf_token,
+ repo_id = resolved,
+ is_cached = lambda: _this_file_is_cached(rel),
+ ):
+ return False
# Reuse the size lookup to skip absent or oversized files.
try:
infos = _api.get_paths_info(resolved, [rel], repo_type = "model", token = hf_token)
except Exception:
- # An inconclusive lookup preserves the existing download behavior.
+ # Nothing cached to serve: let the Hub enforce its own access.
return True
matched = [info for info in infos if getattr(info, "path", None) == rel]
if not matched:
diff --git a/studio/backend/routes/data_recipe/seed.py b/studio/backend/routes/data_recipe/seed.py
index fd8c8287425..4bf54127213 100644
--- a/studio/backend/routes/data_recipe/seed.py
+++ b/studio/backend/routes/data_recipe/seed.py
@@ -20,8 +20,8 @@ from fastapi import APIRouter, Depends, HTTPException, UploadFile, File as FastA
from auth.authentication import allow_ambient_hf_token
from core.data_recipe.jsonable import to_preview_jsonable
-from hub.utils.hf_tokens import HfTokenArg, hf_token_arg, is_anonymous
-from utils.utils import hf_env_offline
+from hub.utils.dataset_cache import refuse_unauthorized_dataset_preview
+from hub.utils.hf_tokens import HfTokenArg, hf_token_arg
from loggers import get_logger
from utils.paths import ensure_dir, seed_uploads_root, unstructured_uploads_root
from utils.utils import log_and_http_error
@@ -329,6 +329,16 @@ def inspect_seed_dataset(
detail = "dataset_name must be a Hugging Face repo id like org/repo",
)
+ split = _normalize_optional_text(payload.split) or DEFAULT_SPLIT
+ subset = _normalize_optional_text(payload.subset)
+ # From the caller: a hardcoded False takes the ambient fallback from UI sessions too.
+ token = hf_token_arg(
+ _normalize_optional_text(payload.hf_token),
+ allow_ambient_token = allow_ambient_token,
+ )
+ preview_size = int(payload.preview_size)
+ refuse_unauthorized_dataset_preview(token, dataset_name)
+
try:
from datasets import load_dataset
except ImportError as exc:
@@ -340,24 +350,6 @@ def inspect_seed_dataset(
log = logger,
) from exc
- split = _normalize_optional_text(payload.split) or DEFAULT_SPLIT
- subset = _normalize_optional_text(payload.subset)
- # From the caller, like every other Hub-reaching route: a hardcoded False would take
- # the ambient fallback from UI sessions too.
- token = hf_token_arg(
- _normalize_optional_text(payload.hf_token),
- allow_ambient_token = allow_ambient_token,
- )
- preview_size = int(payload.preview_size)
- if is_anonymous(token) and hf_env_offline():
- # Offline, `datasets` satisfies a streaming load from its own cache and the sentinel
- # never reaches an authorization check, so a previously cached private dataset would
- # come back as rows. The check-format path refuses the same way.
- raise HTTPException(
- status_code = 404,
- detail = "Dataset preview is not available without Hub authorization.",
- )
-
preview_rows: list[dict[str, Any]] = []
data_files = _list_hf_data_files(dataset_name = dataset_name, token = token)
diff --git a/studio/backend/routes/datasets.py b/studio/backend/routes/datasets.py
index c643c4f4c78..127d4beb906 100644
--- a/studio/backend/routes/datasets.py
+++ b/studio/backend/routes/datasets.py
@@ -13,13 +13,13 @@ backend_path = Path(__file__).parent.parent.parent
if str(backend_path) not in sys.path:
sys.path.insert(0, str(backend_path))
-from auth.authentication import get_current_subject
+from auth.authentication import allow_ambient_hf_token, get_current_subject
from hub.dependencies import get_request_hf_token
from hub.schemas.datasets import (
AiAssistMappingRequest as HubAiAssistMappingRequest,
CheckFormatRequest as HubCheckFormatRequest,
)
-from hub.utils.hf_tokens import HfTokenArg
+from hub.utils.hf_tokens import HfTokenArg, hf_token_arg
from hub.services.datasets import downloads, formatting, local
from models.datasets import (
AiAssistMappingRequest,
@@ -74,12 +74,20 @@ async def get_dataset_download_progress(
def check_format(
request: CheckFormatRequest,
hf_token: HfTokenArg = Depends(get_request_hf_token),
+ allow_ambient_token: bool = Depends(allow_ambient_hf_token),
current_subject: str = Depends(get_current_subject),
) -> CheckFormatResponse:
hub_request = HubCheckFormatRequest.model_validate(request.model_dump(exclude = {"hf_token"}))
+ # Same credential as the header on a legacy route, so classified the same way: raw, it
+ # makes a UI session look like an API key and costs it its own cached dataset offline.
+ body_token = (
+ hf_token_arg(request.hf_token, allow_ambient_token = allow_ambient_token)
+ if request.hf_token
+ else None
+ )
return formatting.check_format_response(
hub_request,
- request.hf_token or hf_token,
+ body_token if body_token else hf_token,
allow_unlabeled_tier1_fallback = True,
)
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 4c6f4725e3c..ecf536fac5c 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -119,8 +119,8 @@ def _is_valid_repo_id(repo_id: str) -> bool:
def _normalize_hf_token(hf_token) -> Optional[str]:
if not isinstance(hf_token, str):
return None
- token = hf_token.strip()
- return token or None
+ # Not str.strip(): that returns a plain str, dropping the UI-session marker.
+ return normalize_token(hf_token)
def _safe_is_dir(path) -> bool:
@@ -194,7 +194,14 @@ if str(backend_path) not in sys.path:
from auth.authentication import allow_ambient_hf_token, get_current_subject
from hub.dependencies import get_hf_token, get_request_hf_token
-from hub.utils.hf_tokens import HfTokenArg, hf_token_arg, is_anonymous
+from hub.utils.hf_tokens import (
+ HfTokenArg,
+ cache_reads_authorized,
+ cached_read_refused,
+ hf_token_arg,
+ is_anonymous,
+ normalize_token,
+)
from utils.utils import anonymous_and_offline
@@ -212,9 +219,15 @@ def _resolve_hub_token(header_token: HfTokenArg, query_token: Optional[str]) ->
returning ``header_token`` itself would return whatever a caller that bypassed
FastAPI's injection left in the parameter -- an unresolved ``Depends`` object.
"""
- explicit = _normalize_hf_token(header_token) or _normalize_hf_token(query_token)
- if explicit:
- return explicit
+ header_explicit = _normalize_hf_token(header_token)
+ if header_explicit:
+ return header_explicit
+ query_explicit = _normalize_hf_token(query_token)
+ if query_explicit:
+ # normalize_token carries a marker through but cannot create one, and a query value
+ # never had it. Rebuild from the caller class the header states, so a UI session is
+ # not denied its own cache for using the legacy parameter.
+ return hf_token_arg(query_explicit, allow_ambient_token = not is_anonymous(header_token))
return False if is_anonymous(header_token) else None
@@ -2404,7 +2417,7 @@ def _model_config_inspection_target(
return model_name
# The cached snapshot answers from disk without consulting the token, so a caller
# denied the ambient credential is sent to the Hub, which refuses a private repo.
- if is_anonymous(hf_token):
+ if not cache_reads_authorized(hf_token, repo_id = canonical_model_repo_id(model_name)):
return model_name
from hub.utils.hf_cache_state import (
latest_snapshot_from_cache_path,
@@ -2480,7 +2493,10 @@ async def get_model_config(
# The bare repo id above only helps if the probes then go over the wire:
# local_files_only resolves config.json out of the cache, unauthorized.
- probe_local_only = prefer_local_cache and not is_anonymous(hf_token)
+ # A local folder is not the Hub cache, so it keeps the local-only probe.
+ probe_local_only = prefer_local_cache and (
+ is_local_path(model_name) or cache_reads_authorized(hf_token, repo_id = model_name)
+ )
is_vision = is_vision_model(
inspection_target,
hf_token = hf_token,
@@ -2620,6 +2636,48 @@ async def scan_model_remote_code(
local_model = is_local_path(model_name)
if not local_model:
model_name = resolve_cached_repo_id_case(model_name)
+
+ # The scanner's hf_hub_download resolves a cached repo's configs without consulting
+ # the credential, so has_remote_code can be answered off the operator's disk; gating
+ # only the prefer_local path below left the scan running anyway. Fail closed HERE
+ # rather than in _repo_in_any_hf_cache, whose other caller needs its False.
+ def _repo_maybe_cached(repo: str) -> bool:
+ """Whether the scan could be answered off disk for this repo.
+
+ The scanner's own inputs, not the repo directory and not config.json alone:
+ auto_map is declared in any of REMOTE_CODE_CONFIG_FILES, and every download the
+ scanner makes passes cache_dir = active_hf_hub_cache(), so asking the library
+ default about one filename both missed four of the five and looked in the wrong
+ root. A snapshot holding only weights still answers nothing. Fails closed.
+ """
+ try:
+ if not _repo_in_any_hf_cache(repo):
+ return False
+ except Exception:
+ return True
+ try:
+ from huggingface_hub import try_to_load_from_cache
+ from utils.hf_cache_settings import active_hf_hub_cache
+ from utils.security.remote_code_scan import remote_code_config_paths
+
+ cache_dir = active_hf_hub_cache()
+ return any(
+ isinstance(
+ try_to_load_from_cache(repo_id = repo, filename = name, cache_dir = cache_dir),
+ str,
+ )
+ for name in remote_code_config_paths()
+ )
+ except Exception:
+ return True
+
+ if not local_model and cached_read_refused(
+ hf_token, repo_id = model_name, is_cached = lambda: _repo_maybe_cached(model_name)
+ ):
+ raise HTTPException(
+ status_code = 404,
+ detail = "This model is not available to an unauthorized caller.",
+ )
scan_target = model_name
exact_snapshot_path = (
model_snapshot_path.strip()
@@ -2653,7 +2711,11 @@ async def scan_model_remote_code(
normalize_path(exact_snapshot_path),
hf_token,
)
- elif prefer_local_cache is True and not local_model and not is_anonymous(hf_token):
+ elif (
+ prefer_local_cache is True
+ and not local_model
+ and cache_reads_authorized(hf_token, repo_id = model_name)
+ ):
# Same guard as the exact_snapshot branch: resolving to a cached snapshot
# hands the scanner a private repo's Python, unauthorized.
from core.training.training import _resolve_model_snapshot
@@ -2696,6 +2758,16 @@ async def scan_model_remote_code(
dict.fromkeys((*_subdirs, *security_load_subdirs(model_name, hf_token)))
)
_target, _subdirs = load_scan_target(_requested_target, _subdirs)
+ # A base, native-audio dependency or auto_map repo is a DIFFERENT repo from the
+ # one the gate above authorized, scanned with the same token. Refused, not
+ # dropped: a silently unscanned base would under-report has_remote_code.
+ if not is_local_path(_target) and cached_read_refused(
+ hf_token, repo_id = _target, is_cached = lambda t = _target: _repo_maybe_cached(t)
+ ):
+ raise HTTPException(
+ status_code = 404,
+ detail = "This model is not available to an unauthorized caller.",
+ )
if _target not in consent_load_subdirs:
security_targets.append(_target)
consent_load_subdirs[_target] = ()
@@ -2736,6 +2808,18 @@ async def scan_model_remote_code(
hf_token,
load_subdirs = consent_load_subdirs[_target],
):
+ # Discovered from the primary's config AFTER the loop above authorized the
+ # targets it knew, and the preflight below downloads and scans it with the
+ # same token, so its cached Python files reach the response as source
+ # snippets. Refused rather than skipped, for the same reason as the base:
+ # an unscanned auto_map repo under-reports has_remote_code.
+ if not is_local_path(_ext) and cached_read_refused(
+ hf_token, repo_id = _ext, is_cached = lambda e = _ext: _repo_maybe_cached(e)
+ ):
+ raise HTTPException(
+ status_code = 404,
+ detail = "This model is not available to an unauthorized caller.",
+ )
external_refs.append(_ext)
_mark_scan_created(_ext)
decision = preflight_remote_code_consent_for_targets(
@@ -4581,7 +4665,12 @@ async def get_gguf_variants(
or hub_gguf_variants.pinned_snapshot_for_request(repo_id, local_path)
or repo_id
)
- local = is_local_path(context_model)
+ # The first two are directories the listing authorized; the bare repo id is not, and
+ # reading it walks every local cache, which is the one local fact the service could
+ # not suppress from inside.
+ if not answer.cache_authorized and not is_local_path(context_model):
+ context_model = None
+ local = context_model is not None and is_local_path(context_model)
return GgufVariantsResponse(
repo_id = response.repo_id,
@@ -4606,7 +4695,11 @@ async def get_gguf_variants(
],
has_vision = response.has_vision,
default_variant = response.default_variant,
- context_length = await _read_native_context_length_bounded(context_model, local),
+ context_length = (
+ await _read_native_context_length_bounded(context_model, local)
+ if context_model is not None
+ else None
+ ),
resolved_locally = bool(getattr(response, "resolved_locally", False)),
loadable_variants = getattr(response, "loadable_variants", None),
loadable = getattr(response, "loadable", None),
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index ceabaa7fe9e..ea906605bd0 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -22,11 +22,13 @@ from pydantic import (
)
from auth.authentication import (
+ allow_ambient_hf_token,
authenticated_via_api_key,
get_current_credential,
get_current_subject,
)
from auth.storage import rotate_preview_link_secret
+from hub.utils.hf_tokens import cache_reads_authorized, cached_read_refused, hf_token_arg
from routes.provider_credentials import current_credential_write, require_ui_session
@@ -2458,7 +2460,34 @@ def _resolve_embedding_model_plan(
The PUT must not persist a client assertion that the GET never validated,
so both routes use this exact resolver.
+
+ The cache lookups below read the operator's disk without consulting the credential,
+ so a caller who cannot reach the repo must not learn its cached state from them. A
+ local path the caller named itself is not the Hub cache and stays available.
+
+ Per REPO, not per request: a lookup often answers with a stored override, a
+ ``sentence-transformers/`` alias or a derived ``-GGUF`` conversion rather than
+ ``resolved``, and /auth-check answers 200 for any string on a public base.
"""
+
+ def _authorized(repo: Optional[str]) -> bool:
+ """The repo a cache lookup actually matched, asked about in its own right.
+
+ Through the shared gate, so the forced-anonymous sentinel keeps a cached PUBLIC
+ embedder instead of being told to download one it already has: the raw check
+ refuses that caller whatever the repo is, which the template, dataset and GGUF
+ paths all stopped doing. is_cached is True because the lookup that produced this
+ repo already found it on disk.
+ """
+ if not repo:
+ return False
+ return not cached_read_refused(token, repo_id = repo, is_cached = lambda: True)
+
+ # No pre-gate on ``resolved``: every cache lookup below is authorized against the repo it
+ # actually matched, so gating the lookup as well probed the Hub on every resolve, including
+ # the local and sentence-transformers paths that never consult it, and could spend half the
+ # resolver's deadline before a miss. It was also the wrong question, per the note above.
+
# Resolve for the model being selected.
on_llama = _llama_backend_active(resolved)
backend: Literal["llama", "sentence-transformers"] = (
@@ -2474,7 +2503,14 @@ def _resolve_embedding_model_plan(
)
# The alias-aware predicate alone, which already pairs the ST file family with the loadable check per candidate;
# the repo the cache hit came from is what the PUT verifies and scans.
+ # Looked up BEFORE any authorization: for a slashless alias the snapshot is filed
+ # under sentence-transformers/, so gating on the literal name's verdict skipped the
+ # lookup entirely and a public alias that is fully cached came back as a download.
+ # Learning WHICH repo answered is not the leak; handing its state back is, and that
+ # repo is the one authorized here.
cached_source = _cached_st_source(resolved)
+ if cached_source is not None and not _authorized(cached_source[0]):
+ cached_source = None
cached = cached_source is not None
source = None if cached else _st_weight_source(resolved, token)
if not cached and source is None:
@@ -2540,6 +2576,8 @@ def _resolve_embedding_model_plan(
# Match the loader's online fast path exactly: only the preferred repo and
# only the configured variant can suppress the download offer.
cached_repo = _cached_embedding_gguf(candidates[:1], require_variant = True)
+ if cached_repo and not _authorized(cached_repo):
+ cached_repo = None
if cached_repo:
return EmbeddingModelResolveResponse(
embedding_model = resolved,
@@ -2552,6 +2590,8 @@ def _resolve_embedding_model_plan(
# The loader's offline fallback accepts any complete cached quant from
# any candidate only after its bounded online listing fails.
cached_repo = _cached_embedding_gguf(candidates, require_variant = False)
+ if cached_repo and not _authorized(cached_repo):
+ cached_repo = None
if cached_repo:
return EmbeddingModelResolveResponse(
embedding_model = resolved,
@@ -2566,6 +2606,13 @@ def _resolve_embedding_model_plan(
if _sentence_transformers_fallback_allowed(resolved)
else None
)
+ # The GGUF branches above are gated and this one was not. The plan answers with the
+ # repo the snapshot is FILED under, which for a slashless alias is not the name the
+ # caller typed, and the response then reports it cached: that is how a denied caller
+ # discovers the operator's private weights and force-saves them as the embedder.
+ # Reading our own disk to find the repo is fine; naming it back is what is gated.
+ if st_plan is not None and not _authorized(st_plan[0]):
+ st_plan = None
if st_plan is None:
return EmbeddingModelResolveResponse(
embedding_model = resolved,
@@ -2579,12 +2626,15 @@ def _resolve_embedding_model_plan(
backend = "sentence-transformers",
download_repo = st_repo,
# Same alias-aware predicate, asked about the repo the plan named
- # rather than the alias the user typed.
+ # rather than the alias the user typed, which the gate above authorized.
cached = _cached_snapshot_has_st_weights(st_repo),
size_bytes = _hf_snapshot_size(st_repo, token),
)
repo, files = plan
- if _cached_embedding_gguf_files(repo, files):
+ # A gated repo can publish its filenames, so a plan coming back is not authorization to
+ # report the operator's copy of it. The repo the plan names need not be the one the
+ # caller asked about, so it is authorized in its own right like every other candidate.
+ if _authorized(repo) and _cached_embedding_gguf_files(repo, files):
return EmbeddingModelResolveResponse(
embedding_model = resolved,
backend = backend,
@@ -2606,6 +2656,7 @@ def resolve_embedding_model(
model: str,
# Header, not a query param: keeps a gated-repo token out of URLs and logs.
hf_token: Optional[str] = Header(None, alias = "X-Unsloth-HF-Token"),
+ allow_ambient_token: bool = Depends(allow_ambient_hf_token),
current_subject: str = Depends(get_current_subject),
) -> EmbeddingModelResolveResponse:
"""What saving ``model`` would need fetched, and whether it is already here.
@@ -2623,13 +2674,17 @@ def resolve_embedding_model(
event = "settings.resolve_embedding_model_failed",
log = logger,
) from exc
- token = (hf_token or "").strip() or None
+ # Classified, not just trimmed: a bare strip makes a UI session look like an API key and
+ # costs it its own cached marker. The GET must refuse exactly what the PUT refuses.
+ token = hf_token_arg(hf_token, allow_ambient_token = allow_ambient_token)
return _resolve_embedding_model_plan(resolved, token)
@router.put("/embedding-model", response_model = EmbeddingModelResponse)
def update_embedding_model(
- payload: EmbeddingModelPayload, current_subject: str = Depends(get_current_subject)
+ payload: EmbeddingModelPayload,
+ allow_ambient_token: bool = Depends(allow_ambient_hf_token),
+ current_subject: str = Depends(get_current_subject),
) -> EmbeddingModelResponse:
"""Set the RAG embedding model. Unless ``force`` is set, the repo is verified
to be an embedding model via HF metadata; an unverifiable model (wrong type,
@@ -2649,7 +2704,7 @@ def update_embedding_model(
event = "settings.update_embedding_model_failed",
log = logger,
) from exc
- hf_token = (payload.hf_token or "").strip() or None
+ hf_token = hf_token_arg(payload.hf_token, allow_ambient_token = allow_ambient_token)
from utils.utils import hf_env_offline
# Offline, both the Hub malware scan and the is-embedding check are unreachable and degrade
@@ -2745,7 +2800,12 @@ def update_embedding_model(
# Require a genuinely loadable cache (config + weights), not just a resolved refs/main,
# so a metadata-only partial cache still gets the forceable 409.
- offline_cached = local_only_load and hf_cache_snapshot_is_loadable(verify_target)
+ # A cached private repo accepted here becomes this deployment's embedder.
+ offline_cached = (
+ local_only_load
+ and cache_reads_authorized(hf_token, repo_id = verify_target)
+ and hf_cache_snapshot_is_loadable(verify_target)
+ )
if not offline_cached:
raise HTTPException(
status_code = 409,
diff --git a/studio/backend/tests/test_capability_detection.py b/studio/backend/tests/test_capability_detection.py
index c8e1b63468e..e3f2fc0d28a 100644
--- a/studio/backend/tests/test_capability_detection.py
+++ b/studio/backend/tests/test_capability_detection.py
@@ -56,8 +56,9 @@ def _write_model_dir(
# load_model_config default
class TestLoadModelConfigDefault:
+ @patch("utils.models.model_config.cache_reads_authorized", return_value = True)
@patch("transformers.AutoConfig.from_pretrained")
- def test_default_off_with_token(self, fp):
+ def test_default_off_with_token(self, fp, _cache_auth):
load_model_config("org/m", token = "hf_x")
assert fp.call_args.kwargs["trust_remote_code"] is False
@@ -75,8 +76,9 @@ class TestLoadModelConfigDefault:
load_model_config("org/m", use_auth = True)
assert fp.call_args.kwargs["trust_remote_code"] is False
+ @patch("utils.models.model_config.cache_reads_authorized", return_value = True)
@patch("transformers.AutoConfig.from_pretrained")
- def test_explicit_true_forwarded(self, fp):
+ def test_explicit_true_forwarded(self, fp, _cache_auth):
load_model_config("org/m", token = "t", trust_remote_code = True)
assert fp.call_args.kwargs["trust_remote_code"] is True
diff --git a/studio/backend/tests/test_embedding_model_resolve.py b/studio/backend/tests/test_embedding_model_resolve.py
index ba504a4670d..5bd8ba23f0a 100644
--- a/studio/backend/tests/test_embedding_model_resolve.py
+++ b/studio/backend/tests/test_embedding_model_resolve.py
@@ -36,6 +36,8 @@ def client(monkeypatch):
app = FastAPI()
app.include_router(settings.router)
app.dependency_overrides[settings.get_current_subject] = lambda: "admin"
+ # Classified by caller now, so the app must be able to say which caller this is.
+ app.dependency_overrides[settings.allow_ambient_hf_token] = lambda: True
return TestClient(app, raise_server_exceptions = False)
diff --git a/studio/backend/tests/test_embedding_model_security_gate.py b/studio/backend/tests/test_embedding_model_security_gate.py
index 1bb5ca09c36..c0b057b724b 100644
--- a/studio/backend/tests/test_embedding_model_security_gate.py
+++ b/studio/backend/tests/test_embedding_model_security_gate.py
@@ -93,6 +93,8 @@ def client(monkeypatch):
app = FastAPI()
app.include_router(settings.router)
app.dependency_overrides[settings.get_current_subject] = lambda: "admin"
+ # Classified by caller now, so the app must be able to say which caller this is.
+ app.dependency_overrides[settings.allow_ambient_hf_token] = lambda: True
return TestClient(app, raise_server_exceptions = False), saved
@@ -274,6 +276,7 @@ def test_llama_backend_skips_the_st_pickle_scan(monkeypatch):
app = FastAPI()
app.include_router(settings.router)
app.dependency_overrides[settings.get_current_subject] = lambda: "admin"
+ app.dependency_overrides[settings.allow_ambient_hf_token] = lambda: True
c = TestClient(app, raise_server_exceptions = False)
r = c.put(
"/embedding-model",
@@ -339,6 +342,7 @@ def test_runtime_llama_fallback_skips_the_st_pickle_scan(monkeypatch):
app = FastAPI()
app.include_router(settings.router)
app.dependency_overrides[settings.get_current_subject] = lambda: "admin"
+ app.dependency_overrides[settings.allow_ambient_hf_token] = lambda: True
c = TestClient(app, raise_server_exceptions = False)
r = c.put(
"/embedding-model",
@@ -429,6 +433,7 @@ def test_settings_scan_scopes_module_subdirs(monkeypatch):
app = FastAPI()
app.include_router(settings.router)
app.dependency_overrides[settings.get_current_subject] = lambda: "admin"
+ app.dependency_overrides[settings.allow_ambient_hf_token] = lambda: True
c = TestClient(app, raise_server_exceptions = False)
r = c.put(
"/embedding-model", json = {"embedding_model": "acme/embed-with-module-dir", "force": True}
@@ -710,3 +715,34 @@ def test_a_llama_download_repo_is_not_used_as_the_scan_target(client, monkeypatc
assert r.status_code == 200
# The llama path does not scan the ST repo at all, so nothing was scanned.
assert "scanned" not in seen
+
+
+def test_offline_cached_acceptance_still_asks_who_is_asking(client, monkeypatch):
+ """The offline branch above accepts a cached transformers-native embedder that HF
+ metadata cannot verify. What makes that safe is the authorization check beside the
+ loadable check: without it, an API key that cannot reach the repo learns the operator
+ has it cached and gets it persisted as this deployment's embedder."""
+ from hub.utils import hf_tokens
+
+ c, saved = client
+ monkeypatch.setitem(sys.modules, "utils.security", _security_stub(blocked = False))
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ import utils.models as _models
+ import utils.utils as _uu
+
+ monkeypatch.setattr(_models, "is_embedding_model", lambda *a, **k: False)
+ monkeypatch.setattr(_uu, "hf_cache_snapshot_is_loadable", lambda name: True)
+ # An API key, so its token is classified as explicit and must reach the repo to read it.
+ c.app.dependency_overrides[settings.allow_ambient_hf_token] = lambda: False
+ hf_tokens.reset_repo_access_cache()
+ monkeypatch.setattr(hf_tokens, "_hub_offline", lambda: False)
+ monkeypatch.setattr(hf_tokens, "_probe_repo_access", lambda *_a, **_k: False)
+
+ r = c.put(
+ "/embedding-model",
+ json = {"embedding_model": "acme/private-embedder", "hf_token": "hf_dummy"},
+ )
+
+ assert r.status_code == 409
+ assert saved.get("model") != "acme/private-embedder"
+ hf_tokens.reset_repo_access_cache()
diff --git a/studio/backend/tests/test_hub_token_caller_identity.py b/studio/backend/tests/test_hub_token_caller_identity.py
index 22f12be7966..38a33baef1b 100644
--- a/studio/backend/tests/test_hub_token_caller_identity.py
+++ b/studio/backend/tests/test_hub_token_caller_identity.py
@@ -3,51 +3,202 @@
"""The forced-anonymous sentinel is a credential of its own, not the absence of one.
+Planting a cached repo is deliberate: a denial gate only fires where the disk could answer,
+so "cached" is the premise every refusal test rests on. The uncached direction has its own
+tests, asserting the request reaches the Hub instead.
+
``hf_token_arg`` returns three values where everything downstream expects ``Optional[str]``,
-so ``False`` breaks four ways: a truthiness test reaches for the ambient token anyway, an
-identity test hits ``.encode()`` on a bool, a shared cache fingerprint crosses the boundary,
-and a child env inherits what it was never granted. ``is`` throughout: ``False == 0 == ""``.
+so ``False`` breaks four ways: truthiness reaches for the ambient token, identity hits
+``.encode()`` on a bool, a shared fingerprint crosses the boundary, and a child env inherits
+what it was never granted. ``is`` throughout, since ``False == 0 == ""``.
"""
+import asyncio
import hashlib
+import inspect
import os
+import threading
+import time
from types import SimpleNamespace
from pathlib import Path
from typing import Optional
+import fastapi
import pytest
-from fastapi import FastAPI
+import requests
+import transformers
+from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
+import utils.models.model_config as model_config_module
from auth.authentication import authenticated_via_api_key, get_current_subject
from core.inference import diffusion_compat
from hub.dependencies import get_request_hf_token
+from hub.schemas.datasets import CheckFormatRequest
+from hub.services.datasets import formatting
+from hub.services.models import gguf_variants
+from hub.utils import dataset_cache, hf_tokens
+from hub.utils.gguf import GgufVariantInfo
+from picker import service as picker_service
from hub.utils.hf_tokens import (
ANONYMOUS_CACHE_IDENTITY,
apply_token_to_child_env,
+ cache_reads_authorized,
hf_token_arg,
is_anonymous,
normalize_token,
+ reset_repo_access_cache,
)
from hub.utils.inventory_scan import token_fingerprint
from routes import models as models_routes
+from routes import settings as settings_routes
+from routes.data_recipe import seed as seed_routes
+from utils import transformers_version
from utils.models.model_config import _token_fingerprint as capability_fingerprint
from utils.transformers_version import _token_cache_key
-from routes.data_recipe import seed as seed_routes
-import asyncio
-import fastapi
-import inspect
-import utils.models.model_config as model_config_module
-def _models_client(via_api_key: bool) -> TestClient:
[email protected](autouse = True)
+def _isolate_repo_access_cache():
+ """``_repo_access_cache`` is a process global, so one test's memoized verdict would
+ otherwise decide the next one's. Every test in this file used to reset it by hand."""
+ reset_repo_access_cache()
+ yield
+ reset_repo_access_cache()
+
+
+def _hub_reachable(monkeypatch, *, offline: bool = False) -> None:
+ """Pin the offline question, which is the other half of nearly every probe setup."""
+ monkeypatch.setattr(hf_tokens, "_hub_offline", lambda: offline)
+
+
+def _counting_probe(
+ monkeypatch,
+ verdict = True,
+ *,
+ offline: Optional[bool] = None,
+ delay: float = 0.0,
+) -> dict:
+ """Stub the access probe and return a live counter, so a test can assert both the
+ verdict it produced and how many round trips it cost.
+
+ ``offline`` pins the other half of nearly every probe setup. Left at ``None`` the real
+ ``_hub_offline`` stands, which is what the tests that never stubbed it expect.
+ """
+ if offline is not None:
+ _hub_reachable(monkeypatch, offline = offline)
+ calls = {"n": 0}
+
+ def _probe(*_a, **_k):
+ calls["n"] += 1
+ if delay:
+ time.sleep(delay)
+ if isinstance(verdict, BaseException):
+ raise verdict
+ return verdict
+
+ monkeypatch.setattr(hf_tokens, "_probe_repo_access", _probe)
+ return calls
+
+
+def _router_client(
+ router,
+ prefix: str,
+ *,
+ via_api_key: bool,
+ subject: str = "alice",
+) -> TestClient:
app = FastAPI()
- app.include_router(models_routes.router, prefix = "/api/models")
- app.dependency_overrides[get_current_subject] = lambda: "alice"
+ app.include_router(router, prefix = prefix)
+ app.dependency_overrides[get_current_subject] = lambda: subject
app.dependency_overrides[authenticated_via_api_key] = lambda: via_api_key
return TestClient(app, raise_server_exceptions = False)
+def _models_client(via_api_key: bool) -> TestClient:
+ return _router_client(models_routes.router, "/api/models", via_api_key = via_api_key)
+
+
+def _st_resolver(monkeypatch, **overrides) -> None:
+ """The sentence-transformers preamble of ``_resolve_embedding_model_plan``.
+
+ Named overrides replace a default rather than adding to it, so a test still says which
+ stub it cares about and the rest stays out of the way.
+ """
+ stubs = {
+ "_llama_backend_active": lambda _m: False,
+ "_local_sentence_transformer_is_present": lambda _m: False,
+ "_st_weight_source": lambda *_a, **_k: None,
+ }
+ for name, value in {**stubs, **overrides}.items():
+ monkeypatch.setattr(settings_routes, name, value)
+
+
+def _gguf_resolver(monkeypatch, **overrides) -> None:
+ """The llama-server preamble: six stubs is what it takes to reach the candidate lookup."""
+ stubs = {
+ "_llama_backend_active": lambda _m: True,
+ "_llama_runtime_available": lambda: True,
+ "_resolves_as_local_gguf": lambda _m: False,
+ "_local_gguf_backend_error": lambda _m: None,
+ "_embedding_gguf_candidates": lambda m: [m],
+ "_cached_embedding_gguf": lambda *_a, **_k: None,
+ }
+ for name, value in {**stubs, **overrides}.items():
+ monkeypatch.setattr(settings_routes, name, value)
+
+
+def _picker_env(monkeypatch, *, offline: bool = False, no_snapshots: bool = False) -> None:
+ """The template walk reads its own offline flag and canonicalizes the repo id first.
+
+ ``no_snapshots`` empties the snapshot walk, which is how a test says the fallback is
+ the only route left to the template.
+ """
+ monkeypatch.setattr(picker_service, "hf_env_offline", lambda: offline)
+ monkeypatch.setattr(picker_service, "resolve_cached_repo_id_case", lambda name: name)
+ if no_snapshots:
+ monkeypatch.setattr(
+ picker_service, "iter_snapshots_preferring_whole", lambda *_a, **_k: iter(())
+ )
+
+
+def _scan_refused(model_name: str, hf_token = "hf_dummy") -> int:
+ """Drive the remote-code scan as an api key and return the status it refused with."""
+ with pytest.raises(fastapi.HTTPException) as excinfo:
+ asyncio.run(
+ models_routes.scan_model_remote_code(
+ model_name = model_name,
+ hf_token = hf_token,
+ allow_ambient_token = False,
+ current_subject = "alice",
+ )
+ )
+ return excinfo.value.status_code
+
+
+def _one_cached_quant(monkeypatch, tmp_path, *, complete: bool = True):
+ """A repo publishing one Q4_K_M, present in a single snapshot.
+
+ The premise the GGUF listing tests rest on: a denial only means something where the disk
+ could have answered. ``complete`` drops the bytes for the partial-state case.
+ """
+ snapshot = tmp_path / "snap"
+ snapshot.mkdir()
+ if complete:
+ (snapshot / "Model-Q4_K_M.gguf").write_bytes(b"x" * 256)
+ monkeypatch.setattr(
+ gguf_variants,
+ "list_gguf_variants",
+ lambda repo_id, hf_token = None: (
+ [GgufVariantInfo(filename = "Model-Q4_K_M.gguf", quant = "Q4_K_M", size_bytes = 256)],
+ False,
+ [],
+ ),
+ )
+ monkeypatch.setattr(gguf_variants, "iter_hf_cache_snapshots", lambda *_a, **_k: [snapshot])
+ return snapshot
+
+
@pytest.mark.parametrize(
"hf_token, allow_ambient, expected",
[
@@ -71,6 +222,461 @@ def test_only_the_sentinel_reads_as_anonymous():
assert is_anonymous(absent) is False
+def test_cache_reads_require_a_credential_that_reaches_the_repo(monkeypatch):
+ """A token-shaped string is not authorization to read the host cache."""
+ probes = _counting_probe(monkeypatch, False, offline = False)
+
+ assert cache_reads_authorized(False, repo_id = "org/private") is False
+ assert cache_reads_authorized(None, repo_id = "org/private") is True
+ assert cache_reads_authorized("hf_dummy", repo_id = "org/private") is False
+ assert probes["n"] == 1, "ambient and anonymous must not pay a Hub round trip"
+ assert cache_reads_authorized("hf_dummy", repo_id = "org/private") is False
+ assert probes["n"] == 1, "the negative answer was not memoized"
+
+
+def test_a_ui_session_that_saved_a_token_still_reads_its_own_cache(monkeypatch):
+ """The UI attaches the operator's saved token on most Hub routes, so an ordinary
+ single-user session is an EXPLICIT-token caller on exactly the routes this gates.
+
+ Measured: with a token saved and the Hub unreachable, that session lost the GGUF variant
+ list, the chat template and the dataset format check on repos already in its own cache.
+ With no token saved it kept all three.
+ """
+ probes = _counting_probe(monkeypatch, None, offline = True)
+
+ ui = hf_token_arg(" hf_saved ", allow_ambient_token = True)
+ api_key = hf_token_arg(" hf_saved ", allow_ambient_token = False)
+
+ assert ui == "hf_saved" and api_key == "hf_saved", "same value, different caller class"
+ assert cache_reads_authorized(ui, repo_id = "org/private") is True
+ assert cache_reads_authorized(api_key, repo_id = "org/private") is False
+ assert probes["n"] == 0, "the UI session must not pay a round trip for its own token"
+
+
+def test_the_ambient_marker_is_a_string_everywhere_it_is_used_as_a_value(monkeypatch):
+ """Value transparent, entitlement not. Every consumer wanting the token VALUE sees a
+ plain token; cache IDENTITY is the deliberate exception, pinned by the caller-class
+ test below (this test once asserted the opposite, which was the bug)."""
+ ui = hf_token_arg("hf_saved", allow_ambient_token = True)
+
+ assert isinstance(ui, str)
+ assert ui == "hf_saved"
+ assert hash(ui) == hash("hf_saved")
+ assert ui.encode() == b"hf_saved"
+ env: dict = {}
+ apply_token_to_child_env(env, ui)
+ assert env["HF_TOKEN"] == "hf_saved"
+ assert type(env["HF_TOKEN"]) is str or isinstance(env["HF_TOKEN"], str)
+ # The Hub still receives the real credential, marker or not.
+ assert capability_fingerprint(ui).endswith(capability_fingerprint("hf_saved"))
+
+
+def test_trimming_does_not_demote_a_ui_session_to_an_api_key():
+ """str.strip returns a plain str, which would put the operator back behind the probe."""
+ ui = hf_token_arg(" hf_saved ", allow_ambient_token = True)
+
+ assert isinstance(normalize_token(ui), hf_tokens.AmbientAuthorizedToken)
+ assert normalize_token(ui) == "hf_saved"
+ assert not isinstance(
+ normalize_token(hf_token_arg("hf_saved", allow_ambient_token = False)),
+ hf_tokens.AmbientAuthorizedToken,
+ )
+ assert normalize_token(False) is False
+ assert normalize_token(None) is None
+
+
+ "cached, authorized, refused",
+ [
+ (True, False, True),
+ (True, True, False),
+ (False, False, False),
+ (False, True, False),
+ ],
+)
+def test_the_shared_gate_refuses_only_where_a_cache_could_answer(
+ monkeypatch, cached, authorized, refused
+):
+ _counting_probe(monkeypatch, authorized, offline = False)
+ assert (
+ hf_tokens.cached_read_refused(
+ "hf_explicit", repo_id = "acme/private", is_cached = lambda: cached
+ )
+ is refused
+ )
+
+
+def test_the_shared_gate_asks_the_cache_before_the_hub(monkeypatch):
+ """``is_cached`` is local and the probe is a round trip, so nothing on disk must mean no
+ probe at all."""
+ probes = _counting_probe(monkeypatch, False, offline = False)
+
+ assert (
+ hf_tokens.cached_read_refused(
+ "hf_explicit", repo_id = "acme/private", is_cached = lambda: False
+ )
+ is False
+ )
+ assert probes["n"] == 0, "an uncached repo paid a Hub round trip"
+
+
+def test_a_verified_token_may_read_the_host_cache(monkeypatch):
+ _counting_probe(monkeypatch, True, offline = False)
+
+ assert cache_reads_authorized("hf_real", repo_id = "org/private") is True
+
+
+def test_offline_explicit_token_is_denied_without_a_prior_probe(monkeypatch):
+ """Fail closed: no Hub round trip means no cache for an unverified credential."""
+ _hub_reachable(monkeypatch, offline = True)
+
+ assert cache_reads_authorized("hf_real", repo_id = "org/private") is False
+
+
+def test_offline_explicit_token_may_use_a_recent_online_probe(monkeypatch):
+ probes = _counting_probe(monkeypatch, True, offline = False)
+
+ assert cache_reads_authorized("hf_real", repo_id = "org/private") is True
+ assert probes["n"] == 1
+
+ _hub_reachable(monkeypatch, offline = True)
+ assert cache_reads_authorized("hf_real", repo_id = "org/private") is True
+ assert probes["n"] == 1, "offline must reuse the memo, not re-probe"
+
+
+def _gated_hub_error(message = "gated"):
+ """GatedRepoError without hub's response-bearing constructor (0.x vs 1.x)."""
+ from huggingface_hub.errors import GatedRepoError
+
+ class _Gated(GatedRepoError):
+ def __init__(self, text):
+ Exception.__init__(self, text)
+
+ return _Gated(message)
+
+
+class _FakeHubSession:
+ def __init__(self, handler):
+ self._handler = handler
+ self.calls: list[dict] = []
+
+ def get(
+ self,
+ url,
+ *,
+ headers = None,
+ timeout = None,
+ **kwargs,
+ ):
+ self.calls.append({"url": url, "headers": headers, "timeout": timeout, **kwargs})
+ return self._handler(url, headers = headers, timeout = timeout, **kwargs)
+
+
+def _patch_auth_check_get(monkeypatch, handler):
+ session = _FakeHubSession(handler)
+ monkeypatch.setattr("huggingface_hub.utils.get_session", lambda: session)
+ return session
+
+
+def _ok_auth_check_response():
+ return SimpleNamespace(status_code = 200, raise_for_status = lambda: None)
+
+
+def test_a_redirect_is_not_an_authorization(monkeypatch):
+ """hf_raise_for_status passes 3xx through, and a client factory installed without
+ follow_redirects would hand a bare 307 back. Legacy repo aliases do redirect."""
+ _hub_reachable(monkeypatch)
+ _patch_auth_check_get(
+ monkeypatch,
+ lambda *_a, **_k: SimpleNamespace(status_code = 307, raise_for_status = lambda: None),
+ )
+
+ assert cache_reads_authorized("hf_dummy", repo_id = "org/repo") is False
+
+
+def test_a_hanging_auth_check_probe_times_out(monkeypatch):
+ """A stalled /auth-check must fail closed without leaving probe workers behind."""
+ _hub_reachable(monkeypatch)
+ monkeypatch.setattr("hub.utils.hf_tokens._REPO_ACCESS_PROBE_TIMEOUT_S", 0.2)
+
+ def _hang(
+ url,
+ *,
+ headers = None,
+ timeout = None,
+ **_k,
+ ):
+ assert timeout == 0.2
+ raise requests.exceptions.Timeout("auth-check timed out")
+
+ session = _patch_auth_check_get(monkeypatch, _hang)
+ started = time.monotonic()
+ assert cache_reads_authorized("hf_real", repo_id = "org/private") is False
+ assert time.monotonic() - started < 5
+ assert "/auth-check" in session.calls[0]["url"]
+ assert not [t for t in threading.enumerate() if t.name == "hf-repo-auth-check"]
+
+
+ "exc_factory, is_timeout",
+ [
+ # A "httpx." prefix matched none of these: httpx's exceptions live in ``httpx``.
+ (lambda: __import__("httpx").TimeoutException("stalled"), True),
+ (lambda: __import__("httpx").ConnectTimeout("stalled"), True),
+ (lambda: __import__("httpx").PoolTimeout("stalled"), True),
+ # A refusal, a DNS failure and a dead proxy are "could not ask" as much as a stall.
+ (lambda: __import__("requests").exceptions.ConnectionError("refused"), True),
+ (lambda: __import__("requests").exceptions.ProxyError("dead proxy"), True),
+ (lambda: __import__("httpx").ConnectError("refused"), True),
+ (lambda: ConnectionRefusedError("refused"), True),
+ # The other half: a real refusal keeps the full TTL, or a revoked token re-probes.
+ (lambda: _gated_hub_error(), False),
+ (lambda: OSError("refused"), False),
+ (lambda: ValueError("bad token"), False),
+ ],
+)
+def test_could_not_ask_is_told_apart_from_told_no(exc_factory, is_timeout):
+ """The unreachable TTL is short and the denial TTL is long, so misclassifying either way
+ is a real outage: a stall that denies for a minute, or a revocation re-probed forever."""
+ pytest.importorskip("httpx")
+ assert hf_tokens._is_probe_timeout(exc_factory()) is is_timeout
+
+
+ "endpoint, repo_id, expected_url",
+ [
+ # A raw "?" ends the path at /api/models/{id}, the repo_info weakness this avoids.
+ (None, "org/gated?ignored=", "/api/models/org/gated%3Fignored%3D/auth-check"),
+ (None, "unsloth/Llama-3.2-1B", "/api/models/unsloth/Llama-3.2-1B/auth-check"),
+ # HfApi().endpoint returns HF_ENDPOINT verbatim, so a scheme-less mirror built a URL
+ # both clients reject, denying every explicit-token cache read on that machine.
+ (
+ "hf-mirror.example",
+ "org/repo",
+ "https://hf-mirror.example/api/models/org/repo/auth-check",
+ ),
+ (
+ "https://hf-mirror.example/",
+ "org/repo",
+ "https://hf-mirror.example/api/models/org/repo/auth-check",
+ ),
+ ],
+)
+def test_the_probe_url_is_built_safely(monkeypatch, endpoint, repo_id, expected_url):
+ """The probe hand-builds the auth-check URL, so id quoting and endpoint normalization are
+ its own responsibility."""
+ _hub_reachable(monkeypatch)
+ if endpoint is not None:
+ monkeypatch.setenv("HF_ENDPOINT", endpoint)
+ session = _patch_auth_check_get(monkeypatch, lambda *_a, **_k: _ok_auth_check_response())
+
+ assert cache_reads_authorized("hf_dummy", repo_id = repo_id) is True
+ url = session.calls[0]["url"]
+ assert "?" not in url
+ assert url.endswith(expected_url)
+
+
[email protected]("repo_id", ["org/../x", "../x", "org/./x", "..", "."])
+def test_a_dot_segment_repo_id_is_refused_before_the_wire(monkeypatch, repo_id):
+ """Quoting keeps "/" so "org/repo" stays two segments, which keeps ".." intact too, and
+ both clients then apply RFC 3986 dot-segment removal: "org/../x" is requested as
+ "/api/models/x". The memo would be keyed on what the caller named while the wire proof
+ was about a different repo."""
+ _hub_reachable(monkeypatch)
+ session = _patch_auth_check_get(monkeypatch, lambda *_a, **_k: _ok_auth_check_response())
+
+ assert cache_reads_authorized("hf_dummy", repo_id = repo_id) is False
+ assert session.calls == []
+
+
+def test_an_unreachable_probe_takes_the_short_ttl_and_spans_the_next_request(monkeypatch):
+ """A timeout says nothing about the credential, so it must not deny it for the full minute,
+ and the short TTL must still outlive the probe or every caller re-pays the stall."""
+ _hub_reachable(monkeypatch)
+ monkeypatch.setattr(hf_tokens, "_REPO_ACCESS_PROBE_TIMEOUT_S", 0.2)
+ probes = {"n": 0}
+
+ def _refuse(*_a, **_k):
+ probes["n"] += 1
+ raise requests.exceptions.ConnectionError("refused")
+
+ _patch_auth_check_get(monkeypatch, _refuse)
+
+ assert cache_reads_authorized("hf_dummy", repo_id = "org/repo") is False
+ assert cache_reads_authorized("hf_dummy", repo_id = "org/repo") is False
+ assert probes["n"] == 1, "the unreachable answer did not survive to the next request"
+
+ # Held under the SHORT ttl, not the denial one, and the constants must stay ordered so
+ # the memo cannot expire before the next request reaches it.
+ (expiry, allowed) = next(iter(hf_tokens._repo_access_cache.values()))
+ assert allowed is False
+ assert expiry - time.monotonic() <= hf_tokens._REPO_ACCESS_UNREACHABLE_TTL_S
+ assert (
+ hf_tokens._REPO_ACCESS_PROBE_TIMEOUT_S
+ < hf_tokens._REPO_ACCESS_UNREACHABLE_TTL_S
+ < hf_tokens._REPO_ACCESS_TTL_S
+ )
+
+
[email protected]("repo_type", ["model", "dataset"])
+def test_a_gated_repo_denies_cache_reads_for_an_invalid_token(monkeypatch, repo_type):
+ """auth_check 401s; serving the host cache would bypass the gate. This is also why the
+ probe is auth_check and not repo_info: repo_info succeeds on a gated repo's public
+ metadata for an invalid token, so its success authorizes nothing."""
+ _hub_reachable(monkeypatch)
+ seen = {}
+
+ def _auth_check(
+ url,
+ *,
+ headers = None,
+ timeout = None,
+ **_k,
+ ):
+ seen["args"] = (url, headers, timeout)
+ raise _gated_hub_error()
+
+ _patch_auth_check_get(monkeypatch, _auth_check)
+
+ assert cache_reads_authorized("hf_invalid", repo_id = "org/gated", repo_type = repo_type) is False
+ assert seen["args"][0].endswith(f"/api/{repo_type}s/org/gated/auth-check")
+
+
[email protected]("value", [True, 0, 1, 1.5, b"hf_bytes", ["hf"], {"t": 1}, object()])
+def test_a_token_that_is_not_a_string_is_denied_rather_than_read_as_ambient(value):
+ """``not isinstance(hf_token, str)`` returned the ambient answer, so every non-string
+ took the operator's cache. Nothing reaches here today -- every HTTP boundary is a
+ pydantic ``Optional[str]``, which rejects rather than coerces -- and this keeps the
+ default at deny so one untyped ``payload.get("hf_token")`` cannot become a bypass."""
+ assert cache_reads_authorized(value, repo_id = "org/private") is False
+
+
+ "path",
+ ["/home/u/models/foo", "C:\\models\\foo", "\\\\srv\\share\\foo", "./rel/model", "~/m/foo"],
+)
+def test_a_local_path_is_not_probed_against_the_hub(monkeypatch, path):
+ """auth_check interpolates its argument into the URL without validating it, so a local
+ path went to huggingface.co with the caller's bearer token attached, for a round trip
+ whose only answer is no."""
+ _hub_reachable(monkeypatch)
+ probes = []
+ monkeypatch.setattr(hf_tokens, "_probe_repo_access", lambda *a, **k: probes.append(a) or True)
+
+ assert cache_reads_authorized("hf_dummy", repo_id = path) is False
+ assert probes == []
+
+
+def test_the_local_config_probe_stays_local_for_an_explicit_token(monkeypatch, tmp_path):
+ """prefer_local_cache on a local FOLDER must not lose local_files_only just because the
+ caller sent a token the Hub has never been asked about.
+
+ The sibling above pins the same argument for a repo id. A local path is not the Hub
+ cache, which is why _model_config_inspection_target returns before the gate for one.
+ """
+ _counting_probe(monkeypatch, False)
+ local_dir = tmp_path / "my-model"
+ local_dir.mkdir()
+ (local_dir / "config.json").write_text("{}", encoding = "utf-8")
+ seen = {}
+
+ def _is_vision(
+ target,
+ hf_token = None,
+ local_files_only = False,
+ **kwargs,
+ ):
+ seen["local_files_only"] = local_files_only
+ return False
+
+ monkeypatch.setattr(models_routes, "is_vision_model", _is_vision)
+ monkeypatch.setattr(models_routes, "is_embedding_model", lambda *_a, **_k: False)
+ monkeypatch.setattr(models_routes, "load_model_defaults", lambda *_a, **_k: {}, raising = False)
+
+ try:
+ asyncio.run(
+ models_routes.get_model_config(
+ str(local_dir),
+ hf_token = None,
+ prefer_local_cache = True,
+ local_path = None,
+ header_hf_token = "hf_dummy",
+ allow_ambient_token = False,
+ current_subject = "tester",
+ )
+ )
+ except Exception:
+ pass
+
+ assert seen.get("local_files_only") is True
+
+
+ "hf_token, probe, cached, may_download, metadata_ok",
+ [
+ # picker's fallback is hf_hub_download, which serves the cached copy when the Hub is
+ # unreachable without consulting the credential. Its gate was hf_env_offline(), and
+ # "hub unreachable" is not "env offline", so an unverified token still got it.
+ ("hf_dummy", False, True, False, False),
+ # Ambient is entitled to the operator's cache, so it keeps the fallback.
+ (None, None, True, True, False),
+ # Nothing cached is nothing to withhold: refusing here would break the ordinary
+ # first-run download, which is the common case rather than the edge case.
+ ("hf_dummy", False, False, True, False),
+ # A gated repo can publish its file metadata publicly, so a 200 from get_paths_info
+ # is not permission to download: hf_hub_download returns the cached pointer for any
+ # failed head call, a 403 as much as an unreachable Hub, before it re-raises.
+ ("hf_dummy", False, True, False, True),
+ # The sentinel cannot authorize itself, which is not the same as being unentitled:
+ # a public repo is one it was always allowed to read, and refusing there costs an
+ # ordinary API-key caller the prompt formatting for a public model.
+ (False, True, True, True, True),
+ (False, False, True, False, True),
+ ],
+ ids = [
+ "unverified-denied",
+ "ambient-served",
+ "uncached-still-fetched",
+ "public-metadata-is-not-authorization",
+ "anonymous-keeps-a-public-template",
+ "anonymous-loses-a-private-one",
+ ],
+)
+def test_the_chat_template_fallback_follows_the_caller(
+ monkeypatch, hf_token, probe, cached, may_download, metadata_ok
+):
+ if probe is not None:
+ _counting_probe(monkeypatch, probe, offline = False)
+ _picker_env(monkeypatch, no_snapshots = True)
+ # The gate asks about THIS template file, not the repo directory: a snapshot holding
+ # only weights can serve no template, so refusing it would cost an authorized caller
+ # one the Hub would have given it.
+ monkeypatch.setattr(
+ "huggingface_hub.try_to_load_from_cache",
+ lambda **_k: "/cached/repo/chat_template.jinja" if cached else None,
+ )
+ downloads: list = []
+
+ class _Api:
+ def __init__(self, *_a, **_k):
+ pass
+
+ def get_paths_info(self, _repo, paths, *_a, **_k):
+ if not metadata_ok:
+ raise ConnectionError("hub unreachable")
+ return [SimpleNamespace(path = paths[0], size = 1024)]
+
+ def _download(*a, **k):
+ downloads.append(a)
+ raise FileNotFoundError("stop here; reaching the fallback is what this asserts")
+
+ monkeypatch.setattr("huggingface_hub.HfApi", _Api)
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _download)
+
+ assert picker_service.read_default_chat_template("org/private", hf_token) is None
+ assert bool(downloads) is may_download
+
+
def test_normalizing_a_token_does_not_launder_the_sentinel():
# `(hf_token or "").strip() or None` turns "stay anonymous" into "use the backend's".
assert normalize_token(False) is False
@@ -221,13 +827,7 @@ def test_seed_inspection_derives_its_policy_from_the_caller(monkeypatch):
monkeypatch.setattr(seed_routes, "_list_hf_data_files", _fake_list)
for via_api_key in (True, False):
- app = FastAPI()
- app.include_router(seed_routes.router, prefix = "/api/data-recipe")
- app.dependency_overrides[get_current_subject] = lambda: "alice"
- app.dependency_overrides[authenticated_via_api_key] = lambda: via_api_key
- client = TestClient(app, raise_server_exceptions = False)
-
- client.post(
+ _router_client(seed_routes.router, "/api/data-recipe", via_api_key = via_api_key).post(
"/api/data-recipe/seed/inspect",
json = {"dataset_name": "org/private-seed"},
headers = {"Authorization": "Bearer token"},
@@ -239,18 +839,16 @@ def test_seed_inspection_derives_its_policy_from_the_caller(monkeypatch):
def test_an_explicit_seed_token_wins_for_either_caller(monkeypatch):
seen = {}
+ _counting_probe(monkeypatch, True)
monkeypatch.setattr(
seed_routes,
"_list_hf_data_files",
lambda *, dataset_name, token: seen.update(token = token) or [],
)
+ monkeypatch.setattr(seed_routes, "load_dataset", lambda **_k: iter([]), raising = False)
for via_api_key in (True, False):
- app = FastAPI()
- app.include_router(seed_routes.router, prefix = "/api/data-recipe")
- app.dependency_overrides[get_current_subject] = lambda: "alice"
- app.dependency_overrides[authenticated_via_api_key] = lambda: via_api_key
- TestClient(app, raise_server_exceptions = False).post(
+ _router_client(seed_routes.router, "/api/data-recipe", via_api_key = via_api_key).post(
"/api/data-recipe/seed/inspect",
json = {"dataset_name": "org/private-seed", "hf_token": " caller-token "},
headers = {"Authorization": "Bearer token"},
@@ -318,8 +916,6 @@ def test_an_explicit_token_evicts_the_ambient_aliases_too():
def test_the_audio_tokenizer_fallback_does_not_reach_for_the_ambient_token(monkeypatch):
"""`hf_token or os.environ.get("HF_TOKEN")` reads past the sentinel to the operator's."""
- import utils.models.model_config as mc
-
monkeypatch.setenv("HF_TOKEN", "ambient-operator-token")
seen = {}
@@ -339,10 +935,9 @@ def test_the_audio_tokenizer_fallback_does_not_reach_for_the_ambient_token(monke
seen.setdefault("headers", headers)
return _Resp()
- import requests
monkeypatch.setattr(requests, "get", _get)
- mc._detect_audio_from_tokenizer("org/private", hf_token = False, revision = None)
+ model_config_module._detect_audio_from_tokenizer("org/private", hf_token = False, revision = None)
assert "Authorization" not in (
seen.get("headers") or {}
@@ -363,8 +958,6 @@ def test_the_stt_sidecars_pass_the_sentinel_through_unchanged():
def test_an_anonymous_caller_does_not_get_the_unauthenticated_preview_cache(monkeypatch):
"""The disk fast path returns real rows without asking the Hub anything."""
- from hub.services.datasets import formatting
-
called = {"cache": 0, "processed": 0}
monkeypatch.setattr(
formatting,
@@ -388,39 +981,75 @@ def test_an_anonymous_caller_does_not_get_the_unauthenticated_preview_cache(monk
assert called["cache"] == 1
assert formatting._load_any_cached_hf_preview_slice(request, 5, False) is None
- assert called["cache"] == 1, "the anonymous caller reached the unauthenticated cache"
- assert called["processed"] == 0, "the anonymous caller reached the processed cache"
+ probes = _counting_probe(monkeypatch, False)
+ assert formatting._load_any_cached_hf_preview_slice(request, 5, "hf_dummy") is None
+ assert called["processed"] == 0, "the raw slice answered; the processed cache is extra reach"
+
+ # The disk read runs first now, and the gate stands between it and the caller: reading our
+ # own disk is not the leak, returning it is. That ordering is also what keeps a cache-only
+ # request off the wire, since a miss never reaches the probe at all.
+ called["cache"] = 0
+ monkeypatch.setattr(formatting, "_load_cached_hf_preview_slice", lambda *_a, **_k: None)
+ monkeypatch.setattr(formatting, "_load_processed_hf_preview_slice", lambda *_a, **_k: None)
+ # The verdict above is memoized for 60s, which would hide the round trip this asserts.
+ hf_tokens.reset_repo_access_cache()
+ probes["n"] = 0
+ assert formatting._load_any_cached_hf_preview_slice(request, 5, "hf_dummy") is None
+ assert probes["n"] == 0, "a cache miss still put the caller's token on the wire"
def test_an_anonymous_caller_does_not_read_a_cached_chat_template(monkeypatch):
- """The snapshot walk returns a private repo's raw template with no Hub call."""
- from picker import service as picker_service
+ """The snapshot walk returns a private repo's raw template with no Hub call.
- walked = {"n": 0}
-
- def _snapshots(*_a, **_k):
- walked["n"] += 1
- return [Path("/nonexistent-snapshot")]
-
- monkeypatch.setattr(picker_service, "iter_snapshots_preferring_whole", _snapshots)
+ The walk itself runs for everyone: it reads our own disk, which is not the leak, and
+ ordering it first is what keeps an uncached repo off the wire. Handing the template
+ back is what is gated.
+ """
+ monkeypatch.setattr(
+ picker_service, "iter_snapshots_preferring_whole", lambda *_a, **_k: [Path("/snap")]
+ )
monkeypatch.setattr(picker_service, "_chat_template_from_dir", lambda *_a, **_k: "TEMPLATE")
assert picker_service.read_default_chat_template("org/private", None) == "TEMPLATE"
- assert walked["n"] == 1
- picker_service.read_default_chat_template("org/private", False)
- assert walked["n"] == 1, "the anonymous caller walked the cached snapshots"
+ assert (
+ picker_service.read_default_chat_template("org/private", False) != "TEMPLATE"
+ ), "the anonymous caller was handed the cached template"
+ probes = _counting_probe(monkeypatch, False)
+ assert (
+ picker_service.read_default_chat_template("org/private", "hf_dummy") != "TEMPLATE"
+ ), "an unverified token was handed the cached template"
+
+ # Nothing cached: there is no disk-backed answer to protect, so no probe is warranted.
+ monkeypatch.setattr(picker_service, "_chat_template_from_dir", lambda *_a, **_k: None)
+ hf_tokens.reset_repo_access_cache()
+ probes["n"] = 0
+ picker_service.read_default_chat_template("org/uncached", "hf_dummy")
+ assert probes["n"] == 0, "an uncached repo still cost the caller a probe"
[email protected]("hf_token", [None, "hf_tok"])
-def test_the_config_inspection_target_still_uses_the_cache_for_the_ambient_caller(hf_token):
+def test_the_config_inspection_target_still_uses_the_cache_for_the_ambient_caller():
"""A caller allowed the ambient credential keeps the prefer_local_cache fast path.
With no snapshot on disk the resolver raises its own 404; reaching that proves the
cache branch ran rather than short-circuiting back to the bare repo id.
"""
with pytest.raises(fastapi.HTTPException):
- models_routes._model_config_inspection_target("org/private", True, None, hf_token)
+ models_routes._model_config_inspection_target("org/private", True, None, None)
+
+
+def test_the_config_inspection_target_skips_the_cache_for_an_unverified_token(monkeypatch):
+ _counting_probe(monkeypatch, False)
+ reset_repo_access_cache()
+ target = models_routes._model_config_inspection_target("org/private", True, None, "hf_dummy")
+ assert target == "org/private", "an unverified token was pointed at the cache"
+
+
+def test_the_config_inspection_target_uses_the_cache_for_a_verified_token(monkeypatch):
+ _counting_probe(monkeypatch, True)
+ reset_repo_access_cache()
+ with pytest.raises(fastapi.HTTPException):
+ models_routes._model_config_inspection_target("org/private", True, None, "hf_real")
def test_the_config_inspection_target_skips_the_cache_for_anonymous():
@@ -430,6 +1059,15 @@ def test_the_config_inspection_target_skips_the_cache_for_anonymous():
assert target == "org/private", "the anonymous caller was pointed at the cache"
+def test_resolving_the_hub_token_keeps_the_anonymous_sentinel():
+ """Rebuilding the sentinel must not quietly restore ambient access."""
+ assert models_routes._resolve_hub_token(False, None) is False
+ assert models_routes._resolve_hub_token(False, " ") is False
+ assert models_routes._resolve_hub_token(None, None) is None
+ assert models_routes._resolve_hub_token(False, "hf_query") == "hf_query"
+ assert models_routes._resolve_hub_token("hf_header", "hf_query") == "hf_header"
+
+
def test_resolving_the_hub_token_never_returns_an_unresolved_dependency():
"""Callers that invoke the route function directly leave a ``Depends`` in the slot.
@@ -445,25 +1083,13 @@ def test_resolving_the_hub_token_never_returns_an_unresolved_dependency():
assert resolved is None, "an unresolved dependency reached the Hub call"
-def test_resolving_the_hub_token_keeps_the_anonymous_sentinel():
- """Rebuilding the sentinel must not quietly restore ambient access."""
- assert models_routes._resolve_hub_token(False, None) is False
- assert models_routes._resolve_hub_token(False, " ") is False
- assert models_routes._resolve_hub_token(None, None) is None
- assert models_routes._resolve_hub_token(False, "hf_query") == "hf_query"
- assert models_routes._resolve_hub_token("hf_header", "hf_query") == "hf_header"
-
-
def test_an_anonymous_caller_gets_no_template_from_the_offline_fallback(monkeypatch):
"""Offline, hf_hub_download answers from disk and never checks the credential.
The chat-template route forces offline whenever the Hub looks unreachable, so
without this the Hub fallback hands back the template the cache walk just refused.
"""
- from picker import service as picker_service
-
- monkeypatch.setattr(picker_service, "hf_env_offline", lambda: True)
- monkeypatch.setattr(picker_service, "resolve_cached_repo_id_case", lambda name: name)
+ _picker_env(monkeypatch, offline = True)
def _exploded(*args, **kwargs):
raise AssertionError("the anonymous caller reached the hub fallback")
@@ -490,7 +1116,6 @@ def test_an_anonymous_config_read_does_not_strip_the_process_credential(monkeypa
seen["ambient"] = os.environ.get("HF_TOKEN")
return _Config()
- import transformers
monkeypatch.setattr(transformers.AutoConfig, "from_pretrained", staticmethod(_from_pretrained))
monkeypatch.setattr(model_config_module, "active_hf_hub_cache", lambda: None, raising = False)
@@ -504,8 +1129,9 @@ def test_an_anonymous_config_read_does_not_strip_the_process_credential(monkeypa
@pytest.mark.parametrize(
+ # Explicit-token leg is an API key; as a UI session it asserted the regression.
"hf_token, expected_local_only",
- [(None, True), ("hf_tok", True), (False, False)],
+ [(None, True), ("hf_tok", False), (False, False)],
)
def test_the_config_probes_do_not_go_local_only_for_an_anonymous_caller(
monkeypatch, hf_token, expected_local_only
@@ -515,6 +1141,7 @@ def test_the_config_probes_do_not_go_local_only_for_an_anonymous_caller(
Sending the anonymous caller back to the bare repo id only helps if the probe then
goes over the wire, where `token=False` is refused for a private repo.
"""
+ _counting_probe(monkeypatch, False)
seen = {}
def _is_vision(
@@ -544,7 +1171,7 @@ def test_the_config_probes_do_not_go_local_only_for_an_anonymous_caller(
prefer_local_cache = True,
local_path = None,
header_hf_token = hf_token if isinstance(hf_token, str) else None,
- allow_ambient_token = hf_token is not False,
+ allow_ambient_token = hf_token is None,
current_subject = "tester",
)
)
@@ -576,8 +1203,7 @@ def test_gguf_variants_serve_the_hf_cache_only_to_an_authorized_caller(monkeypat
The listing carries variant filenames, sizes and the vision flag, so a caller denied
the ambient token could name a private repo the UI had cached and read it back.
"""
- from hub.services.models import gguf_variants
-
+ _counting_probe(monkeypatch, False)
reads = {"snapshot": 0, "state": 0}
def _snapshot(*_a, **_k):
@@ -605,11 +1231,11 @@ def test_gguf_variants_serve_the_hf_cache_only_to_an_authorized_caller(monkeypat
# Offline with nothing cached is a 404 either way; the reads are the point.
pass
- if is_anonymous(hf_token):
+ if is_anonymous(hf_token) or hf_token == "hf_tok":
assert reads == {
"snapshot": 0,
"state": 0,
- }, "the anonymous caller was served from the hub cache"
+ }, "an unverified caller was served from the hub cache"
else:
assert reads["snapshot"] > 0, "the authorized caller lost its cache fast path"
@@ -621,6 +1247,7 @@ def test_offline_capability_probes_do_not_read_the_cache_anonymously(monkeypatch
So passing local_files_only=False does not put the anonymous caller back on the wire:
the probe reads the cached config.json off disk and never authorizes.
"""
+ _counting_probe(monkeypatch, False)
monkeypatch.setattr(model_config_module, "_env_offline", lambda: True)
reached = {"vision": 0, "audio": 0}
@@ -643,9 +1270,9 @@ def test_offline_capability_probes_do_not_read_the_cache_anonymously(monkeypatch
"org/private", hf_token = hf_token, local_files_only = False
)
- if is_anonymous(hf_token):
+ if is_anonymous(hf_token) or hf_token == "hf_tok":
assert is_vision is False
- assert reached["vision"] == 0, "the anonymous caller probed the offline cache"
+ assert reached["vision"] == 0, "an unverified caller probed the offline cache"
else:
assert reached["vision"] == 1, "the authorized caller lost its offline probe"
@@ -653,25 +1280,24 @@ def test_offline_capability_probes_do_not_read_the_cache_anonymously(monkeypatch
@pytest.mark.parametrize("hf_token", [None, "hf_tok", False])
def test_the_config_json_fallbacks_do_not_reach_the_cache_anonymously(monkeypatch, hf_token):
"""Keying the memo apart is not enough when the value came off disk to begin with."""
- import utils.transformers_version as tv
-
- monkeypatch.setattr(tv, "_env_offline", lambda: True)
- monkeypatch.setattr(tv, "_safe_is_file", lambda _p: False)
- monkeypatch.setattr(tv, "_safe_is_dir", lambda _p: False)
- monkeypatch.setattr(tv, "_config_json_cache", {})
+ _counting_probe(monkeypatch, False)
+ monkeypatch.setattr(transformers_version, "_env_offline", lambda: True)
+ monkeypatch.setattr(transformers_version, "_safe_is_file", lambda _p: False)
+ monkeypatch.setattr(transformers_version, "_safe_is_dir", lambda _p: False)
+ monkeypatch.setattr(transformers_version, "_config_json_cache", {})
reads = {"n": 0}
def _from_cache(_name):
reads["n"] += 1
return {"max_position_embeddings": 4096}
- monkeypatch.setattr(tv, "_config_json_from_hf_cache", _from_cache)
+ monkeypatch.setattr(transformers_version, "_config_json_from_hf_cache", _from_cache)
- cfg = tv._load_config_json("org/private", hf_token = hf_token)
+ cfg = transformers_version._load_config_json("org/private", hf_token = hf_token)
- if is_anonymous(hf_token):
+ if is_anonymous(hf_token) or hf_token == "hf_tok":
assert cfg is None
- assert reads["n"] == 0, "the anonymous caller read the offline config cache"
+ assert reads["n"] == 0, "an unverified caller read the offline config cache"
else:
assert cfg == {"max_position_embeddings": 4096}
@@ -682,7 +1308,7 @@ def test_a_cache_only_gguf_listing_is_refused_for_an_anonymous_caller(monkeypatc
Declining to build a second cached response is not enough: falling through would
serialize the first one.
"""
- from hub.services.models import gguf_variants
+
monkeypatch.setattr(
gguf_variants,
@@ -711,16 +1337,23 @@ def test_the_scan_route_derives_its_caller_rather_than_trusting_an_absent_body_t
), "the body token reaches the cache-backed scan target unresolved"
-def test_an_anonymous_seed_preview_is_refused_while_offline(monkeypatch):
- """Offline, `datasets` satisfies a streaming load from its own cache.
-
- The sentinel never reaches an authorization check there, so a previously cached
- private dataset would come back as rows.
- """
- monkeypatch.setattr(seed_routes, "hf_env_offline", lambda: True)
+ "reason, hf_token, offline",
+ [
+ # Offline, `datasets` serves a streaming load from its own cache without reaching an
+ # authorization check, so a cached private dataset would come back as rows.
+ ("the anonymous caller, offline", None, True),
+ # Online, the same load is satisfied from cache without asking the Hub.
+ ("an unverified token, online", "hf_dummy", False),
+ ],
+)
+def test_a_seed_preview_off_the_cache_is_refused(monkeypatch, reason, hf_token, offline):
+ _counting_probe(monkeypatch, False)
+ monkeypatch.setattr("utils.utils.hf_env_offline", lambda: offline)
+ monkeypatch.setattr(dataset_cache, "dataset_cache_can_answer", lambda *_a, **_k: True)
def _never(*_a, **_k):
- raise AssertionError("the anonymous caller reached the dataset load")
+ raise AssertionError(f"{reason} reached the dataset load")
monkeypatch.setattr(seed_routes, "_list_hf_data_files", _never)
@@ -728,7 +1361,7 @@ def test_an_anonymous_seed_preview_is_refused_while_offline(monkeypatch):
dataset_name = "org/private",
split = None,
subset = None,
- hf_token = None,
+ hf_token = hf_token,
preview_size = 5,
)
@@ -766,6 +1399,7 @@ def test_the_lora_resolver_does_not_launder_the_sentinel(monkeypatch, hf_token):
@pytest.mark.parametrize("hf_token", [None, "hf_tok", False])
def test_the_audio_tokenizer_probe_does_not_read_the_cache_anonymously(monkeypatch, hf_token):
"""The cache root is walked before any network branch, online as well as offline."""
+ _counting_probe(monkeypatch, False)
reads = {"n": 0}
def _cache_path(_name):
@@ -780,8 +1414,8 @@ def test_the_audio_tokenizer_probe_does_not_read_the_cache_anonymously(monkeypat
except Exception:
pass
- if is_anonymous(hf_token):
- assert reads["n"] == 0, "the anonymous caller walked the hub cache"
+ if is_anonymous(hf_token) or hf_token == "hf_tok":
+ assert reads["n"] == 0, "an unverified caller walked the hub cache"
else:
assert reads["n"] > 0, "the authorized caller lost its cache fast path"
@@ -819,11 +1453,19 @@ def test_a_public_model_keeps_its_size_when_the_cache_is_bypassed():
@pytest.mark.parametrize("hf_token", [None, "hf_tok", False])
def test_the_offline_autoconfig_read_is_denied_to_an_anonymous_caller(monkeypatch, hf_token):
- """token=False disables authentication but not the local cache."""
- import transformers
+ """token=False disables authentication but not the local cache.
+
+ The repo is cached here, which is the premise the denial rests on: the gate exists to
+ stop a caller reading config.json off the operator's disk. An uncached repo has nothing
+ to read and is covered separately, because refusing it protects nothing and breaks a
+ mirror without /auth-check.
+ """
+
+ _counting_probe(monkeypatch, False)
monkeypatch.setattr(model_config_module, "_env_offline", lambda: True)
monkeypatch.setattr(model_config_module, "active_hf_hub_cache", lambda: None, raising = False)
+ monkeypatch.setattr(model_config_module, "_config_json_already_cached", lambda *_a, **_k: True)
reached = {"n": 0}
def _from_pretrained(_name, **_kwargs):
@@ -832,10 +1474,10 @@ def test_the_offline_autoconfig_read_is_denied_to_an_anonymous_caller(monkeypatc
monkeypatch.setattr(transformers.AutoConfig, "from_pretrained", staticmethod(_from_pretrained))
- if is_anonymous(hf_token):
+ if is_anonymous(hf_token) or hf_token == "hf_tok":
with pytest.raises(OSError):
model_config_module.load_model_config("org/private", token = hf_token)
- assert reached["n"] == 0, "the anonymous caller read the offline config cache"
+ assert reached["n"] == 0, "an unverified caller read the offline config cache"
else:
model_config_module.load_model_config("org/private", token = hf_token)
assert reached["n"] == 1
@@ -843,12 +1485,21 @@ def test_the_offline_autoconfig_read_is_denied_to_an_anonymous_caller(monkeypatc
def test_the_prefer_local_scan_branch_carries_the_anonymous_guard():
"""Only the exact-snapshot branch was gated; the sibling resolved the cache anyway."""
- source = inspect.getsource(models_routes.scan_model_remote_code)
- marker = source.index("elif prefer_local_cache is True")
- branch = source[marker : marker + 200]
+ # The rest of the condition this marker opens, bounded by indentation: it ends at the
+ # closing "):", which dedents. A fixed character window drifted with every edit to the
+ # surrounding function, and widened the claim silently rather than failing.
+ lines = inspect.getsource(models_routes.scan_model_remote_code).splitlines()
+ start = next(i for i, line in enumerate(lines) if "prefer_local_cache is True" in line)
+ depth = len(lines[start]) - len(lines[start].lstrip())
+ condition = []
+ for line in lines[start + 1 :]:
+ if line.strip() and len(line) - len(line.lstrip()) < depth:
+ break
+ condition.append(line)
+ branch = "\n".join(condition)
assert (
- "not is_anonymous(hf_token)" in branch
+ "cache_reads_authorized(hf_token, repo_id = model_name)" in branch
), "the prefer-local scan branch still resolves a cached snapshot for any caller"
@@ -876,14 +1527,1067 @@ def test_the_offline_anonymous_rule_is_stated_once(hf_token, offline, denied, mo
def test_every_offline_reachable_route_refuses_before_it_reads(monkeypatch):
- """The three routes that reach disk offline all consult the shared rule."""
- from hub.services.datasets import formatting
+ """The three routes that reach disk offline all consult a shared rule rather than
+ open-coding one, which is how the per-site version drifted six times before."""
+
+
+ shared_rules = ("anonymous_and_offline", "refuse_unauthorized_dataset_preview")
for owner, name in (
(models_routes.get_model_config, "/config"),
(models_routes.scan_model_remote_code, "scan-remote-code"),
(formatting.check_format_response, "check-format"),
):
source = inspect.getsource(owner)
- assert (
- "anonymous_and_offline" in source
+ assert any(
+ rule in source for rule in shared_rules
), f"{name} can still be answered from disk for a denied caller"
+
+
+def test_an_unreachable_hub_is_a_503_not_a_404_and_not_a_500():
+ """check-format has no refusal of its own: a denied caller returns None from the disk
+ route, falls through to a Hub that cannot answer, and the pair below came back. They
+ were not mapped, so the catch-all turned "I could not reach the Hub" into a 500.
+
+ 404 is the wrong repair. "I could not ask" is not "it is not there", and
+ ``openai_auto_download._admit_and_start`` calls ``_mark_not_servable`` for every 404,
+ which suppresses the repo for ten minutes. ``force_hf_offline`` flips
+ ``huggingface_hub.constants`` process-wide for the length of one unreachable download,
+ so a concurrent /v1 request really does see ``OfflineModeIsEnabled`` from a plain
+ ``model_info``. 503 is retryable, which is also what routes/training's preflight
+ already retries on."""
+ from huggingface_hub.errors import LocalEntryNotFoundError, OfflineModeIsEnabled
+ from hub.utils.hf_errors import hf_error_status
+
+ assert hf_error_status(LocalEntryNotFoundError("no cache, no hub")) == 503
+ assert hf_error_status(OfflineModeIsEnabled("offline")) == 503
+ assert hf_error_status(RuntimeError("boom")) is None
+
+
+def test_a_forced_offline_window_does_not_quarantine_a_repo_for_ten_minutes():
+ """The regression the mapping above caused: ``_admit_and_start`` reads the status, and
+ 404 both reports "not found on Hugging Face" and pins the repo in ``_not_servable``."""
+ from unittest import mock
+
+ import huggingface_hub
+ from huggingface_hub.errors import OfflineModeIsEnabled
+
+ from core.inference import openai_auto_download as auto
+
+ auto._not_servable.clear()
+
+ class _Api:
+ def __init__(self, *a, **k): pass
+ def model_info(self, *a, **k): raise OfflineModeIsEnabled("offline mode is enabled")
+
+ with mock.patch.object(huggingface_hub, "HfApi", _Api):
+ refusal = asyncio.run(
+ auto._admit_and_start(
+ "org/repo", "Q4_K_M", "org/repo:Q4_K_M", None, auto._Active(repo_id = "org/repo")
+ )
+ )
+
+ assert refusal is not None and refusal.status == 503, "a forced-offline window is retryable"
+ assert not auto._is_not_servable("org/repo", None), "an unreachable Hub quarantined the repo"
+
+
+def test_a_ui_sessions_marker_survives_the_route_level_token_normalizer():
+ """``routes.models._normalize_hf_token`` trimmed with ``str.strip()``, which returns a
+ plain ``str``. That silently demoted a UI session to an API key between the dependency
+ and the gate, so an ordinary session lost its own cache offline: the exact regression
+ ``AmbientAuthorizedToken`` exists to prevent, reintroduced one call later."""
+ ui = hf_token_arg(" hf_saved ", allow_ambient_token = True)
+ resolved = models_routes._normalize_hf_token(ui)
+
+ assert resolved == "hf_saved"
+ assert isinstance(resolved, hf_tokens.AmbientAuthorizedToken), "marker lost in normalization"
+ # An API key must not acquire the marker on the way through.
+ api_key = hf_token_arg(" hf_saved ", allow_ambient_token = False)
+ assert not isinstance(
+ models_routes._normalize_hf_token(api_key), hf_tokens.AmbientAuthorizedToken
+ )
+ assert models_routes._normalize_hf_token(" ") is None
+ assert models_routes._normalize_hf_token(False) is None
+
+
+ "via_api_key, gated",
+ [(True, True), (False, False)],
+ ids = ["api-key-denied", "ui-session-served"],
+)
+def test_the_format_check_gates_the_streaming_tiers_by_caller(monkeypatch, via_api_key, gated):
+ """Measured against the installed ``datasets``: offline, ``load_dataset`` answers BOTH
+ ``streaming=True`` tiers out of its own prepared cache, logging "using the latest cached
+ version", with the token never consulted. Both tiers run on the default
+ ``prefer_local_cache=false``, ahead of the guarded cache reader, so the gate stands in
+ front of them. The UI leg is the regression guard: a session holding its own saved token
+ is entitled to ambient and must reach the loader with no probe."""
+ probes = _counting_probe(monkeypatch, False)
+ monkeypatch.setattr(dataset_cache, "dataset_cache_can_answer", lambda *_a, **_k: True)
+
+ loads = {"n": 0}
+
+ def _loader(*_a, **_k):
+ loads["n"] += 1
+ raise RuntimeError("reached the loader, which is all this leg asserts")
+
+ monkeypatch.setattr("datasets.load_dataset", _loader)
+
+ token = hf_token_arg("hf_saved", allow_ambient_token = not via_api_key)
+ request = CheckFormatRequest(dataset_name = "acme/private-secrets")
+
+ with pytest.raises(Exception) as excinfo:
+ formatting.check_format_response(request, token)
+
+ if gated:
+ assert isinstance(excinfo.value, HTTPException) and excinfo.value.status_code == 404
+ assert loads["n"] == 0, "load_dataset ran for an unauthorized caller"
+ else:
+ assert loads["n"] > 0, "an ordinary UI session was denied its own dataset"
+ assert probes["n"] == 0, "the UI session paid a round trip for its own token"
+
+
+ "explicit, memoized",
+ [(True, False), (False, True)],
+ ids = ["explicit-token-re-derives", "ambient-keeps-memo"],
+)
+def test_the_offline_config_memo_follows_the_caller(monkeypatch, explicit, memoized):
+ """``cache_reads_authorized`` expires in 60 s so a revoked token stops reading, but
+ ``_config_json_cache`` has no TTL: memoizing a value that came off the operator's disk
+ outlived the access it was granted under. Ambient still memoizes, or every read becomes a
+ fresh disk walk."""
+ transformers_version._config_json_cache.clear()
+ monkeypatch.setattr(transformers_version, "_env_offline", lambda: True)
+ reads = {"n": 0}
+
+ def _from_cache(*_a, **_k):
+ reads["n"] += 1
+ return {"model_type": "secret"}
+
+ monkeypatch.setattr(transformers_version, "_config_json_from_hf_cache", _from_cache)
+ authorized = {"v": True}
+ monkeypatch.setattr(transformers_version, "cache_reads_authorized", lambda *_a, **_k: authorized["v"])
+
+ token = hf_token_arg("hf_explicit", allow_ambient_token = False) if explicit else None
+ assert transformers_version._load_config_json("acme/private", token) == {"model_type": "secret"}
+
+ if memoized:
+ assert transformers_version._load_config_json("acme/private", token) == {"model_type": "secret"}
+ assert reads["n"] == 1, "the ambient memo stopped working"
+ else:
+ # Revoke: an explicit token must re-derive rather than replay the memo.
+ authorized["v"] = False
+ assert transformers_version._load_config_json("acme/private", token) is None
+
+
+def test_the_vision_config_read_refuses_an_unauthorized_cache_fallback(monkeypatch, tmp_path):
+ """Measured against the installed huggingface_hub: with a planted cache entry and a dead
+ endpoint, ``hf_hub_download(local_files_only=False)`` returns the operator's CACHED
+ config.json for a token that cannot read the repo, because it falls back to disk whenever
+ the Hub is unreachable and never consults the credential to do it."""
+ # A real cached config, so an unguarded read returns the leak rather than an error.
+ tmp_config = tmp_path / "config.json"
+ tmp_config.write_text('{"vision_config": {}, "model_type": "secret"}')
+ monkeypatch.setattr(model_config_module, "_config_json_already_cached", lambda *_a, **_k: True)
+ monkeypatch.setattr(model_config_module, "cache_reads_authorized", lambda *_a, **_k: False)
+
+ # Counted, not raised: the reader wraps everything in `except Exception`, so an
+ # AssertionError thrown in here would be swallowed and the test would pass unguarded.
+ calls = {"n": 0}
+
+ def _download(*_a, **_k):
+ calls["n"] += 1
+ return str(tmp_config)
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _download)
+
+ api_key = hf_token_arg("hf_cannot_read_this", allow_ambient_token = False)
+ assert model_config_module._raw_config_has_vision_config("acme/private-vlm", hf_token = api_key) is None
+ assert calls["n"] == 0, "hf_hub_download ran for an unauthorized cached repo"
+
+
+def test_a_failed_cache_check_does_not_open_the_path_it_guards(monkeypatch):
+ """If the cache lookup itself raises, the guard must assume a hit and authorize."""
+
+ def _boom(*_a, **_k):
+ raise OSError("cache unreadable")
+
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", _boom)
+ assert model_config_module._config_json_already_cached("acme/private-vlm") is True
+
+
+def test_the_remote_code_scan_refuses_a_cached_repo_it_cannot_authorize(monkeypatch):
+ """_load_remote_code_configs calls hf_hub_download without local_files_only, which
+ serves a cached file on an unreachable Hub without consulting the credential, so
+ has_remote_code is answered off the operator's disk; gating only the prefer_local path
+ left the scan running anyway. Uncached is the shared gate's own test."""
+ _counting_probe(monkeypatch, False, offline = False)
+ monkeypatch.setattr(models_routes, "_repo_in_any_hf_cache", lambda *_a, **_k: True)
+ # config.json cached, which is what makes the scan answerable off disk.
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda **_k: "/cache/config.json")
+
+ async def _call():
+ return await models_routes.scan_model_remote_code(
+ model_name = "acme/private-vlm",
+ hf_token = "hf_cannot_read_this",
+ allow_ambient_token = False,
+ current_subject = "alice",
+ )
+
+ with pytest.raises(fastapi.HTTPException) as excinfo:
+ asyncio.run(_call())
+ assert excinfo.value.status_code == 404
+
+
+def test_the_legacy_body_token_keeps_its_caller_class():
+ """The deprecated /api/datasets/check-format still accepts the token in the BODY. That
+ value arrived as a plain str and skipped the marker get_request_hf_token attaches, so the
+ same UI session, sending the same token, lost its own cached dataset offline purely for
+ using the legacy route. The header and the body are one credential, classified alike."""
+ from routes import datasets as datasets_routes
+
+ app = FastAPI()
+ app.include_router(datasets_routes.router, prefix = "/api/datasets")
+ app.dependency_overrides[get_current_subject] = lambda: "tester"
+ app.dependency_overrides[authenticated_via_api_key] = lambda: False # a UI session
+
+ seen = {}
+
+ def _capture(
+ request,
+ hf_token = None,
+ **_k,
+ ):
+ seen["token"] = hf_token
+ raise HTTPException(status_code = 418, detail = "captured")
+
+ original = datasets_routes.formatting.check_format_response
+ datasets_routes.formatting.check_format_response = _capture
+ try:
+ with TestClient(app) as client:
+ client.post(
+ "/api/datasets/check-format",
+ json = {"dataset_name": "acme/private-secrets", "hf_token": "hf_saved"},
+ )
+ finally:
+ datasets_routes.formatting.check_format_response = original
+
+ assert isinstance(
+ seen.get("token"), hf_tokens.AmbientAuthorizedToken
+ ), "a UI session's body token was demoted to an API key"
+
+
+def test_the_same_token_from_two_caller_classes_takes_two_cache_identities():
+ """The marker is a str subclass with the same encoded value, so every fingerprint that
+ hashes the token alone collided. Any cache keyed on one could hand a caller the other's
+ verdict, and the GGUF in-flight coalescer merged their scans into a single computation
+ whose authorization was settled by whichever request arrived first."""
+ from hub.utils import inventory_scan
+ from core.inference import diffusion_compat as dc
+
+ ui = hf_token_arg("hf_saved", allow_ambient_token = True)
+ api = hf_token_arg("hf_saved", allow_ambient_token = False)
+
+ for fingerprint in (
+ inventory_scan.token_fingerprint,
+ model_config_module._token_fingerprint,
+ dc._token_fingerprint,
+ ):
+ ui_id, api_id = fingerprint(ui), fingerprint(api)
+ assert ui_id != api_id, f"{fingerprint.__module__} still collides across caller classes"
+ # The qualifier must not smuggle the credential into a dict key.
+ assert "hf_saved" not in str(ui_id) and "hf_saved" not in str(api_id)
+
+ # The sentinel and the ambient caller keep the identities they already had.
+ assert inventory_scan.token_fingerprint(False) == ANONYMOUS_CACHE_IDENTITY
+ assert inventory_scan.token_fingerprint(None) == ""
+
+
+def test_the_legacy_query_token_is_classified_like_the_header(monkeypatch):
+ """normalize_token can carry a marker through but cannot create one, and ?hf_token= never
+ had it: the value arrives as a bare string, not from the dependency. Measured before this,
+ for one UI session sending one token two ways with the Hub unreachable:
+
+ query type=str authorized=False
+ header type=AmbientAuthorizedToken authorized=True
+ """
+ _counting_probe(monkeypatch, False)
+
+ ui_header_absent = hf_token_arg(None, allow_ambient_token = True)
+ resolved = models_routes._resolve_hub_token(ui_header_absent, "hf_saved")
+ assert isinstance(resolved, hf_tokens.AmbientAuthorizedToken)
+ assert cache_reads_authorized(resolved, repo_id = "acme/private") is True
+
+ # An API key sending only the query parameter stays an API key: its header is the sentinel.
+ api_no_header = hf_token_arg(None, allow_ambient_token = False)
+ api_resolved = models_routes._resolve_hub_token(api_no_header, "hf_saved")
+ assert not isinstance(api_resolved, hf_tokens.AmbientAuthorizedToken)
+ assert cache_reads_authorized(api_resolved, repo_id = "acme/private") is False
+
+ # The header still wins over a stale query value, and the no-token cases are unchanged.
+ header = hf_token_arg("hf_header", allow_ambient_token = True)
+ assert models_routes._resolve_hub_token(header, "hf_query") == "hf_header"
+ assert (
+ models_routes._resolve_hub_token(hf_token_arg(None, allow_ambient_token = False), None)
+ is False
+ )
+ assert (
+ models_routes._resolve_hub_token(hf_token_arg(None, allow_ambient_token = True), None) is None
+ )
+
+
+def test_the_embedding_memo_does_not_cross_caller_classes(monkeypatch):
+ """The memo is read at the top of is_embedding_model, above every authorization check, and
+ was keyed on the raw token. The marker hashes and compares equal to a plain API token of
+ the same value, so a UI-computed classification came straight back to an unverified API
+ caller. Keyed on the fingerprint now, which carries the caller class."""
+ ui = hf_token_arg("hf_saved", allow_ambient_token = True)
+ api = hf_token_arg("hf_saved", allow_ambient_token = False)
+
+ monkeypatch.setattr(model_config_module, "_embedding_detection_cache", {})
+ monkeypatch.setattr(model_config_module, "is_local_path", lambda *_a, **_k: False)
+ monkeypatch.setattr(model_config_module, "_embedding_marker_in_hf_cache", lambda *_a, **_k: True)
+ monkeypatch.setattr("utils.utils.hf_env_offline", lambda: False)
+
+ def _no_hub(*_a, **_k):
+ raise RuntimeError("hub unreachable, so the cached marker is the fallback")
+
+ monkeypatch.setattr("huggingface_hub.model_info", _no_hub)
+ # Only the UI session is entitled to the operator's cache here.
+ monkeypatch.setattr(
+ model_config_module,
+ "cache_reads_authorized",
+ lambda token, **_k: isinstance(token, hf_tokens.AmbientAuthorizedToken),
+ )
+
+ # The UI session classifies from its own cached marker and memoizes that.
+ assert model_config_module.is_embedding_model("acme/private-emb", ui) is True
+ # The API caller must be refused, not handed the entry the UI just wrote.
+ assert model_config_module.is_embedding_model("acme/private-emb", api) is False
+
+
+def test_an_offline_request_is_fail_closed_but_keeps_a_paid_for_answer(monkeypatch):
+ """``cache_reads_authorized`` saw only the process-level env, so a request carrying its own
+ offline=true still put the caller's token and repo id on the wire and could stall for the
+ full probe timeout, to reach a branch that was never going to use the network. Fail closed
+ must not discard an authorization already paid for, so the memo is consulted first."""
+ probes = _counting_probe(monkeypatch, True, offline = False)
+
+ # Cold and offline: refuse without asking.
+ assert cache_reads_authorized("hf_explicit", repo_id = "acme/private", offline = True) is False
+ assert probes["n"] == 0, "an offline request still went to the network"
+
+ # Online, the same call probes: the flag is the caller's, not a new default.
+ assert cache_reads_authorized("hf_explicit", repo_id = "acme/private") is True
+ assert probes["n"] == 1
+
+ # Now memoized, an offline call keeps the yes rather than downgrading it.
+ assert cache_reads_authorized("hf_explicit", repo_id = "acme/private", offline = True) is True
+ assert probes["n"] == 1
+
+
+def test_an_uncached_dataset_is_not_denied_for_an_unavailable_probe(monkeypatch):
+ """Same rule as the config reader: authorize only where a cached read could be served.
+ An uncached dataset has nothing to leak, so denying it just costs a legitimate caller its
+ preview whenever the probe is unavailable rather than negative, which is what an
+ HF_ENDPOINT mirror without the undocumented /auth-check route looks like."""
+ _counting_probe(monkeypatch, False)
+ monkeypatch.setattr(dataset_cache, "dataset_cache_can_answer", lambda *_a, **_k: False)
+
+ reached = {"n": 0}
+
+ def _reached(*_a, **_k):
+ reached["n"] += 1
+ raise RuntimeError("reached the loader, which is all this asserts")
+
+ monkeypatch.setattr("datasets.load_dataset", _reached)
+
+ api_key = hf_token_arg("hf_explicit", allow_ambient_token = False)
+ with pytest.raises(Exception):
+ formatting.check_format_response(
+ CheckFormatRequest(dataset_name = "acme/not-cached"), api_key
+ )
+ assert reached["n"] > 0, "an uncached dataset was refused for nothing"
+
+ # Cached: the operator's disk can answer, so authorization is required again.
+ monkeypatch.setattr(dataset_cache, "dataset_cache_can_answer", lambda *_a, **_k: True)
+ reached["n"] = 0
+ with pytest.raises(HTTPException) as excinfo:
+ formatting.check_format_response(
+ CheckFormatRequest(dataset_name = "acme/cached-private"), api_key
+ )
+ assert excinfo.value.status_code == 404
+ assert reached["n"] == 0
+
+
+def test_the_dataset_cache_predicate_counts_both_caches(monkeypatch):
+ """`datasets` answers a streaming load from its own PREPARED cache, which is where the
+ measured leak was; the hub snapshot backs the file-level readers. Either can answer."""
+ from hub.utils import dataset_cache as dc
+
+ monkeypatch.setattr(dc, "latest_processed_dataset_cache_path", lambda *_a, **_k: None)
+ monkeypatch.setattr(dc, "latest_cached_dataset_snapshot", lambda *_a, **_k: None)
+ assert dc.dataset_cache_can_answer("acme/ds") is False
+
+ monkeypatch.setattr(dc, "latest_processed_dataset_cache_path", lambda *_a, **_k: Path("/x"))
+ assert dc.dataset_cache_can_answer("acme/ds") is True
+
+ monkeypatch.setattr(dc, "latest_processed_dataset_cache_path", lambda *_a, **_k: None)
+ monkeypatch.setattr(dc, "latest_cached_dataset_snapshot", lambda *_a, **_k: Path("/y"))
+ assert dc.dataset_cache_can_answer("acme/ds") is True
+
+ def _boom(*_a, **_k):
+ raise OSError("cache unreadable")
+
+ monkeypatch.setattr(dc, "latest_processed_dataset_cache_path", _boom)
+ assert dc.dataset_cache_can_answer("acme/ds") is True, "a failed check must not open the gate"
+
+
+def test_a_redirected_probe_does_not_authorize_the_repo_it_left(monkeypatch):
+ """get_session builds httpx.Client(follow_redirects=True), so the 3xx check never sees
+ the hop: a redirect to a login page returns a 200 that approved somewhere else."""
+ _hub_reachable(monkeypatch)
+ _patch_auth_check_get(
+ monkeypatch,
+ lambda *_a, **_k: SimpleNamespace(
+ status_code = 200,
+ raise_for_status = lambda: None,
+ url = "https://huggingface.co/login",
+ ),
+ )
+
+ assert cache_reads_authorized("hf_dummy", repo_id = "org/repo") is False
+
+
+def test_a_cache_only_caller_is_never_put_on_the_wire(monkeypatch):
+ """`local_files_only` and `prefer_local_cache` are promises, not hints. Both gates read
+ only the process env, so on a host with no offline variables they probed anyway: one Hub
+ round trip per cached repo in the /loras scan, for an answer neither branch would use."""
+ probes = _counting_probe(monkeypatch, True, offline = False)
+
+ assert model_config_module._offline_cache_read_refused("hf_dummy", "acme/m", "acme/m", True) is True
+
+
+ monkeypatch.setattr(dataset_cache, "dataset_cache_can_answer", lambda *_a, **_k: True)
+ with pytest.raises(HTTPException) as excinfo:
+ formatting.check_format_response(
+ CheckFormatRequest(dataset_name = "acme/ds", prefer_local_cache = True), "hf_dummy"
+ )
+ assert excinfo.value.status_code == 404
+ assert probes["n"] == 0
+
+
[email protected]("public, refused", [(True, False), (False, True)])
+def test_an_anonymous_caller_keeps_a_public_cached_dataset_and_loses_a_private_one(
+ monkeypatch, public, refused
+):
+ """Refused only under a declared offline env, which missed the case that matters: an
+ unreachable Hub is not a Hub declared absent, and `datasets` takes its prepared cache
+ either way. It cannot authorize itself, so ask whether the repo is public at all."""
+ # Answers only for the dataset endpoint: asking /api/models/<dataset id>/auth-check
+ # gets a 404 that reads as "private", which would refuse a public cached preview.
+ monkeypatch.setattr(
+ hf_tokens,
+ "_probe_repo_access",
+ lambda _repo, _token, repo_type: public and repo_type == "dataset",
+ )
+ _hub_reachable(monkeypatch)
+ monkeypatch.setattr(dataset_cache, "dataset_cache_can_answer", lambda *_a, **_k: True)
+
+ def _preview():
+ dataset_cache.refuse_unauthorized_dataset_preview(False, "acme/ds")
+
+ if refused:
+ with pytest.raises(HTTPException) as excinfo:
+ _preview()
+ assert excinfo.value.status_code == 404
+ else:
+ _preview()
+
+
+def test_the_public_probe_does_not_borrow_the_operators_login(monkeypatch):
+ """`build_hf_headers(token=None)` falls back to the ambient login, which would call
+ every private repo the operator can reach public. False is the value meaning none."""
+ _hub_reachable(monkeypatch)
+ seen: dict = {}
+
+ def _headers(*, token = "unset", **_k):
+ seen["token"] = token
+ return {}
+
+ monkeypatch.setattr("huggingface_hub.utils.build_hf_headers", _headers)
+ _patch_auth_check_get(monkeypatch, lambda *_a, **_k: _ok_auth_check_response())
+
+ assert hf_tokens.public_cache_read_authorized(repo_id = "acme/ds") is True
+ assert seen["token"] is False
+
+
+def test_the_public_verdict_takes_its_own_memo_key(monkeypatch):
+ """A public repo answers 200 for every token, so sharing one key would let any string
+ read back the anonymous verdict as its own authorization."""
+ verdicts = iter([True, False])
+ monkeypatch.setattr(hf_tokens, "_probe_repo_access", lambda *_a, **_k: next(verdicts))
+ _hub_reachable(monkeypatch)
+
+ assert hf_tokens.public_cache_read_authorized(repo_id = "acme/ds") is True
+ assert cache_reads_authorized("hf_dummy", repo_id = "acme/ds") is False
+
+
+def test_a_cached_alias_repo_is_authorized_in_its_own_right(monkeypatch):
+ """One decision from the base covered lookups answering with a DIFFERENT repo: an alias
+ or a derived `-GGUF` conversion. /auth-check returns 200 for any string on a public base,
+ so that decision is nearly free and hands back a cached private conversion."""
+ reachable = {"acme/base"}
+ monkeypatch.setattr(
+ hf_tokens,
+ "_probe_repo_access",
+ lambda repo_id, *_a, **_k: repo_id in reachable,
+ )
+ _hub_reachable(monkeypatch)
+ _st_resolver(
+ monkeypatch,
+ _cached_st_source = lambda _m: ("sentence-transformers/private-conversion", Path("/cache/snap")),
+ )
+
+ plan = settings_routes._resolve_embedding_model_plan("acme/base", "hf_dummy")
+
+ assert plan.cached is False, "the cached alias was never authorized"
+ assert plan.error, "with the alias withheld there is no artifact to offer"
+
+
+def test_the_gguf_listing_withholds_local_readiness_from_a_denied_caller(monkeypatch, tmp_path):
+ """A gated repo can serve file metadata publicly, so the lister succeeding is not
+ authorization. The cache-only and exception paths refuse that caller; the success path
+ walked the snapshots anyway and reported `downloaded`, which is the same fact."""
+ _one_cached_quant(monkeypatch, tmp_path)
+ _hub_reachable(monkeypatch)
+
+ def _answer(token):
+ return asyncio.run(gguf_variants.get_gguf_variants_answer("acme/gated", hf_token = token))
+
+ _counting_probe(monkeypatch, True)
+ assert _answer("hf_dummy").response.variants[0].downloaded is True
+ reset_repo_access_cache()
+ _counting_probe(monkeypatch, False)
+ answer = _answer("hf_dummy")
+ assert answer.response.variants[0].downloaded is False
+ assert answer.cache_authorized is False
+
+
+def test_the_context_length_lookup_honours_the_listings_refusal(monkeypatch):
+ """With no directory named the route falls back to the bare repo id, and reading that
+ walks every local cache. The one local fact the service cannot suppress, so the answer
+ carries the verdict out to it."""
+ from models.models import GgufVariantsResponse as ServiceResponse
+
+ reads: list = []
+ monkeypatch.setattr(
+ models_routes,
+ "_read_native_context_length",
+ lambda model, *, is_local: reads.append(model) or 8192,
+ )
+
+ async def _denied(repo_id, **_k):
+ return gguf_variants.VariantsAnswer(
+ ServiceResponse(repo_id = repo_id, variants = [], has_vision = False),
+ None,
+ False,
+ )
+
+ monkeypatch.setattr(gguf_variants, "get_gguf_variants_answer", _denied)
+ monkeypatch.setattr(gguf_variants, "pinned_snapshot_for_request", lambda *_a, **_k: None)
+
+ result = asyncio.run(
+ models_routes.get_gguf_variants(
+ repo_id = "acme/gated", hf_token = "hf_dummy", current_subject = "alice"
+ )
+ )
+
+ assert result.context_length is None
+ assert reads == [], "the cache walk ran for a caller the listing had just refused"
+
+
+def test_every_scan_target_is_authorized_not_only_the_one_named(monkeypatch):
+ """The scan expands to the adapter's base, native-audio dependencies and auto_map repos
+ and downloads each with the same token, falling back to their cached configs and Python
+ files. Refused, not dropped: an unscanned base would under-report has_remote_code."""
+ reachable = {"acme/adapter"}
+ monkeypatch.setattr(
+ hf_tokens,
+ "_probe_repo_access",
+ lambda repo_id, *_a, **_k: repo_id in reachable,
+ )
+ _hub_reachable(monkeypatch)
+ monkeypatch.setattr(models_routes, "_repo_in_any_hf_cache", lambda *_a, **_k: True)
+ # config.json cached, which is what makes the scan answerable off disk.
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda **_k: "/cache/config.json")
+ monkeypatch.setattr(
+ "core.inference.native_audio.native_audio_security_targets",
+ lambda target, **_k: [target, "acme/private-base"],
+ )
+
+ assert _scan_refused("acme/adapter") == 404
+
+
+def test_the_embedding_resolver_gates_the_base_repo_too(monkeypatch):
+ """The per-candidate check answers for an alias or a derived conversion, and defers to
+ the base decision when the cache answered under the requested id itself. That leg is the
+ one the base decision still owns, so it needs its own row."""
+ _counting_probe(monkeypatch, False, offline = False)
+ _st_resolver(monkeypatch, _cached_st_source = lambda m: (m, Path("/cache/snap")))
+
+ plan = settings_routes._resolve_embedding_model_plan("acme/private", "hf_dummy")
+
+ assert plan.cached is False, "the operator's cached copy was reported to a denied caller"
+
+
+def test_the_embedding_resolver_does_not_probe_before_a_cache_lookup(monkeypatch):
+ """Every cache lookup in the resolver is authorized against the repo it actually matched,
+ so gating the lookups on the requested id as well bought nothing and cost a /auth-check on
+ every resolve, including the local and sentence-transformers paths that never read the GGUF
+ cache. The probe is bounded at 10s against a 20s resolver deadline, so it was half the
+ budget spent to reach a miss."""
+ probes = _counting_probe(monkeypatch, True, offline = False)
+ _st_resolver(monkeypatch, _local_sentence_transformer_is_present = lambda _m: True)
+
+ plan = settings_routes._resolve_embedding_model_plan("acme/local-st", "hf_dummy")
+
+ assert plan.cached is True
+ assert probes["n"] == 0, "a local sentence-transformers hit still probed the Hub"
+
+
+def test_the_scan_is_refused_before_it_expands_its_targets(monkeypatch):
+ """The per-target check inside the loop cannot stand in for this one. Target expansion
+ resolves the adapter's base and its native-audio dependencies, which reads the cache and
+ talks to the Hub with the caller's token, so the primary has to be refused ahead of it."""
+ _counting_probe(monkeypatch, False, offline = False)
+ monkeypatch.setattr(models_routes, "_repo_in_any_hf_cache", lambda *_a, **_k: True)
+ # config.json cached, which is what makes the scan answerable off disk.
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda **_k: "/cache/config.json")
+
+ def _must_not_run(*_a, **_k):
+ raise AssertionError("target expansion ran for a caller that was already refused")
+
+ monkeypatch.setattr("core.inference.native_audio.native_audio_security_targets", _must_not_run)
+
+ assert _scan_refused("acme/private") == 404
+
+
+def test_local_only_audio_detection_refuses_without_asking(monkeypatch):
+ """The twin of the vision gate, and its own call site. /loras drives this one with
+ local_files_only=True over every adapter it finds, so an unentitled caller must be told
+ no from the disk state alone, without a probe and without a cached answer."""
+ probes = _counting_probe(monkeypatch, True, offline = False)
+ monkeypatch.setattr(model_config_module, "_env_offline", lambda: False)
+
+ audio_type, definitive = model_config_module.detect_audio_type_checked(
+ "acme/private-audio", hf_token = "hf_dummy", local_files_only = True
+ )
+
+ assert (audio_type, definitive) == (None, False)
+ assert probes["n"] == 0
+
+
[email protected]("public", [True, False])
+def test_an_anonymous_caller_keeps_a_cached_public_gguf(monkeypatch, tmp_path, public):
+ """The same rule the chat template needed, at the site that still asked the raw
+ question. The sentinel can never authorize itself, so a downloaded public quant was
+ reported as absent and a cache-only listing fell through to the network."""
+ _one_cached_quant(monkeypatch, tmp_path)
+ monkeypatch.setattr(hf_tokens, "_probe_repo_access", lambda *_a, **_k: public)
+ _hub_reachable(monkeypatch)
+
+ answer = asyncio.run(gguf_variants.get_gguf_variants_answer("acme/repo", hf_token = False))
+
+ assert answer.response.variants[0].downloaded is public
+ assert answer.cache_authorized is public
+
+
+def test_the_safetensors_fallback_authorizes_the_repo_it_found(monkeypatch):
+ """The GGUF branch was gated and this one was not: after the remote probes come back
+ empty, the plan reads the operator's snapshot and reports the repo it is filed under as
+ cached, which is how a denied caller discovers and then force-saves private weights."""
+ _counting_probe(monkeypatch, False, offline = False)
+ _gguf_resolver(monkeypatch)
+ monkeypatch.setattr(settings_routes, "_remote_embedding_gguf_plan", lambda *_a, **_k: None)
+ monkeypatch.setattr(settings_routes, "_search_hub_for_gguf", lambda *_a, **_k: None)
+ monkeypatch.setattr(settings_routes, "_sentence_transformers_fallback_allowed", lambda _m: True)
+ monkeypatch.setattr(
+ settings_routes, "_safetensors_plan", lambda *_a, **_k: ("acme/private-st", [])
+ )
+ reported: list = []
+ monkeypatch.setattr(
+ settings_routes,
+ "_cached_snapshot_has_st_weights",
+ lambda repo: reported.append(repo) or True,
+ )
+
+ plan = settings_routes._resolve_embedding_model_plan("acme/private", "hf_dummy")
+
+ assert plan.download_repo is None, "a denied caller was pointed at the private weights"
+ assert plan.error, "with the snapshot withheld there is no artifact to offer"
+ assert reported == [], "the cache was consulted for a repo nothing had authorized"
+
+
+def test_the_config_memo_is_rechecked_before_it_is_served(monkeypatch):
+ """The memo is untimed and was read before the authorization check, so a token revoked
+ after one successful online fetch kept its answer for the life of the process, outliving
+ the TTL that exists to end exactly that."""
+ _hub_reachable(monkeypatch)
+ key = transformers_version._token_cache_key("acme/private", "hf_dummy")
+ monkeypatch.setitem(transformers_version._config_json_cache, key, {"model_type": "llama"})
+
+ monkeypatch.setattr(hf_tokens, "_probe_repo_access", lambda *_a, **_k: True)
+ assert transformers_version._load_config_json("acme/private", "hf_dummy") == {"model_type": "llama"}
+
+ reset_repo_access_cache()
+ monkeypatch.setattr(hf_tokens, "_probe_repo_access", lambda *_a, **_k: False)
+ monkeypatch.setattr(transformers_version, "_env_offline", lambda: True)
+ assert transformers_version._load_config_json("acme/private", "hf_dummy") is None, "revoked token kept the memo"
+
+
+def test_the_inner_preview_gate_does_not_veto_the_outer_one(monkeypatch):
+ """Two gates on the same request, and only the outer one was public-aware, so the
+ anonymous sentinel cleared the guard and was then refused by the reader behind it:
+ a prefer-local request answered local-cache-miss for a public dataset on disk."""
+ monkeypatch.setattr(hf_tokens, "_probe_repo_access", lambda *_a, **_k: True)
+ _hub_reachable(monkeypatch)
+ monkeypatch.setattr(formatting, "_load_cached_hf_preview_slice", lambda *_a, **_k: ("ROWS", 3))
+
+ served = formatting._load_any_cached_hf_preview_slice(
+ SimpleNamespace(dataset_name = "acme/public"), 5, False
+ )
+
+ assert served == ("ROWS", 3), "a public cached preview was withheld from the sentinel"
+
+
+def test_the_gguf_partial_state_is_withheld_with_the_rest(monkeypatch, tmp_path):
+ """The snapshot walk was gated and the partial-download accounting beside it was not,
+ so a caller who can list a gated repo's public metadata still learned the operator had
+ an interrupted download: `partial`, its transport, and the bytes left to fetch."""
+ reads: list = []
+ _one_cached_quant(monkeypatch, tmp_path, complete = False)
+ monkeypatch.setattr(
+ gguf_variants.download_registry,
+ "incomplete_blob_hashes",
+ lambda *_a, **_k: reads.append("registry") or {"deadbeef"},
+ )
+ monkeypatch.setattr(
+ gguf_variants,
+ "_local_main_gguf_blobs_by_quant",
+ lambda *_a, **_k: reads.append("blobs") or {},
+ )
+ monkeypatch.setattr(
+ gguf_variants.hf_cache_scan,
+ "is_variant_partial",
+ lambda *_a, **_k: reads.append("manifest") or True,
+ )
+ monkeypatch.setattr(hf_tokens, "_probe_repo_access", lambda *_a, **_k: False)
+ _hub_reachable(monkeypatch)
+
+ answer = asyncio.run(gguf_variants.get_gguf_variants_answer("acme/gated", hf_token = "hf_dummy"))
+ variant = answer.response.variants[0]
+
+ assert variant.partial is False
+ assert reads == [], "the operator's download state was read for a refused caller"
+
+
+def test_a_repo_directory_is_not_a_cached_template(monkeypatch):
+ """The predicate asks what the read could actually be served, which is one file. A repo
+ cached for its weights alone holds no template, so refusing there protects nothing and
+ costs an authorized caller the copy the Hub still has, whenever the probe is merely
+ unavailable: a mirror without /auth-check, one transient failure."""
+ _counting_probe(monkeypatch, False, offline = False)
+ _picker_env(monkeypatch, no_snapshots = True)
+ # A snapshot is here, the template file is not.
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda **_k: None)
+ downloads: list = []
+
+ class _Api:
+ def __init__(self, *_a, **_k):
+ pass
+
+ def get_paths_info(self, _repo, paths, *_a, **_k):
+ return [SimpleNamespace(path = paths[0], size = 1024)]
+
+ def _download(*a, **k):
+ downloads.append(a)
+ raise FileNotFoundError("reaching the download is what this asserts")
+
+ monkeypatch.setattr("huggingface_hub.HfApi", _Api)
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", _download)
+
+ assert picker_service.read_default_chat_template("org/repo", "hf_dummy") is None
+ assert downloads, "a template the repo does not hold cached was refused anyway"
+
+
+def test_the_transformers_cache_key_separates_the_caller_classes():
+ """The qualifier reached three fingerprints and missed this one. The tokenizer and
+ config-tier caches keyed here return before any authorization check, so a UI session
+ populating one handed its verdict to an API caller with the same token text."""
+ ui = hf_token_arg("hf_saved", allow_ambient_token = True)
+ api = hf_token_arg("hf_saved", allow_ambient_token = False)
+
+ assert _token_cache_key("acme/m", ui) != _token_cache_key("acme/m", api)
+ assert "hf_saved" not in str(_token_cache_key("acme/m", ui))
+ # The values that already had their own slots keep them.
+ assert _token_cache_key("acme/m", False) == ("acme/m", ANONYMOUS_CACHE_IDENTITY)
+ assert _token_cache_key("acme/m", None) == ("acme/m", None)
+
+
+def test_a_resolved_gguf_plan_does_not_report_an_unauthorized_cache(monkeypatch):
+ """A gated repo can publish its filenames, so a plan coming back is not permission to
+ report the operator's copy of it, and the repo the plan names need not be the one the
+ caller asked about."""
+ _counting_probe(monkeypatch, False, offline = False)
+ _gguf_resolver(monkeypatch)
+ monkeypatch.setattr(
+ settings_routes,
+ "_remote_embedding_gguf_plan",
+ lambda *_a, **_k: ("acme/private-GGUF", ["model-Q4_K_M.gguf"]),
+ )
+ reported: list = []
+ monkeypatch.setattr(
+ settings_routes,
+ "_cached_embedding_gguf_files",
+ lambda repo, files: reported.append(repo) or True,
+ )
+ monkeypatch.setattr(settings_routes, "_hf_files_size", lambda *_a, **_k: 1)
+
+ plan = settings_routes._resolve_embedding_model_plan("acme/private", "hf_dummy")
+
+ assert plan.cached is not True, "the operator's cached GGUF was reported to a denied caller"
+ assert reported == [], "the cache was consulted for a repo nothing had authorized"
+
+
+def test_a_weights_only_cache_does_not_block_the_scan(monkeypatch):
+ """config.json, not the repo directory: has_remote_code comes from its auto_map and the
+ Python files are reached through it, so a snapshot holding only weights can answer
+ nothing. Refusing it cost a valid token the scan a mirror would have served, in exactly
+ the case the probe is unavailable rather than negative."""
+ _counting_probe(monkeypatch, False, offline = False)
+ monkeypatch.setattr(models_routes, "_repo_in_any_hf_cache", lambda *_a, **_k: True)
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda **_k: None)
+
+ reached: list = []
+ monkeypatch.setattr(
+ "core.inference.native_audio.native_audio_security_targets",
+ lambda target, **_k: reached.append(target) or [target],
+ )
+
+ try:
+ asyncio.run(
+ models_routes.scan_model_remote_code(
+ model_name = "acme/weights-only",
+ hf_token = "hf_dummy",
+ allow_ambient_token = False,
+ current_subject = "alice",
+ )
+ )
+ except Exception:
+ # Whatever the scan does next needs the network; getting there is the assertion.
+ pass
+
+ assert reached == ["acme/weights-only"], "a weights-only cache was treated as an answer"
+
+
+def test_an_external_auto_map_repo_is_authorized_before_it_is_scanned(monkeypatch):
+ """auto_map repos are read out of the primary's config, so they are discovered after the
+ target loop has authorized what it knew. The preflight downloads and scans each one with
+ the same token, and its cached Python files reach the response as source snippets."""
+ reachable = {"acme/adapter"}
+ monkeypatch.setattr(
+ hf_tokens, "_probe_repo_access", lambda repo_id, *_a, **_k: repo_id in reachable
+ )
+ _hub_reachable(monkeypatch)
+ monkeypatch.setattr(models_routes, "_repo_in_any_hf_cache", lambda *_a, **_k: True)
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", lambda **_k: "/cache/config.json")
+ monkeypatch.setattr(
+ "core.inference.native_audio.native_audio_security_targets",
+ lambda target, **_k: [target],
+ )
+ monkeypatch.setattr(
+ "utils.security.remote_code_scan.external_auto_map_repos",
+ lambda *_a, **_k: ["acme/private-code"],
+ )
+
+ assert _scan_refused("acme/adapter") == 404
+
+
+def test_the_cached_alias_is_looked_up_before_the_literal_name_is_judged(monkeypatch):
+ """A slashless alias caches under sentence-transformers/, so gating the lookup on the
+ literal name's verdict skipped it entirely when that name has no repo to authorize, and
+ a public alias already fully cached came back as a download to run."""
+ reachable = {"sentence-transformers/all-MiniLM-L6-v2"}
+ monkeypatch.setattr(
+ hf_tokens, "_probe_repo_access", lambda repo_id, *_a, **_k: repo_id in reachable
+ )
+ _hub_reachable(monkeypatch)
+ _st_resolver(
+ monkeypatch,
+ _cached_st_source = lambda _m: ("sentence-transformers/all-MiniLM-L6-v2", Path("/cache/snap")),
+ )
+
+ plan = settings_routes._resolve_embedding_model_plan("all-MiniLM-L6-v2", "hf_dummy")
+
+ assert plan.cached is True, "a cached, authorized alias was offered as a download"
+ assert plan.download_repo == "sentence-transformers/all-MiniLM-L6-v2"
+
+
+ "endpoint, final_url, authorized",
+ [
+ # httpx lower-cases the host and drops an explicit default port while HF_ENDPOINT
+ # keeps its spelling, so comparing the strings denied these mirrors outright.
+ (
+ "https://HF-MIRROR.example",
+ "https://hf-mirror.example/api/models/org/repo/auth-check",
+ True,
+ ),
+ (
+ "https://mirror.example:443",
+ "https://mirror.example/api/models/org/repo/auth-check",
+ True,
+ ),
+ ("https://mirror.example", "https://mirror.example/api/models/org/repo/auth-check/", True),
+ # Still not the target we asked about.
+ ("https://mirror.example", "https://mirror.example/login", False),
+ ("https://mirror.example", "https://mirror.example/api/models/org/other/auth-check", False),
+ # Same path, but a query is where a login hand-off hides.
+ (
+ "https://mirror.example",
+ "https://mirror.example/api/models/org/repo/auth-check?next=login",
+ False,
+ ),
+ ],
+ ids = [
+ "uppercase-host",
+ "default-port",
+ "trailing-slash",
+ "login-page",
+ "other-repo",
+ "query-added",
+ ],
+)
+def test_the_probe_compares_targets_not_spellings(monkeypatch, endpoint, final_url, authorized):
+ """A 200 only counts when it came from the repo that was asked about, and the client
+ is free to rewrite the parts of a URL that carry no meaning."""
+ _hub_reachable(monkeypatch)
+ monkeypatch.setenv("HF_ENDPOINT", endpoint)
+ _patch_auth_check_get(
+ monkeypatch,
+ lambda *_a, **_k: SimpleNamespace(
+ status_code = 200, raise_for_status = lambda: None, url = final_url
+ ),
+ )
+
+ assert cache_reads_authorized("hf_dummy", repo_id = "org/repo") is authorized
+
+
+def test_a_recorded_redirect_is_refused_whatever_the_final_url(monkeypatch):
+ """The direct signal, for the clients that keep it: any hop at all means the answer
+ came from somewhere other than the endpoint the memo is keyed on."""
+ _hub_reachable(monkeypatch)
+ _patch_auth_check_get(
+ monkeypatch,
+ lambda *_a, **_k: SimpleNamespace(
+ status_code = 200,
+ raise_for_status = lambda: None,
+ history = [SimpleNamespace(status_code = 302)],
+ ),
+ )
+
+ assert cache_reads_authorized("hf_dummy", repo_id = "org/repo") is False
+
+
+ "cached_name", ["config.json", "tokenizer_config.json", "video_preprocessor_config.json"]
+)
+def test_the_scan_predicate_covers_every_config_the_scanner_reads(monkeypatch, cached_name):
+ """auto_map is declared in any of REMOTE_CODE_CONFIG_FILES, so asking about config.json
+ alone let four of the five open the gate. The lookup also has to name the cache the
+ scanner's own downloads pass, or it asks the library default about a read that happens
+ in the operator's chosen root."""
+ seen: list = []
+ _counting_probe(monkeypatch, False, offline = False)
+ monkeypatch.setattr(models_routes, "_repo_in_any_hf_cache", lambda *_a, **_k: True)
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.active_hf_hub_cache", lambda: Path("/studio/cache")
+ )
+
+ def _lookup(
+ *,
+ repo_id,
+ filename,
+ cache_dir = None,
+ **_k,
+ ):
+ seen.append((filename, str(cache_dir)))
+ return "/studio/cache/hit" if filename == cached_name else None
+
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", _lookup)
+
+ assert _scan_refused("acme/private") == 404
+ assert all(root == "/studio/cache" for _n, root in seen), "asked the wrong cache root"
+
+
+def test_the_template_predicate_asks_the_active_cache(monkeypatch):
+ """The download names active_hf_hub_cache(), so a predicate that omits it reports a miss
+ for a template living only in the operator's chosen root and opens the gate on it."""
+ roots: list = []
+ _counting_probe(monkeypatch, False, offline = False)
+ _picker_env(monkeypatch, no_snapshots = True)
+ monkeypatch.setattr(picker_service, "active_hf_hub_cache", lambda: Path("/studio/cache"))
+
+ def _lookup(
+ *,
+ repo_id,
+ filename,
+ cache_dir = None,
+ **_k,
+ ):
+ roots.append(str(cache_dir))
+ return "/studio/cache/template.jinja"
+
+ monkeypatch.setattr("huggingface_hub.try_to_load_from_cache", _lookup)
+ downloads: list = []
+
+ class _Api:
+ def __init__(self, *_a, **_k):
+ pass
+
+ def get_paths_info(self, _repo, paths, *_a, **_k):
+ return [SimpleNamespace(path = paths[0], size = 1024)]
+
+ monkeypatch.setattr("huggingface_hub.HfApi", _Api)
+ monkeypatch.setattr(
+ "huggingface_hub.hf_hub_download", lambda *a, **k: downloads.append(a) or "/x"
+ )
+
+ assert picker_service.read_default_chat_template("org/private", "hf_dummy") is None
+ assert roots and all(r == "/studio/cache" for r in roots), "asked the wrong cache root"
+ assert not downloads, "a template cached in the active root was served to a denied caller"
+
+
+def test_a_tokenless_api_caller_keeps_a_public_cached_embedder(monkeypatch):
+ """The sentinel cannot authorize itself, so the raw check refused it whatever the repo
+ was: an online resolve offered a multi-gigabyte download of something already on disk."""
+ monkeypatch.setattr(hf_tokens, "_probe_repo_access", lambda *_a, **_k: True)
+ _hub_reachable(monkeypatch)
+ _st_resolver(monkeypatch, _cached_st_source = lambda m: (m, Path("/cache/snap")))
+
+ plan = settings_routes._resolve_embedding_model_plan("acme/public-embed", False)
+
+ assert plan.cached is True, "a public cached embedder was offered as a download"
+
+
+def test_a_local_only_config_read_stays_off_the_wire(monkeypatch):
+ """local_files_only is a contract. The guard tested the caller's flag and did not
+ forward it, so the read it protects dialled /auth-check anyway."""
+ probes = _counting_probe(monkeypatch, True, offline = False)
+ monkeypatch.setattr(model_config_module, "_config_json_already_cached", lambda *_a, **_k: True)
+
+ with pytest.raises(OSError):
+ model_config_module.load_model_config("acme/private", token = "hf_dummy", local_files_only = True)
+
+ assert probes["n"] == 0
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index 1fc63ef6d2e..9c178c38b28 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -18,8 +18,11 @@ from utils.paths import (
)
from hub.utils.hf_tokens import (
ANONYMOUS_CACHE_IDENTITY,
+ cached_read_refused,
+ qualify_cache_identity,
HfTokenArg,
apply_token_to_child_env,
+ cache_reads_authorized,
is_anonymous,
normalize_token,
)
@@ -574,6 +577,22 @@ def load_model_config(
**revision_kwargs,
)
+ if (
+ isinstance(token, str)
+ and token
+ and not is_local_path(model_name)
+ and cached_read_refused(
+ token,
+ repo_id = model_name,
+ is_cached = lambda: _config_json_already_cached(model_name, revision),
+ # The caller's own cache-only contract, forwarded: without it a
+ # local_files_only read still dialled /auth-check and could stall for the
+ # probe timeout, which is the one thing that kind of read promises not to do.
+ offline = bool(local_files_only),
+ )
+ ):
+ raise OSError(f"config.json for {model_name} is not available to an unauthorized caller")
+
if token:
return AutoConfig.from_pretrained(
model_name,
@@ -807,6 +826,15 @@ def _raw_config_has_vision_config(
}
if revision is not None:
download_kwargs["revision"] = revision
+ # Measured: hf_hub_download falls back to the cache even with
+ # local_files_only=False, never consulting the credential, so a planted entry
+ # plus a dead endpoint returns a private config.json to a token that cannot read it.
+ if cached_read_refused(
+ hf_token,
+ repo_id = model_name,
+ is_cached = lambda: _config_json_already_cached(model_name, revision),
+ ):
+ return None
config_path = Path(hf_hub_download(**download_kwargs))
config = json.loads(config_path.read_text(encoding = "utf-8-sig"))
architectures = config.get("architectures") or []
@@ -834,6 +862,39 @@ def _raw_config_has_vision_config(
# why: inline _is_vlm and constants are prepended so the subprocess stays self-contained
# and doesn't import the parent module graph. Built on demand to defer the registry read.
+def _offline_cache_read_refused(hf_token, model_name: str, repo_id: str, offline: bool) -> bool:
+ """Offline the capability probes read the cache and never authorize, so an unentitled
+ caller is not put back on the wire by local_files_only being False. A local path the
+ caller named itself is not the Hub cache and stays available.
+
+ ``offline`` is forwarded, not just tested: else a local_files_only call on a host with no
+ offline env probes anyway, once per repo, which is what it promises not to do.
+ """
+ return (
+ offline
+ and not is_local_path(model_name)
+ and not cache_reads_authorized(hf_token, repo_id = repo_id, offline = offline)
+ )
+
+
+def _config_json_already_cached(model_name: str, revision: Optional[str] = None) -> bool:
+ """True if this repo's config.json is on disk, so an unauthorized read could be served it."""
+ try:
+ from huggingface_hub import try_to_load_from_cache
+ hit = try_to_load_from_cache(
+ repo_id = model_name,
+ filename = "config.json",
+ revision = revision,
+ cache_dir = active_hf_hub_cache(),
+ )
+ # Also returns a sentinel object recording a known-absent file; only a str is a real hit.
+ return isinstance(hit, str)
+ except Exception as exc:
+ # Never let the guard's own failure open the path it guards.
+ logger.debug("Could not check cached config.json for '%s': %s", model_name, exc)
+ return True
+
+
def _build_vision_check_inline_helpers() -> str:
vlm_types, vlm_classes, audio_types = _detection_sets()
return (
@@ -1061,7 +1122,7 @@ def _token_fingerprint(token: HfTokenArg) -> Optional[str]:
return ANONYMOUS_CACHE_IDENTITY
if token is None:
return None
- return hashlib.sha256(token.encode("utf-8")).hexdigest()
+ return qualify_cache_identity(token, hashlib.sha256(token.encode("utf-8")).hexdigest())
# Scoped to a request, not cached: a repo gated or deleted between requests is seen on the next.
@@ -1197,9 +1258,10 @@ def is_vision_model(
resolved_name = model_name
# Key on effective offline (kwarg OR env) so an offline probe can't poison a later lookup.
effective_offline = bool(local_files_only or _env_offline())
- # Offline the probe reads the cache and never authorizes, so local_files_only=False
- # does not put an anonymous caller back on the wire. It gets the default instead.
- if effective_offline and is_anonymous(hf_token) and not is_local_path(model_name):
+ # The ONLINE fallback is guarded inside _raw_config_has_vision_config, where a cached
+ # file can actually be served; gating the whole call would deny a legitimate token its
+ # answer on any Hub hiccup, for a repo with nothing to leak.
+ if _offline_cache_read_refused(hf_token, model_name, resolved_name, effective_offline):
return False
cache_key: _CapabilityCacheKey = (
resolved_name,
@@ -1420,9 +1482,7 @@ def detect_audio_type_checked(
# Key on effective offline (kwarg OR env) so an offline negative can't poison a later probe.
effective_offline = bool(local_files_only or _env_offline())
- # Offline the probe reads the cache and never authorizes, so local_files_only=False
- # does not put an anonymous caller back on the wire. Inconclusive for it instead.
- if effective_offline and is_anonymous(hf_token) and not is_local_path(model_name):
+ if _offline_cache_read_refused(hf_token, model_name, model_name, effective_offline):
return None, False
local_fingerprint = (
_local_audio_metadata_fingerprint(model_name) if is_local_path(model_name) else None
@@ -1556,7 +1616,11 @@ def _detect_audio_from_tokenizer(
else:
# Read before any network branch and never authorizes, so it would serve a
# cached private repo's audio tokens online as well as offline.
- repo_dir = None if is_anonymous(hf_token) else get_cache_path(model_name)
+ repo_dir = (
+ get_cache_path(model_name)
+ if cache_reads_authorized(hf_token, repo_id = model_name)
+ else None
+ )
if repo_dir is not None and repo_dir.is_dir():
snapshots_dir = repo_dir / "snapshots"
if snapshots_dir.is_dir() and revision is None:
@@ -3361,13 +3425,14 @@ def is_embedding_model(model_name: str, hf_token: Optional[str] = None) -> bool:
# online lookup can memoize True from tags with no weights cached, and a cached negative can
# be invalidated by later materialization. The cache probe is local-only, so it's cheap.
if not is_local_path(model_name) and hf_env_offline():
- # The marker is read off the HF cache and never authorizes. Offline this caller
- # cannot establish access, so it reports the default rather than the cache.
- if is_anonymous(hf_token):
+ # The marker never authorizes, so offline an unverified token reports the default.
+ if not cache_reads_authorized(hf_token, repo_id = model_name):
return False
return _embedding_marker_in_hf_cache(model_name)
- cache_key = (model_name, hf_token)
+ # Fingerprinted, not the raw token: the marker is a str subclass equal to a plain token
+ # of the same value, so a UI-computed classification was served to an API caller.
+ cache_key = (model_name, _token_fingerprint(hf_token))
if cache_key in _embedding_detection_cache:
return _embedding_detection_cache[cache_key]
@@ -3402,7 +3467,7 @@ def is_embedding_model(model_name: str, hf_token: Optional[str] = None) -> bool:
except Exception as e:
# Timeout or transient network error: fall back to the local cache marker, don't hard-fail.
logger.warning(f"Could not determine if {model_name} is embedding model: {e}")
- if is_anonymous(hf_token):
+ if not cache_reads_authorized(hf_token, repo_id = model_name):
# The anonymous 404 lands here too, and the marker read never authorizes.
return False
is_emb = _embedding_marker_in_hf_cache(model_name)
diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.py
index 9e0f614939f..881b068c668 100644
--- a/studio/backend/utils/transformers_version.py
+++ b/studio/backend/utils/transformers_version.py
@@ -49,7 +49,9 @@ from hub.utils.hf_tokens import (
ANONYMOUS_CACHE_IDENTITY,
HfTokenArg,
apply_token_to_child_env,
+ cache_reads_authorized,
is_anonymous,
+ qualify_cache_identity,
)
from utils.native_path_leases import child_env_without_native_path_secret
from utils.native_tls import inline_gate_source, vendor_dir
@@ -675,14 +677,19 @@ def _token_cache_key(model_name: str, hf_token: HfTokenArg) -> tuple[str, str |
"""Cache key that keeps authenticated and unauthenticated reads separate, so an
unauthenticated miss on a gated/private repo never poisons a later authed lookup.
- Forced-anonymous is its own credential, so it takes its own slot too.
+ Forced-anonymous is its own credential, so it takes its own slot too, and so is a UI
+ session: the marker hashes to the same bytes as a plain token of the same value, and the
+ tokenizer and config-tier caches keyed here return before any authorization check, so
+ without the qualifier an API caller reads back the classification a UI session cached.
"""
import hashlib
if is_anonymous(hf_token):
return (model_name, ANONYMOUS_CACHE_IDENTITY)
- tok = hashlib.sha256(hf_token.encode()).hexdigest()[:16] if hf_token else None
- return (model_name, tok)
+ if not hf_token:
+ return (model_name, None)
+ digest = hashlib.sha256(hf_token.encode()).hexdigest()[:16]
+ return (model_name, qualify_cache_identity(hf_token, digest))
def _is_canonical_repo_id(model_name: str) -> bool:
@@ -902,10 +909,20 @@ def _load_config_json(model_name: str, hf_token: str | None = None) -> dict | No
network fetch, so an online read never serves stale metadata.
"""
cache_key = _token_cache_key(model_name, hf_token)
+ local_cfg = Path(model_name) / "config.json"
if cache_key in _config_json_cache:
- return _config_json_cache[cache_key]
+ # A hit predates the 60 s authorization TTL, so an explicit token revoked since the
+ # fetch would keep reading this repo's metadata for the life of the process. Local
+ # paths are the caller's own and never went through the Hub. A miss here re-fetches,
+ # which is what tells a revoked token no.
+ if (
+ not isinstance(hf_token, str)
+ or _safe_is_file(local_cfg)
+ or _safe_is_dir(Path(model_name))
+ or cache_reads_authorized(hf_token, repo_id = model_name)
+ ):
+ return _config_json_cache[cache_key]
- local_cfg = Path(model_name) / "config.json"
if _safe_is_file(local_cfg):
try:
with open(local_cfg, encoding = "utf-8-sig") as f:
@@ -924,18 +941,19 @@ def _load_config_json(model_name: str, hf_token: str | None = None) -> dict | No
# Every route to the hub cache below reads it without authorizing, so a caller denied
# the ambient credential is refused them all: keying the memo apart is not enough when
# the value it memoizes came off disk in the first place.
- if is_anonymous(hf_token):
- cache_denied = True
- else:
- cache_denied = False
+ cache_denied = not cache_reads_authorized(hf_token, repo_id = model_name)
if _env_offline():
# No network: a downloaded repo can still tier from the hub cache. Cache a real hit,
- # never the miss, so a later online read still fetches the config.
+ # never the miss, so a later online read still fetches the config. An unverified
+ # explicit token is denied here; ambient None keeps the cache path.
if cache_denied:
return None
cfg = _config_json_from_hf_cache(model_name)
- if cfg is not None:
+ # Ambient/anonymous only: this came off the operator's disk, and an untimed memo
+ # outlives the 60 s cache_reads_authorized grants it, so a revoked token would keep
+ # reading. Explicit tokens re-derive per call.
+ if cfg is not None and not isinstance(hf_token, str):
_config_json_cache[cache_key] = cfg
return cfg