Skip to main content

firstpass_proxy/
tenant_auth.rs

1//! Multi-tenant API-key authentication (ADR 0004 §D1) — the hosted plane's front door.
2//!
3//! **EXPERIMENTAL / pre-external-review (ADR 0004 §D7).** This is the *foundation* for tenant
4//! isolation; it has NOT yet had the independent, non-author security review the ADR requires.
5//! Do not rely on it as a hard isolation boundary for real, mutually-distrusting tenants until
6//! that review lands. It is default-OFF (`FIRSTPASS_REQUIRE_AUTH=false`): with auth disabled the
7//! single-operator path is unchanged and this module only stamps the static default tenant.
8//!
9//! Keys are verified against **Argon2id** password hashes via the crate's own constant-time
10//! [`PasswordVerifier`] path (ADR 0004 §D1) — we never roll our own comparison. A missing or
11//! invalid key returns `401` with an opaque body, so there is no "unknown tenant" oracle.
12
13use std::collections::HashMap;
14
15use argon2::Argon2;
16use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
17use axum::extract::{Request, State};
18use axum::http::{HeaderMap, header};
19use axum::middleware::Next;
20use axum::response::{IntoResponse, Response};
21
22use crate::error::ProxyError;
23use crate::proxy::AppState;
24
25/// Prefix for the `Authorization: Bearer <key>` header.
26const BEARER_PREFIX: &str = "Bearer ";
27/// Alternative header carrying the raw tenant API key.
28const KEY_HEADER: &str = "x-firstpass-key";
29
30/// A resolved tenant identity, injected into request extensions by [`auth_middleware`].
31///
32/// This is the *only* source of a request's tenant: it comes either from a verified API key
33/// (auth on) or the static default (auth off) — never from anything in the request body.
34#[derive(Clone, Debug)]
35pub struct TenantId(pub String);
36
37/// Argon2id-hashed per-tenant API keys, keyed by tenant id.
38///
39/// A presented key has the form `<tenant_id>.<secret>`: the (non-secret) tenant id names which
40/// hash to check, so verification is O(1) — exactly one Argon2 verify — rather than one per tenant.
41///
42/// `Debug` deliberately redacts every hash — they are password-equivalent secrets — revealing
43/// only the configured tenant ids so a `ProxyConfig` dump can never leak credential material.
44#[derive(Clone, Default)]
45pub struct TenantKeys {
46    /// `tenant_id` -> PHC-encoded Argon2id hash of that tenant's secret.
47    hashes: HashMap<String, String>,
48    /// A valid Argon2 hash of a throwaway secret, verified against on the unknown-tenant path so an
49    /// invalid key takes the same time whether or not the named tenant exists — no existence oracle.
50    decoy: String,
51}
52
53impl std::fmt::Debug for TenantKeys {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        f.debug_struct("TenantKeys")
56            .field("tenants", &self.hashes.keys().collect::<Vec<_>>())
57            .field("hashes", &"<redacted>")
58            .finish()
59    }
60}
61
62/// Errors building [`TenantKeys`] or hashing a key.
63#[derive(Debug, thiserror::Error)]
64pub enum AuthConfigError {
65    /// The tenant-keys JSON did not parse into `{ tenant_id: hash }`.
66    #[error("tenant keys JSON is invalid: {0}")]
67    Json(#[from] serde_json::Error),
68    /// A configured hash is not a valid Argon2 PHC string (fail closed at startup, not per-request).
69    #[error("tenant {tenant:?} has an invalid Argon2 hash")]
70    BadHash {
71        /// The offending tenant id (never the hash itself).
72        tenant: String,
73    },
74    /// The Argon2 hasher failed while provisioning a new key.
75    #[error("argon2 hashing failed")]
76    Hash,
77}
78
79impl TenantKeys {
80    /// Parse from a JSON object `{ "<tenant_id>": "<argon2id-phc-hash>", ... }`.
81    ///
82    /// Every hash is validated up front so a malformed roster fails at startup rather than
83    /// silently rejecting every request at runtime.
84    ///
85    /// # Errors
86    /// [`AuthConfigError::Json`] if the JSON is malformed; [`AuthConfigError::BadHash`] if any
87    /// value is not a valid Argon2 PHC hash string.
88    pub fn from_json(s: &str) -> Result<Self, AuthConfigError> {
89        let hashes: HashMap<String, String> = serde_json::from_str(s)?;
90        for (tenant, hash) in &hashes {
91            PasswordHash::new(hash).map_err(|_| AuthConfigError::BadHash {
92                tenant: tenant.clone(),
93            })?;
94        }
95        // Decoy hash for the unknown-tenant path (equalizes verify time). Computed once at startup.
96        let decoy = Self::hash_key("firstpass-unknown-tenant-decoy")?;
97        Ok(Self { hashes, decoy })
98    }
99
100    /// Whether any tenant keys are configured.
101    #[must_use]
102    pub fn is_empty(&self) -> bool {
103        self.hashes.is_empty()
104    }
105
106    /// Verify a presented `<tenant_id>.<secret>` key, returning the owning tenant on a match. The
107    /// tenant id (before the first `.`, not itself secret) names which hash to check, so this does
108    /// **exactly one** Argon2 verify — O(1), not O(tenants) — using the crate's constant-time
109    /// [`PasswordVerifier`], never a plain `==`.
110    ///
111    /// An unknown tenant id (or a malformed key) still performs one Argon2 verify against a decoy
112    /// hash, so an invalid key takes the same time whether or not the named tenant exists — this
113    /// closes both the CPU-amplification DoS and the tenant-existence timing oracle. Tenant ids must
114    /// not contain `.` (they are simple identifiers; the first `.` splits id from secret).
115    #[must_use]
116    pub fn verify(&self, presented_key: &str) -> Option<TenantId> {
117        let argon = Argon2::default();
118        let (tenant_id, secret) = presented_key.split_once('.').unwrap_or(("", presented_key));
119        if let Some(hash) = self.hashes.get(tenant_id) {
120            if let Ok(parsed) = PasswordHash::new(hash)
121                && argon.verify_password(secret.as_bytes(), &parsed).is_ok()
122            {
123                return Some(TenantId(tenant_id.to_owned()));
124            }
125            return None;
126        }
127        // Unknown tenant: burn one verify against the decoy to equalize timing, then fail.
128        if let Ok(decoy) = PasswordHash::new(&self.decoy) {
129            let _ = argon.verify_password(secret.as_bytes(), &decoy);
130        }
131        None
132    }
133
134    /// Hash a fresh secret into a PHC-encoded Argon2id string for provisioning a tenant key.
135    /// Operators store the returned hash; the plaintext key is shown to the tenant once and is
136    /// never persisted here.
137    ///
138    /// # Errors
139    /// [`AuthConfigError::Hash`] if the Argon2 hasher fails.
140    pub fn hash_key(secret: &str) -> Result<String, AuthConfigError> {
141        let salt = SaltString::generate(&mut argon2::password_hash::rand_core::OsRng);
142        Argon2::default()
143            .hash_password(secret.as_bytes(), &salt)
144            .map(|h| h.to_string())
145            .map_err(|_| AuthConfigError::Hash)
146    }
147}
148
149/// Axum middleware: resolve the tenant for a request and inject a [`TenantId`] into extensions.
150///
151/// - `require_auth = false` (default): no auth check; injects the static default tenant so every
152///   downstream handler reads a uniform identity. Single-operator behavior is unchanged.
153/// - `require_auth = true`: reads the key from `Authorization: Bearer <key>` (or `x-firstpass-key`),
154///   verifies it against the configured tenant hashes, and injects the resolved tenant. A missing
155///   or invalid key returns `401` with an opaque body — no "unknown tenant" oracle.
156pub async fn auth_middleware(
157    State(state): State<AppState>,
158    mut req: Request,
159    next: Next,
160) -> Response {
161    if !state.config.require_auth {
162        req.extensions_mut()
163            .insert(TenantId(state.config.tenant_id.clone()));
164        return next.run(req).await;
165    }
166    // Argon2 is deliberately slow CPU work; on the async worker it would stall every other
167    // request on that thread for the length of a verify. A failed join fails closed (401).
168    //
169    // Determine the credential source BEFORE the verify so we can strip the Authorization header
170    // if Bearer was used as the tenant credential — preventing it from being forwarded upstream.
171    let bearer_was_tenant = key_came_from_bearer_only(req.headers());
172    let verified = match extract_key(req.headers()) {
173        Some(key) => {
174            let config = state.config.clone();
175            tokio::task::spawn_blocking(move || config.tenant_keys.verify(&key))
176                .await
177                .ok()
178                .flatten()
179        }
180        None => None,
181    };
182    match verified {
183        Some(tenant) => {
184            req.extensions_mut().insert(tenant);
185            // SECURITY: if the tenant credential was taken from Authorization: Bearer, strip it
186            // now so it is never forwarded to the upstream model provider (observe or enforce path).
187            if bearer_was_tenant {
188                req.headers_mut().remove(header::AUTHORIZATION);
189            }
190            next.run(req).await
191        }
192        None => ProxyError::Unauthorized.into_response(),
193    }
194}
195
196/// Read the tenant API key from `x-firstpass-key` (preferred) or `Authorization: Bearer <key>`.
197///
198/// `x-firstpass-key` takes precedence so that OpenAI-compatible clients which send
199/// `Authorization: Bearer sk-…` as their *provider* key are not mistaken for a tenant credential.
200/// When a client sends both, `x-firstpass-key` is the tenant credential and Authorization reaches
201/// the provider unchanged.
202fn extract_key(headers: &HeaderMap) -> Option<String> {
203    // Prefer the dedicated header — leaves Authorization for the upstream provider.
204    if let Some(key) = headers
205        .get(KEY_HEADER)
206        .and_then(|v| v.to_str().ok())
207        .map(str::trim)
208        .filter(|s| !s.is_empty())
209    {
210        return Some(key.to_owned());
211    }
212    // Fall back to Bearer — but auth_middleware will strip it before forwarding upstream.
213    headers
214        .get(header::AUTHORIZATION)
215        .and_then(|v| v.to_str().ok())
216        .and_then(|v| v.strip_prefix(BEARER_PREFIX))
217        .map(str::trim)
218        .filter(|s| !s.is_empty())
219        .map(str::to_owned)
220}
221
222/// Whether the request's only tenant-key source is `Authorization: Bearer`.
223///
224/// Returns `true` when no non-empty `x-firstpass-key` is present and a non-empty Bearer token
225/// exists. The middleware uses this to strip the Authorization header before forwarding upstream
226/// so that a tenant credential sent as Bearer is never relayed to the model provider.
227///
228/// An empty or whitespace-only `x-firstpass-key` is treated as absent: the header value can
229/// carry no real key, so Bearer is still the (only) credential source and must be stripped.
230fn key_came_from_bearer_only(headers: &HeaderMap) -> bool {
231    let has_explicit_key = headers
232        .get(KEY_HEADER)
233        .and_then(|v| v.to_str().ok())
234        .map(str::trim)
235        .is_some_and(|s| !s.is_empty());
236    if has_explicit_key {
237        return false; // x-firstpass-key is the credential; Bearer is for the provider.
238    }
239    headers
240        .get(header::AUTHORIZATION)
241        .and_then(|v| v.to_str().ok())
242        .and_then(|v| v.strip_prefix(BEARER_PREFIX))
243        .map(str::trim)
244        .is_some_and(|s| !s.is_empty())
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    #[test]
252    fn argon2_hash_round_trips_and_rejects_wrong_key() {
253        let hash = TenantKeys::hash_key("s3cret-key").unwrap();
254        let json = format!("{{\"acme\": {hash:?}}}");
255        let keys = TenantKeys::from_json(&json).unwrap();
256
257        // Correct `<tenant>.<secret>` key resolves to its tenant.
258        assert_eq!(
259            keys.verify("acme.s3cret-key").map(|t| t.0).as_deref(),
260            Some("acme")
261        );
262        // Right tenant, wrong secret → nothing.
263        assert!(keys.verify("acme.wrong-key").is_none());
264        // Unknown tenant → nothing (and it still burns a decoy verify — no existence oracle).
265        assert!(keys.verify("ghost.s3cret-key").is_none());
266        // Malformed (no `.`) and empty keys never match.
267        assert!(keys.verify("s3cret-key").is_none());
268        assert!(keys.verify("").is_none());
269    }
270
271    #[test]
272    fn two_tenants_resolve_to_their_own_identity() {
273        let a = TenantKeys::hash_key("key-a").unwrap();
274        let b = TenantKeys::hash_key("key-b").unwrap();
275        let json = format!("{{\"tenant-a\": {a:?}, \"tenant-b\": {b:?}}}");
276        let keys = TenantKeys::from_json(&json).unwrap();
277
278        assert_eq!(
279            keys.verify("tenant-a.key-a").map(|t| t.0).as_deref(),
280            Some("tenant-a")
281        );
282        assert_eq!(
283            keys.verify("tenant-b.key-b").map(|t| t.0).as_deref(),
284            Some("tenant-b")
285        );
286        // Tenant A's id with tenant B's secret is rejected — you can't cross tenants.
287        assert!(keys.verify("tenant-a.key-b").is_none());
288        // A secret for no configured tenant is rejected.
289        assert!(keys.verify("tenant-c.key-c").is_none());
290    }
291
292    #[test]
293    fn invalid_hash_in_config_is_rejected_at_build_time() {
294        let json = r#"{"acme": "not-a-real-argon2-hash"}"#;
295        assert!(matches!(
296            TenantKeys::from_json(json),
297            Err(AuthConfigError::BadHash { tenant }) if tenant == "acme"
298        ));
299    }
300
301    #[test]
302    fn debug_redacts_hashes() {
303        let hash = TenantKeys::hash_key("top-secret").unwrap();
304        let json = format!("{{\"acme\": {hash:?}}}");
305        let keys = TenantKeys::from_json(&json).unwrap();
306        let dbg = format!("{keys:?}");
307        assert!(dbg.contains("acme"), "tenant id is fine to show");
308        assert!(dbg.contains("<redacted>"), "hashes must be redacted");
309        assert!(
310            !dbg.contains("$argon2"),
311            "no hash material may leak in Debug"
312        );
313    }
314
315    #[test]
316    fn extract_key_prefers_custom_header_over_bearer() {
317        // Custom header only → used.
318        let mut h = HeaderMap::new();
319        h.insert(KEY_HEADER, "xyz789".parse().unwrap());
320        assert_eq!(extract_key(&h).as_deref(), Some("xyz789"));
321
322        // Bearer only → used as fallback.
323        let mut h2 = HeaderMap::new();
324        h2.insert(header::AUTHORIZATION, "Bearer abc123".parse().unwrap());
325        assert_eq!(extract_key(&h2).as_deref(), Some("abc123"));
326
327        // Both present → custom header wins (Bearer is for the provider, not the tenant).
328        let mut h3 = HeaderMap::new();
329        h3.insert(KEY_HEADER, "tenant-key".parse().unwrap());
330        h3.insert(
331            header::AUTHORIZATION,
332            "Bearer provider-key".parse().unwrap(),
333        );
334        assert_eq!(extract_key(&h3).as_deref(), Some("tenant-key"));
335
336        // No key header at all.
337        assert!(extract_key(&HeaderMap::new()).is_none());
338        // Empty bearer token is not a key.
339        let mut h4 = HeaderMap::new();
340        h4.insert(header::AUTHORIZATION, "Bearer ".parse().unwrap());
341        assert!(extract_key(&h4).is_none());
342    }
343
344    #[test]
345    fn key_came_from_bearer_only_detects_bearer_without_custom_header() {
346        // Bearer only → true.
347        let mut h = HeaderMap::new();
348        h.insert(header::AUTHORIZATION, "Bearer abc123".parse().unwrap());
349        assert!(key_came_from_bearer_only(&h));
350
351        // Custom header present (with or without Bearer) → false.
352        let mut h2 = HeaderMap::new();
353        h2.insert(KEY_HEADER, "tenant-key".parse().unwrap());
354        assert!(!key_came_from_bearer_only(&h2));
355
356        let mut h3 = HeaderMap::new();
357        h3.insert(KEY_HEADER, "tenant-key".parse().unwrap());
358        h3.insert(
359            header::AUTHORIZATION,
360            "Bearer provider-key".parse().unwrap(),
361        );
362        assert!(!key_came_from_bearer_only(&h3));
363
364        // No headers → false.
365        assert!(!key_came_from_bearer_only(&HeaderMap::new()));
366
367        // Empty bearer → false (not a valid key).
368        let mut h4 = HeaderMap::new();
369        h4.insert(header::AUTHORIZATION, "Bearer ".parse().unwrap());
370        assert!(!key_came_from_bearer_only(&h4));
371    }
372
373    #[test]
374    fn key_came_from_bearer_only_treats_empty_or_whitespace_custom_header_as_absent() {
375        // x-firstpass-key is present but empty → Bearer is still the only credential; strip it.
376        let mut h = HeaderMap::new();
377        h.insert(KEY_HEADER, "".parse().unwrap());
378        h.insert(header::AUTHORIZATION, "Bearer real-token".parse().unwrap());
379        assert!(
380            key_came_from_bearer_only(&h),
381            "empty x-firstpass-key must not suppress Bearer stripping"
382        );
383
384        // x-firstpass-key is present but whitespace-only → same.
385        let mut h2 = HeaderMap::new();
386        h2.insert(KEY_HEADER, "   ".parse().unwrap());
387        h2.insert(header::AUTHORIZATION, "Bearer real-token".parse().unwrap());
388        assert!(
389            key_came_from_bearer_only(&h2),
390            "whitespace x-firstpass-key must not suppress Bearer stripping"
391        );
392
393        // x-firstpass-key has a real value → Bearer is the provider key; do NOT strip.
394        let mut h3 = HeaderMap::new();
395        h3.insert(KEY_HEADER, "tenant-key".parse().unwrap());
396        h3.insert(
397            header::AUTHORIZATION,
398            "Bearer provider-key".parse().unwrap(),
399        );
400        assert!(
401            !key_came_from_bearer_only(&h3),
402            "non-empty x-firstpass-key means Bearer is a provider key, not the tenant key"
403        );
404    }
405
406    // ── Defect 4: auth middleware integration tests ──────────────────────────────
407
408    /// Build a minimal `AppState` with auth enabled and the given tenant hash JSON.
409    fn auth_state(hash_json: &str) -> crate::proxy::AppState {
410        use std::sync::Arc;
411        let config = crate::config::ProxyConfig::from_lookup(|k| match k {
412            "FIRSTPASS_REQUIRE_AUTH" => Some("true".to_owned()),
413            "FIRSTPASS_TENANT_KEYS_JSON" => Some(hash_json.to_owned()),
414            _ => None,
415        })
416        .expect("minimal auth config");
417        let (traces, _rx) = tokio::sync::mpsc::channel(1);
418        crate::proxy::AppState {
419            config: Arc::new(config),
420            http: reqwest::Client::new(),
421            providers: crate::provider::ProviderRegistry::from_map(Default::default()),
422            gate_health: Arc::new(crate::gate::GateHealthRegistry::new()),
423            shadow_ledger: Arc::new(crate::shadow::ShadowLedger::new()),
424            paired_ledger: Arc::new(crate::shadow::ShadowLedger::new()),
425            experiments: Arc::default(),
426            guardrails: Arc::new(crate::guard::GuardrailRegistry::new()),
427            traces,
428            adaptive: None,
429            eprocess: None,
430            bandit: None,
431            promoter: None,
432            verified_cache: None,
433            predictor: None,
434            prior: None,
435            tenant_rate_limiter: None,
436            spill: None,
437        }
438    }
439
440    /// Build an axum app that runs `auth_middleware` and then echoes the `Authorization` header
441    /// value (or empty string) from the downstream view.
442    fn auth_echo_app(state: crate::proxy::AppState) -> axum::Router {
443        let inner = axum::routing::get(|req: axum::extract::Request| async move {
444            req.headers()
445                .get(header::AUTHORIZATION)
446                .and_then(|v| v.to_str().ok())
447                .unwrap_or("")
448                .to_owned()
449        });
450        axum::Router::new()
451            .route("/test", inner)
452            .layer(axum::middleware::from_fn_with_state(
453                state.clone(),
454                auth_middleware,
455            ))
456            .with_state(state)
457    }
458
459    #[tokio::test]
460    async fn auth_middleware_strips_bearer_when_used_as_tenant_key() {
461        use tower::ServiceExt;
462        let hash = TenantKeys::hash_key("my-secret").unwrap();
463        let json = format!("{{\"acme\": {hash:?}}}");
464        let app = auth_echo_app(auth_state(&json));
465
466        // Bearer carries the tenant credential "acme.my-secret" — no x-firstpass-key.
467        let req = axum::http::Request::builder()
468            .uri("/test")
469            .header(header::AUTHORIZATION, "Bearer acme.my-secret")
470            .body(axum::body::Body::empty())
471            .unwrap();
472        let resp = app.oneshot(req).await.unwrap();
473        assert_eq!(resp.status(), axum::http::StatusCode::OK, "tenant verified");
474        let body = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
475        let downstream_auth = String::from_utf8_lossy(&body);
476        assert!(
477            downstream_auth.is_empty(),
478            "Authorization must be stripped downstream when Bearer was the tenant credential, \
479             got: {downstream_auth:?}"
480        );
481    }
482
483    #[tokio::test]
484    async fn auth_middleware_leaves_provider_bearer_when_custom_header_is_tenant_key() {
485        use tower::ServiceExt;
486        let hash = TenantKeys::hash_key("my-secret").unwrap();
487        let json = format!("{{\"acme\": {hash:?}}}");
488        let app = auth_echo_app(auth_state(&json));
489
490        // x-firstpass-key carries the tenant credential; Authorization carries the provider key.
491        let req = axum::http::Request::builder()
492            .uri("/test")
493            .header(KEY_HEADER, "acme.my-secret")
494            .header(header::AUTHORIZATION, "Bearer sk-provider-key")
495            .body(axum::body::Body::empty())
496            .unwrap();
497        let resp = app.oneshot(req).await.unwrap();
498        assert_eq!(resp.status(), axum::http::StatusCode::OK, "tenant verified");
499        let body = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
500        let downstream_auth = String::from_utf8_lossy(&body);
501        assert_eq!(
502            downstream_auth, "Bearer sk-provider-key",
503            "provider Bearer must reach downstream unchanged when x-firstpass-key is the tenant credential"
504        );
505    }
506}