Repository navigation
Studio: verify Hub credentials before cache-backed reads - #10264
danielhanchen merged 53 commits into
Conversation
unslothai#10076 keyed disk-cache gates on is_anonymous, which is only true when the caller sent no token. An API key that sent any token-shaped string took the same fast paths as the operator: dataset previews, chat templates, config and audio probes, and GGUF listings. Authorize those reads with one helper. Ambient None still uses the host cache. The sentinel still does not. An explicit token is allowed only after it can reach the named repository, with the answer memoized briefly so the extra Hub round trip is not paid on every request.
The cache-authorization check ran after `import datasets`, so a denied caller still 500ed on hosts without that dependency. Decide first.
cache_reads_authorized probes repo access before seed inspect continues. The caller-boundary test only checks that an explicit token is forwarded, so stub the probe as authorized.
|
Confirmed the gate in studio/backend/utils/transformers_version.py and formatting.py still keys on the sentinel alone, so an API-key token does take the disk fast paths today, and this closes that. One thing before I review: the repo_info probe cannot succeed with no network, so an explicit token offline now falls to denied in is_embedding_model and _load_config_json, could you confirm what should happen on that path? |
When the Hub is offline, an explicit token may use cache-backed reads only if a recent online repo_info probe is still memoized. Otherwise deny (fail closed) so token-shaped API-key strings cannot read the host cache.
Keep the repo_info probe assertions independent of HF_HUB_OFFLINE in the environment so fail-closed offline behavior cannot skip the online cases.
|
On the offline explicit-token path: fail closed. When the Hub is offline, Who keeps working offline:
Documented in |
|
Confirmed a remaining gated-cache bypass on 4e3be38. |
repo_info returns gated public metadata even with an invalid token, so an explicit credential could still be served from the host cache. auth_check 401s that case while still allowing public repos.
|
@Imagineer99 Thanks — that gated-cache bypass with Pushed a follow-up that swaps the probe in Regression coverage is in
|
load_model_config now refuses unverified explicit tokens before AutoConfig.from_pretrained; patch cache_reads_authorized in the token-bearing trust_remote_code tests.
|
One remaining issue: no timeout on A/B proof: the previous probe failed safely after about 10 seconds. The current probe remained blocked beyond 13 seconds and required termination. The same result occurred across Ubuntu, macOS, and Windows. Proposed fix: retain |
The redirect check compared response.url to the URL it built as raw strings. httpx canonicalises: measured on 0.28.1, it lower-cases the host and drops an explicit :443, while HF_ENDPOINT keeps whatever spelling the operator wrote. So a mirror configured as HF-MIRROR.example or with the default port spelled out had every 200 read as a redirect and every explicit-token cache read denied, which is the third mirror-shaped failure this probe has had. Now refuses on a recorded redirect history first, which is the direct signal, and otherwise compares scheme, host, port and path as parts. Query included: the path alone would let a login hand-off at ?next= through. Four mutations, each red, including one that drops the query from the compare.
Two of these are holes the last two rounds opened. Narrowing a predicate only protects what the narrowed version actually covers, and both narrowings covered less than the reader does: - The scan predicate asked about config.json in the library-default cache. The scanner reads auto_map from any of REMOTE_CODE_CONFIG_FILES and every download it makes passes cache_dir = active_hf_hub_cache(), so four of the five files and the operator's whole chosen root fell outside the gate. - The template predicate omitted cache_dir for the same reason, while the download beside it names the active cache, so a template living only there reported a miss and opened the gate on itself. And two of the older shapes, at sites that had not been reached yet: - The embedding resolver still asked the raw question, so the forced-anonymous sentinel was refused a cached PUBLIC embedder and told to download one it already had. - load_model_config tested local_files_only and did not forward it, so a cache-only read dialled /auth-check anyway. Five mutations, each red, including one that keeps the file list and drops the cache root and one that keeps the root and drops the file list.
Three fixes from the latest review round. hf_errors: LocalEntryNotFoundError and OfflineModeIsEnabled mapped to 404, which was the wrong repair for the 500 they used to produce. The second is not raised by a dead network at all; it fires whenever huggingface_hub.constants.HF_HUB_OFFLINE is true, and this server flips that constant on itself: llama_cpp._hf_offline_if_unreachable wraps every GGUF download in utils.utils.force_hf_offline, which sets the constants process-wide under a refcount and rebuilds the sessions. So for the length of one download against dead DNS, an unrelated concurrent /v1 request calling HfApi.model_info in _admit_and_start was told the repository was not found and had its repo pinned in _not_servable for ten minutes, long after the window closed. Both names now map to 503, which _admit_and_start already answers as model_lookup_failed with a Retry-After and no marking, and which routes/training already classifies as transient. check-format keeps its non-500. settings: drop the cache_ok pre-gate on the embedding resolver. It asked about the requested id while every lookup it guarded is already authorized against the repo that lookup matched, so it could only subtract: a private id whose derived -GGUF conversion is public was suppressed even though the repo being reported was one the caller may read. It also sat above the backend branch, so the local and sentence-transformers paths each paid a /auth-check bounded at 10s out of the resolver's 20s. formatting: read the disk, then gate the answer. Gating first probed the Hub for a prefer-local request that had ruled the network out and then missed the cache anyway. Neither reader touches the network, and reading our own disk is not the leak, returning it is. Substituting dataset_cache_can_answer instead would under-gate: it covers the prepared cache, not the raw snapshot the other reader walks. Forwarding the offline intent alone would newly deny an API-key caller a preview their token reaches, since cache_reads_authorized fails closed on an explicit token when offline.
Mechanical deduplication, no distinct claim removed. 2753 to 2584 lines, 196 collected cases before and after, and the assertion inventory differs by exactly the one intended merge below. Setup: _counting_probe gains an offline keyword, folding the 21 places it sat adjacent to _hub_reachable. New _st_resolver / _gguf_resolver for the two resolver preambles, _picker_env for the template walk, _scan_refused for the five copies of the scan-and-expect-404 block, and _one_cached_quant for the GGUF listing premise. Imports: the same module was imported under four names in 68 function-local imports, which is why nothing about the setup was greppable. One alias per module, hoisted, verified with scripts/verify_import_hoist.py in both directions since F401 is ignored repo-wide and ruff cannot see a stranded import here. Merged: the two seed-preview refusal tests were 86 percent identical and now run as two named rows, one per reason. That is the only test-name change. Hardened while here: the prefer-local scan branch test sliced 280 characters after a marker, which drifts with every edit to the surrounding function and widens the claim silently rather than failing. It now bounds the condition by indentation. Confirmed it still goes red when the guard is removed. All 27 gates stay CAUGHT under the mutation sweep, and the three fixes from the previous commit still go red when reverted.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 16fad397e1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # 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) |
There was a problem hiding this comment.
Treat prefer-local GGUF listings as offline
When an API-key caller supplies an explicit HF token with prefer_local_cache=true and offline=false, this gate still contacts /auth-check because it forwards only offline. The service subsequently treats either flag as local_only, and the frontend uses prefer-local requests for disk-only cached-quant checks, so a cold authorization entry can unnecessarily block for the 10-second probe timeout and consume a third of the variant request's 30-second bound. Pass prefer_local_cache or offline to this gate and the duplicate gate inside _compute so these cache-only requests fail closed without network access.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The observation is right and the fix is not, so I am declining it rather than skipping it quietly. local_only = prefer_local_cache or offline at line 1308 is real, and this gate does forward only offline.
But the two flags answer different questions. offline means we cannot ask the Hub; prefer_local_cache means do not fetch from it. The process still has a network in the second case, so the credential is still verifiable. Conflating them here is not free, because cache_reads_authorized treats offline = True as fail closed for an explicit token: _explicit_token_reaches_repo returns False before any probe (hf_tokens.py, if offline or _hub_offline(): return False, above the inflight lock). Only None and AmbientAuthorizedToken survive it.
So the concrete effect on the caller you name is not a saved 10 seconds. An api key sending a token that does reach the repo, asking for a prefer-local listing, gets cache_reads_authorized = False, which makes _scoped_local_response() return None and select_gguf_cache_snapshot be skipped at line 1313, and the request falls through to the network branch. The prefer-local request ends up doing the one thing it asked not to do. The UI is unaffected either way, since a session token is an AmbientAuthorizedToken and is authorized offline.
I also tried the other direction, deferring the probe until a reader wants it, and stopped: cache_reads_authorized is consumed as a bool at several sites here, and turning it into a callable makes every site I miss truthy, which is fail-open at a gate. The comment above the gate already records why the predicate is lambda: True rather than something narrower.
Worth noting the probe is memoized per repo and token for _REPO_ACCESS_TTL_S = 60s, so the 10s is a cold-start worst case, not a per-request cost. I took the same ordering fix you suggested on the chat template path in the sibling comment, where the read is local and the verdict does not change.
The chat template gate probed /auth-check before establishing that any cached snapshot could supply a template. With nothing cached there is no disk-backed answer to protect, so the probe was spent deciding a question with no subject, and it can hold the caller for the probe timeout before the download path even starts. The walk is local, so it now runs first with the gate between it and the caller: reading our own disk is not the leak, handing the template back is. Same order the per-file fallback gate below already uses. Verdicts are unchanged for every caller class. A denied caller still gets nothing and still falls through to the offline gate and the download path. The offline gate short-circuits on hf_env_offline() before it asks about the credential, so an online uncached request now reaches no probe at all. The test asserted the walk did not RUN for a denied caller, which pinned the ordering rather than the property. It now asserts the template is not handed back, and adds a row that an uncached repo costs zero probes.
|
@codex review |
One conflict, in studio/backend/tests/test_hub_token_caller_identity.py. Main's unslothai#10498 hoisted the repeated function-local imports in that file; this branch hoisted the same ones and 58 more in the same pass, so the branch side is a superset and is taken whole. Confirmed every module unslothai#10498 lifted (seed_routes, asyncio, fastapi, inspect, model_config_module) is present at module level here.
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 509ff6ab29
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if not is_cached(): | ||
| return False |
There was a problem hiding this comment.
Reauthorize cache entries that appear after the miss check
When a trusted download populates a private repo concurrently, an unauthorized request can observe is_cached() as false here and bypass authorization, then have a downstream disk-capable operation serve the newly created entry. This is reachable in callers such as picker.read_default_chat_template, where hf_hub_download runs after this check and is explicitly documented there to return a cached pointer even after a 403; the same check-then-read pattern exists for config, dataset, and remote-code reads. The gate must either hold cache state stable through the read or validate authorization/result provenance again before returning disk-backed data.
Useful? React with 👍 / 👎.
| if not repo: | ||
| return False | ||
| return not cached_read_refused(token, repo_id = repo, is_cached = lambda: True) |
There was a problem hiding this comment.
Charge authorization probes to the resolver deadline
For API-key callers whose token has no memoized verdict, _authorized() can block for the probe's full 10-second timeout without consulting _EMBEDDING_RESOLVE_DEADLINE. In the llama fallback path, the bounded remote GGUF search can first consume the 20-second resolution budget and a cache hit found afterward (for example, a complete cached quant other than the configured preferred variant) then invokes this probe, extending a nominally bounded settings GET/PUT to roughly 30 seconds. Run this probe through the remaining resolution budget, or skip it once that budget is exhausted.
Useful? React with 👍 / 👎.
Summary
Part of #10147 (item 1 — the sentinel authenticates the caller class, not the credential).
#10076 keyed every disk-cache gate on
is_anonymous(hf_token), which is only true when the caller sent no token. An API key that sent any token-shaped string left the sentinel and took the same fast paths as the operator: cached dataset previews, the chat template walk, config and audio probes, and GGUF listings.This is one helper applied at those gates, not eight separate checks.
cache_reads_authorized(hf_token, repo_id=..., repo_type=...):False(sentinel) — no cacheNone(ambient / UI) — cache, no extra Hub callHfApi.repo_infosucceeds for that repo; the answer is memoized for 60s so the round trip is not paid on every requestChanges
hub/utils/hf_tokens.pydatasetsUI sessions keep the cache fast path. A dummy API-key token does not.
Test plan
python -m pytest tests/test_hub_token_caller_identity.py -q --tb=short -k 'not test_seed_inspection_derives and not test_an_explicit_seed_token'(84 passed; the two skipped tests need thedatasetspackage, same as before)