Skip to content

Studio: do not lend the backend's HF_TOKEN to API key callers - #8433

Merged
danielhanchen merged 6 commits into
mainfrom
hub-download-ambient-hf-token
Aug 11, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
hub-download-ambient-hf-token

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

A hub download that arrives without an X-Unsloth-HF-Token header falls back to the backend process HF_TOKEN, so a private repo stays downloadable on an install whose token lives in the environment rather than in Settings. spawn_worker already takes an allow_ambient_token flag to opt out of that, but only the OpenAI-compatible auto-download ever passed it. The two hub download routes still defaulted to allowing the fallback, so an authenticated caller could name any syntactically valid repo id and have the worker fetch it with the operator's Hugging Face credential.

The gate

Draw the line where Studio already draws it. routes/settings.py uses require_ui_session to refuse an sk-unsloth API key the saved Hugging Face token, so an API key should not reach the operator's private repos by naming one in a download request instead.

New allow_ambient_hf_token dependency in auth/authentication.py, next to authenticated_via_api_key:

  • UI session: keeps the fallback. Settings hands that session the saved token on request, so letting its downloads use the ambient one grants it nothing it did not already have.
  • API key: worker stays anonymous (HF_HUB_DISABLE_IMPLICIT_TOKEN=1, no HF_TOKEN in its env). Programmatic callers send their own token in the header.

Both POST /api/hub/download and POST /api/hub/datasets/download now pass it through. The dataset service had no such parameter at all, so it gained one to match the model service.

The recovery ladder

_try_transport_retry respawned the worker without the flag, so a job that started anonymous picked the ambient token back up the moment its Xet worker fell over to HTTP. That defeated the existing allow_ambient_token=False on the auto-download path as well. The flag now rides through launch_worker to register_worker to _try_transport_retry, so every rung keeps the policy the job started under.

No user flow changes

poll-loop.ts reads the saved token from the store and download-manager/api.ts sends it as X-Unsloth-HF-Token on every download start, public or private, so a UI download that has a token was never on the fallback path to begin with. The Settings token is stored encrypted in studio.db and is never written into the backend process environment, so the ambient HF_TOKEN is purely deployment provided and only ever fired for a caller that sent none. Browser sessions and the Desktop JWT (authenticated_via_desktop_jwt, not an API key) are untouched.

Tests

Seven new tests.

hub/tests/test_download_lifecycle.py, driving the real spawn_worker against a fake Popen and reading the child environment:

  • an API key caller gets no HF_TOKEN and HF_HUB_DISABLE_IMPLICIT_TOKEN=1
  • a UI session still inherits the backend token
  • an explicit request token wins over the backend one
  • a job started anonymous stays anonymous on the HTTP retry

tests/test_hub_download_ambient_token.py, new, end to end through TestClient: both download routes for both credential types, plus the dependency itself.

hub/tests/test_download_lifecycle.py          22 passed
hub/tests/test_model_services.py             265 passed
tests/test_scoped_download_job.py             13 passed
tests/test_hub_download_transport_auto.py     26 passed
tests/test_openai_auto_download.py           160 passed
tests/test_hub_download_ambient_token.py       6 passed

hub/tests/test_dataset_services.py (4), tests/test_openai_auto_switch.py (1) and tests/test_desktop_auth.py (4) fail identically on main in this environment, unrelated to this change: the dataset ones are a datasets.config.TORCHCODEC_AVAILABLE version mismatch.

Not in scope

Around twenty five other call sites pass token=hf_token to HfApi where None means "use the ambient token": GGUF variant listing, model_info, list_repo_files, chat template sidecars. Those disclose repo metadata rather than repo contents and have a much wider blast radius, so they are worth a separate look rather than folding in here.

danielhanchen and others added 3 commits August 11, 2026 13:00
A hub download with no X-Unsloth-HF-Token header falls back to the backend
process HF_TOKEN so a private repo stays downloadable on an install whose
token lives in the environment rather than in Settings. spawn_worker already
takes allow_ambient_token to opt out of that, but only the OpenAI-compatible
auto-download passed it, so the two download routes still handed the
operator's Hugging Face reach to whatever repo id the caller named.

Gate it on the credential instead. A UI session is the installation's owner
and Settings hands it the saved token on request, so nothing changes there.
An sk-unsloth API key is the lesser credential, and require_ui_session
already refuses it that same token, so it must not reach a private repo by
naming one in a download request instead. The UI sends the saved token on
every download start, public or private, so no user flow loses a token it
was sending before.

Carry the flag onto the recovery ladder too. _try_transport_retry respawned
without it, so a job that started anonymous picked the ambient token back up
the moment its Xet worker fell over to HTTP.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ce430c22a4

ℹ️ 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".

spawn_kwargs = {
"use_xet": retry_over_xet,
"protected_blob_hashes": peer_hashes or None,
"allow_ambient_token": allow_ambient_token,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Update the HTTP-rung test double for the new keyword

When test_a_verdict_carried_onto_the_http_rung_is_still_charged triggers this retry, its flaky_spawn double accepts only use_xet and protected_blob_hashes. Supplying allow_ambient_token therefore raises TypeError on both the Xet and HTTP attempts; the exception is treated as a spawn failure, but the test still passes because _give_up() records the expected verdict. Consequently, that test no longer exercises its claimed successful HTTP-completion path and can miss regressions that incorrectly clear the carried Xet verdict after HTTP succeeds; update the double to accept this keyword and assert that the HTTP worker was spawned.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and worse than described: the TypeError fires at the call, so the double's body never ran once. I instrumented it and got zero invocations through while the test still passed on the verdict _give_up() recorded.

Fixed in f727ed4. The double takes the keyword now, and the test asserts spawned == [True, False] so both rungs must actually have been spawned. Verified the assertion bites: with the old signature restored it fails with "the HTTP rung never ran, so the verdict proves nothing" instead of passing green.

studio-backend-ci.yml runs studio/backend/tests only; nothing runs
studio/backend/hub/tests, so the four spawn_worker and retry-ladder tests
would never have executed in CI. They need no hub-only fixtures, so move
them next to the route tests they belong with.
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
The new spawn_worker keyword made this test's double raise TypeError at the
call, which reads as a spawn failure: _give_up() still recorded the expected
verdict, so the test stayed green while its HTTP-completion path never ran.
Accept the keyword and assert both rungs were actually spawned, so a double
that falls behind the signature fails instead of silently skipping.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: f727ed4d5a

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 6b3868a into main Aug 11, 2026
0 of 44 checks passed
@danielhanchen
danielhanchen deleted the hub-download-ambient-hf-token branch August 11, 2026 13:31
danielhanchen added a commit that referenced this pull request Sep 1, 2026
* fix(studio): enforce Hub token caller boundary

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: give the anonymous Hub token its own identity

`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.

* Studio: stop the anonymous sentinel picking the ambient token back up

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.

* Studio: derive the seed-inspect policy from the caller, and keep header 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.

* Studio: close the Hub read paths that never had a caller boundary

#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.

* Studio: do not gate a local model load behind Hub token preparation

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.

* Studio: pin the caller boundary with tests that fail without the fix

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.

* Studio: let the OpenAI-compat route tests resolve the caller boundary

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.

* Studio: let the remaining video-route tests resolve the caller boundary

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.

* Studio: tighten the comments added by this PR

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.

* Studio: keep the media load routes off the request-scoped token

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.

* Studio: stop four more paths reading past the anonymous sentinel

All four review items are right. Three are the same `or` laundering this branch already
fixed elsewhere, in places I had not followed far enough.

The STT one corrects a claim I made on the previous round. I said the sidecars were safe
because they end at spawn_download, whose child environment this branch scrubs. They do
not: all three convert with `hf_token or None` first, at stt_sidecar.py:766 and :837,
stt_mtmd_sidecar.py:447 and :486, stt_ggml_sidecar.py:588 and :631. `False or None` is
`None`, which is the value that means "ambient is allowed", so the scrub was unreachable
and the metadata requests authenticated too. They now pass the sentinel through unchanged.

`_detect_audio_from_tokenizer` resolved `hf_token or os.environ.get("HF_TOKEN")`, so
/api/models/config would fetch an arbitrary private model's tokenizer with the operator's
credential and cache the derived audio_type under the anonymous identity.

apply_token_to_child_env granted an explicit token by setting HF_TOKEN without clearing
the aliases first, so a child could hold the caller's token in HF_TOKEN and the operator's
in HF_HUB_TOKEN. spawn_download scrubbed all five before granting; the helper that replaced
it did not. My own verification output showed the leftover alias last round and I read it
as pre-existing rather than as the regression it was.

The dataset preview cache is different in kind: it is not laundering but a fast path that
predates this branch. `_load_cached_hf_preview_slice` returns real sampled rows off disk
without consulting the token, and it is tried first, so an API caller could name a private
dataset the UI had cached and read its contents. Behaviour is unchanged from before the
branch, but this is a route the branch converted, so the promise it now makes should hold.
Only a forced-anonymous caller loses the fast path; a UI session resolves to None and keeps
it.

Four tests, each verified to fail with its fix reverted and pass with it applied.

* Studio: close three more anonymous-sentinel read paths

picker/service.py walked the cached snapshot for a chat template before
consulting the token, so a forced-anonymous caller could read a private
repo's template out of a slot the operator's credential filled. Gate the
walk on the caller not being anonymous; ambient and explicit callers keep
the fast path.

routes/models.py resolved prefer_local_cache to a local snapshot without
the token in hand, giving the same read for the config inspection and
scan targets. Thread the token through _model_config_inspection_target
and short-circuit back to the bare repo id when the caller is anonymous.

training-runtime-store.ts kept startHfToken in module state across an
in-tab logout: hf-token-store.ts already clears itself on
AUTH_SESSION_CLEARED_EVENT, and __root.tsx remounts rather than reloads,
so the training store survived. Subscribe to the same event and reset.

Tests: three regressions in test_hub_token_caller_identity.py, all four
parametrizations verified to fail with the fixes reverted.

* Studio: fix two staging-CI regressions in this branch

Staging CI (danielhanchen/unsloth-staging-2 #1268) caught two failures
that are this branch's own, not infrastructure.

_resolve_hub_token ended its or-chain on header_token so the anonymous
sentinel would survive. Callers that invoke a route function directly
rather than through FastAPI leave the unresolved Depends object in that
parameter, and the backend's own tests do exactly that, so the Depends
reached token_fingerprint and 500ed every GGUF variants listing: 28
failures in test_cached_gguf_routes.py. Rebuild the sentinel from
is_anonymous instead of returning the header unchanged, which restores
the pre-branch None while still never laundering False into ambient.

check_format_response passed the token to the HfApi constructor as well
as to list_repo_files. The explicit call argument already wins, so the
constructor argument bought nothing and broke a caller substituting a
plain HfApi stand-in, which fell through to the split-only load path:
test_legacy_format_alias_preserves_single_source_file_column_order.

Tests: two regressions pinning the Depends case and the sentinel
precedence table. test_every_shipped_video_family_resolves_on_this_diffusers
fails identically on the merge base (ModularPipeline missing from the
pinned diffusers) and is not from this branch.

* Studio: close three more sentinel bypasses, one of them mine

read_default_chat_template refused the cache walk for an anonymous caller
but then fell through to hf_hub_download. Under HF_HUB_OFFLINE the hub
serves the cached copy off disk without checking the credential at all,
verified directly against huggingface_hub 0.36.2, and the route wraps the
read in _hf_offline_if_unreachable_for, so a disconnected install handed
back the very template the walk had just refused. Return None instead
when the caller is anonymous and offline is in force.

load_model_config sent the anonymous probe through without_hf_auth(),
which deletes HF_TOKEN/HF_HOME and physically moves the login token files
process-wide. /config runs these probes in worker threads, so it stripped
a concurrent download's credential, and two overlapping windows had the
inner exit restore the token while the outer probe was still running.
Pass token=False to AutoConfig directly: confirmed to send no
Authorization header even with HF_TOKEN set in the environment.

The mayReachHub guard added last round used isLocalModelPath alone. An
Ollama row's id is an opaque ollama-manifest: reference, not a path, so
an invalid stored token could still open the validation dialog and cancel
a load the backend serves entirely from the local Ollama store. Compose
isOllamaLinkPath into the guard.

Also fixes a regression of mine from last round: training-runtime-store.ts
imported AUTH_SESSION_CLEARED_EVENT through the @/ alias, which
node --experimental-strip-types does not resolve, so
tests/training-runtime-store.test.ts failed to load. Relative and
extensioned like its sibling import. Frontend suite is 6096 passing
again; I had checked only typecheck and biome last round, which both
pass on the alias.

Tests: two backend regressions verified to fail with their fixes
reverted, a new frontend test for what the disk-served predicate
classifies, and the existing guard assertion extended to the new term.

* Studio: the sentinel must reach the wire, not the cache

Two more places where sending the anonymous caller "to the Hub" still
ended in a local read, both the same shape as the offline chat-template
hole fixed in 5b180a9.

/config short-circuited the inspection target back to the bare repo id
for an anonymous caller, then handed the probes local_files_only =
prefer_local_cache regardless. hf_hub_download resolves config.json out
of the cache under local_files_only and never looks at the credential,
verified directly, so a denied caller still read a private repo's
capabilities whenever it was already cached. The probes now go over the
wire for that caller, where token=False is refused. is_embedding_model
had the same hole by another route: offline it reads its cache marker
straight off disk, so it now reports the default instead.

_load_any_cached_hf_preview_slice guarded only the raw snapshot read.
The processed fallback loads through DownloadConfig(local_files_only =
True) and drops the sentinel entirely, because load_cached_hf_dataset
builds kwargs with `if token:` and False is falsy, so check-format with
prefer_local_cache = true returned an already-processed private
dataset's rows. The guard now covers the whole disk route; the handler's
existing local-cache-miss 404 is what the caller gets.

prepareHfTokenForUse also runs three times per load: once for the
progress pollers as of this branch, then again inside validateModel and
loadModel. Each was its own POST /api/hub/token/validate, so the branch
added a third sequential round trip to the load's critical path.
Collapse a burst into one call instead of threading a prepared
credential through every API signature. Positive-only and short: an
invalid or inconclusive verdict is never reused, so the warning dialog
still appears, and a cleared credential drops its window immediately.

Tests: three backend regressions and five frontend ones, all verified to
fail with their fixes reverted. The existing preview-cache test stubbed
the processed path to None, which is why it did not catch this; it now
returns rows and counts.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: the validation cache must not outlive the credential

recentlyValid keys on the raw bearer token, so the 15s window bounded
reuse but not retention: a token stayed in module memory after the user
logged out or replaced it, and the map only ever grew. That is the same
objection already accepted against training-runtime-store.ts in this
branch, and hf-token-store.ts resets itself on the same event for the
same reason.

Expired entries are now dropped on every lookup, a logout clears the
cache through AUTH_SESSION_CLEARED_EVENT, and replacing the stored
credential forgets the superseded key rather than waiting out its
window. anonymousForSession is deliberately left alone: it predates this
cache and records a user's choice rather than a Hub verdict.

The token-change subscription is installed on first use, not at module
scope. module-scope-cycle-safety.test.ts caught the first attempt:
reading a barrel-imported value while this module is still loading
throws if the import cycle re-enters before the binding initializes.

Tests: two regressions driving the real module against a fake window and
a subscribable token store, both verified to fail with the fix reverted.
Frontend suite 6357 passing.

* Studio: GGUF variant listings must authorize before reading the cache

get_gguf_variants_answer takes prefer_local_cache or offline as
permission to answer from the HF cache, and the cache is read with the
credential never consulted. The listing carries variant filenames,
sizes, the vision flag and snapshot-derived context, so an API key
denied the ambient token could name a private repo the UI had already
cached and read it back, through either /api/hub/gguf-variants or the
compatibility route on /api/models.

_cache_fallback_response is the same disclosure without any query
parameter: for an anonymous caller list_gguf_variants raises on the
private repo, and the fallback then answered from the cache instead of
letting that refusal stand.

Both now require an authorized caller. A local_path the caller named
itself is not the Hub cache and keeps working, and an anonymous offline
request falls through to the existing "No cached GGUF variants available
while offline" 404 rather than a bare failure.

Tests: one regression parametrized over all three token states, so the
ambient and explicit callers are pinned as keeping the fast path.
Verified to fail on the anonymous case with the guards reverted.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: offline capability probes must not answer for a denied caller

is_vision_model and detect_audio_type_checked derive their effective
offline mode from `local_files_only or _env_offline()`, so the earlier
fix in /config -- passing local_files_only=False for an anonymous caller
so the probe goes over the wire -- is overridden whenever the route's
_hf_offline_if_unreachable_for context is active, which is exactly the
disconnected install. The probe then reads the cached config.json off
disk and never authorizes.

Both now return their default for a forced-anonymous caller while
offline, on the same reasoning as the chat-template and embedding-marker
fixes: there is no way for that caller to establish access with no
network, so the honest answer is "not established" rather than the
cache's. Local paths are unaffected; they are the caller's own files.

Tests: one regression parametrized over all three token states, pinning
that ambient and explicit callers keep the offline probe.

* Studio: fix four staging-CI failures this branch introduced

Staging CI on danielhanchen/unsloth-staging-2 caught four, all mine and
all invisible to the suites I had been running.

test_export_absolute_paths hand-builds a stub auth.authentication module
exposing only get_current_subject, and routes/models.py now imports
allow_ambient_hf_token from it too. The stub is missing the name, which
surfaces as ImportError "unknown location" and reads like a sys.path
problem rather than an incomplete stub.

test_consent_gate patches _model_config_inspection_target with a
three-argument lambda; the helper takes the caller's token as a fourth
argument now, so the scan route 500ed.

test_model_picker_contracts asserted the literal "hf_token:
preparedToken.token". The preflight still gets the prepared credential,
but through the hoisted hfToken binding, so the assertion is rewritten
to pin both halves: the assignment, and that the preflight reads that
binding after it.

test_source_read_encoding flagged a read_text() without an encoding in
my own test file, which breaks on Windows the moment the file it reads
gains a non-ASCII byte.

test_non_gguf_reload_settings also fails in that job and is NOT this
branch: it fails identically on current origin/main.

* Studio: close the last five cache-backed reads past the sentinel

seed inspect passed the sentinel to load_dataset(streaming=True) without
disabling local resolution. Offline, datasets satisfies the load from its
own cache and the sentinel never reaches an authorization check, so a
previously cached private dataset came back as preview rows. Refused the
same way check-format already refuses.

scan_model_remote_code took the body token raw, so an absent one read as
None, i.e. ambient-authorized, and a caller naming an exact cached
snapshot got the repo's Python scanned and its source snippets returned.
It resolves through allow_ambient_hf_token now like every other route.

_load_config_json keyed its memo on the token but still called
_config_json_from_hf_cache on the offline branch and on both transient
error fallbacks, so max_position_embeddings and friends came off disk for
a caller who could not authorize. Keying a memo apart does not help when
the value it memoizes came off disk to begin with.

get_gguf_variants_answer: siblings is None means list_gguf_variants
already answered from its own repo-wide cache. Declining to build a
second cached response left the first one to be serialized on the
fall-through, so for an unauthorized caller a cache-only answer is now a
refusal rather than a decline.

prepareHfTokenForUse cleared its maps on logout but could not cancel a
request already in flight, so a late resolution wrote the raw bearer
token back into recentlyValid -- and expiry only runs during another
preparation, so it stayed. A generation counter makes a stale resolution
non-cacheable.

Tests: five regressions, three parametrized over all token states, all
verified to fail with their fixes reverted.

* Studio: seed the token-change subscription from the current store

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.

* Studio: apply the repo formatter to this branch's two new test files

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.

* Studio: four more sentinel gaps, including a size regression of mine

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.

* Studio: the last two cache reads the sentinel reached but did not stop

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.

* Studio: state the offline-anonymous rule once instead of per reader

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.

* Studio: teach the export stub test about anonymous_and_offline

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.

* Studio: shorten this branch's comments

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.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant