Repository navigation
fix(responses): prevent duplicate authorization headers - #52259
mateo-berri merged 7 commits into
Conversation
Co-authored-by: Bytechoreographer <Bytechoreographer@users.noreply.github.com>
surlymochan
left a comment
There was a problem hiding this comment.
Verified the fix in both the sync (response_api_handler) and async (async_response_api_handler) paths: _merge_response_api_headers drops the validated Authorization header whenever extra_headers carries any case-variant of authorization, then overlays extra_headers, so the outgoing request carries exactly one Authorization value. The updated test strengthens this meaningfully: it now sends a lowercase authorization in extra_headers and asserts get_list("authorization") == ["Bearer fake-caller-key"] (exactly one value), where the old headers["authorization"] assertion could pass even with duplicates present. The added bigmodel parametrization extends the same coverage to a third provider.
One edge case worth considering: if a caller passes both Authorization and authorization keys inside extra_headers itself, the overlay comprehension keeps both keys and httpx would still send two Authorization headers — the dedup here covers validated-vs-extra, not duplicates within extra_headers. Unlikely in practice, but a case-insensitive dedup of extra_headers would close it completely.
Co-authored-by: Bytechoreographer <Bytechoreographer@users.noreply.github.com>
|
@surlymochan Thanks for the review and for catching an edge case we missed. We added case-insensitive deduplication and pushed the improvement in the latest commit. |
surlymochan
left a comment
There was a problem hiding this comment.
Verified the merge logic against the two call sites (sync response_api_handler and async_response_api_handler): both now route through _merge_response_api_headers, and the chatgpt path still passes None for extra headers, so its behavior is unchanged.
What I checked:
- Base headers lose their
authorizationonly when the caller actually supplied one (caller_authorization is not Noneguard), so a provider-derived key fromvalidate_environmentis kept when the caller passes no auth header. - Among caller-supplied auth headers the last case-variant wins (
reversedscan), all other auth spellings are dropped, and the single winner is appended once — the test'sget_list("authorization") == ["Bearer <redacted>"]assertion pins exactly the duplicate-header bug this fixes. - Non-auth extra headers still merge in, and the
bigmodelprovider case in the test covers the non-OpenAI/non-Azure path.
One question on intended precedence: when both validate_environment returns an authorization (from the configured api_key) and the caller passes one in extra_headers, the caller now wins. That matches the test, but is caller-wins the documented contract for extra_headers, or should the configured key win for the Responses API the way it does for the chat path? Worth a line in the PR description either way.
Reuse the case-insensitive header merge the chatgpt path already uses for every Responses provider, so a caller's header replaces the configured one whatever its case and caller case variants collapse to the last one.
Merging this PR will not alter performance1 warning
Comparing Footnotes |
[Medium impact] The PR appears safe to merge.
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…onses route Get, delete, cancel, input items and compact now run the same merge as create, on a copy of extra_headers, so a caller's authorization of any case is the only one that goes upstream The merge keeps caller header values as given again. Only the chatgpt path keeps its str() coercion
…utes Stored-response calls to ChatGPT no longer merge caller headers again after its header validation, which already keeps a caller's ChatGPT OAuth token and drops any other caller authorization, the same as create The delete request kwargs mark url, headers and timeout as ReadOnly
1 similar comment
|
bugbot run |
|
bugbot run |
…headers on Responses
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 9c2f1ba. Configure here.
mateo-berri
left a comment
There was a problem hiding this comment.
LGTM. Thanks for the contribution!
Handwritten 1-3 sentence description
Fix Responses API requests sending both the configured credential and a caller-provided credential when their Authorization header names differ in case. Caller-provided values now replace the configured header case-insensitively and duplicate caller Authorization keys collapse to the last value, while other header merging remains unchanged.
Details
TLDR
Problem this solves:
authorizationgoes upstream beside the configured keyHow it solves it:
User Flow
Before: a developer who passes their own OpenAI key in
extra_headersgets a 401, because the proxy also sends the deployment's keygpt-6-lunato config.yaml with anapi_key"model": "gpt-6-luna"and"extra_headers": {"authorization": "Bearer <their OpenAI key>"}Incorrect API key provided, and the SDK's stored-response calls fail tooAfter: the same request goes to OpenAI with only the developer's key, so it completes
gpt-6-lunato config.yaml with anapi_key"status": "completed", served on their own key, and the SDK's stored-response calls work tooRelevant issues
discussion_r4405367654
discussion_r4409350111
discussion_r4405448012
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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 moreDelays 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
Last updated:
9c2f1ba20b. QA ran on7fa1806942, and on9c2f1ba20bfor cases H and I. Changes since QA: a Bedrock Mantle fix and two tests. Proof remains valid because A to G never use the Mantle config. Verification: the handler, Responses and Mantle suites pass at9c2f1ba20bCases A to E each boot one proxy with 2 workers and no database at the named commit, with the same config and the real OpenAI API. The configured key is invalid, so only the caller's key succeeds
config.yaml:
Env vars and proxy start
Env vars:
LITELLM_MASTER_KEYis the master key,QA_CONFIGURED_OPENAI_KEYholds an invalid key,OPENAI_API_KEYis the client's real key,PROXYis the proxy URL andOUTis an output folder.disable_cooldownsstops one 401 from cooling down the only deploymentProxy start, from the checkout at each commit with
DATABASE_URLunset andPYTHON_DOTENV_DISABLED=1:litellm --config config.yaml --port $PORT --num_workers 2 --timeout_worker_healthcheck 60sdk_cases.py
Case F runs the script below with Python from the checkout at each commit (
PYTHONPATHset to it,PYTHON_DOTENV_DISABLED=1,OPENAI_API_KEYset to a real key). Every call passes an invalidapi_keyand the caller's real key inextra_headers, once asauthorizationand once asAuthorization, so a call only succeeds when OpenAI reads the caller's key alone. Case G runs the second script on the BigModel provider at https://api.z.ai with a realZAI_API_KEYsdk_bigmodel.py
9c2f1ba20b9c2f1ba20bChatGPT stored-response and compact routes, probed with an invalid token
Known routes answer 401 to a bad token and unknown paths answer 404, so every route the ChatGPT stored-response change touches is one ChatGPT does not serve
Case F by call, sync and async each
Cases H and I, Bedrock Mantle with a pinned project
Both cases call Bedrock Mantle in us-east-1 with
openai.gpt-6.1-solthrough a proxy with 2 workers at each commit. The deployment pinsaws_bedrock_project_id: default, and the caller sends a project that does not exist, or a key Mantle does not accept, inextra_headers. A call only succeeds when Mantle reads the configured project and key alone, and Mantle's errors name the project or key it got. Case H signs with SigV4 from an AWS role. Case I sets a short-lived Bedrock API key asapi_key, with no AWS credentials in the proxy's environment. The AWS account id is redactedconfig.yaml for case H. Case I names the model
mantle-bearerand addsapi_key: os.environ/QA_MANTLE_API_KEY:parse.py, which prints one line per response
Case H before,
0cc072c999:Case H after,
9c2f1ba20b:Case I before,
0cc072c999:Case I after,
9c2f1ba20b:Before (0cc072c)
Case A, lowercase
authorization, non-streamSend the request
Read the saved response
Cases B to G, before
Case B, lowercase
authorization, streamSend the request
Case C, caller sends
Authorizationandauthorization, the last one validSend the request
Read the saved response
Case D (control), exact-case
AuthorizationSend the request
Read the saved response
Case E (out of scope), /v1/chat/completions with lowercase
authorizationSend the request
Read the saved response
Case F, SDK, every Responses route, sync and async
Run the script
Case G, SDK on the BigModel provider at api.z.ai, sync and async
Run the script
After (7fa1806)
Case A, lowercase
authorization, non-streamSend the request
Read the saved response
Cases B to G, after
Case B, lowercase
authorization, streamSend the request
Case C, caller sends
Authorizationandauthorization, the last one validSend the request
Read the saved response
Case D (control), exact-case
AuthorizationSend the request
Read the saved response
Case E (out of scope), /v1/chat/completions with lowercase
authorizationSend the request
Read the saved response
Case F, SDK, every Responses route, sync and async
Run the script
Case G, SDK on the BigModel provider at api.z.ai, sync and async
Run the script
Observations:
/live-pr-risk
PASS at
9c2f1ba20b. Nothing that worked at the merge base breaks. The Mantle fix since the full run at7fa1806942was walked again and run live as cases H and IReport, dependency graph and wire diff
Rig: three proxies with 2 workers each (merge base, head, and head merged into main at
2ae4aad2ca, which matched the head on every cell), each with its own Postgres, the same config, and a recorder in front of api.openai.com that logs each request and forwards it. Every cell called the real OpenAI API. The config hasresp-bad(invalidapi_key),resp-good(real key),bridge-bad(openai/responses/gpt-6-luna, invalid key),cfg-extra-exactandcfg-extra-lower(invalidapi_keyplus the real key inextra_headersasAuthorizationorauthorization), andfallback-primaryfalling back toresp-good, withforward_client_headers_to_llm_api: trueMantle fix at
9c2f1ba20b: it addssign_requestand changesvalidate_environmenton the Mantle Responses config only. Its callers are Mantle create, streamed create and compact, sync and async. Stored-response calls never reach Mantle because they carry no model. Websocket calls still get a plain dict fromvalidate_environmentand do not sign. Since the merge base, main changed only the TTS handler in these files, so the merged tree runs the same Mantle code. Cases H and I flip every failing cell to 200 and change no cell that passedBreaking
None found. Every cell that answered 200 at the merge base answers the same on the head. Each cell sent OpenAI as many requests on the head as at the merge base, one each and two for the fallback, apart from the deleted-key cell below
Backward incompatible
/v1/responseswith a lowercase caller key: 401 before, with both keys joined into one value on the wire, and 200 after with one key/v1/chat/completionsonbridge-bad: 401 before, 200 after, streamed too (0 chunks before, 15 after)extra_headers: lowercase gave 401 before and 200 after. Exact case could create before, but get, input items and delete sent the invalidapi_keyand got 401. All give 200 afterapi_keyand a wrong key inextra_headers, or a caller with a wrong exact-case key, used to succeed on get and delete and now gets 401, the same as create already didauthorizationnow goes upstream alone instead of joined with the deployment key. OpenAI answers 401 on both sides. Same Decisionaws_bedrock_project_id, an exact-case callerOpenAI-Projectused to pick the project on create, and now the configured one wins. First Decision, case HRegression risk
Authorization. For per-user sessions the proxy's per-user auth step strips the caller key before the handler, so that step is what protects it. Not run, no Copilot login hereDependency graph
/v1/responses/v1/chat/completions/v1/chat/completionsextra_headerskey/v1/responses/v1/responses/{id}/v1/responsesx-headers/v1/responses/v1/responses/v1/responsesWire diff
On every changed cell the head sent one
authorizationvalue, the caller's, where the merge base sent the deployment key or both keys joined. Forwardedx-client headers went out the same on both sides, on create and not on get. Int and list values answer 500 on both sides before any request goes out. Native chat,/v1/messages, key create and use, fallback (x-litellm-attempted-fallbacks: 1), readiness and health matched. Spend rows matched each response's status with no duplicate call ids. A deleted key sometimes still works for a moment on both sides, because each worker keeps its own key cache, so this PR does not cause itNot verified
Type
🐛 Bug Fix
Caveats (if any)
Medium
openai/responses/...) are fixed by this PR/v1/responseson deepseek, mistral and groq goes through chat, so it still doesLow
Authorizationcan replace a Copilot session token (follow-up)ChatGPT-Account-Idsent without a ChatGPT login, as create doesDecisions
Authorization, and the caller's value wins. Exact-case caller headers already replaced provider headers on create before this PR, so an Authorization-only merge would keep the result depending on case for every other header. It also matches how the proxy already merges client-forwarded headers on Responses calls, and HTTP header names are case-insensitiveaws_bedrock_project_idwin over caller headers in any case on create and compact, as its signer already did for an exact-caseAuthorization. The proxy already refusesaws_bedrock_project_idfrom callers, so a callerOpenAI-Projectheader no longer picks the project eitherAuthorizationincluded, now wins over the provider's, the same as on create. Before this PR, providers that set headers in place on those calls (OpenAI, Azure, xAI and others) overwrote even an exact-case caller header, so OpenAI got the configured keyChatGPT-Account-Idand drops any other callerAuthorizationor account id, so the handler does not merge caller headers again for ChatGPTauthorizationandAuthorization, collapse to the last one sent, so one value goes upstream. JSON parsers treat a repeated key the same way and keep the last oneAuthorizationtakes one value and the joined one is what OpenAI answers 401 to before this PRNonevalue still fails before the request, as before this PR. Only the chatgpt path keeps its existingstr()conversionFinal Attestation
Bugbot summary