Files
headroom/tests/test_oauth_bearer_routing.py
Tejas ChopraandClaude Opus 5.5 098df1c74e refactor(proxy): deprecate is_anthropic_auth (#4083)
## Description

`headroom.proxy.helpers.is_anthropic_auth` is re-exported from
`headroom.proxy.server`, so it counts as public API. Nothing in the
product calls it. Request routing (`/v1/models`, the catch-all
passthrough, rate-limit keys) uses
`headroom.providers.registry._is_anthropic_auth` instead. That
classifier also handles a capitalised `Authorization` header and Claude
Code's user-agent. The two copies have already drifted apart, and the
tests were guarding the copy that no request reaches.

This PR deprecates `is_anthropic_auth` rather than deleting it. The
function and the `server.py` re-export stay, and calling it now emits a
`DeprecationWarning` that points at the registry classifier. The routing
unit tests are repointed at the classifier the router actually uses.

Evidence: `grep -rnw is_anthropic_auth` across `headroom`, `tests`,
`docs`, `scripts`, `crates`, `sdk`, `plugins` and the private consumer
repos. It finds only the definition, the `server.py` re-export, and
`tests/test_oauth_bearer_routing.py` / `tests/test_pr208_changes.py`.

Refs #4136

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [x] Code refactoring (no functional changes)

## Changes Made

- `headroom/proxy/helpers.py`: `is_anthropic_auth` emits
`DeprecationWarning("is_anthropic_auth is deprecated and will be removed
in a future release; request routing uses the auth classifier in
headroom.providers.registry.")` and has a `.. deprecated::` note. Its
return values are unchanged.
- `tests/test_oauth_bearer_routing.py`: the nine `TestIsAnthropicAuth`
cases now import the live classifier, and every assertion still holds. A
new case checks that a Claude Code user-agent with a gateway bearer
token routes to Anthropic.
- `tests/test_pr208_changes.py`: the duplicate six-case
`TestIsAnthropicAuth` class is replaced by one test that asserts the
deprecation warning fires.
- Use instead: nothing outside the router needs this check. Code that
does should match the router's behaviour, which lives in
`headroom.providers.registry`.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ pytest -q -p no:cacheprovider tests/test_oauth_bearer_routing.py tests/test_pr208_changes.py
============================== 64 passed in 7.43s ==============================
$ uvx ruff@0.16.8 check headroom/proxy/helpers.py tests/test_oauth_bearer_routing.py tests/test_pr208_changes.py
All checks passed!
$ python -W error::DeprecationWarning -c "import headroom.proxy.server"
(exit 0: importing the server stays quiet; only a call warns)
```

## Real Behavior Proof

- Environment: macOS, Python 3.12.13, branch checkout at ad2d2148, using
the repo .venv. A temp HOME, workspace and CODEX_HOME were used, with
offline mode on.
- Exact command / steps:
1. Ran the shared smoke harness. It starts a real proxy from this
checkout against a local fake upstream and sends one Anthropic request
(x-api-key) and one OpenAI request through the router.
2. Called the deprecated function through its `server.py` re-export,
with warnings shown: `python -W always -c "from headroom.proxy.server
import is_anthropic_auth; print(is_anthropic_auth({'x-api-key':
'k'}))"`.
- Observed result:
```text
branch: cleanup/proxy-core-a-deprecate-is-anthropic-auth @ ad2d2148
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines (<tmp>):
(smoke dir: <tmp>)
```
```text
<string>:1: DeprecationWarning: is_anthropic_auth is deprecated and will be removed in a future release; request routing uses the auth classifier in headroom.providers.registry.
True
```
- Routing is unaffected: both providers return 200, and the proxy adds
no warnings.
  - Importing through the re-export is silent.
- A call warns once, at the caller's line, and still returns the same
result.
- Two pre-existing offline-mode and Kompress-prefetch warnings are left
out of the smoke output.
- Not tested: Third-party callers of the deprecated function. They will
see the DeprecationWarning and nothing else changes for them.

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: N/A; deprecation only.
- Stable/default behavior changed: No. The function returns the same
values. Only a DeprecationWarning is added, and no product code path
calls the function.
- 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
- [ ] 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

Part of a maintainer-requested codebase cleanup (dead code, duplication,
debuggability), split into small PRs for review. It is part of
maintainer-requested cleanup #4136.

Removing the function and the `server.py` re-export is left for a later
release, after the deprecation period. mypy was not run because no
signatures changed. The function is not in the docs, so no docs change
was needed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 09:02:20 -07:00

222 lines
8.3 KiB
Python

"""Tests for OAuth Bearer token routing and auth detection."""
import httpx
from fastapi.testclient import TestClient
from headroom.providers.registry import _is_anthropic_auth as is_anthropic_auth
from headroom.proxy.server import ProxyConfig, create_app
# ---------------------------------------------------------------------------
# Unit tests: the auth classifier the router uses (providers.registry)
# ---------------------------------------------------------------------------
class TestIsAnthropicAuth:
def test_x_api_key(self):
assert is_anthropic_auth({"x-api-key": "sk-ant-api03-xxx"}) is True
def test_anthropic_version(self):
assert is_anthropic_auth({"anthropic-version": "2023-06-01"}) is True
def test_bearer_sk_ant_oat(self):
assert is_anthropic_auth({"authorization": "Bearer sk-ant-oat01-xxx"}) is True
def test_bearer_sk_ant_api(self):
"""API key prefix in Bearer header still detected as Anthropic."""
assert is_anthropic_auth({"authorization": "Bearer sk-ant-api03-xxx"}) is True
def test_bearer_openai(self):
assert is_anthropic_auth({"authorization": "Bearer sk-proj-xxx"}) is False
def test_bearer_arbitrary_uuid(self):
"""Non-Anthropic Bearer tokens don't auto-detect as Anthropic."""
assert is_anthropic_auth({"authorization": "Bearer 1a18a113-ab50-43c8"}) is False
def test_no_auth_headers(self):
assert is_anthropic_auth({}) is False
def test_anthropic_version_plus_bearer(self):
"""Claude Code sends both anthropic-version and Bearer token."""
assert (
is_anthropic_auth(
{
"anthropic-version": "2023-06-01",
"authorization": "Bearer 1a18a113-ab50-43c8",
}
)
is True
)
def test_empty_authorization(self):
assert is_anthropic_auth({"authorization": ""}) is False
def test_claude_code_user_agent_with_gateway_bearer(self):
"""Claude Code behind a gateway token is still routed to Anthropic."""
assert (
is_anthropic_auth(
{
"authorization": "Bearer 1a18a113-ab50-43c8",
"user-agent": "claude-cli/2.1.0 (external, cli)",
}
)
is True
)
# ---------------------------------------------------------------------------
# Integration tests: /v1/models routing
# ---------------------------------------------------------------------------
class FakeAsyncClient:
"""Captures outbound requests instead of making real HTTP calls."""
def __init__(self) -> None:
self.calls: list[tuple[str, str]] = []
async def request(self, method, url, **_kwargs):
self.calls.append((method, url))
return httpx.Response(200, json={"data": []})
async def aclose(self) -> None:
return None
class TestModelsRouting:
def _make_client(self):
app = create_app(ProxyConfig())
client = TestClient(app)
fake = FakeAsyncClient()
client.app.state.proxy.http_client = fake
client.app.state.proxy.ANTHROPIC_API_URL = "https://api.anthropic.test"
client.app.state.proxy.OPENAI_API_URL = "https://api.openai.test"
return client, fake
def test_models_with_x_api_key_routes_anthropic(self):
with self._make_client() as (client, fake):
client.get("/v1/models", headers={"x-api-key": "sk-ant-api03-test"})
assert any("anthropic.test" in url for _, url in fake.calls)
def test_models_with_anthropic_version_routes_anthropic(self):
with self._make_client() as (client, fake):
client.get("/v1/models", headers={"anthropic-version": "2023-06-01"})
assert any("anthropic.test" in url for _, url in fake.calls)
def test_models_with_bearer_sk_ant_routes_anthropic(self):
with self._make_client() as (client, fake):
client.get(
"/v1/models",
headers={"authorization": "Bearer sk-ant-oat01-testtoken"},
)
assert any("anthropic.test" in url for _, url in fake.calls)
def test_models_with_openai_bearer_routes_openai(self):
with self._make_client() as (client, fake):
client.get(
"/v1/models",
headers={"authorization": "Bearer sk-proj-testtoken"},
)
assert any("openai.test" in url for _, url in fake.calls)
def _make_client(self):
"""Return (client, fake) as a context manager."""
import contextlib
@contextlib.contextmanager
def _ctx():
app = create_app(ProxyConfig())
with TestClient(app) as client:
fake = FakeAsyncClient()
client.app.state.proxy.http_client = fake
client.app.state.proxy.ANTHROPIC_API_URL = "https://api.anthropic.test"
client.app.state.proxy.OPENAI_API_URL = "https://api.openai.test"
yield client, fake
return _ctx()
# ---------------------------------------------------------------------------
# Integration tests: catch-all passthrough routing
# ---------------------------------------------------------------------------
class TestCatchAllRouting:
def _make_client(self):
import contextlib
@contextlib.contextmanager
def _ctx():
app = create_app(ProxyConfig())
with TestClient(app) as client:
fake = FakeAsyncClient()
client.app.state.proxy.http_client = fake
client.app.state.proxy.ANTHROPIC_API_URL = "https://api.anthropic.test"
client.app.state.proxy.OPENAI_API_URL = "https://api.openai.test"
yield client, fake
return _ctx()
def test_catchall_anthropic_version_routes_anthropic(self):
with self._make_client() as (client, fake):
client.get(
"/v1/some/unknown/path",
headers={"anthropic-version": "2023-06-01"},
)
assert any("anthropic.test" in url for _, url in fake.calls)
def test_catchall_bearer_sk_ant_routes_anthropic(self):
with self._make_client() as (client, fake):
client.get(
"/v1/some/unknown/path",
headers={"authorization": "Bearer sk-ant-oat01-xxx"},
)
assert any("anthropic.test" in url for _, url in fake.calls)
def test_catchall_no_auth_routes_openai(self):
with self._make_client() as (client, fake):
client.get("/v1/some/unknown/path")
assert any("openai.test" in url for _, url in fake.calls)
# ---------------------------------------------------------------------------
# Unit test: rate-limit key uses Bearer token when no x-api-key
# ---------------------------------------------------------------------------
class TestRateLimitKey:
def test_rate_key_with_x_api_key(self):
"""x-api-key takes precedence for rate key."""
headers = {"x-api-key": "sk-ant-api03-abcdef1234567890"}
api_key = headers.get("x-api-key", "")
if not api_key:
auth = headers.get("authorization", "")
if auth.startswith("Bearer "):
api_key = auth[7:]
client_ip = "127.0.0.1"
rate_key = f"{api_key[:16]}:{client_ip}" if api_key else client_ip
assert rate_key == "sk-ant-api03-abc:127.0.0.1"
def test_rate_key_with_bearer_only(self):
"""Bearer token used for rate key when no x-api-key."""
headers = {"authorization": "Bearer sk-ant-oat01-mytoken123456"}
api_key = headers.get("x-api-key", "")
if not api_key:
auth = headers.get("authorization", "")
if auth.startswith("Bearer "):
api_key = auth[7:]
client_ip = "127.0.0.1"
rate_key = f"{api_key[:16]}:{client_ip}" if api_key else client_ip
assert rate_key == "sk-ant-oat01-myt:127.0.0.1"
def test_rate_key_no_auth(self):
"""No auth headers → IP-only rate key."""
headers = {}
api_key = headers.get("x-api-key", "")
if not api_key:
auth = headers.get("authorization", "")
if auth.startswith("Bearer "):
api_key = auth[7:]
client_ip = "127.0.0.1"
rate_key = f"{api_key[:16]}:{client_ip}" if api_key else client_ip
assert rate_key == "127.0.0.1"