Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
29 changes: 27 additions & 2 deletions docs/source/en/concepts/sandbox.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ Combining distinct uids (discretionary access control) with Landlock is designed
- ✅ `/tmp` and `/dev/shm` access is denied — each sandbox is Landlock-confined to its own home (its
`TMPDIR` points inside `$HOME`).
- ✅ A cannot `bind` a TCP port, so there is no inter-sandbox localhost service (outbound `connect`
stays allowed, so the internet works).
stays allowed, so the internet works, unless the sandbox has a [network policy](#network-policies)).
- ✅ Cross-sandbox abstract unix sockets are blocked (`LANDLOCK_SCOPED_ABSTRACT_UNIX_SOCKET`; uid
isolation alone does *not* block these).

Expand Down Expand Up @@ -218,6 +218,31 @@ What the cache is and isn't trusted for:

Two things to keep in mind. Treat `$HF_HOME` as sensitive: an entry is still a reusable host URL plus the public nonce its token derives from, and while a file written under a different credential is ignored, one written under *yours* is credited for the 15-minute window above. And because the namespace is part of the key, a pool cached under an explicit `namespace=` is only found again when the same `namespace=` is passed — `hf sandbox create --pool <id>` wants the same `--namespace` the pool was created with, or it takes the cold path and looks in your own namespace.

## Network policies

A Job always has network access, and code inside the container cannot drop it: there is no `CAP_NET_ADMIN`, and no way to create a network namespace. But the sandbox server starts every command itself, so it can take the network away from those commands, and only from them. The server keeps its own connection, so it still serves the API. Volumes are mounted by the platform, outside the container, so they keep working too.

A dedicated sandbox gets its policy from the `SBX_NETWORK` variable of its Job. A pooled sandbox gets it in the create request, so each sandbox on a host can have a different policy. In both cases, the server sends the policy back, and the client checks it. An older server ignores the policy, so the client refuses it instead of handing out a sandbox with network access.

Before a command starts, the server applies two kernel restrictions to it. Both are inherited by every child process, and neither can be removed, even by root inside the sandbox:

- A **seccomp filter** decides which sockets can exist. Unix and netlink sockets are allowed. IPv4 and IPv6 are allowed for TCP only, so UDP (and DNS), ICMP and raw sockets are refused. The filter also refuses `io_uring`, TCP Fast Open and `ptrace`, which could get around the other checks.
- A **Landlock** rule refuses every TCP `connect()`, including to `127.0.0.1`. Listening on a port still works, so the [port proxy](../guides/sandbox#reaching-a-server-inside-a-sandbox) can still reach a server in a dedicated sandbox.

With `network="none"`, that is all. With an allowlist, the server starts each command through a small supervisor: a second copy of the server binary that runs inside the sandbox, as the command's parent. The seccomp filter hands the command's TCP socket calls to the supervisor. The supervisor creates each socket itself, so it can later connect that same socket. On `connect()`, it reads the destination and checks it against the allowlist. If it matches, the supervisor connects the socket to the address it checked, not the one in the sandbox's memory. Otherwise, the call fails with "permission denied". The supervisor shares the command's limits and process group, so a timeout or a kill stops it too.

Hostnames in the allowlist are resolved once, by the server, when the sandbox is created. The server writes them to `/etc/hosts`. The sandbox can then resolve them without DNS, and it reaches the same addresses the allowlist holds.

Some limits:

- With an allowlist, background processes that outlive the command that started them lose their socket access when that command exits: connecting and listening then fail for every socket, unix sockets included. Start long-running services with `run(..., background=True)`.
- With an allowlist, the supervisor notices that a socket was closed within about 3 seconds, and the socket keeps its local port until then. Code that picks a free port by binding port 0, closing the socket and binding that port again (common in test and distributed-training helpers) can fail with "address already in use".
- With an allowlist, a process that runs as another user than the command, or that marks itself non-dumpable, cannot connect: the supervisor cannot read the address it connects to. This affects tools that drop privileges, such as `apt-get` (pass `-o APT::Sandbox::User=root`), `su` or `gosu`, and agents such as `ssh-agent`.
- An allowlist holds at most 1024 rules, counting every address its hostnames resolve to.
- A writable volume can still be used to move data out. Mount volumes read-only for strict isolation.
- In a pool, a sandbox with network access could pass an open connection to an isolated one over a unix socket, if both cooperate. A pool is one trust boundary.
- The policy needs Landlock ABI 4 or newer. HF Jobs have ABI 6.

## Known limitations

**Pools are for workloads within one trust boundary. Use dedicated sandboxes for code you do not trust.** The checks below reduce specific risks; they do not turn pooled sandboxes into separate VMs.
Expand All @@ -236,7 +261,7 @@ Two things to keep in mind. Treat `$HF_HOME` as sensitive: an entry is still a r

- **Host discovery is not attestation.** The default `adopt_hosts="own"` checks initiator, image, flavor, command, and exposed URL. It does not attest the running binary or make a mutable image trustworthy. Only use `adopt_hosts="namespace"` with namespace members you trust.
- **Host credentials remain powerful.** They manage the pool and recover each sandbox's token. They are never substituted for missing scoped tokens by this client. Hosts booted by this version run sbx-server 0.7.0, which refuses them on scoped routes; hosts started by older clients keep their server (and its host-token compatibility) until they are recycled.
- **Shared channels remain.** Outbound TCP, loopback access to the control server, UDP, kernel IPC, and readable process-list metadata are not isolated. System directories and selected device nodes remain accessible. GPU pool isolation is untested; use dedicated mode for GPU.
- **Shared channels remain.** Unless a sandbox has a [network policy](#network-policies), outbound TCP, loopback access to the control server and UDP are open to it. Kernel IPC and readable process-list metadata are not isolated. System directories and selected device nodes remain accessible. GPU pool isolation is untested; use dedicated mode for GPU.
- **Limits are not aggregate quotas.** Per-process rlimits and bounded output queues reduce resource amplification. They do not partition CPU shares, total memory, disk space, inodes, or network capacity between sandboxes. Directory pagination bounds responses but still materializes the directory on the server. API file writes are not a disk quota, and dedicated-mode writes to special files can block.
- **Confinement can be explicitly weakened.** Host mode requires Landlock ABI 6 by default and refuses a failed ruleset. Lowering `SBX_MIN_LANDLOCK_ABI` or using the server's `--allow-unconfined` development flag accepts fewer guarantees; inspect authenticated `/health` for the effective ABI and features.
- **Proxy connections are authenticated only once.** After the first request, the proxy copies bytes to that backend until EOF. Subsequent HTTP requests on that connection are not independently authenticated or routed. WebSocket/SSE compatibility does not establish safety against upstream connection reuse.
Expand Down
14 changes: 14 additions & 0 deletions docs/source/en/guides/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -2413,6 +2413,20 @@ warns about it on stderr, including in quiet mode. Pooled sandboxes reject `--se
encrypted-secrets channel, and `hf sandbox create --pool <id> -s KEY=value` errors out with a pointer to
`--env`.

### Restrict network access

Pass `--network none` to block all outbound connections from the sandbox, or a comma-separated allowlist to allow only some destinations. Entries can be IP ranges, IPs and hostnames, with an optional port. Mounted volumes keep working. It works for pooled sandboxes too.

```bash
# No internet access
>>> hf sandbox create --network none

# Only an internal network range and the Hub
>>> hf sandbox create --network 10.0.0.0/8,huggingface.co:443
```

See [Sandboxes without internet access](./sandbox#sandboxes-without-internet-access) for details.

## hf webhooks

`hf webhooks` lets you manage webhooks on the Hugging Face Hub directly from the terminal. Webhooks allow you to listen for events (pushes, discussions, etc.) on repos, users, or organizations and trigger actions — either by pinging a remote URL or by running a Job on Hugging Face infrastructure.
Expand Down
54 changes: 54 additions & 0 deletions docs/source/en/guides/sandbox.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,56 @@ How the inner server must listen depends on the sandbox kind:
- **Dedicated** ([`Sandbox.create`]): bind a normal TCP port on `127.0.0.1:<port>`.
- **Pool / shared** ([`SandboxPool`]): pooled sandboxes can't bind a TCP port (Landlock), so listen on a **unix socket** at `$SBX_PROXY_DIR/<port>.sock` (that env var is set in every sandbox), e.g. `uvicorn app:app --uds $SBX_PROXY_DIR/8000.sock`. The client side (`proxy_url_for` / `proxy_headers`) is identical either way.

## Sandboxes without internet access

By default, code in a sandbox can reach the internet. To run untrusted code, you can take that access away with `network`. Pass `"none"` to block all outbound connections:

```python
>>> from huggingface_hub import Sandbox, Volume
>>> sbx = Sandbox.create(
... network="none",
... volumes=[Volume(type="model", source="openai-community/gpt2", mount_path="/data")],
... )
>>> sbx.run("python -c \"import urllib.request; urllib.request.urlopen('https://example.com')\"").ok
False
>>> sbx.run("cat /data/config.json").ok # mounted volumes still work
True
```

Or allow only some destinations. For example, let the sandbox reach a vLLM server on your internal network and the Hub, and nothing else:

```python
>>> sbx = Sandbox.create(
... network={
... "allow": [
... "10.0.0.0/8", # an IP range
... "203.0.113.10:443", # one IP, one port
... "huggingface.co", # a hostname
... ]
... },
... )
>>> sbx.run("curl -s http://10.0.3.7:8000/v1/models") # allowed
>>> sbx.run("curl -s https://example.com") # refused
```

The policy applies to every command the sandbox runs, and to every process they start. It cannot be removed from inside the sandbox, even by root. A few things to know:

- Only TCP is allowed. UDP is always blocked, so there is no DNS. Hostnames from the allowlist are resolved once, when the sandbox starts, and written to `/etc/hosts`, so they still resolve.
- Blocking also applies to `127.0.0.1`. Tools that talk to themselves over local TCP (Ray, NCCL, Jupyter kernels) need `"127.0.0.1"` in the allowlist.
- Mounted volumes are not affected. A writable volume is still a way to send data out, so mount volumes read-only (`read_only=True`) for strict isolation.
- Debuggers (`gdb`, `strace`) do not work in a sandbox with a network policy.
- With an allowlist, start long-running services with `run(..., background=True)`, and run `apt-get` with `-o APT::Sandbox::User=root`. See [Network policies](../concepts/sandbox#network-policies) for these limits and a few others.

Pooled sandboxes take the same argument, per sandbox, so one host can run isolated and connected sandboxes side by side:

```python
>>> with SandboxPool() as pool:
... agent = pool.create(network="none")
... judge = pool.create(network={"allow": ["10.0.3.7:8000"]})
```

If the sandbox server cannot apply the policy (for example, a pool host started by an older version of `huggingface_hub`), creation fails with a [`SandboxError`] instead of returning a sandbox with network access. See [Network policies](../concepts/sandbox#network-policies) for how it works.

## Lifecycle

A sandbox outlives the process that created it — you can create it now and reconnect later, from any machine that holds the same HF token, with no state to copy around:
Expand Down Expand Up @@ -248,6 +298,10 @@ The `hf sandbox` command mirrors the Python API. A dedicated sandbox:
# Attach labels to the underlying Job
>>> hf sandbox create --label controller-run=run-42 --label team=data-infra

# No internet access, or only an allowlist
>>> hf sandbox create --network none
>>> hf sandbox create --network 10.0.0.0/8,huggingface.co

>>> hf sandbox exec 687f911eaea852de79c4a50a -- python -c "print('hi')"
hi

Expand Down
3 changes: 3 additions & 0 deletions docs/source/en/package_reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -4104,6 +4104,7 @@ $ hf sandbox create [OPTIONS] [IMAGE]
* `-v, --volume TEXT`: Mount one or more volumes. Format: hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. TYPE is one of: models, datasets, spaces, buckets. TYPE defaults to models if omitted. models, datasets and spaces are always mounted read-only. buckets are read+write by default. E.g. -v hf://org/m:/data or -v hf://datasets/org/ds:/data or -v hf://buckets/org/b:/mnt:ro
* `--namespace TEXT`: The namespace where the job will be running. Defaults to the current user's namespace.
* `--forward-hf-token`: Inject your HF token as HF_TOKEN in the sandbox.
* `--network TEXT`: Restrict outbound access: 'none' (no network), or a comma-separated allowlist of IP ranges, IPs and hostnames with optional ports (e.g. '10.0.0.0/8,203.0.113.10:443,huggingface.co'). Only TCP is allowed.
* `--token TEXT`: A User Access Token generated from https://huggingface.co/settings/tokens.
* `--help`: Show this message and exit.

Expand All @@ -4112,6 +4113,8 @@ Examples
$ hf sandbox create ubuntu:24.04
$ hf sandbox create --flavor a10g-small
$ hf sandbox create --label controller-run=run-42
$ hf sandbox create --network none
$ hf sandbox create --network 10.0.0.0/8,huggingface.co
$ hf sandbox create --pool pool-ab12cd34ef56 --env LOG_LEVEL=debug

Learn more
Expand Down
Loading
Loading