Repository navigation
fix(studio): enforce Hub token caller boundary - #10076
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Confirmed this closes the metadata and progress side of the boundary that studio/backend/auth/authentication.py already draws for downloads, which reads right to me. One thing before I review: inspect_seed_dataset in studio/backend/routes/data_recipe/seed.py passes allow_ambient_token = False for every caller, so a UI session on an install whose Hugging Face token comes from the environment would lose the fallback it has today, could you confirm that is intended? |
`hf_token_arg` resolves a request to three values, but the code it feeds was written
for two. `False` is falsy AND is not None, so it falls down whichever branch the
call site did not think about.
`utils/models/model_config.py` guards its cache fingerprint with `if token is None`,
so `False` reached `.encode()`:
GET /api/models/check-vision/unsloth/Llama-3.2-1B-Instruct
UI session: 200
API-key caller: 500 AttributeError: 'bool' object has no attribute 'encode'
`/api/models/config` 500s the same way. `/api/models/loras` swallows the exception per
checkpoint, so it reports every audio LoRA as unclassified instead of failing loudly.
The other three fingerprints fold `False` and `None` into one identity, which defeats
the boundary this PR draws. `hub/utils/inventory_scan.py` keys the model snapshot,
dataset size, GGUF requirement and GGUF blob-hash caches; the dataset one carries the
defence explicitly as `not restricted or cached_fp == token_fp`, and the collision
turns that into `"" == ""`, so a private dataset's size and blob hashes fetched by a
UI session under the ambient token are served straight back to an API key. It leaks
the other way too: an API key's anonymous 403 writes a negative entry that blanks the
UI's variant list for the next 60 seconds.
`gguf_variants.py:1689` puts the same fingerprint in the in-flight coroutine key, so a
concurrent UI and API-key scan join one task and share whichever credential started
it. That one is not TTL-bounded.
`utils/transformers_version.py` has it in the config.json / tokenizer_config.json
caches, whose own docstrings promise "an unauthenticated miss never poisons a later
authed lookup".
One shared `ANONYMOUS_CACHE_IDENTITY` in hf_tokens.py, checked before the truthiness
test at each site. Deliberately not hex, so no token digest can collide with it, and
not "" or None, so the historical ambient identity is unchanged and no existing cache
key shape moves.
Three places treated "no token" and "must not have a token" as the same thing, so the sentinel quietly became ambient access again. `load_model_config` tests `if token:` and then `if not use_auth:`. `False` is falsy and `_is_vision_model_uncached` passes `use_auth=True`, so it fell past both explicit branches to the "default auth (cached tokens)" call at the bottom and authenticated an API-key caller with the operator's credential. It now routes through the no-auth path that already exists. The probe subprocesses build their environment from the parent's, so declining to SET `HF_TOKEN` is not the same as denying one -- the child inherits it. `_probe_autoconfig` and the vision-check spawn now scrub it, matching what `spawn_worker` has always done for download workers. `stt_download_worker.spawn_download` had the clearest version of the mistake, with a comment explaining that it deliberately leaves the ambient login alone when no token is supplied. That is right for a UI session and wrong for a caller forced anonymous, so the two cases are now separated rather than shared. The vision-check argv slot collapsed `False` to "", which the child reads back as "no token" and then satisfies from that inherited environment. `diffusion_compat` normalises with `(hf_token or "").strip() or None`, an idiom that predates the sentinel and maps `False` onto exactly the value that means "use the backend's credential". `normalize_token` keeps the trim without the laundering. `apply_token_to_child_env` is the one place that decides: explicit token grants and clears an inherited DISABLE_IMPLICIT_TOKEN, anonymous scrubs all five credential variables and sets it, and None is left alone on purpose -- scrubbing there would break gated repos on installs whose token lives in the environment.
…er precedence Two review findings, both correct. `inspect_seed_dataset` hardcoded `allow_ambient_token = False`, so a UI session on an install whose Hugging Face token comes from the environment lost gated and private seed inspection that works today. The route had no auth dependency at all, so it could not tell callers apart; it now takes `allow_ambient_hf_token` like every other Hub-reaching route. Its sibling `inspect_seed_upload` reads local files only and needs nothing. `get_gguf_variants` flipped token precedence: the header used to win over the legacy `?hf_token=` query parameter, and after the conversion the query parameter did. Both are the caller's own credential so nothing leaks, but a stale query token silently displacing the resolved header one is not a change this PR set out to make. The `or` chain is subtle enough to deserve a name and a test -- `_resolve_hub_token` keeps the dependency's value last so the anonymous sentinel survives when neither explicit token is present, which an `or` ending on the query value would turn back into None.
unslothai#8433 drew the boundary for downloads and left "around twenty five other call sites" for a separate look; this PR is that look, but it stopped at the metadata routes. These five still resolved through the old dependency, so a blank token meant the ambient one: POST /video/generate content, downloads and loads the named model POST /v1/videos content, and on the surface API keys actually use POST /audio/stt/download content, snapshot_downloads a whole Whisper repo POST /audio/stt/validate metadata, a gated/private existence oracle POST /v1/images/generations content, via the diffusion auto-switch The STT download is the one worth naming: an API key could name any private Whisper repo and have the backend fetch it with the operator's credential. It reaches the worker whose environment the previous commit had to fix, which is why that one came first. Hub WRITE paths are deliberately not in scope here. `data_recipe/jobs.py` publish and `routes/export.py` push have the same hole and it is worse -- a blank body token lets an API caller push as the operator -- but they are pre-existing, they are writes, and they deserve their own change rather than being folded into this one.
The progress pollers need the prepared token, so `prepareHfTokenForUse` moved out of performLoad's `isGguf && isDiffusion === undefined` branch to the top of the load. That widened what it runs on: it validates over the network and, for a token the Hub reports as definitively invalid, raises a blocking dialog that can abort the load. Non-GGUF, local-path and cached-LoRA loads now hit that, and a local load asks the Hub for nothing, so a stale token sitting in Settings could stop a model that lives on disk. Guarded on the load being able to reach the Hub at all. A connectivity failure still returns early inside prepareHfTokenForUse, so offline installs were never affected. The cancellation also moved: it used to throw inside the try whose catch renders the error toast, and now lands in the outer catch, which only sets the banner. The load toast does not exist that early, so the cancel says so itself.
Backend, two files. `test_hub_token_caller_identity.py` covers the sentinel itself: the resolver's three values, `is`-compared so False/None/0/"" cannot be confused; every fingerprint separating anonymous from ambient; the child environment granted, scrubbed or left alone per caller; and the route that used to 500. `test_hub_token_cache_isolation.py` drives the real caches rather than the fingerprint in isolation, because the fingerprint was never the interesting part -- what mattered was that a UI session warms a private dataset's size and blob hashes and an API key reads them back. It covers that, the negative direction where an anonymous 403 blanks the UI's next lookup, the in-flight scan two credentials used to share, and the two cases the fix must NOT break: an identical caller still gets its cache hit, and two identical-scope requests still dedupe onto one scan. Verified against the unfixed code: re-introducing just the two fingerprint collisions fails exactly five of these and leaves the other thirty-five passing. The frontend test asserted source text with regexes, so it would have passed with the header dropped, and it was fragile to the formatter that had already run on the branch. It now stubs fetch and asserts on what authFetch emits: the token present, the header omitted rather than blanked when there is none, Authorization and the timezone headers surviving the merge, and the token appearing in no other header.
Converting /v1/images/generations and /v1/videos to the request-scoped token pulled `authenticated_via_api_key` into their dependency graph. These fixtures override `get_current_subject` and send no bearer, so the real dependency ran and answered 401 on 75 tests. Production was never affected: both routes already depend on `get_current_subject`, which resolves through the same `security` scheme, so a real caller that reaches them has always carried a credential. Only the fixtures bypassed it. Overridden the same way `test_hub_download_ambient_token.py` does. `True` is the honest value here rather than a convenience: this is the programmatic surface, keyless callers count as API callers, and `openai_auto_download.py` already hardcodes `allow_ambient_token = False` for exactly that reason -- these routes were always meant to be anonymous, the metadata paths just had not caught up.
The same fixture gap as the OpenAI-compat routes, in the four files that reach /video/generate rather than /v1/videos: they override get_current_subject and send no bearer, so pulling authenticated_via_api_key into the route's dependency graph answered 401 on 43 tests. Same reasoning, same override. Production is unaffected for the same reason: these routes already depend on get_current_subject, which resolves through the same security scheme.
|
Both review findings are right, and chasing the second one turned up a merge blocker underneath it. I pushed eight commits to the branch rather than leaving a list. The blocker
That is the shape of the whole problem: a third state went into a parameter that about sixty downstream functions were written to treat as The cache identity, which is the P1
elif not restricted or cached_fp == token_fp:The collision makes that Worth noting this repo has been here before. Three more the sentinel walked into
On your two findings
I also converted the five read paths that never had the boundary at all - VerificationThe new tests are regression tests, checked the way that word should mean: re-introducing just the two fingerprint collisions fails exactly five of them and leaves thirty-five passing. Full backend suite, this branch versus its own head, same flags: The 575 and the 465 reproduce on your head untouched (missing The frontend test asserted source text with regexes, so it would have passed with the header dropped entirely, and it was fragile to the formatter that had already run on this branch. It now stubs fetch and asserts on what One frontend behaviour change worth flagging: hoisting Two things I could not answer from here. The branch is 25 commits behind main - it merges cleanly and touches nothing main has moved, so I left it rather than force-push your fork. And this box cannot run about a thousand of the tests, so CI on the PR is still the authority for those. |
Opening comment-reduction pass over the comment lines this PR adds: 111 to 48, with
every load-bearing fact kept.
Cut hardest on restatement. Five section banners went outright, as did the lines that
narrated the assertion directly beneath them ("the UI session warms the cache", "the API
key probes first and is refused") - the assert messages already say it, and better. The
two new test modules had 19- and 14-line docstrings enumerating each failure mode; the
enumeration is what the test names are for, so both collapse to the shape of the problem.
The same fixture note had been pasted at three lengths across six files and is now one
line everywhere.
Kept, deliberately: anything that names a mistake rather than describing the code. Why
DISABLE_IMPLICIT_TOKEN is set when the token vars are already scrubbed (get_token still
reads a cached login file), why `None` is left alone where `False` is scrubbed, why the
`or` chain ends on the header, and that a bare `is False` invites a `not hf_token`
simplification that reopens the boundary. When torn, kept it and spent the line.
AST-gated: comment_tools.py check --strip-docstrings, 16/16 code unchanged.
The review is right, and it is my regression. /v1/images/generations, /v1/videos and
/video/generate all reach maybe_auto_switch_media_model, whose _start_load constructs a
DiffusionLoadRequest or VideoLoadRequest. Both declare hf_token: Optional[str], so the
anonymous sentinel is a ValidationError that kills the switch before the cached model
loads:
DiffusionLoadRequest(hf_token=False) -> ValidationError
VideoLoadRequest(hf_token=False) -> ValidationError
Reverted those three to get_hf_token. The alternative, widening both models to HfTokenArg,
means auditing roughly thirty request.hf_token consumers in routes/inference.py that feed
the whole load path, and laundering False to None there would hand back the ambient token
this PR exists to withhold. That is its own change, not a rider on this one.
The STT pair keeps the boundary: /audio/stt/download and /audio/stt/validate pass the
token to plain sidecar functions and end at spawn_download, whose environment this branch
already scrubs. No pydantic sink on that path. It is also the gap worth closing most, since
the download pulls a whole repo the caller only had to name.
Two tests pin the split so neither half drifts back: one asserts both load models still
reject the sentinel and says why the routes opt out, one asserts the STT routes still
resolve through it. The fixture overrides those three routes needed are reverted with them.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1c03f3c68c
ℹ️ 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 is_anonymous(hf_token): | ||
| return None |
There was a problem hiding this comment.
Require authorization before serving cached dataset rows
For an API-key request to /api/hub/datasets/check-format with prefer_local_cache=true, this check treats every nonempty X-Unsloth-HF-Token as authorization even though the token has not been validated against the named repository. A caller can therefore send an arbitrary string, bypass the False sentinel, and make _load_cached_hf_preview_slice return preview rows from a cached private dataset entirely from disk without any Hub request. Cache-backed previews need proof that this credential can access the repository, rather than checking only that some token-shaped value was supplied.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The observation is right and I want to record it plainly rather than wave it off: the sentinel authenticates the caller class, not the credential, so an API key that sends any token-shaped string is no longer False and unlocks the disk fast path. Where I disagree is that this is a bug in this line. It is a property of the whole design, and it applies identically to every guard in this PR -- the chat template walk, the config and audio probes, the GGUF listings, the seed preview, this preview. Fixing it where you have flagged it would leave the other seven bypassable in exactly the same way, which is worse than leaving them consistent. The remedy you describe, proving the credential can reach the repository before any cache-backed read, is a Hub round trip in front of every one of those fast paths. That is a cross-cutting authorization change with a real latency cost on the paths these caches exist to make fast, and it wants to be designed once and applied uniformly, with its own tests and its own review. What this PR set out to do, and does, is stop an API key from silently borrowing the operator's ambient credential; a caller sending a bogus token is refused by every network path and is not using the operator's token. So: thumbs down on fixing it here, not on the finding. It goes into the follow-up issue alongside the cached-inventory routes and the Hub write paths (data_recipe/jobs.py publish, routes/export.py), and I would rather it be reviewed on its own than smuggled into the tail of this one.
zustand's subscribe does not fire on install, so lastKnownStoredToken stayed null until the first change and that change was then read as initialization. Replacing a token that was already stored therefore never called forgetHfTokenValidation, and the superseded raw bearer kept its 15s window and its slot in recentlyValid, since expiry only runs during another preparation. Seeded from useHfTokenStore.getState() when the subscription is installed. The test store now tracks its current value so the already-stored case is what the new regression drives.
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
pre-commit.ci fails on ruff-format-with-kwargs, and most of that is repo-wide churn: the hook rewrites 1015 files, and 9 of the files this branch touches are rewritten identically on origin/main, so they are not this PR's to fix here. Two are: test_hub_token_caller_identity.py and test_hub_token_cache_isolation.py, both added by this branch, are rewritten only on this side. Formatted them, confirmed the hook is now idempotent on both, and re-ran the 71 tests they hold. The remaining pre-commit.ci failure is the repo-wide rewrite plus its "a conflict occurred when applying fixes to the pr" push, neither of which this branch can resolve.
get_base_model_from_lora_identifier passed `hf_token if hf_token else None` to both its probe and its download, laundering the sentinel back into ambient access while resolving a named private adapter, after which the scan route returns that repo's source findings. Uses normalize_token now, which keeps False as False. _detect_audio_from_tokenizer walks get_cache_path before it ever reaches a network branch, so forcing the probe online did nothing for it: an anonymous caller still read a cached private repo's audio tokens. is_embedding_model had the online half of the same hole, since the anonymous 404 lands in the transient-error branch that falls back to the cache marker. Both are denied to that caller now; the offline halves were already guarded. model_size_bytes chose _get_snapshot_model_size_bytes purely from prefer_local_cache, but the anonymous short-circuit hands back the bare repo id, which sizes as a relative path and returns None. That regressed the size for PUBLIC models on the new path, not just private ones. Keyed on what the target actually is instead of on the flag. The validation cache's finally deleted its inFlight entry unconditionally, so a request that had been forgotten and replaced would evict the live replacement on settling and send the next caller to the network. Deletes only when the entry is still its own. Tests: five regressions, three parametrized over all token states, all verified to fail with their fixes reverted. The frontend one initially passed either way because the positive-verdict cache masked it; rewritten with per-call gates and a never-cached verdict so sharing is observable.
scan_model_remote_code gated only its exact_snapshot_path branch. The sibling, taken on prefer_local_cache alone, called _resolve_model_snapshot unconditionally, which resolves the named repo straight to its cached snapshot; the scanner then reads that repo's Python and the route returns source snippets from it, with no credential consulted anywhere. Same guard as the branch above it now. load_model_config sends the anonymous caller to the hub as token=False, which disables authentication but not the local cache. Offline -- which _hf_offline_if_unreachable_for forces whenever the hub looks unreachable -- AutoConfig would load a cached private repo's config.json regardless, and /config derives the base model and max context from it. With no network that caller cannot establish access, so it raises rather than answering from the cache, the same call the other capability probes make. Tests: two regressions, one parametrized over all three token states so the ambient and explicit callers are pinned as keeping the offline read. Both verified to fail with their fixes reverted.
Three more offline disclosures were reported: the plain repository path in scan_model_remote_code, the default Tier 2 preview in check_format_response, and ModelConfig.from_identifier's adapter_config fallback under /config. All three are the same condition, and so were the six fixed before them -- the snapshot walk, the config probes, the embedding marker, the GGUF listing, the preview slices, AutoConfig. Each per-site fix only moved the boundary to the next reader. So this adds utils.utils.anonymous_and_offline and refuses at the three route entries rather than at a tenth call site. token=False denies authentication, not the cache: with no network a caller holding the sentinel cannot establish access, so every downstream read is a disk read it never earned, whether or not anyone has enumerated that reader. /config takes the check inside _hf_offline_if_unreachable_for, since the guard forces offline itself when the hub is unreachable. Local paths are excluded throughout: those are the caller's own files. Tests: the rule's truth table over all three token states online and offline, plus an assertion that each of the three routes consults it.
|
Codex Review: Didn't find any major issues. Bravo. 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". |
test_export_absolute_paths hand-builds a stub utils.utils, and routes/models.py now imports anonymous_and_offline from it, so the import failed with "unknown location" -- which reads like a path problem rather than an incomplete stub. Same shape as the allow_ambient_hf_token stub fixed earlier on this branch. The stub answers False so the export paths under test keep their ordinary route. Not this branch, both re-confirmed this round: the pinned-cached-row and non-GGUF-status failures in the same job fail identically on current origin/main, and the Startup profile budget miss at 12:04 passed on the sibling staging branch in the same minute with the same content.
|
Codex Review: Didn't find any major issues. Hooray! 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". |
Final comment pass over the lines this branch added. Every explanation that ran to four or five lines is one or two now, and the repeated "a caller denied the ambient credential" phrasing is said once per site rather than spelled out each time. Nothing about the reasoning is dropped: each comment still names the mechanism it exists for, because the mechanism is the part that is not obvious from the code, and it is what made these bugs recur. Comments only: comment_tools.py check reports code unchanged on all seven files. 770 backend and 30 frontend tests still pass.
|
You have reached your Codex usage limits for security reviews. Please try again later. |
Summary
This extracts the remaining applicable behavior from #7413 onto current main. The worker/download boundary was already handled by #8433; this PR covers the metadata and progress boundary without reviving the stale branch.
Tests
The broad frontend run passed 6086 of 6089 tests. Its three failures are pre-existing local dependency-state failures: node_modules contains remend 1.3.0 while the repository pins 1.3.1.