Repository navigation
[core][sandbox] Require the API token on the gRPC facade - #66675
Conversation
The gRPC facade served sandbox create, exec, and file access to any client that could reach its port: unlike the REST app, it never read RAY_SANDBOX_API_TOKEN. When the token is set, every RPC must now present it, as the client SDK's token secret or as "authorization: Bearer <token>". TaskGetCommandRouterAccess hands the token out as the command router's credential, which the SDK sends as a bearer token, so an unmodified client only needs its token secret set. The check wraps the servicers' handler tables, so every grpclib server built from build_servicers enforces it, on every RPC, before a handler reads its request. Without a token, the CLI now refuses a non-loopback --host unless --allow-unauthenticated is passed: sandboxes with network access reach any address their node can, so a tokenless facade on a network address would also serve the code running inside them. Also: - The REST app compares the bearer header as bytes, so a non-ASCII header is a 401 instead of a TypeError and a 500. - test_seeding_stays_inside_the_tree no longer depends on where pytest's tmp_path lives. Under /tmp, as in CI, the image's /tmp link named a path under /tmp, a symlink loop, which failed the core sandbox tests. - The HTTP tests no longer pick up a token exported in the shell, and the SDK test helper no longer waits on the SDK's idle connection when it stops the facade (Python 3.12+). Signed-off-by: xyuzh <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces token-based authentication for the Ray Sandbox gRPC facade, aligning its security model with the REST API. It requires clients to present a token (via RAY_SANDBOX_API_TOKEN) for all RPCs when configured, and restricts unauthenticated facades to loopback addresses by default. The changes also include encoding updates to handle non-ASCII authorization headers safely, comprehensive test coverage for the new authentication flows, and documentation updates. Feedback on the changes highlights a potential security vulnerability in _TokenGate where an empty string token could allow unauthenticated clients to bypass authentication because hmac.compare_digest evaluates empty strings to True. It is recommended to check if not token instead of if token is None to safely treat empty tokens as disabled authentication.
| token = self._state.token | ||
| if token is None: | ||
| return mapping |
There was a problem hiding this comment.
If token is configured as an empty string "", _TokenGate will still wrap the handlers because token is None is False. In _carries_token, comparing an empty expected token against an empty presented token (when no headers are sent) using hmac.compare_digest(b"", b"") will return True, effectively bypassing authentication for unauthenticated clients. Changing the check to if not token: ensures that empty tokens are safely treated as disabled authentication.
| token = self._state.token | |
| if token is None: | |
| return mapping | |
| token = self._state.token | |
| if not token: | |
| return mapping |
…#66675) ## Description The Ray Sandbox gRPC facade (`ray.experimental.sandbox.http.grpc_facade`) served sandbox create, exec, and file read/write to any client that could reach its port. Unlike the REST app, it never read `RAY_SANDBOX_API_TOKEN`, so even an operator who wanted to lock it down couldn't, and the documented quickstart binds `--host 0.0.0.0`. With this PR: - **The token is required on every RPC.** When `RAY_SANDBOX_API_TOKEN` is set, a call that doesn't present it fails with `UNAUTHENTICATED` before its handler reads the request. - A client presents the token the way the client SDK already sends credentials: as its token secret (`x-modal-token-secret`, from `MODAL_TOKEN_SECRET`), or as `authorization: Bearer <token>`, the REST app's form, which `MODAL_OVERRIDE_HEADERS` can also send. - `TaskGetCommandRouterAccess` hands out the token as the command router's credential. The SDK then sends it as a bearer token on every exec and file call, so an unmodified client only needs `MODAL_TOKEN_SECRET` set. - A bearer-only check wouldn't work with the SDK: its control-plane calls carry the token secret, and its router calls carry only the credential that `TaskGetCommandRouterAccess` returned. - **The check is bound to the servicers, not to one server.** `_TokenGate` wraps the handler table (`__mapping__`) that `grpclib.server.Server` dispatches through. So every server built from `build_servicers` is gated, including RPCs added later, such as ray-project#66359's `TaskSetNetworkAccess`. Without a token the table is returned unchanged. - **The CLI fails closed.** Without a token, `python -m ray.experimental.sandbox.http.grpc_facade` refuses a non-loopback `--host` unless `--allow-unauthenticated` is passed. - Keeping the facade on a private network isn't enough on its own. The facade's sandboxes get open egress by default and can reach any address their node can, including the facade's. So a tokenless facade on a network address would also serve the code running inside them. - Loopback binds stay tokenless, since `--disable-host-loopback` keeps sandboxes off the node's loopback. - **Docs.** The gRPC section now covers: - the token; - the trust model: one token controls every sandbox in the namespace, as with the REST token, with no per-client isolation; - the TLS requirement; - a fix for the stale network bullet: allowlists are refused, not widened. - **REST.** `require_bearer_token` compares bytes, so a non-ASCII `Authorization` header gets a 401 instead of a `TypeError` and a 500. **Behavior change:** a tokenless facade started with a non-loopback `--host`, as the old quickstart did, now exits with an error that names `RAY_SANDBOX_API_TOKEN` and `--allow-unauthenticated`. **This PR also fixes the failing `:ray: core: sandbox tests` job** (for example premerge build 74278 and microcheck build 55110). - `test_image_utils.py::test_seeding_stays_inside_the_tree` linked the fake image's `/tmp` to an absolute path under pytest's `tmp_path`, which is itself under `/tmp` in CI. - From the image's point of view that's a symlink loop. `_resolve_in_root` correctly reports it as `ELOOP`, so nothing was seeded. - The test now gives `tmp` its own tree with a relative link. The product code is unchanged. - The test only passed on macOS because `tmp_path` lives under `/private/var/folders` there. ## Related issues Related to ray-project#65839 (the facade) and ray-project#65352 (sandboxing umbrella). Not a duplicate: no open PR or issue covers facade authentication. I searched open PRs and issues for `grpc_facade`, `RAY_SANDBOX_API_TOKEN`, and sandbox authentication. ## Additional information **Tests run.** Environment: macOS, Python 3.12, the ray 2.58 wheel with this branch's sandbox package overlaid, grpclib 0.4.9. | Command | Result | | --- | --- | | `pytest --import-mode=importlib python/ray/experimental/sandbox/http/tests` | 130 passed, 8 skipped (modal not installed, `TEST_SANDBOX` unset) | | The same, with `RAY_SANDBOX_API_TOKEN=ambient` exported | 130 passed, 8 skipped | | `uv run --with modal==1.5.5 pytest .../http/tests/test_modal_client.py` | 6 passed | | `uv run --with modal==1.5.1 pytest .../http/tests/test_modal_client.py` | 5 passed, 1 skipped (1.5.1 can't send custom headers) | | The new auth tests against `origin/master`'s `grpc_facade.py` | 29 failed, as expected | | `test_image_utils.py::test_seeding_stays_inside_the_tree`, with the default `tmp_path` and with `tmp_path` under `/tmp` | Passed both ways (the old test fails with `tmp_path` under `/tmp`) | | `python -m ray.experimental.sandbox.http.grpc_facade --host 0.0.0.0` without a token | Exit 2, before connecting to the cluster | | Unauthenticated create path replayed against a local Ray cluster | Anonymous and wrong-token `AppGetOrCreate`, `ImageGetOrCreate`, and `SandboxCreate` return `UNAUTHENTICATED` and create no actor. With the token, a `SandboxHost` actor is created and then terminated. | | `pre-commit` (ruff, pydoclint, docstyle, import order), black 22.10.0, API param coverage check | Pass | `test_grpc_facade.py` and `test_modal_client.py` skip in CI because grpclib and modal aren't in the CI image, so the auth tests above ran locally only. AI assistance was used to write this change. Signed-off-by: xyuzh <[email protected]> Co-authored-by: Philipp Moritz <[email protected]>
## Why are these changes needed? Style and grammar pass over the remaining Ray Core prose pages, against `doc/source/ray-contribute/writing-style.md` and its "Writing Ray Core docs" terms. This is the fifth and last prose layer of the Ray Core stack: `compiled-graph/`, `direct-transport/`, `internals/`, `accelerator-types.md`, `api/index.md`, `examples/index.md`, and `examples/monte-carlo-pi.md`. It's stacked on #66672 (fault tolerance and scheduling), which is stacked on #66667 (design patterns), #66666 (tasks, actors, and objects), #66642 (top-level pages), #66640 (Core Vale term library), and #66605 (the `ray-core/` to `core/` move). Three things are out of scope. `sandboxes.md` and `api/sandboxes.md` are left for a follow-up, because five open PRs (#66675, #66471, #66470, #66359, #65898) make large edits to them. The autodoc `.rst` API pages and the example notebooks aren't prose pages. The edits are voice, person, tense, word choice, and list structure. First-person plural is now "you" or an imperative. Per the Core terms table, "Raylet" mid-sentence is now "raylet", "plasma store" is now "Plasma store", and "via" is now "through". Parenthetical asides and em dashes are now separate sentences or lists, and ordered lists use `1.` throughout. `internals/object-spilling.md` had 24 em dashes and now has none. Two MyST conversion artifacts were inline pseudo-lists (`\*` and `\-` bullets in one paragraph) in `compiled-graph/quickstart.md` and `internals/ray-event-exporter.md`. A third was a numbered list collapsed into one paragraph in `direct-transport/index.md`. All three are now real lists. Compiled Graph got a light pass, because #66464 deprecates it. The lines where #66464 inserts its deprecation banners are byte-identical, including each page's front matter, H1, and the paragraph after it, plus the landing page's beta warning. #66464's doc changes still apply cleanly on top of this branch. Headings changed only in case, except two whose slugs changed. On `compiled-graph/troubleshooting.md`, "Explicitly teardown before reusing the same actors" is now "Explicitly tear down...". On `internals/object-spilling.md`, "Primary vs. Secondary Copies" is now "Primary versus secondary copies". Both keep their old URL fragments through MyST labels named after the old slugs. No link in `doc/source` targets either old slug. No code block, role target, or URL changed beyond the fixes below. ### Fixes Each of these is checked against the page itself: - `compiled-graph/troubleshooting.md`: two `{ref}` links pointed at each other's sections. The item about tearing down a Compiled Graph before running another on the same actor linked to "Return NumPy arrays". The item about zero-copy values blocking later executions linked to the teardown section. Each now links to the section it describes. - `compiled-graph/quickstart.md`: "a ActorDiedError" is now "an". - `internals/metric-exporter.md`: the cardinality level labels were written as `` **\`legacy\`** ``, which rendered literal backticks. They're now bold code. - `examples/monte-carlo-pi.md`: the `{image}` directive had no alt text. ### Pre-existing claims, tracked separately These claims were already on the pages, and this pass kept them as written. They don't block this PR. #66790 fixes the mechanical ones and #66791 corrects the ones that the source settles, both stacked on #66677. The rest need a Core engineering decision and are tracked separately: - `compiled-graph/quickstart.md` and `troubleshooting.md`: several roadmap sentences, such as "Ray might detect such errors in the future", "The Ray team also plans to support custom communicators", and "Collective communication operations are coming soon". With #66464 deprecating Compiled Graph, should these go? - `compiled-graph/overlap.md`: "enabling `_overlap_gpu_communication` improves latency by about 14%". Latency goes down; the sample output shows about 13.7% less. Should this say "reduces latency"? - `compiled-graph/profiling.md`: the heading "Nsight system profiler" and the prose "Nsight system profiling". NVIDIA's product is Nsight Systems. - `direct-transport/index.md`: the NCCL section lists using `create_collective_group` as a "main difference" from the Gloo example, but the Gloo example also uses it. - `direct-transport/custom-tensor-transport.md`: the "Out-of-order actors" limitation looks like a special case of the "Actor creation and task submission from different processes" limitation that follows it. Is being out of order a separate trigger? - `internals/task-lifecycle.md`: the execution steps say the executor pulls arguments from a remote Plasma store if needed before it runs the function. A later step says the data was already pulled during scheduling. Which is right? - `internals/object-spilling.md`: - The architecture section says the raylet decides what to spill by least recently used (LRU) order and pinning status. The batch construction section says `TryToSpillObjects` walks `pinned_objects_` in order. Is spill selection LRU? - The prose says spilling starts when usage "exceeds" `object_spilling_threshold`, but the trigger table uses `>=`. - The configuration list calls `object_spilling_threshold` a fraction of available object store memory, while the trigger table defines it as primary object bytes divided by capacity. - Is `max_io_workers` a total, or per worker type, as the worker pool section says? - "GCS" in the cloud storage passages means Google Cloud Storage. On a Ray Core page, it reads as Ray's GCS. Should it be spelled out? - `internals/ray-event-exporter.md`: - The page says it describes Ray 2.52.1, but `RAY_DASHBOARD_AGGREGATOR_AGENT_EXPOSABLE_EVENT_TYPES` says `ALL` is supported in Ray 2.54.0 and later. - The Step 5 link text names `RayEventRecorder::AddEvent()`, but it points at the line the page elsewhere calls `AddEvents()`. - The Step 6 aggregator link uses the same anchor as Step 4. - `internals/metric-exporter.md`: the `DoubleGaugeCallback` link is pinned to commit `52ed7e3`, while every other link on the page uses `05e7efd5`. The `OpenTelemetryMetricRecorder::SetMetricValue()` link points into `src/ray/stats/metric.cc`. - `internals/token-authentication.md`: two notes both say that new HTTP services must add the middleware and header injection themselves. Should one go? - `compiled-graph/troubleshooting.md`: the page says Compiled Graph supports only peer-to-peer GPU transfers and that collective operations are planned, but `ray.experimental.collective` exports `allreduce`, `allgather`, and `reducescatter` with DAG wrappers. Is the limitation stale? - `internals/metric-exporter.md`: the page says C++ metrics register lazily on first use. With OpenTelemetry enabled, registration seems to happen when the `ray::stats` metric object is constructed (`src/ray/stats/metric.h`), and `SetMetricValue` fails on an unregistered name. - `internals/object-spilling.md`: the page names `ReleaseFreedObject()`; the function is `LocalObjectManager::ReleaseFreedLocalObject`. The two `PopDeleteWorker` links point at different lines of `worker_pool.cc`. - `internals/ray-event-exporter.md`: `_can_expose_event` and the event filtering now live in `publisher/async_publisher_client.py`, not `aggregator_agent.py`, and `ALL` bypasses the exposable-types list. - `internals/port-service-discovery.md`: the page calls core workers C++ processes. The core worker is a C++ library inside Python, Java, or C++ worker processes. - `examples/monte-carlo-pi.md`: the sampling task is described as sampling "up to" `num_samples`, but the code samples exactly `num_samples`. - `examples/index.md`: several list-table link texts don't match the titles of the notebooks they link to, such as "Build Batch Prediction Using Ray" for "Batch Prediction with Ray Core". ## Related issue number None. Not a duplicate. #66464 edits the Compiled Graph pages; see above. ## Checks - `vale` on the 21 pages from the repo root: 1,228 alerts before the pass, 372 after all three commits. The remaining alerts are intentional passives where the page names no actor, "currently" and "for now" where they mark an alpha feature or a temporary limitation, acronym alerts that fire after the acronym is spelled out, code identifiers used as link text, alerts on the lines protected for #66464, and Mermaid diagram source in `object-spilling.md`. - The third commit adds Perfetto, GDRCopy, `inlines` and `inlined`, `unlink`, `temporality`, `misconfiguration`, and `microbenchmark` to the `General` accept list, and `evictable` and `exposable` to the `Core` accept list. Across `doc/source` that removes 16 alerts and adds none. - `codespell` on the 21 pages: clean apart from `asend`, the Python async generator method. - Per-file invariant check against the pre-edit files: fenced-code count, role-target multiset, and URLs unchanged. The only anchor changes are the two legacy-slug labels. Line-count changes come from the new lists, the repaired pseudo-lists, and blank-line cleanup. - `doc/.claude/skills/ray-soft-wrap/scripts/softwrap.py --check`: clean. - `git apply --check` of #66464's doc hunks onto this branch, with paths remapped to `doc/source/core/`: clean. - Meaning review of the first commit: of 691 changed blocks, 140 were cosmetic. The other 551 were checked against source, and 545 preserved their meaning. The second commit restores the six that didn't: three `request_resources` mentions on `autoscaler-v2.md` that had made the caller "you" (Ray Data also calls it), the users-set-it framing of an environment variable on `ray-event-exporter.md`, "currently spillable" on `object-spilling.md`, and the attribution of a NIXL limitation on `direct-transport/index.md`. It also restores a few smaller shifts that the review noted. - A later commit restores one more shift, on `internals/port-service-discovery.md`. The pass had turned "Raylet (C++) spawns Core Workers (C++)" into "both are C++ processes", which is wrong for Python and Java worker processes. The restored sentence says both are written in C++. - Full `-W` doc build: relying on the Read the Docs preview. AI assistance (Claude Code) was used to draft these edits. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
…C facade (#66675) (#66897) Cherry-pick of #66675 (master commit 4f967ab) onto `releases/2.60.0`. ## Why - **The gRPC facade ships without authentication on this branch.** `releases/2.60.0` includes the sandbox gRPC facade (#65839) but not #66675, which makes it require the API token. This pick brings the branch's facade in line with master. - **It fixes the `:ray: core: sandbox tests` job on this branch.** For example, it fails in microcheck build 55893 for #66801. `test_image_utils.py::test_seeding_stays_inside_the_tree` linked the fake image's `/tmp` to an absolute path under pytest's `tmp_path`, which is itself under `/tmp` in CI. #66675 fixes the test, and the product code is unchanged. The branch already has #65815, which made the sandbox tests actually run in CI instead of skipping. ## Cherry-pick details Applied cleanly with `git cherry-pick -x`. The diff is byte-identical to the master commit: the same 10 files, 726 insertions and 29 deletions, with identical hunks, context lines and offsets. No prerequisite commits are missing: - No commit on master between the branch cut and #66675 touched `python/ray/experimental/sandbox/` or `doc/source/ray-core/sandboxes.md`. Neither did any commit on this branch after the cut. - After the pick, the whole `python/ray/experimental/sandbox/` package and `doc/source/ray-core/sandboxes.md` are identical to master at 4f967ab. - Outside the sandbox package, the picked code imports only `ray.util.annotations`, which is identical on both branches. Not a duplicate: no existing PR against `releases/2.60.0` references #66675. ## Testing `test_grpc_facade.py` and `test_modal_client.py` skip in CI because `grpclib` and `modal` aren't in the CI image, so I ran them locally. Environment: Linux, Python 3.10, `grpclib` 0.4.9 and `modal` 1.5.5 (the versions #66675 used). Other test dependencies were pinned from `python/requirements_compiled.txt`. Ray was the CI-built `ray-2.60.0` wheel for this PR's parent commit (b7a4529), with the wheel's `ray/experimental/sandbox/` replaced by this branch's copy. | Command | Code under test | Result | |---|---|---| | `pytest .../http/tests/test_grpc_facade.py .../http/tests/test_modal_client.py` | this PR | 58 passed (52 + 6), 0 skipped | | `pytest .../http/tests` | this PR | 136 passed, 2 skipped (`test_http_integration.py`, `TEST_SANDBOX` unset) | | Same two files, the branch's tests before this pick | `releases/2.60.0` | 24 passed | | This PR's two test files | `releases/2.60.0` (before this pick) | 30 failed, 28 passed: every token/auth test fails, as expected | `test_image_utils.py::test_seeding_stays_inside_the_tree` and the 2 skipped `test_http_integration.py` cases run in CI's `:ray: core: sandbox tests` job, which sets `TEST_SANDBOX=1`. AI assistance was used to prepare this cherry-pick. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: xyuzh <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: Xinyu Zhang <[email protected]> Co-authored-by: Philipp Moritz <[email protected]>
## Description Lets Ray Serve deploy the Modal-compatible gRPC facade (#65839), so a Serve application, such as an Anyscale service, exposes the facade from configuration alone. The facade itself becomes a standard `grpc` servicer, which both its own server and Serve's gRPC proxy call: - Each RPC is a method named after it that takes the request and the call's context (as `grpc_context`, the name Serve passes it under) and returns or yields its replies. The vendored service stubs are now grpcio's (`*_pb2_grpc.py`, from the same pinned grpcio-tools), so the facade no longer needs grpclib, and `python -m ray.experimental.sandbox.http.grpc_facade` runs a `grpc.aio` server. - `RaySandboxFacade` serves both services over one state. One decorator checks the API token (#66675) before a handler runs and ends a failed call with its status: through `abort()` on `grpc.aio`, and on Serve, whose context has no `abort()`, by setting the status on the context and raising. - `grpc_facade.add_servicers_to_server`, for `grpc_options.grpc_servicer_functions`, registers the client SDK's two services under their wire names. - `grpc_app.build_app` builds a one-replica deployment of the facade's servicer. `build_app` refuses to build without `RAY_SANDBOX_API_TOKEN`, and the replica refuses to start without the token in its own environment, which can lack what `build_app` saw (as with `serve run` outside the cluster). Serve's proxies listen on every node's address, which sandboxes with network access can reach. - Without a configured `advertise_url`, the facade gives each client `https://` plus the host it dialed (`x-modal-host`) as its command-router URL, which suits a TLS endpoint in front of the proxy. - Docs: a "Serve the facade with Ray Serve" section in `doc/source/core/sandboxes.md`, with the Anyscale service config, and two notes about clients: - Client SDK 1.6+ needs `MODAL_SANDBOX_V2=0`, because 1.6 made a newer sandbox API its default and the facade doesn't serve it. The client SDK tests set it too. - The TLS endpoint in front of the facade must accept HTTP/2 without ALPN, because the SDK's command-router connection offers none. Envoy does; ingress-nginx doesn't. So on Anyscale, the service belongs on a Kubernetes cloud that routes services through an Envoy Gateway. ## Related issues Related to #65839 (the facade) and #66675 (its API token). #66821, stacked on this one, makes the facade fast under bursts of sandboxes. ## Additional information - Not a duplicate: no open PR serves the facade through Ray Serve. I searched open PRs for `grpc_app`, "sandbox facade Serve" and "sandbox gRPC facade". - Tests: - `pytest python/ray/experimental/sandbox/http/tests` on macOS with the Ray 2.58.0 wheel (with Serve and the Modal SDK 1.6.1 installed) and this branch's `ray.experimental.sandbox`: 157 passed, 2 skipped (the two `TEST_SANDBOX=1` integration tests). This includes the unmodified SDK against both the facade's `grpc.aio` server and a local Ray Serve gRPC proxy: sandbox create, exec, a multi-message file-write stream, and a rejected token. - With CI's pins (grpcio 1.75.0, protobuf 5.27.5) and without grpclib, Serve or modal installed: `test_grpc_facade.py`, `test_grpc_app.py` and `test_modal_client.py` gave 70 passed, 9 skipped (the Serve and SDK end-to-end tests). The facade's wire tests no longer need grpclib, so CI now runs them instead of skipping them. - `pre-commit run --files <changed files>` with pre-commit 3.5.0 (every hook that applies, including both ruff hooks, pydoclint and black) and the API parameter coverage check (`ci/ray_ci/doc/cmd_check_api_param_coverage.py --base-ref origin/master --blocking`) pass. - End to end with the stock Modal SDK (1.6.1, no patch), before the facade became a `grpc` servicer (the first revision served it through an adapter in `grpc_app`): this app ran as an Anyscale staging service on a Kubernetes cloud whose edge is Envoy Gateway. - The SDK created sandboxes, ran commands in them (exit code, stdout, stderr, line streaming, secrets, workdir), wrote and read files, reattached, and terminated them. - Uploads and downloads of up to 64 MiB passed, and so did reading a command's output before `wait()` while it stayed silent for 720 s. - A command-router call over TLS without ALPN reached the facade, and calls without the token got UNAUTHENTICATED. - Behind ingress-nginx, the same SDK creates sandboxes, but its command-router calls fail, as the docs now say. - The burst benchmarks in #66821 also ran this app as an Anyscale service, on a 16-node EKS staging cluster behind ingress-nginx, with a one-line ALPN fix applied to the client SDK. - AI assistance (Claude Code) was used to prepare this change. --------- Signed-off-by: xyuzh <[email protected]>
…66786) ## Description `test_image_utils` is flaky in CI because three of its tests pull from the real Docker Hub. The two `busybox` pull tests fail whenever Docker Hub rate-limits the runner (100 anonymous pulls per 6 hours per IP) or the network blips. `test_pull_nonexistent_image` also goes to Docker Hub, but passes either way. This PR adds a `fake_docker_hub` fixture: a small registry on `127.0.0.1` that `RAY_SANDBOX_REGISTRY_MIRROR` points Docker Hub references at. It serves `library/busybox` through each step of a real pull: the bearer-token challenge, a multi-arch index that lists another platform first, the manifest and config, and blobs behind a redirect that rejects the registry token, as presigned object storage does. The tests still cover `busybox:latest` and `docker.io/library/busybox:latest`, and the nonexistent image now fails on the fake's 404. Only the test file changes. The gVisor backend tests still pull real images. ## Related issues Related to #65352. Follows #66675, which fixed the other `test_image_utils` failure in CI. ## Additional information - Not a duplicate: searches of open PRs and issues for `test_image_utils`, `sandbox flaky` and `sandbox docker hub` found nothing. - Tested on macOS with the Ray 2.58 wheel and this branch's sandbox package: `TEST_SANDBOX=1 pytest python/ray/experimental/sandbox/tests/test_image_utils.py` passed (26 tests) on Python 3.10 with pytest 7.4.4, CI's versions, and on Python 3.11 with pytest 8.0.2. With every non-loopback socket blocked, it passed 25 runs out of 25; master's file fails its two `busybox` tests that way. Making `image_utils.py` forward the token on the redirect, take the first index entry, or drop the token makes the pull tests fail. CI's sandbox job covers Linux. - I used Claude Code to help write and test this change. Signed-off-by: xyuzh <[email protected]>
…#66675) ## Description The Ray Sandbox gRPC facade (`ray.experimental.sandbox.http.grpc_facade`) served sandbox create, exec, and file read/write to any client that could reach its port. Unlike the REST app, it never read `RAY_SANDBOX_API_TOKEN`, so even an operator who wanted to lock it down couldn't, and the documented quickstart binds `--host 0.0.0.0`. With this PR: - **The token is required on every RPC.** When `RAY_SANDBOX_API_TOKEN` is set, a call that doesn't present it fails with `UNAUTHENTICATED` before its handler reads the request. - A client presents the token the way the client SDK already sends credentials: as its token secret (`x-modal-token-secret`, from `MODAL_TOKEN_SECRET`), or as `authorization: Bearer <token>`, the REST app's form, which `MODAL_OVERRIDE_HEADERS` can also send. - `TaskGetCommandRouterAccess` hands out the token as the command router's credential. The SDK then sends it as a bearer token on every exec and file call, so an unmodified client only needs `MODAL_TOKEN_SECRET` set. - A bearer-only check wouldn't work with the SDK: its control-plane calls carry the token secret, and its router calls carry only the credential that `TaskGetCommandRouterAccess` returned. - **The check is bound to the servicers, not to one server.** `_TokenGate` wraps the handler table (`__mapping__`) that `grpclib.server.Server` dispatches through. So every server built from `build_servicers` is gated, including RPCs added later, such as ray-project#66359's `TaskSetNetworkAccess`. Without a token the table is returned unchanged. - **The CLI fails closed.** Without a token, `python -m ray.experimental.sandbox.http.grpc_facade` refuses a non-loopback `--host` unless `--allow-unauthenticated` is passed. - Keeping the facade on a private network isn't enough on its own. The facade's sandboxes get open egress by default and can reach any address their node can, including the facade's. So a tokenless facade on a network address would also serve the code running inside them. - Loopback binds stay tokenless, since `--disable-host-loopback` keeps sandboxes off the node's loopback. - **Docs.** The gRPC section now covers: - the token; - the trust model: one token controls every sandbox in the namespace, as with the REST token, with no per-client isolation; - the TLS requirement; - a fix for the stale network bullet: allowlists are refused, not widened. - **REST.** `require_bearer_token` compares bytes, so a non-ASCII `Authorization` header gets a 401 instead of a `TypeError` and a 500. **Behavior change:** a tokenless facade started with a non-loopback `--host`, as the old quickstart did, now exits with an error that names `RAY_SANDBOX_API_TOKEN` and `--allow-unauthenticated`. **This PR also fixes the failing `:ray: core: sandbox tests` job** (for example premerge build 74278 and microcheck build 55110). - `test_image_utils.py::test_seeding_stays_inside_the_tree` linked the fake image's `/tmp` to an absolute path under pytest's `tmp_path`, which is itself under `/tmp` in CI. - From the image's point of view that's a symlink loop. `_resolve_in_root` correctly reports it as `ELOOP`, so nothing was seeded. - The test now gives `tmp` its own tree with a relative link. The product code is unchanged. - The test only passed on macOS because `tmp_path` lives under `/private/var/folders` there. ## Related issues Related to ray-project#65839 (the facade) and ray-project#65352 (sandboxing umbrella). Not a duplicate: no open PR or issue covers facade authentication. I searched open PRs and issues for `grpc_facade`, `RAY_SANDBOX_API_TOKEN`, and sandbox authentication. ## Additional information **Tests run.** Environment: macOS, Python 3.12, the ray 2.58 wheel with this branch's sandbox package overlaid, grpclib 0.4.9. | Command | Result | | --- | --- | | `pytest --import-mode=importlib python/ray/experimental/sandbox/http/tests` | 130 passed, 8 skipped (modal not installed, `TEST_SANDBOX` unset) | | The same, with `RAY_SANDBOX_API_TOKEN=ambient` exported | 130 passed, 8 skipped | | `uv run --with modal==1.5.5 pytest .../http/tests/test_modal_client.py` | 6 passed | | `uv run --with modal==1.5.1 pytest .../http/tests/test_modal_client.py` | 5 passed, 1 skipped (1.5.1 can't send custom headers) | | The new auth tests against `origin/master`'s `grpc_facade.py` | 29 failed, as expected | | `test_image_utils.py::test_seeding_stays_inside_the_tree`, with the default `tmp_path` and with `tmp_path` under `/tmp` | Passed both ways (the old test fails with `tmp_path` under `/tmp`) | | `python -m ray.experimental.sandbox.http.grpc_facade --host 0.0.0.0` without a token | Exit 2, before connecting to the cluster | | Unauthenticated create path replayed against a local Ray cluster | Anonymous and wrong-token `AppGetOrCreate`, `ImageGetOrCreate`, and `SandboxCreate` return `UNAUTHENTICATED` and create no actor. With the token, a `SandboxHost` actor is created and then terminated. | | `pre-commit` (ruff, pydoclint, docstyle, import order), black 22.10.0, API param coverage check | Pass | `test_grpc_facade.py` and `test_modal_client.py` skip in CI because grpclib and modal aren't in the CI image, so the auth tests above ran locally only. AI assistance was used to write this change. Signed-off-by: xyuzh <[email protected]> Co-authored-by: Philipp Moritz <[email protected]>
## Description Lets Ray Serve deploy the Modal-compatible gRPC facade (ray-project#65839), so a Serve application, such as an Anyscale service, exposes the facade from configuration alone. The facade itself becomes a standard `grpc` servicer, which both its own server and Serve's gRPC proxy call: - Each RPC is a method named after it that takes the request and the call's context (as `grpc_context`, the name Serve passes it under) and returns or yields its replies. The vendored service stubs are now grpcio's (`*_pb2_grpc.py`, from the same pinned grpcio-tools), so the facade no longer needs grpclib, and `python -m ray.experimental.sandbox.http.grpc_facade` runs a `grpc.aio` server. - `RaySandboxFacade` serves both services over one state. One decorator checks the API token (ray-project#66675) before a handler runs and ends a failed call with its status: through `abort()` on `grpc.aio`, and on Serve, whose context has no `abort()`, by setting the status on the context and raising. - `grpc_facade.add_servicers_to_server`, for `grpc_options.grpc_servicer_functions`, registers the client SDK's two services under their wire names. - `grpc_app.build_app` builds a one-replica deployment of the facade's servicer. `build_app` refuses to build without `RAY_SANDBOX_API_TOKEN`, and the replica refuses to start without the token in its own environment, which can lack what `build_app` saw (as with `serve run` outside the cluster). Serve's proxies listen on every node's address, which sandboxes with network access can reach. - Without a configured `advertise_url`, the facade gives each client `https://` plus the host it dialed (`x-modal-host`) as its command-router URL, which suits a TLS endpoint in front of the proxy. - Docs: a "Serve the facade with Ray Serve" section in `doc/source/core/sandboxes.md`, with the Anyscale service config, and two notes about clients: - Client SDK 1.6+ needs `MODAL_SANDBOX_V2=0`, because 1.6 made a newer sandbox API its default and the facade doesn't serve it. The client SDK tests set it too. - The TLS endpoint in front of the facade must accept HTTP/2 without ALPN, because the SDK's command-router connection offers none. Envoy does; ingress-nginx doesn't. So on Anyscale, the service belongs on a Kubernetes cloud that routes services through an Envoy Gateway. ## Related issues Related to ray-project#65839 (the facade) and ray-project#66675 (its API token). ray-project#66821, stacked on this one, makes the facade fast under bursts of sandboxes. ## Additional information - Not a duplicate: no open PR serves the facade through Ray Serve. I searched open PRs for `grpc_app`, "sandbox facade Serve" and "sandbox gRPC facade". - Tests: - `pytest python/ray/experimental/sandbox/http/tests` on macOS with the Ray 2.58.0 wheel (with Serve and the Modal SDK 1.6.1 installed) and this branch's `ray.experimental.sandbox`: 157 passed, 2 skipped (the two `TEST_SANDBOX=1` integration tests). This includes the unmodified SDK against both the facade's `grpc.aio` server and a local Ray Serve gRPC proxy: sandbox create, exec, a multi-message file-write stream, and a rejected token. - With CI's pins (grpcio 1.75.0, protobuf 5.27.5) and without grpclib, Serve or modal installed: `test_grpc_facade.py`, `test_grpc_app.py` and `test_modal_client.py` gave 70 passed, 9 skipped (the Serve and SDK end-to-end tests). The facade's wire tests no longer need grpclib, so CI now runs them instead of skipping them. - `pre-commit run --files <changed files>` with pre-commit 3.5.0 (every hook that applies, including both ruff hooks, pydoclint and black) and the API parameter coverage check (`ci/ray_ci/doc/cmd_check_api_param_coverage.py --base-ref origin/master --blocking`) pass. - End to end with the stock Modal SDK (1.6.1, no patch), before the facade became a `grpc` servicer (the first revision served it through an adapter in `grpc_app`): this app ran as an Anyscale staging service on a Kubernetes cloud whose edge is Envoy Gateway. - The SDK created sandboxes, ran commands in them (exit code, stdout, stderr, line streaming, secrets, workdir), wrote and read files, reattached, and terminated them. - Uploads and downloads of up to 64 MiB passed, and so did reading a command's output before `wait()` while it stayed silent for 720 s. - A command-router call over TLS without ALPN reached the facade, and calls without the token got UNAUTHENTICATED. - Behind ingress-nginx, the same SDK creates sandboxes, but its command-router calls fail, as the docs now say. - The burst benchmarks in ray-project#66821 also ran this app as an Anyscale service, on a 16-node EKS staging cluster behind ingress-nginx, with a one-line ALPN fix applied to the client SDK. - AI assistance (Claude Code) was used to prepare this change. --------- Signed-off-by: xyuzh <[email protected]>
…ay-project#66786) ## Description `test_image_utils` is flaky in CI because three of its tests pull from the real Docker Hub. The two `busybox` pull tests fail whenever Docker Hub rate-limits the runner (100 anonymous pulls per 6 hours per IP) or the network blips. `test_pull_nonexistent_image` also goes to Docker Hub, but passes either way. This PR adds a `fake_docker_hub` fixture: a small registry on `127.0.0.1` that `RAY_SANDBOX_REGISTRY_MIRROR` points Docker Hub references at. It serves `library/busybox` through each step of a real pull: the bearer-token challenge, a multi-arch index that lists another platform first, the manifest and config, and blobs behind a redirect that rejects the registry token, as presigned object storage does. The tests still cover `busybox:latest` and `docker.io/library/busybox:latest`, and the nonexistent image now fails on the fake's 404. Only the test file changes. The gVisor backend tests still pull real images. ## Related issues Related to ray-project#65352. Follows ray-project#66675, which fixed the other `test_image_utils` failure in CI. ## Additional information - Not a duplicate: searches of open PRs and issues for `test_image_utils`, `sandbox flaky` and `sandbox docker hub` found nothing. - Tested on macOS with the Ray 2.58 wheel and this branch's sandbox package: `TEST_SANDBOX=1 pytest python/ray/experimental/sandbox/tests/test_image_utils.py` passed (26 tests) on Python 3.10 with pytest 7.4.4, CI's versions, and on Python 3.11 with pytest 8.0.2. With every non-loopback socket blocked, it passed 25 runs out of 25; master's file fails its two `busybox` tests that way. Making `image_utils.py` forward the token on the redirect, take the first index entry, or drop the token makes the pull tests fail. CI's sandbox job covers Linux. - I used Claude Code to help write and test this change. Signed-off-by: xyuzh <[email protected]> Signed-off-by: Pawel Beza <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: 4b9df5c4-6ec3-4e1f-ac3e-54f320ebd8c4
Description
The Ray Sandbox gRPC facade (
ray.experimental.sandbox.http.grpc_facade) served sandbox create, exec, and file read/write to any client that could reach its port. Unlike the REST app, it never readRAY_SANDBOX_API_TOKEN, so even an operator who wanted to lock it down couldn't, and the documented quickstart binds--host 0.0.0.0.With this PR:
RAY_SANDBOX_API_TOKENis set, a call that doesn't present it fails withUNAUTHENTICATEDbefore its handler reads the request.x-modal-token-secret, fromMODAL_TOKEN_SECRET), or asauthorization: Bearer <token>, the REST app's form, whichMODAL_OVERRIDE_HEADERScan also send.TaskGetCommandRouterAccesshands out the token as the command router's credential. The SDK then sends it as a bearer token on every exec and file call, so an unmodified client only needsMODAL_TOKEN_SECRETset.TaskGetCommandRouterAccessreturned._TokenGatewraps the handler table (__mapping__) thatgrpclib.server.Serverdispatches through. So every server built frombuild_servicersis gated, including RPCs added later, such as [core][sandbox] Default network="public" egress to the public internet and enforce allowlists #66359'sTaskSetNetworkAccess. Without a token the table is returned unchanged.python -m ray.experimental.sandbox.http.grpc_facaderefuses a non-loopback--hostunless--allow-unauthenticatedis passed.--disable-host-loopbackkeeps sandboxes off the node's loopback.require_bearer_tokencompares bytes, so a non-ASCIIAuthorizationheader gets a 401 instead of aTypeErrorand a 500.Behavior change: a tokenless facade started with a non-loopback
--host, as the old quickstart did, now exits with an error that namesRAY_SANDBOX_API_TOKENand--allow-unauthenticated.This PR also fixes the failing
:ray: core: sandbox testsjob (for example premerge build 74278 and microcheck build 55110).test_image_utils.py::test_seeding_stays_inside_the_treelinked the fake image's/tmpto an absolute path under pytest'stmp_path, which is itself under/tmpin CI._resolve_in_rootcorrectly reports it asELOOP, so nothing was seeded.tmpits own tree with a relative link. The product code is unchanged.tmp_pathlives under/private/var/foldersthere.Related issues
Related to #65839 (the facade) and #65352 (sandboxing umbrella).
Not a duplicate: no open PR or issue covers facade authentication. I searched open PRs and issues for
grpc_facade,RAY_SANDBOX_API_TOKEN, and sandbox authentication.Additional information
Tests run. Environment: macOS, Python 3.12, the ray 2.58 wheel with this branch's sandbox package overlaid, grpclib 0.4.9.
pytest --import-mode=importlib python/ray/experimental/sandbox/http/testsTEST_SANDBOXunset)RAY_SANDBOX_API_TOKEN=ambientexporteduv run --with modal==1.5.5 pytest .../http/tests/test_modal_client.pyuv run --with modal==1.5.1 pytest .../http/tests/test_modal_client.pyorigin/master'sgrpc_facade.pytest_image_utils.py::test_seeding_stays_inside_the_tree, with the defaulttmp_pathand withtmp_pathunder/tmptmp_pathunder/tmp)python -m ray.experimental.sandbox.http.grpc_facade --host 0.0.0.0without a tokenAppGetOrCreate,ImageGetOrCreate, andSandboxCreatereturnUNAUTHENTICATEDand create no actor. With the token, aSandboxHostactor is created and then terminated.pre-commit(ruff, pydoclint, docstyle, import order), black 22.10.0, API param coverage checktest_grpc_facade.pyandtest_modal_client.pyskip in CI because grpclib and modal aren't in the CI image, so the auth tests above ran locally only.AI assistance was used to write this change.