Skip to content

feat(ai-gateway): add virtual-key auth via python control plane - #31223

Open
ghost wants to merge 45 commits into
mainfrom
litellm_rust_gateway_auth
Open

ghost wants to merge 45 commits into
mainfrom
litellm_rust_gateway_auth

Conversation

@ghost

@ghost ghost commented Jun 24, 2026

Copy link
Copy Markdown

Relevant issues

v0 of virtual-key auth on the Rust ai-gateway. Today the gateway only checks the master key; this adds per-key auth by delegating to the Python control plane's existing user_api_key_auth (key lookup, expiry, budget, rate-limit, route checks) — Rust holds no secrets and never touches the DB. Same control-plane/data-plane pattern as the logging endpoint in #31134.

Pre-Submission checklist

  • Tests added — Rust (extractor, cache eviction/TTL, JSON deser) + Python (data-plane gate, verify_key)
  • Rust: cargo test -p litellm-ai-gateway --features server → 22 passed, 1 ignored; clippy -D warnings + fmt clean
  • Python: pytest tests/test_litellm/proxy/auth/test_internal_auth_endpoints.py → 9 passed

Type

🆕 New Feature

Changes

Python control plane — one gated endpoint:

  • POST /internal/v1/auth/verify runs the real user_api_key_auth and returns the resolved UserAPIKeyAuth JSON (or 401).
  • Gated by require_data_plane_key: constant-time check of X-LiteLLM-Data-Plane-Key against LITELLM_DATA_PLANE_KEY — a dedicated secret, not the master key (least privilege). 500 if unset (fail closed), 401 if missing/wrong.
  • Unexpected errors (e.g. DB outage) surface as 500 rather than masquerading as "invalid key"; the data plane still fails closed (rejects any non-200).

Rust data plane (ai-gateway/src/auth/), designed to swap to native later without touching routes:

  • client/mod.rs — KeyAuthenticator trait (the swap seam). v0 = client/python.rs (PythonAuthClient, pooled rustls reqwest, bounded timeouts). Later = a native impl, drop-in.
  • user_api_key.rs — UserApiKeyAuth struct (mirrors Python) + the axum FromRequestParts extractor = the route "decorator". Flow: Bearer → master key short-circuits to admin (constant-time, no Python call) → else sha256(key) → cache hit → miss verifies via the trait and caches.
  • cache.rs — KeyCache: bounded ≤200 entries (FIFO evict) + TTL (60s, LITELLM_AUTH_CACHE_TTL_SECS), keyed by sha256 so plaintext keys never sit in memory.
  • Wired into AppState (authenticator: Arc<dyn KeyAuthenticator>, key_cache); main.rs builds it from LITELLM_DATA_PLANE_KEY + LITELLM_AUTH_VERIFY_URL. The realtime WS route now uses auth: UserApiKeyAuth (auth runs on the upgrade, before the socket).

Fail-closed throughout; raw keys never logged (only sha256/alias). All auth lives in litellm-ai-gateway (host) behind the server feature — litellm-core stays pure and the python-bridge cdylib is unaffected.

@CLAassistant

CLAassistant commented Jun 24, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.


Ishaan Jaff seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@codecov

codecov Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.55172% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...oxy/rust_control_plane_endpoints/auth_endpoints.py 95.74% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR completes the v0 virtual-key auth for the Rust ai-gateway by wiring the Python control plane's budget reservation into the Rust session lifecycle, closing the gap where realtime sessions previously bypassed optimistic budget tracking.

  • Auth flow: The /v1/rust_control_plane/authentication endpoint now returns budget_reservation (a field excluded from normal model_dump via exclude=True) alongside the resolved identity; Rust stores it in RequestMetadata and the realtime route now bypasses the auth cache entirely so every session gets a fresh reservation.
  • Budget reconciliation: RequestMetadata.user_api_key_budget_reservation flows through StandardLoggingMetadata into the /v1/rust_control_plane/logs replay, where it is placed in litellm_params.metadata[\"user_api_key_budget_reservation\"] — exactly where _get_budget_reservation_from_metadata reads it for reconciliation.
  • Previous comments addressed: URL leakage from reqwest errors is redacted via err.without_url(); the extractor logs the raw detail server-side and returns a generic \"authentication unavailable\" to clients; 5xx errors from user_api_key_auth are re-raised rather than masked as 401; the O(n) retain scan is moved from the hot get path to insert.

Confidence Score: 5/5

The auth and budget-reservation changes are safe to merge; the end-to-end flow from Python reservation creation through Rust session metadata to logging reconciliation is complete and well-tested.

All three concerns raised in the previous review round are directly addressed: internal URLs are stripped from upstream errors, 5xx auth failures propagate rather than masquerade as 401, and the O(n) lock-hold is moved off the hot path. The budget-reservation plumbing is the only structural addition and each link in the chain — auth response, RequestMetadata, StandardLoggingMetadata, log replay, cost callback — is covered by a targeted unit test. The _reserve_budget_after_common_checks signature change has a single production call site, which is updated.

No files require special attention.

Important Files Changed

Filename Overview
litellm/proxy/rust_control_plane_endpoints/auth_endpoints.py New internal auth endpoint for the Rust data plane; correctly re-raises 5xx errors, uses constant-time comparison, and explicitly includes budget_reservation (excluded=True in model) in the response.
litellm/proxy/auth/user_api_key_auth.py Adds optional request parameter to _reserve_budget_after_common_checks and a skip_budget_reservation state-flag guard; only one production call site, already updated.
litellm/proxy/rust_control_plane_endpoints/logging_endpoints.py Replays finished logging payloads through LiteLLM's callback fan-out; correctly maps user_api_key_budget_reservation from payload metadata to litellm_params.metadata where the cost callback reconciles it.
litellm-rust/crates/ai-gateway/src/auth/user_api_key.rs Auth extractor; /v1/realtime always bypasses the cache, auth results with budget_reservation are never cached, and upstream errors are logged server-side with a generic message to clients.
litellm-rust/crates/ai-gateway/src/auth/cache.rs Bounded TTL cache; disabled by default (TTL=0). O(n) retain moved from the hot get path to insert, addressing the prior review comment.
litellm-rust/crates/ai-gateway/src/auth/client/python.rs HTTP client for delegating verification to the Python control plane; uses err.without_url() to redact internal URLs before storing in AuthError::Upstream.
litellm-rust/crates/ai-gateway/src/routes/realtime/mod.rs Switches realtime handler from RequireMasterKey to UserApiKeyAuth; request_metadata_for_auth correctly propagates budget_reservation into RequestMetadata for the logging path.
litellm-rust/crates/ai-gateway/src/integrations/types.rs Adds user_api_key_budget_reservation: Option<Value> to both RequestMetadata and StandardLoggingMetadata with skip_serializing_if to keep the JSON clean when absent.
litellm-rust/crates/ai-gateway/src/realtime/streaming.rs Propagates user_api_key_budget_reservation from RequestMetadata into the StandardLoggingMetadata emitted at session end.
tests/test_litellm/proxy/rust_control_plane_endpoints/test_auth_endpoints.py Comprehensive unit tests covering data-plane key guard (500/401 paths), budget_reservation passthrough, 5xx propagation, and Bearer prefix de-duplication.

Reviews (5): Last reviewed commit: "fix(proxy): reconcile rust realtime budg..." | Re-trigger Greptile

@veria-ai

veria-ai Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 7 · PR risk: 0/10

Ishaan Jaff added 3 commits June 24, 2026 15:27
…staging' into codex/rust-auth-control-plane

# Conflicts:
#	litellm-rust/Cargo.lock
#	litellm-rust/Cargo.toml
#	litellm-rust/crates/ai-gateway/Cargo.toml
#	litellm-rust/crates/ai-gateway/src/routes/realtime/mod.rs
#	litellm/proxy/proxy_server.py
@ghost

ghost commented Jun 24, 2026 •

Copy link
Copy Markdown
Author

@veria-ai please re-review. Latest head c5c0d5fce6 addresses both open findings:

  • Model auth bypass: auth now decodes model with the same query parser as Axum, so encoded parameter names like mo%64el are included in the Python verifier request.
  • Virtual-key spend accounting: after merging the current target logging path, realtime carries UserApiKeyAuth into RequestMetadata, so virtual-key sessions log usage against the verified key hash/user/team; master-key sessions still use a SHA-256 hash of the master key.

Checks run: cargo fmt --check, cargo test -p litellm-ai-gateway --features server, cargo clippy -p litellm-ai-gateway --features server -- -D warnings, uv run pytest tests/test_litellm/proxy/rust_control_plane/test_auth_endpoints.py tests/test_litellm/proxy/logging_endpoints/test_callback_logs_endpoints.py -q, and targeted ruff check.

@ghost ghost changed the title feat(ai-gateway): Virtual-key auth via Python control plane (data-plane gated) feat(ai-gateway): add virtual-key auth via python control plane Jun 24, 2026
@ghost
ghost self-requested a review June 24, 2026 23:01
@ghost

ghost commented Jun 24, 2026

Copy link
Copy Markdown
Author

Addressed the remaining Veria security issue in b9c3c2b: realtime auth verification now skips only optimistic budget reservation while preserving normal admission checks, so repeated WebSocket opens cannot pin shared budget counters before actual spend. @veria-ai please run a fresh review.

@ghost

ghost commented Jun 25, 2026

Copy link
Copy Markdown
Author

Pushed one more CI-only fix on top: Codecov now ignores litellm-rust/** because this PR's Rust gateway diff is validated by rustfmt/clippy/test but does not have a matching Codecov upload.\n\nVaria, please review the latest head commit as well.

@ghost

ghost commented Jun 25, 2026

Copy link
Copy Markdown
Author

Fixed the SERVER_ROOT_PATH workflow failure. It was not a route assertion failure: Playwright's was failing during apt update because the GitHub runner had Microsoft apt sources returning 403 ( and ).\n\nAdded a workflow step to disable only apt source files containing before installing Chromium deps. Latest pushed commit: 5996946.

@ghost

ghost commented Jun 25, 2026

Copy link
Copy Markdown
Author

Clean note on the SERVER_ROOT_PATH failure: it was not a route assertion failure. Playwright's browser dependency install failed during apt update because the GitHub runner had Microsoft apt sources returning 403:

  • packages.microsoft.com/repos/azure-cli
  • packages.microsoft.com/ubuntu/24.04/prod

The pushed fix disables only apt source files containing packages.microsoft.com before running Playwright's Chromium dependency install. Latest pushed commit: 5996946.

@ghost

ghost commented Jun 25, 2026

Copy link
Copy Markdown
Author

@greptileai @veria-ai please re-review latest head 65760a0264.

This addresses the remaining realtime budget issue by carrying the Python budget reservation into Rust session metadata and reconciling it through /v1/rust_control_plane/logs:

  • auth no longer sets skip_budget_reservation on the synthetic /v1/realtime request
  • /v1/rust_control_plane/authentication includes budget_reservation in its internal response when present
  • Rust deserializes that reservation, stores it on RequestMetadata, and emits metadata.user_api_key_budget_reservation in the finished realtime logging payload
  • /v1/rust_control_plane/logs maps that into litellm_params.metadata, where the existing cost callback already reconciles user_api_key_budget_reservation
  • /v1/realtime bypasses the optional auth cache, and auth objects with request-scoped reservations are never cached

Local checks run:

  • uv run pytest tests/test_litellm/proxy/rust_control_plane_endpoints tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py::test_get_budget_reservation_from_metadata_handles_dict_auth_object -q
  • uv run ruff check on touched Python files
  • cargo fmt --all --check
  • cargo test -p litellm-ai-gateway --features server -- --nocapture
  • npm run gen:api with bundled Node; no schema.d.ts diff
  • git merge-tree --write-tree HEAD FETCH_HEAD against litellm_internal_staging completed without conflicts

@ghost
ghost enabled auto-merge (squash) June 25, 2026 01:45
@yuneng-berri
yuneng-berri deleted the branch main September 13, 2026 04:26
auto-merge was automatically disabled September 13, 2026 04:26

Pull request was closed

@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 15:59

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants