use std::num::NonZeroUsize;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use lru::LruCache;
use sqlx::PgPool;
use crate::cache::digest;
use crate::Limits;
const LOOKUP_TIMEOUT: Duration = Duration::from_secs(2);
const MIN_STALE_WINDOW: Duration = Duration::from_secs(5 * 60);
const CACHE_CAP: usize = 10_000;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthOutcome {
Authorized(Limits),
MissingOrUnknownKey,
WrongTenant,
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum AuthError {
#[error("auth lookup failed: {0}")]
Db(#[from] sqlx::Error),
}
type AuthRow = (String, Vec<String>, i32, i64);
#[derive(Clone)]
enum Cached {
Found { tenant: String, limits: Limits },
Unknown,
}
struct Inner {
pool: PgPool,
ttl: Duration,
cache: Mutex<LruCache<String, (Instant, Cached)>>,
}
#[derive(Clone)]
pub struct Authenticator(Arc<Inner>);
impl std::fmt::Debug for Authenticator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Authenticator")
.field("ttl", &self.0.ttl)
.finish_non_exhaustive()
}
}
impl Authenticator {
pub fn new(pool: PgPool, ttl: Duration) -> Self {
Self(Arc::new(Inner {
pool,
ttl,
cache: Mutex::new(LruCache::new(NonZeroUsize::new(CACHE_CAP).unwrap())),
}))
}
pub fn pool(&self) -> &PgPool {
&self.0.pool
}
pub async fn authenticate(
&self,
tenant: &str,
bearer: Option<&str>,
) -> Result<AuthOutcome, AuthError> {
let Some(token) = bearer else {
return Ok(AuthOutcome::MissingOrUnknownKey);
};
let inner = &*self.0;
let key_hash = digest(token.as_bytes());
let mut stale = None;
if !inner.ttl.is_zero() {
let hit = inner.cache.lock().unwrap().get(&key_hash).cloned();
if let Some((at, cached)) = hit {
if at.elapsed() < inner.ttl {
return Ok(outcome(cached, tenant));
}
if at.elapsed() < (inner.ttl * 10).max(MIN_STALE_WINDOW) {
stale = Some(cached);
}
}
}
let row: Result<Option<AuthRow>, sqlx::Error> = match tokio::time::timeout(
LOOKUP_TIMEOUT,
sqlx::query_as(
"SELECT t.name, t.allowed_hosts, t.cpu_budget_ms, t.mem_cap_bytes \
FROM warpline.api_keys k JOIN warpline.tenants t ON t.id = k.tenant_id \
WHERE k.key_hash = $1",
)
.bind(&key_hash)
.fetch_optional(&inner.pool),
)
.await
{
Ok(r) => r,
Err(_) => Err(sqlx::Error::PoolTimedOut),
};
let row = match row {
Ok(row) => row,
Err(e) => {
return match stale {
Some(cached) => {
tracing::warn!(error = %e, "auth lookup failed; serving stale cache entry");
Ok(outcome(cached, tenant))
}
None => Err(e.into()),
};
}
};
let cached = match row {
None => Cached::Unknown,
Some((tenant, allowed_hosts, cpu, mem)) => {
let limits = Limits {
cpu_budget_ms: cpu as u64,
mem_cap_bytes: mem as usize,
allowed_hosts,
};
Cached::Found { tenant, limits }
}
};
if !inner.ttl.is_zero() {
inner
.cache
.lock()
.unwrap()
.put(key_hash, (Instant::now(), cached.clone()));
}
Ok(outcome(cached, tenant))
}
}
fn outcome(cached: Cached, requested: &str) -> AuthOutcome {
match cached {
Cached::Unknown => AuthOutcome::MissingOrUnknownKey,
Cached::Found { tenant, .. } if tenant != requested => AuthOutcome::WrongTenant,
Cached::Found { limits, .. } => AuthOutcome::Authorized(limits),
}
}