1use 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
25const BEARER_PREFIX: &str = "Bearer ";
27const KEY_HEADER: &str = "x-firstpass-key";
29
30#[derive(Clone, Debug)]
35pub struct TenantId(pub String);
36
37#[derive(Clone, Default)]
45pub struct TenantKeys {
46 hashes: HashMap<String, String>,
48 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#[derive(Debug, thiserror::Error)]
64pub enum AuthConfigError {
65 #[error("tenant keys JSON is invalid: {0}")]
67 Json(#[from] serde_json::Error),
68 #[error("tenant {tenant:?} has an invalid Argon2 hash")]
70 BadHash {
71 tenant: String,
73 },
74 #[error("argon2 hashing failed")]
76 Hash,
77}
78
79impl TenantKeys {
80 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 let decoy = Self::hash_key("firstpass-unknown-tenant-decoy")?;
97 Ok(Self { hashes, decoy })
98 }
99
100 #[must_use]
102 pub fn is_empty(&self) -> bool {
103 self.hashes.is_empty()
104 }
105
106 #[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 if let Ok(decoy) = PasswordHash::new(&self.decoy) {
129 let _ = argon.verify_password(secret.as_bytes(), &decoy);
130 }
131 None
132 }
133
134 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
149pub 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 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 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
196fn extract_key(headers: &HeaderMap) -> Option<String> {
203 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 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
222fn 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; }
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 assert_eq!(
259 keys.verify("acme.s3cret-key").map(|t| t.0).as_deref(),
260 Some("acme")
261 );
262 assert!(keys.verify("acme.wrong-key").is_none());
264 assert!(keys.verify("ghost.s3cret-key").is_none());
266 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 assert!(keys.verify("tenant-a.key-b").is_none());
288 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 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 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 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 assert!(extract_key(&HeaderMap::new()).is_none());
338 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 let mut h = HeaderMap::new();
348 h.insert(header::AUTHORIZATION, "Bearer abc123".parse().unwrap());
349 assert!(key_came_from_bearer_only(&h));
350
351 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 assert!(!key_came_from_bearer_only(&HeaderMap::new()));
366
367 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 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 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 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 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 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 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 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}