Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
[Sandbox] Show the network policy in 'hf sandbox create', accept any …
…case for 'none', document supervisor limits

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
Wauplin and claude committed Nov 5, 2026
commit 723a21c6cd5ff67c88a5903b2fc9df58836dc112
5 changes: 4 additions & 1 deletion docs/source/en/concepts/sandbox.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,10 @@ Hostnames in the allowlist are resolved once, by the server, when the sandbox is

Some limits:

- With an allowlist, background processes that outlive the command that started them lose their network access when that command exits. Start long-running services with `run(..., background=True)`.
- 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.
Expand Down
1 change: 1 addition & 0 deletions docs/source/en/guides/sandbox.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ The policy applies to every command the sandbox runs, and to every process they
- 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:

Expand Down
2 changes: 1 addition & 1 deletion docs/source/en/package_reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -4104,7 +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', 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.
* `--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 Down
28 changes: 24 additions & 4 deletions src/huggingface_hub/cli/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,21 @@ def _parse_network(network: str | None) -> SandboxNetwork | None:
"""Turn `--network` into a policy: 'none', or a comma-separated allowlist."""
if network is None:
return None
if network == "none":
if network.strip().lower() == "none":
return "none"
allow = [entry.strip() for entry in network.split(",") if entry.strip()]
if not allow:
raise CLIError("--network must be 'none' or a comma-separated list of destinations.")
return {"allow": allow}


def _format_network(policy: SandboxNetwork | None) -> str | None:
"""Show a policy the way `--network` takes it (None when unrestricted)."""
if isinstance(policy, dict):
return ",".join(policy["allow"])
return policy


@sandbox_cli.command(
"create",
examples=[
Expand Down Expand Up @@ -125,7 +132,7 @@ def sandbox_create(
str | None,
Option(
"--network",
help="Restrict outbound access: 'none', or a comma-separated allowlist of IP ranges, IPs and hostnames "
help="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.",
),
] = None,
Expand Down Expand Up @@ -159,7 +166,14 @@ def sandbox_create(
forward_hf_token=forward_hf_token,
network=network_policy,
)
out.result("Sandbox ready", id=sbx.id, host=sbx.host_id, pool=pool, elapsed=f"{time.time() - start:.1f}s")
out.result(
"Sandbox ready",
id=sbx.id,
host=sbx.host_id,
pool=pool,
network=_format_network(network_policy),
elapsed=f"{time.time() - start:.1f}s",
)
out.hint(f"Run a command with `hf sandbox exec {sbx.id} -- echo hello`.")
out.hint(f"Terminate it with `hf sandbox kill {sbx.id}`.")
return
Expand All @@ -179,7 +193,13 @@ def sandbox_create(
)
# Release the HTTP client (the sandbox keeps running)
sandbox.close()
out.result("Sandbox ready", id=sandbox.id, image=sandbox.image, elapsed=f"{time.time() - start:.1f}s")
out.result(
"Sandbox ready",
id=sandbox.id,
image=sandbox.image,
network=_format_network(network_policy),
elapsed=f"{time.time() - start:.1f}s",
)
out.hint(f"Run a command with `hf sandbox exec {sandbox.id} -- echo hello`.")
out.hint(f"Terminate it with `hf sandbox kill {sandbox.id}`.")

Expand Down
16 changes: 16 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5111,6 +5111,22 @@ def test_delete_confirm_no(self, runner: CliRunner) -> None:
api_cls.return_value.delete_webhook.assert_not_called()


class TestSandboxCreateNetwork:
def test_network_none_is_case_insensitive_and_shown(self, runner: CliRunner) -> None:
result, sandbox_cls = TestSecretHygiene._create_sandbox(runner, "--network", "None", "--format", "human")
assert result.exit_code == 0, result.output
assert sandbox_cls.create.call_args.kwargs["network"] == "none"
assert "network: none" in result.stdout

def test_allowlist_is_shown(self, runner: CliRunner) -> None:
result, sandbox_cls = TestSecretHygiene._create_sandbox(
runner, "--network", "10.0.0.0/8, huggingface.co:443", "--format", "human"
)
assert result.exit_code == 0, result.output
assert sandbox_cls.create.call_args.kwargs["network"] == {"allow": ["10.0.0.0/8", "huggingface.co:443"]}
assert "network: 10.0.0.0/8,huggingface.co:443" in result.stdout


class TestSecretHygiene:
"""Test the warnings that steer secret material out of argv (shared options in `_cli_utils.py`)."""

Expand Down
1 change: 1 addition & 0 deletions tests/test_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -1805,6 +1805,7 @@ def test_cli_option(self):

assert _parse_network(None) is None
assert _parse_network("none") == "none"
assert _parse_network("None") == "none"
assert _parse_network("10.0.0.0/8, huggingface.co:443") == {"allow": ["10.0.0.0/8", "huggingface.co:443"]}

def test_pool_applies_policy(self, fake_server: str, monkeypatch) -> None:
Expand Down
Loading