Skip to content

feat(mcp): derive bridge and session keys with HKDF-SHA256 behind a legacy grace window - #42917

Open
devin-ai-integration[bot] wants to merge 19 commits into
mainfrom
litellm_mcp_kdf_hkdf_sha256
Open

devin-ai-integration[bot] wants to merge 19 commits into
mainfrom
litellm_mcp_kdf_hkdf_sha256

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • MCP bridge envelope and session keys came from scrypt, not a FIPS approved KDF
  • Changing the KDF invalidates every envelope and session token already issued

How it solves it:

  • Derive both key families with HKDF-SHA256 over the master key, domain label as info
  • The rotation window is on by default: the old scrypt key is also tried on open unless LITELLM_MCP_LEGACY_KDF_GRACE is set to false/0/no/off
  • Never tries the scrypt key when LITELLM_FIPS_MODE=true; mint always uses the HKDF key
  • Main's feat(claude_code_gateway): issue rotating refresh tokens and a revocation endpoint #44635 refresh grant for the Claude Code CLI (refresh_proxy_credential on /claude_code_gateway/oauth/token) is wired into the same grace window

Depends on #42700 (is_fips_mode), which has landed on main and is merged into this branch, so the diff is now only the MCP files

The scrypt docstrings advertised a memory hard guessing cost for a captured envelope. HKDF drops that on purpose: the master key is a high entropy secret, so the guessing cost was never what protected it, and HKDF-SHA256 is the FIPS approved construction the roadmap specifies (the earlier PR 38491 used PBKDF2 to keep the cost, which is not what the roadmap asks for)

User Flow

Before: an operator who upgrades sees every MCP client with an outstanding bridge or session token break at once, and a FIPS deployment cannot use these tokens at all

  1. A client sends POST https://litellm-domain/{alias}/mcp with Authorization: Bearer <envelope issued before the upgrade>
  2. After the upgrade the proxy answers 401 invalid_token, so the client must go through the OAuth flow again immediately
  3. A gateway DCR client sends POST https://litellm-domain/mcp with Authorization: Bearer llm_session_... issued before the upgrade and also gets 401

After: a one release grace window is on by default, existing tokens keep working, and new tokens use the FIPS approved key

  1. The operator deploys with nothing new to set; the legacy window is already on
  2. A client sends POST https://litellm-domain/{alias}/mcp with the envelope issued before the upgrade and gets 200; tools are listed and called as before
  3. A token minted after the deploy (POST https://litellm-domain/{alias}/token or /mcp/token) opens with or without the grace variable
  4. The operator sets LITELLM_MCP_LEGACY_KDF_GRACE=false next release; envelopes and session tokens issued before the upgrade then answer 401 and clients re-authenticate
  5. With LITELLM_FIPS_MODE=true the grace variable is ignored and only HKDF keyed tokens open

Linear ticket

Resolves LIT-8426

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/test_litellm/<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
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Screenshots / Proof of Fix

Proof of Fix

Two live proxies on the same box, same Postgres shape, same master key sk-integration-master, same scripted MCP peer and OAuth AS double. Base runs the merge-base commit c0663d52025d1f7ee3651045a30174ea9c142c40 where envelope and session keys are derived with scrypt; head runs a806e94246e9b66fe88db61cf2884dfc96a0ddcf where they are derived with HKDF-SHA256 and the legacy scrypt grace window is ON BY DEFAULT (a806e94246 is a pyright narrowing commit on top of 4aa0bc024f with no runtime change; 4aa0bc024f is a merge of origin/main into the branch, product code for this change unchanged since 3d589dc35b flipped the default). Only LITELLM_MCP_LEGACY_KDF_GRACE set to false/0/no/off disables the window, and LITELLM_FIPS_MODE=true forces it off regardless

Setup, run once against each leg (identical commands, only the port changes):

  1. Register an oauth_delegate bridge server backed by the MCP peer
curl -s -X POST http://127.0.0.1:$PORT/v1/mcp/server \
  -H "Authorization: Bearer sk-integration-master" \
  -H 'Content-Type: application/json' \
  -d "{\"server_name\":\"proof_$PORT\",\"alias\":\"proof_$PORT\",\"transport\":\"http\",\"url\":\"$PEER_URL\",\"auth_type\":\"oauth_delegate\",\"dcr_bridge\":true,\"issuer\":\"$ISSUER\",\"authorization_url\":\"$ISSUER/authorize\",\"token_url\":\"$ISSUER/token\",\"registration_url\":\"$ISSUER/register\"}"

Response: {"server_id":"e819ab98-..."} on 4101, {"server_id":"49b15187-..."} on 4100

  1. Create a user and a key scoped to that server
curl -s -X POST http://127.0.0.1:$PORT/user/new -H "Authorization: Bearer sk-integration-master" -d '{"user_id":"proof-user-'$PORT'","auto_create_key":false}'
curl -s -X POST http://127.0.0.1:$PORT/key/generate -H "Authorization: Bearer sk-integration-master" -d '{"user_id":"proof-user-'$PORT'","object_permission":{"mcp_servers":["<server_id>"]}}'
  1. Mint an envelope or session token directly from the product functions with an explicitly derived key
uv run --no-sync python -c '
import os
from datetime import datetime, timezone
from pydantic import SecretStr
from litellm.proxy.utils import hash_token
from litellm.proxy._experimental.mcp_server.outbound_credentials.key_derivation import hkdf_sha256, legacy_scrypt
from litellm.proxy._experimental.mcp_server.outbound_credentials.envelope import EnvelopeKeys, UpstreamTokenGrant, key_hash_identity, mint_envelope
mk = os.environ["MK"]
f = hkdf_sha256 if os.environ["KDF"] == "hkdf" else legacy_scrypt
keys = EnvelopeKeys(signing_key=SecretStr(f(mk, b"litellm-mcp-bridge:envelope-signing:")), encryption_key=SecretStr(f(mk, b"litellm-mcp-bridge:envelope-encryption:")))
sealed = mint_envelope(key_hash_identity(server_id="<server_id>", key_hash=hash_token("<key>")), UpstreamTokenGrant(access_token=SecretStr("proof-upstream-token"), token_type="Bearer", expires_in=600), keys, datetime.now(timezone.utc))
print(sealed.token.get_secret_value())
'

Session tokens are minted the same way via SessionKeys(signing_key=...) + mint_session_token(SessionPrincipal(user_id=<user>, client_id="dcr-integration"), keys, now) with the litellm-mcp-gateway:session-signing: label

  1. Present the token with curl; the request is the customer-facing tools/list
curl -i -X POST http://127.0.0.1:$PORT/proof_$PORT/mcp \
  -H "Authorization: Bearer <envelope>" \
  -H "Accept: application/json, text/event-stream" \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'

Note: the auth-time body pre-read rejects curl's default application/x-www-form-urlencoded content type with 400 "Invalid form payload" on both legs, so Content-Type: application/json is sent explicitly; the tokens, headers and bodies are otherwise identical to the earlier proofs

Both legs run with general_settings.enable_claude_code_gateway: true via per-leg scratch configs proxy_config_head_claude.yaml and proxy_config_base_claude.yaml in this directory (copies of tests/integration/proxy_config.yaml plus the flag) so the /claude_code_gateway/oauth/token route exists for the refresh-grant row; the shared test config is untouched

The Claude Code refresh grant row mints a proxy_api-audience session refresh token for client_id=claude_code under legacy_scrypt via mint_session_refresh_token, then posts it form-encoded (the endpoint parses request.form()): POST /claude_code_gateway/oauth/token with grant_type=refresh_token&refresh_token=<token>. The rotated refresh token is single-use, so each leg gets a fresh mint

Before (c0663d5)

Base proxy on http://127.0.0.1:4101, scrypt-only KDF, no LITELLM_MCP_LEGACY_KDF_GRACE anywhere in the code

case: bridge envelope minted with HKDF keys

  1. Minted an envelope whose EnvelopeKeys come from hkdf_sha256 and presented it to POST /proof_4101/mcp
  2. Observed 401 Unauthorized, www-authenticate: Bearer error="invalid_token", body {"detail":"Invalid or expired credential"} (capture env_hkdf_4101_a806.txt)

case: bridge envelope minted with legacy scrypt keys

  1. Minted an envelope whose EnvelopeKeys come from legacy_scrypt (the pre-rotation derivation) and presented it to POST /proof_4101/mcp
  2. Observed 200 OK, SSE tools frame with "server_outcomes":{"proof_4101":{"status":"ok","tool_count":3}} (capture env_scrypt_4101_a806.txt)

case: gateway session token minted with HKDF key

  1. Minted a session token under hkdf_sha256 and presented it to POST /mcp
  2. Observed 401 Unauthorized, body {"detail":{"error":"authentication_required","message":"Authenticate with the gateway to use the MCP endpoint."}} (capture sess_hkdf_4101_a806.txt)

case: gateway session token minted with legacy scrypt key

  1. Minted a session token under legacy_scrypt and presented it to POST /mcp
  2. Observed 200 OK, SSE frame {"jsonrpc":"2.0","id":1,"result":{"tools":[]}} (capture sess_scrypt_4101_a806.txt)

case: Claude Code refresh grant with a legacy scrypt session refresh token

  1. Minted a proxy_api session refresh token for claude_code under legacy_scrypt and posted grant_type=refresh_token form-encoded to POST /claude_code_gateway/oauth/token
  2. Observed 200 OK with access_token (litellm_login_...) and a rotated refresh_token (capture ccrefresh_4101_a806.txt)

After (a806e94)

Head proxy on http://127.0.0.1:4100, HKDF-SHA256 KDF with the legacy grace window on by default (no LITELLM_MCP_LEGACY_KDF_GRACE in its environment)

case: bridge envelope minted with HKDF keys

  1. Same mint command, same curl, pointed at POST /proof_4100/mcp
  2. Observed 200 OK, SSE tools frame with "server_outcomes":{"proof_4100":{"status":"ok","tool_count":3}} (capture env_hkdf_4100_a806.txt)

case: bridge envelope minted with legacy scrypt keys, no grace variable set

  1. Same mint under legacy_scrypt, same curl
  2. Observed 200 OK with the SSE tools list: the default-on window admits legacy material with the variable unset (capture env_scrypt_4100_a806.txt)

case: bridge envelope minted with legacy scrypt keys, grace explicitly disabled

  1. Restarted the head proxy with LITELLM_MCP_LEGACY_KDF_GRACE=false (log proxy_nograce_a806.log)
  2. Same scrypt envelope, same curl to POST /proof_4100/mcp
  3. Observed 401 Unauthorized, www-authenticate: Bearer error="invalid_token" (capture env_scrypt_4100_nograce_a806.txt); the HKDF envelope still answered 200 on the same proxy (env_hkdf_4100_nograce_a806.txt)

case: bridge envelope minted with legacy scrypt keys, grace set to a non-disabled value

  1. Restarted the head proxy with LITELLM_MCP_LEGACY_KDF_GRACE=yes (log proxy_yes_a806.log)
  2. Same scrypt envelope, same curl
  3. Observed 200 OK: only false/0/no/off disable the window, yes keeps it on (capture env_scrypt_4100_yes_a806.txt)

case: gateway session token minted with HKDF key

  1. Same session mint under hkdf_sha256, presented to POST /mcp
  2. Observed 200 OK, SSE frame {"jsonrpc":"2.0","id":1,"result":{"tools":[]}} (capture sess_hkdf_4100_a806.txt)

case: gateway session token minted with legacy scrypt key, no grace variable set

  1. Same session mint under legacy_scrypt, presented to POST /mcp
  2. Observed 200 OK, SSE frame {"jsonrpc":"2.0","id":1,"result":{"tools":[]}} (capture sess_scrypt_4100_a806.txt)

case: gateway session token minted with legacy scrypt key, grace explicitly disabled and yes

  1. Under LITELLM_MCP_LEGACY_KDF_GRACE=false the same scrypt session token answered 401 Unauthorized with the authentication_required body (capture sess_scrypt_4100_nograce_a806.txt)
  2. Under LITELLM_MCP_LEGACY_KDF_GRACE=yes it answered 200 OK (capture sess_scrypt_4100_yes_a806.txt)

case: Claude Code refresh grant with a legacy scrypt session refresh token

  1. With no grace variable set, posted the scrypt proxy_api session refresh token for claude_code to POST /claude_code_gateway/oauth/token
  2. Observed 200 OK with access_token (litellm_login_...) and a rotated refresh_token: the default-on window covers refresh_proxy_credential too (capture ccrefresh_4100_a806.txt)
  3. Under LITELLM_MCP_LEGACY_KDF_GRACE=false a fresh mint of the same token observed 400 Bad Request, {"error":"invalid_grant","error_description":"the refresh token is invalid for this client"} (capture ccrefresh_4100_nograce_a806.txt)
  4. Under LITELLM_MCP_LEGACY_KDF_GRACE=yes another fresh mint observed 200 OK again (capture ccrefresh_4100_yes_a806.txt); the proxy was restarted without the var afterwards

case: FIPS mode with grace enabled

  1. Launched the head proxy with LITELLM_FIPS_MODE=true on a spare port so the running legs were untouched (log proxy_fips_a806.log)
  2. The proxy refused to boot: litellm.proxy.common_utils.fips.FipsModeError: LiteLLM proxy refused to start: LITELLM_FIPS_MODE is on but this Python does not enforce FIPS (proxy_fips_a806.log:433-434)
  3. This box has no OpenSSL FIPS provider (/usr/lib/x86_64-linux-gnu/ossl-modules/ contains only legacy.so), so a live 401 cannot be produced; on a real FIPS image the proxy boots and legacy_kdf_grace_enabled returns False under FIPS even though the window defaults on, so the legacy envelope is rejected. That path is pinned by the updated FIPS unit tests in test_bridge_credentials.py and test_session_credentials.py. The same FIPS boot gate exists at base, so a FIPS attempt refuses to boot on either leg

Summary

token kdf base (c0663d5) head no env (default-on) head GRACE=false head GRACE=yes
bridge envelope hkdf 401 200 200
bridge envelope scrypt 200 200 401 200
gateway session hkdf 401 200
gateway session scrypt 200 200 401 200
claude code refresh (session refresh) scrypt 200 200 400 invalid_grant 200

Under FIPS the grace fallback is compiled out (legacy_kdf_grace_enabled returns False before the env var is even read) and on this non-FIPS box LITELLM_FIPS_MODE=true refuses to boot at all, so legacy material is dead either way. To retire the window an operator sets LITELLM_MCP_LEGACY_KDF_GRACE=false (or 0/no/off) in the next release

Type

🆕 New Feature

Caveats (if any)

Severe

  • The window is on by default, so nothing breaks on upgrade; it only closes when an operator sets LITELLM_MCP_LEGACY_KDF_GRACE=false (or 0/no/off)
  • Grace window is one release; tokens issued before the upgrade die when it is turned off

Medium

  • Grace only applies to the default master key HS256 session path, never to configured RS256 keys
  • Any value other than false/0/no/off (including unset) keeps the window on

Low

  • Memory hard guessing cost for a captured envelope is gone by design (see TLDR)
  • Unit tests pin the HKDF output for a fixed master key; changing a domain label changes the pin

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

Link to Devin session: https://app.devin.ai/sessions/6149133afa70451880d474f84343e2a9
Open in Devin Desktop: https://app.devin.ai/desktop/session/6149133afa70451880d474f84343e2a9?variant=devin
Requested by: @yucheng-berri


Note

High Risk
Changes authentication key material and token validation for MCP bridge envelopes and gateway sessions; misconfiguration or premature grace disable would invalidate outstanding tokens, though default-on grace mitigates upgrade breakage.

Overview
Rotates MCP outbound credential key derivation from memory-hard scrypt to HKDF-SHA256 over the proxy master_key (new key_derivation.py). Bridge envelope and gateway session signing keys are minted with HKDF; opening tokens tries the active keys first, then optional legacy scrypt subkeys.

Default-on upgrade path: legacy_envelope_keys_from_master_key / legacy_session_keys_from_master_key supply the old derivation unless LITELLM_MCP_LEGACY_KDF_GRACE is false/0/no/off, or FIPS mode is on (no scrypt fallback; RS256 session config also skips legacy). Admission (resolve_bridge_envelope, resolve_session_bearer), bridge refresh, DCR refresh/revoke/introspect, and Claude Code refresh_proxy_credential all pass legacy_keys through shared open helpers.

Tests add integration coverage for HKDF vs scrypt tokens across MCP, token, revoke, introspect, and Claude Code paths, plus unit KATs and grace/FIPS behavior.

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

yucheng-berri and others added 9 commits September 23, 2026 07:20
…TLS verify guard and loud password migration

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…l semantics

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… return checks

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…and covers markers

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…y instead of patching _setup_prisma_client

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.23810% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
.../mcp_server/outbound_credentials/key_derivation.py 92.85% 2 Missing ⚠️
..._server/outbound_credentials/bridge_credentials.py 96.15% 1 Missing ⚠️
...server/outbound_credentials/session_credentials.py 95.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Critical risk] Rotates key derivation for authentication tokens with legacy fallback.

The PR appears safe to merge based on the reviewed changes and previously resolved findings.

Summary

The PR derives MCP bridge-envelope and gateway-session keys with HKDF-SHA256, with an opt-in, non-FIPS grace window for opening legacy scrypt tokens.

  • Extends the fallback to bridge and gateway admission, refresh, revocation, introspection, and Claude Code credential refresh.
  • Adds unit and proxy-level rotation coverage.

Reviews (6) · Last reviewed commit: "fix(mcp): honor the legacy KDF grace win..." · Reviewed by Greptile

Comment thread litellm/proxy/common_utils/fips.py Resolved

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

@codspeed

codspeed Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_mcp_kdf_hkdf_sha256 (a806e94) with main (3fec507)

Open in CodSpeed

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@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.

…sha256

# Conflicts:
#	tests/integration/_support/process.py
#	tests/unit/proxy/common_utils/test_fips.py
@yucheng-berri

Copy link
Copy Markdown
Contributor

@greptileai review latest head

@yucheng-berri

Copy link
Copy Markdown
Contributor

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai review

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

…S, cache the legacy derivation

legacy_kdf_grace_enabled required LITELLM_MCP_LEGACY_KDF_GRACE=true, so
operators who never heard of the variable lost every main-era scrypt token
on upgrade day. The window now defaults on and only explicit false-style
values (false/0/no/off) disable it; FIPS deployments stay force-off via the
existing is_fips_mode check. legacy_scrypt (n=2**15, memory-hard) is now
lru_cache'd per process so repeated legacy-format token attempts derive the
subkeys once instead of re-running scrypt per attempt.
@yucheng-berri

Copy link
Copy Markdown
Contributor

@litereview full

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

@litereview

litereview Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

✅ full

Scope: full · Full PR review.

Completed · Some checks not run.

Verdict: one actionable defect remains, the rolling-upgrade break

I mapped every caller of the re-keyed symbols:

  • envelope_keys_from_master_key
  • session_keys_from_master_key (reached through active_session_signing_keys and resolve_session_signing)
  • resolve_bridge_envelope
  • open_bridge_refresh_envelope
  • resolve_session_bearer
  • open_session_refresh_bearer

Every read site now receives the legacy keys:

  • the bridge admission edge
  • bridge refresh
  • the DCR refresh_token grant
  • the Claude Code /oauth/token refresh and /oauth/revoke
  • gateway session admission
  • RFC 7662 introspection

So pre-upgrade scrypt tokens still open on upgraded pods. The RS256 mcp_session_token_signing path correctly gets no legacy key. FIPS mode correctly forces the fallback off.

Earlier findings

  • Default-on vs. opt-in mismatch (b3029712…): resolved. The PR body now says the window is on by default and is closed with =false. The docstrings at bridge_credentials.py:70 and session_credentials.py:68 now say "default-on" too.
  • Rolling-upgrade finding (f9e23d87… / e58ad423…): still open. The code is unchanged and there is no recorded decision or approval. The PR body still says nothing about mixed-version fleets. I re-verified it by running code, so it is reported again below.

What I ran

  • The five affected unit suites (bridge credentials, session credentials, session token, envelope, and the gateway DCR flow): 410 passed.
  • A direct reproduction of the new→old incompatibility.

I did not build a live base-vs-head proxy A/B with Postgres. No rig was available in this sandbox, so the breaking scenario was reproduced at the product-function level rather than over HTTP.

Breaking-change marker

This is an observable compatibility change: tokens minted by the new release are rejected by the previous release. The PR title feat(mcp): … has no ! marker.

Checks and execution details
  • Passed · Affected unit suites (test_bridge_credentials, test_session_credentials, test_session_token, test_envelope, test_gateway_dcr_flow) (optional): uv run --no-sync pytest on the five files: 410 passed in 24.9s, after uv sync --frozen --all-extras.
  • Passed · Dependency graph of changed key/open symbols (required): Grepped every caller of the re-keyed and open helpers across litellm/ and enterprise/. Every read site gets legacy_keys, and the RS256 path is excluded. Mint sites use only HKDF.
  • Passed · New-mint vs old-release verify reproduction (required): A head-minted HKDF refresh token opened under the base scrypt key returns session_bad_signature, which confirms the rolling-deploy break.
  • Not run · Live base-vs-head proxy A/B with Postgres (optional): No proxy, Postgres or credentials rig was available in this sandbox. The incompatibility was reproduced at the function level instead.

View review · Reviewed a806e94246e9

litereview flagged that the session/bridge docstrings still called the
grace window opt-in after the default flipped on; align them with the
LITELLM_MCP_LEGACY_KDF_GRACE=false opt-out semantics.
@yucheng-berri

Copy link
Copy Markdown
Contributor

@litereview full

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

…lt-on grace window

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@yucheng-berri

Copy link
Copy Markdown
Contributor

@litereview full

dklen=_DERIVED_KEY_BYTES,
).hex()
return SessionKeys(signing_key=SecretStr(hkdf_sha256(master_key, _SESSION_SIGNING_KEY_DOMAIN)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Low · Rolling upgrade: pods still on the old release reject HKDF-minted tokens, so clients can lose their session

The new release starts minting with HKDF straight away:

  • envelope_keys_from_master_key and session_keys_from_master_key now return hkdf_sha256(...).
  • Minting in bridge_token_flow.py:802 and the session issuer in gateway_dcr_flow.py:1179/1415 use those keys.

The fallback added here only works one way: new code can open old scrypt tokens. Pods still running the base release only know the scrypt key and cannot open an HKDF token.

Failure scenario: a multi-replica proxy behind a load balancer is mid rolling upgrade.

  1. A gateway DCR client (or the Claude Code CLI) refreshes on an upgraded pod.
  2. That pod burns the old refresh token's jti and returns a new access token and refresh token signed with HKDF.
  3. The client's next MCP call or refresh lands on an old pod.
  4. The old pod sees a bad signature and answers 401 invalid_token or 400 invalid_grant.
  5. The old refresh token is already burned, so the client is left with nothing it can use on the old pods. It has to re-authenticate unless retries happen to land on new pods.

The same applies to bridge oauth_delegate envelopes minted by new pods and presented at old pods. The codebase already designs for mixed-version fleets (see the rolling-deploy note in _seal, gateway_dcr_flow.py), but this rotation does not.

Suggested fix: split the rollout. Release N accepts both HKDF and scrypt keys but still mints with scrypt; release N+1 switches minting to HKDF. Alternatively, add an env toggle for the mint key, or at least document that this upgrade needs a full stop and restart, or should be done in a quiet window, for MCP gateway users.

Evidence

session_credentials.py:63: return SessionKeys(signing_key=SecretStr(hkdf_sha256(master_key, _SESSION_SIGNING_KEY_DOMAIN))), so all minting switches to HKDF immediately

bridge_credentials.py envelope_keys_from_master_key now returns HKDF keys, and that is what bridge_token_flow.py:802 mints with

The fallback (open_session_credential_with_legacy, _open_envelope_with_fallback) only lets new code read old tokens; the base release has no HKDF read path

Latest summary by full · View this review · Reviewed b7955aa07fc0

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Known and intended per LIT-8426: new release mints HKDF at once, grace only reads old tokens. Mixed-fleet 401s last only the rollout, clients re-auth

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

…sha256

# Conflicts:
#	tests/unit/proxy/_experimental/mcp_server/test_gateway_dcr_flow.py
@yucheng-berri

Copy link
Copy Markdown
Contributor

@litereview full

@yucheng-berri

Copy link
Copy Markdown
Contributor

bugbot run

@greptile-apps

greptile-apps Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

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

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@yucheng-berri

Copy link
Copy Markdown
Contributor

bugbot run

@yucheng-berri

Copy link
Copy Markdown
Contributor

@litereview full

@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 a806e94. Configure here.

maxmem=_SCRYPT_MAXMEM,
dklen=_DERIVED_KEY_BYTES,
).hex()
return SessionKeys(signing_key=SecretStr(hkdf_sha256(master_key, _SESSION_SIGNING_KEY_DOMAIN)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Medium · Rolling deploy: HKDF-minted tokens from new pods are rejected by pods still on the old release, and the used refresh token is already burned

The grace window only works in one direction. New pods can open old scrypt tokens, but they mint only with HKDF:

  • session_keys_from_master_key at session_credentials.py:62 returns only the HKDF key.
  • envelope_keys_from_master_key does the same for envelopes.
  • The minters use these keys: bridge_token_flow.py:812, plus _session_token_pair and mint_session_refresh_token through resolve_session_signing (gateway_dcr_flow.py:379, 1259, 1497).

Pods still on the base release can only verify with scrypt.

Failure scenario

A multi-replica proxy behind a load balancer, partway through a rolling upgrade:

  1. The Claude Code CLI (/claude_code_gateway/oauth/token) or a DCR client (/mcp/token) sends grant_type=refresh_token, and the request lands on an upgraded pod.
  2. That pod claims the old refresh jti (single-use) and returns an HKDF-signed access/refresh pair.
  3. The next POST /mcp or refresh lands on an old pod.
  4. The old pod answers 401 invalid_token or 400 invalid_grant (bad signature).
  5. The previous refresh token is already burned, so the client holds nothing the old pods accept and has to re-authenticate.

Bridge oauth_delegate envelopes minted on new pods fail the same way on old pods.

The codebase explicitly designs sealed artifacts to survive mixed-version fleets (see the _seal docstring at gateway_dcr_flow.py:397-403). This rotation breaks that property, and the PR body does not mention it.

Fix options

  • Two-step rollout (preferred): release N reads both keys but still mints with scrypt (outside FIPS); release N+1 switches minting to HKDF.
  • Mint-key toggle: add a toggle that selects the mint key.
  • At minimum: document that MCP gateway deployments need a stop-the-world upgrade, and record who approved shipping it that way.
Evidence

session_credentials.py:62: return SessionKeys(signing_key=SecretStr(hkdf_sha256(master_key, _SESSION_SIGNING_KEY_DOMAIN))) is the only key resolve_session_signing gives the minters.

bridge_credentials.py:61-64: envelope_keys_from_master_key returns HKDF keys, which bridge_token_flow.py:812 mints with.

Executed: I minted a refresh token with session_keys_from_master_key('sk-test') (head) and opened it with the base-release scrypt key legacy_scrypt(mk, b'litellm-mcp-gateway:session-signing:'). Output: old-release open of head-minted refresh: tag='session_bad_signature'.

The fallbacks _open_envelope_with_fallback (bridge_credentials.py:138-147) and open_session_credential_with_legacy (session_credentials.py:283-298) only let new code read old tokens.

Latest summary by full · View this review · Reviewed a806e94246e9

This branch was successfully deployed

No deployments
e2e-changed — a806e942 Deployed Oct 15, 2026 by devin-ai-integration[bot] via oauth #5190
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