Files
headroom/tests/test_auth_policy.py
9e8cc64b48 fix(core): case-insensitive Bearer scheme, clamp SQLite CCR TTLs, redact the Redis URL in logs (#4561)
## Description

I fix the three small `headroom-core` defects from #4551. None of them
changes a shipped path today (the only production caller of
`auth_mode::classify` coerces every result to OAuth, and the SQLite and
Redis CCR backends are only built from tests and benches), so this is
hardening before those paths get wired in.

1. `auth_mode::classify` matched the Bearer scheme case-sensitively and
did not trim. `bearer sk-ant-api03-...` was classified OAuth (should be
Payg) and `Bearer sk-ant-oat01-...` (two spaces) was classified Payg
(should be OAuth). The scheme is now matched with `eq_ignore_ascii_case`
(RFC 9110 section 11.1) and the token is `trim_start`ed.
2. SQLite CCR: `u64 as i64` on TTLs wrapped `u64::MAX` to -1, so a put
followed by a get returned `None`. A small `ccr::secs_i64` helper
saturates to `i64::MAX`, used at every non-test cast in `sqlite.rs`.
`redis.rs` had the same overflow at `conn.expire(&key, new_ttl as i64)`
(`new_ttl` comes from `max_lifetime_for`, which saturates), so I
switched it to the same helper.
3. `from_config` logged the full Redis URL at info, including
`redis://:password@host`. It now logs `scheme://host[:port]` via a small
`redact_redis_url` (userinfo, path and query dropped; a string with no
`://` becomes a placeholder). No new dependency.

Fixes #4551

## Type of Change

- [x] 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
- [ ] Code refactoring (no functional changes)

## Changes Made

- `crates/headroom-core/src/auth_mode.rs`: case-insensitive `Bearer `
scheme, `trim_start` on the token; test
`bearer_scheme_is_case_insensitive_and_token_is_trimmed` (the four cases
from the issue plus an upper-case scheme, fake tokens only).
- `crates/headroom-core/src/ccr/mod.rs`: `pub(crate) fn secs_i64(u64) ->
i64` (saturating).
- `crates/headroom-core/src/ccr/backends/sqlite.rs`: use `secs_i64` at
the TTL/lifetime/timestamp casts; test
`huge_ttl_means_keep_not_expire_immediately` (temp dir via `tempfile`,
`ttl = u64::MAX`).
- `crates/headroom-core/src/ccr/backends/redis.rs`: `expire(&key,
secs_i64(new_ttl))`.
- `crates/headroom-core/src/ccr/backends/mod.rs`: `redact_redis_url`,
used in the `ccr_backend_initialized` log; test
`redis_url_credentials_are_not_logged`.

## Testing

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

Rust-only change, so the Python checks above are not applicable. I ran
`cargo test -p headroom-core --lib`, `cargo clippy -p headroom-core
--lib --tests -- -D warnings`, `cargo fmt -p headroom-core -- --check`,
and `cargo check -p headroom-core --lib --features redis`.

### Test Output

Before (source fixes reverted, new tests kept):

```text
test auth_mode::inline_tests::bearer_scheme_is_case_insensitive_and_token_is_trimmed ... FAILED
test ccr::backends::sqlite::tests::huge_ttl_means_keep_not_expire_immediately ... FAILED
  left: OAuth
 right: Payg
  left: None
 right: Some("payload")
test result: FAILED. 0 passed; 2 failed; 0 ignored; 0 measured; 982 filtered out
```

After:

```text
test ccr::backends::tests::redis_url_credentials_are_not_logged ... ok
test auth_mode::inline_tests::bearer_scheme_is_case_insensitive_and_token_is_trimmed ... ok
test ccr::backends::sqlite::tests::huge_ttl_means_keep_not_expire_immediately ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 981 filtered out

cargo test -p headroom-core --lib
test result: ok. 983 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out

cargo clippy -p headroom-core --lib --tests -- -D warnings
    Finished `dev` profile [unoptimized + debuginfo] target(s)

cargo fmt -p headroom-core -- --check   (exit 0)
cargo check -p headroom-core --lib --features redis   Finished
```

## Real Behavior Proof

- Environment: Windows 11, native Windows cargo, Rust 1.95.0 (pinned
toolchain), clone of `main` at `a2d4fe72` plus this change.
- Exact command / steps: `cargo test -p headroom-core --lib --
bearer_scheme huge_ttl redis_url`, once with the source fixes reverted
(tests kept) and once with the fixes; then the full `--lib` run, clippy
and fmt as above.
- Observed result: with the fixes reverted the bearer and SQLite tests
fail with exactly the values in the issue (`bearer ...` gives OAuth,
`ttl = u64::MAX` put-then-get gives `None`); with the fixes all pass,
983 passed in the full lib run.
- Not tested: no Redis server, so the Redis `expire` change is
compile-checked (`--features redis`) only and the redaction is covered
by a unit test of the helper, not by capturing a real log line. These
paths are not wired into production today per the issue, so there is no
end-to-end behavior to observe yet. The `Bearer` tab-separator case and
non-ASCII schemes were not exercised beyond the code reading.

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: no for shipped paths; `classify`
gives a different result only for non-canonical Bearer headers
(lowercase scheme, extra spaces) and well-formed headers keep their
classification
- Kill switch / disable path: none needed; revert the PR
- Unsafe override required: no
- Qualification impact: none expected
- 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 (none
needed)
- [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)

## Additional Notes

The three fixes are independent; I can split them if you prefer one PR
per item. Existing tests in `crates/headroom-core/tests/auth_mode.rs`
were not changed and still pass.

Produced with AI assistance (Claude Code) operated by me (HetCreep); the
tests were run on my machine against a clone of the repository.

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

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4561"
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: JD Davis <mxjerrett@gmail.com>
2026-11-04 23:20:34 -06:00

115 lines
4.4 KiB
Python

"""Tests for pure auth and client classification policy."""
from __future__ import annotations
from headroom.proxy.auth_policy import (
AuthMode,
AuthSignals,
classify_auth_signals,
classify_client_signals,
should_stamp_codex_client_signals,
)
def test_subscription_user_agent_wins_over_oauth_token() -> None:
signals = AuthSignals(
user_agent="claude-code/1.5.0 (linux; x86_64)",
authorization="Bearer sk-ant-oat01-abc123",
)
assert classify_auth_signals(signals) is AuthMode.SUBSCRIPTION
def test_oauth_bearer_token_shapes_are_oauth() -> None:
jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.signature"
assert classify_auth_signals(AuthSignals(authorization="Bearer sk-ant-oat01-abc")) is (
AuthMode.OAUTH
)
assert classify_auth_signals(AuthSignals(authorization=f"Bearer {jwt}")) is AuthMode.OAUTH
def test_payg_key_shapes_are_payg() -> None:
assert classify_auth_signals(AuthSignals(authorization="Bearer sk-ant-api03-abc")) is (
AuthMode.PAYG
)
assert classify_auth_signals(AuthSignals(x_api_key="sk-ant-api03-abc")) is AuthMode.PAYG
assert classify_auth_signals(AuthSignals(x_goog_api_key="AIzaSyDUMMY")) is AuthMode.PAYG
def test_client_explicit_override_wins_over_user_agent() -> None:
signals = AuthSignals(user_agent="claude-code/1.2.3", x_client=" AIDER ")
assert classify_client_signals(signals) == "aider"
def test_grok_build_user_agent_keeps_credential_driven_policy() -> None:
signals = AuthSignals(user_agent="grok/1.2.3")
assert classify_auth_signals(signals) is AuthMode.PAYG
assert classify_client_signals(signals) == "grok_build"
def test_grok_shell_user_agent_maps_to_grok_build_but_not_subscription() -> None:
# Current Grok Build releases send grok-shell/<version> (grok 0.2.112).
# Client classification must recognize it; auth mode deliberately stays
# key-driven (API-key grok is pay-per-token and should keep the
# aggressive policy), so grok-shell/ is NOT a subscription UA prefix.
signals = AuthSignals(user_agent="grok-shell/0.2.112 (macos; aarch64)")
assert classify_client_signals(signals) == "grok_build"
assert classify_auth_signals(signals) is not AuthMode.SUBSCRIPTION
def test_codex_stamp_only_for_unidentified_responses_callers() -> None:
assert should_stamp_codex_client_signals("/v1/responses", AuthSignals()) is True
assert (
should_stamp_codex_client_signals(
"/v1/responses/foo",
AuthSignals(user_agent="codex-cli/0.5"),
)
is False
)
assert should_stamp_codex_client_signals("/v1/chat/completions", AuthSignals()) is False
def test_bearer_scheme_is_case_insensitive() -> None:
# RFC 7235 §2.1: the auth-scheme token is case-insensitive. A lowercase or
# mixed-case "bearer" carrying a PAYG key must classify as PAYG, not fall
# through to the non-Bearer OAUTH branch.
for scheme in ("bearer", "BEARER", "Bearer", "BeArEr"):
signals = AuthSignals(authorization=f"{scheme} sk-ant-api03-abc")
assert classify_auth_signals(signals) is AuthMode.PAYG, scheme
def test_bearer_case_insensitive_preserves_oauth_and_jwt_shapes() -> None:
jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.signature"
assert classify_auth_signals(AuthSignals(authorization="bearer sk-ant-oat01-abc")) is (
AuthMode.OAUTH
)
assert classify_auth_signals(AuthSignals(authorization=f"bearer {jwt}")) is AuthMode.OAUTH
def test_extra_spaces_between_scheme_and_token_are_ignored() -> None:
# Same answer as the Rust classifier (headroom_core::auth_mode::classify).
assert classify_auth_signals(AuthSignals(authorization="Bearer sk-ant-oat01-abc")) is (
AuthMode.OAUTH
)
assert classify_auth_signals(AuthSignals(authorization="bearer sk-ant-api03-abc")) is (
AuthMode.PAYG
)
def test_credential_case_is_not_folded() -> None:
# Only the scheme is case-folded; the token keeps its case, so a PAYG
# `sk-...` prefix still matches exactly (it is lowercase by construction).
signals = AuthSignals(authorization="Bearer sk-PROJ-Abc123")
assert classify_auth_signals(signals) is AuthMode.PAYG
def test_non_bearer_scheme_still_oauth() -> None:
# AWS SigV4 (Bedrock) and any other non-Bearer scheme keep the OAUTH
# passthrough-prefer classification.
signals = AuthSignals(authorization="AWS4-HMAC-SHA256 Credential=AKIA/...")
assert classify_auth_signals(signals) is AuthMode.OAUTH