diff --git a/docs/source/en/concepts/sandbox.md b/docs/source/en/concepts/sandbox.md index 9b1bb52fe3..a056504b48 100644 --- a/docs/source/en/concepts/sandbox.md +++ b/docs/source/en/concepts/sandbox.md @@ -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). @@ -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 ` 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. @@ -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. diff --git a/docs/source/en/guides/cli.md b/docs/source/en/guides/cli.md index 3f3de127a6..21161ad9c8 100644 --- a/docs/source/en/guides/cli.md +++ b/docs/source/en/guides/cli.md @@ -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 -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. diff --git a/docs/source/en/guides/sandbox.md b/docs/source/en/guides/sandbox.md index 43c66d715d..bd7ffe6741 100644 --- a/docs/source/en/guides/sandbox.md +++ b/docs/source/en/guides/sandbox.md @@ -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:`. - **Pool / shared** ([`SandboxPool`]): pooled sandboxes can't bind a TCP port (Landlock), so listen on a **unix socket** at `$SBX_PROXY_DIR/.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: @@ -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 diff --git a/docs/source/en/package_reference/cli.md b/docs/source/en/package_reference/cli.md index 62d543932a..951cd3f466 100644 --- a/docs/source/en/package_reference/cli.md +++ b/docs/source/en/package_reference/cli.md @@ -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. @@ -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 diff --git a/src/huggingface_hub/_sandbox.py b/src/huggingface_hub/_sandbox.py index d108c570f9..07b24bba23 100644 --- a/src/huggingface_hub/_sandbox.py +++ b/src/huggingface_hub/_sandbox.py @@ -73,8 +73,8 @@ # reviewed for this release -- not whatever the mutable `sbx-server` alias points at today. # Both constants move together on every server release; the digest is printed by the server # repo's publish workflow. -SANDBOX_SERVER_VERSION = "0.7.0" -SANDBOX_SERVER_SHA256 = "eb2b04f79fbe765195300aaf1582be2a2a9ea698ff067d0cab428171d5584932" +SANDBOX_SERVER_VERSION = "0.8.0" +SANDBOX_SERVER_SHA256 = "15942ee7905530b34b563979ba01dd3e87aeb48dc9ebb2df192283f4dd3cf8e0" # The sbx-server wire contract this client drives, checked against `/health`'s `protocol` on # startup. A pool host keeps the binary it downloaded at boot for up to 24h, so pinning a @@ -180,6 +180,32 @@ def _derive_sandbox_token(hf_token: str, nonce: str) -> str: return hmac.new(hf_token.encode(), f"hf-sandbox:{nonce}".encode(), hashlib.sha256).hexdigest() +SandboxNetwork = Literal["none"] | dict[str, List[str]] + + +def _network_payload(network: SandboxNetwork | None) -> SandboxNetwork | None: + """Validate a `network` argument into the policy sbx-server expects (it checks each entry).""" + if network is None or network == "none": + return network + if isinstance(network, dict) and set(network) == {"allow"}: + allow = network["allow"] + if isinstance(allow, (list, tuple)) and all(isinstance(entry, str) for entry in allow): + return {"allow": list(allow)} + raise ValueError(f'`network` must be "none" or {{"allow": [...]}} with a list of strings, got {network!r}.') + + +def _check_network_applied(requested: SandboxNetwork, reported: Any, *, where: str, remedy: str) -> None: + """Refuse a sandbox whose server did not apply the requested network policy. + + An older sbx-server ignores the policy, and would run the sandbox with full network access. + """ + if reported != requested: + raise SandboxError( + f"{where} did not apply the requested network policy (it reported {reported!r}). Its sandbox " + f"server is too old to restrict the network: {remedy}." + ) + + def _duration_to_secs(duration: int | float | str) -> int: """Parse a duration like 300, "300s", "10m", "2h", "1d" into seconds.""" if isinstance(duration, (int, float)): @@ -845,6 +871,7 @@ def create( namespace: str | None = None, forward_hf_token: bool = False, labels: dict[str, str] | None = None, + network: SandboxNetwork | None = None, start_timeout: float = 120.0, token: str | None = None, ) -> "Sandbox": @@ -881,6 +908,12 @@ def create( If True, your HF token is injected as `HF_TOKEN` (opt-in). labels (`dict[str, str]`, *optional*): Labels to attach to the underlying HF Job. + network (`"none"` or `dict`, *optional*): + Restrict the network access of the commands run in the sandbox. Pass `"none"` to block all + outbound connections, or `{"allow": [...]}` to allow only some destinations: IP ranges + (`"10.0.0.0/8"`), single IPs with an optional port (`"203.0.113.10:443"`) or hostnames + (`"huggingface.co"`). Only TCP is allowed, even with an allowlist. Defaults to `None` (no + restriction). See [Sandboxes without internet access](../guides/sandbox#sandboxes-without-internet-access). start_timeout (`float`, *optional*, defaults to `120.0`): Max seconds to wait for the sandbox to become ready. token (`str`, *optional*): @@ -898,6 +931,7 @@ def create( raise ValueError("`labels` keys and values must be strings") if key in RESERVED_SANDBOX_LABELS: raise ValueError(f"Label '{key}' is reserved by huggingface_hub Sandbox and cannot be overridden.") + network = _network_payload(network) api = HfApi(token=token) hf_token = _effective_token(api) @@ -914,6 +948,9 @@ def create( forward_hf_token=forward_hf_token, sandbox_token=sandbox_token, ) + if network is not None: + # Applied by the server to every command it runs, never to itself. + job_env["SBX_NETWORK"] = json.dumps(network) job = api.run_job( image=image, @@ -937,6 +974,11 @@ def create( max_connections=SandboxFiles.PARALLEL_MAX_WORKERS + 2, ) server.wait_ready(start_timeout) + if network is not None: + health = server.request("GET", "/health").json() + _check_network_applied( + network, health.get("network"), where=f"Sandbox job {job.id}", remedy="upgrade huggingface_hub" + ) except Exception: # run_job already started a billable job; cancel it before re-raising so it # doesn't linger as an orphan (e.g. if the server port isn't exposed or startup fails). @@ -1594,6 +1636,7 @@ def create( env: dict[str, Any] | None = None, idle_timeout: int | float | str | None = DEFAULT_IDLE_TIMEOUT, forward_hf_token: bool = False, + network: SandboxNetwork | None = None, ) -> "Sandbox": """Create one sandbox, provisioning a host if needed. @@ -1616,7 +1659,15 @@ def create( (opt-in). Unlike a dedicated sandbox's `secrets`, a pooled sandbox's env is delivered to the host server at creation (never stored in the host job), so it doesn't appear in any job's metadata. + network (`"none"` or `dict`, *optional*): + Restrict the network access of the commands run in this sandbox. Pass `"none"` to block all + outbound connections, or `{"allow": [...]}` to allow only some destinations: IP ranges + (`"10.0.0.0/8"`), single IPs with an optional port (`"203.0.113.10:443"`) or hostnames + (`"huggingface.co"`). Only TCP is allowed, even with an allowlist. Defaults to `None` (no + restriction). See [Sandboxes without internet access](../guides/sandbox#sandboxes-without-internet-access). + Sandboxes with and without a policy can share a host. """ + network = _network_payload(network) with self._lock: if self._closed: raise SandboxError("This SandboxPool is closed.") @@ -1624,7 +1675,7 @@ def create( # `close()` cannot snapshot the host list between the two. self._in_flight += 1 try: - return self._create_locked(env, idle_timeout, forward_hf_token) + return self._create_locked(env, idle_timeout, forward_hf_token, network) finally: with self._lock: self._in_flight -= 1 @@ -1635,6 +1686,7 @@ def _create_locked( env: dict[str, Any] | None, idle_timeout: int | float | str | None, forward_hf_token: bool, + network: SandboxNetwork | None, ) -> "Sandbox": sandbox_env = dict(env or {}) if forward_hf_token: @@ -1673,7 +1725,7 @@ def _create_locked( # (another process packed it) or a stale cached host is gone — retry. if host is not None: try: - sandbox = self._create_one(host, sandbox_env, idle_secs) + sandbox = self._create_one(host, sandbox_env, idle_secs, network) except Exception: # The create POST failed on a live host: release the slot we optimistically # reserved so the host isn't left permanently one sandbox short. @@ -2141,7 +2193,9 @@ def _boot_host(self) -> _SandboxServer: server.owned = self._owns_hosts return server - def _create_one(self, host: "_SandboxServer", env: dict[str, Any], idle_secs: int | None) -> "Sandbox | None": + def _create_one( + self, host: "_SandboxServer", env: dict[str, Any], idle_secs: int | None, network: SandboxNetwork | None + ) -> "Sandbox | None": """Create one sandbox on a reserved `host`. Returns the sandbox, or None to retry. None means either the host filled up between our reservation and the create @@ -2154,6 +2208,8 @@ def _create_one(self, host: "_SandboxServer", env: dict[str, Any], idle_secs: in body["idle_timeout_secs"] = idle_secs if env: body["env"] = env + if network is not None: + body["network"] = network try: data = host.request("POST", "/v1/sandboxes", json=body).json() except (SandboxError, httpx2.HTTPError) as e: @@ -2169,6 +2225,18 @@ def _create_one(self, host: "_SandboxServer", env: dict[str, Any], idle_secs: in host.live = host.capacity # the host is full; stop reserving it return None item = sandboxes[0] + if network is not None and item.get("network") != network: + # Scoped route: the host token is refused, so present the new sandbox's own token. + try: + host.request("DELETE", f"/v1/sandboxes/{item['id']}", sandbox_token=item.get("token")) + except Exception as e: + logger.warning(f"Failed to delete sandbox {item['id']} from host {host.job_id}: {e}") + _check_network_applied( + network, + item.get("network"), + where=f"Sandbox host {host.job_id}", + remedy="recycle the pool's hosts (kill them, or let them idle-time-out) to pick up the current server", + ) sandbox = Sandbox( id=f"{host.job_id}{SHARED_ID_SEP}{item['id']}", server=host, diff --git a/src/huggingface_hub/cli/sandbox.py b/src/huggingface_hub/cli/sandbox.py index 2d93fd9e50..f25aafaaf1 100644 --- a/src/huggingface_hub/cli/sandbox.py +++ b/src/huggingface_hub/cli/sandbox.py @@ -30,6 +30,7 @@ SANDBOX_LABEL, SHARED_ID_SEP, Sandbox, + SandboxNetwork, SandboxPool, SandboxProcess, _split_sandbox_id, @@ -75,6 +76,25 @@ def _connect(sandbox_id: str, *, namespace: str | None, token: str | None) -> It sandbox.close() +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.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=[ @@ -82,6 +102,8 @@ def _connect(sandbox_id: str, *, namespace: str | None, token: str | None) -> It "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", ], ) @@ -106,6 +128,14 @@ def sandbox_create( forward_hf_token: Annotated[ bool, Option("--forward-hf-token", help="Inject your HF token as HF_TOKEN in the sandbox.") ] = False, + network: Annotated[ + str | None, + Option( + "--network", + 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, token: TokenOpt = None, ) -> None: """Create a sandbox: a dedicated VM by default, or a cheap shared one with `--pool`. @@ -117,6 +147,7 @@ def sandbox_create( """ start = time.time() idle = idle_timeout if idle_timeout is not None else DEFAULT_IDLE_TIMEOUT + network_policy = _parse_network(network) if pool is not None: if image is not None or flavor is not None or volume: @@ -133,8 +164,16 @@ def sandbox_create( env=parse_env_map(env, env_file), idle_timeout=idle, forward_hf_token=forward_hf_token, + network=network_policy, + ) + 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.result("Sandbox ready", id=sbx.id, host=sbx.host_id, pool=pool, 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 @@ -149,11 +188,18 @@ def sandbox_create( namespace=namespace, forward_hf_token=forward_hf_token, labels=_parse_labels_map(label), + network=network_policy, token=token, ) # 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}`.") diff --git a/tests/test_cli.py b/tests/test_cli.py index 1c77caae73..8baae0262a 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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`).""" diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 4cbd77cffc..346b312524 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -152,6 +152,7 @@ class _FakeServer(BaseHTTPRequestHandler): redirect_to = "" # where the /v1/redirect route points (set per-subclass) # Extra /health fields, so a test can stand in for a server of another vintage. health: dict = {"protocol": sandbox_mod.SANDBOX_SERVER_PROTOCOL} + echo_network = False # False stands in for a server that ignores `network` (sbx-server <= 0.7.0) def log_message(self, *args) -> None: pass @@ -234,7 +235,10 @@ def do_POST(self) -> None: sid = f"sbx{cls.seq}" cls.seq += 1 cls.sandboxes.add(sid) - created.append({"id": sid, "token": f"tok-{sid}"}) + item = {"id": sid, "token": f"tok-{sid}"} + if cls.echo_network and body.get("network") is not None: + item["network"] = body["network"] # a server that applies network policies echoes them + created.append(item) self._json({"sandboxes": created, "rejected": rejected}) def do_PUT(self) -> None: @@ -314,6 +318,7 @@ def fake_server(): _FakeServer.writes = [] _FakeServer.redirect_to = "" _FakeServer.health = {"protocol": sandbox_mod.SANDBOX_SERVER_PROTOCOL} + _FakeServer.echo_network = False server = ThreadingHTTPServer(("127.0.0.1", 0), _FakeServer) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() @@ -1780,3 +1785,41 @@ def test_upload_reads_the_file_it_measured(self, fake_server: str, tmp_path) -> link.symlink_to(source) _make_sandbox(fake_server).files.upload(link, "/dest") assert sum(len(body) for _, body in _FakeServer.writes) == 1024 + + +class TestNetworkPolicy: + def test_valid_policies(self): + assert sandbox_mod._network_payload(None) is None + assert sandbox_mod._network_payload("none") == "none" + assert sandbox_mod._network_payload({"allow": ("10.0.0.0/8", "huggingface.co")}) == { + "allow": ["10.0.0.0/8", "huggingface.co"] + } + + @pytest.mark.parametrize("network", ["all", {"allow": "10.0.0.0/8"}, {"allow": [1]}, {"deny": []}, ["10.0.0.1"]]) + def test_invalid_policies(self, network): + with pytest.raises(ValueError): + sandbox_mod._network_payload(network) + + def test_cli_option(self): + from huggingface_hub.cli.sandbox import _parse_network + + 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: + _FakeServer.echo_network = True + pool = TestSandboxPool()._pool(fake_server, monkeypatch) + pool.create(network="none") + assert _FakeServer.sandboxes == {"sbx0"} + + def test_pool_refuses_server_ignoring_policy(self, fake_server: str, monkeypatch) -> None: + # An older host ignores `network`: the client deletes the unrestricted sandbox (with its + # own scoped token, as the host token is refused there) and reports the outdated server. + pool = TestSandboxPool()._pool(fake_server, monkeypatch) + with pytest.raises(SandboxError, match="did not apply the requested network policy"): + pool.create(network={"allow": ["10.0.0.0/8"]}) + assert _FakeServer.sandboxes == set() + assert ("DELETE", "/v1/sandboxes/sbx0") in _FakeServer.requests + assert pool.num_sandboxes == 0