Repository navigation
feat(mcp): derive bridge and session keys with HKDF-SHA256 behind a legacy grace window - #42917
devin-ai-integration[bot] wants to merge 19 commits into
Conversation
…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>
…into litellm_mcp_kdf_hkdf_sha256
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>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
bugbot run |
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
|
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>
|
bugbot run |
…sha256 # Conflicts: # tests/integration/_support/process.py # tests/unit/proxy/common_utils/test_fips.py
|
@greptileai review latest head |
|
bugbot run |
|
@greptileai review |
…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.
|
@litereview full |
|
bugbot run |
✅ fullScope: full · Full PR review. Completed · Some checks not run. Verdict: one actionable defect remains, the rolling-upgrade breakI mapped every caller of the re-keyed symbols:
Every read site now receives the legacy keys:
So pre-upgrade scrypt tokens still open on upgraded pods. The RS256 Earlier findings
What I ran
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 markerThis is an observable compatibility change: tokens minted by the new release are rejected by the previous release. The PR title
Checks and execution details
View review · Reviewed |
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.
|
@litereview full |
|
bugbot run |
…lt-on grace window Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
@litereview full |
| dklen=_DERIVED_KEY_BYTES, | ||
| ).hex() | ||
| return SessionKeys(signing_key=SecretStr(hkdf_sha256(master_key, _SESSION_SIGNING_KEY_DOMAIN))) | ||
|
|
There was a problem hiding this comment.
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_keyandsession_keys_from_master_keynow returnhkdf_sha256(...).- Minting in
bridge_token_flow.py:802and the session issuer ingateway_dcr_flow.py:1179/1415use 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.
- A gateway DCR client (or the Claude Code CLI) refreshes on an upgraded pod.
- That pod burns the old refresh token's
jtiand returns a new access token and refresh token signed with HKDF. - The client's next MCP call or refresh lands on an old pod.
- The old pod sees a bad signature and answers 401
invalid_tokenor 400invalid_grant. - 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
There was a problem hiding this comment.
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
|
bugbot run |
…sha256 # Conflicts: # tests/unit/proxy/_experimental/mcp_server/test_gateway_dcr_flow.py
|
@litereview full |
|
bugbot run |
|
Automatic reviews are disabled for this repository. |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
|
@litereview full |
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 a806e94. Configure here.
| maxmem=_SCRYPT_MAXMEM, | ||
| dklen=_DERIVED_KEY_BYTES, | ||
| ).hex() | ||
| return SessionKeys(signing_key=SecretStr(hkdf_sha256(master_key, _SESSION_SIGNING_KEY_DOMAIN))) |
There was a problem hiding this comment.
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_keyatsession_credentials.py:62returns only the HKDF key.envelope_keys_from_master_keydoes the same for envelopes.- The minters use these keys:
bridge_token_flow.py:812, plus_session_token_pairandmint_session_refresh_tokenthroughresolve_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:
- The Claude Code CLI (
/claude_code_gateway/oauth/token) or a DCR client (/mcp/token) sendsgrant_type=refresh_token, and the request lands on an upgraded pod. - That pod claims the old refresh
jti(single-use) and returns an HKDF-signed access/refresh pair. - The next
POST /mcpor refresh lands on an old pod. - The old pod answers 401
invalid_tokenor 400invalid_grant(bad signature). - 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
TLDR
Problem this solves:
How it solves it:
infoLITELLM_MCP_LEGACY_KDF_GRACEis set tofalse/0/no/offLITELLM_FIPS_MODE=true; mint always uses the HKDF keyrefresh_proxy_credentialon/claude_code_gateway/oauth/token) is wired into the same grace windowDepends on #42700 (
is_fips_mode), which has landed onmainand is merged into this branch, so the diff is now only the MCP filesThe 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
Authorization: Bearer <envelope issued before the upgrade>invalid_token, so the client must go through the OAuth flow again immediatelyAuthorization: Bearer llm_session_...issued before the upgrade and also gets 401After: a one release grace window is on by default, existing tokens keep working, and new tokens use the FIPS approved key
LITELLM_MCP_LEGACY_KDF_GRACE=falsenext release; envelopes and session tokens issued before the upgrade then answer 401 and clients re-authenticateLITELLM_FIPS_MODE=truethe grace variable is ignored and only HKDF keyed tokens openLinear ticket
Resolves LIT-8426
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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@greptileaito 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 commitc0663d52025d1f7ee3651045a30174ea9c142c40where envelope and session keys are derived with scrypt; head runsa806e94246e9b66fe88db61cf2884dfc96a0ddcfwhere they are derived with HKDF-SHA256 and the legacy scrypt grace window is ON BY DEFAULT (a806e94246is a pyright narrowing commit on top of4aa0bc024fwith no runtime change;4aa0bc024fis a merge oforigin/maininto the branch, product code for this change unchanged since3d589dc35bflipped the default). OnlyLITELLM_MCP_LEGACY_KDF_GRACEset tofalse/0/no/offdisables the window, andLITELLM_FIPS_MODE=trueforces it off regardlessSetup, run once against each leg (identical commands, only the port changes):
Response:
{"server_id":"e819ab98-..."}on 4101,{"server_id":"49b15187-..."}on 4100Session tokens are minted the same way via
SessionKeys(signing_key=...)+mint_session_token(SessionPrincipal(user_id=<user>, client_id="dcr-integration"), keys, now)with thelitellm-mcp-gateway:session-signing:labeltools/listNote: the auth-time body pre-read rejects curl's default
application/x-www-form-urlencodedcontent type with 400 "Invalid form payload" on both legs, soContent-Type: application/jsonis sent explicitly; the tokens, headers and bodies are otherwise identical to the earlier proofsBoth legs run with
general_settings.enable_claude_code_gateway: truevia per-leg scratch configsproxy_config_head_claude.yamlandproxy_config_base_claude.yamlin this directory (copies oftests/integration/proxy_config.yamlplus the flag) so the/claude_code_gateway/oauth/tokenroute exists for the refresh-grant row; the shared test config is untouchedThe Claude Code refresh grant row mints a
proxy_api-audience session refresh token forclient_id=claude_codeunderlegacy_scryptviamint_session_refresh_token, then posts it form-encoded (the endpoint parsesrequest.form()):POST /claude_code_gateway/oauth/tokenwithgrant_type=refresh_token&refresh_token=<token>. The rotated refresh token is single-use, so each leg gets a fresh mintBefore (c0663d5)
Base proxy on http://127.0.0.1:4101, scrypt-only KDF, no
LITELLM_MCP_LEGACY_KDF_GRACEanywhere in the codecase: bridge envelope minted with HKDF keys
hkdf_sha256and presented it toPOST /proof_4101/mcp401 Unauthorized,www-authenticate: Bearer error="invalid_token", body{"detail":"Invalid or expired credential"}(captureenv_hkdf_4101_a806.txt)case: bridge envelope minted with legacy scrypt keys
legacy_scrypt(the pre-rotation derivation) and presented it toPOST /proof_4101/mcp200 OK, SSEtoolsframe with"server_outcomes":{"proof_4101":{"status":"ok","tool_count":3}}(captureenv_scrypt_4101_a806.txt)case: gateway session token minted with HKDF key
hkdf_sha256and presented it toPOST /mcp401 Unauthorized, body{"detail":{"error":"authentication_required","message":"Authenticate with the gateway to use the MCP endpoint."}}(capturesess_hkdf_4101_a806.txt)case: gateway session token minted with legacy scrypt key
legacy_scryptand presented it toPOST /mcp200 OK, SSE frame{"jsonrpc":"2.0","id":1,"result":{"tools":[]}}(capturesess_scrypt_4101_a806.txt)case: Claude Code refresh grant with a legacy scrypt session refresh token
proxy_apisession refresh token forclaude_codeunderlegacy_scryptand postedgrant_type=refresh_tokenform-encoded toPOST /claude_code_gateway/oauth/token200 OKwithaccess_token(litellm_login_...) and a rotatedrefresh_token(captureccrefresh_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_GRACEin its environment)case: bridge envelope minted with HKDF keys
POST /proof_4100/mcp200 OK, SSEtoolsframe with"server_outcomes":{"proof_4100":{"status":"ok","tool_count":3}}(captureenv_hkdf_4100_a806.txt)case: bridge envelope minted with legacy scrypt keys, no grace variable set
legacy_scrypt, same curl200 OKwith the SSEtoolslist: the default-on window admits legacy material with the variable unset (captureenv_scrypt_4100_a806.txt)case: bridge envelope minted with legacy scrypt keys, grace explicitly disabled
LITELLM_MCP_LEGACY_KDF_GRACE=false(logproxy_nograce_a806.log)POST /proof_4100/mcp401 Unauthorized,www-authenticate: Bearer error="invalid_token"(captureenv_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
LITELLM_MCP_LEGACY_KDF_GRACE=yes(logproxy_yes_a806.log)200 OK: onlyfalse/0/no/offdisable the window,yeskeeps it on (captureenv_scrypt_4100_yes_a806.txt)case: gateway session token minted with HKDF key
hkdf_sha256, presented toPOST /mcp200 OK, SSE frame{"jsonrpc":"2.0","id":1,"result":{"tools":[]}}(capturesess_hkdf_4100_a806.txt)case: gateway session token minted with legacy scrypt key, no grace variable set
legacy_scrypt, presented toPOST /mcp200 OK, SSE frame{"jsonrpc":"2.0","id":1,"result":{"tools":[]}}(capturesess_scrypt_4100_a806.txt)case: gateway session token minted with legacy scrypt key, grace explicitly disabled and
yesLITELLM_MCP_LEGACY_KDF_GRACE=falsethe same scrypt session token answered401 Unauthorizedwith theauthentication_requiredbody (capturesess_scrypt_4100_nograce_a806.txt)LITELLM_MCP_LEGACY_KDF_GRACE=yesit answered200 OK(capturesess_scrypt_4100_yes_a806.txt)case: Claude Code refresh grant with a legacy scrypt session refresh token
proxy_apisession refresh token forclaude_codetoPOST /claude_code_gateway/oauth/token200 OKwithaccess_token(litellm_login_...) and a rotatedrefresh_token: the default-on window coversrefresh_proxy_credentialtoo (captureccrefresh_4100_a806.txt)LITELLM_MCP_LEGACY_KDF_GRACE=falsea fresh mint of the same token observed400 Bad Request,{"error":"invalid_grant","error_description":"the refresh token is invalid for this client"}(captureccrefresh_4100_nograce_a806.txt)LITELLM_MCP_LEGACY_KDF_GRACE=yesanother fresh mint observed200 OKagain (captureccrefresh_4100_yes_a806.txt); the proxy was restarted without the var afterwardscase: FIPS mode with grace enabled
LITELLM_FIPS_MODE=trueon a spare port so the running legs were untouched (logproxy_fips_a806.log)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)/usr/lib/x86_64-linux-gnu/ossl-modules/contains onlylegacy.so), so a live 401 cannot be produced; on a real FIPS image the proxy boots andlegacy_kdf_grace_enabledreturns 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 intest_bridge_credentials.pyandtest_session_credentials.py. The same FIPS boot gate exists at base, so a FIPS attempt refuses to boot on either legSummary
GRACE=falseGRACE=yesinvalid_grantUnder FIPS the grace fallback is compiled out (
legacy_kdf_grace_enabledreturns False before the env var is even read) and on this non-FIPS boxLITELLM_FIPS_MODE=truerefuses to boot at all, so legacy material is dead either way. To retire the window an operator setsLITELLM_MCP_LEGACY_KDF_GRACE=false(or0/no/off) in the next releaseType
🆕 New Feature
Caveats (if any)
Severe
LITELLM_MCP_LEGACY_KDF_GRACE=false(or0/no/off)Medium
false/0/no/off(including unset) keeps the window onLow
Final Attestation
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(newkey_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_keysupply the old derivation unlessLITELLM_MCP_LEGACY_KDF_GRACEisfalse/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 Coderefresh_proxy_credentialall passlegacy_keysthrough 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.