## 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>
headroom-oauth2
Generic OAuth2 client-credentials upstream-auth extension for the Headroom proxy.
When Headroom routes to an OpenAI-compatible backend that is protected by an
OAuth2 client-credentials flow (enterprise AI gateways, Azure AD / Entra, Okta,
Auth0, Keycloak, Cognito, …), this extension mints a bearer token from a
configurable token endpoint, caches + refreshes it (single-flight), and injects
Authorization: Bearer <token> on each upstream request. Optional static upstream
headers are sent via litellm. Fully vendor-neutral — no provider is hard-coded.
It plugs into Headroom's public headroom.proxy_extension entry-point seam, so it
is fully out-of-tree and opt-in.
Install & enable
pip install headroom-oauth2
headroom proxy --backend litellm-openai --proxy-extension oauth2
Configure (env; no-op unless HEADROOM_OAUTH2_TOKEN_URL is set)
| Env | Meaning |
|---|---|
HEADROOM_OAUTH2_TOKEN_URL |
token endpoint (client_credentials grant) |
HEADROOM_OAUTH2_CLIENT_ID / _CLIENT_SECRET |
credentials (secrets) |
HEADROOM_OAUTH2_SCOPES |
space/comma-separated scopes |
HEADROOM_OAUTH2_AUDIENCE |
optional audience |
HEADROOM_OAUTH2_GRANT_TYPE |
default client_credentials |
HEADROOM_OAUTH2_AUTH_STYLE |
post (form creds) or basic (HTTP Basic) |
HEADROOM_OAUTH2_HEADERS |
static upstream headers, K=V,K2=V2 |
Tokens are minted with the standard library (urllib, system cert store), which
works behind corporate SSL-inspection where bundled-root TLS stacks fail.
Effective backends: the injected bearer reaches the upstream only for OpenAI-compatible /
passthrough litellm providers. bedrock / vertex / sagemaker authenticate from env and
ignore it, so this extension is a no-op there (it logs a warning at startup).
Transport: token_url must be https (loopback http is allowed for tests; set
HEADROOM_OAUTH2_ALLOW_INSECURE=1 to override). Tokens are minted with the standard library
(urllib, system cert store), so a corporate-injected CA is trusted without bundling roots.
Startup: with HEADROOM_OAUTH2_TOKEN_URL set but the rest of the config invalid (non-https
token URL, missing client id/secret, unparseable TIMEOUT/SKEW), the proxy refuses to
start rather than running without the middleware and relaying the client's own Authorization
upstream. The extension marks its install() fail_closed for that; a core too old to honour
the marker logs a warning and starts without it.
What gets the upstream bearer
The minted token is injected only on requests that go upstream. Routes the
proxy answers itself — /health, /livez, /readyz, /stats*, /metrics,
/quota, /settings*, /dashboard*, /admin/*, /debug/*, /v1/compress*,
/v1/usage, /v1/retrieve*, /v1/telemetry*, /v1/toin*, /v1/feedback*,
and any extension route under /ext/ — are passed through untouched, so an
unreachable IdP never turns a health probe into a 502 and management calls never
cost a token mint. A /p/<project>/ base-URL prefix is stripped before the
check.
Requires headroom-ai ≥ 0.40, where extension middleware runs inside the
proxy's HEADROOM_PROXY_TOKEN gate: clients may then authenticate with
Authorization: Bearer <proxy token> and the gate checks it before this
extension replaces it with the upstream bearer.