mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(subscription): match the Bearer scheme case-insensitively for the Codex usage poll (RFC 7235) (#3966)
## Description
`_build_usage_headers` (in `headroom/subscription/codex_rate_limits.py`)
decides whether to fire the Codex live usage poll (`GET /wham/usage`)
that refreshes the rate-limit window shown to the user. It gates on the
inbound `Authorization` header, but checked the scheme with a
case-sensitive `startswith("Bearer ")`.
The HTTP auth-scheme token is **case-insensitive** per RFC 7235 §2.1, so
a client sending `Authorization: bearer <token>` was rejected,
`_build_usage_headers` returned `None`, and the poll was skipped — the
Codex rate-limit window was never refreshed for that session. This
matches the case-insensitive handling the proxy already applies
elsewhere (`auth_policy.classify_auth_signals`).
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- Parse the `Authorization` scheme with `partition(" ")` and compare it
case-insensitively (`scheme.lower() == "bearer"`), still requiring a
non-empty credential. The credential and the forwarded `Authorization`
header value are unchanged.
- Tests: a regression asserting a lowercase `bearer` scheme now builds
the poll headers, plus a guard test confirming a bare scheme / empty
credential / non-bearer value is still rejected.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```text
$ pytest tests/test_codex_rate_limits.py -k "lowercase_bearer or bare_scheme" -q # before fix
FAILED tests/test_codex_rate_limits.py::TestUsagePollGating::test_build_headers_accepts_lowercase_bearer_scheme
1 failed, 1 passed
$ pytest tests/test_codex_rate_limits.py -q # after fix
43 passed
$ ruff check headroom/subscription/codex_rate_limits.py tests/test_codex_rate_limits.py
All checks passed!
```
## Real Behavior Proof
- Environment: macOS (arm64), Python 3.13, local editable install
(`maturin develop --release`). Driven through the real
`_build_usage_headers` with a lowercase-scheme request.
- Exact command / steps: call `_build_usage_headers({"authorization":
"bearer <token>", "chatgpt-account-id": "acct-42"})` before and after
the patch and report whether the poll headers were built.
- Observed result: The lowercase Bearer usage-poll headers changed from
not built to built, with Authorization and ChatGPT-Account-Id preserved,
as captured below.
```text
=== BEFORE fix ===
usage-poll headers built: NO (poll skipped)
=== AFTER fix ===
usage-poll headers built: YES
Authorization: bearer eyJ.header.sig
ChatGPT-Account-Id: acct-42
```
Before the patch a valid lowercase-scheme Codex session never refreshed
its rate-limit window; after, the poll is scheduled and the
Authorization value is forwarded unchanged.
- Not tested: a live `GET /wham/usage` round-trip against ChatGPT (no
Codex OAuth session in this environment); the header-building gate was
exercised directly.
## Runtime Rollout Safety
- Rollout-managed feature(s): none — request-header gating fix for the
usage poll.
- Minimum rollout channel: n/a
- Stable/default behavior changed: only that a lowercase/other-cased
`Bearer` scheme now triggers the poll as an exact-cased `Bearer` already
did.
- Kill switch / disable path: n/a
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this commit.
## 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
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`
## Additional Notes
`mypy` not run locally (not set up in this environment); `ruff
check`/`ruff format` are clean. No new dependencies. Part of the same
RFC 7235 scheme-casing class the proxy already handles in `auth_policy`;
this fixes the Codex usage-poll gate.
<!-- devin-review-badge-begin -->
---
<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3966"
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: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
@@ -423,7 +423,12 @@ def _build_usage_headers(request_headers: dict[str, str]) -> dict[str, str] | No
|
||||
"""
|
||||
lower = {str(k).lower(): v for k, v in request_headers.items()}
|
||||
auth = str(lower.get("authorization", ""))
|
||||
if not auth.startswith("Bearer ") or not auth[len("Bearer ") :].strip():
|
||||
# The auth-scheme token is case-insensitive per RFC 7235 2.1, so a client
|
||||
# sending "authorization: bearer <token>" must be recognized the same as
|
||||
# "Bearer <token>". A case-sensitive check skipped the usage poll for such
|
||||
# requests, so the Codex rate-limit window was never refreshed for them.
|
||||
scheme, sep, credentials = auth.partition(" ")
|
||||
if not sep or scheme.lower() != "bearer" or not credentials.strip():
|
||||
return None
|
||||
account_id = lower.get("chatgpt-account-id")
|
||||
if not account_id:
|
||||
|
||||
@@ -368,6 +368,28 @@ class TestUsagePollGating:
|
||||
assert headers["User-Agent"] == "codex_exec/0.139.0"
|
||||
assert headers["originator"] == "codex_exec"
|
||||
|
||||
def test_build_headers_accepts_lowercase_bearer_scheme(self):
|
||||
"""RFC 7235 2.1: the auth scheme is case-insensitive.
|
||||
|
||||
A client sending `authorization: bearer <token>` must still trigger the
|
||||
usage poll; a case-sensitive check previously returned None, so the
|
||||
Codex rate-limit window was never refreshed for such requests.
|
||||
"""
|
||||
headers = _build_usage_headers(
|
||||
{
|
||||
"authorization": "bearer abc.def.ghi",
|
||||
"chatgpt-account-id": "acct-1",
|
||||
}
|
||||
)
|
||||
assert headers is not None
|
||||
assert headers["Authorization"] == "bearer abc.def.ghi"
|
||||
assert headers["ChatGPT-Account-Id"] == "acct-1"
|
||||
|
||||
def test_build_headers_still_rejects_a_bare_scheme_or_non_bearer(self):
|
||||
assert _build_usage_headers({"authorization": "Bearer", "chatgpt-account-id": "a"}) is None
|
||||
assert _build_usage_headers({"authorization": "bearer ", "chatgpt-account-id": "a"}) is None
|
||||
assert _build_usage_headers({"authorization": "sk-live", "chatgpt-account-id": "a"}) is None
|
||||
|
||||
def test_try_begin_poll_throttles(self):
|
||||
state = CodexRateLimitState()
|
||||
assert state._try_begin_poll(60.0) is True
|
||||
|
||||
Reference in New Issue
Block a user