mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(oauth2): stop following redirects from the token endpoint (#4849)
## Description
`OAuth2ClientCredentials._mint` (headroom-oauth2 extension) used plain
`urllib.request.urlopen`. For the token POST, urllib follows a
301/302/303 as a GET to the `Location` URL. It re-sends the request
headers, including `Authorization: Basic <client_id:client_secret>` when
`auth_style="basic"`, and then uses whatever `access_token` that host
returns as the upstream bearer. The https/loopback check only looks at
the configured `token_url`, not at a redirect target.
The token request now goes through an opener whose redirect handler does
not follow redirects. A 30x becomes an `HTTPError`, which the existing
handler turns into `OAuth2Error("token endpoint returned HTTP 30x")`.
The response body is still drained and never surfaced. 307/308 on a POST
already raised before. Standard library only; no new dependency.
Behaviour change for users: a token endpoint that answers with a
redirect now fails to mint, and the error names the status code. Set
`HEADROOM_OAUTH2_TOKEN_URL` to the final URL instead.
Fix adapted from a proposal by HetCreep.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- `plugins/headroom-oauth2/src/headroom_oauth2/provider.py`: adds
`_RefuseRedirect` (an `HTTPRedirectHandler` whose `redirect_request`
returns `None`) and `_open()`. `_mint` calls `_open()`. The opener is
built per mint, so proxy env vars are read at call time, as with
`urlopen`.
- `plugins/headroom-oauth2/tests/test_oauth2.py`: parametrised test over
301/302/303/307/308 × basic/post with real local HTTP servers. Each case
checks that minting raises, that the redirect target is never contacted,
and that nothing is cached. The existing drain-failure test now patches
`_open`.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`). The plugin is outside
`mypy headroom`. Run on the file directly, it reports only the 2
untyped-def errors already on main (`__init__`, `_mint`); the new code
is fully annotated.
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```text
# plugin tests against origin/main (c21b0813)
$ cd plugins/headroom-oauth2 && PYTHONPATH=src pytest tests
FAILED tests/test_oauth2.py::test_error_body_drain_failure_is_sanitized (patch target _open does not exist on main)
FAILED tests/test_oauth2.py::test_token_endpoint_redirect_is_not_followed[basic-301]
FAILED tests/test_oauth2.py::test_token_endpoint_redirect_is_not_followed[basic-302]
FAILED tests/test_oauth2.py::test_token_endpoint_redirect_is_not_followed[basic-303]
FAILED tests/test_oauth2.py::test_token_endpoint_redirect_is_not_followed[post-301]
FAILED tests/test_oauth2.py::test_token_endpoint_redirect_is_not_followed[post-302]
FAILED tests/test_oauth2.py::test_token_endpoint_redirect_is_not_followed[post-303]
======================== 7 failed, 75 passed in 22.78s =========================
# this branch
$ cd plugins/headroom-oauth2 && PYTHONPATH=src pytest tests
============================= 82 passed in 32.65s ==============================
$ ruff check src tests && ruff format --check src tests (0.17.3): All checks passed!
```
## Real Behavior Proof
- Environment: macOS, Python 3.12. Two local `http.server` listeners: a
token endpoint that answers POST with `302 Location:
http://127.0.0.1:<other>/collect`, and a second server that records
requests and returns `{"access_token": "FROM-COLLECTOR"}`.
- Exact command / steps: `OAuth2ClientCredentials(token_url=<first>,
client_id="demo-id", client_secret="demo-secret",
auth_style=...).token()` for `basic` and `post`.
- Observed result:
```text
origin/main:
basic token(): FROM-COLLECTOR | second server saw: [('GET', '/collect', 'Basic ZGVtby1pZDpkZW1vLXNlY3JldA==')]
post token(): FROM-COLLECTOR | second server saw: [('GET', '/collect', None)]
this branch:
basic token(): raised OAuth2Error: token endpoint returned HTTP 302 | second server saw: []
post token(): raised OAuth2Error: token endpoint returned HTTP 302 | second server saw: []
```
- Not tested: a real IdP.
## Runtime Rollout Safety
- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: see Description
- Kill switch / disable path: none needed
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this PR
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)
## Screenshots (if applicable)
N/A
## Additional Notes
No CI workflow runs the headroom-oauth2 plugin tests; they were run
locally as shown. The plugin version and its CHANGELOG are unchanged; a
maintainer may want to bump to 0.2.1 at release.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- devin-review-badge-begin -->
---
<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4849"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
JerrettDavis
parent
5f82080329
commit
02dfdd8f89
@@ -15,6 +15,8 @@ import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from contextlib import suppress
|
||||
from http.client import HTTPMessage
|
||||
from typing import IO, Any
|
||||
from urllib.error import HTTPError, URLError
|
||||
|
||||
log = logging.getLogger("headroom_oauth2")
|
||||
@@ -32,6 +34,30 @@ class OAuth2Error(RuntimeError):
|
||||
"""Raised when a token cannot be minted."""
|
||||
|
||||
|
||||
class _RefuseRedirect(urllib.request.HTTPRedirectHandler):
|
||||
"""Turn a token-endpoint redirect into an HTTPError instead of following it.
|
||||
|
||||
For a POST, urllib follows 301/302/303 as a GET to whatever ``Location`` names,
|
||||
re-sending the Basic ``Authorization`` (client id and secret), and then takes the
|
||||
token from that response. The https/loopback check only covers ``token_url``.
|
||||
"""
|
||||
|
||||
def redirect_request(
|
||||
self,
|
||||
req: urllib.request.Request,
|
||||
fp: IO[bytes],
|
||||
code: int,
|
||||
msg: str,
|
||||
headers: HTTPMessage,
|
||||
newurl: str,
|
||||
) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def _open(req: urllib.request.Request, timeout: float) -> Any:
|
||||
return urllib.request.build_opener(_RefuseRedirect).open(req, timeout=timeout)
|
||||
|
||||
|
||||
class OAuth2ClientCredentials:
|
||||
"""Mints and caches an OAuth2 client-credentials bearer (RFC 6749 section 4.4).
|
||||
|
||||
@@ -126,7 +152,7 @@ class OAuth2ClientCredentials:
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
with _open(req, self.timeout) as resp:
|
||||
payload = json.load(resp)
|
||||
except HTTPError as e:
|
||||
with suppress(Exception):
|
||||
|
||||
@@ -5,6 +5,7 @@ import logging
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
from typing import ClassVar
|
||||
from urllib.error import HTTPError
|
||||
|
||||
import pytest
|
||||
@@ -171,7 +172,7 @@ def test_error_body_drain_failure_is_sanitized(monkeypatch, caplog):
|
||||
def fail(*_args, **_kwargs):
|
||||
raise _UnreadableHTTPError("https://idp.example/token", 503, "unavailable", {}, None)
|
||||
|
||||
monkeypatch.setattr("urllib.request.urlopen", fail)
|
||||
monkeypatch.setattr("headroom_oauth2.provider._open", fail)
|
||||
caplog.set_level(logging.DEBUG, logger="headroom_oauth2")
|
||||
p = OAuth2ClientCredentials(
|
||||
token_url="https://idp.example/token", client_id="c", client_secret="s"
|
||||
@@ -570,3 +571,60 @@ def test_install_handles_invalid_litellm_headers(monkeypatch, caplog):
|
||||
|
||||
install(App(), _cfg("litellm-openai"))
|
||||
assert "could not set litellm.headers" in caplog.text
|
||||
|
||||
|
||||
class _Sink(BaseHTTPRequestHandler):
|
||||
seen: ClassVar[list] = []
|
||||
|
||||
def do_POST(self):
|
||||
_Sink.seen.append((self.path, self.headers.get("authorization")))
|
||||
body = json.dumps({"access_token": "FROM-REDIRECT", "expires_in": 3600}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("content-length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
do_GET = do_POST
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
|
||||
def _serve(handler):
|
||||
srv = HTTPServer(("127.0.0.1", 0), handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
return srv
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code", [301, 302, 303, 307, 308])
|
||||
@pytest.mark.parametrize("style", ["basic", "post"])
|
||||
def test_token_endpoint_redirect_is_not_followed(code, style):
|
||||
_Sink.seen = []
|
||||
sink = _serve(_Sink)
|
||||
target = f"http://127.0.0.1:{sink.server_address[1]}/elsewhere"
|
||||
|
||||
class _Redirecting(BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
self.send_response(code)
|
||||
self.send_header("location", target)
|
||||
self.send_header("content-length", "0")
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
token_endpoint = _serve(_Redirecting)
|
||||
try:
|
||||
p = OAuth2ClientCredentials(
|
||||
token_url=f"http://127.0.0.1:{token_endpoint.server_address[1]}/token",
|
||||
client_id="cid",
|
||||
client_secret="csec",
|
||||
auth_style=style,
|
||||
)
|
||||
with pytest.raises(OAuth2Error, match=f"HTTP {code}"):
|
||||
p.token()
|
||||
assert _Sink.seen == [] # the redirect target was never contacted
|
||||
assert p.cached() is None
|
||||
finally:
|
||||
token_endpoint.shutdown()
|
||||
sink.shutdown()
|
||||
|
||||
Reference in New Issue
Block a user