Skip to content

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]

fix(cli): never follow a redirect when posting to the proxy's OAuth endpoints

mateo-berri218a3ec3701c
diff --git a/litellm/proxy/client/cli/commands/pkce_login.py b/litellm/proxy/client/cli/commands/pkce_login.py
index 0e3b7c3271e..16d2a7b05d6 100644
--- a/litellm/proxy/client/cli/commands/pkce_login.py
+++ b/litellm/proxy/client/cli/commands/pkce_login.py
@@ -106,6 +106,7 @@ class Http(Protocol):
data: Mapping[str, str] | None = None,
json: Mapping[str, object] | None = None,
timeout: float,
+ allow_redirects: bool,
) -> requests.Response: ...
@@ -256,6 +257,17 @@ def _form(**fields: str) -> Mapping[str, str]:
return MappingProxyType(fields)
+def _refused_redirect(request_name: str, response: requests.Response) -> PkceFailure | None:
+ """Every POST to the proxy is sent with ``allow_redirects=False``: a 307 or 308 would make
+ ``requests`` replay the form, code and verifier or refresh token included, wherever ``Location``
+ points, past the origin check discovery passed."""
+ if not 300 <= response.status_code < 400:
+ return None
+ return PkceFailure(
+ f"{request_name} redirected to {response.headers.get('Location', 'another address')}; refusing to follow it"
+ )
+
+
def register_client(contract: CliAuthContract, redirect_uri: str, http: Http) -> str | PkceFailure:
registration: Final[_ClientRegistration] = {
"client_name": _CLIENT_NAME,
@@ -265,9 +277,14 @@ def register_client(contract: CliAuthContract, redirect_uri: str, http: Http) ->
"token_endpoint_auth_method": "none",
}
try:
- response: Final = http.post(contract.registration_endpoint, json=registration, timeout=_HTTP_TIMEOUT_SECONDS)
+ response: Final = http.post(
+ contract.registration_endpoint, json=registration, timeout=_HTTP_TIMEOUT_SECONDS, allow_redirects=False
+ )
except requests.RequestException as exc:
return PkceFailure(f"client registration failed: {exc}")
+ redirected: Final = _refused_redirect("client registration", response)
+ if redirected is not None:
+ return redirected
if response.status_code not in (200, 201):
return PkceFailure(f"client registration failed with {response.status_code}: {_error_detail(response)}")
try:
@@ -354,9 +371,12 @@ def _token_request(
now: Callable[[], float],
) -> PkceCredential | PkceFailure:
try:
- response: Final = http.post(token_endpoint, data=form, timeout=_HTTP_TIMEOUT_SECONDS)
+ response: Final = http.post(token_endpoint, data=form, timeout=_HTTP_TIMEOUT_SECONDS, allow_redirects=False)
except requests.RequestException as exc:
return PkceFailure(f"token request failed: {exc}")
+ redirected: Final = _refused_redirect("token request", response)
+ if redirected is not None:
+ return redirected
if response.status_code != 200:
return PkceFailure(f"token request failed with {response.status_code}: {_error_detail(response)}")
try:
@@ -382,9 +402,13 @@ def revoke_credential(revocation_endpoint: str, client_id: str, refresh_token: s
revocation_endpoint,
data=_form(token=refresh_token, token_type_hint="refresh_token", client_id=client_id),
timeout=_HTTP_TIMEOUT_SECONDS,
+ allow_redirects=False,
)
except requests.RequestException as exc:
return PkceFailure(f"revocation request failed: {exc}")
+ redirected: Final = _refused_redirect("revocation request", response)
+ if redirected is not None:
+ return redirected
if response.status_code != 200:
return PkceFailure(f"revocation failed with {response.status_code}: {_error_detail(response)}")
return None
diff --git a/tests/test_litellm/proxy/client/cli/test_auth_commands.py b/tests/test_litellm/proxy/client/cli/test_auth_commands.py
index 27568534bb6..0fc42e7158e 100644
--- a/tests/test_litellm/proxy/client/cli/test_auth_commands.py
+++ b/tests/test_litellm/proxy/client/cli/test_auth_commands.py
@@ -1178,7 +1178,7 @@ class _FakeSession:
self.response = _FakeHttpResponse(200, {})
_FakeSession.instances.append(self)
- def post(self, url, *, data=None, json=None, timeout):
+ def post(self, url, *, data=None, json=None, timeout, allow_redirects):
self.posts.append((url, data))
return self.response
diff --git a/tests/test_litellm/proxy/client/cli/test_pkce_login.py b/tests/test_litellm/proxy/client/cli/test_pkce_login.py
index db7d3c81d6c..1281de3634f 100644
--- a/tests/test_litellm/proxy/client/cli/test_pkce_login.py
+++ b/tests/test_litellm/proxy/client/cli/test_pkce_login.py
@@ -76,8 +76,9 @@ STORED = {
class _FakeResponse:
- def __init__(self, status_code, payload=None, text=""):
+ def __init__(self, status_code, payload=None, text="", headers=None):
self.status_code = status_code
+ self.headers = headers or {}
self._payload = payload
self.text = json.dumps(payload) if payload is not None else text
self.content = self.text.encode()
@@ -101,9 +102,12 @@ class _FakeHttp:
self.calls.append(("GET", url, None, None))
return self._route("GET", url, None, None)
- def post(self, url, *, data=None, json=None, timeout):
+ def post(self, url, *, data=None, json=None, timeout, allow_redirects):
self.calls.append(("POST", url, data, _wire(json)))
- return self._route("POST", url, data, json)
+ response = self._route("POST", url, data, json)
+ if allow_redirects and 300 <= response.status_code < 400:
+ return self.post(response.headers["Location"], data=data, json=json, timeout=timeout, allow_redirects=True)
+ return response
def _route(self, method, url, data, json):
handler = self.routes[(method, url)]
@@ -404,6 +408,29 @@ def test_revoke_failures_name_the_cause(response, expected):
assert expected in result.reason
[email protected]("status", [302, 307, 308])
+def test_posts_to_the_proxy_never_follow_a_redirect(status):
+ elsewhere = "https://evil.example.net/oauth"
+ http = _FakeHttp(
+ {
+ ("POST", f"{BASE}/register"): _FakeResponse(status, headers={"Location": elsewhere}),
+ ("POST", f"{BASE}/token"): _FakeResponse(status, headers={"Location": elsewhere}),
+ ("POST", f"{BASE}/revoke"): _FakeResponse(status, headers={"Location": elsewhere}),
+ ("POST", elsewhere): _FakeResponse(200, {"client_id": "llm_dcrc_evil", **TOKEN_JSON}),
+ }
+ )
+ outcomes = (
+ register_client(CONTRACT, "http://127.0.0.1:5/callback", http),
+ redeem_code(CONTRACT, "llm_dcrc_abc", "http://127.0.0.1:5/callback", "code", "verifier", http),
+ refresh_credential(f"{BASE}/token", f"{BASE}/revoke", BASE, "llm_dcrc_abc", "llm_srefresh_old", http),
+ revoke_credential(f"{BASE}/revoke", "llm_dcrc_abc", "llm_srefresh_old", http),
+ )
+ assert [type(outcome) for outcome in outcomes] == [PkceFailure] * 4
+ assert all(f"redirected to {elsewhere}; refusing to follow it" in outcome.reason for outcome in outcomes)
+ posted_to = [url for _, url, _, _ in http.calls]
+ assert posted_to == [f"{BASE}/register", f"{BASE}/token", f"{BASE}/token", f"{BASE}/revoke"]
+
+
@pytest.mark.parametrize(
"response, expected",
[