Repository navigation
[cherry-pick][2.58.0][core][sandbox] Make Ray Sandbox run Docker-built images out of the box (#65570) - #65622
Conversation
…ox (#65570) ## Description `ray.experimental.sandbox` cannot run standard Docker-built images without reaching for the private `_oci_spec_transform_fn` hook and client-side workarounds. We hit all of these while integrating Ray Sandbox with the [Harbor](https://github.com/harbor-framework/harbor) eval framework (see the workarounds carried in harbor-framework/harbor#2725), and the follow-up items while testing this PR end-to-end on a live Ray cluster with real gVisor. ### Capabilities - **`SandboxConfig.capabilities`** (plumbed through `create()`, the `Sandbox` actor, `SandboxRuntime.create`, and the gVisor backend): None keeps the runtime default; otherwise the bounding/effective/permitted sets are written exactly, so `[]` runs with no capabilities at all (inheritable and ambient untouched, matching modern Docker, which stopped setting inheritable for CVE-2022-24769). A new `DOCKER_DEFAULT_CAPABILITIES` constant ([Docker's documented default set](https://docs.docker.com/engine/containers/run/#runtime-privilege-and-linux-capabilities)) gives Docker parity in one line: the runtime's default (whatever `runsc spec` emits) grants only three capabilities, and standard images break confusingly without more — `apt-get` needs `CAP_SETUID`/`CAP_SETGID` for its `_apt` sub-processes, `tar` extracting as root fatally fails restoring archived uid/gids (e.g. `1000`) without `CAP_CHOWN`. ### Networking and DNS - **`network="public"`** — the recommended internet-access mode: host egress (`--network=host` under the hood) with a **synthetic `/etc/resolv.conf`** generated from `dns` (default `8.8.8.8`, `1.1.1.1`). Nothing about the host resolver is inherited, so the config stays portable and doesn't leak host search domains or internal resolver addresses (a cluster node's resolv.conf typically carries internal Kubernetes search domains, the cluster DNS VIP, and `ndots:5`). - **`network="host"`** stays the explicit power mode — full host network identity (including internal networks reachable from the node) with the host's own resolv.conf mounted read-only; `dns=` overrides it with a generated file. Keeping the modes separate lets the docs state that difference plainly. `"none"` remains the default. - **`dns=`** mirrors `docker --dns` and is the escape hatch for locked-down VPCs that block public DNS; it's rejected for modes that mount no resolv.conf. Host-side networking also drops the spec's empty network namespace, which previously left the sandbox loopback-only despite `--network=host`. - **`network="sandbox"` with `rootless=True` is rejected at config time**: runsc refuses the combination at container start, after the image pull, with an error naming a flag the user never set. ### Working directory and writability - **Writability is now fully explicit** — determined by the two parameters the user actually set, with the image's `WORKDIR` inherited for the *process cwd only*: | `readonly` | `workdir` | writable | cwd | |---|---|---|---| | `True` *(default)* | `None` *(default)* | nothing on the rootfs (safe default; standard tmpfs mounts like `/tmp` remain writable) | image `WORKDIR`, else `/` | | `True` | `/data` | only `/data` (host-backed scratch) | `/data` | | `False` | any | everything (per-sandbox overlay; image content stays visible, nothing shadowed) | explicit workdir, else image `WORKDIR` | Previously the backend defaulted `workdir` to the image's `WORKDIR` (or `/`) and scratch-mounted there, so what was writable depended on image metadata invisible in the config. An inherited `WORKDIR` is never silently made writable now. This made the interim `mount_workdir` knob redundant, so it's removed; the backend also no longer mutates `config.workdir` (the resolved cwd lives in sandbox metadata), and inherited image `WORKDIR` values are no longer used in host path joins, removing that traversal surface. ### TTL - **`ttl_seconds` now defaults to `None`** (no TTL) everywhere: the old 1h default was wall-clock from creation, not idle time, so actively-running sandboxes were deleted mid-work — a silent, hard-to-attribute failure in long agent runs. Opt-in destruction is the safer default. - **`SandboxRuntime` now actually enforces a set TTL** (daemon timer, canceled on delete); previously the parameter was a documented no-op below the actor layer, and the `Sandbox` actor's duplicate timer is dropped in favor of the runtime's. ### Shell for string commands - String commands ran under `/bin/sh` — `dash` on Debian-family images — while agent-generated commands overwhelmingly assume bash, failing confusingly on `[[ ]]`/`pipefail`/arrays. **`SandboxConfig.shell`** now defaults to `"/bin/bash"` outright (no auto-detection — deterministic per review), with a per-command `shell=` override on `exec()`. Images without bash set `shell="/bin/sh"` explicitly, as the busybox-based tests now do; list commands still bypass the shell. ### Robustness - `SandboxRuntime.create()` forwards `mount_workdir` into the config (it was silently dropped — caught by live testing; a new runtime-layer test suite pins config fields actually reaching the backend, the gap that let it ship green). - Caller-supplied `base_spec`s with null capability sets or non-dict namespace entries no longer raise; malformed namespace entries are kept for runsc to reject with its own error. - `SandboxConfig` validates the network mode against `("none", "public", "host", "sandbox")`. Defaults are behavior-preserving except where called out (TTL, and mount_workdir under `readonly=False`); the API is alpha. ## Related issues Related to #64964 (Ray Sandboxing with gVisor). Enables removing the OCI-spec transform, DNS seeding, and `tar --no-same-owner` workarounds in harbor-framework/harbor#2725 / harbor-framework/harbor#2785. ## Additional information Usage: ```python from ray.experimental import sandbox from ray.experimental.sandbox import DOCKER_DEFAULT_CAPABILITIES sb = sandbox.create( image="ubuntu:24.04", network="public", capabilities=DOCKER_DEFAULT_CAPABILITIES, readonly=False, ) # apt-get / tar / DNS / bash / image WORKDIR all behave as under Docker, # without inheriting the host's resolver configuration. ``` Testing: - Unit tests run without runsc or a cluster: spec construction against `base_spec` with a stub image manager, config validation, resolv.conf generation policy at the `prepare_oci_bundle` layer, and a new `SandboxRuntime`-layer suite (fake backend) covering field forwarding and TTL enforcement. - Full `TEST_SANDBOX=1` suite with real gVisor/runsc on Linux: 64 tests pass, including the shell-detection and rootless-rejection paths. - Docs: new "Networking and DNS" section with the mode table and security property of each mode, the recommended internet-access example, the `dns=` escape hatch, and an updated OCI-transform section (its example used the now-rejected `network="sandbox"` default combination and hand-mounted resolv.conf). This is the first of two changes for running Harbor evals on Ray Sandbox; a follow-up adds an HTTP API service so sandboxes can be consumed as a standalone service. --------- Signed-off-by: xyuzh <[email protected]> (cherry picked from commit 7408258) Signed-off-by: elliot-barn <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request enhances Ray Sandboxes by introducing configurable network modes, custom DNS nameservers, Linux capabilities (with Docker-parity defaults), and custom shell execution. It also transitions the default TTL cleanup mechanism to be runtime-enforced and disabled by default. The review feedback highlights several critical security and robustness improvements: validating nameserver IP addresses to prevent injection in resolv.conf, using os.path.realpath to robustly prevent path traversal, correctly handling empty DNS lists, safely parsing potentially null sections in base OCI specifications, and logging warnings when TTL-based sandbox deletions fail.
| if nameservers is not None: | ||
| # Generated and host-independent: no search domains, resolver | ||
| # VIPs, or ndots options leak in from the host. | ||
| resolv_conf_source = os.path.join(root_dir, "resolv.conf") | ||
| with open(resolv_conf_source, "w", encoding="utf-8") as f: | ||
| f.write("".join(f"nameserver {ip}\n" for ip in nameservers)) |
There was a problem hiding this comment.
The nameserver IP addresses are written directly to resolv.conf without validation. If a user passes a nameserver containing newline characters (e.g., \nsearch malicious.com), they can inject arbitrary directives into /etc/resolv.conf. We should validate that each nameserver is a valid IP address using ipaddress.ip_address.
if nameservers is not None:
import ipaddress
validated_nameservers = []
for ip in nameservers:
try:
validated_nameservers.append(str(ipaddress.ip_address(ip.strip())))
except ValueError as e:
raise ValueError(f"Invalid DNS nameserver IP address: {ip}") from e
# Generated and host-independent: no search domains, resolver
# VIPs, or ndots options leak in from the host.
resolv_conf_source = os.path.join(root_dir, "resolv.conf")
with open(resolv_conf_source, "w", encoding="utf-8") as f:
f.write("".join(f"nameserver {ip}\\n" for ip in validated_nameservers))| if config.workdir and config.readonly: | ||
| workdir_path = os.path.abspath( | ||
| os.path.join(root_dir, config.workdir.lstrip("/")) | ||
| ) | ||
| os.makedirs(workdir_path, mode=0o777, exist_ok=True) | ||
| if not ( | ||
| workdir_path == os.path.abspath(root_dir) | ||
| or workdir_path.startswith(os.path.abspath(root_dir) + os.sep) | ||
| ): | ||
| raise SandboxCreationError( | ||
| f"Invalid workdir '{config.workdir}': Path traversal detected." | ||
| ) | ||
| os.makedirs(workdir_path, mode=0o777, exist_ok=True) |
There was a problem hiding this comment.
os.path.abspath does not resolve symlinks, which can lead to path traversal detection bypasses or false positives/negatives if root_dir or any parent directory contains symlinks (e.g., /tmp being a symlink to /private/tmp on macOS). Using os.path.realpath is much safer and robust for path traversal checks.
| if config.workdir and config.readonly: | |
| workdir_path = os.path.abspath( | |
| os.path.join(root_dir, config.workdir.lstrip("/")) | |
| ) | |
| os.makedirs(workdir_path, mode=0o777, exist_ok=True) | |
| if not ( | |
| workdir_path == os.path.abspath(root_dir) | |
| or workdir_path.startswith(os.path.abspath(root_dir) + os.sep) | |
| ): | |
| raise SandboxCreationError( | |
| f"Invalid workdir '{config.workdir}': Path traversal detected." | |
| ) | |
| os.makedirs(workdir_path, mode=0o777, exist_ok=True) | |
| if config.workdir and config.readonly: | |
| workdir_path = os.path.realpath( | |
| os.path.join(root_dir, config.workdir.lstrip("/")) | |
| ) | |
| real_root_dir = os.path.realpath(root_dir) | |
| if not ( | |
| workdir_path == real_root_dir | |
| or workdir_path.startswith(real_root_dir + os.sep) | |
| ): | |
| raise SandboxCreationError( | |
| f"Invalid workdir '{config.workdir}': Path traversal detected." | |
| ) | |
| os.makedirs(workdir_path, mode=0o777, exist_ok=True) |
| nameservers = list(dns) if dns else None | ||
| if network == "public" and nameservers is None: | ||
| nameservers = list(DEFAULT_PUBLIC_DNS) |
There was a problem hiding this comment.
Using dns as a boolean check (if dns) treats an explicitly provided empty list [] the same as None (not provided), causing it to silently fall back to DEFAULT_PUBLIC_DNS. We should check dns is not None to respect the user's explicit request for an empty DNS list.
| nameservers = list(dns) if dns else None | |
| if network == "public" and nameservers is None: | |
| nameservers = list(DEFAULT_PUBLIC_DNS) | |
| nameservers = list(dns) if dns is not None else None | |
| if network == "public" and nameservers is None: | |
| nameservers = list(DEFAULT_PUBLIC_DNS) |
| if capabilities is not None: | ||
| # The key may exist with a null value in a caller-supplied base_spec. | ||
| caps = spec["process"].get("capabilities") | ||
| if not isinstance(caps, dict): | ||
| caps = {} | ||
| spec["process"]["capabilities"] = caps | ||
| for cap_set in _OCI_CAPABILITY_SETS: | ||
| # Written exactly (not unioned): [] runs with no capabilities. | ||
| caps[cap_set] = list(dict.fromkeys(capabilities)) |
There was a problem hiding this comment.
If base_spec contains a null "process" key (e.g., "process": None), attempting to access spec["process"].get("capabilities") will raise an AttributeError. We should safely handle a null or non-dict "process" section.
| if capabilities is not None: | |
| # The key may exist with a null value in a caller-supplied base_spec. | |
| caps = spec["process"].get("capabilities") | |
| if not isinstance(caps, dict): | |
| caps = {} | |
| spec["process"]["capabilities"] = caps | |
| for cap_set in _OCI_CAPABILITY_SETS: | |
| # Written exactly (not unioned): [] runs with no capabilities. | |
| caps[cap_set] = list(dict.fromkeys(capabilities)) | |
| if capabilities is not None: | |
| # The key may exist with a null value in a caller-supplied base_spec. | |
| process_sec = spec.get("process") | |
| if not isinstance(process_sec, dict): | |
| process_sec = {} | |
| spec["process"] = process_sec | |
| caps = process_sec.get("capabilities") | |
| if not isinstance(caps, dict): | |
| caps = {} | |
| process_sec["capabilities"] = caps | |
| for cap_set in _OCI_CAPABILITY_SETS: | |
| # Written exactly (not unioned): [] runs with no capabilities. | |
| caps[cap_set] = list(dict.fromkeys(capabilities)) |
| def _expire(self, instance_id: str) -> None: | ||
| """TTL callback: best-effort delete (the sandbox may already be gone).""" | ||
| try: | ||
| self.delete(instance_id) | ||
| except Exception: | ||
| pass |
There was a problem hiding this comment.
If sandbox deletion fails during TTL expiration, the exception is silently caught and ignored. This can lead to silent resource leaks (CPU, memory, disk) on the node. We should log a warning to ensure visibility.
def _expire(self, instance_id: str) -> None:
"""TTL callback: best-effort delete (the sandbox may already be gone)."""
try:
self.delete(instance_id)
except Exception as e:
import logging
logging.getLogger(__name__).warning(
f"Failed to auto-delete expired sandbox '{instance_id}': {e}"
)
Description
Cherry-pick of #65570 (
7408258f64) intoreleases/2.58.0.Brings the Ray Sandbox Docker-image support onto the release branch, complementing the sandbox documentation already cherry-picked in #65573 (#65503). All changes are confined to
python/ray/experimental/sandbox/plus its doc page anddoc/source/conf.py.Verification
git cherry-pick -x -s 7408258f64), no conflicts; 14 files changed matching the original commit.Not a duplicate: no existing cherry-pick PR for #65570 targets
releases/2.58.0.AI assistance (Claude Code) was used to prepare this cherry-pick.
🤖 Generated with Claude Code