Repository navigation
[Core/Auth] Require the auth token on Ray's Prometheus metrics endpoints - #67128
Conversation
With token auth on, the node, dashboard and autoscaler metrics endpoints reject scrapes without the token, and Ray's generated Prometheus configs read it from RAY_AUTH_TOKEN_PATH or ~/.ray/auth_token. Signed-off-by: Chi-Sheng Liu <[email protected]>
…ile, malformed cookies Signed-off-by: Chi-Sheng Liu <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces token authentication for Ray's Prometheus metrics endpoints, wrapping WSGI applications with token validation and updating the autoscaler, dashboard, and prometheus exporter to enforce authentication when enabled. Additionally, various tests have been updated to pass the necessary authentication headers. The review feedback highlights opportunities to improve test robustness and portability, specifically by catching broader exceptions during Prometheus startup checks to prevent abrupt test failures, and replacing non-portable shell kill commands with Python's built-in os.kill for cross-platform compatibility.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit d4179a7. Configure here.
…s on any request error launch-prometheus reads scrape targets through the /tmp/ray discovery-file symlink, and Prometheus misses rewrites of the session file behind it until its 5-minute refresh. The test now starts Prometheus only once the file lists all four targets. Signed-off-by: Chi-Sheng Liu <[email protected]>
…en launch-prometheus token checks Signed-off-by: Chi-Sheng Liu <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces token authentication for Ray's Prometheus metrics endpoints, ensuring that metrics scraping requires a valid token when token authentication is enabled. It wraps WSGI applications with token authentication middleware, updates the autoscaler and dashboard to use the new secure metrics server, and securely writes Prometheus configuration files. Additionally, the C++ token loader was updated to read the first non-blank line of token files. The review feedback highlights critical issues that need to be addressed, including a missing import of request_with_auth_token in conftest.py which will cause a NameError, and several Windows compatibility issues such as the use of os.O_NOFOLLOW and POSIX-specific file permissions/symlinks in tests.
Signed-off-by: Chi-Sheng Liu <[email protected]>
rueian
left a comment
There was a problem hiding this comment.
The implementation looks good to me, so approved.
I think someone might wants to disable authentication for the metrics endpoint. It is probably worth to introduce a flag/env to allow accesses to the metrics endpoint without a token.
|
Created another issue to track this #67251 |
…7119-metrics Signed-off-by: Chi-Sheng Liu <[email protected]> # Conflicts: # python/ray/_private/authentication/http_token_authentication.py
…s without the auth token (#67264) ## Description With token auth on, Ray's metrics endpoints require the token since #67128, and the only way to scrape them without one was to turn auth off for the whole cluster. Some scrapers can't send a bearer token, and some users protect the metrics port at the network layer instead. Setting `RAY_AUTH_SKIP_METRICS=1` on every node now serves Ray's metrics endpoints (each node's metrics port, the dashboard head and both autoscaler monitors) without the token, while `RAY_AUTH_MODE=token` still protects everything else. ```text metrics request (get_token_auth_wsgi_app) auth off -> serve metrics (unchanged) RAY_AUTH_SKIP_METRICS=1 -> serve metrics without a token otherwise -> token check from #67128 (401 / 403 / serve) ``` All three metrics servers already go through `get_token_auth_wsgi_app`, so the skip is checked there once. The env var is read with `env_bool`, so `true` works as well as `1`. Each Ray process reads it from its own environment, so it must be set wherever a node starts, for example in `ray up` start commands or KubeRay pod specs. When the skip is also set in the shell that runs `ray metrics launch-prometheus`, it writes no `authorization` block and runs Prometheus with the bundled config unchanged. Its warning for when it finds no token now says that every Ray target returns 401 unless the cluster's nodes set `RAY_AUTH_SKIP_METRICS=1`, since the launcher can't see the nodes' setting. With auth off, the env var changes nothing. ## Related issues Closes #67251 ## Additional information The opt-out is off unless the env var is set, so clusters that don't set it behave exactly as after #67128. --------- Signed-off-by: Chi-Sheng Liu <[email protected]>
…ds, and require one for ray start --head (#67258) ## Description Once token auth is the default, every head start needs a token. Only entry points that start a throwaway cluster on this machine create one; `ray start --head` fails instead, because a token made there would not reach the cluster's worker nodes. | Entry point | Missing token | |---|---| | `ray.init()` starting a new cluster | Creates it | | `ray.cluster_utils.Cluster()`, `AutoscalingCluster` | Creates it before the head starts | | `Cluster(enable_token_auth=False)`, `AutoscalingCluster(enable_token_auth=False)` | Not needed: auth is off | | C++ / Java driver that starts its own cluster, with `RAY_AUTH_MODE=token` | Creates it before its `ray start --head` | | `ray get-auth-token --generate` | Creates it | | `ray start --head` | Fails before starting any process | | `ray start --address`, `ray.init(address=...)` | Never creates it | Every creator goes through one function in the C++ token loader, which already owns the token sources and their precedence: ```text AuthenticationTokenLoader::CreateTokenIfMissing() TryLoadToken(ignore_auth_mode=true) # any source has a token -> return mkdir ~/.ray (0700; a failed chmod only warns) write 32 RAND_bytes, hex-encoded, to ~/.ray/auth_token (0600) callers Python create_token_if_missing() # ray.init(), Cluster, AutoscalingCluster, get-auth-token --generate C++ process_helper.cc # driver that starts its own cluster Java nativeCreateTokenIfMissingForOwnCluster # library now loads before startRayHead ``` It replaces the Python `generate_and_save_token` and keeps its file format and mode. It never overwrites a file that holds a token, using the loader's first-non-blank-line rule from #67128. Starting several creators at the same moment in a fresh HOME is not supported, so there is no locking. `Cluster()` and `AutoscalingCluster` take a new argument, `enable_token_auth`, default `True`. It decides the cluster's mode whatever `RAY_AUTH_MODE` the test process had: ```text start head save RAY_AUTH_MODE; set it to token | disabled in this process reset RayConfig and the token cache token mode -> CreateTokenIfMissing() shutdown(), or a failed constructor / head add_node() / start() restore the saved RAY_AUTH_MODE (or unset it) ``` Because the test process holds the mode, its nodes, its own `ray.init(address=cluster.address)` and the subprocess drivers it starts all agree, so none is rejected for a mode mismatch (#67052). A `token` that an earlier `ray.init()` left in `RAY_AUTH_MODE` no longer matters. Tests that need auth off pass `enable_token_auth=False`, such as the `setup_cluster_without_token_auth` fixture and `test_kill_raylet_on_auth_disabled_cluster_with_token_file`. `test_autoscaler_warn_infeasible`'s driver now inherits the test process's environment, so it runs in the cluster's mode. - **Before:** `Cluster()` with token auth on and no token built `Node(head=True)`, its GCS crashed on `RAY_CHECK(has_token || ignore_auth_mode)`, and the user saw `Timed out waiting for file .../gcs_server_port_...`. `ray start --head` with no token raised `AuthenticationError`, with fix text telling the reader to copy the token from the head. **After:** `Cluster()` writes `~/.ray/auth_token` and starts in token mode. `ray start --head` with no token stops before starting anything: ```text Error: Token authentication is enabled but no authentication token was found. Run `ray get-auth-token --generate` to create one, then put that token on every node of the cluster before starting it. ``` ## Related issues Closes #67049 ## Additional information `Cluster()` and `AutoscalingCluster` change their default: they now run with token auth on and write `~/.ray/auth_token` in HOME when no token exists, even while `AUTH_MODE` defaults to `disabled`. A test that builds one of them and starts a driver or `ray start` subprocess with an environment not copied from `os.environ` now fails against the token-mode cluster; pass `enable_token_auth=False` or copy the environment. Reverting this PR restores the old behavior; the token files it leaves in HOME are what a bare `ray.init()` already writes. Other changes while `AUTH_MODE` defaults to `disabled`: - `Cluster()` and `AutoscalingCluster` raise a `RuntimeError` when `_system_config` sets an `AUTH_MODE` other than the mode `enable_token_auth` picks, instead of a GCS timeout or `InvalidAuthToken` later. - With `RAY_AUTH_MODE=token` and no token, `ray start --head` fails with the CLI error above instead of `AuthenticationError`. - `ray get-auth-token --generate` reports a failed write as an error naming the path instead of a traceback; the Java driver throws a `RayException`. - The Java driver loads its native library before it starts the head. - A C++ / Java driver with `RAY_AUTH_MODE` unset still runs with auth off; #67055 makes token the default. `//cpp:metric_example` runs with `RAY_AUTH_MODE=token` and no token, pointing HOME at `TEST_TMPDIR` because Bazel's test runner leaves HOME unset. `java/test.sh` runs `RayDemo` with an empty HOME and checks the token file is non-empty. Not in this change: `ray up` doesn't call the new creator yet; that comes with shipping the token in #67050. --------- Signed-off-by: Chi-Sheng Liu <[email protected]>
…ds, and require one for ray start --head (ray-project#67258) ## Description Once token auth is the default, every head start needs a token. Only entry points that start a throwaway cluster on this machine create one; `ray start --head` fails instead, because a token made there would not reach the cluster's worker nodes. | Entry point | Missing token | |---|---| | `ray.init()` starting a new cluster | Creates it | | `ray.cluster_utils.Cluster()`, `AutoscalingCluster` | Creates it before the head starts | | `Cluster(enable_token_auth=False)`, `AutoscalingCluster(enable_token_auth=False)` | Not needed: auth is off | | C++ / Java driver that starts its own cluster, with `RAY_AUTH_MODE=token` | Creates it before its `ray start --head` | | `ray get-auth-token --generate` | Creates it | | `ray start --head` | Fails before starting any process | | `ray start --address`, `ray.init(address=...)` | Never creates it | Every creator goes through one function in the C++ token loader, which already owns the token sources and their precedence: ```text AuthenticationTokenLoader::CreateTokenIfMissing() TryLoadToken(ignore_auth_mode=true) # any source has a token -> return mkdir ~/.ray (0700; a failed chmod only warns) write 32 RAND_bytes, hex-encoded, to ~/.ray/auth_token (0600) callers Python create_token_if_missing() # ray.init(), Cluster, AutoscalingCluster, get-auth-token --generate C++ process_helper.cc # driver that starts its own cluster Java nativeCreateTokenIfMissingForOwnCluster # library now loads before startRayHead ``` It replaces the Python `generate_and_save_token` and keeps its file format and mode. It never overwrites a file that holds a token, using the loader's first-non-blank-line rule from ray-project#67128. Starting several creators at the same moment in a fresh HOME is not supported, so there is no locking. `Cluster()` and `AutoscalingCluster` take a new argument, `enable_token_auth`, default `True`. It decides the cluster's mode whatever `RAY_AUTH_MODE` the test process had: ```text start head save RAY_AUTH_MODE; set it to token | disabled in this process reset RayConfig and the token cache token mode -> CreateTokenIfMissing() shutdown(), or a failed constructor / head add_node() / start() restore the saved RAY_AUTH_MODE (or unset it) ``` Because the test process holds the mode, its nodes, its own `ray.init(address=cluster.address)` and the subprocess drivers it starts all agree, so none is rejected for a mode mismatch (ray-project#67052). A `token` that an earlier `ray.init()` left in `RAY_AUTH_MODE` no longer matters. Tests that need auth off pass `enable_token_auth=False`, such as the `setup_cluster_without_token_auth` fixture and `test_kill_raylet_on_auth_disabled_cluster_with_token_file`. `test_autoscaler_warn_infeasible`'s driver now inherits the test process's environment, so it runs in the cluster's mode. - **Before:** `Cluster()` with token auth on and no token built `Node(head=True)`, its GCS crashed on `RAY_CHECK(has_token || ignore_auth_mode)`, and the user saw `Timed out waiting for file .../gcs_server_port_...`. `ray start --head` with no token raised `AuthenticationError`, with fix text telling the reader to copy the token from the head. **After:** `Cluster()` writes `~/.ray/auth_token` and starts in token mode. `ray start --head` with no token stops before starting anything: ```text Error: Token authentication is enabled but no authentication token was found. Run `ray get-auth-token --generate` to create one, then put that token on every node of the cluster before starting it. ``` ## Related issues Closes ray-project#67049 ## Additional information `Cluster()` and `AutoscalingCluster` change their default: they now run with token auth on and write `~/.ray/auth_token` in HOME when no token exists, even while `AUTH_MODE` defaults to `disabled`. A test that builds one of them and starts a driver or `ray start` subprocess with an environment not copied from `os.environ` now fails against the token-mode cluster; pass `enable_token_auth=False` or copy the environment. Reverting this PR restores the old behavior; the token files it leaves in HOME are what a bare `ray.init()` already writes. Other changes while `AUTH_MODE` defaults to `disabled`: - `Cluster()` and `AutoscalingCluster` raise a `RuntimeError` when `_system_config` sets an `AUTH_MODE` other than the mode `enable_token_auth` picks, instead of a GCS timeout or `InvalidAuthToken` later. - With `RAY_AUTH_MODE=token` and no token, `ray start --head` fails with the CLI error above instead of `AuthenticationError`. - `ray get-auth-token --generate` reports a failed write as an error naming the path instead of a traceback; the Java driver throws a `RayException`. - The Java driver loads its native library before it starts the head. - A C++ / Java driver with `RAY_AUTH_MODE` unset still runs with auth off; ray-project#67055 makes token the default. `//cpp:metric_example` runs with `RAY_AUTH_MODE=token` and no token, pointing HOME at `TEST_TMPDIR` because Bazel's test runner leaves HOME unset. `java/test.sh` runs `RayDemo` with an empty HOME and checks the token file is non-empty. Not in this change: `ray up` doesn't call the new creator yet; that comes with shipping the token in ray-project#67050. --------- Signed-off-by: Chi-Sheng Liu <[email protected]>
…67418) ## Description Ray 2.61 turns token auth on by default, and since #67128 every Ray metrics endpoint requires the token. Serve's HAProxy ingress was left out. HAProxy runs two pages of its own: a Prometheus metrics page on port 9101 and a stats page on port 8404. HAProxy is a separate program and knows nothing about Ray's token, so both pages answer anyone who can reach the node. #67211 reports the metrics page. The stats page shows the same backend and server names and the same request and error counts, so this PR covers both. The fix takes HAProxy off those ports and puts Ray's own token check in front of it. When token auth is on and `RAY_AUTH_SKIP_METRICS` is unset: - HAProxy serves the metrics page and the stats page only on a unix socket with mode 600, which only the Ray user can open. Nothing listens on port 8404. - `HAProxyManager`, which already starts and manages HAProxy on each node, listens on port 9101 instead. Every request goes through `get_token_auth_wsgi_app`, the same check #67128 put on the node, dashboard head and autoscaler metrics servers. A missing token gets 401, a wrong one gets 403, and a request with the right token is passed to HAProxy over the socket and gets HAProxy's answer back. ```text before: Prometheus -> :9101 -> HAProxy (no check) browser -> :8404 -> HAProxy (no check) after: Prometheus -> :9101 -> HAProxyManager token check -> 0600 socket -> HAProxy :8404 -> nothing listening ``` With token auth off, or with `RAY_AUTH_SKIP_METRICS=1`, nothing changes. HAProxy serves both pages directly, and the rendered HAProxy config is byte-for-byte the same as on master. Why not have HAProxy check the token itself, the other option in #67211? It can't cover every mode. In Kubernetes token mode, Ray doesn't compare against a fixed token: it asks the Kubernetes API (TokenReview and SubjectAccessReview), and HAProxy can't make those calls. For a fixed token, HAProxy would have to get the token from its environment, which #67047 rules out, or read the token file on its own terms, which differ from Ray's. HAProxy keeps trailing spaces, skips a line that starts with `#` and accepts every line in the file, where Ray takes only the first non-blank line, trimmed. Reusing Ray's check avoids all of that, and the HAProxy pages follow any later change to the auth rules. A few smaller pieces. `start_metrics_http_server` now calls a new `start_metrics_wsgi_server`, which serves any WSGI app behind the same check, so existing callers don't change. With `SERVE_SOCKET_REUSE_PORT_ENABLED=1`, co-located `EveryNode` proxies share the metrics port, so `HAProxyManager` passes `reuse_port` and the server sets `SO_REUSEPORT` the way HAProxy's own listeners do. It sets the option in `server_bind()` because socketserver's `allow_reuse_port` only exists from Python 3.11. The socket path is per node, like the admin socket (`RAY_SERVE_HAPROXY_EXPORTER_SOCKET_PATH`, default `/tmp/haproxy-serve/<node_id>/exporter.sock`). A request is retried once if a reload resets its connection to the old HAProxy worker. If HAProxy is down, the answer is 503. ## Related issues Closes #67211 ## Additional information What users will notice with token auth on: whoever scrapes `:9101/metrics` must send the token, as for Ray's other metrics endpoints since #67128. The stats page moves from `:8404/stats` to `:9101/stats`, also behind the token. Nothing in Ray reads port 8404 outside tests. `RAY_AUTH_SKIP_METRICS=1` keeps both pages open, and reverting this PR brings back the old listeners with no state to migrate. Tests added: - `test_haproxy.py::test_haproxy_metrics_and_stats_require_token`: 401 and 403, 200 for each token source, `/stats;csv` through `:9101`, and nothing answering on `:8404`. - `test_haproxy.py::test_haproxy_metrics_and_stats_open_without_token`: both pages open without a token, once with `RAY_AUTH_SKIP_METRICS=1` and once with auth disabled. - `test_haproxy.py::test_haproxy_metrics_token_auth_with_colocated_reuse_port_proxies`: two nodes on one machine with `EveryNode` proxies, token auth and `SERVE_SOCKET_REUSE_PORT_ENABLED=1`. Both proxies come up healthy, and `/metrics` answers 401 without the token and 200 with it. - `test_haproxy_api.py::test_metrics_auth_required_moves_exporter_to_unix_socket`: against a real HAProxy, the config binds only the socket, the socket's mode is 0600, both ports are closed and `/metrics` and `/stats;csv` are forwarded. It then reloads HAProxy, checks that a new process took over and that both pages still answer, and gets 503 once HAProxy stops. It runs with `enable_hap_optimization` on (the `-x` socket handoff) and off (plain `-sf`). - `test_haproxy_api.py::test_exporter_proxy_app_retries_after_dropped_connection`: the retry. - `test_haproxy.py::test_haproxy_metrics` now sends the token. I ran both HAProxy test files on Linux in a container: the Ray nightly image at `fb22a8a266` with this PR's files copied over it (the nightly's 15 commits past this branch's base touch none of them), and HAProxy 2.8.25 from `ray-haproxy`. `test_haproxy.py` passed 37 of 37 and `test_haproxy_api.py` passed 60 of 60, each file in one pytest session. With the `reuse_port` change reverted, the co-located test fails with `OSError: [Errno 98] Address already in use` and the second proxy is marked unhealthy. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: harshit-anyscale <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>

Description
With token auth on, Ray's Prometheus metrics endpoints served metrics to anyone who could reach them: job, actor and deployment names, node IPs and resource use. This PR puts the dashboard's token check on Ray's own metrics endpoints (each node's metrics port, the dashboard head and the autoscaler) and makes Ray's own Prometheus send the token. The HAProxy exporter that Serve's HAProxy ingress serves on its own port is not covered; that's #67211.
The node exporter wraps its WSGI app with the new
get_token_auth_wsgi_app. The dashboard head and both autoscaler monitors switch fromprometheus_client.start_http_servertostart_metrics_http_server, which serves the same registry with the same address-family choice plus the token check.With auth on,
ray metrics launch-prometheusadds anauthorizationblock to therayscrape job in the config it writes,./prometheus-<version>.linux-amd64/ray_prometheus.yml:Ray creates that config fresh with mode 0600 (
O_CREAT|O_EXCL|O_NOFOLLOW, after deleting any old file at that path).RAY_AUTH_TOKENtakes precedence over the token file, so when it is set, the config holds the token inline. Otherwise the block points at the token file, andlaunch-prometheusexits before downloading anything if that file is missing, unreadable, empty, or holds more than one non-blank line, since Prometheus sends the whole file. Ray's C++ token loader (AuthenticationTokenLoader::ReadTokenFromFile) now reads the first non-blank line of a token file instead of the first line, so blank lines around the token work everywhere. If writing the config fails,launch-prometheuslogs the error and exits 1 instead of printing a traceback. WhenRAY_AUTH_MODEis unset andlaunch-prometheusfinds no token, it warns that every Ray target returns 401 if the cluster runs token auth. With auth off, the config is unchanged. The dashboard'sprometheus.ymlin the session folder is a template for users who run their own Prometheus. It gets noauthorizationblock, so those users add it themselves.launch-prometheusdecides whether auth is on the wayray startdoes (maybe_enable_token_auth_if_token_available), so local clusters that have token auth on by default are scraped with the token.Tests that scrape metrics endpoints directly now send the token:
fetch_raw_prometheus, the Serve metrics tests and conftest,test_tls_auth.py, and the vLLM batch release test.fetch_raw_prometheusalso raisesHTTPErroron a 401 or 403, so a token mismatch shows up as an auth error instead of an empty scrape.Evidence from running
ray metrics launch-prometheusagainst a two-node cluster with token auth on and the endpoints already requiring the token:authorizationblock (a manual run with the earlier launcher), the four Ray targets (two nodes, autoscaler, dashboard) never all come up in Prometheus's/api/v1/targets.test_launch_prometheus_scrapes_token_auth_cluster, with the token from a file and fromRAY_AUTH_TOKEN), all four targets reporthealth: up.Related issues
Closes #67119
Additional information
This changes behavior for clusters that already run with token auth on, including local clusters, which have had it on by default since 2.59. Any Prometheus that scrapes their metrics endpoints without the token starts getting 401s once this merges, and has to add the
authorizationblock above. Clusters withRAY_AUTH_MODE=disabledsee no change. Reverting the PR restores open endpoints, with no data or state to migrate.