The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(cli): pin PKCE discovery to the typed proxy and ignore foreign sibling records
mateo-berri912206832c8a
diff --git a/litellm/proxy/client/cli/commands/pkce_login.py b/litellm/proxy/client/cli/commands/pkce_login.pyindex 6d6646a886c..2d8d5bf68bb 100644--- a/litellm/proxy/client/cli/commands/pkce_login.py+++ b/litellm/proxy/client/cli/commands/pkce_login.py@@ -200,9 +200,49 @@ def discover_cli_auth(base_url: str, http: Http) -> CliAuthContract | PkceFailurreturn PkceFailure(f"{url} returned an unsupported discovery document: {exc}")if "S256" not in contract.code_challenge_methods_supported:return PkceFailure("the proxy does not support PKCE S256")+ if _canonical_url(contract.issuer) != _canonical_url(base_url):+ return PkceFailure(f"{url} is issued for {contract.issuer}, not {base_url}; pass that address as --base-url")+ foreign: Final = _endpoints_outside(contract, _origin(base_url))+ if foreign:+ return PkceFailure(+ f"{url} names endpoints outside {base_url} ({', '.join(foreign)}); refusing to send credentials there"+ )return contract+def _endpoints_outside(contract: CliAuthContract, origin: str | None) -> tuple[str, ...]:+ endpoints: Final = (+ contract.authorization_endpoint,+ contract.token_endpoint,+ contract.registration_endpoint,+ contract.revocation_endpoint,+ contract.resource,+ )+ return tuple(endpoint for endpoint in endpoints if origin is None or _origin(endpoint) != origin)+++def _origin(url: str) -> str | None:+ """``scheme://host:port`` with the default port made explicit, so the same server spelled+ two ways (``https://llm.example.com`` and ``https://LLM.example.com:443/``) compares equal+ and two different servers never do."""+ parsed: Final = urlparse(url)+ try:+ port: Final = parsed.port+ except ValueError:+ return None+ if parsed.scheme not in ("http", "https") or not parsed.hostname:+ return None+ host: Final = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname+ return f"{parsed.scheme}://{host}:{port or (443 if parsed.scheme == 'https' else 80)}"+++def _canonical_url(url: str) -> str | None:+ """The origin plus the path with its trailing slash dropped: the RFC 8414 section 3.3+ identity check, so a document can only ever be accepted for the proxy it was fetched from."""+ origin: Final = _origin(url)+ return None if origin is None else f"{origin}{urlparse(url).path.rstrip('/')}"++class _ClientRegistration(TypedDict):client_name: ReadOnly[str]redirect_uris: ReadOnly[tuple[str, ...]]@@ -423,7 +463,7 @@ def fresh_api_key(on file. The rotated pair is saved before the new key is returned, so a crash afterthis point never strands the CLI with a burned refresh token. A refresh that failsreads the record again, because a sibling ``lite`` process may have rotated the pair- first, in which case the key it saved is the live one. A record without+ first, in which case the key it saved for this same proxy is the live one. A record without``expires_at`` (the classic ``lite login`` credential) is returned as stored."""key: Final = token_data.get("key")if not isinstance(key, str) or not key:@@ -439,14 +479,25 @@ def fresh_api_key(return still_validrefreshed: Final = refresh_credential(*refresh_inputs, http=http, now=now)if isinstance(refreshed, PkceFailure):- return _key_rotated_by_a_sibling(reload(), token_data.get("refresh_token")) or still_valid+ return _key_rotated_by_a_sibling(reload(), token_data, now()) or still_validbase_url: Final = token_data.get("base_url")save(pkce_token_record(base_url if isinstance(base_url, str) else "", refreshed))return refreshed.access_token-def _key_rotated_by_a_sibling(record: Mapping[str, object] | None, sent_refresh_token: object) -> str | None:- if record is None or record.get("refresh_token") == sent_refresh_token:+def _key_rotated_by_a_sibling(+ record: Mapping[str, object] | None, token_data: Mapping[str, object], now: float+) -> str | None:+ """The key a sibling process saved, but only when it continues this very credential:+ same proxy, same token endpoint, same resource, and not yet expired. A concurrent+ ``lite login`` against a different proxy replaces the same file, and its key must never+ be sent to this one."""+ if record is None or record.get("refresh_token") == token_data.get("refresh_token"):+ return None+ if any(record.get(field) != token_data.get(field) for field in ("base_url", "token_endpoint", "resource")):+ return None+ expires_at: Final = record.get("expires_at")+ if not isinstance(expires_at, (int, float)) or now >= expires_at:return Nonekey: Final = record.get("key")return key if isinstance(key, str) and key else Nonediff --git a/tests/test_litellm/proxy/client/cli/test_pkce_login.py b/tests/test_litellm/proxy/client/cli/test_pkce_login.pyindex 355d1c39d08..39f750835df 100644--- a/tests/test_litellm/proxy/client/cli/test_pkce_login.py+++ b/tests/test_litellm/proxy/client/cli/test_pkce_login.py@@ -199,6 +199,15 @@ def test_discover_reads_the_contract_from_the_well_known_path():(_FakeResponse(200, text="<html>"), "unsupported discovery document"),(_FakeResponse(200, {**CONTRACT_DOC, "code_challenge_methods_supported": ["plain"]}), "PKCE S256"),(requests.ConnectionError("refused"), "could not reach"),+ (_FakeResponse(200, {**CONTRACT_DOC, "issuer": "https://evil.example.com"}), "is issued for https://evil"),+ (_FakeResponse(200, {**CONTRACT_DOC, "issuer": f"{BASE}/other"}), "is issued for"),+ (_FakeResponse(200, {**CONTRACT_DOC, "issuer": "http://llm.example.com"}), "is issued for"),+ (_FakeResponse(200, {**CONTRACT_DOC, "token_endpoint": "https://evil.example.com/token"}), "outside"),+ (_FakeResponse(200, {**CONTRACT_DOC, "registration_endpoint": f"{BASE}:8443/register"}), "outside"),+ (_FakeResponse(200, {**CONTRACT_DOC, "revocation_endpoint": "https://evil.example.com/revoke"}), "outside"),+ (_FakeResponse(200, {**CONTRACT_DOC, "authorization_endpoint": "http://llm.example.com/authorize"}), "outside"),+ (_FakeResponse(200, {**CONTRACT_DOC, "resource": "https://evil.example.com"}), "outside"),+ (_FakeResponse(200, {**CONTRACT_DOC, "token_endpoint": "/token"}), "outside"),],)def test_discover_failures_name_the_cause(response, expected):@@ -207,6 +216,46 @@ def test_discover_failures_name_the_cause(response, expected):assert expected in result.reason+def test_discover_refuses_endpoints_on_another_origin_and_names_each_of_them():+ doc = {**CONTRACT_DOC, "token_endpoint": "https://evil.example.com/token", "resource": "https://evil.example.com"}+ result = discover_cli_auth(BASE, _FakeHttp({("GET", DISCOVERY_URL): _FakeResponse(200, doc)}))+ assert isinstance(result, PkceFailure)+ assert "https://evil.example.com/token" in result.reason+ assert "https://evil.example.com" in result.reason+ assert "refusing to send credentials" in result.reason+++ "typed_base_url",+ ["https://LLM.example.com:443/", "https://llm.example.com", "HTTPS://llm.example.com/"],+)+def test_discover_accepts_the_same_proxy_however_the_user_spelled_it(typed_base_url):+ discovery_url = f"{typed_base_url.rstrip('/')}/.well-known/litellm-cli-auth"+ http = _FakeHttp({("GET", discovery_url): _FakeResponse(200, CONTRACT_DOC)})+ assert discover_cli_auth(typed_base_url, http) == CONTRACT+++def test_discover_accepts_a_proxy_mounted_under_a_path_only_at_that_path():+ mounted = f"{BASE}/litellm"+ doc = {+ **CONTRACT_DOC,+ "issuer": mounted,+ "authorization_endpoint": f"{mounted}/authorize",+ "token_endpoint": f"{mounted}/token",+ "registration_endpoint": f"{mounted}/register",+ "revocation_endpoint": f"{mounted}/revoke",+ "resource": mounted,+ }+ routes = {+ ("GET", f"{mounted}/.well-known/litellm-cli-auth"): _FakeResponse(200, doc),+ ("GET", DISCOVERY_URL): _FakeResponse(200, doc),+ }+ assert discover_cli_auth(f"{mounted}/", _FakeHttp(routes)) == CliAuthContract.model_validate(doc)+ rejected = discover_cli_auth(BASE, _FakeHttp(routes))+ assert isinstance(rejected, PkceFailure)+ assert f"is issued for {mounted}" in rejected.reason++def test_register_sends_a_public_loopback_client_and_returns_its_id():http = _FakeHttp({("POST", f"{BASE}/register"): _FakeResponse(201, {"client_id": "llm_dcrc_abc"})})assert register_client(CONTRACT, "http://127.0.0.1:5/callback", http) == "llm_dcrc_abc"@@ -533,6 +582,37 @@ def test_fresh_api_key_uses_a_sibling_rotation_when_its_own_refresh_loses_the_raassert saved == []+ "sibling_record",+ [+ {"base_url": "https://other.example.com", "token_endpoint": "https://other.example.com/token"},+ {"base_url": "https://other.example.com", "resource": "https://other.example.com"},+ {"base_url": "https://other.example.com"},+ {"token_endpoint": "https://other.example.com/token"},+ {"resource": "https://other.example.com"},+ {"expires_at": 999_000.0},+ {"expires_at": None},+ {"key": ""},+ ],+ ids=[+ "other-proxy",+ "other-resource-line",+ "other-base-url",+ "other-token-endpoint",+ "other-resource",+ "expired",+ "no-expiry",+ "empty-key",+ ],+)+def test_fresh_api_key_never_substitutes_a_sibling_record_for_another_proxy_or_a_dead_key(sibling_record):+ rotated = {**STORED, "key": "sk-cli-sibling", "refresh_token": "llm_srefresh_sibling", "expires_at": 1_003_600.0}+ foreign = {**rotated, **sibling_record}+ http = _FakeHttp({("POST", f"{BASE}/token"): _FakeResponse(400, {"error": "invalid_grant"})})+ assert _fresh(STORED, lambda _: None, http, reload=lambda: foreign, now=lambda: 1_000_001.0) is None+ assert _fresh(STORED, lambda _: None, http, reload=lambda: foreign, now=lambda: 999_950.0) == "sk-cli-old"++def test_fresh_api_key_without_refresh_inputs_expires_like_a_classic_key():http = _FakeHttp()no_refresh = {key: value for key, value in STORED.items() if key != "refresh_token"}