Skip to content

[Serve][LLM] [Testing in Progress] Enforce API-key auth on the OpenAI-compatible ingress - #66587

Open
khushali9 wants to merge 10 commits into
ray-project:masterfrom
khushali9:serve-llm-ingress-api-key-auth
Open

khushali9 wants to merge 10 commits into
ray-project:masterfrom
khushali9:serve-llm-ingress-api-key-auth

Conversation

@khushali9

Copy link
Copy Markdown

Description

Fixes #66487. VLLM_API_KEY / engine api_key are delivered only to the model-replica process, which the ingress reaches over a DeploymentHandle (RPC) — that process never sits on the HTTP boundary, so it never runs vLLM's HTTP auth. The HTTP boundary is OpenAiIngress, whose FastAPI app installed no auth middleware and referenced VLLM_API_KEY nowhere. Result: a wrong/missing Authorization: Bearer token returned 200 instead of 401. This affects the default (OpenAiIngress) path used by both build_openai_app and build_dp_openai_app.

The RAY_SERVE_LLM_ENABLE_DIRECT_STREAMING path is not affected: it serves vLLM's own FastAPI app (build_app), which already installs vLLM's AuthenticationMiddleware when VLLM_API_KEY is set in the replica. No change needed there.

What changed

  • New AuthMiddleware (raw-ASGI, mirroring SetRequestIdMiddleware) + add_auth_middleware helper in core/ingress/middleware.py. Validates Authorization: Bearer with a constant-time compare, returns a 401 (OpenAI-style body + WWW-Authenticate: Bearer), exempts CORS OPTIONS preflight and configurable paths, and on success sets request.state.user_id (filling the existing get_user_id hook consumed by metrics).
  • Wired into OpenAiIngress.init() — added after the metrics middleware (so it runs before it and populates user_id) and before SetRequestIdMiddleware (which stays outermost so rejected requests keep a request id).
  • Key resolution: explicit api_key field on LLMServingArgs / DPOpenAiServingArgs (build-time) takes precedence; otherwise the VLLM_API_KEY env var, read inside the ingress replica at middleware instantiation (so it reflects the ingress process, matching vLLM semantics).
  • Backward compatible: when neither is set, the endpoints stay open (enforcement is opt-in).

Configuration

  • vLLM parity: set VLLM_API_KEY at the application/container level runtime_env (not inside a per-model LLMConfig.runtime_env, which only reaches model replicas).
  • Or set the explicit api_key in the builder args (LLMServingArgs / DPOpenAiServingArgs).

Testing

  • python/ray/llm/tests/serve/cpu/deployments/routers/test_auth_middleware.py — 19 tests (missing/wrong/empty/wrong-scheme creds → 401; valid key → 200 + user tagging; env fallback, explicit-key precedence, unset-env no-op; init() installs/forwards/orders the middleware; OPTIONS and exempt-path bypass). Result: 19 passed.
  • Lint: ruff, black, pydoclint, check-import-order — clean.
  • End-to-end (GPU): deploy with VLLM_API_KEY=; wrong key → 401, correct key → 200, no key configured → Working on this

Not a duplicate

No open PR addresses #66487 (searched open PRs for the serve-LLM auth area); the issue is unassigned and maintainer-triaged serve/security/llm.

AI assistance was used to analyze and implement this change; I have reviewed every changed line and run the tests above.

🤖 Generated with Claude Opus 4.8

@khushali9
khushali9 requested a review from a team as a code owner September 30, 2026 00:19

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces bearer-token authentication to the OpenAI-compatible ingress by adding an api_key configuration parameter and implementing AuthMiddleware to enforce token checks while bypassing CORS preflight and exempt paths. Feedback suggests updating the middleware ordering tests to assert that AuthMiddleware runs inside CORSMiddleware, ensuring CORS headers are correctly applied to unauthorized responses.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue llm community-contribution Contributed by the community labels Sep 30, 2026

@eicherseiji eicherseiji left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this! A few follow-ups:

  • Please support the configured api_key consistently across all OpenAI builder entrypoints—standard, DP, PD, and dev—including direct-streaming mode. The standard and DP direct-streaming branches currently return before the key is wired, so the explicit value is silently ignored. Dev accepts it through the shared LLMServingArgs but does not forward it, while PD does not expose it at all. Authentication should not depend on which builder is used.
  • Please run auth inside the CORS and HTTP metrics middleware. With the current LIFO ordering, an auth rejection bypasses both, so cross-origin 401 responses lack CORS headers and rejected requests are not recorded by the HTTP metrics middleware. Metrics reads user_id after the inner app returns, so authenticated-user tagging should still work with auth inside it.

Please follow up with me on Ray Slack once these are addressed so we can get this landed.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@khushali9

khushali9 commented Oct 1, 2026 •

Copy link
Copy Markdown
Author

Thanks for working on this! A few follow-ups:

  • Please support the configured api_key consistently across all OpenAI builder entrypoints—standard, DP, PD, and dev—including direct-streaming mode. The standard and DP direct-streaming branches currently return before the key is wired, so the explicit value is silently ignored. Dev accepts it through the shared LLMServingArgs but does not forward it, while PD does not expose it at all. Authentication should not depend on which builder is used.
  • Please run auth inside the CORS and HTTP metrics middleware. With the current LIFO ordering, an auth rejection bypasses both, so cross-origin 401 responses lack CORS headers and rejected requests are not recorded by the HTTP metrics middleware. Metrics reads user_id after the inner app returns, so authenticated-user tagging should still work with auth inside it.

Please follow up with me on Ray Slack once these are addressed so we can get this landed.

@eicherseiji I have addressed your feedback, but i am not able to access or join Ray Slack, the link on Ray' readme seems to take me to https://www.ray.io/join-slack and it later asks for anyscale mail account. It even has gmail as option but that is not working for me to sign in.

@khushali9
khushali9 requested a review from eicherseiji October 1, 2026 21:44
@khushali9

Copy link
Copy Markdown
Author

@eicherseiji Can you please review this again, and I tried to join slack but the process seem very involved and after filling forms also it is not letting me sign and asking for anyscale domain email, which I dont have.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@kouroshHakha

Copy link
Copy Markdown
Contributor

Thanks for the report and @khushali9 for offering to pick this up. Some context on direction first, then concrete tasks.

Direction. We're making direct streaming (RAY_SERVE_LLM_ENABLE_DIRECT_STREAMING=1, LLMRouter + HAProxy) the primary serving path for Ray Serve LLM. The OpenAiIngress path won't get new features. We also don't plan to build API-key management into Ray Serve LLM. Static keys set at engine startup can't be rotated without a redeploy and have no notion of separate clients. Production deployments should do auth at the gateway in front of Ray (e.g. a Kubernetes Gateway), or at the platform layer. What we do want: (a) the engine-level key behaves correctly and predictably on the direct streaming path, (b) nothing fails open silently, and (c) a documented, copy-pasteable production recipe.

Background. With direct streaming, the LLMServer replica serves vLLM's own ASGI app (VLLMEngine.build_asgi_app() → vllm.entrypoints.openai.api_server.build_app). build_app installs vLLM's AuthenticationMiddleware whenever args.api_key or VLLM_API_KEY is set. So on this path the key should already be enforced, unlike the OpenAiIngress path you hit.

Tasks

1. Confirm and lock in the current behavior with tests (direct streaming).
Add tests that bring up a direct-streaming app with engine_kwargs={"api_key": ["k1"]}, and separately with VLLM_API_KEY in the LLMServer runtime_env. Check:

  • /v1/chat/completions, /v1/completions and /v1/models return 401 without a key or with a wrong one, and 200 with Authorization: Bearer k1.
  • The /v1/models/{model} route that Ray adds (_add_openai_models_retrieve_route in llm_server.py) is also protected.
  • A single-string api_key is either normalized to a list or rejected with a clear error. vLLM's FrontendArgs.api_key is list[str] | None.

2. Fix the middleware order so auth runs before LoRA resolution.
In llm_server.py, _add_middleware_to_built_app calls app.add_middleware(_ResolveLoRAMiddleware, ...) on the already-built vLLM app. Starlette's add_middleware inserts at index 0, so the LoRA middleware becomes the outermost layer and runs before vLLM's AuthenticationMiddleware. Unauthenticated requests could then trigger LoRA resolution or download. Make the LoRA middleware run inside the auth check, and add a test that a request without a key naming a LoRA model gets 401 without calling _maybe_resolve_lora_from_multiplex.

3. Fail loudly on the OpenAiIngress path instead of silently ignoring the key.
When direct streaming is off and api_key is in engine_kwargs (or VLLM_API_KEY is set in the LLM deployment's env), build_openai_app should raise or log a prominent warning. Say the key isn't enforced on this path and point to the direct streaming path and the docs below. Please don't port the auth middleware into OpenAiIngress.

4. Document it.
Add a "Securing endpoints" section to the direct streaming guide (doc/source/serve/llm/user-guides/direct-streaming.md) covering:

  • How to set the key (list form, or VLLM_API_KEY in runtime_env) and that it only works with direct streaming.
  • What it covers: vLLM guards only /v1, /v2, /inference and /cohere. /invocations, /tokenize, /health and similar stay open. Link vLLM's security doc.
  • That the key is checked on the replica after HAProxy has asked LLMRouter to pick a replica, so rejected requests still cost a routing call. With RAY_SERVE_INGRESS_REQUEST_ROUTER_FORWARD_BODY=1 they also cost body buffering and body-aware scoring.
  • That rotating a key means a redeploy.
  • The recommendation to enforce auth at a gateway in front of Ray for production.

5. Add a KubeRay production recipe.
Add a sample with a RayService running direct streaming (RAY_SERVE_ENABLE_HA_PROXY=1, RAY_SERVE_LLM_ENABLE_DIRECT_STREAMING=1) behind a Gateway API Gateway with API-key auth. Envoy Gateway's SecurityPolicy.apiKeyAuth backed by a Kubernetes Secret is a good default. RayService already supports attaching to an existing Gateway via upgradeStrategy.clusterUpgradeOptions.gatewayRef, so the sample can also show zero-downtime upgrades. Include:

  • A rotation walkthrough: add a new client key to the Secret, move clients over, remove the old key, all without touching the RayService.
  • A test that the OpenAI SDK's Authorization: Bearer <key> header works with the policy's extractFrom config.

Out of scope

  • A Ray-native API key, auth setting or rotation mechanism.
  • Auth inside Serve's HAProxy config.
  • Changes to Ray token auth (RAY_AUTH_MODE), which protects Ray's internal and dashboard traffic, not the public Serve HTTP port.

Suggested PR split: 1+2 (tests + ordering fix), 3, 4, 5. Happy to review. CC @eicherseiji

@khushali9

Copy link
Copy Markdown
Author

Thanks a lot @kouroshHakha for guidance , I will take up this work soon.

@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 30, 2026
@khushali9

Copy link
Copy Markdown
Author

Team, I have been bit busy, someone can take this issue, if not I will take once I have bandwidth.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit a9b5777. Configure here.

)
engine_kwargs = dict(llm_config.engine_kwargs)
engine_kwargs["api_key"] = [api_key]
return llm_config.model_copy(update={"engine_kwargs": engine_kwargs})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale engine config drops API key

High Severity

_apply_ingress_api_key copies the LLMConfig with an updated engine_kwargs but does not invalidate the cached engine config. get_engine_config snapshots kwargs into frontend_kwargs once, and _prepare_engine_config builds FrontendArgs from that snapshot. A copied stale cache leaves api_key out of FrontendArgs, so vLLM never installs auth on the direct-streaming ingress.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit a9b5777. Configure here.

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Nov 5, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community llm serve Ray Serve Related Issue unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Serve] VLLM_API_KEY / engine api_key argument is not enforced by Ray Serve LLM OpenAI endpoints

3 participants