Repository navigation
Studio: keep an API key from borrowing the operator's Hugging Face token (#10126) - #10142
danielhanchen merged 59 commits into
Conversation
efe42c9 to
ca42a37
Compare
97fbbd9 to
1746ea3
Compare
There was a problem hiding this comment.
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Pull request overview
Copilot reviewed 9 out of 9 changed files in this pull request and generated 3 comments.
253f56b to
74ef564
Compare
There was a problem hiding this comment.
💡 Codex Review
unsloth/studio/backend/core/export/export.py
Line 523 in 5d759df
When an API-key caller without hf_token loads a gated Transformers-5 checkpoint, this forwards False, but _is_vision_model_subprocess converts it to an empty argument and launches the child with child_env_without_native_path_secret(), which still inherits the operator's HF_TOKEN; the child then omits the explicit token keyword and AutoConfig authenticates implicitly. Fresh evidence beyond the earlier fixed in-process AutoConfig fallback is this separate vision-sidecar environment path at utils/models/model_config.py:889-920; strip HF credentials and disable implicit authentication for the False sentinel before spawning it.
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
c481a67 to
4ab5bb8
Compare
yep, stripped HF environment tokens and set HF_HUB_DISABLE_IMPLICIT_TOKEN=1 in _is_vision_model_subprocess when hf_token is False |
|
Confirmed the hole is still there on main, in data_recipe/jobs.py:562,595 and in the export routes, so gating the ambient token on the write paths is right. The part I would like narrowed is the False sentinel threaded through model_config.py, file_security.py, transformers_version.py and worker.py where the parameters are typed str or None; could you carry the policy as an explicit anonymous flag instead of overloading the token value? |
a262a88 to
81d1d26
Compare
hey @danielhanchen, Yep. Makes total sense. I've updated the PR and rebased onto latest
|
|
I have cut this back, and I owe an explanation because most of what I am removing is code I added. Twenty-eight review rounds is the signal. Classifying all 59 bot findings by what they landed on: 29 were about a private per-worker token store and its lifecycle, 19 about a shared-cache authorization gate, and 5 about the original scope. Both of those subsystems were mine, added during review, and neither is required by #10126. The findings were real, one after another, because the code under them kept being wrong; what they were reviewing should not have been there. The root cause is one decision. What is left is what the issue asks for. The recipe publish refusal, which is the one place the operator's token was actually handed over. The export routes resolving the credential as the anonymous sentinel instead of Removed: the token store and everything that grew around it, the per-command credential scope, and the One thing the removal re-opened, so I closed it directly: the merged local save was relying on the store, and now forwards the credential itself. I have cleared the settled threads. The five rejected findings and their replies are kept, since that is the live argument. Title and description are rewritten to match what the code now does, including that the export push refusal is a better error rather than a closed hole. Verified on this commit: 1807 passed and 4 skipped across the affected Sorry for the detour, @harshaygadekar. Your original change was closer to right than what I turned it into. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9ee0ea30f2
ℹ️ 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".
| Tuple of (success: bool, message: str) | ||
| """ | ||
| token = hf_token if hf_token and hf_token.strip() else None | ||
| token = normalize_token(hf_token) |
There was a problem hiding this comment.
Reauthorize anonymous cache-backed checkpoint loads
When an API-key or MCP caller omits hf_token and requests a private repository already present in the operator's shared Hugging Face cache, normalizing to False prevents ambient authentication but does not prevent from_pretrained from serving the cached weights (especially with local_files_only=True while offline); the caller can then export or push those private weights. Fresh evidence after the earlier confirmed fix is that the final tree removed the _access_allowed cache-authorization gate and now proceeds directly from this normalization to the shared-cache loader, so anonymous cache-backed targets must be refused or reauthorized.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this, and the reason is the reason the PR was just cut back. The phenomenon is real, I measured it earlier against a gated repo this host has cached: hf_hub_download and transformers cached_file both serve the operator's snapshot for token=False, online as well as offline. It is also unchanged from main, where the same caller received the operator's token outright and could fetch that repo from the network as well, so nothing here is a regression.
The gate you are asking for is the one I removed. It was an auth_check round-trip on every remote target, plus revision pinning, adapter-base resolution and provenance handling, and it produced three availability regressions I had to walk back one at a time: offline exports of local LoRAs, air-gapped loads of ordinary cached models, and a synchronous Hub call under the orchestrator's export lock. The correct fix is to partition the shared cache per credential, the way hub/services/models/gguf_variants.py:1277 already gates its own cache reads, applied consistently across the cache readers. That is a design change and a product decision, not something the export loader should carry, and it is now written into the description as an explicit boundary rather than half-solved here.
| if not config.get("allow_ambient", True): | ||
| apply_token_to_child_env(os.environ, config.get("hf_token") or False) |
There was a problem hiding this comment.
Re-scope the worker environment for every export caller
When a UI session loads the persistent worker and a later API-key caller starts a local export without hf_token, this load-time-only condition leaves the operator's ambient token in the worker environment even though the export command carries False. The LoRA-GGUF and compressed exporters copy os.environ for their child processes and only replace tokens for nonempty strings (unsloth/save.py:5761-5764 and 7238-7242), so those children can fetch a private base config or calibration data with the operator credential. Fresh evidence after the earlier per-command isolation fix is that the final tree removed _credential_scope and retained only this worker-wide decision; scrub or grant credentials around each export command instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this either, same reasoning. The cross-caller case is real and it is stated: an export runs under the identity that loaded the checkpoint, and the orchestrator spawns a fresh worker per load, so a later load re-decides.
Per-command re-scoping is what I removed, and it cannot deliver the symmetric rule it appears to. huggingface_hub freezes HF_HUB_DISABLE_IMPLICIT_TOKEN into a module constant at import, so a command can tighten the worker's credentials but can never restore ambient use for a UI caller that follows an API-key load. The result is a rule that only works one way, in a process that outlives the request, which is exactly the mismatch that produced twenty-eight rounds here: a per-request policy enforced inside a per-worker process. Re-adding it walks back into that.
Keeping the worker-wide decision is the coherent version: one identity per worker, decided at load, stated in the code and in the description. If per-caller export identity is wanted, the answer is a worker per credential scope, which is a real design change rather than another guard.
|
Codex Review: Didn't find any major issues. Delightful! 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". |
|
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". |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
…ambient Three things the write-path gating did not cover, found by running the caller, route, platform and worker-sequence combinations against the branch. The worker kept the caller's own token. `apply_token_to_child_env` grants for a string and only scrubs for the sentinel, and the worker passed it `config["hf_token"] or False`, so an API-key caller that supplied a token of its own left it in `HF_TOKEN` with `HF_HUB_DISABLE_IMPLICIT_TOKEN=0`. That process outlives the load: `load_checkpoint` is the only thing that respawns a worker and every later export command reuses whichever one is alive, whoever sends it. So the next caller's `save_pretrained_merged`, which passes no token when it has none of its own, resolved `get_token()` to the previous caller's credential. It is the same leak this file exists to close, pointing the other way. A non-ambient worker now holds no credential at all; the caller's own travels as an argument, and the helper still grants it per child that needs it, so nothing loses access it had. `HF_OIDC_RESOURCE` was not scrubbed. It is not a token but it names one: huggingface_hub 1.23 and later exchange it for a short-lived credential inside `get_token()`, ahead of `HF_TOKEN`, and studio.txt pins that range for every supported interpreter. On a Trusted-Publisher host the scrub therefore left a second road to an operator-scoped token. Harmless on older versions, which have no OIDC source. `export_gguf` still declared `hf_token: Optional[str]` while the sentinel reaches it, alone among the five entry points. That is the annotation that invites the next reader to normalise `False` back to `None`. Tests. A regression test for the cross-caller case that reads what `get_token()` resolves to inside the worker rather than only the environment. Three structural guards, because nothing enumerated these before and a new endpoint would ship ungated in silence: every export entry point declares the sentinel type, every Hub write route declares the ambient policy, and every MCP tool that calls a gated route names it, since a direct Python call never resolves a `Depends` default. Each is mutation-checked. The worker-environment case that asserted the caller's token was kept now asserts it is passed instead.
|
Reviewed this end to end and pushed 33b34b4 with three fixes. The write-path gating is right and the load-path argument is right; I verified both rather than taking them on trust, and then found three things the gating does not cover. The premise, measured rather than readThe suite asserts the and with Base versus head on the publish path, same test against both trees:
The description's own correction is accurate: the four export pushes were already refused without a token at What I changedThe worker kept the caller's own token. and the consuming end: for a later caller with no token of its own,
Plus three structural guards, since nothing enumerated any of this and a new endpoint would ship ungated in silence: every export entry point declares the sentinel type, every Hub write route declares the ambient policy, and every MCP tool calling a gated route names it, because a direct Python call never resolves a How it was tested175 combinations of caller shape, route, platform and worker sequence: Availability was checked as deliberately as the leak: an API-key caller with its own token still reaches every preflight helper and the loader, on both policies. Also confirmed no UI-session flow is refused anywhere in the matrix, no frontend file changes so no browser path is affected, an old saver with no The full backend leg as CI runs it, before and after 33b34b4, gives an identical failure set (34, all reproducing on the merge base in my environment, diffusers and peft pins) with 37178 passing against 37174. All eight production hunks of the original change are mutation-caught, and a full revert is caught by 10 of the 14 test functions; the four survivors are back-compat characterisations rather than fix coverage, which is the right shape for them. Left open, deliberatelyAn export still runs under the identity that loaded the checkpoint, so a non-ambient export command in a worker a UI session loaded can still reach the operator's environment through any call that passes no token, |
…s on huggingface_hub reads HF_HUB_DISABLE_IMPLICIT_TOKEN once, into a module constant, so the scrub in run_export_process only works while nothing has imported it yet. An import added anywhere in the worker's module chain would silently disable the switch with every other test in this file still green, because they only read os.environ. A subprocess now asserts that importing core.export.worker leaves huggingface_hub out of sys.modules. Also drops a get_token() assertion added in the previous commit. It read as "nothing is reachable", but get_token() also reads the operator's stored login off disk, which no environment change touches; that is the reason the sentinel is threaded to the loaders in the first place, and asserting it in-process only passed because no token file existed there. The environment assertion beside it is the one an in-process test can honestly make.
|
Codex Review: Didn't find any major issues. Delightful! 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". |
|
You have reached your Codex usage limits for security reviews. Please try again later. |
Fixes #10126. Follows #8433 and #10076, which did the download paths.
The hole
The operator's ambient
HF_TOKEN, whether from the host environment or Studio Settings, is an operator credential. Ansk-unslothAPI key is refused that token byrequire_ui_session, so it must not reach it another way.One write path handed it over outright.
publish_job_datasetpassedhf_token=Nonetopublish_recipe_dataset, which gives it straight toHuggingFaceHubClientandcard.push_to_hub(core/data_recipe/huggingface.py:74,99), so a dataset published by an API-key caller was published as whoever the host is logged in as.The load path was subtler and is the larger part of the change. Even with the environment scrubbed,
Noneis not anonymous to this stack: unsloth reads it as go and find a credential, spelledif token is None: token = get_token()insave.pyand inhf_login(models/_utils.py:4106), andget_token()reads the operator's stored login from~/.cache/huggingface/token, which no environment change touches. Measured in a spawned worker:So an API-key checkpoint load ran as the operator on any host where the operator had ever run
hf auth login, which is the normal state.The change
allow_ambient_hf_token, the dependency #10076 added for downloads, now also gates the write and load paths:_resolve_export_hf_token, which returns the anonymous sentinel (hub/utils/hf_tokens.HfTokenArg) rather thanNone, and refuses a Hub push without a token. The push refusal is a better error rather than a closed hole:core/export/export.pyalready declined a push without an explicit token, so ambient credentials were never reachable there.HF_HUB_DISABLE_IMPLICIT_TOKENbeforehuggingface_hubis imported, via the existingapply_token_to_child_env. It then rebuilds the canonicalHfTokenArgonce and uses it for the whole preflight and forExportBackend.load_checkpoint, so the sentinel reaches the detection probes, the weight loaders and the local GGUF and merged saves instead of collapsing toNone.Dependsdefault.An export runs under the identity that loaded the checkpoint. The orchestrator spawns a fresh worker per load, so a later load re-decides.
What this does not do
The shared Hugging Face cache still answers from disk without reauthorizing, so a caller who is denied the ambient token can still be served content the operator cached. That is unchanged from main and is a read-path question about partitioning the cache per credential, which belongs in its own change rather than in the export loader.
Testing
studio/backend/tests/test_hub_write_ambient_token.pycovers the publish refusal and its two allowed shapes, the four export routes for push refusal, push with a token, and local export identity, the load-checkpoint policy, the worker environment for each policy including a pre-change config, the preflight credential, the loader never receivingNone, the upstreamhf_logincontract, and the local GGUF and merged saves.Verified locally: 1807 passed, 4 skipped across the affected
studio/backend/tests; the same suites give 51 passed, 1 skipped with unsloth unimportable, which is a supported torch-less install; and a real load plus merged export through the actual spawned worker succeeds in both modes on an RTX 6000 Ada and a 3090 with the operator's token planted in the environment and absent from the worker's output.