Skip to content

fix(gateway-forward): keep x-litellm-api-key when the client names it in connection - #52427

Merged
narmstrong-berri merged 1 commit into
mainfrom
nate_fix_rust_forward_litellm_api_key
Nov 18, 2026
Merged

narmstrong-berri merged 1 commit into
mainfrom
nate_fix_rust_forward_litellm_api_key

Conversation

@narmstrong-berri

@narmstrong-berri narmstrong-berri commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

[insert handwritten description here]

Details

TLDR

Problem this solves:

  • Rust forwarder strips x-litellm-api-key when Connection lists it
  • Python then answers 401 No api key passed in
  • Python alone accepts the same request

How it solves it:

  • Add x-litellm-api-key to the headers Connection can never remove

User Flow

Before: a client authenticating with the x-litellm-api-key header is rejected when the proxy runs behind the Rust forwarder and the request's Connection header names that key header

  1. The client sends POST https://litellm-domain/v1/chat/completions with x-litellm-api-key: sk-... and Connection: x-litellm-api-key, keep-alive
  2. The proxy answers 401 with No api key passed in

After: the same request is authenticated as it is without the Rust forwarder

  1. The client sends the same POST https://litellm-domain/v1/chat/completions with the same headers
  2. The proxy authenticates the key and answers 200 with the completion

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Live proxy proof

Screenshots / Proof of Fix

Live run of the real Rust forwarding path. With LITELLM_RUST_FIRST=true, proxy_cli.py hands startup to litellm.proxy.rust_forward.supervisor, which runs the litellm-gateway binary on the public port 4301 and the Python proxy (two uvicorn workers) on a private loopback listener. The binary was built from this checkout with cargo build -p litellm-gateway --bin litellm-gateway (debug profile) and put in the scripts directory of the venv running the proxy, which is where the supervisor looks for it. No provider credentials exist in this environment, so the one deployment points at a small local HTTP stub on 127.0.0.1:4351 that speaks the OpenAI chat completions wire format. Redis on 6403 backs both router_settings and general_settings.coordination_redis. No database is used, the client authenticates with the master key in x-litellm-api-key

Before is the commit's parent 532df6e and after is the tip 89a839f. The commit only touches Rust files (rewrite.rs and its test), so the Python side is byte for byte the same at both SHAs. To avoid a second full build, the before binary was produced by checking out only the parent's litellm/rust/crates/gateway-forward/src/rewrite.rs into the tip worktree and rebuilding incrementally, then restoring the tip file. Both runs use the same command, config, two workers and Redis

At the parent, the request whose Connection header names x-litellm-api-key gets 401 No api key passed in through Rust, while the same request sent straight to the Python private listener gets 200, and the same key without the Connection token also gets 200 through Rust. At the tip, both requests get 200 with the stub's completion

Proxy command, run from the repo root (the same for before and after)

LITELLM_RUST_FIRST=true LITELLM_MASTER_KEY=<master key> STUB_OPENAI_API_KEY=<any value> \
  python litellm/proxy/proxy_cli.py --config config.yaml --port 4301 --num_workers 2 --detailed_debug --reload --use_v2_migration_resolver

Two worker PIDs served each run (before 13967 and 13966, after 14485 and 14486), and the proxy did not print that workers is ignored with reload. The gateway logged forwarding gateway listening on 0.0.0.0:4301 in both runs

config.yaml
model_list:
  - model_name: stub-gpt
    litellm_params:
      model: openai/stub-gpt
      api_base: http://127.0.0.1:4351/v1
      api_key: os.environ/STUB_OPENAI_API_KEY

router_settings:
  redis_host: 127.0.0.1
  redis_port: 6403

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  coordination_redis:
    host: 127.0.0.1
    port: 6403
stub.py (local OpenAI-compatible upstream, run as python stub.py 4351)
import json, sys, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        body = json.loads(self.rfile.read(int(self.headers.get("content-length", 0))) or b"{}")
        reply = {
            "id": "chatcmpl-stub",
            "object": "chat.completion",
            "created": int(time.time()),
            "model": body.get("model", "stub"),
            "choices": [{"index": 0, "finish_reason": "stop",
                         "message": {"role": "assistant", "content": "hello from the local stub"}}],
            "usage": {"prompt_tokens": 5, "completion_tokens": 5, "total_tokens": 10},
        }
        data = json.dumps(reply).encode()
        self.send_response(200)
        self.send_header("content-type", "application/json")
        self.send_header("content-length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), Handler).serve_forever()
client.sh (run as ./client.sh 4301 with LITELLM_MASTER_KEY exported)
#!/bin/sh
# usage: client.sh <port>
PORT=$1
BODY='{"model":"stub-gpt","messages":[{"role":"user","content":"hi"}]}'
echo "== 1. x-litellm-api-key, Connection names the key header =="
curl -sS -i http://localhost:$PORT/v1/chat/completions \
  -H "x-litellm-api-key: Bearer $LITELLM_MASTER_KEY" \
  -H "Connection: x-litellm-api-key, keep-alive" \
  -H "content-type: application/json" -d "$BODY"
echo; echo
echo "== 2. x-litellm-api-key, no Connection token (control) =="
curl -sS -i http://localhost:$PORT/v1/chat/completions \
  -H "x-litellm-api-key: Bearer $LITELLM_MASTER_KEY" \
  -H "content-type: application/json" -d "$BODY"
echo

Before (parent 532df6e)

Request 1 is rejected through Rust

HTTP/1.1 401 Unauthorized
{"error":{"message":"Authentication Error, No api key passed in.","type":"auth_error","param":null,"code":"401"}}

and the proxy log shows litellm.proxy.proxy_server.user_api_key_auth(): Exception occured - Authentication Error, No api key passed in.

The same request sent directly to the Python private listener of that run (127.0.0.1:47341) is accepted, so the 401 comes from the Rust hop

$ curl -sS -i http://127.0.0.1:47341/v1/chat/completions -H "x-litellm-api-key: Bearer $LITELLM_MASTER_KEY" -H "Connection: x-litellm-api-key, keep-alive" -H "content-type: application/json" -d '{"model":"stub-gpt","messages":[{"role":"user","content":"hi"}]}'
HTTP/1.1 200 OK
{"id":"chatcmpl-stub","created":1795037198,"model":"stub-gpt","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"hello from the local stub","role":"assistant"},"provider_specific_fields":{}}],"usage":{"completion_tokens":5,"prompt_tokens":5,"total_tokens":10}}
Full client output, before
== 1. x-litellm-api-key, Connection names the key header ==
HTTP/1.1 401 Unauthorized
date: Wed, 18 Nov 2026 21:26:32 GMT
content-length: 113
content-type: application/json
vary: Origin
x-frame-options: DENY
content-security-policy: frame-ancestors 'none'
x-content-type-options: nosniff

{"error":{"message":"Authentication Error, No api key passed in.","type":"auth_error","param":null,"code":"401"}}

== 2. x-litellm-api-key, no Connection token (control) ==
HTTP/1.1 200 OK
date: Wed, 18 Nov 2026 21:26:32 GMT
content-length: 303
content-type: application/json
x-litellm-call-id: 154dd000-787b-4c25-9bc1-ef4aafc92a00
x-litellm-model-id: 6d94bb447a82e7140e3a17e4171e06e09e23d020d0ad4575ac98cd6a193d7c8b
x-litellm-model-name: openai/stub-gpt
x-litellm-model-api-base: http://127.0.0.1:4351/v1
x-litellm-version: 1.111.0
x-litellm-key-spend: 0.0
x-litellm-response-duration-ms: 295.7489490509033
x-litellm-overhead-duration-ms: 288.7411
x-litellm-callback-duration-ms: 0.0
llm_provider-server: BaseHTTP/0.6 Python/3.12.3
llm_provider-date: Wed, 18 Nov 2026 21:26:33 GMT
llm_provider-content-type: application/json
llm_provider-content-length: 297
x-litellm-model-group: stub-gpt
x-litellm-attempted-retries: 0
x-litellm-attempted-fallbacks: 0
vary: Origin
x-frame-options: DENY
content-security-policy: frame-ancestors 'none'
x-content-type-options: nosniff

{"id":"chatcmpl-stub","created":1795037193,"model":"stub-gpt","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"hello from the local stub","role":"assistant"},"provider_specific_fields":{}}],"usage":{"completion_tokens":5,"prompt_tokens":5,"total_tokens":10}}

After (tip 89a839f)

Request 1 is authenticated and served through Rust

HTTP/1.1 200 OK
{"id":"chatcmpl-stub","created":1795037242,"model":"stub-gpt","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"hello from the local stub","role":"assistant"},"provider_specific_fields":{}}],"usage":{"completion_tokens":5,"prompt_tokens":5,"total_tokens":10}}
Full client output, after
== 1. x-litellm-api-key, Connection names the key header ==
HTTP/1.1 200 OK
date: Wed, 18 Nov 2026 21:27:21 GMT
content-length: 303
content-type: application/json
x-litellm-call-id: 9024e62d-4624-4f47-abd1-e3f0245eb581
x-litellm-model-id: 6d94bb447a82e7140e3a17e4171e06e09e23d020d0ad4575ac98cd6a193d7c8b
x-litellm-model-name: openai/stub-gpt
x-litellm-model-api-base: http://127.0.0.1:4351/v1
x-litellm-version: 1.111.0
x-litellm-key-spend: 0.0
x-litellm-response-duration-ms: 142.74001121520996
x-litellm-overhead-duration-ms: 134.464
x-litellm-callback-duration-ms: 0.0
llm_provider-server: BaseHTTP/0.6 Python/3.12.3
llm_provider-date: Wed, 18 Nov 2026 21:27:22 GMT
llm_provider-content-type: application/json
llm_provider-content-length: 297
x-litellm-model-group: stub-gpt
x-litellm-attempted-retries: 0
x-litellm-attempted-fallbacks: 0
vary: Origin
x-frame-options: DENY
content-security-policy: frame-ancestors 'none'
x-content-type-options: nosniff

{"id":"chatcmpl-stub","created":1795037242,"model":"stub-gpt","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"hello from the local stub","role":"assistant"},"provider_specific_fields":{}}],"usage":{"completion_tokens":5,"prompt_tokens":5,"total_tokens":10}}

== 2. x-litellm-api-key, no Connection token (control) ==
HTTP/1.1 200 OK
date: Wed, 18 Nov 2026 21:27:21 GMT
content-length: 303
content-type: application/json
x-litellm-call-id: 33b2db66-091c-4f6f-8a57-69037ee07e9d
x-litellm-model-id: 6d94bb447a82e7140e3a17e4171e06e09e23d020d0ad4575ac98cd6a193d7c8b
x-litellm-model-name: openai/stub-gpt
x-litellm-model-api-base: http://127.0.0.1:4351/v1
x-litellm-version: 1.111.0
x-litellm-key-spend: 0.0
x-litellm-response-duration-ms: 19.821882247924805
x-litellm-overhead-duration-ms: 17.5948
x-litellm-callback-duration-ms: 0.0
llm_provider-server: BaseHTTP/0.6 Python/3.12.3
llm_provider-date: Wed, 18 Nov 2026 21:27:22 GMT
llm_provider-content-type: application/json
llm_provider-content-length: 297
x-litellm-model-group: stub-gpt
x-litellm-attempted-retries: 0
x-litellm-attempted-fallbacks: 0
vary: Origin
x-frame-options: DENY
content-security-policy: frame-ancestors 'none'
x-content-type-options: nosniff

{"id":"chatcmpl-stub","created":1795037242,"model":"stub-gpt","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"hello from the local stub","role":"assistant"},"provider_specific_fields":{}}],"usage":{"completion_tokens":5,"prompt_tokens":5,"total_tokens":10}}

Unit tests

Scope is one entry added to the list of end-to-end headers that a client's Connection header cannot strip in litellm/rust/crates/gateway-forward/src/rewrite.rs, next to the x-api-key, api-key and litellm-api-key entries already there, plus one new case in the existing connection_cannot_remove_end_to_end_headers socket test in litellm/rust/crates/gateway-forward/tests/exchange.rs. The only caller of that list is the hop-by-hop stripping on the request path, and the test drives a real request through the forwarder to a recording upstream and checks the header reaches Python with its value. The change is mechanical and the test proves it fully, so no live proxy run was done.

The bug was found by the Dec 1 integration contract tests (draft PR #50853), where test_dec1_rustparity_unary::test_the_master_key_in_the_x_litellm_api_key_header_is_served_in_both_modes is skipped with BUG for it.

Commands, run from litellm/rust:

cargo test -p litellm-gateway-forward --test exchange connection_cannot_remove_end_to_end_headers
cargo fmt -p litellm-gateway-forward
cargo clippy -p litellm-gateway-forward --all-targets

Without the rewrite.rs change the new case connection_cannot_remove_end_to_end_headers::case_08_x_litellm_key fails (13 passed, 1 failed). With it all 14 cases pass. cargo fmt changed nothing and clippy reported no warnings.

Type

Bug Fix

Caveats (if any)

Low

  • A custom litellm_key_header_name named in Connection is still stripped
  • x-goog-api-key and Ocp-Apim-Subscription-Key are likewise unprotected, left for a follow-up

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Generated by Claude Code

@veria-ai

veria-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

Copy link
Copy Markdown
Contributor Author

[AI] @greptileai review


Generated by Claude Code

@devin-ai-integration devin-ai-integration 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.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

@greptile-apps

greptile-apps Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The change affects requests passing through the Rust forwarding gateway when `Connection` names this key header.

The code change looks sound, but the repository's live-proof requirement must be met before merging.

Findings

  1. P2 Live authentication proof missing ▶

Summary

This PR keeps x-litellm-api-key intact when a client lists it in Connection.

  • The Rust forwarder keeps the LiteLLM key when Connection names it.

Reviews (1) · Last reviewed commit: "fix(gateway-forward): keep x-litellm-api..." · Reviewed by Greptile

@codecov

codecov Bot commented Nov 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 2 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 45 untouched benchmarks


Comparing nate_fix_rust_forward_litellm_api_key (89a839f) with main (6a09e4e)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (532df6e) during the generation of this report, so 6a09e4e was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@narmstrong-berri
narmstrong-berri force-pushed the nate_fix_rust_forward_litellm_api_key branch from b0b42de to 89a839f Compare November 18, 2026 05:16
@narmstrong-berri narmstrong-berri self-assigned this Nov 18, 2026
@narmstrong-berri
narmstrong-berri enabled auto-merge (squash) November 18, 2026 20:57
@narmstrong-berri
narmstrong-berri merged commit 36f23db into main Nov 18, 2026
122 checks passed
@narmstrong-berri
narmstrong-berri deleted the nate_fix_rust_forward_litellm_api_key branch November 18, 2026 21:05
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.

2 participants