firstpass-proxy 0.10.0

Drop-in, Anthropic-compatible LLM proxy that routes each request to the cheapest model that provably passes a quality gate, escalates on failure, and records a tamper-evident audit trace.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! Multi-tenant API-key authentication (ADR 0004 §D1) — the hosted plane's front door.
//!
//! **EXPERIMENTAL / pre-external-review (ADR 0004 §D7).** This is the *foundation* for tenant
//! isolation; it has NOT yet had the independent, non-author security review the ADR requires.
//! Do not rely on it as a hard isolation boundary for real, mutually-distrusting tenants until
//! that review lands. It is default-OFF (`FIRSTPASS_REQUIRE_AUTH=false`): with auth disabled the
//! single-operator path is unchanged and this module only stamps the static default tenant.
//!
//! Keys are verified against **Argon2id** password hashes via the crate's own constant-time
//! [`PasswordVerifier`] path (ADR 0004 §D1) — we never roll our own comparison. A missing or
//! invalid key returns `401` with an opaque body, so there is no "unknown tenant" oracle.

use std::collections::HashMap;

use argon2::Argon2;
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
use axum::extract::{Request, State};
use axum::http::{HeaderMap, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};

use crate::error::ProxyError;
use crate::proxy::AppState;

/// Prefix for the `Authorization: Bearer <key>` header.
const BEARER_PREFIX: &str = "Bearer ";
/// Alternative header carrying the raw tenant API key.
const KEY_HEADER: &str = "x-firstpass-key";

/// A resolved tenant identity, injected into request extensions by [`auth_middleware`].
///
/// This is the *only* source of a request's tenant: it comes either from a verified API key
/// (auth on) or the static default (auth off) — never from anything in the request body.
#[derive(Clone, Debug)]
pub struct TenantId(pub String);

/// Argon2id-hashed per-tenant API keys, keyed by tenant id.
///
/// A presented key has the form `<tenant_id>.<secret>`: the (non-secret) tenant id names which
/// hash to check, so verification is O(1) — exactly one Argon2 verify — rather than one per tenant.
///
/// `Debug` deliberately redacts every hash — they are password-equivalent secrets — revealing
/// only the configured tenant ids so a `ProxyConfig` dump can never leak credential material.
#[derive(Clone, Default)]
pub struct TenantKeys {
    /// `tenant_id` -> PHC-encoded Argon2id hash of that tenant's secret.
    hashes: HashMap<String, String>,
    /// A valid Argon2 hash of a throwaway secret, verified against on the unknown-tenant path so an
    /// invalid key takes the same time whether or not the named tenant exists — no existence oracle.
    decoy: String,
}

impl std::fmt::Debug for TenantKeys {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TenantKeys")
            .field("tenants", &self.hashes.keys().collect::<Vec<_>>())
            .field("hashes", &"<redacted>")
            .finish()
    }
}

/// Errors building [`TenantKeys`] or hashing a key.
#[derive(Debug, thiserror::Error)]
pub enum AuthConfigError {
    /// The tenant-keys JSON did not parse into `{ tenant_id: hash }`.
    #[error("tenant keys JSON is invalid: {0}")]
    Json(#[from] serde_json::Error),
    /// A configured hash is not a valid Argon2 PHC string (fail closed at startup, not per-request).
    #[error("tenant {tenant:?} has an invalid Argon2 hash")]
    BadHash {
        /// The offending tenant id (never the hash itself).
        tenant: String,
    },
    /// The Argon2 hasher failed while provisioning a new key.
    #[error("argon2 hashing failed")]
    Hash,
}

impl TenantKeys {
    /// Parse from a JSON object `{ "<tenant_id>": "<argon2id-phc-hash>", ... }`.
    ///
    /// Every hash is validated up front so a malformed roster fails at startup rather than
    /// silently rejecting every request at runtime.
    ///
    /// # Errors
    /// [`AuthConfigError::Json`] if the JSON is malformed; [`AuthConfigError::BadHash`] if any
    /// value is not a valid Argon2 PHC hash string.
    pub fn from_json(s: &str) -> Result<Self, AuthConfigError> {
        let hashes: HashMap<String, String> = serde_json::from_str(s)?;
        for (tenant, hash) in &hashes {
            PasswordHash::new(hash).map_err(|_| AuthConfigError::BadHash {
                tenant: tenant.clone(),
            })?;
        }
        // Decoy hash for the unknown-tenant path (equalizes verify time). Computed once at startup.
        let decoy = Self::hash_key("firstpass-unknown-tenant-decoy")?;
        Ok(Self { hashes, decoy })
    }

    /// Whether any tenant keys are configured.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.hashes.is_empty()
    }

    /// Verify a presented `<tenant_id>.<secret>` key, returning the owning tenant on a match. The
    /// tenant id (before the first `.`, not itself secret) names which hash to check, so this does
    /// **exactly one** Argon2 verify — O(1), not O(tenants) — using the crate's constant-time
    /// [`PasswordVerifier`], never a plain `==`.
    ///
    /// An unknown tenant id (or a malformed key) still performs one Argon2 verify against a decoy
    /// hash, so an invalid key takes the same time whether or not the named tenant exists — this
    /// closes both the CPU-amplification DoS and the tenant-existence timing oracle. Tenant ids must
    /// not contain `.` (they are simple identifiers; the first `.` splits id from secret).
    #[must_use]
    pub fn verify(&self, presented_key: &str) -> Option<TenantId> {
        let argon = Argon2::default();
        let (tenant_id, secret) = presented_key.split_once('.').unwrap_or(("", presented_key));
        if let Some(hash) = self.hashes.get(tenant_id) {
            if let Ok(parsed) = PasswordHash::new(hash)
                && argon.verify_password(secret.as_bytes(), &parsed).is_ok()
            {
                return Some(TenantId(tenant_id.to_owned()));
            }
            return None;
        }
        // Unknown tenant: burn one verify against the decoy to equalize timing, then fail.
        if let Ok(decoy) = PasswordHash::new(&self.decoy) {
            let _ = argon.verify_password(secret.as_bytes(), &decoy);
        }
        None
    }

    /// Hash a fresh secret into a PHC-encoded Argon2id string for provisioning a tenant key.
    /// Operators store the returned hash; the plaintext key is shown to the tenant once and is
    /// never persisted here.
    ///
    /// # Errors
    /// [`AuthConfigError::Hash`] if the Argon2 hasher fails.
    pub fn hash_key(secret: &str) -> Result<String, AuthConfigError> {
        let salt = SaltString::generate(&mut argon2::password_hash::rand_core::OsRng);
        Argon2::default()
            .hash_password(secret.as_bytes(), &salt)
            .map(|h| h.to_string())
            .map_err(|_| AuthConfigError::Hash)
    }
}

/// Axum middleware: resolve the tenant for a request and inject a [`TenantId`] into extensions.
///
/// - `require_auth = false` (default): no auth check; injects the static default tenant so every
///   downstream handler reads a uniform identity. Single-operator behavior is unchanged.
/// - `require_auth = true`: reads the key from `Authorization: Bearer <key>` (or `x-firstpass-key`),
///   verifies it against the configured tenant hashes, and injects the resolved tenant. A missing
///   or invalid key returns `401` with an opaque body — no "unknown tenant" oracle.
pub async fn auth_middleware(
    State(state): State<AppState>,
    mut req: Request,
    next: Next,
) -> Response {
    if !state.config.require_auth {
        req.extensions_mut()
            .insert(TenantId(state.config.tenant_id.clone()));
        return next.run(req).await;
    }
    // Argon2 is deliberately slow CPU work; on the async worker it would stall every other
    // request on that thread for the length of a verify. A failed join fails closed (401).
    //
    // Determine the credential source BEFORE the verify so we can strip the Authorization header
    // if Bearer was used as the tenant credential — preventing it from being forwarded upstream.
    let bearer_was_tenant = key_came_from_bearer_only(req.headers());
    let verified = match extract_key(req.headers()) {
        Some(key) => {
            let config = state.config.clone();
            tokio::task::spawn_blocking(move || config.tenant_keys.verify(&key))
                .await
                .ok()
                .flatten()
        }
        None => None,
    };
    match verified {
        Some(tenant) => {
            req.extensions_mut().insert(tenant);
            // SECURITY: if the tenant credential was taken from Authorization: Bearer, strip it
            // now so it is never forwarded to the upstream model provider (observe or enforce path).
            if bearer_was_tenant {
                req.headers_mut().remove(header::AUTHORIZATION);
            }
            next.run(req).await
        }
        None => ProxyError::Unauthorized.into_response(),
    }
}

/// Read the tenant API key from `x-firstpass-key` (preferred) or `Authorization: Bearer <key>`.
///
/// `x-firstpass-key` takes precedence so that OpenAI-compatible clients which send
/// `Authorization: Bearer sk-…` as their *provider* key are not mistaken for a tenant credential.
/// When a client sends both, `x-firstpass-key` is the tenant credential and Authorization reaches
/// the provider unchanged.
fn extract_key(headers: &HeaderMap) -> Option<String> {
    // Prefer the dedicated header — leaves Authorization for the upstream provider.
    if let Some(key) = headers
        .get(KEY_HEADER)
        .and_then(|v| v.to_str().ok())
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        return Some(key.to_owned());
    }
    // Fall back to Bearer — but auth_middleware will strip it before forwarding upstream.
    headers
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix(BEARER_PREFIX))
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_owned)
}

/// Whether the request's only tenant-key source is `Authorization: Bearer`.
///
/// Returns `true` when no non-empty `x-firstpass-key` is present and a non-empty Bearer token
/// exists. The middleware uses this to strip the Authorization header before forwarding upstream
/// so that a tenant credential sent as Bearer is never relayed to the model provider.
///
/// An empty or whitespace-only `x-firstpass-key` is treated as absent: the header value can
/// carry no real key, so Bearer is still the (only) credential source and must be stripped.
fn key_came_from_bearer_only(headers: &HeaderMap) -> bool {
    let has_explicit_key = headers
        .get(KEY_HEADER)
        .and_then(|v| v.to_str().ok())
        .map(str::trim)
        .is_some_and(|s| !s.is_empty());
    if has_explicit_key {
        return false; // x-firstpass-key is the credential; Bearer is for the provider.
    }
    headers
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix(BEARER_PREFIX))
        .map(str::trim)
        .is_some_and(|s| !s.is_empty())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn argon2_hash_round_trips_and_rejects_wrong_key() {
        let hash = TenantKeys::hash_key("s3cret-key").unwrap();
        let json = format!("{{\"acme\": {hash:?}}}");
        let keys = TenantKeys::from_json(&json).unwrap();

        // Correct `<tenant>.<secret>` key resolves to its tenant.
        assert_eq!(
            keys.verify("acme.s3cret-key").map(|t| t.0).as_deref(),
            Some("acme")
        );
        // Right tenant, wrong secret → nothing.
        assert!(keys.verify("acme.wrong-key").is_none());
        // Unknown tenant → nothing (and it still burns a decoy verify — no existence oracle).
        assert!(keys.verify("ghost.s3cret-key").is_none());
        // Malformed (no `.`) and empty keys never match.
        assert!(keys.verify("s3cret-key").is_none());
        assert!(keys.verify("").is_none());
    }

    #[test]
    fn two_tenants_resolve_to_their_own_identity() {
        let a = TenantKeys::hash_key("key-a").unwrap();
        let b = TenantKeys::hash_key("key-b").unwrap();
        let json = format!("{{\"tenant-a\": {a:?}, \"tenant-b\": {b:?}}}");
        let keys = TenantKeys::from_json(&json).unwrap();

        assert_eq!(
            keys.verify("tenant-a.key-a").map(|t| t.0).as_deref(),
            Some("tenant-a")
        );
        assert_eq!(
            keys.verify("tenant-b.key-b").map(|t| t.0).as_deref(),
            Some("tenant-b")
        );
        // Tenant A's id with tenant B's secret is rejected — you can't cross tenants.
        assert!(keys.verify("tenant-a.key-b").is_none());
        // A secret for no configured tenant is rejected.
        assert!(keys.verify("tenant-c.key-c").is_none());
    }

    #[test]
    fn invalid_hash_in_config_is_rejected_at_build_time() {
        let json = r#"{"acme": "not-a-real-argon2-hash"}"#;
        assert!(matches!(
            TenantKeys::from_json(json),
            Err(AuthConfigError::BadHash { tenant }) if tenant == "acme"
        ));
    }

    #[test]
    fn debug_redacts_hashes() {
        let hash = TenantKeys::hash_key("top-secret").unwrap();
        let json = format!("{{\"acme\": {hash:?}}}");
        let keys = TenantKeys::from_json(&json).unwrap();
        let dbg = format!("{keys:?}");
        assert!(dbg.contains("acme"), "tenant id is fine to show");
        assert!(dbg.contains("<redacted>"), "hashes must be redacted");
        assert!(
            !dbg.contains("$argon2"),
            "no hash material may leak in Debug"
        );
    }

    #[test]
    fn extract_key_prefers_custom_header_over_bearer() {
        // Custom header only → used.
        let mut h = HeaderMap::new();
        h.insert(KEY_HEADER, "xyz789".parse().unwrap());
        assert_eq!(extract_key(&h).as_deref(), Some("xyz789"));

        // Bearer only → used as fallback.
        let mut h2 = HeaderMap::new();
        h2.insert(header::AUTHORIZATION, "Bearer abc123".parse().unwrap());
        assert_eq!(extract_key(&h2).as_deref(), Some("abc123"));

        // Both present → custom header wins (Bearer is for the provider, not the tenant).
        let mut h3 = HeaderMap::new();
        h3.insert(KEY_HEADER, "tenant-key".parse().unwrap());
        h3.insert(
            header::AUTHORIZATION,
            "Bearer provider-key".parse().unwrap(),
        );
        assert_eq!(extract_key(&h3).as_deref(), Some("tenant-key"));

        // No key header at all.
        assert!(extract_key(&HeaderMap::new()).is_none());
        // Empty bearer token is not a key.
        let mut h4 = HeaderMap::new();
        h4.insert(header::AUTHORIZATION, "Bearer ".parse().unwrap());
        assert!(extract_key(&h4).is_none());
    }

    #[test]
    fn key_came_from_bearer_only_detects_bearer_without_custom_header() {
        // Bearer only → true.
        let mut h = HeaderMap::new();
        h.insert(header::AUTHORIZATION, "Bearer abc123".parse().unwrap());
        assert!(key_came_from_bearer_only(&h));

        // Custom header present (with or without Bearer) → false.
        let mut h2 = HeaderMap::new();
        h2.insert(KEY_HEADER, "tenant-key".parse().unwrap());
        assert!(!key_came_from_bearer_only(&h2));

        let mut h3 = HeaderMap::new();
        h3.insert(KEY_HEADER, "tenant-key".parse().unwrap());
        h3.insert(
            header::AUTHORIZATION,
            "Bearer provider-key".parse().unwrap(),
        );
        assert!(!key_came_from_bearer_only(&h3));

        // No headers → false.
        assert!(!key_came_from_bearer_only(&HeaderMap::new()));

        // Empty bearer → false (not a valid key).
        let mut h4 = HeaderMap::new();
        h4.insert(header::AUTHORIZATION, "Bearer ".parse().unwrap());
        assert!(!key_came_from_bearer_only(&h4));
    }

    #[test]
    fn key_came_from_bearer_only_treats_empty_or_whitespace_custom_header_as_absent() {
        // x-firstpass-key is present but empty → Bearer is still the only credential; strip it.
        let mut h = HeaderMap::new();
        h.insert(KEY_HEADER, "".parse().unwrap());
        h.insert(header::AUTHORIZATION, "Bearer real-token".parse().unwrap());
        assert!(
            key_came_from_bearer_only(&h),
            "empty x-firstpass-key must not suppress Bearer stripping"
        );

        // x-firstpass-key is present but whitespace-only → same.
        let mut h2 = HeaderMap::new();
        h2.insert(KEY_HEADER, "   ".parse().unwrap());
        h2.insert(header::AUTHORIZATION, "Bearer real-token".parse().unwrap());
        assert!(
            key_came_from_bearer_only(&h2),
            "whitespace x-firstpass-key must not suppress Bearer stripping"
        );

        // x-firstpass-key has a real value → Bearer is the provider key; do NOT strip.
        let mut h3 = HeaderMap::new();
        h3.insert(KEY_HEADER, "tenant-key".parse().unwrap());
        h3.insert(
            header::AUTHORIZATION,
            "Bearer provider-key".parse().unwrap(),
        );
        assert!(
            !key_came_from_bearer_only(&h3),
            "non-empty x-firstpass-key means Bearer is a provider key, not the tenant key"
        );
    }

    // ── Defect 4: auth middleware integration tests ──────────────────────────────

    /// Build a minimal `AppState` with auth enabled and the given tenant hash JSON.
    fn auth_state(hash_json: &str) -> crate::proxy::AppState {
        use std::sync::Arc;
        let config = crate::config::ProxyConfig::from_lookup(|k| match k {
            "FIRSTPASS_REQUIRE_AUTH" => Some("true".to_owned()),
            "FIRSTPASS_TENANT_KEYS_JSON" => Some(hash_json.to_owned()),
            _ => None,
        })
        .expect("minimal auth config");
        let (traces, _rx) = tokio::sync::mpsc::channel(1);
        crate::proxy::AppState {
            config: Arc::new(config),
            http: reqwest::Client::new(),
            providers: crate::provider::ProviderRegistry::from_map(Default::default()),
            gate_health: Arc::new(crate::gate::GateHealthRegistry::new()),
            shadow_ledger: Arc::new(crate::shadow::ShadowLedger::new()),
            paired_ledger: Arc::new(crate::shadow::ShadowLedger::new()),
            experiments: Arc::default(),
            guardrails: Arc::new(crate::guard::GuardrailRegistry::new()),
            traces,
            adaptive: None,
            eprocess: None,
            bandit: None,
            promoter: None,
            verified_cache: None,
            predictor: None,
            prior: None,
            tenant_rate_limiter: None,
            spill: None,
        }
    }

    /// Build an axum app that runs `auth_middleware` and then echoes the `Authorization` header
    /// value (or empty string) from the downstream view.
    fn auth_echo_app(state: crate::proxy::AppState) -> axum::Router {
        let inner = axum::routing::get(|req: axum::extract::Request| async move {
            req.headers()
                .get(header::AUTHORIZATION)
                .and_then(|v| v.to_str().ok())
                .unwrap_or("")
                .to_owned()
        });
        axum::Router::new()
            .route("/test", inner)
            .layer(axum::middleware::from_fn_with_state(
                state.clone(),
                auth_middleware,
            ))
            .with_state(state)
    }

    #[tokio::test]
    async fn auth_middleware_strips_bearer_when_used_as_tenant_key() {
        use tower::ServiceExt;
        let hash = TenantKeys::hash_key("my-secret").unwrap();
        let json = format!("{{\"acme\": {hash:?}}}");
        let app = auth_echo_app(auth_state(&json));

        // Bearer carries the tenant credential "acme.my-secret" — no x-firstpass-key.
        let req = axum::http::Request::builder()
            .uri("/test")
            .header(header::AUTHORIZATION, "Bearer acme.my-secret")
            .body(axum::body::Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK, "tenant verified");
        let body = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
        let downstream_auth = String::from_utf8_lossy(&body);
        assert!(
            downstream_auth.is_empty(),
            "Authorization must be stripped downstream when Bearer was the tenant credential, \
             got: {downstream_auth:?}"
        );
    }

    #[tokio::test]
    async fn auth_middleware_leaves_provider_bearer_when_custom_header_is_tenant_key() {
        use tower::ServiceExt;
        let hash = TenantKeys::hash_key("my-secret").unwrap();
        let json = format!("{{\"acme\": {hash:?}}}");
        let app = auth_echo_app(auth_state(&json));

        // x-firstpass-key carries the tenant credential; Authorization carries the provider key.
        let req = axum::http::Request::builder()
            .uri("/test")
            .header(KEY_HEADER, "acme.my-secret")
            .header(header::AUTHORIZATION, "Bearer sk-provider-key")
            .body(axum::body::Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK, "tenant verified");
        let body = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
        let downstream_auth = String::from_utf8_lossy(&body);
        assert_eq!(
            downstream_auth, "Bearer sk-provider-key",
            "provider Bearer must reach downstream unchanged when x-firstpass-key is the tenant credential"
        );
    }
}