Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
160 commits
Select commit Hold shift + click to select a range
5ec8e27
Post-release: bump version to 1.30.0.dev0 (#4763)
huggingface-hub-bot[bot] Aug 27, 2026
ae20a50
[CI] Enable enforcement in close-unscoped-community-prs workflow (#4766)
hanouticelina Aug 27, 2026
97655e8
Align `hf jobs scheduled ls` filtering with `hf jobs ls` (`--status`/…
moon-bot-app[bot] Aug 28, 2026
1de4817
[Download] Follow redirects between Hub hosts when resolving files (#…
hanouticelina Aug 28, 2026
4cc16bc
[Download] A `ResolvedRevision` only pins the repo it was resolved fo…
Wauplin Aug 28, 2026
94cb25d
[CI] Fix torch_1.11 case-arm label to match renamed matrix entry (#4776)
MohammedAlkindi Aug 31, 2026
6a2eb09
[Sandbox] Document experimental status (#4783)
Wauplin Sep 1, 2026
f0a5c6d
[Inference Providers] Do not require the conversational tag for chat-…
hanouticelina Sep 1, 2026
176d4f3
[CI] Disable auto close (#4800)
Wauplin Sep 2, 2026
b84090b
[Release] Consolidate the HF CLI skill sync into the release workflow…
hanouticelina Sep 3, 2026
c804cdd
Post-release: bump version to 1.31.0.dev0 (#4806)
huggingface-hub-bot[bot] Sep 3, 2026
15bb844
Bump the actions group across 1 directory with 5 updates (#4798)
dependabot[bot] Sep 4, 2026
deb9777
[Docs] Clarify Jobs argument forwarding and align examples (#4809)
davanstrien Sep 4, 2026
634ad9b
[httpx migration] Expose `httpx` as a `huggingface_hub` submodule (#4…
Wauplin Sep 7, 2026
f1bb85f
[hf_api] Make CommitInfo copy-able and pickle-able (#4822)
Wauplin Sep 7, 2026
21e687e
[Download] Prevent cached file copies during local-dir dry runs (#4817)
wakamex Sep 7, 2026
6c8c56b
Fix: keep single-quoted values verbatim in load_dotenv (#4827)
AnishPatel526 Sep 8, 2026
a9b9ac6
[CLI] Fix 'hf buckets rm --recursive' deleting lexical siblings of th…
Wauplin Sep 8, 2026
01fe4bc
[Sandbox] Support custom Job labels (#4824)
Wauplin Sep 8, 2026
204b717
[CLI] Don't let `hf update` self-upgrade a pip install on Windows (#4…
Wauplin Sep 8, 2026
aa3c2fd
[HfFileSystem] Reject unsafe paths before local downloads (#4828)
Wauplin Sep 8, 2026
9d7bbfe
[Download] Share retry handling for stream entry and body failures (#…
Wauplin Sep 8, 2026
8934ec0
[Download] Tolerate missing HEAD Content-Length (#4805)
Wauplin Sep 8, 2026
b9c14d9
[Download] Write cache ref file atomically in `snapshot_download` (#4…
Wauplin Sep 8, 2026
063b37b
[CLI] Raise explicit error for shell-script extensions on Windows (#4…
hanouticelina Sep 9, 2026
6cae778
[Jobs] Add network groups to hf jobs run (#4833)
co42 Sep 9, 2026
22fe960
Fix dotenv parser truncating unquoted values containing '#' (#4842)
BenYang12 Sep 9, 2026
c4f076c
(LFS)Fix SliceFileObj.__iter__ yielding only the first 4MB chunk (#4844)
BenYang12 Sep 9, 2026
f148666
[CLI] Fix truncated command descriptions in the CLI reference (#4849)
hanouticelina Sep 9, 2026
ff4292b
Post-release: bump version to 1.32.0.dev0 (#4856)
huggingface-hub-bot[bot] Sep 10, 2026
a2af2e0
docs(jobs): scope network groups to the namespace and resource group …
co42 Sep 10, 2026
0790f7b
[Community] Fix docstring for DiscussionComment.last_edited_by (#4864)
Saniyagupte Sep 10, 2026
bf85073
fix(sandbox): preserve terminal command results (#4851)
evalstate Sep 10, 2026
819cd77
[CLI] Read a UV script's `[tool.hf-jobs]` launch config (opus-generat…
Wauplin Sep 10, 2026
b853ec6
Add `--container-registry-{username,password}` (#4854)
alvarobartt Sep 10, 2026
e203a7f
fix(serialization): save_torch_state_dict cleanup regex silently matc…
g0rdonL Sep 10, 2026
3493edb
Bump the actions group with 4 updates (#4848)
dependabot[bot] Sep 10, 2026
4110cac
Key the doc build concurrency group on the pull request number (#4876)
albertvillanova Sep 11, 2026
edb2c83
[Buckets] Fix file metadata size on redirects (#4874)
davanstrien Sep 11, 2026
5694eda
[RepoCard] Fix AttributeError when model-index has source: null (#4870)
Saniyagupte Sep 11, 2026
b2678ec
[Spaces] Fix AttributeError in SpaceRuntime when hardware is null (#4…
Saniyagupte Sep 11, 2026
8a408cd
[CI] Make CI less flaky and stop 6h hung jobs (#4830)
Wauplin Sep 11, 2026
dd6919c
[Serialization] Harden torch checkpoint deserialization (#4877)
Wauplin Sep 11, 2026
9588035
feat(jobs): expose the network group on JobInfo (#4862)
co42 Sep 11, 2026
129bbb5
[Http] Fix race in get_session() creating multiple clients (#4868)
hanouticelina Sep 11, 2026
98e2db8
[CLI] Make --format human override agent auto-detection (#4878)
hanouticelina Sep 14, 2026
c5ff040
[Serialization] Sync `_get_dtype_size` with safetensors (#4902)
Wauplin Sep 14, 2026
f1e70a2
[Safetensors] Recognize proposed U3 metadata (#4898)
7dsolv Sep 14, 2026
fb21643
[Download] Fix silently disabled tree cache on long Windows paths (#4…
askalf Sep 14, 2026
490f06e
docs: make the sandbox security contract match the implementation (#4…
Wauplin Sep 14, 2026
1fb5b3b
feat(sandbox): use each pooled sandbox's own capability token (#4832)
Wauplin Sep 14, 2026
ef2662f
fix(sandbox): validate a pool host before sending it a credential (#4…
Wauplin Sep 14, 2026
40efc5e
fix(sandbox): bind the pool cache to the context that wrote it (#4838)
Wauplin Sep 14, 2026
0613ead
fix(sandbox): bound what a transfer or a command's output costs the c…
Wauplin Sep 14, 2026
c7e60d8
fix(sandbox): decide host teardown per host, and report it honestly (…
Wauplin Sep 14, 2026
ec61993
fix(sandbox): address background processes by their server-assigned i…
Wauplin Sep 14, 2026
0219ad5
[sandbox audit] Pin the sandbox server binary by digest and verify it…
Wauplin Sep 14, 2026
1173050
[sandbox audit] Keep secret values out of argv in the CLI and fix the…
Wauplin Sep 14, 2026
48cdc03
Fix doubled colon in snapshot download transfer bar description (#4890)
sandeepb2013 Sep 14, 2026
a3b62f6
[CLI] Add `hf --skills` as an alias for `hf skills preview` (#4906)
Wauplin Sep 14, 2026
bd9ece0
[CLI] Support file URIs in hf cache rm (#4847)
hanouticelina Sep 14, 2026
0a57df9
[Core] Restrict repo_id validation regex to ASCII word characters (#4…
bodapatisaikrishna Sep 15, 2026
af6b41e
[Core] Reject path traversal via embedded ".." segments in path_in_re…
bodapatisaikrishna Sep 15, 2026
2075fd6
[Cache] Support kernel repos in `hf cache` commands (#4905)
hanouticelina Sep 15, 2026
5a9cdda
[Core] Speed up package imports (#4914)
Wauplin Sep 15, 2026
6e3d21f
[Cache] Add cross-repo shared blob store (#4498)
hanouticelina Sep 17, 2026
f94ea55
[Buckets] Send mtime when copying files (#4920)
Wauplin Sep 17, 2026
d7b62c7
[CLI] Fix card data serialization (#4882)
davanstrien Sep 17, 2026
79dd41e
[Docs] Fix hf discussions info options that do not exist (#4886)
rishabhsai Sep 17, 2026
b064a14
[Download] Send X-HF-Download-Counter header on download calls (#4613)
Wauplin Sep 17, 2026
e9c55ce
Post-release: bump version to 1.33.0.dev0 (#4926)
huggingface-hub-bot[bot] Sep 17, 2026
618250b
[Download] Publish symlink support only after probing (#4923)
Wauplin Sep 17, 2026
77b6b2b
[Core] Skip invalid eval results entries instead of raising (#4924)
davanstrien Sep 17, 2026
34ae660
[Cache] Use posix paths for scan_cache_dir ref names (#4925)
gokay-ai Sep 18, 2026
0ba990a
[Download] Measure http_get progress from the initial file position (…
Wauplin Sep 18, 2026
cea607a
[Serialization] Fix device type when map_location is None (#4938)
Wauplin Sep 18, 2026
83ba61a
[CLI] Honor --format / --json / -q on jobs run commands (#4936)
Wauplin Sep 18, 2026
8c9546f
[Quality] Replace `re.match` with `re.fullmatch` / `re.search` and ba…
Wauplin Sep 18, 2026
22b5e87
[Docs] Sync provider task table with the PROVIDERS registry (#4930)
rishabhsai Sep 18, 2026
8efc0a9
[HfFileSystem] Make lpath optional in get_file (fsspec>=2026.9.0) (#4…
assafvayner Sep 21, 2026
4c80e7e
Fix `format_timesince` showing "60 seconds ago" / "60 minutes ago" / …
Sreekant13 Sep 21, 2026
55668e2
Fix Windows conftest erroring test subsets on lazy-loaded file_downlo…
dltsum Sep 21, 2026
7ce68b9
[Webhooks] Allow `bucket` as a watched item type (#4958)
davanstrien Sep 21, 2026
7025391
[MCP] Follow nextCursor when listing tools in MCPClient (#4960)
Kayvan-Zahiri Sep 22, 2026
80aef09
Align the `hf` package's python_requires with huggingface_hub (#4959)
sharziki Sep 22, 2026
94cf392
Remove dots from allowed characters in job labels. (#4962)
evalstate Sep 22, 2026
8d4fba6
[CLI] Honor `CLAUDE_CONFIG_DIR` in `hf skills add -g --claude` (#4957)
hanouticelina Sep 22, 2026
aa8742c
[CLI] Always install skills for Claude Code, deprecate --claude (#4967)
hanouticelina Sep 22, 2026
ce69fdb
[Buckets] Raise when a batch reports failed operations (#4954)
hanouticelina Sep 22, 2026
0f88f32
[Download] Extend tmp .incomplete path on Windows when too long (#4978)
Wauplin Sep 23, 2026
7532272
Fix HfFileSystem.get_file with a bare local filename (#4981)
davanstrien Sep 23, 2026
da5e244
Scope GITHUB_TOKEN permissions per job (#4982)
hf-security-analysis[bot] Sep 23, 2026
1e0c305
Send PrivateLink config under privateService in create_inference_endp…
co42 Sep 23, 2026
b904b94
Apply the repo_id length limit to the namespace as well (#4988)
anishmehta24 Sep 24, 2026
ac3ed2f
[Xet] Show Validating progress during shard finalization (#4478)
seanses Sep 24, 2026
fa26f34
[CI] Support major (pre-)releases in release workflow (#4991)
Wauplin Sep 24, 2026
c2e6e0a
Post-release: bump version to 1.34.0.dev0 (#4993)
huggingface-hub-bot[bot] Sep 24, 2026
9f51867
[Release] Prepare huggingface_hub 2.0 (#4994)
Wauplin Sep 24, 2026
89ae51f
unbump
Wauplin Sep 24, 2026
f5b624c
Post-release: bump version to 2.1.0.dev0 (#4999)
huggingface-hub-bot[bot] Sep 24, 2026
32456ab
[Buckets] Make include/exclude patterns case-sensitive on all platfor…
Wauplin Sep 25, 2026
c749dfa
Support secrets on Job-triggered webhooks (#5009)
moon-bot-app[bot] Sep 25, 2026
ee4f802
[HTTP] Fix repo_id in errors for query strings and download URLs (#5008)
Wauplin Sep 25, 2026
79874bc
[Buckets] Fix copy_files treating lexical siblings as an existing des…
AnishPatel526 Sep 25, 2026
ff0ccab
[CI] Bump doc-builder workflows pin to 63ec6f1 (#5010)
Wauplin Sep 25, 2026
34e8baa
[docs] xet caching and concurrency updates (#4883)
cbensimon Sep 25, 2026
62a1f2f
[HfFileSystem] Download Xet files with hf_xet in get_file (#4990)
hanouticelina Sep 25, 2026
e155ad3
[docs] Fix hf.cos typo in repository guide link (#5016)
pratikgx Sep 28, 2026
a076863
[datasets sql] Run the DuckDB CLI subprocess with UTF-8 encoding (#5020)
825pranav Sep 28, 2026
b15915b
[Auth] Store token names as UTF-8 instead of locale encoding (#5021)
Evolian-o Sep 28, 2026
41222c5
Fix scalar tags splitting into single-character list in card front ma…
zeenat28-ui Sep 28, 2026
14ee250
[CLI] Hint to use --global after local 'hf skills add/update' (#5024)
Wauplin Sep 28, 2026
f151320
[Sandbox] Require scoped credentials for pooled sandboxes (#4782)
Wauplin Sep 28, 2026
f64c26e
[Dataclasses] Accept bare typing.List/Dict/Set in @strict validation …
anishmehta24 Sep 29, 2026
7caeebb
Suggest `hf auth login` when `hf auth whoami` fails (#5033)
moon-bot-app[bot] Sep 29, 2026
5583746
[CLI] Align 'hf auth whoami' not-logged-in message with 'hf auth toke…
Wauplin Sep 29, 2026
862f23d
[Sandbox] Pin sbx-server 0.7.0 (protocol 3) (#5028)
Wauplin Sep 29, 2026
1b8b2fa
[CLI] Escape control characters in listings and table output (#5029)
Wauplin Sep 29, 2026
548f7e3
[Jobs] Allow rescheduling scheduled jobs (#5026)
Wauplin Sep 29, 2026
3fd18f2
[Jobs] Manage public and private exposed ports (#5027)
Wauplin Sep 29, 2026
231a2eb
[Jobs] Add rerun and retry attempts (#5025)
Wauplin Sep 29, 2026
d889712
[Tests] Reduce redundant Hub calls in repo settings and move tests (#…
Wauplin Sep 29, 2026
cc2f368
[Utils] Retry the first pagination page (#5035)
Wauplin Sep 29, 2026
1092497
[Spaces] Update docs for cpu-basic gating and dev mode disabling (#5037)
Wauplin Sep 29, 2026
013afa7
[CLI] Raise if a bare --secrets NAME is not set locally in hf jobs (#…
Wauplin Sep 30, 2026
83a714e
[CLI] Update hf upload help text after upload_large_folder removal (#…
davanstrien Sep 30, 2026
881a6c4
[Docs] Fix links in i18n issue template (#5051)
pratikgx Oct 1, 2026
60fdb08
[Docs] Fix duplicated words in docstring and comments (#5052)
Ad1th Oct 1, 2026
b5e3a12
[HfApi] Support resource_group_id in duplicate_repo (#5038)
Wauplin Oct 1, 2026
3bb08e2
[Endpoints] Migrate catalog to the new /api/v1 API (#4928)
Wauplin Oct 1, 2026
4c88ea6
[Repos] Warn when duplicated repo files are still being copied (#5041)
Wauplin Oct 1, 2026
604252e
[HfApi] Add visibility to create_bucket (#5053)
hanouticelina Oct 1, 2026
0b26b50
[Spaces] Add get_zero_gpu_quota and hf spaces zero-gpu-quota (#5040)
Wauplin Oct 1, 2026
ff61343
Post-release: bump version to 2.2.0.dev0 (#5054)
huggingface-hub-bot[bot] Oct 1, 2026
b3fa3a4
[CLI] Rename 'hf spaces zero-gpu-quota' to 'hf spaces zero-gpu quota'…
Wauplin Oct 1, 2026
7da19ff
[CI] Split tests into api / transfer / inference suites (#5042)
Wauplin Oct 1, 2026
7a54109
[Tests] Always clean up staging repos and buckets created by tests (#…
Wauplin Oct 1, 2026
1a76ad2
[CI] Reduce flaky tests: isolate jedi cache, sleep before read-after-…
Wauplin Oct 1, 2026
c31df86
[Bugfix] Fix wrong exception type and unbound variable guard (#5063)
vector15-05 Oct 2, 2026
37ce057
[CLI] Upload existing paths with glob characters as-is in hf upload (…
Ganesh2325 Oct 2, 2026
0ce4427
[Download] Warn when allow/ignore patterns match no files in snapshot…
Ad1th Oct 2, 2026
a625317
[Repocard] Respect configured endpoint when validating cards (#5069)
Wauplin Oct 2, 2026
d711944
[CLI] Read env/secrets files as UTF-8 and strip the BOM (#5066)
hanouticelina Oct 2, 2026
42f9085
[Setup] Install hf-xet on Windows ARM64 (#5074)
angt Oct 5, 2026
d699913
[Docs] Fix HTTP migration and async session references (#5079)
Yuilona Oct 5, 2026
bc9b691
Bump doc-builder workflow pin (#5087)
paulinebm Oct 5, 2026
3b05c63
[Jobs] Ignore 406 from metrics endpoint for finished jobs (#5091)
hanouticelina Oct 6, 2026
e817417
Bump doc-builder pin to 9fc8a41 in build_documentation.yaml (#5093)
paulinebm Oct 6, 2026
9071b17
[Jobs] Fix no-follow logs hanging while the job keeps printing (#5092)
hanouticelina Oct 6, 2026
68becf4
[CommitScheduler] Fix race that skips the first scheduled push (#5086)
hanouticelina Oct 6, 2026
ff4c989
[CLI] Print [] from hf jobs stats --json when no jobs are running (#5…
hanouticelina Oct 6, 2026
83ce8b0
[Download] Consider port when following /resolve redirects (#4942)
assafvayner Oct 6, 2026
a5277cf
[CLI] Snapshot by default in hf jobs stats, add -f/--follow (#5090)
hanouticelina Oct 6, 2026
14a48e7
[HfFileSystem] fix `ls()` on new empty bucket (#5097)
lhoestq Oct 7, 2026
38e0b3c
[HfFileSystem] Replace cached listings instead of appending to them (…
ChihebBENCHEIKH1 Oct 7, 2026
af74167
[Tests] Wait for bucket listings after writes (#5095)
hanouticelina Oct 7, 2026
cf992a9
[HfFileSystem] Make refresh=True clear cached not-found results (#5106)
hanouticelina Oct 7, 2026
bb3a875
[Docs] Fix from_pretrained integration example (#5105)
Ayushdevo Oct 7, 2026
8abbfe5
Fix race in `_get_version` that makes concurrent downloads skip hf_xe…
BramVanroy Oct 7, 2026
3cfa593
Guard upload_pr_documentation workflow to upstream repo only
g0rdonL Oct 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat(sandbox): use each pooled sandbox's own capability token (huggin…
…gface#4832)

The pool host's token authorized every sandbox on the host plus its
management routes, and it was the only credential the client had. So every
per-sandbox call -- and `proxy_headers`, which is handed to browsers and
WebSocket clients -- offered authority over the whole host.

sbx-server 0.6.0 mints a capability token per sandbox. This uses it:

- `_SandboxServer.request`/`stream` take an optional `sandbox_token` that
  overrides `X-Sandbox-Token` for one request; the client-level header keeps
  carrying the host credential for management calls.
- `Sandbox` holds its own token and sends it on every scoped call, including
  the `DELETE` that kills a pooled sandbox.
- `SandboxPool.create()` keeps the token from the create response.
- `Sandbox.connect("<host>.<id>")` recovers it via
  `GET /v1/sandboxes/{id}/token`, so reattaching stays stateless.
- `proxy_headers` hands out the sandbox's token, not the host's.

Hosts running an older server return no token and have no recovery route;
those sandboxes fall back to the host credential, so a pool booted before
the server upgrade keeps working. Requires the server change to be deployed
first.

Also makes the test fake enforce the same scoping as the real server --
host token on management routes, the sandbox's own token on scoped ones --
rather than accepting one value everywhere. That laxness is exactly how a
client/server protocol mismatch survives a green suite, and it caught two
of this change's own call sites while writing it.

Validation:
- 44 tests pass, including new ones asserting per-sandbox operations present
  the scoped token, `proxy_headers` does not leak the host one, and the
  older-server fallback still works.
- Driven end-to-end against a real sbx-server 0.6.0 in a container: A's
  token cannot exec, read, write, delete or proxy into B, cannot create,
  list or delete sandboxes, and cannot recover any token; the host token
  recovers A's token and matches.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
  • Loading branch information
Wauplin and claude authored Sep 14, 2026
commit 1fb5b3b3216c9d164e78a7e0312b3c2b1ffbdbc0
19 changes: 13 additions & 6 deletions docs/source/en/concepts/sandbox.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,22 @@ The token is delivered to the server via a Job secret. The client re-derives it

### Token scope

One nonce is minted per **Job**, not per sandbox. That distinction matters in pool mode:
One nonce is minted per **Job**, so the derived token is a *job* credential. In dedicated mode the job is the sandbox, so the two coincide. In pool mode the job is the host, and a host holds many sandboxes — so a pooled sandbox gets a second, narrower credential of its own:

| mode | how many tokens | what a leaked token gives access to |
| credential | derived how | authorizes |
| --- | --- | --- |
| dedicated (`Sandbox.create`) | one per job, and the job *is* the sandbox | that sandbox |
| pool (`SandboxPool`) | one per **host job**, shared by every sandbox packed on it | **every sandbox on that host**, current and future, plus the host's management routes (create/list/delete sandboxes) |
| **dedicated sandbox token** | `HMAC(hf_token, nonce)` from the job's label | that sandbox (which is the whole job) |
| **pool host token** | `HMAC(hf_token, nonce)` from the host job's label | pool management: create, list and delete sandboxes on that host, and recover their tokens |
| **pooled sandbox token** | random 256 bits, minted by the host server per sandbox | that one sandbox — not a sibling, not the pool |

So in a pool, a token leak is a host-wide event, not a per-sandbox one. Members of your namespace hold a different HF token and cannot derive yours — but see [Known limitations](#known-limitations) for how a token can be *delivered* to the wrong place.
The client uses the narrow one automatically: `pool.create()` receives it in the create response, `Sandbox.connect("<host>.<id>")` recovers it with the host token, and [`proxy_headers`] hands out the sandbox's token rather than the host's — those headers usually end up in a browser or WebSocket client, so they should confer access to one sandbox and nothing more.

What this means for a leak: a **pooled sandbox token** compromises that sandbox. A **host token** compromises the host — every sandbox on it, current and future, plus its management routes — so treat it as the pool's admin credential. Members of your namespace hold a different HF token and cannot derive yours, but see [Known limitations](#known-limitations) for how a token can be *delivered* to the wrong place.

> [!NOTE]
> During the rollout the host server still accepts the host token on per-sandbox routes, so
> clients that predate per-sandbox tokens keep working. That is a management credential
> reaching the sandboxes it created; a sandbox credential can never reach a sibling.

## Dedicated sandboxes (`Sandbox.create`)

Expand Down Expand Up @@ -229,7 +237,6 @@ This section is deliberately exhaustive rather than reassuring: if you are decid

Both require a legitimate caller to invoke the endpoint (the sandbox has no token of its own), so they are confused-deputy problems rather than direct escapes — but they do break confidentiality and integrity between pooled sandboxes.
- **Host discovery trusts Job labels.** Hosts are found by filtering Jobs on labels, which any Job creator in the namespace can set, and the nonce that derives the token is a public label. Nothing binds a Job to its creator, image, or pool. In a namespace whose members do not all trust each other, prefer `Sandbox.create`, or use a namespace you control for pools.
- **One token per host.** See [Token scope](#token-scope).
- **Landlock can degrade silently.** If Landlock is unavailable, or its ruleset cannot be built, the server currently falls back to uid-only isolation and creates the sandbox anyway — without telling the client. Under uid-only isolation, `/tmp`, `/dev/shm`, TCP bind and cross-home filesystem access are *not* denied. The server also accepts Landlock ABI 1, while the ✅ list above needs ABI 4 (TCP bind) and ABI 6 (abstract sockets); production kernels provide ABI 6, but a lower one would silently drop those two guarantees.
- **Residual shared channels**, none of which Landlock or uid isolation closes: unrestricted outbound TCP; loopback access to the control server; **UDP bind is allowed** (Landlock has no UDP coverage); a sibling's `/proc/<pid>/cmdline` and `status` are readable (`environ` is not — that is the part that would leak credentials, and it is denied); `/proc` and `/sys` are readable and `/dev` is broadly readable and writable; kernel IPC and all machine resources are shared.
- **No CPU, disk, FD or total-memory quotas.** Only per-process `RLIMIT_NPROC` and `RLIMIT_AS` are set; cgroup delegation is not available on Jobs. One sandbox can starve its neighbours. The `max_procs`/`max_mem_mb` values are caller-supplied and not clamped server-side.
Expand Down
80 changes: 70 additions & 10 deletions src/huggingface_hub/_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,10 @@ def _derive_sandbox_token(hf_token: str, nonce: str) -> str:
itself is not.

Scope: one nonce is minted per *job*, not per sandbox. For a dedicated sandbox those are
the same thing, but in a pool every sandbox on a host shares that host's token, which
also gates the host's management routes -- so a leak there is host-wide.
the same thing. In a pool this derives the *host* credential, which manages the pool and
can recover per-sandbox tokens -- a leak there is host-wide. Each pooled sandbox also has
its own random capability token, minted by the host server, which is what per-sandbox
operations and `proxy_headers` use.

This is not a hardened boundary in either direction. An untrusted image can own the
sandbox port, so don't treat it as a guarantee that credentials stay out of the sandbox;
Expand Down Expand Up @@ -430,23 +432,53 @@ def from_job(
def image(self) -> str | None:
return self._image

def request(self, method: str, path: str, **kwargs) -> httpx.Response:
def _with_token(self, kwargs: dict, sandbox_token: str | None) -> dict:
"""Override `X-Sandbox-Token` for one request.

The client-level header carries the *host* credential, which manages the
pool. A pooled sandbox's own operations should present that sandbox's
capability token instead, so nothing wider than the sandbox is offered on
a per-sandbox call.
"""
if sandbox_token is not None:
kwargs["headers"] = {**kwargs.get("headers", {}), "X-Sandbox-Token": sandbox_token}
return kwargs

def request(self, method: str, path: str, *, sandbox_token: str | None = None, **kwargs) -> httpx.Response:
"""Request to the in-job server. Raises SandboxError on API errors."""
timeout = kwargs.pop("timeout", httpx.Timeout(60.0, connect=10.0))
kwargs = self._with_token(kwargs, sandbox_token)
response = self._client.request(method, self.base_url + path, timeout=timeout, **kwargs)
if response.status_code >= 400:
_raise_for_status(response)
return response

@contextmanager
def stream(self, method: str, path: str, **kwargs) -> Iterator[httpx.Response]:
def stream(
self, method: str, path: str, *, sandbox_token: str | None = None, **kwargs
) -> Iterator[httpx.Response]:
"""Streaming request to the in-job server. Raises SandboxError on API errors."""
timeout = kwargs.pop("timeout", httpx.Timeout(70.0, connect=10.0)) # server pings every 15s
kwargs = self._with_token(kwargs, sandbox_token)
with self._client.stream(method, self.base_url + path, timeout=timeout, **kwargs) as response:
if response.status_code >= 400:
_raise_for_status(response)
yield response

def sandbox_token(self, local_id: str) -> str | None:
"""Recover a pooled sandbox's capability token, using the host credential.

Keeps reconnection stateless: `Sandbox.connect` can reattach to a sandbox
it never created. Returns `None` when the host runs a server that predates
per-sandbox tokens, in which case the caller falls back to the host token.
"""
try:
return self.request("GET", f"/v1/sandboxes/{local_id}/token").json()["token"]
except SandboxError as e:
if e.status_code == 404:
return None # older sbx-server: no such route
raise

def close(self) -> None:
self._client.close()

Expand Down Expand Up @@ -518,9 +550,17 @@ def __init__(
local_id: str | None,
owns_sandbox: bool,
owns_server: bool,
sandbox_token: str | None = None,
) -> None:
self.id = id
self._server = server
# Capability token for this sandbox alone (pool mode). Sent instead of the
# host credential on every per-sandbox call, so a pooled sandbox's
# operations -- and the headers handed to a port-proxy client -- confer no
# authority over its siblings or over the pool. None in dedicated mode
# (where the job is the sandbox, so the job token is already scoped to it)
# and on hosts running a server that predates per-sandbox tokens.
self._sandbox_token = sandbox_token
# None in dedicated mode; the host-local sandbox id in shared mode.
self._local_id = local_id
# Path prefix for all in-server operations: dedicated routes live under
Expand Down Expand Up @@ -668,10 +708,20 @@ def connect(cls, sandbox_id: str, *, namespace: str | None = None, token: str |
existing = {item["id"] for item in server.request("GET", "/v1/sandboxes").json()}
if local_id not in existing:
raise SandboxError(f"Sandbox {sandbox_id} no longer exists on host {host_job_id}.")
# Recover the sandbox's capability token with the host credential, so
# this handle operates with the narrow one from here on.
sandbox_token = server.sandbox_token(local_id)
except Exception:
server.close() # don't leak the HTTP client when the host is gone/unreachable
raise
return cls(id=sandbox_id, server=server, local_id=local_id, owns_sandbox=False, owns_server=True)
return cls(
id=sandbox_id,
server=server,
local_id=local_id,
owns_sandbox=False,
owns_server=True,
sandbox_token=sandbox_token,
)

job = api.inspect_job(job_id=sandbox_id, namespace=namespace)
labels = job.labels or {}
Expand Down Expand Up @@ -711,7 +761,7 @@ def _kill(self) -> None:
if self._local_id is None:
self._server.cancel_job()
else:
self._server.request("DELETE", f"/v1/sandboxes/{self._local_id}")
self._server.request("DELETE", f"/v1/sandboxes/{self._local_id}", sandbox_token=self._sandbox_token)
except Exception as e:
# Don't mark as killed: a later kill() call should retry so nothing leaks.
logger.warning(f"Failed to kill sandbox {self.id}: {e}")
Expand Down Expand Up @@ -941,10 +991,15 @@ def proxy_url_for(self, port: int | str, path: str = "/", *, scheme: str = "http

@property
def proxy_headers(self) -> dict[str, str]:
"""Auth headers to send with [`proxy_url_for`] requests (HF token + sandbox token)."""
"""Auth headers to send with [`proxy_url_for`] requests (HF token + sandbox token).

For a pooled sandbox this is the sandbox's own capability token, not the
pool host's: these headers typically end up in a browser or WebSocket
client, so they should confer access to this sandbox and nothing else.
"""
return {
"Authorization": f"Bearer {self._server._auth_token}",
"X-Sandbox-Token": self._server._sandbox_token,
"X-Sandbox-Token": self._sandbox_token or self._server._sandbox_token,
}

def __repr__(self) -> str:
Expand All @@ -953,11 +1008,13 @@ def __repr__(self) -> str:
# ------------------------------------------------------------------ internals

def _request(self, method: str, resource: str, **kwargs) -> httpx.Response:
return self._server.request(method, self._base_path + resource, **kwargs)
return self._server.request(method, self._base_path + resource, sandbox_token=self._sandbox_token, **kwargs)

@contextmanager
def _stream(self, method: str, resource: str, **kwargs) -> Iterator[httpx.Response]:
with self._server.stream(method, self._base_path + resource, **kwargs) as response:
with self._server.stream(
method, self._base_path + resource, sandbox_token=self._sandbox_token, **kwargs
) as response:
yield response


Expand Down Expand Up @@ -1646,6 +1703,9 @@ def _create_one(self, host: "_SandboxServer", env: dict[str, Any], idle_secs: in
local_id=item["id"],
owns_sandbox=True,
owns_server=False,
# Absent on hosts running a server that predates per-sandbox tokens;
# those keep using the host credential.
sandbox_token=item.get("token"),
)
sandbox._on_kill = self._on_sandbox_killed
return sandbox
Expand Down
59 changes: 55 additions & 4 deletions tests/test_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,20 @@ def _json(self, obj) -> None:
self.end_headers()
self.wfile.write(body)

def _expect_token(self) -> None:
"""Mirror the real server's credential scoping.

Management routes (`/v1/sandboxes`, token recovery) take the host token;
every per-sandbox route takes that sandbox's own capability token. Keeping
the fake as strict as the server is the point: a lax fake is how a client
bug like addressing a process by pid survives a green test suite.
"""
provided = self.headers["X-Sandbox-Token"]
parts = self.path.split("?")[0].strip("/").split("/")
scoped = len(parts) >= 3 and parts[:2] == ["v1", "sandboxes"] and parts[3:4] != ["token"]
expected = f"tok-{parts[2]}" if scoped else "secret"
assert provided == expected, f"{self.path}: expected {expected!r}, got {provided!r}"

def _exec(self, body) -> None:
type(self).last_exec = body
self._ndjson(
Expand All @@ -151,7 +165,7 @@ def _exec(self, body) -> None:
)

def do_POST(self) -> None:
assert self.headers["X-Sandbox-Token"] == "secret"
self._expect_token()
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
cls = type(self)
# exec (dedicated /v1/exec or shared /v1/sandboxes/<id>/exec)
Expand Down Expand Up @@ -181,11 +195,11 @@ def do_POST(self) -> None:
sid = f"sbx{cls.seq}"
cls.seq += 1
cls.sandboxes.add(sid)
created.append({"id": sid})
created.append({"id": sid, "token": f"tok-{sid}"})
self._json({"sandboxes": created, "rejected": rejected})

def do_DELETE(self) -> None:
assert self.headers["X-Sandbox-Token"] == "secret"
self._expect_token()
last = self.path.rsplit("/", 1)[-1]
if "/processes/" in self.path: # kill a background process
type(self).processes = [p for p in type(self).processes if str(p["pid"]) != last]
Expand All @@ -195,6 +209,7 @@ def do_DELETE(self) -> None:
self._json({"id": last, "deleted": True})

def do_GET(self) -> None:
self._expect_token()
cls = type(self)
if self.path.startswith("/v1/files/stat") or "/files/stat" in self.path:
self._json({"name": "x", "path": "/x", "type": "file", "size": 5})
Expand All @@ -207,6 +222,9 @@ def do_GET(self) -> None:
self._json(cls.processes)
elif self.path == "/v1/sandboxes":
self._json([{"id": sid} for sid in sorted(cls.sandboxes)])
elif self.path.startswith("/v1/sandboxes/") and self.path.endswith("/token"):
sid = self.path.split("/")[3]
self._json({"id": sid, "token": f"tok-{sid}"})


@pytest.fixture()
Expand Down Expand Up @@ -361,7 +379,15 @@ class TestSharedSandbox:
def _make_shared(self, base_url: str) -> Sandbox:
server = _make_server(base_url, capacity=10)
_FakeServer.sandboxes.add("local1")
return Sandbox(id="job123.local1", server=server, local_id="local1", owns_sandbox=True, owns_server=False)
return Sandbox(
id="job123.local1",
server=server,
local_id="local1",
owns_sandbox=True,
owns_server=False,
# What `SandboxPool.create()` would have received in the create response.
sandbox_token="tok-local1",
)

def test_base_path_is_scoped(self, fake_server: str) -> None:
sandbox = self._make_shared(fake_server)
Expand All @@ -376,6 +402,31 @@ def test_kill_deletes_sandbox_not_job(self, fake_server: str) -> None:
sandbox._server._api.cancel_job.assert_not_called() # host keeps running
assert "local1" not in _FakeServer.sandboxes

def test_per_sandbox_operations_present_the_sandbox_token(self, fake_server: str) -> None:
# The fake asserts the scoping itself (host token on management routes, the
# sandbox's own token on scoped ones), so any operation reaching the server
# is evidence the narrow credential was sent.
sandbox = self._make_shared(fake_server)
assert sandbox.run("echo").stdout == "out1"
assert sandbox.files.read_text("f") == "hello"
assert sandbox.processes() == []

def test_proxy_headers_carry_the_sandbox_token_not_the_host_one(self, fake_server: str) -> None:
# These headers are handed to browsers and WebSocket clients, so they must
# not confer authority over the pool or over sibling sandboxes.
sandbox = self._make_shared(fake_server)
assert sandbox.proxy_headers["X-Sandbox-Token"] == "tok-local1"
assert sandbox.proxy_headers["X-Sandbox-Token"] != sandbox._server._sandbox_token

def test_falls_back_to_the_host_token_on_an_older_server(self, fake_server: str) -> None:
# A host running a server that predates per-sandbox tokens returns no token
# in the create response; those sandboxes keep working with the host one.
server = _make_server(fake_server, capacity=10)
_FakeServer.sandboxes.add("local1")
sandbox = Sandbox(id="job123.local1", server=server, local_id="local1", owns_sandbox=True, owns_server=False)
assert sandbox._sandbox_token is None
assert sandbox.proxy_headers["X-Sandbox-Token"] == "secret"


class TestSandboxPool:
def _pool(self, fake_server: str, monkeypatch, per_host: int = 4) -> SandboxPool:
Expand Down