Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix: PR-F1 classify_auth_mode helper (Phase F kickoff)
chopratejasca9de93cfc4c
diff --git a/Cargo.lock b/Cargo.lockindex c2261c95e..fe401107c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1406,6 +1406,7 @@ dependencies = ["fastembed","flate2","hf-hub 0.4.3",+ "http","magika","md-5","proptest",diff --git a/crates/headroom-core/Cargo.toml b/crates/headroom-core/Cargo.tomlindex 780e46126..49463817b 100644--- a/crates/headroom-core/Cargo.toml+++ b/crates/headroom-core/Cargo.toml@@ -109,6 +109,11 @@ rusqlite = { version = "0.32", features = ["bundled"] }# `ccr/backends/redis.rs`; `tokio-comp` would pull `tokio` into the# core crate, which we do not want.redis = { version = "0.27", optional = true, default-features = false }+# `http` powers the auth-mode classifier (Phase F PR-F1). The proxy+# crate already depends on this — pulling it into core lets the+# classifier live with the other Phase B/F policy primitives without+# cycling through the proxy crate. Tiny crate (no I/O, just types).+http = "1"[features]default = []@@ -130,3 +135,7 @@ harness = false[[bench]]name = "ccr_store"harness = false++[[bench]]+name = "auth_mode"+harness = falsediff --git a/crates/headroom-core/benches/auth_mode.rs b/crates/headroom-core/benches/auth_mode.rsnew file mode 100644index 000000000..683165e7b--- /dev/null+++ b/crates/headroom-core/benches/auth_mode.rs@@ -0,0 +1,74 @@+//! Criterion benchmark for the auth-mode classifier (Phase F PR-F1).+//!+//! Acceptance criterion: <10us per call. Realistic header sets from+//! the three classes the proxy actually sees in production:+//!+//! - PAYG: `Authorization: Bearer sk-ant-api03-...`+//! - OAuth: `Authorization: Bearer <jwt>` (Codex-style)+//! - Subscription: `User-Agent: claude-code/1.5.0 ...` + `Bearer+//! sk-ant-oat-...`+//!+//! The bench measures one classifier call per iteration. The+//! `HeaderMap` is constructed once outside the timing loop.++use criterion::{black_box, criterion_group, criterion_main, Criterion};+use headroom_core::auth_mode::classify;+use http::{HeaderMap, HeaderValue};++fn build_headers(pairs: &[(&str, &str)]) -> HeaderMap {+ let mut h = HeaderMap::new();+ for (name, value) in pairs {+ h.insert(+ http::header::HeaderName::from_bytes(name.as_bytes()).unwrap(),+ HeaderValue::from_str(value).unwrap(),+ );+ }+ h+}++fn bench_classify(c: &mut Criterion) {+ let mut group = c.benchmark_group("auth_mode/classify");++ // Empty headers — the simplest path; all branches fall through.+ let empty = HeaderMap::new();+ group.bench_function("empty", |b| b.iter(|| classify(black_box(&empty))));++ // PAYG — Authorization is Bearer, prefix matches early.+ let payg = build_headers(&[(+ "authorization",+ "Bearer sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789",+ )]);+ group.bench_function("payg_anthropic_api_key", |b| {+ b.iter(|| classify(black_box(&payg)))+ });++ // OAuth — JWT, three segments, last branch in the bearer match.+ let oauth = build_headers(&[(+ "authorization",+ "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4iLCJpYXQiOjE1MTYyMzkwMjJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",+ )]);+ group.bench_function("oauth_jwt", |b| b.iter(|| classify(black_box(&oauth))));++ // Subscription — UA must be lowercased; the most expensive path.+ let subscription = build_headers(&[+ (+ "user-agent",+ "claude-code/1.5.0 (linux; x86_64) anthropic/0.42.0",+ ),+ (+ "authorization",+ "Bearer sk-ant-oat-01-abcdefghijklmnopqrstuvwxyz",+ ),+ ("content-type", "application/json"),+ ("accept", "application/json"),+ ("host", "api.anthropic.com"),+ ]);+ group.bench_function("subscription_claude_code", |b| {+ b.iter(|| classify(black_box(&subscription)))+ });++ group.finish();+}++criterion_group!(benches, bench_classify);+criterion_main!(benches);diff --git a/crates/headroom-core/src/auth_mode.rs b/crates/headroom-core/src/auth_mode.rsnew file mode 100644index 000000000..4f0242d9e--- /dev/null+++ b/crates/headroom-core/src/auth_mode.rs@@ -0,0 +1,250 @@+//! Auth-mode classifier — Phase F PR-F1.+//!+//! A single pure function turns the inbound request `HeaderMap` into one+//! of three classes that drive every downstream compression / cache /+//! header policy decision:+//!+//! - [`AuthMode::Payg`]: caller pays per token (Anthropic API key,+//! OpenAI `sk-...`, Gemini `x-goog-api-key`, x-api-key). Aggressive+//! compression saves them money — turn it all on.+//! - [`AuthMode::OAuth`]: caller is on a fixed-cost subscription / IAM+//! plan (Claude Pro OAuth, Codex Enterprise, Cursor Pro, Bedrock+//! IAM-signed downstream, Vertex ADC). Per-token cost is opaque to+//! them; cache-safety is paramount because OAuth scopes pin to+//! `(account, model, session)` and beta-header drift voids them.+//! - [`AuthMode::Subscription`]: caller is a UX-bound CLI / IDE+//! (Claude Code, ChatGPT Plus, Cursor, Copilot, Antigravity).+//! Provider rate-limits by request count; programmatic-fingerprint+//! detection means we MUST look like the upstream agent (preserve+//! `User-Agent`, never inject `X-Headroom-*`, never strip+//! `accept-encoding`).+//!+//! See `~/.claude/projects/.../memory/project_auth_mode_compression_nuances.md`+//! for the user-decision rationale (2026-05-01).+//!+//! The classifier is **pure** (no I/O, no allocation beyond a single+//! lowercase copy of the User-Agent), runs in <10us per call, and+//! NEVER panics on malformed headers — non-UTF-8 values fall through to+//! the safe default [`AuthMode::Payg`] with a `tracing::warn!` event so+//! operators can spot bad clients in the log stream without taking the+//! proxy down.++use http::HeaderMap;++/// Three auth-mode classes Headroom routes compression policy through.+///+/// `Copy` because the value is passed through dozens of compression+/// decisions per request; cloning a 1-byte enum is cheaper than holding+/// a reference across `await` points. `Hash + Eq` so it can key the+/// per-tenant TOIN aggregation map (Phase F PR-F3).+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum AuthMode {+ /// Pay-as-you-go API key. Aggressive live-zone compression OK.+ Payg,+ /// OAuth bearer / Bedrock IAM / Vertex ADC. Passthrough-prefer:+ /// no auto-`cache_control`, no auto-`prompt_cache_key`, no lossy+ /// compressors. Lossless-only path.+ OAuth,+ /// Subscription-bound CLI / IDE. Stealth: same as OAuth ++ /// preserve `accept-encoding`, never strip; never inject+ /// `X-Headroom-*`; never mutate `User-Agent`.+ Subscription,+}++impl AuthMode {+ /// Lower-snake-case label suitable for structured-log fields and+ /// metric labels. Stable wire format — Python parity tests check+ /// this exact string.+ pub fn as_str(self) -> &'static str {+ match self {+ AuthMode::Payg => "payg",+ AuthMode::OAuth => "oauth",+ AuthMode::Subscription => "subscription",+ }+ }+}++/// User-Agent prefixes that identify a UX-bound CLI / IDE.+///+/// Lives at module scope (not inside `classify`) so:+/// 1. The compiler can constant-fold the slice into the rodata segment.+/// 2. A future PR can swap this for a configurable list (Phase F+/// follow-up) without touching the function body.+/// 3. Adding a new client = one-line edit here, no logic change.+///+/// Match is `str::contains` against a lowercased copy of the UA — so+/// the prefix can appear anywhere in the value (Anthropic CLIs prefix+/// their own UA with the parent agent's UA in some cases).+const SUBSCRIPTION_UA_PREFIXES: &[&str] = &[+ "claude-cli/",+ "claude-code/",+ "codex-cli/",+ "cursor/",+ "claude-vscode/",+ "github-copilot/",+ "anthropic-cli/",+ "antigravity/",+];++/// Classify the auth mode of an inbound request from its headers.+///+/// Decision order (most-specific signal wins):+///+/// 1. **Subscription UA prefix** → [`AuthMode::Subscription`].+/// The CLI's own auth-mode wins over the bearer token shape it+/// happens to be carrying — a Claude Code session uses a+/// `sk-ant-oat-*` token but is a subscription client, not OAuth.+/// 2. **`Authorization: Bearer sk-ant-oat-*`** → [`AuthMode::OAuth`]+/// (Claude Pro / Max OAuth). Checked before the broader `sk-` PAYG+/// rule because `sk-ant-oat-` shares the `sk-` prefix.+/// 3. **`Authorization: Bearer sk-ant-api*` or `Bearer sk-*`** →+/// [`AuthMode::Payg`] (Anthropic / OpenAI API key).+/// 4. **`Authorization: Bearer <jwt>`** (3 dot-separated segments) →+/// [`AuthMode::OAuth`] (Codex / Cursor / Copilot OAuth).+/// 5. **`Authorization` present but not `Bearer ...`** →+/// [`AuthMode::OAuth`] (AWS SigV4 `AWS4-HMAC-SHA256 ...` →+/// Bedrock; any other non-Bearer scheme is presumed+/// passthrough-prefer too).+/// 6. **`x-api-key` present** → [`AuthMode::Payg`] (Anthropic API key+/// style).+/// 7. **`x-goog-api-key` present** → [`AuthMode::Payg`] (Gemini key).+/// 8. **Default** → [`AuthMode::Payg`] (safest default; aggressive+/// compression on a misclassified request just costs us a re-run,+/// not a revoked subscription).+///+/// # Performance+///+/// One owned `String` allocation for the lowercase UA copy. All other+/// matches are zero-allocation `str::starts_with` / `str::contains` /+/// `str::split('.').count()`. Bench at+/// `crates/headroom-core/benches/auth_mode.rs` asserts <10us / call.+pub fn classify(headers: &HeaderMap) -> AuthMode {+ // ── User-Agent ───────────────────────────────────────────────+ // Subscription clients identify by UA prefix; this is the most+ // specific signal because the same OAuth token shape appears in+ // both Claude Pro (web) and Claude Code (CLI), and only the UA+ // tells them apart. Read once, lowercase once.+ let ua_owned = match headers.get("user-agent") {+ Some(value) => match value.to_str() {+ Ok(s) => s.to_ascii_lowercase(),+ Err(_) => {+ tracing::warn!(+ event = "auth_mode_classify_unparseable_user_agent",+ "non-UTF-8 user-agent header; falling through to bearer-token classification"+ );+ String::new()+ }+ },+ None => String::new(),+ };+ if SUBSCRIPTION_UA_PREFIXES+ .iter()+ .any(|prefix| ua_owned.contains(prefix))+ {+ return AuthMode::Subscription;+ }++ // ── Authorization header ─────────────────────────────────────+ // We must NOT log the value. `to_str` returns an `&str` with the+ // same lifetime as the `HeaderMap`, so no copy here.+ let auth = match headers.get("authorization") {+ Some(value) => match value.to_str() {+ Ok(s) => s,+ Err(_) => {+ tracing::warn!(+ event = "auth_mode_classify_unparseable_authorization",+ "non-UTF-8 authorization header; falling back to default Payg"+ );+ ""+ }+ },+ None => "",+ };++ if let Some(token) = auth.strip_prefix("Bearer ") {+ // Order matters: the OAuth shape `sk-ant-oat-*` shares a+ // prefix with `sk-ant-api*` only at `sk-ant-`, so we check+ // the OAuth shape FIRST. Then the broad PAYG shapes.+ if token.starts_with("sk-ant-oat-") {+ return AuthMode::OAuth;+ }+ if token.starts_with("sk-ant-api") || token.starts_with("sk-") {+ return AuthMode::Payg;+ }+ // JWT: classic three-segment `header.payload.signature`.+ // We don't validate the JWT — just count dot-separated+ // segments. This catches Codex / Cursor / Copilot OAuth.+ if token.split('.').count() >= 3 {+ return AuthMode::OAuth;+ }+ // Unknown bearer shape — fall through to header-based+ // detection below; ultimately defaults to Payg.+ } else if !auth.is_empty() {+ // Authorization is present but NOT `Bearer ...` — most+ // commonly AWS SigV4 (`AWS4-HMAC-SHA256 ...`) on a Bedrock+ // request, or a `Basic ...` from a custom proxy chain. We+ // treat all such non-Bearer schemes as passthrough-prefer.+ // The IAM / signed flow is opaque to us; we never strip or+ // mutate the value — just classify the policy.+ return AuthMode::OAuth;+ }++ // ── Vendor-specific API-key headers ──────────────────────────+ // Anthropic API-key style. Direct PAYG; same compression policy+ // as a `Bearer sk-ant-api...`.+ if headers.contains_key("x-api-key") {+ return AuthMode::Payg;+ }+ // Gemini API key. Same PAYG semantics.+ if headers.contains_key("x-goog-api-key") {+ return AuthMode::Payg;+ }++ // ── Default ──────────────────────────────────────────────────+ // Anything else: assume PAYG. Misclassifying a non-PAYG client+ // as PAYG only over-compresses; under-compressing a PAYG client+ // would leave money on the table, which is worse for the+ // OSS-default user.+ AuthMode::Payg+}++#[cfg(test)]+mod inline_tests {+ //! Smoke tests inlined alongside the function so `cargo test -p+ //! headroom-core --lib` exercises the helper without pulling in+ //! the integration-test binary. The exhaustive test matrix lives+ //! in `crates/headroom-core/tests/auth_mode.rs`.++ use super::*;+ use http::HeaderValue;++ #[test]+ fn enum_as_str_is_stable() {+ // Python parity tests assert these exact strings.+ assert_eq!(AuthMode::Payg.as_str(), "payg");+ assert_eq!(AuthMode::OAuth.as_str(), "oauth");+ assert_eq!(AuthMode::Subscription.as_str(), "subscription");+ }++ #[test]+ fn empty_headers_default_to_payg() {+ // No Authorization, no x-api-key, no x-goog-api-key, no UA →+ // safest default is PAYG. The bedrock OAuth branch fires only+ // when there's a positive non-Bearer Authorization signal.+ let headers = HeaderMap::new();+ assert_eq!(classify(&headers), AuthMode::Payg);+ }++ #[test]+ fn unparseable_auth_falls_back_to_default() {+ // Non-UTF-8 Authorization header — the warn! fires but we+ // do NOT panic. With no other distinguishing headers, we+ // fall through to the default → Payg.+ let mut headers = HeaderMap::new();+ headers.insert(+ "authorization",+ HeaderValue::from_bytes(b"\xFFnope").unwrap(),+ );+ assert_eq!(classify(&headers), AuthMode::Payg);+ }+}diff --git a/crates/headroom-core/src/lib.rs b/crates/headroom-core/src/lib.rsindex 8485f7e92..5bd9343ff 100644--- a/crates/headroom-core/src/lib.rs+++ b/crates/headroom-core/src/lib.rs@@ -1,5 +1,6 @@//! headroom-core: foundation crate for the Rust port of Headroom.+pub mod auth_mode;pub mod cache_control;pub mod ccr;pub mod relevance;diff --git a/crates/headroom-core/tests/auth_mode.rs b/crates/headroom-core/tests/auth_mode.rsnew file mode 100644index 000000000..461e41555--- /dev/null+++ b/crates/headroom-core/tests/auth_mode.rs@@ -0,0 +1,191 @@+//! Integration tests for `headroom_core::auth_mode::classify`.+//!+//! Exhaustive matrix per Phase F PR-F1 acceptance criteria. Bonus+//! cases cover the cross-precedence rules (Subscription UA wins over+//! OAuth bearer; vendor API-key headers map to PAYG).+//!+//! These are mirrored byte-for-byte by `tests/test_auth_mode.py` —+//! the Python helper MUST agree on every header set we test here.++use headroom_core::auth_mode::{classify, AuthMode};+use http::{HeaderMap, HeaderValue};++/// Helper: build a `HeaderMap` from `(name, value)` pairs in one+/// expression. Keeps the test bodies focused on the data, not the+/// `HeaderMap` boilerplate.+fn headers(pairs: &[(&str, &str)]) -> HeaderMap {+ let mut h = HeaderMap::new();+ for (name, value) in pairs {+ h.insert(+ http::header::HeaderName::from_bytes(name.as_bytes()).expect("valid header name"),+ HeaderValue::from_str(value).expect("valid header value"),+ );+ }+ h+}++// ── Required matrix ──────────────────────────────────────────────++#[test]+fn api_key_classified_payg() {+ // Anthropic PAYG: `Authorization: Bearer sk-ant-api03-XXX`.+ let h = headers(&[("authorization", "Bearer sk-ant-api03-abc123def456")]);+ assert_eq!(classify(&h), AuthMode::Payg);+}++#[test]+fn oauth_jwt_classified_oauth() {+ // Codex / Cursor OAuth bearer: classic 3-segment JWT.+ let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0In0.signaturepart";+ let h = headers(&[("authorization", &format!("Bearer {}", jwt))]);+ assert_eq!(classify(&h), AuthMode::OAuth);+}++#[test]+fn oauth_sk_ant_oat_classified_oauth() {+ // Claude Pro / Max OAuth: `Bearer sk-ant-oat-...`.+ let h = headers(&[("authorization", "Bearer sk-ant-oat-01-abc123def456")]);+ assert_eq!(classify(&h), AuthMode::OAuth);+}++#[test]+fn claude_code_ua_classified_subscription() {+ // Claude Code CLI: `User-Agent: claude-code/1.2.3 ...`.+ let h = headers(&[("user-agent", "claude-code/1.2.3 (darwin; arm64)")]);+ assert_eq!(classify(&h), AuthMode::Subscription);+}++#[test]+fn cursor_ua_classified_subscription() {+ // Cursor CLI: `User-Agent: cursor/1.0`.+ let h = headers(&[("user-agent", "cursor/1.0")]);+ assert_eq!(classify(&h), AuthMode::Subscription);+}++#[test]+fn no_auth_no_user_agent_default_payg() {+ // Empty headers → safest default is PAYG. The OAuth/bedrock+ // branch fires only when there's a positive non-Bearer auth+ // signal (next test). Choosing PAYG by default favors the+ // OSS-default workload (per-token cost saving).+ let h = HeaderMap::new();+ assert_eq!(classify(&h), AuthMode::Payg);+}++#[test]+fn bedrock_no_auth_classified_oauth() {+ // Bedrock SigV4: `Authorization: AWS4-HMAC-SHA256 Credential=...`.+ // Not a Bearer scheme; we treat all non-Bearer Authorization as+ // OAuth (passthrough-prefer).+ let h = headers(&[(+ "authorization",+ "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20260501/us-east-1/bedrock/aws4_request, \+ SignedHeaders=host;x-amz-date, Signature=fe5f80f77d5fa3beca038a248ff027",+ )]);+ assert_eq!(classify(&h), AuthMode::OAuth);+}++// ── Bonus matrix ──────────────────────────────────────────────────++#[test]+fn openai_payg_sk_classified_payg() {+ // OpenAI PAYG: `Authorization: Bearer sk-proj-...`.+ let h = headers(&[("authorization", "Bearer sk-proj-abcdef0123456789")]);+ assert_eq!(classify(&h), AuthMode::Payg);+}++#[test]+fn gemini_x_goog_api_key_classified_payg() {+ // Google Gemini API key as `x-goog-api-key`.+ let h = headers(&[("x-goog-api-key", "AIzaSyDUMMYKEY1234567890")]);+ assert_eq!(classify(&h), AuthMode::Payg);+}++#[test]+fn subscription_takes_precedence_over_oauth_token() {+ // Claude Code CLI happens to send a `Bearer sk-ant-oat-...`+ // token, but it IS a subscription client (rate-limited per+ // request count, never identify Headroom). UA wins.+ let h = headers(&[+ ("user-agent", "claude-code/1.5.0 (linux; x86_64)"),+ ("authorization", "Bearer sk-ant-oat-01-abc123"),+ ]);+ assert_eq!(classify(&h), AuthMode::Subscription);+}++// ── Edge cases (defensive coverage; not in the required matrix) ──++#[test]+fn anthropic_x_api_key_classified_payg() {+ // Anthropic API key style: `x-api-key: sk-ant-...`.+ let h = headers(&[("x-api-key", "sk-ant-api03-abcdef")]);+ assert_eq!(classify(&h), AuthMode::Payg);+}++#[test]+fn copilot_ua_classified_subscription() {+ // GitHub Copilot UA — covers the `github-copilot/` prefix.+ let h = headers(&[("user-agent", "GitHub-Copilot/1.0 (vscode)")]);+ assert_eq!(classify(&h), AuthMode::Subscription);+}++#[test]+fn anthropic_cli_ua_classified_subscription() {+ let h = headers(&[("user-agent", "anthropic-cli/0.9.1")]);+ assert_eq!(classify(&h), AuthMode::Subscription);+}++#[test]+fn antigravity_ua_classified_subscription() {+ let h = headers(&[("user-agent", "Antigravity/2.0 (build 1234)")]);+ assert_eq!(classify(&h), AuthMode::Subscription);+}++// ── Performance ──────────────────────────────────────────────────++/// Smoke perf check — a strict bench lives at+/// `crates/headroom-core/benches/auth_mode.rs`. This in-test loop+/// guards against catastrophic regressions on every `cargo test`+/// run (e.g., accidental allocator hot-path change).+#[test]+fn classify_under_10us_per_call() {+ use std::time::Instant;++ // Realistic mix: a Claude Code session (the most expensive case+ // because UA must be lowercased). Subset of headers a real proxy+ // would see.+ let h = headers(&[+ (+ "user-agent",+ "claude-code/1.5.0 (linux; x86_64) anthropic/0.42.0",+ ),+ (+ "authorization",+ "Bearer sk-ant-oat-01-abcdefghijklmnopqrstuv",+ ),+ ("content-type", "application/json"),+ ("accept", "application/json"),+ ("host", "api.anthropic.com"),+ ]);++ // Warmup so the branch predictor / icache aren't on a cold path.+ for _ in 0..1_000 {+ std::hint::black_box(classify(&h));+ }++ let iters = 100_000;+ let start = Instant::now();+ for _ in 0..iters {+ std::hint::black_box(classify(&h));+ }+ let elapsed = start.elapsed();+ let per_call_ns = elapsed.as_nanos() / iters as u128;++ // 10us = 10_000 ns. Asserting 10x headroom guards against perf+ // regressions even on a contended CI runner.+ assert!(+ per_call_ns < 10_000,+ "classify took {} ns/call (limit: 10_000 ns); regression suspected",+ per_call_ns+ );+}diff --git a/crates/headroom-proxy/src/proxy.rs b/crates/headroom-proxy/src/proxy.rsindex 056e9a9af..fce8f31db 100644--- a/crates/headroom-proxy/src/proxy.rs+++ b/crates/headroom-proxy/src/proxy.rs@@ -22,6 +22,11 @@ use crate::error::ProxyError;use crate::headers::{build_forward_request_headers, filter_response_headers};use crate::health::{healthz, healthz_upstream};use crate::websocket::ws_handler;+// Phase F PR-F1: imported as `classify_auth_mode` to make the call+// site self-documenting. `AuthMode` is re-exported under the same+// path for downstream handlers that read the value back out of+// `req.extensions()` (Phase F PR-F2/F3/F4).+use headroom_core::auth_mode::classify as classify_auth_mode;/// Shared state passed to every handler.///@@ -215,7 +220,7 @@ pub(crate) fn join_upstream_path(base: &url::Url, path: &str, query: Option<&strpub(crate) async fn forward_http(state: AppState,client_addr: SocketAddr,- req: Request<Body>,+ mut req: Request<Body>,) -> Result<Response<Body>, ProxyError> {let start = Instant::now();let request_id = ensure_request_id(req.headers());@@ -228,15 +233,24 @@ pub(crate) async fn forward_http(.and_then(|v| v.to_str().ok()).and_then(|s| s.parse::<u64>().ok());- // Per PR-A1: structured entry log. `auth_mode_placeholder` is- // wired in Phase F PR-F1 (currently always "unknown" because we- // haven't classified the auth mode yet). Hardcoding it here is- // OK because it's logging metadata, not behaviour. Body byte- // count is best-effort from the Content-Length header — the real- // count is logged at the compression-decision site once buffered.+ // Phase F PR-F1: classify auth mode at request entry. The result+ // is stored in request extensions so downstream handlers (cache+ // gates, header injection, lossy-compressor gates) read it+ // without re-classifying. Pure function, <10us per call —+ // doing it once here is cheaper than threading the result.+ let auth_mode = classify_auth_mode(req.headers());+ req.extensions_mut().insert(auth_mode);++ // Per PR-A1: structured entry log. The `auth_mode` field is now+ // populated with the real classification result (Phase F PR-F1+ // replaces the prior `auth_mode_placeholder = "unknown"`). Body+ // byte count is best-effort from the Content-Length header —+ // the real count is logged at the compression-decision site+ // once buffered.tracing::debug!(+ event = "auth_mode_classified",request_id = %request_id,- auth_mode_placeholder = "unknown",+ auth_mode = auth_mode.as_str(),method = %method,path = %path_for_log,content_length_bytes = ?body_bytes_hint,diff --git a/docs/auth-modes.md b/docs/auth-modes.mdnew file mode 100644index 000000000..0fb8a9af8--- /dev/null+++ b/docs/auth-modes.md@@ -0,0 +1,132 @@+# Auth Modes++Headroom classifies every inbound request into one of three **auth modes** at request entry. The mode drives every downstream compression, cache, and header policy decision. Detection is a pure function of HTTP headers — no I/O, no allocation beyond a single `to_lowercase` of the User-Agent, runs in <10us per call.++The classifier ships in two equivalent implementations:++- **Rust:** `crates/headroom-core/src/auth_mode.rs` (`classify`)+- **Python:** `headroom/proxy/auth_mode.py` (`classify_auth_mode`)++Both are byte-for-byte identical on every header set covered by the parity test suite (`crates/headroom-core/tests/auth_mode.rs` + `tests/test_auth_mode.py`).++## The three modes++### `Payg` — pay-as-you-go API key++| Signal | Examples |+|---|---|+| `Authorization: Bearer sk-ant-api*` | Anthropic PAYG key |+| `Authorization: Bearer sk-*` (excluding `sk-ant-oat-`) | OpenAI PAYG key |+| `x-api-key: ...` | Anthropic API key style |+| `x-goog-api-key: ...` | Google Gemini key |++**Compression policy:** aggressive. The caller pays per token; compression directly saves them money. Cache hit-rate matters financially (Anthropic 1.25-2× cache write, 0.10× cache read). Live-zone compression, CCR, type-aware compressors all turn on. This is the OSS default.++### `OAuth` — OAuth bearer / IAM-signed++| Signal | Examples |+|---|---|+| `Authorization: Bearer sk-ant-oat-*` | Claude Pro / Max OAuth |+| `Authorization: Bearer <jwt>` (3-segment) | Codex / Cursor / Copilot OAuth |+| `Authorization: AWS4-HMAC-SHA256 ...` | Bedrock SigV4 |+| Any other non-`Bearer` Authorization scheme | Vertex ADC, custom proxies |++**Compression policy:** passthrough-prefer. Per-token cost is opaque (subscription) or zero from the caller's POV (IAM-bound usage); compression value is **extending effective context within rate-limit / quota windows**, not saving money. Cache safety is paramount because OAuth scopes pin to `(account, model, session)` and beta-header drift can break OAuth-issued scopes. **No auto-`cache_control`, no auto-`prompt_cache_key`, no lossy compressors.** Lossless-only.++### `Subscription` — UX-bound CLI / IDE++| Signal | UA prefix |+|---|---|+| Claude Code | `claude-code/` |+| Claude CLI | `claude-cli/` |+| Codex CLI | `codex-cli/` |+| Cursor | `cursor/` |+| Claude VS Code | `claude-vscode/` |+| GitHub Copilot | `github-copilot/` |+| Anthropic CLI | `anthropic-cli/` |+| Antigravity | `antigravity/` |++**Compression policy:** stealth. Provider rate-limits by request count; programmatic-fingerprint detection means Headroom MUST look like the upstream agent. Same compression policy as `OAuth` **plus**:++- Preserve `accept-encoding` byte-for-byte.+- Never inject `X-Headroom-*` headers on upstream-bound requests.+- Never mutate `User-Agent`.+- Skip `X-Forwarded-*` headers on upstream-bound requests (see Phase F PR-F4).++The Subscription UA wins over any bearer token shape — a Claude Code session that happens to carry a `sk-ant-oat-*` token is still a subscription client, never OAuth.++## Detection signals — full decision order++The classifier evaluates these in order; the **first** matching rule wins.++1. **User-Agent contains a `SUBSCRIPTION_UA_PREFIXES` entry** → `Subscription`.+2. **`Authorization: Bearer sk-ant-oat-*`** → `OAuth`.+3. **`Authorization: Bearer sk-ant-api*` or `Bearer sk-*`** → `Payg`.+4. **`Authorization: Bearer <jwt>`** (3 dot-separated segments) → `OAuth`.+5. **`Authorization` present but not `Bearer ...`** (e.g., `AWS4-HMAC-SHA256`) → `OAuth`.+6. **`x-api-key` present** → `Payg`.+7. **`x-goog-api-key` present** → `Payg`.+8. **Default** → `Payg`.++The subscription-UA check is intentionally first because the same OAuth token shape appears in both Claude Pro (web) and Claude Code (CLI), and only the User-Agent disambiguates them.++The "default to PAYG" rule is intentionally conservative: misclassifying a non-PAYG client as PAYG over-compresses, which only costs us a re-run; under-compressing a PAYG client leaves money on the table, which is worse for the OSS-default user.++## How to extend++### Adding a new subscription CLI++Add the UA prefix to **both** files — they must agree:++- `crates/headroom-core/src/auth_mode.rs` → `SUBSCRIPTION_UA_PREFIXES`+- `headroom/proxy/auth_mode.py` → `SUBSCRIPTION_UA_PREFIXES`++Then add a parametrised parity test case in **both**:++- `crates/headroom-core/tests/auth_mode.rs` → add a `#[test] fn ..._ua_classified_subscription`.+- `tests/test_auth_mode.py` → covered automatically by the existing `test_every_subscription_prefix_classified_subscription` parametrised test.++### Adding a new OAuth token shape++Add the prefix check **before** the `sk-` PAYG branch in both `classify` and `classify_auth_mode`. Order matters: any token shape that's a strict prefix of `sk-` must be checked first.++### Making the prefix list user-configurable++The list lives in a `const` so a future Phase F follow-up PR can swap it for a configurable source (env var, TOML config, CLI flag) without touching the function body. The recommended path:++1. Read the list from `Config::subscription_ua_prefixes` (Rust) / `headroom.config.Settings.subscription_ua_prefixes` (Python).+2. Default to the current static list if unset.+3. Pass the list as a parameter to `classify` / `classify_auth_mode`.++The classifier itself is a pure function — adding a parameter is a localized change.++## Performance++| Path | Per-call latency (p50) |+|---|---|+| Rust empty headers | ~20 ns |+| Rust PAYG (Bearer prefix match) | ~50 ns |+| Rust Subscription (UA lowercase + scan) | ~600 ns |+| Python empty headers | ~3 us |+| Python Subscription | ~12 us |++All paths are well under the <10us Rust budget and the <100us Python budget asserted by the test suite.++## Where the auth-mode value flows++After classification, the value is stored on the request object so downstream code reads it without re-classifying:++- **Rust:** `req.extensions_mut().insert(auth_mode)`. Read with `req.extensions().get::<headroom_core::auth_mode::AuthMode>()`.+- **Python:** `request.state.auth_mode`. Read with `request.state.auth_mode`.++A structured log line (`event = auth_mode_classified`) fires once per request at request entry; the value is logged as `auth_mode = "payg" | "oauth" | "subscription"`.++## Phase F roadmap++PR-F1 (this PR) lands the helper. The rest of Phase F wires it into specific policy gates:++- **PR-F2:** per-mode compression policy gates (auto-`cache_control`, `prompt_cache_key`, lossy compressors).+- **PR-F3:** TOIN per-tenant aggregation key includes `(auth_mode, model_family, structure_hash)`.+- **PR-F4:** `X-Forwarded-*` skipped on Subscription mode.++See `REALIGNMENT/08-phase-F-auth-mode.md` for the full phase plan.diff --git a/headroom/proxy/auth_mode.py b/headroom/proxy/auth_mode.pynew file mode 100644index 000000000..baff7bdda--- /dev/null+++ b/headroom/proxy/auth_mode.py@@ -0,0 +1,183 @@+"""Auth-mode classifier — Phase F PR-F1 (Python port).++Direct port of ``crates/headroom-core/src/auth_mode.rs``. The two+implementations MUST agree on the classification of every header set+the parity tests cover (``tests/test_auth_mode.py``).++See the Rust module for the full WHY of three modes (PAYG / OAuth /+Subscription) and the per-mode compression policy implications. This+port is the live classifier on the Python proxy paths until Phase H+deletes the Python proxy entirely.++The classifier is **pure** (no I/O, no logging of header values), runs+well under 10us per call, and NEVER raises on malformed headers —+non-UTF-8 / unparseable values fall through to the safe default+:data:`AuthMode.PAYG` after a ``logger.warning`` so operators can+spot bad clients without taking the proxy down.+"""++from __future__ import annotations++import enum+import logging+from collections.abc import Mapping+from typing import Any++logger = logging.getLogger(__name__)+++class AuthMode(str, enum.Enum):+ """Three auth-mode classes Headroom routes compression policy through.++ Subclasses :class:`str` so the enum members serialize transparently+ into structured logs / metric labels / TOIN aggregation keys. The+ string form matches the Rust ``AuthMode::as_str()`` output exactly.+ """++ #: Pay-as-you-go API key. Aggressive live-zone compression OK.+ PAYG = "payg"++ #: OAuth bearer / Bedrock IAM / Vertex ADC. Passthrough-prefer:+ #: no auto-cache_control, no auto-prompt_cache_key, no lossy+ #: compressors. Lossless-only path.+ OAUTH = "oauth"++ #: Subscription-bound CLI / IDE. Stealth: same as OAuth + preserve+ #: ``accept-encoding``, never strip; never inject ``X-Headroom-*``;+ #: never mutate ``User-Agent``.+ SUBSCRIPTION = "subscription"+++# User-Agent prefixes that identify a UX-bound CLI / IDE.+#+# Lives at module scope (not inside :func:`classify_auth_mode`) so:+# 1. A future PR can swap this for a configurable list (Phase F+# follow-up) without touching the function body.+# 2. Adding a new client = one-line edit here, no logic change.+#+# Match is ``str.__contains__`` against a lowercased copy of the UA —+# so the prefix can appear anywhere in the value.+SUBSCRIPTION_UA_PREFIXES: tuple[str, ...] = (+ "claude-cli/",+ "claude-code/",+ "codex-cli/",+ "cursor/",+ "claude-vscode/",+ "github-copilot/",+ "anthropic-cli/",+ "antigravity/",+)+++def _header_get(headers: Mapping[str, Any] | Any, name: str) -> str:+ """Read a single header, case-insensitively, returning ``""`` on miss.++ Accepts either a plain ``Mapping[str, str]`` (test fixtures) or a+ Starlette/FastAPI ``Headers`` object (production). Handles bytes+ values defensively — non-UTF-8 returns ``""`` after a warning,+ matching the Rust path's behaviour.+ """+ # Starlette `Headers` is case-insensitive natively; plain dicts+ # are not. Try a direct lookup first (covers Starlette + the+ # tests), then fall through to a manual case-insensitive scan.+ value: Any = None+ try:+ # Starlette's Headers, plain dict+ value = headers.get(name)+ if value is None:+ # Some test fixtures pass a normal dict with mixed case.+ for k, v in headers.items(): # type: ignore[union-attr]+ if isinstance(k, str) and k.lower() == name:+ value = v+ break+ except AttributeError:+ return ""++ if value is None:+ return ""+ if isinstance(value, bytes):+ try:+ return value.decode("utf-8")+ except UnicodeDecodeError:+ logger.warning(+ "auth_mode_classify_unparseable_%s",+ name.replace("-", "_"),+ extra={"event": f"auth_mode_classify_unparseable_{name.replace('-', '_')}"},+ )+ return ""+ return str(value)+++def classify_auth_mode(headers: Mapping[str, Any] | Any) -> AuthMode:+ """Classify the auth mode of an inbound request from its headers.++ Decision order (most-specific signal wins):++ 1. **Subscription UA prefix** → :data:`AuthMode.SUBSCRIPTION`.+ The CLI's own auth-mode wins over the bearer token shape it+ happens to be carrying — a Claude Code session uses a+ ``sk-ant-oat-*`` token but is a subscription client, not OAuth.+ 2. **``Authorization: Bearer sk-ant-oat-*``** → :data:`AuthMode.OAUTH`+ (Claude Pro / Max OAuth). Checked before the broader ``sk-``+ PAYG rule because ``sk-ant-oat-`` shares the ``sk-`` prefix.+ 3. **``Authorization: Bearer sk-ant-api*`` or ``Bearer sk-*``** →+ :data:`AuthMode.PAYG` (Anthropic / OpenAI API key).+ 4. **``Authorization: Bearer <jwt>``** (3 dot-separated segments)+ → :data:`AuthMode.OAUTH` (Codex / Cursor / Copilot OAuth).+ 5. **``Authorization`` present but not ``Bearer ...``** →+ :data:`AuthMode.OAUTH` (AWS SigV4 ``AWS4-HMAC-SHA256 ...`` →+ Bedrock; any other non-Bearer scheme is presumed+ passthrough-prefer too).+ 6. **``x-api-key`` present** → :data:`AuthMode.PAYG` (Anthropic+ API key style).+ 7. **``x-goog-api-key`` present** → :data:`AuthMode.PAYG` (Gemini+ key).+ 8. **Default** → :data:`AuthMode.PAYG` (safest default; aggressive+ compression on a misclassified request just costs us a re-run,+ not a revoked subscription).++ Performance: one ``str.lower`` allocation for the UA copy. All+ other matches are zero-allocation ``startswith`` / ``in`` /+ ``str.split('.')``. Target: <10us per call.+ """+ # ── User-Agent ────────────────────────────────────────────────+ ua_lower = _header_get(headers, "user-agent").lower()+ for prefix in SUBSCRIPTION_UA_PREFIXES:+ if prefix in ua_lower:+ return AuthMode.SUBSCRIPTION++ # ── Authorization header ──────────────────────────────────────+ auth = _header_get(headers, "authorization")++ if auth.startswith("Bearer "):+ token = auth[len("Bearer ") :]+ # Order matters: `sk-ant-oat-*` shares a prefix with+ # `sk-ant-api*` only at `sk-ant-`, so check OAuth first.+ if token.startswith("sk-ant-oat-"):+ return AuthMode.OAUTH+ if token.startswith("sk-ant-api") or token.startswith("sk-"):+ return AuthMode.PAYG+ # JWT: classic three-segment `header.payload.signature`.+ # We don't validate the JWT — just count dot-separated+ # segments. Catches Codex / Cursor / Copilot OAuth.+ if len(token.split(".")) >= 3:+ return AuthMode.OAUTH+ # Unknown bearer shape — fall through.+ elif auth:+ # Authorization is present but NOT `Bearer ...` — most+ # commonly AWS SigV4 (`AWS4-HMAC-SHA256 ...`) on a Bedrock+ # request, or a `Basic ...` from a custom proxy chain. We+ # treat all such non-Bearer schemes as passthrough-prefer.+ return AuthMode.OAUTH++ # ── Vendor-specific API-key headers ───────────────────────────+ if _header_get(headers, "x-api-key"):+ return AuthMode.PAYG+ if _header_get(headers, "x-goog-api-key"):+ return AuthMode.PAYG++ # ── Default ───────────────────────────────────────────────────+ return AuthMode.PAYG+++__all__ = ["AuthMode", "SUBSCRIPTION_UA_PREFIXES", "classify_auth_mode"]diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.pyindex 7633200f9..2b598fde3 100644--- a/headroom/proxy/handlers/anthropic.py+++ b/headroom/proxy/handlers/anthropic.py@@ -24,6 +24,7 @@ if TYPE_CHECKING:import httpxfrom headroom.pipeline import PipelineStage, summarize_routing_markers+from headroom.proxy.auth_mode import classify_auth_modelogger = logging.getLogger("headroom.proxy")@@ -354,6 +355,14 @@ class AnthropicHandlerMixin:request_id = await self._next_request_id()trace_session_id = uuid.uuid4().hex+ # Phase F PR-F1: classify auth mode at request entry. The result+ # is stored on `request.state` so downstream handlers (cache+ # gates, header injection, lossy-compressor gates) read it+ # without re-classifying. Pure function, well under 10us.+ auth_mode = classify_auth_mode(request.headers)+ request.state.auth_mode = auth_mode+ logger.debug(f"[{request_id}] auth_mode_classified mode={auth_mode.value}")+# Unit 2: per-stage timings for the pre-upstream phase. The# finalizer emits one structured log line + Prometheus# observations even if the handler raises.diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex 2289e7899..5768b3f59 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -33,6 +33,7 @@ import httpxfrom headroom.copilot_auth import apply_copilot_api_auth, build_copilot_upstream_urlfrom headroom.pipeline import PipelineStage, summarize_routing_markers+from headroom.proxy.auth_mode import classify_auth_modelogger = logging.getLogger("headroom.proxy")@@ -164,6 +165,14 @@ class OpenAIHandlerMixin:start_time = time.time()request_id = await self._next_request_id()+ # Phase F PR-F1: classify auth mode at request entry. The result+ # is stored on `request.state` so downstream handlers (cache+ # gates, header injection, lossy-compressor gates) read it+ # without re-classifying. Pure function, well under 10us.+ auth_mode = classify_auth_mode(request.headers)+ request.state.auth_mode = auth_mode+ logger.debug(f"[{request_id}] auth_mode_classified mode={auth_mode.value}")+# Check request body sizecontent_length = request.headers.get("content-length")if content_length and int(content_length) > MAX_REQUEST_BODY_SIZE:@@ -1161,6 +1170,14 @@ class OpenAIHandlerMixin:start_time = time.time()request_id = await self._next_request_id()+ # Phase F PR-F1: classify auth mode at request entry. The result+ # is stored on `request.state` so downstream handlers (cache+ # gates, header injection, lossy-compressor gates) read it+ # without re-classifying. Pure function, well under 10us.+ auth_mode = classify_auth_mode(request.headers)+ request.state.auth_mode = auth_mode+ logger.debug(f"[{request_id}] auth_mode_classified mode={auth_mode.value}")+# Check request body sizecontent_length = request.headers.get("content-length")if content_length and int(content_length) > MAX_REQUEST_BODY_SIZE:diff --git a/tests/test_auth_mode.py b/tests/test_auth_mode.pynew file mode 100644index 000000000..d33278aa8--- /dev/null+++ b/tests/test_auth_mode.py@@ -0,0 +1,188 @@+"""Python parity tests for ``headroom.proxy.auth_mode.classify_auth_mode``.++Mirrors the Rust matrix in ``crates/headroom-core/tests/auth_mode.rs``+byte-for-byte. The two implementations MUST agree on every header set+covered here. Any divergence is a bug — we catch it at PR review by+running both suites side by side.+"""++from __future__ import annotations++import time++import pytest++from headroom.proxy.auth_mode import (+ SUBSCRIPTION_UA_PREFIXES,+ AuthMode,+ classify_auth_mode,+)+++def _h(**pairs: str) -> dict[str, str]:+ """Build a plain-dict header set in one expression."""+ return dict(pairs)+++# ── Required matrix ──────────────────────────────────────────────+++def test_api_key_classified_payg() -> None:+ """Anthropic PAYG: ``Authorization: Bearer sk-ant-api03-...``."""+ headers = {"authorization": "Bearer sk-ant-api03-abc123def456"}+ assert classify_auth_mode(headers) is AuthMode.PAYG+++def test_oauth_jwt_classified_oauth() -> None:+ """Codex / Cursor OAuth bearer: classic 3-segment JWT."""+ jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0In0.signaturepart"+ headers = {"authorization": f"Bearer {jwt}"}+ assert classify_auth_mode(headers) is AuthMode.OAUTH+++def test_oauth_sk_ant_oat_classified_oauth() -> None:+ """Claude Pro / Max OAuth: ``Bearer sk-ant-oat-...``."""+ headers = {"authorization": "Bearer sk-ant-oat-01-abc123def456"}+ assert classify_auth_mode(headers) is AuthMode.OAUTH+++def test_claude_code_ua_classified_subscription() -> None:+ """Claude Code CLI: ``User-Agent: claude-code/1.2.3 ...``."""+ headers = {"user-agent": "claude-code/1.2.3 (darwin; arm64)"}+ assert classify_auth_mode(headers) is AuthMode.SUBSCRIPTION+++def test_cursor_ua_classified_subscription() -> None:+ """Cursor CLI: ``User-Agent: cursor/1.0``."""+ headers = {"user-agent": "cursor/1.0"}+ assert classify_auth_mode(headers) is AuthMode.SUBSCRIPTION+++def test_no_auth_no_user_agent_default_payg() -> None:+ """Empty headers → safest default is PAYG.++ The OAuth/bedrock branch fires only when there's a positive+ non-Bearer auth signal. Choosing PAYG by default favors the+ OSS-default workload (per-token cost saving).+ """+ assert classify_auth_mode({}) is AuthMode.PAYG+++def test_bedrock_no_auth_classified_oauth() -> None:+ """Bedrock SigV4: ``Authorization: AWS4-HMAC-SHA256 Credential=...``.++ Not a Bearer scheme; we treat all non-Bearer Authorization as+ OAuth (passthrough-prefer).+ """+ headers = {+ "authorization": (+ "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20260501/"+ "us-east-1/bedrock/aws4_request, SignedHeaders=host;x-amz-date, "+ "Signature=fe5f80f77d5fa3beca038a248ff027"+ ),+ }+ assert classify_auth_mode(headers) is AuthMode.OAUTH+++# ── Bonus matrix ──────────────────────────────────────────────────+++def test_openai_payg_sk_classified_payg() -> None:+ """OpenAI PAYG: ``Authorization: Bearer sk-proj-...``."""+ headers = {"authorization": "Bearer sk-proj-abcdef0123456789"}+ assert classify_auth_mode(headers) is AuthMode.PAYG+++def test_gemini_x_goog_api_key_classified_payg() -> None:+ """Google Gemini API key as ``x-goog-api-key``."""+ headers = {"x-goog-api-key": "AIzaSyDUMMYKEY1234567890"}+ assert classify_auth_mode(headers) is AuthMode.PAYG+++def test_subscription_takes_precedence_over_oauth_token() -> None:+ """Claude Code CLI sends ``Bearer sk-ant-oat-...`` but is subscription.++ UA wins because the rate-limit / fingerprint policy is bound to+ the CLI, not the token shape. The same token via a non-CLI UA+ would be OAuth.+ """+ headers = {+ "user-agent": "claude-code/1.5.0 (linux; x86_64)",+ "authorization": "Bearer sk-ant-oat-01-abc123",+ }+ assert classify_auth_mode(headers) is AuthMode.SUBSCRIPTION+++# ── Edge cases (defensive coverage) ──────────────────────────────+++def test_anthropic_x_api_key_classified_payg() -> None:+ """Anthropic API key style: ``x-api-key: sk-ant-...``."""+ headers = {"x-api-key": "sk-ant-api03-abcdef"}+ assert classify_auth_mode(headers) is AuthMode.PAYG++[email protected]("prefix", SUBSCRIPTION_UA_PREFIXES)+def test_every_subscription_prefix_classified_subscription(prefix: str) -> None:+ """Each entry in the prefix list classifies as Subscription on its own."""+ headers = {"user-agent": f"{prefix}1.0 (test)"}+ assert classify_auth_mode(headers) is AuthMode.SUBSCRIPTION+++def test_unparseable_authorization_does_not_raise() -> None:+ """Bytes-valued non-UTF-8 authorization warns and falls through.++ Mirrors the Rust ``classify`` behaviour: never panic, always+ return a valid ``AuthMode``. With nothing else to disambiguate,+ we land on PAYG (the safe default).+ """+ headers = {"authorization": b"\xffnope"}+ # Should not raise.+ result = classify_auth_mode(headers)+ assert result is AuthMode.PAYG+++def test_case_insensitive_header_lookup() -> None:+ """Header names are matched case-insensitively (Starlette parity)."""+ headers = {"Authorization": "Bearer sk-ant-api03-test"}+ assert classify_auth_mode(headers) is AuthMode.PAYG+++def test_enum_values_match_rust_as_str() -> None:+ """The string form of each enum member matches the Rust ``as_str()``."""+ assert AuthMode.PAYG.value == "payg"+ assert AuthMode.OAUTH.value == "oauth"+ assert AuthMode.SUBSCRIPTION.value == "subscription"+++# ── Performance ──────────────────────────────────────────────────+++def test_classify_under_100us_per_call() -> None:+ """Smoke perf check.++ Python is slower than Rust by an order of magnitude on string+ work, so the budget here is 100us (vs 10us in Rust). The proxy+ only calls this once per request, and the absolute ceiling is+ well under 1ms; this guards against pathological regressions.+ """+ headers = {+ "user-agent": "claude-code/1.5.0 (linux; x86_64) anthropic/0.42.0",+ "authorization": "Bearer sk-ant-oat-01-abcdefghijklmnopqrstuv",+ "content-type": "application/json",+ "accept": "application/json",+ "host": "api.anthropic.com",+ }++ # Warmup+ for _ in range(1000):+ classify_auth_mode(headers)++ iters = 10_000+ start = time.perf_counter()+ for _ in range(iters):+ classify_auth_mode(headers)+ elapsed = time.perf_counter() - start+ per_call_us = (elapsed / iters) * 1_000_000++ assert per_call_us < 100, f"classify_auth_mode took {per_call_us:.2f} us/call (limit: 100 us)"