Skip to content

fix(responses): prevent duplicate authorization headers - #52259

Merged
mateo-berri merged 7 commits into
BerriAI:mainfrom
AaronHowell:litellm_responses_authorization_headers
Nov 18, 2026
Merged

mateo-berri merged 7 commits into
BerriAI:mainfrom
AaronHowell:litellm_responses_authorization_headers

Conversation

@AaronHowell

@AaronHowell AaronHowell commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • A caller's lowercase authorization goes upstream beside the configured key
  • OpenAI answers 401, or an HTML 400 on sync SDK calls
  • Stored-response calls sent the configured key over an exact-case caller key
  • Caller case variants of one header also all go upstream

How it solves it:

  • Native Responses routes merge caller headers case-insensitively, caller wins
  • ChatGPT and Bedrock Mantle keep their own credential rules
  • Caller case variants collapse to the last one sent
  • Reuses the header merge the chatgpt path already had

User Flow

Before: a developer who passes their own OpenAI key in extra_headers gets a 401, because the proxy also sends the deployment's key

  1. The proxy admin adds gpt-6-luna to config.yaml with an api_key
  2. A developer sends POST http://localhost:4000/v1/responses with "model": "gpt-6-luna" and "extra_headers": {"authorization": "Bearer <their OpenAI key>"}
  3. OpenAI reads both keys as one value and the developer gets back 401 Incorrect API key provided, and the SDK's stored-response calls fail too

After: the same request goes to OpenAI with only the developer's key, so it completes

  1. The proxy admin adds gpt-6-luna to config.yaml with an api_key
  2. A developer sends the same request as above
  3. The developer gets HTTP 200 with "status": "completed", served on their own key, and the SDK's stored-response calls work too

Relevant issues

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

Last updated: 9c2f1ba20b. QA ran on 7fa1806942, and on 9c2f1ba20b for 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 at 9c2f1ba20b

Cases 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:

model_list:
  - model_name: gpt-6-luna
    litellm_params:
      model: openai/gpt-6-luna
      api_key: os.environ/QA_CONFIGURED_OPENAI_KEY
router_settings:
  disable_cooldowns: true
Env vars and proxy start

Env vars: LITELLM_MASTER_KEY is the master key, QA_CONFIGURED_OPENAI_KEY holds an invalid key, OPENAI_API_KEY is the client's real key, PROXY is the proxy URL and OUT is an output folder. disable_cooldowns stops one 401 from cooling down the only deployment

Proxy start, from the checkout at each commit with DATABASE_URL unset and PYTHON_DOTENV_DISABLED=1:

litellm --config config.yaml --port $PORT --num_workers 2 --timeout_worker_healthcheck 60
sdk_cases.py

Case F runs the script below with Python from the checkout at each commit (PYTHONPATH set to it, PYTHON_DOTENV_DISABLED=1, OPENAI_API_KEY set to a real key). Every call passes an invalid api_key and the caller's real key in extra_headers, once as authorization and once as Authorization, 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 real ZAI_API_KEY

import asyncio
import os
import re

import litellm

MODEL = "openai/gpt-6-luna"
CALLER_KEY = os.environ["OPENAI_API_KEY"]
CONFIGURED_KEY = "sk-proj-stale-configured-key-for-qa"


def describe(result):
    fields = result if isinstance(result, dict) else result.model_dump()
    return " ".join(f"{name}={fields[name]}" for name in ("object", "status", "deleted") if fields.get(name) is not None)


def reason(error):
    found = re.search(r'"message": "([^":]+)|<title>([^<]+)</title>', str(error))
    return next(group for group in found.groups() if group) if found else str(error)[:60]


def stored_response(**kwargs):
    return litellm.responses(model=MODEL, input="Reply with the single word hi", api_key=CALLER_KEY, **kwargs).id


def background_response():
    return stored_response(background=True, instructions="Count from 1 to 5000, one number per line")


def calls(caller_headers):
    configured = {"api_key": CONFIGURED_KEY, "extra_headers": caller_headers}
    stored = {**configured, "custom_llm_provider": "openai"}
    return {
        "responses": lambda prefix: (
            getattr(litellm, f"{prefix}responses"),
            {"model": MODEL, "input": "Reply with the single word hi", **configured},
        ),
        "get": lambda prefix: (getattr(litellm, f"{prefix}get_responses"), {"response_id": stored_response(), **stored}),
        "input_items": lambda prefix: (
            getattr(litellm, f"{prefix}list_input_items"),
            {"response_id": stored_response(), **stored},
        ),
        "cancel": lambda prefix: (
            getattr(litellm, f"{prefix}cancel_responses"),
            {"response_id": background_response(), **stored},
        ),
        "delete": lambda prefix: (
            getattr(litellm, f"{prefix}delete_responses"),
            {"response_id": stored_response(), **stored},
        ),
        "compact": lambda prefix: (
            getattr(litellm, f"{prefix}compact_responses"),
            {"model": MODEL, "input": "Reply with the single word hi", **configured},
        ),
    }


async def main():
    for header_name in ("authorization", "Authorization"):
        for route, build in calls({header_name: f"Bearer {CALLER_KEY}"}).items():
            for mode, prefix in (("sync", ""), ("async", "a")):
                function, kwargs = build(prefix)
                try:
                    result = await function(**kwargs) if prefix else function(**kwargs)
                    outcome = f"OK {describe(result)}"
                except Exception as error:
                    outcome = f"{type(error).__name__} {getattr(error, 'status_code', '')}: {reason(error)}"
                print(f"{header_name:13} {route:11} {mode:5} -> {outcome}")


asyncio.run(main())
sdk_bigmodel.py
import asyncio
import os
import re

import litellm

CALLER_KEY = os.environ["ZAI_API_KEY"]
CONFIGURED_KEY = "stale-configured-key-for-qa"


def reason(error):
    found = re.search(r'"message": "([^":]+)|<h1>([^<]+)</h1>', str(error))
    return next(group for group in found.groups() if group) if found else str(error)[:60]


async def main():
    for header_name in ("authorization", "Authorization"):
        kwargs = {
            "model": "bigmodel/glm-4.6",
            "input": "Reply with the single word hi",
            "api_base": "https://api.z.ai",
            "api_key": CONFIGURED_KEY,
            "extra_headers": {header_name: f"Bearer {CALLER_KEY}"},
        }
        for mode in ("sync", "async"):
            try:
                result = await litellm.aresponses(**kwargs) if mode == "async" else litellm.responses(**kwargs)
                outcome = f"OK status={result.status}"
            except Exception as error:
                outcome = f"{type(error).__name__} {getattr(error, 'status_code', '')}: {reason(error)}"
            print(f"{header_name:13} {mode:5} -> {outcome}")


asyncio.run(main())
Case Before (0cc072c) After (7fa1806)
A, lowercase 401 200, "hi"
B, lowercase stream 401 200, completed
C, both cases 401 200, "hi"
D, exact case 200, "hi" 200, "hi"
E, chat completions 401 401
F, SDK, 24 calls 22 fail 24 OK
G, SDK BigModel, 4 calls 2 fail 4 OK
H, Mantle SigV4, 7 calls 4 fail 7 OK at 9c2f1ba20b
I, Mantle API key, 6 calls 3 fail 6 OK at 9c2f1ba20b
ChatGPT 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

$ B=https://chatgpt.com/backend-api/codex
$ for spec in "GET $B/models?client_version=0.156.1" "GET $B/responses/resp_abc" "DELETE $B/responses/resp_abc" "POST $B/responses/resp_abc/cancel" "GET $B/responses/resp_abc/input_items" "POST $B/responses/compact" "POST $B/responses"; do m=${spec%% *}; u=${spec#* }; echo "$m $u -> $(curl -s -o /dev/null -w '%{http_code}' -X $m -H 'Authorization: Bearer not-a-real-token' -H 'ChatGPT-Account-ID: acct-fake' -H 'originator: codex_cli_rs' -H 'version: 0.156.1' -H 'Content-Type: application/json' $([ $m = POST ] && echo -d '{}') "$u")"; done
GET https://chatgpt.com/backend-api/codex/models?client_version=0.156.1 -> 401
GET https://chatgpt.com/backend-api/codex/responses/resp_abc -> 404
DELETE https://chatgpt.com/backend-api/codex/responses/resp_abc -> 404
POST https://chatgpt.com/backend-api/codex/responses/resp_abc/cancel -> 404
GET https://chatgpt.com/backend-api/codex/responses/resp_abc/input_items -> 404
POST https://chatgpt.com/backend-api/codex/responses/compact -> 404
POST https://chatgpt.com/backend-api/codex/responses -> 401
Case F by call, sync and async each
SDK call Before, lowercase sync Before, lowercase async Before, exact case After, both
responses 400 401 OK OK
get_responses 400 401 401 OK
list_input_items 400 401 401 OK
cancel_responses 400 401 401 OK
delete_responses 400 401 401 OK
compact_responses 400 401 401 OK
Cases H and I, Bedrock Mantle with a pinned project

Both cases call Bedrock Mantle in us-east-1 with openai.gpt-6.1-sol through a proxy with 2 workers at each commit. The deployment pins aws_bedrock_project_id: default, and the caller sends a project that does not exist, or a key Mantle does not accept, in extra_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 as api_key, with no AWS credentials in the proxy's environment. The AWS account id is redacted

config.yaml for case H. Case I names the model mantle-bearer and adds api_key: os.environ/QA_MANTLE_API_KEY:

model_list:
  - model_name: mantle-pinned
    litellm_params:
      model: bedrock_mantle/openai.gpt-6.1-sol
      aws_region_name: us-east-1
      aws_bedrock_project_id: default
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
router_settings:
  disable_cooldowns: true
parse.py, which prints one line per response
import json
import sys

raw = sys.stdin.read()
body, _, code = raw.rpartition("\nHTTP ")
if body.lstrip().startswith(("event:", "data:")):
    events = [line[7:].strip() for line in body.splitlines() if line.startswith("event: ")]
    datas = [line[6:] for line in body.splitlines() if line.startswith("data: ") and line[6:].strip() not in ("", "[DONE]")]
    types = events or [json.loads(d).get("type") for d in datas]
    errors = [d for d in datas if '"error"' in d][:1]
    print(f"HTTP {code.strip()} stream events={len(types)} last={types[-1] if types else None} error={errors[0][:200] if errors else None}")
    sys.exit()
try:
    d = json.loads(body)
except Exception:
    print(raw[:300])
    sys.exit()
err = d.get("error")
if err:
    msg = err.get("message") if isinstance(err, dict) else str(err)
    print(f"HTTP {code.strip()} error: {str(msg)[:220]}")
else:
    texts = [c.get("text") for o in d.get("output", []) if o.get("type") == "message" for c in o.get("content", [])]
    print(f"HTTP {code.strip()} status={d.get('status')} object={d.get('object')} text={texts[:1]}")

Case H before, 0cc072c999:

### M0 create, no caller header
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23417/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok", "max_output_tokens": 16}'
HTTP 200 status=completed object=response text=['ok']
### M1 create, caller OpenAI-Project
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23417/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok", "max_output_tokens": 16, "extra_headers": {"OpenAI-Project": "proj_bogus0000000000"}}'
HTTP 404 error: litellm.NotFoundError: BedrockException - {"error":{"code":"not_found_error","message":"Project 'arn:aws:bedrock-mantle:us-east-1:<aws-account>:project/proj_bogus0000000000 does not exist.","param":null,"type":"invalid_re
### M2 create, caller openai-project
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23417/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok", "max_output_tokens": 16, "extra_headers": {"openai-project": "proj_bogus0000000000"}}'
HTTP 400 error: litellm.BadRequestError: BedrockException - {"error":{"code":"validation_error","message":"'default, proj_bogus0000000000' is not a valid project ARN","param":null,"type":"invalid_request_error"}}

LiteLLM: model group '
### M3 compact, caller OpenAI-Project
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23417/v1/responses/compact -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok", "extra_headers": {"OpenAI-Project": "proj_bogus0000000000"}}'
HTTP 200 status=None object=response.compaction text=[]
### M4 compact, caller openai-project
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23417/v1/responses/compact -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok", "extra_headers": {"openai-project": "proj_bogus0000000000"}}'
HTTP 404 error: litellm.NotFoundError: BedrockException - {"error":{"code":"not_found_error","message":"Project 'arn:aws:bedrock-mantle:us-east-1:<aws-account>:project/proj_bogus0000000000, default does not exist.","param":null,"type":"i
### M5 compact, no caller header
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23417/v1/responses/compact -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok"}'
HTTP 200 status=None object=response.compaction text=[]
### M6 stream create, caller openai-project
$ curl -sS -N -w '\nHTTP %{http_code}' http://127.0.0.1:23417/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok", "max_output_tokens": 16, "stream": true, "extra_headers": {"openai-project": "proj_bogus0000000000"}}'
HTTP 400 error: litellm.BadRequestError: BedrockException - {"error":{"code":"validation_error","message":"'default, proj_bogus0000000000' is not a valid project ARN","param":null,"type":"invalid_request_error"}}

LiteLLM: model group '

Case H after, 9c2f1ba20b:

### M0 create, no caller header
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23418/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok", "max_output_tokens": 16}'
HTTP 200 status=completed object=response text=['ok']
### M1 create, caller OpenAI-Project
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23418/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok", "max_output_tokens": 16, "extra_headers": {"OpenAI-Project": "proj_bogus0000000000"}}'
HTTP 200 status=completed object=response text=['ok']
### M2 create, caller openai-project
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23418/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok", "max_output_tokens": 16, "extra_headers": {"openai-project": "proj_bogus0000000000"}}'
HTTP 200 status=completed object=response text=['ok']
### M3 compact, caller OpenAI-Project
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23418/v1/responses/compact -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok", "extra_headers": {"OpenAI-Project": "proj_bogus0000000000"}}'
HTTP 200 status=None object=response.compaction text=[]
### M4 compact, caller openai-project
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23418/v1/responses/compact -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok", "extra_headers": {"openai-project": "proj_bogus0000000000"}}'
HTTP 200 status=None object=response.compaction text=[]
### M5 compact, no caller header
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23418/v1/responses/compact -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok"}'
HTTP 200 status=None object=response.compaction text=[]
### M6 stream create, caller openai-project
$ curl -sS -N -w '\nHTTP %{http_code}' http://127.0.0.1:23418/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-pinned", "input": "Say ok", "max_output_tokens": 16, "stream": true, "extra_headers": {"openai-project": "proj_bogus0000000000"}}'
HTTP 200 stream events=9 last=response.completed error=None

Case I before, 0cc072c999:

### B0 create, no caller header
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23419/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-bearer", "input": "Say ok", "max_output_tokens": 16}'
HTTP 200 status=completed object=response text=['ok']
### B1 create, caller authorization
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23419/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-bearer", "input": "Say ok", "max_output_tokens": 16, "extra_headers": {"authorization": "Bearer caller-key-not-for-mantle"}}'
HTTP 401 error: litellm.AuthenticationError: BedrockException - {"error":{"code":"invalid_api_key","message":"Invalid bearer token","param":null,"type":"permission_denied_error"}}

LiteLLM: model group 'mantle-bearer' failed with the er
### B2 create, caller Authorization
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23419/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-bearer", "input": "Say ok", "max_output_tokens": 16, "extra_headers": {"Authorization": "Bearer caller-key-not-for-mantle"}}'
HTTP 200 status=completed object=response text=['ok']
### B3 stream create, caller authorization and openai-project
$ curl -sS -N -w '\nHTTP %{http_code}' http://127.0.0.1:23419/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-bearer", "input": "Say ok", "max_output_tokens": 16, "stream": true, "extra_headers": {"authorization": "Bearer caller-key-not-for-mantle", "openai-project": "proj_bogus0000000000"}}'
HTTP 401 error: litellm.AuthenticationError: BedrockException - {"error":{"code":"invalid_api_key","message":"Invalid bearer token","param":null,"type":"permission_denied_error"}}

LiteLLM: model group 'mantle-bearer' failed with the er
### B4 compact, caller authorization
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23419/v1/responses/compact -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-bearer", "input": "Say ok", "extra_headers": {"authorization": "Bearer caller-key-not-for-mantle"}}'
HTTP 401 error: litellm.AuthenticationError: BedrockException - {"error":{"code":"invalid_api_key","message":"Invalid bearer token","param":null,"type":"permission_denied_error"}}

LiteLLM: model group 'mantle-bearer' failed with the er
### B5 compact, caller Authorization
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23419/v1/responses/compact -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-bearer", "input": "Say ok", "extra_headers": {"Authorization": "Bearer caller-key-not-for-mantle"}}'
HTTP 200 status=None object=response.compaction text=[]

Case I after, 9c2f1ba20b:

### B0 create, no caller header
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23420/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-bearer", "input": "Say ok", "max_output_tokens": 16}'
HTTP 200 status=completed object=response text=['ok']
### B1 create, caller authorization
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23420/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-bearer", "input": "Say ok", "max_output_tokens": 16, "extra_headers": {"authorization": "Bearer caller-key-not-for-mantle"}}'
HTTP 200 status=completed object=response text=['ok']
### B2 create, caller Authorization
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23420/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-bearer", "input": "Say ok", "max_output_tokens": 16, "extra_headers": {"Authorization": "Bearer caller-key-not-for-mantle"}}'
HTTP 200 status=completed object=response text=['ok']
### B3 stream create, caller authorization and openai-project
$ curl -sS -N -w '\nHTTP %{http_code}' http://127.0.0.1:23420/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-bearer", "input": "Say ok", "max_output_tokens": 16, "stream": true, "extra_headers": {"authorization": "Bearer caller-key-not-for-mantle", "openai-project": "proj_bogus0000000000"}}'
HTTP 200 stream events=9 last=response.completed error=None
### B4 compact, caller authorization
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23420/v1/responses/compact -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-bearer", "input": "Say ok", "extra_headers": {"authorization": "Bearer caller-key-not-for-mantle"}}'
HTTP 200 status=None object=response.compaction text=[]
### B5 compact, caller Authorization
$ curl -sS -w '\nHTTP %{http_code}' http://127.0.0.1:23420/v1/responses/compact -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model": "mantle-bearer", "input": "Say ok", "extra_headers": {"Authorization": "Bearer caller-key-not-for-mantle"}}'
HTTP 200 status=None object=response.compaction text=[]

Before (0cc072c)

Case A, lowercase authorization, non-stream

  1. Send the request

    $ curl -sS -o $OUT/a.json -w "HTTP %{http_code}\n" $PROXY/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"model\": \"gpt-6-luna\", \"input\": \"Reply with the single word hi\", \"extra_headers\": {\"authorization\": \"Bearer $OPENAI_API_KEY\"}}"
    HTTP 401
  2. Read the saved response

    $ jq "{status, model, output: [.output[]?.content[]?.text], error: .error.message}" $OUT/a.json
    {
      "status": null,
      "model": null,
      "output": [],
      "error": "litellm.AuthenticationError: AuthenticationError: OpenAIException - {\n  \"error\": {\n    \"message\": \"Incorrect API key provided: <redacted-key>. You can find your API key at https://platform.openai.com/account/api-keys.\",\n    \"type\": \"invalid_request_error\",\n    \"code\": \"invalid_api_key\",\n    \"param\": null\n  },\n  \"status\": 401\n}\n\nLiteLLM: model group 'gpt-6-luna' failed with the error above. No fallback was attempted."
    }
Cases B to G, before

Case B, lowercase authorization, stream

  1. Send the request

    $ curl -sSN -w "\nHTTP %{http_code}\n" $PROXY/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"model\": \"gpt-6-luna\", \"input\": \"Reply with the single word hi\", \"stream\": true, \"extra_headers\": {\"authorization\": \"Bearer $OPENAI_API_KEY\"}}" | grep -E "^event: response\.(created|completed|failed)|\"error\"|^HTTP" | cut -c1-300
    {"error":{"message":"litellm.AuthenticationError: AuthenticationError: OpenAIException - {\n  \"error\": {\n    \"message\": \"Incorrect API key provided: <redacted-key>
    HTTP 401

Case C, caller sends Authorization and authorization, the last one valid

  1. Send the request

    $ curl -sS -o $OUT/c.json -w "HTTP %{http_code}\n" $PROXY/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"model\": \"gpt-6-luna\", \"input\": \"Reply with the single word hi\", \"extra_headers\": {\"Authorization\": \"Bearer sk-proj-stale-caller-key-for-qa\", \"authorization\": \"Bearer $OPENAI_API_KEY\"}}"
    HTTP 401
  2. Read the saved response

    $ jq "{status, model, output: [.output[]?.content[]?.text], error: .error.message}" $OUT/c.json
    {
      "status": null,
      "model": null,
      "output": [],
      "error": "litellm.AuthenticationError: AuthenticationError: OpenAIException - {\n  \"error\": {\n    \"message\": \"Incorrect API key provided: <redacted-key>. You can find your API key at https://platform.openai.com/account/api-keys.\",\n    \"type\": \"invalid_request_error\",\n    \"code\": \"invalid_api_key\",\n    \"param\": null\n  },\n  \"status\": 401\n}\n\nLiteLLM: model group 'gpt-6-luna' failed with the error above. No fallback was attempted."
    }

Case D (control), exact-case Authorization

  1. Send the request

    $ curl -sS -o $OUT/d.json -w "HTTP %{http_code}\n" $PROXY/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"model\": \"gpt-6-luna\", \"input\": \"Reply with the single word hi\", \"extra_headers\": {\"Authorization\": \"Bearer $OPENAI_API_KEY\"}}"
    HTTP 200
  2. Read the saved response

    $ jq "{status, model, output: [.output[]?.content[]?.text], error: .error.message}" $OUT/d.json
    {
      "status": "completed",
      "model": "gpt-6-luna",
      "output": [
        "hi"
      ],
      "error": null
    }

Case E (out of scope), /v1/chat/completions with lowercase authorization

  1. Send the request

    $ curl -sS -o $OUT/e.json -w "HTTP %{http_code}\n" $PROXY/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"model\": \"gpt-6-luna\", \"messages\": [{\"role\": \"user\", \"content\": \"Reply with the single word hi\"}], \"extra_headers\": {\"authorization\": \"Bearer $OPENAI_API_KEY\"}}"
    HTTP 401
  2. Read the saved response

    $ jq "{model, content: .choices[0].message.content, error: .error.message}" $OUT/e.json
    {
      "model": null,
      "content": null,
      "error": "litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: <redacted-key>. You can find your API key at https://platform.openai.com/account/api-keys.\n\nLiteLLM: model group 'gpt-6-luna' failed with the error above. No fallback was attempted."
    }

Case F, SDK, every Responses route, sync and async

  1. Run the script

    $ python sdk_cases.py
    authorization responses   sync  -> BadRequestError 400: 400 Bad Request
    authorization responses   async -> AuthenticationError 401: Incorrect API key provided
    authorization get         sync  -> BadRequestError 400: 400 Bad Request
    authorization get         async -> AuthenticationError 401: Incorrect API key provided
    authorization input_items sync  -> BadRequestError 400: 400 Bad Request
    authorization input_items async -> AuthenticationError 401: Incorrect API key provided
    authorization cancel      sync  -> BadRequestError 400: 400 Bad Request
    authorization cancel      async -> AuthenticationError 401: Incorrect API key provided
    authorization delete      sync  -> BadRequestError 400: 400 Bad Request
    authorization delete      async -> AuthenticationError 401: Incorrect API key provided
    authorization compact     sync  -> BadRequestError 400: 400 Bad Request
    authorization compact     async -> AuthenticationError 401: Incorrect API key provided
    Authorization responses   sync  -> OK object=response status=completed
    Authorization responses   async -> OK object=response status=completed
    Authorization get         sync  -> AuthenticationError 401: Incorrect API key provided
    Authorization get         async -> AuthenticationError 401: Incorrect API key provided
    Authorization input_items sync  -> AuthenticationError 401: Incorrect API key provided
    Authorization input_items async -> AuthenticationError 401: Incorrect API key provided
    Authorization cancel      sync  -> AuthenticationError 401: Incorrect API key provided
    Authorization cancel      async -> AuthenticationError 401: Incorrect API key provided
    Authorization delete      sync  -> AuthenticationError 401: Incorrect API key provided
    Authorization delete      async -> AuthenticationError 401: Incorrect API key provided
    Authorization compact     sync  -> AuthenticationError 401: Incorrect API key provided
    Authorization compact     async -> AuthenticationError 401: Incorrect API key provided

Case G, SDK on the BigModel provider at api.z.ai, sync and async

  1. Run the script

    $ python sdk_bigmodel.py
    authorization sync  -> BadRequestError 400: 400 Bad Request
    authorization async -> AuthenticationError 401: litellm.AuthenticationError: BigmodelException - 身份验证失败。
    Authorization sync  -> OK status=completed
    Authorization async -> OK status=completed

After (7fa1806)

Case A, lowercase authorization, non-stream

  1. Send the request

    $ curl -sS -o $OUT/a.json -w "HTTP %{http_code}\n" $PROXY/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"model\": \"gpt-6-luna\", \"input\": \"Reply with the single word hi\", \"extra_headers\": {\"authorization\": \"Bearer $OPENAI_API_KEY\"}}"
    HTTP 200
  2. Read the saved response

    $ jq "{status, model, output: [.output[]?.content[]?.text], error: .error.message}" $OUT/a.json
    {
      "status": "completed",
      "model": "gpt-6-luna",
      "output": [
        "hi"
      ],
      "error": null
    }
Cases B to G, after

Case B, lowercase authorization, stream

  1. Send the request

    $ curl -sSN -w "\nHTTP %{http_code}\n" $PROXY/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"model\": \"gpt-6-luna\", \"input\": \"Reply with the single word hi\", \"stream\": true, \"extra_headers\": {\"authorization\": \"Bearer $OPENAI_API_KEY\"}}" | grep -E "^event: response\.(created|completed|failed)|\"error\"|^HTTP" | cut -c1-300
    event: response.created
    event: response.completed
    HTTP 200

Case C, caller sends Authorization and authorization, the last one valid

  1. Send the request

    $ curl -sS -o $OUT/c.json -w "HTTP %{http_code}\n" $PROXY/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"model\": \"gpt-6-luna\", \"input\": \"Reply with the single word hi\", \"extra_headers\": {\"Authorization\": \"Bearer sk-proj-stale-caller-key-for-qa\", \"authorization\": \"Bearer $OPENAI_API_KEY\"}}"
    HTTP 200
  2. Read the saved response

    $ jq "{status, model, output: [.output[]?.content[]?.text], error: .error.message}" $OUT/c.json
    {
      "status": "completed",
      "model": "gpt-6-luna",
      "output": [
        "hi"
      ],
      "error": null
    }

Case D (control), exact-case Authorization

  1. Send the request

    $ curl -sS -o $OUT/d.json -w "HTTP %{http_code}\n" $PROXY/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"model\": \"gpt-6-luna\", \"input\": \"Reply with the single word hi\", \"extra_headers\": {\"Authorization\": \"Bearer $OPENAI_API_KEY\"}}"
    HTTP 200
  2. Read the saved response

    $ jq "{status, model, output: [.output[]?.content[]?.text], error: .error.message}" $OUT/d.json
    {
      "status": "completed",
      "model": "gpt-6-luna",
      "output": [
        "hi"
      ],
      "error": null
    }

Case E (out of scope), /v1/chat/completions with lowercase authorization

  1. Send the request

    $ curl -sS -o $OUT/e.json -w "HTTP %{http_code}\n" $PROXY/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d "{\"model\": \"gpt-6-luna\", \"messages\": [{\"role\": \"user\", \"content\": \"Reply with the single word hi\"}], \"extra_headers\": {\"authorization\": \"Bearer $OPENAI_API_KEY\"}}"
    HTTP 401
  2. Read the saved response

    $ jq "{model, content: .choices[0].message.content, error: .error.message}" $OUT/e.json
    {
      "model": null,
      "content": null,
      "error": "litellm.AuthenticationError: AuthenticationError: OpenAIException - Incorrect API key provided: <redacted-key>. You can find your API key at https://platform.openai.com/account/api-keys.\n\nLiteLLM: model group 'gpt-6-luna' failed with the error above. No fallback was attempted."
    }

Case F, SDK, every Responses route, sync and async

  1. Run the script

    $ python sdk_cases.py
    authorization responses   sync  -> OK object=response status=completed
    authorization responses   async -> OK object=response status=completed
    authorization get         sync  -> OK object=response status=completed
    authorization get         async -> OK object=response status=completed
    authorization input_items sync  -> OK object=list
    authorization input_items async -> OK object=list
    authorization cancel      sync  -> OK object=response status=cancelled
    authorization cancel      async -> OK object=response status=cancelled
    authorization delete      sync  -> OK object=response.deleted deleted=True
    authorization delete      async -> OK object=response.deleted deleted=True
    authorization compact     sync  -> OK object=response.compaction
    authorization compact     async -> OK object=response.compaction
    Authorization responses   sync  -> OK object=response status=completed
    Authorization responses   async -> OK object=response status=completed
    Authorization get         sync  -> OK object=response status=completed
    Authorization get         async -> OK object=response status=completed
    Authorization input_items sync  -> OK object=list
    Authorization input_items async -> OK object=list
    Authorization cancel      sync  -> OK object=response status=cancelled
    Authorization cancel      async -> OK object=response status=cancelled
    Authorization delete      sync  -> OK object=response.deleted deleted=True
    Authorization delete      async -> OK object=response.deleted deleted=True
    Authorization compact     sync  -> OK object=response.compaction
    Authorization compact     async -> OK object=response.compaction

Case G, SDK on the BigModel provider at api.z.ai, sync and async

  1. Run the script

    $ python sdk_bigmodel.py
    authorization sync  -> OK status=completed
    authorization async -> OK status=completed
    Authorization sync  -> OK status=completed
    Authorization async -> OK status=completed

Observations:

  • OpenAI reads both keys as one joined value, answering 401
  • Sync SDK calls got an HTML 400 on OpenAI and Z.ai

/live-pr-risk

PASS at 9c2f1ba20b. Nothing that worked at the merge base breaks. The Mantle fix since the full run at 7fa1806942 was walked again and run live as cases H and I

Report, 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 has resp-bad (invalid api_key), resp-good (real key), bridge-bad (openai/responses/gpt-6-luna, invalid key), cfg-extra-exact and cfg-extra-lower (invalid api_key plus the real key in extra_headers as Authorization or authorization), and fallback-primary falling back to resp-good, with forward_client_headers_to_llm_api: true

Mantle fix at 9c2f1ba20b: it adds sign_request and changes validate_environment on 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 from validate_environment and 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 passed

Breaking

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

  • A caller key in any case now replaces the deployment key on create, get, input items, cancel, delete and compact, and on chat models routed through Responses. Kept by design, see the first two Decisions
    • /v1/responses with a lowercase caller key: 401 before, with both keys joined into one value on the wire, and 200 after with one key
    • /v1/chat/completions on bridge-bad: 401 before, 200 after, streamed too (0 chunks before, 15 after)
    • A deployment key in extra_headers: lowercase gave 401 before and 200 after. Exact case could create before, but get, input items and delete sent the invalid api_key and got 401. All give 200 after
    • Who loses: a deployment with a valid api_key and a wrong key in extra_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 did
  • An empty or 5 KB caller authorization now goes upstream alone instead of joined with the deployment key. OpenAI answers 401 on both sides. Same Decision
  • Two case variants of one caller header collapse to the last one, so both cases with the same key give 200 instead of 401. Listed under Low caveats
  • ChatGPT get and compact drop a caller key sent without a ChatGPT login, as create does. Third Decision, unit tests only
  • On a Mantle deployment with aws_bedrock_project_id, an exact-case caller OpenAI-Project used to pick the project on create, and now the configured one wins. First Decision, case H

Regression risk

  • GitHub Copilot: the handler no longer keeps a pinned session token over a caller 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 here
  • Bedrock compact: it signs after the merge. A code read shows the same headers on both sides. Not run
  • Responses over websocket and the interactions API use other handlers and were not run

Dependency graph

Dependent Entry point State
Create, lowercase caller key /v1/responses verified live
Chat routed through Responses /v1/chat/completions verified live
Same, streamed /v1/chat/completions verified live
Deployment extra_headers key /v1/responses verified live
Get, input items, delete /v1/responses/{id} verified live
Cancel, compact /v1/responses verified live
Forwarded x- headers /v1/responses verified live
Int, list, empty, 5 KB values /v1/responses verified live
Native chat, Messages proxy routes verified live
Fallbacks, keys, health proxy routes verified live
SDK, every route SDK verified live
BigModel Responses SDK verified live
ChatGPT routes SDK unit tests
GitHub Copilot SDK untested
Mantle create, stream, compact /v1/responses verified live
Bedrock compact SDK untested
Websocket, interactions proxy routes untested

Wire diff

On every changed cell the head sent one authorization value, the caller's, where the merge base sent the deployment key or both keys joined. Forwarded x- 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 it

Not verified

  • GitHub Copilot, since this node has no Copilot login
  • ChatGPT live, since its backend serves none of the changed routes (probe above)
  • Bedrock compact, Responses over websocket, and the interactions API were not run

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Native chat completions and other non-Responses handlers still send both keys (follow-up)
    • Chat models routed through Responses (openai/responses/...) are fixed by this PR
    • /v1/responses on deepseek, mistral and groq goes through chat, so it still does
    • Vector store, container, video, image, realtime and TTS calls are unchanged too

Low

  • A caller Authorization can replace a Copilot session token (follow-up)
  • Caller case variants of one header collapse to the last one
  • ChatGPT get and compact drop a caller key or ChatGPT-Account-Id sent without a ChatGPT login, as create does
  • ChatGPT answers 404 on stored-response and compact routes, so that change has unit tests only
  • The handwritten summary says other header merging is unchanged, but all caller headers now merge case-insensitively
  • A pre-existing gap went to security engineering
Decisions
  • Every caller header merges case-insensitively, not only 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-insensitive
    • An Authorization-only merge was rejected for the reason above
    • Bedrock Mantle is the one exemption. Its configured key and aws_bedrock_project_id win over caller headers in any case on create and compact, as its signer already did for an exact-case Authorization. The proxy already refuses aws_bedrock_project_id from callers, so a caller OpenAI-Project header no longer picks the project either
    • Exempting pinned headers for every provider was rejected because it needs a provider-owned final header pass, a design change for its own PR
  • On get, delete, cancel, input items and compact, a caller's header, Authorization included, 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 key
    • Letting the configured key win on every route was rejected. Create already sent an exact-case caller key before this PR, so that would break callers who bring their own key, and a response created with the caller's key lives in the caller's account, so get and delete need that key too
    • BigModel's Messages config drops a caller key for the configured one. That is its own provider rule, and it already differed from Responses create for exact-case keys before this PR
  • ChatGPT keeps its own credential rules on every route, create included. Its provider code keeps a caller's ChatGPT OAuth token with its ChatGPT-Account-Id and drops any other caller Authorization or account id, so the handler does not merge caller headers again for ChatGPT
    • Merging caller headers after that step on get and compact, as before this PR, was rejected because it pairs a caller's key or account id with the deployment's ChatGPT login, which create already refuses
  • Two case variants of one caller header, such as authorization and Authorization, collapse to the last one sent, so one value goes upstream. JSON parsers treat a repeated key the same way and keep the last one
    • Joining the values with a comma, as HTTP allows for list-valued headers, was rejected because Authorization takes one value and the joined one is what OpenAI answers 401 to before this PR
    • Keeping the first one was rejected because every other merge in the handler lets the later value win
    • Answering 400 was rejected because it would fail requests that work today when both variants carry the same key
  • Caller header values go upstream as given, so bytes stay bytes and a None value still fails before the request, as before this PR. Only the chatgpt path keeps its existing str() conversion

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
Bugbot summary

[!NOTE]
Medium Risk
Changes authentication header precedence across all Responses API routes and stored-response SDK calls; intentional for BYOK proxies but can 401 deployments that previously succeeded with mismatched caller vs configured keys.

Overview
Fixes Responses API requests that sent two Authorization values when callers used a different header casing (e.g. lowercase authorization) than the provider-configured key.

The shared HTTP handler now merges provider headers with extra_headers case-insensitively, with the caller winning on conflicts and duplicate case variants collapsing to the last value. Create/stream paths use this merge consistently; stored-response routes (get, delete, cancel, list input items, compact) go through a new _stored_response_request_headers helper instead of validate_environment plus a blind headers.update(extra_headers).

ChatGPT still relies on its own credential rules and does not re-merge caller headers after validation. Bedrock Mantle adds sign_request and _pinned_headers so configured bearer/SigV4 auth and OpenAI-Project override caller-supplied values on create and compact (including after signing).

Unit tests cover non-ChatGPT and stored-response flows, Mantle pinning, bytes header values, and rejection of None header values.

Reviewed by Cursor Bugbot for commit 9c2f1ba. Bugbot is set up for automated code reviews on this repo. Configure here.

Co-authored-by: Bytechoreographer <Bytechoreographer@users.noreply.github.com>
@veria-ai

veria-ai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@surlymochan surlymochan 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.

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>
@AaronHowell

AaronHowell commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

@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 surlymochan 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.

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 authorization only when the caller actually supplied one (caller_authorization is not None guard), so a provider-derived key from validate_environment is kept when the caller passes no auth header.
  • Among caller-supplied auth headers the last case-variant wins (reversed scan), all other auth spellings are dropped, and the single winner is appended once — the test's get_list("authorization") == ["Bearer <redacted>"] assertion pins exactly the duplicate-header bug this fixes.
  • Non-auth extra headers still merge in, and the bigmodel provider 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.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@codspeed

codspeed Bot commented Nov 17, 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 AaronHowell:litellm_responses_authorization_headers (9c2f1ba) with main (1b07f26)1

Open in CodSpeed

Footnotes

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

@greptile-apps

greptile-apps Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge.

Summary

Fixes duplicate authorization headers across Responses API calls while preserving ChatGPT and Bedrock Mantle credential rules.

  • Responses calls use the caller’s last header value, whatever its capitalization.
  • Bedrock Mantle keeps its configured key and project on Responses calls.

The latest Mantle before/after proof now addresses the previous QA finding. The earlier ChatGPT live-proof request remains retracted because those backend routes return 404.

Reviews (8) · Last reviewed commit: "fix(bedrock_mantle): keep the configured..." · Reviewed by Greptile

@codecov

codecov Bot commented Nov 17, 2026

Copy link
Copy Markdown

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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor 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.

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor 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.

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor 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.

✅ 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 mateo-berri 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.

LGTM. Thanks for the contribution!

@mateo-berri
mateo-berri merged commit 2174e75 into BerriAI:main Nov 18, 2026
97 checks passed
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