Repository navigation
[core][sandbox] Pull private images with the node's Docker credentials - #67026
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces support for pulling sandbox container images from private registries using credentials from the node's Docker configuration file, supporting credential helpers, credential stores, and static auths. It includes comprehensive documentation updates and a new test suite covering various authentication scenarios. The review feedback focuses on enhancing robustness and compatibility, specifically by checking both stdout and stderr for credential helper errors, adding type and error checks when parsing malformed Docker configurations, explicitly setting the Content-Type header for OAuth2 token requests, and handling non-standard registry error JSON structures gracefully.
| output = proc.stdout.decode("utf-8", "replace").strip() | ||
| if proc.returncode != 0: | ||
| if output == _HELPER_NOT_FOUND: | ||
| return None | ||
| detail = output or proc.stderr.decode("utf-8", "replace").strip() | ||
| raise SandboxCreationError( | ||
| f"{program} failed to get credentials for {server}: {detail}" | ||
| ) |
There was a problem hiding this comment.
Credential helpers can print error messages like "credentials not found in native keychain" to stderr instead of stdout depending on the helper implementation or version. To ensure robust detection of missing credentials, we should check both stdout and stderr for the _HELPER_NOT_FOUND message.
output = proc.stdout.decode("utf-8", "replace").strip()
stderr = proc.stderr.decode("utf-8", "replace").strip()
if proc.returncode != 0:
if output == _HELPER_NOT_FOUND or stderr == _HELPER_NOT_FOUND:
return None
detail = output or stderr
raise SandboxCreationError(
f"{program} failed to get credentials for {server}: {detail}"
)There was a problem hiding this comment.
Not changing this: helpers print this message on stdout, and the Docker CLI only looks for it there. In docker-credential-helpers v0.9.10, credentials.Serve writes every error with fmt.Fprintln(os.Stdout, err), and client.Get matches IsErrCredentialsNotFoundMessage against cmd.Output(), which is stdout only. The helper's stderr goes straight to the CLI's own stderr (ec.Stderr = os.Stderr in client/command.go). Checking only stdout keeps the lookup the same as docker pull, where a helper that printed this only on stderr fails too.
| def _auths_credentials( | ||
| entry: Dict[str, Any], server: str, path: str | ||
| ) -> Optional[RegistryCredentials]: | ||
| """Credentials from an ``auths`` entry, as ``docker login`` writes them.""" | ||
| username = entry.get("username", "") | ||
| password = entry.get("password", "") | ||
| if entry.get("auth"): | ||
| try: | ||
| decoded = base64.b64decode(entry["auth"]).decode("utf-8") | ||
| except ValueError: | ||
| raise SandboxCreationError( | ||
| f"The auths entry for {server} in {path} has a malformed auth field" | ||
| ) from None | ||
| username, _, password = decoded.partition(":") | ||
| creds = RegistryCredentials( | ||
| username=username, | ||
| password=password.strip("\x00"), | ||
| identity_token=entry.get("identitytoken", ""), | ||
| registry_token=entry.get("registrytoken", ""), | ||
| ) | ||
| # An empty entry is a placeholder, like those ``docker login`` writes | ||
| # beside a credsStore. | ||
| return creds if creds != RegistryCredentials() else None |
There was a problem hiding this comment.
If the user's config.json is malformed (e.g., auths contains a non-dictionary entry, or the auth field is not a string/bytes-like object), this function can raise unhandled AttributeError or TypeError exceptions, which will propagate and crash the sandbox creation. Adding type checks for entry and catching TypeError during base64 decoding makes this parsing extremely robust.
def _auths_credentials(
entry: Any, server: str, path: str
) -> Optional[RegistryCredentials]:
"""Credentials from an auths entry, as docker login writes them."""
if not isinstance(entry, dict):
return None
username = entry.get("username", "")
password = entry.get("password", "")
if entry.get("auth"):
try:
decoded = base64.b64decode(entry["auth"]).decode("utf-8")
except (ValueError, TypeError):
raise SandboxCreationError(
f"The auths entry for {server} in {path} has a malformed auth field"
) from None
username, _, password = decoded.partition(":")
creds = RegistryCredentials(
username=username,
password=password.strip("\x00"),
identity_token=entry.get("identitytoken", ""),
registry_token=entry.get("registrytoken", ""),
)
# An empty entry is a placeholder, like those docker login writes
# beside a credsStore.
return creds if creds != RegistryCredentials() else NoneThere was a problem hiding this comment.
Already handled in 63da58a: a top level, auths, or auths entry that isn't an object, or an auth that isn't a string, fails with a SandboxCreationError that names the file but no value. 7f3b805 adds three more cases: a credHelpers that isn't an object, an auth that isn't base64 of user:password (the Docker CLI's decodeAuth rejects that too), and a registrytoken with a line break, which http.client would otherwise quote in the pull error. I raise instead of skipping the entry so the error points at the file, not at a later 401. test_lookup_refuses_a_malformed_config covers all 8 cases.
| auth_req = urllib.request.Request( | ||
| auth_url, | ||
| data=urllib.parse.urlencode(form).encode("utf-8"), | ||
| headers={"User-Agent": _USER_AGENT}, | ||
| ) |
There was a problem hiding this comment.
OAuth2 token endpoints strictly require the Content-Type: application/x-www-form-urlencoded header for POST requests containing form-encoded data. Without this header, some registries or token providers may reject the request with a 400 or 415 error. Adding this header ensures maximum compatibility.
auth_req = urllib.request.Request(
auth_url,
data=urllib.parse.urlencode(form).encode("utf-8"),
headers={
"User-Agent": _USER_AGENT,
"Content-Type": "application/x-www-form-urlencoded",
},
)There was a problem hiding this comment.
Not changing this: urllib already sends Content-Type: application/x-www-form-urlencoded on any request that has a body and no Content-Type (AbstractHTTPHandler.do_request_ in urllib/request.py). 4370cb9 makes the test's token service read a body only when it has that type, so test_identity_token_takes_the_oauth2_refresh_grant fails if the header ever goes missing.
| def _describe_pull_error(err: Exception) -> str: | ||
| """Describe a failed pull, with the registry's own reasons for an HTTP error. | ||
|
|
||
| A registry's error body says why it refused a request: Amazon ECR's | ||
| ``DENIED``, for one, names the IAM action that the node's role lacks. | ||
| """ | ||
| if not isinstance(err, urllib.error.HTTPError): | ||
| return str(err) | ||
| try: | ||
| errors = json.loads(err.read(65536)).get("errors") or [] | ||
| reasons = "; ".join(f"{e['code']}: {e['message']}" for e in errors) | ||
| except Exception: | ||
| reasons = "" | ||
| return f"{err}: {reasons}" if reasons else str(err) |
There was a problem hiding this comment.
The current implementation of _describe_pull_error assumes that the error response JSON always contains a list of dictionaries under the errors key. If a proxy or registry returns a different structure (e.g., a single string, a dictionary, or a simple message or error field), this can raise secondary exceptions or fail to extract the error reason. A more robust parser handles these cases gracefully.
def _describe_pull_error(err: Exception) -> str:
"""Describe a failed pull, with the registry's own reasons for an HTTP error.
A registry's error body says why it refused a request: Amazon ECR's
DENIED, for one, names the IAM action that the node's role lacks.
"""
if not isinstance(err, urllib.error.HTTPError):
return str(err)
try:
body = err.read(65536).decode("utf-8", "replace")
data = json.loads(body)
if isinstance(data, dict):
errors = data.get("errors")
if isinstance(errors, list):
reasons = "; ".join(
f"{e.get('code', 'UNKNOWN')}: {e.get('message', '')}"
if isinstance(e, dict) else str(e)
for e in errors
)
elif isinstance(data.get("message"), str):
reasons = data["message"]
else:
reasons = ""
else:
reasons = ""
except Exception:
reasons = ""
return f"{err}: {reasons}" if reasons else str(err)There was a problem hiding this comment.
Not changing this: the parse and the join both sit inside try: ... except Exception, so a body of any other shape (a proxy's HTML, a JSON string, errors that isn't a list of objects with code and message) falls back to the plain HTTP error, which still has the status. The OCI distribution spec defines registry errors as that errors array, so I don't read other fields. 4370cb9 adds test_pull_error_adds_only_the_registry_errors, which checks the spec's shape and 7 odd bodies.
Image pulls were anonymous. A registry that answers with an HTTP basic challenge, as Amazon ECR does, failed every pull, and bearer tokens were only ever requested anonymously. Ray now answers a registry's challenge with the credentials that the node's Docker configuration file ($DOCKER_CONFIG/config.json, by default ~/.docker/config.json) holds for it, looked up the way the Docker CLI does: the credHelpers helper for the registry, else the credsStore helper, else its auths entry. A helper such as docker-credential-ecr-login mints short-lived credentials from the Pod's IAM role at pull time, so an image named at sandbox creation pulls with no preloading and no secret on disk. - Credentials are looked up only after a challenge, so public pulls never run a helper. - A basic challenge gets them on every registry request. A bearer challenge trades them, or an identity token through the OAuth2 refresh grant, for a pull token. Redirects to presigned storage never carry them. - They live only in the pulling worker: never in the image cache, logs, error messages, or a repr, and never in a sandbox. - A failed pull now includes the registry's stated reason; ECR's DENIED names the IAM action that the role lacks. A RAY_SANDBOX_REGISTRY_MIRROR mirror authenticates the same way, so an ECR pull-through cache now works. The sandbox tests run with an empty DOCKER_CONFIG, so they never use the runner's credentials. Signed-off-by: xyuzh <[email protected]>
Review follow-up: a config.json whose top level, auths, or auths entry isn't an object, or whose auth field isn't a string, raised a bare AttributeError or TypeError from the lookup. It now fails the pull with a SandboxCreationError that names the file, as the Docker CLI refuses such a file. The message names types, not values, so it carries no secret. Signed-off-by: xyuzh <[email protected]>
Three malformed entries still went through the lookup: - A registrytoken with a line break. It goes into the Authorization header as is, and http.client's error for a line break in a header value quotes the whole value, so the token ended up in the pull's SandboxCreationError. - An auth field that isn't base64 of user:password, such as a bare token. Its value became the username, which RegistryCredentials shows in its repr, and the registry then refused the credentials. The Docker CLI rejects such a field as well. - A credHelpers that isn't an object, which was silently ignored unless it happened to contain the registry. Each now fails the lookup with an error that names the file and the field but not the value. Signed-off-by: xyuzh <[email protected]>
Review follow-up. The fake token service now reads a POST body only when it comes as application/x-www-form-urlencoded, as an OAuth2 token endpoint does, so the refresh-grant test fails if the request stops being sent that way. urllib sets that Content-Type on any request with a body, so the code needs no explicit header. A new test checks that a registry's errors join the HTTP error, and that an error body of any other shape (HTML, a JSON string, errors that aren't a list of code and message objects) leaves the HTTP error as it is. Signed-off-by: xyuzh <[email protected]>
The docs said that public images pull as before, and a docstring that public pulls never run a credential helper. Docker Hub and GHCR answer an anonymous request for a public image's manifest with a bearer challenge too, so Ray looks up their credentials on every pull. When the node's Docker config has some, public images pull with them, and a failing helper fails those pulls, as it fails docker pull. Say so in the docs and the docstring, rename the test that pulls without a challenge to say just that, and run the failing-helper test against a bearer registry too. Signed-off-by: xyuzh <[email protected]>
587c741 to
b80a369
Compare
… once (#67023) ## Description Cold pulls of large images are slow. A SWE-bench image with 1.1 GiB of layers took 57-64 s to pull on a CoreWeave node, and two things wasted most of that time: - Layers were downloaded one at a time, and each was extracted only after its download finished. - Each layer was decompressed twice: `tar.getmembers()` reads the whole gzip stream, then `extractfile()` seeks back and decompresses it again. This PR downloads up to three layers at once (Docker's default) into temporary files and extracts them in manifest order as they arrive, so whiteouts and overrides apply exactly as before. A failed download fails the pull right away. The other downloads stop at their next read, and ones that haven't started never connect. `extract_tar_layer` iterates the archive instead of calling `getmembers()` first, so it reads each layer once. It keeps the `r:*` reader rather than stream mode (`r|*`), because only `r:*` checks where a gzip stream ends. That check catches a layer download the registry closed early. Same image, two cold pulls each, alternating: | | master | this PR | | --- | --- | --- | | Whole pull | 63.7 s / 56.7 s | 37.6 s / 37.8 s | | Download and extraction | 38.1 s / 33.0 s | 18.6 s / 16.8 s | This PR doesn't touch the EROFS build. It took 17-24 s in these runs, and both sides built the same 2.92 GiB image. ## Related issues None filed. Found while running SkyRL's SWE-bench Multimodal tasks on Ray Sandbox (skyrl-project/SkyRL#2467). ## Additional information - Not a duplicate: no open PR changes how layers are fetched or read. #66469, #66985 and #67026 edit other parts of `image_utils.py`. - Tests: four new tests. Three layer downloads must run at once and still apply in order. A failed layer must fail the pull within 5 s and close the other downloads. A layer download cut short on a member boundary must fail the pull. A 2 MiB layer must be read once. The first, second and fourth fail on master, and the third fails with stream mode. - Tested on a CoreWeave pod (runsc release-20261005.0, erofs-utils 1.9.4): `TEST_SANDBOX=1 pytest tests/test_gvisor_backend.py tests/test_image_manager.py tests/test_image_utils.py tests/test_sandbox_config.py tests/test_sandbox_runtime.py -k "not netns"`: 93 passed, 1 skipped. `-k netns`: 7 passed. pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Philipp Moritz <[email protected]> Co-authored-by: Philipp Moritz <[email protected]>
Signed-off-by: Philipp Moritz <[email protected]>
dstrodtman
left a comment
There was a problem hiding this comment.
Hi @xyuzh, this is a docs-side review from Douglas Strodtman on the Ray docs team. I used Claude Code to help with this review. I've read every comment below and stand behind it.
Scope: This review covers style, grammar, and docs conventions against Ray's writing-style guide only. Technical accuracy and final approval belong to the maintainers. The suggestions don't change any technical claims. Where I reworded a sentence that carries one, I kept the claim's meaning and strength as written.
The new private-registries section is clear and well organized. Most of the suggestions are punctuation and list mechanics.
Question: This PR removes the sentence from the "Container images" intro saying that python:3.12-slim, library/python:3.12-slim, and docker.io/library/python:3.12-slim share one cache entry. The docstring near image_utils.py:194 at this head still describes that behavior. Was dropping the sentence intentional, or a casualty of the rewrite?
| ## Container images | ||
|
|
||
| Sandboxes boot from OCI container images. The image manager pulls an image straight from the registry's HTTP API (anonymously, with no Docker daemon and no credentials), flattens its layers, and caches the result under `/tmp/ray/sandbox/images` on the node for reuse by subsequent sandboxes on that node using the same image. References that name the same image share one cache entry, so `python:3.12-slim`, `library/python:3.12-slim`, and `docker.io/library/python:3.12-slim` pull and build it once. The cached root filesystem is a single EROFS image, built with `mkfs.erofs`, that gVisor mounts inside the Sentry, which keeps the image's file ownership intact. Sandboxes with write access to the filesystem get their own private writable overlay on top of the cached root filesystem. One consequence: a `readonly=True` sandbox with an explicit `workdir` runs on a private writable overlay, because runsc drops the rootfs overlay for read-only roots and can't create the workdir mount point in an immutable image; its writes are discarded with the sandbox. A cache left by an earlier Ray version, which extracted images into directories, is rebuilt on the next pull. | ||
| Sandboxes boot from OCI container images. The image manager pulls an image straight from the registry's HTTP API, with no Docker daemon, flattens its layers, and caches the result under `/tmp/ray/sandbox/images` on the node for reuse by subsequent sandboxes on that node using the same image. The cached root filesystem is a single EROFS image, built with `mkfs.erofs`, that gVisor mounts inside the Sentry, which keeps the image's file ownership intact. Sandboxes with write access to the filesystem get their own private writable overlay on top of the cached root filesystem. One consequence: a `readonly=True` sandbox with an explicit `workdir` runs on a private writable overlay, because runsc drops the rootfs overlay for read-only roots and can't create the workdir mount point in an immutable image; its writes are discarded with the sandbox. A cache left by an earlier Ray version, which extracted images into directories, is rebuilt on the next pull. |
There was a problem hiding this comment.
Ray's writing-style guide (§Sentence structure) asks for a period instead of a semicolon, and reserves colons for introducing a list or code block. Both predate this PR, but the line is in the diff, so here's a fix:
| Sandboxes boot from OCI container images. The image manager pulls an image straight from the registry's HTTP API, with no Docker daemon, flattens its layers, and caches the result under `/tmp/ray/sandbox/images` on the node for reuse by subsequent sandboxes on that node using the same image. The cached root filesystem is a single EROFS image, built with `mkfs.erofs`, that gVisor mounts inside the Sentry, which keeps the image's file ownership intact. Sandboxes with write access to the filesystem get their own private writable overlay on top of the cached root filesystem. One consequence: a `readonly=True` sandbox with an explicit `workdir` runs on a private writable overlay, because runsc drops the rootfs overlay for read-only roots and can't create the workdir mount point in an immutable image; its writes are discarded with the sandbox. A cache left by an earlier Ray version, which extracted images into directories, is rebuilt on the next pull. | |
| Sandboxes boot from OCI container images. The image manager pulls an image straight from the registry's HTTP API, with no Docker daemon, flattens its layers, and caches the result under `/tmp/ray/sandbox/images` on the node for reuse by subsequent sandboxes on that node using the same image. The cached root filesystem is a single EROFS image, built with `mkfs.erofs`, that gVisor mounts inside the Sentry, which keeps the image's file ownership intact. Sandboxes with write access to the filesystem get their own private writable overlay on top of the cached root filesystem. As a result, a `readonly=True` sandbox with an explicit `workdir` runs on a private writable overlay, because runsc drops the rootfs overlay for read-only roots and can't create the workdir mount point in an immutable image. The overlay's writes are discarded with the sandbox. A cache left by an earlier Ray version, which extracted images into directories, is rebuilt on the next pull. |
There was a problem hiding this comment.
Applied in c0522ea, and I put the dropped cache sentence back into this paragraph.
| 1. **`credHelpers`** maps a registry to a [credential helper](https://github.com/docker/docker-credential-helpers). Ray runs that `docker-credential-<name>` program from the `$PATH` to get the registry's credentials. A helper such as [`docker-credential-ecr-login`](https://github.com/awslabs/amazon-ecr-credential-helper) mints short-lived credentials from the node's cloud identity at pull time, so no secret sits on disk. | ||
| 2. **`credsStore`** names the helper for every registry that `credHelpers` doesn't list. | ||
| 3. **`auths`** holds static credentials, in the format that `docker login` writes and that a Kubernetes `kubernetes.io/dockerconfigjson` Secret stores. Mount such a Secret's `.dockerconfigjson` key as `config.json`. |
There was a problem hiding this comment.
Two style-guide items: number every ordered-list item 1., since MyST renumbers them (§Lists and punctuation), and don't bold inline code (§Bold and italics). The code styling already sets the keys apart.
| 1. **`credHelpers`** maps a registry to a [credential helper](https://github.com/docker/docker-credential-helpers). Ray runs that `docker-credential-<name>` program from the `$PATH` to get the registry's credentials. A helper such as [`docker-credential-ecr-login`](https://github.com/awslabs/amazon-ecr-credential-helper) mints short-lived credentials from the node's cloud identity at pull time, so no secret sits on disk. | |
| 2. **`credsStore`** names the helper for every registry that `credHelpers` doesn't list. | |
| 3. **`auths`** holds static credentials, in the format that `docker login` writes and that a Kubernetes `kubernetes.io/dockerconfigjson` Secret stores. Mount such a Secret's `.dockerconfigjson` key as `config.json`. | |
| 1. `credHelpers` maps a registry to a [credential helper](https://github.com/docker/docker-credential-helpers). Ray runs that `docker-credential-<name>` program from the `$PATH` to get the registry's credentials. A helper such as [`docker-credential-ecr-login`](https://github.com/awslabs/amazon-ecr-credential-helper) mints short-lived credentials from the node's cloud identity at pull time, so no secret sits on disk. | |
| 1. `credsStore` names the helper for every registry that `credHelpers` doesn't list. | |
| 1. `auths` holds static credentials, in the format that `docker login` writes and that a Kubernetes `kubernetes.io/dockerconfigjson` Secret stores. Mount such a Secret's `.dockerconfigjson` key as `config.json`. |
| 2. **`credsStore`** names the helper for every registry that `credHelpers` doesn't list. | ||
| 3. **`auths`** holds static credentials, in the format that `docker login` writes and that a Kubernetes `kubernetes.io/dockerconfigjson` Secret stores. Mount such a Secret's `.dockerconfigjson` key as `config.json`. | ||
|
|
||
| Ray reads the file only when a registry asks a pull to authenticate. It handles both the token authentication that Docker Hub, GHCR, and Artifact Registry use and the HTTP basic authentication that Amazon ECR uses. Docker Hub and GHCR ask every pull to authenticate, including pulls of public images. So when the file holds credentials for them, Ray uses those for public images too, and if their credential helper fails, so do those pulls, as with `docker pull`. |
There was a problem hiding this comment.
The last sentence carries three clauses. Splitting it makes the failure case easier to spot:
| Ray reads the file only when a registry asks a pull to authenticate. It handles both the token authentication that Docker Hub, GHCR, and Artifact Registry use and the HTTP basic authentication that Amazon ECR uses. Docker Hub and GHCR ask every pull to authenticate, including pulls of public images. So when the file holds credentials for them, Ray uses those for public images too, and if their credential helper fails, so do those pulls, as with `docker pull`. | |
| Ray reads the file only when a registry asks a pull to authenticate. It handles both the token authentication that Docker Hub, GHCR, and Artifact Registry use and the HTTP basic authentication that Amazon ECR uses. Docker Hub and GHCR ask every pull to authenticate, including pulls of public images. When the file holds credentials for Docker Hub or GHCR, Ray uses them for public images too. If that registry's credential helper fails, public image pulls from it fail too, as they do with `docker pull`. |
| The credentials stay out of sandboxes. The Ray worker that pulls an image holds them in memory for the pull and sends them only to the registry and to the token service that the registry names, not to the object storage that serves the image's layers. Ray never writes them to the image cache or its logs, and a sandbox's processes see only the image's files and the environment variables that you pass. Keep the following in mind: | ||
|
|
||
| * **Ray checks credentials when it pulls, not when a sandbox starts.** Every sandbox on a node can use any image that the node already holds in its cache. | ||
| * **A sandbox with network access can reach whatever its node can.** That can include the source a credential helper draws on, such as a cloud's instance metadata service. On Amazon EKS, require IMDSv2 with a hop limit of 1, so that Pods, and the sandboxes they run, can't reach it. |
There was a problem hiding this comment.
Spells out IMDSv2 on first use (§Define acronyms on first use) and drops the comma-bracketed aside:
| * **A sandbox with network access can reach whatever its node can.** That can include the source a credential helper draws on, such as a cloud's instance metadata service. On Amazon EKS, require IMDSv2 with a hop limit of 1, so that Pods, and the sandboxes they run, can't reach it. | |
| * **A sandbox with network access can reach whatever its node can.** That can include the source a credential helper draws on, such as a cloud's instance metadata service. On Amazon EKS, require Instance Metadata Service Version 2 (IMDSv2) with a hop limit of 1 so that Pods and the sandboxes they run can't reach it. |
| * **Ray checks credentials when it pulls, not when a sandbox starts.** Every sandbox on a node can use any image that the node already holds in its cache. | ||
| * **A sandbox with network access can reach whatever its node can.** That can include the source a credential helper draws on, such as a cloud's instance metadata service. On Amazon EKS, require IMDSv2 with a hop limit of 1, so that Pods, and the sandboxes they run, can't reach it. | ||
|
|
||
| For example, to pull from Amazon ECR with the IAM role of the Ray Pods, through IRSA or EKS Pod Identity, add `docker-credential-ecr-login` to the Ray image, and give every Ray container that runs sandboxes this configuration: |
There was a problem hiding this comment.
Spells out IRSA on first use, and splits the sentence so the lead-in to the JSON block stands on its own:
| For example, to pull from Amazon ECR with the IAM role of the Ray Pods, through IRSA or EKS Pod Identity, add `docker-credential-ecr-login` to the Ray image, and give every Ray container that runs sandboxes this configuration: | |
| For example, to pull from Amazon ECR with the IAM role of the Ray Pods, through IAM roles for service accounts (IRSA) or EKS Pod Identity, add `docker-credential-ecr-login` to the Ray image. Then give every Ray container that runs sandboxes the following configuration: |
| {"credHelpers": {"<acct>.dkr.ecr.<region>.amazonaws.com": "ecr-login"}} | ||
| ``` | ||
|
|
||
| One way is a ConfigMap, here named `ray-docker-config`, that holds the file as `config.json`, mounted into each Ray container with `DOCKER_CONFIG` pointing at it: |
There was a problem hiding this comment.
"One way" refers back across the JSON block, so it's hard to tell what it's a way of. This version restates the subject and says what the example does:
| One way is a ConfigMap, here named `ray-docker-config`, that holds the file as `config.json`, mounted into each Ray container with `DOCKER_CONFIG` pointing at it: | |
| One way to provide the file is a ConfigMap. The following example mounts a ConfigMap named `ray-docker-config`, which holds the file as `config.json`, into each Ray container and points `DOCKER_CONFIG` at the mount: |
| * **cgroup or permission errors**: In containerized environments such as Kubernetes without root permissions, keep the default `rootless=True`. Where cgroups are restricted, set `RAY_SANDBOX_IGNORE_CGROUPS=1`. | ||
| * **Node disk filling up with images**: The image cache is capped at half of its filesystem by default. Lower the cap with `RAY_SANDBOX_IMAGE_CACHE_MAX_BYTES` (bytes) on worker nodes, or move the cache to a larger volume. Images that running sandboxes use are never evicted, so many concurrent sandboxes on distinct large images still need that much disk. | ||
| * **Image pull failures**: Verify that the node can reach the container registry, such as Docker Hub or GHCR, or pre-populate the image cache directory at `/tmp/ray/sandbox/images`. When many nodes pull large images at once, Docker Hub's anonymous rate limits are a likely cause; see [Route Docker Hub pulls through a mirror](#route-docker-hub-pulls-through-a-mirror). | ||
| * **Image pull failures**: Verify that the node can reach the container registry, such as Docker Hub or GHCR, or pre-populate the image cache directory at `/tmp/ray/sandbox/images`. When many nodes pull large images at once, Docker Hub's anonymous rate limits are a likely cause; see [Route Docker Hub pulls through a mirror](#route-docker-hub-pulls-through-a-mirror). An error that a registry requires credentials, or that a `docker-credential-*` helper failed, points at the node's Docker configuration; see [Pull from private registries](#pull-from-private-registries). |
There was a problem hiding this comment.
Replaces the semicolons with periods (§Sentence structure). The first one predates this PR. The second one is new here, so I've fixed both together:
| * **Image pull failures**: Verify that the node can reach the container registry, such as Docker Hub or GHCR, or pre-populate the image cache directory at `/tmp/ray/sandbox/images`. When many nodes pull large images at once, Docker Hub's anonymous rate limits are a likely cause; see [Route Docker Hub pulls through a mirror](#route-docker-hub-pulls-through-a-mirror). An error that a registry requires credentials, or that a `docker-credential-*` helper failed, points at the node's Docker configuration; see [Pull from private registries](#pull-from-private-registries). | |
| * **Image pull failures**: Verify that the node can reach the container registry, such as Docker Hub or GHCR, or pre-populate the image cache directory at `/tmp/ray/sandbox/images`. When many nodes pull large images at once, Docker Hub's anonymous rate limits are a likely cause. See [Route Docker Hub pulls through a mirror](#route-docker-hub-pulls-through-a-mirror). An error that a registry requires credentials, or that a `docker-credential-*` helper failed, points at the node's Docker configuration. See [Pull from private registries](#pull-from-private-registries). |
…tence Apply the seven style suggestions from the docs review. Also put back the sentence that ray-project#66985 added to the "Container images" intro, which was lost when master was merged into this branch. Signed-off-by: xyuzh <[email protected]>
A Kubernetes dockerconfigjson Secret may file Docker Hub's credentials under docker.io, which kubelet accepts but the lookup missed. Take an auths entry under any Docker Hub hostname when the Docker CLI's own key, https://index.docker.io/v1/, isn't there. Signed-off-by: xyuzh <[email protected]>
xyuzh
left a comment
There was a problem hiding this comment.
Applied all seven in c0522ea, thanks @dstrodtman.
On your question: dropping the cache sentence wasn't intentional. #66985 added it on master, and it got lost when master was merged into this branch. It's back in the same commit.
@pcmoritz one small code change since your approval: aeea32d, from the Bugbot thread below.
| ## Container images | ||
|
|
||
| Sandboxes boot from OCI container images. The image manager pulls an image straight from the registry's HTTP API (anonymously, with no Docker daemon and no credentials), flattens its layers, and caches the result under `/tmp/ray/sandbox/images` on the node for reuse by subsequent sandboxes on that node using the same image. References that name the same image share one cache entry, so `python:3.12-slim`, `library/python:3.12-slim`, and `docker.io/library/python:3.12-slim` pull and build it once. The cached root filesystem is a single EROFS image, built with `mkfs.erofs`, that gVisor mounts inside the Sentry, which keeps the image's file ownership intact. Sandboxes with write access to the filesystem get their own private writable overlay on top of the cached root filesystem. One consequence: a `readonly=True` sandbox with an explicit `workdir` runs on a private writable overlay, because runsc drops the rootfs overlay for read-only roots and can't create the workdir mount point in an immutable image; its writes are discarded with the sandbox. A cache left by an earlier Ray version, which extracted images into directories, is rebuilt on the next pull. | ||
| Sandboxes boot from OCI container images. The image manager pulls an image straight from the registry's HTTP API, with no Docker daemon, flattens its layers, and caches the result under `/tmp/ray/sandbox/images` on the node for reuse by subsequent sandboxes on that node using the same image. The cached root filesystem is a single EROFS image, built with `mkfs.erofs`, that gVisor mounts inside the Sentry, which keeps the image's file ownership intact. Sandboxes with write access to the filesystem get their own private writable overlay on top of the cached root filesystem. One consequence: a `readonly=True` sandbox with an explicit `workdir` runs on a private writable overlay, because runsc drops the rootfs overlay for read-only roots and can't create the workdir mount point in an immutable image; its writes are discarded with the sandbox. A cache left by an earlier Ray version, which extracted images into directories, is rebuilt on the next pull. |
There was a problem hiding this comment.
Applied in c0522ea, and I put the dropped cache sentence back into this paragraph.
| 1. **`credHelpers`** maps a registry to a [credential helper](https://github.com/docker/docker-credential-helpers). Ray runs that `docker-credential-<name>` program from the `$PATH` to get the registry's credentials. A helper such as [`docker-credential-ecr-login`](https://github.com/awslabs/amazon-ecr-credential-helper) mints short-lived credentials from the node's cloud identity at pull time, so no secret sits on disk. | ||
| 2. **`credsStore`** names the helper for every registry that `credHelpers` doesn't list. | ||
| 3. **`auths`** holds static credentials, in the format that `docker login` writes and that a Kubernetes `kubernetes.io/dockerconfigjson` Secret stores. Mount such a Secret's `.dockerconfigjson` key as `config.json`. |
| 2. **`credsStore`** names the helper for every registry that `credHelpers` doesn't list. | ||
| 3. **`auths`** holds static credentials, in the format that `docker login` writes and that a Kubernetes `kubernetes.io/dockerconfigjson` Secret stores. Mount such a Secret's `.dockerconfigjson` key as `config.json`. | ||
|
|
||
| Ray reads the file only when a registry asks a pull to authenticate. It handles both the token authentication that Docker Hub, GHCR, and Artifact Registry use and the HTTP basic authentication that Amazon ECR uses. Docker Hub and GHCR ask every pull to authenticate, including pulls of public images. So when the file holds credentials for them, Ray uses those for public images too, and if their credential helper fails, so do those pulls, as with `docker pull`. |
| The credentials stay out of sandboxes. The Ray worker that pulls an image holds them in memory for the pull and sends them only to the registry and to the token service that the registry names, not to the object storage that serves the image's layers. Ray never writes them to the image cache or its logs, and a sandbox's processes see only the image's files and the environment variables that you pass. Keep the following in mind: | ||
|
|
||
| * **Ray checks credentials when it pulls, not when a sandbox starts.** Every sandbox on a node can use any image that the node already holds in its cache. | ||
| * **A sandbox with network access can reach whatever its node can.** That can include the source a credential helper draws on, such as a cloud's instance metadata service. On Amazon EKS, require IMDSv2 with a hop limit of 1, so that Pods, and the sandboxes they run, can't reach it. |
| * **Ray checks credentials when it pulls, not when a sandbox starts.** Every sandbox on a node can use any image that the node already holds in its cache. | ||
| * **A sandbox with network access can reach whatever its node can.** That can include the source a credential helper draws on, such as a cloud's instance metadata service. On Amazon EKS, require IMDSv2 with a hop limit of 1, so that Pods, and the sandboxes they run, can't reach it. | ||
|
|
||
| For example, to pull from Amazon ECR with the IAM role of the Ray Pods, through IRSA or EKS Pod Identity, add `docker-credential-ecr-login` to the Ray image, and give every Ray container that runs sandboxes this configuration: |
| {"credHelpers": {"<acct>.dkr.ecr.<region>.amazonaws.com": "ecr-login"}} | ||
| ``` | ||
|
|
||
| One way is a ConfigMap, here named `ray-docker-config`, that holds the file as `config.json`, mounted into each Ray container with `DOCKER_CONFIG` pointing at it: |
| * **cgroup or permission errors**: In containerized environments such as Kubernetes without root permissions, keep the default `rootless=True`. Where cgroups are restricted, set `RAY_SANDBOX_IGNORE_CGROUPS=1`. | ||
| * **Node disk filling up with images**: The image cache is capped at half of its filesystem by default. Lower the cap with `RAY_SANDBOX_IMAGE_CACHE_MAX_BYTES` (bytes) on worker nodes, or move the cache to a larger volume. Images that running sandboxes use are never evicted, so many concurrent sandboxes on distinct large images still need that much disk. | ||
| * **Image pull failures**: Verify that the node can reach the container registry, such as Docker Hub or GHCR, or pre-populate the image cache directory at `/tmp/ray/sandbox/images`. When many nodes pull large images at once, Docker Hub's anonymous rate limits are a likely cause; see [Route Docker Hub pulls through a mirror](#route-docker-hub-pulls-through-a-mirror). | ||
| * **Image pull failures**: Verify that the node can reach the container registry, such as Docker Hub or GHCR, or pre-populate the image cache directory at `/tmp/ray/sandbox/images`. When many nodes pull large images at once, Docker Hub's anonymous rate limits are a likely cause; see [Route Docker Hub pulls through a mirror](#route-docker-hub-pulls-through-a-mirror). An error that a registry requires credentials, or that a `docker-credential-*` helper failed, points at the node's Docker configuration; see [Pull from private registries](#pull-from-private-registries). |
andrewsykim
left a comment
There was a problem hiding this comment.
We should also ensure workloads can use service account tokens mounted into Pods to access images, this should be possible on both AWS / GCP.
|
@andrewsykim Agreed. Both should already work through credential helpers, which use the Pod's identity at pull time. On EKS, |
Signed-off-by: xyuzh <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit a46eeac. Configure here.
| helpers = config.get("credHelpers") or {} | ||
| helper = helpers.get(key, config.get("credsStore")) | ||
| if helper: | ||
| return _helper_credentials(helper, key, timeout) |
There was a problem hiding this comment.
Helper miss skips auths fallback
Medium Severity
When a credHelpers or credsStore helper reports nothing stored for the registry, registry_credentials returns None and never reads that registry's auths entry. Docker CLI still uses those static credentials in this case, so a config that pairs a global helper with auths for other registries fails the pull even though docker pull succeeds.
Reviewed by Cursor Bugbot for commit a46eeac. Configure here.
There was a problem hiding this comment.
Not changing this: it matches Docker CLI. With a credHelpers entry or a credsStore for the registry, docker/cli reads through the helper's store (GetCredentialsStore), and on a miss nativeStore.Get overwrites the auths entry's username and password with the helper's empty result, so docker pull goes anonymous there too.
… once (ray-project#67023) ## Description Cold pulls of large images are slow. A SWE-bench image with 1.1 GiB of layers took 57-64 s to pull on a CoreWeave node, and two things wasted most of that time: - Layers were downloaded one at a time, and each was extracted only after its download finished. - Each layer was decompressed twice: `tar.getmembers()` reads the whole gzip stream, then `extractfile()` seeks back and decompresses it again. This PR downloads up to three layers at once (Docker's default) into temporary files and extracts them in manifest order as they arrive, so whiteouts and overrides apply exactly as before. A failed download fails the pull right away. The other downloads stop at their next read, and ones that haven't started never connect. `extract_tar_layer` iterates the archive instead of calling `getmembers()` first, so it reads each layer once. It keeps the `r:*` reader rather than stream mode (`r|*`), because only `r:*` checks where a gzip stream ends. That check catches a layer download the registry closed early. Same image, two cold pulls each, alternating: | | master | this PR | | --- | --- | --- | | Whole pull | 63.7 s / 56.7 s | 37.6 s / 37.8 s | | Download and extraction | 38.1 s / 33.0 s | 18.6 s / 16.8 s | This PR doesn't touch the EROFS build. It took 17-24 s in these runs, and both sides built the same 2.92 GiB image. ## Related issues None filed. Found while running SkyRL's SWE-bench Multimodal tasks on Ray Sandbox (skyrl-project/SkyRL#2467). ## Additional information - Not a duplicate: no open PR changes how layers are fetched or read. ray-project#66469, ray-project#66985 and ray-project#67026 edit other parts of `image_utils.py`. - Tests: four new tests. Three layer downloads must run at once and still apply in order. A failed layer must fail the pull within 5 s and close the other downloads. A layer download cut short on a member boundary must fail the pull. A 2 MiB layer must be read once. The first, second and fourth fail on master, and the third fails with stream mode. - Tested on a CoreWeave pod (runsc release-20261005.0, erofs-utils 1.9.4): `TEST_SANDBOX=1 pytest tests/test_gvisor_backend.py tests/test_image_manager.py tests/test_image_utils.py tests/test_sandbox_config.py tests/test_sandbox_runtime.py -k "not netns"`: 93 passed, 1 skipped. `-k netns`: 7 passed. pre-commit passes. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Philipp Moritz <[email protected]> Co-authored-by: Philipp Moritz <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
ray-project#67026) ## Description Ray Sandbox pulled every image anonymously. A registry that answers with an HTTP basic challenge, as Amazon ECR does, failed every pull with `HTTP Error 401: Unauthorized`, and private images on Docker Hub, GHCR or Artifact Registry failed too. This PR answers the registry's challenge with the credentials that the node's Docker config (`$DOCKER_CONFIG/config.json`, by default `~/.docker/config.json`) holds for it. It looks them up the way the Docker CLI does: the registry's `credHelpers` helper, else `credsStore`, else its `auths` entry. A helper such as `docker-credential-ecr-login` mints short-lived credentials from the Pod's IAM role at pull time, so no secret sits on disk. Start with the new `_internal/docker_config.py`, then `get_registry_auth_headers` in `image_utils.py`. - A basic challenge gets the credentials on every registry request. A bearer challenge trades them, or an identity token through the OAuth2 refresh grant, for a pull token. Redirects to presigned storage never carry them. - Credentials stay in the pulling worker. They never reach the image cache, logs, error messages, or a sandbox. - A failed pull includes the registry's stated reason. ECR's `DENIED` names the IAM action that the role lacks. - A `RAY_SANDBOX_REGISTRY_MIRROR` mirror authenticates the same way, so an ECR pull-through cache works. - New docs section: "Pull from private registries", with an ECR example. One change users may notice: Docker Hub and GHCR challenge every pull, public images included. A node whose Docker config has credentials for them now pulls public images with those, and if their credential helper fails, so does the pull, as with `docker pull`. A node with no Docker config pulls as before. ## Related issues None filed. A user running Ray on EKS with sandbox images in private ECR asked for this, and SkyRL's Harbor environment for Ray Sandbox (skyrl-project/SkyRL#2467) lists registry auth as a gap. ## Additional information - Not a duplicate: no open PR matching "sandbox registry", "sandbox credentials", "credHelpers" or "ECR sandbox" authenticates pulls. ray-project#66782, the Modal API prototype, rejects private registries. - Tests: `tests/test_registry_auth.py` (37 tests, all failing on master) serves a fake registry and fake credential helpers from the standard library. It covers lookup order, both challenges, the refresh grant, redirects, the mirror, malformed configs, and secrets in errors. `tests/conftest.py` points `DOCKER_CONFIG` at an empty directory, so no test uses the runner's credentials. - Tested on a CoreWeave pod (runsc release-20261005.0, erofs-utils 1.9.4), `TEST_SANDBOX=1 pytest` in `python/ray/experimental/sandbox/tests`: - `test_gvisor_backend.py test_image_manager.py test_image_utils.py test_sandbox_config.py test_sandbox_runtime.py test_registry_auth.py -k "not netns and not test_create_sandbox_helper"`: 125 passed, 1 skipped. - `test_gvisor_backend.py -k netns`: 7 passed. `test_sandbox.py` plus `test_create_sandbox_helper`: 7 passed. - macOS, `test_registry_auth.py test_image_utils.py`: 72 passed. pre-commit passes. - End to end, on the first commit: in the same kind of pod, a gVisor sandbox booted from a private image behind a `registry` 3.0.0 with htpasswd (a basic challenge, like ECR's), and the password reached none of the sandbox's environment, processes or files. Master gets a 401. - I used Claude Code to help write and test this change. --------- Signed-off-by: xyuzh <[email protected]> Signed-off-by: Philipp Moritz <[email protected]> Co-authored-by: Philipp Moritz <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4


Description
Ray Sandbox pulled every image anonymously. A registry that answers with an HTTP basic challenge, as Amazon ECR does, failed every pull with
HTTP Error 401: Unauthorized, and private images on Docker Hub, GHCR or Artifact Registry failed too.This PR answers the registry's challenge with the credentials that the node's Docker config (
$DOCKER_CONFIG/config.json, by default~/.docker/config.json) holds for it. It looks them up the way the Docker CLI does: the registry'scredHelpershelper, elsecredsStore, else itsauthsentry. A helper such asdocker-credential-ecr-loginmints short-lived credentials from the Pod's IAM role at pull time, so no secret sits on disk. Start with the new_internal/docker_config.py, thenget_registry_auth_headersinimage_utils.py.DENIEDnames the IAM action that the role lacks.RAY_SANDBOX_REGISTRY_MIRRORmirror authenticates the same way, so an ECR pull-through cache works.One change users may notice: Docker Hub and GHCR challenge every pull, public images included. A node whose Docker config has credentials for them now pulls public images with those, and if their credential helper fails, so does the pull, as with
docker pull. A node with no Docker config pulls as before.Related issues
None filed. A user running Ray on EKS with sandbox images in private ECR asked for this, and SkyRL's Harbor environment for Ray Sandbox (skyrl-project/SkyRL#2467) lists registry auth as a gap.
Additional information
tests/test_registry_auth.py(37 tests, all failing on master) serves a fake registry and fake credential helpers from the standard library. It covers lookup order, both challenges, the refresh grant, redirects, the mirror, malformed configs, and secrets in errors.tests/conftest.pypointsDOCKER_CONFIGat an empty directory, so no test uses the runner's credentials.TEST_SANDBOX=1 pytestinpython/ray/experimental/sandbox/tests:test_gvisor_backend.py test_image_manager.py test_image_utils.py test_sandbox_config.py test_sandbox_runtime.py test_registry_auth.py -k "not netns and not test_create_sandbox_helper": 125 passed, 1 skipped.test_gvisor_backend.py -k netns: 7 passed.test_sandbox.pyplustest_create_sandbox_helper: 7 passed.test_registry_auth.py test_image_utils.py: 72 passed. pre-commit passes.registry3.0.0 with htpasswd (a basic challenge, like ECR's), and the password reached none of the sandbox's environment, processes or files. Master gets a 401.