use std::sync::Arc;
use std::time::{Duration, Instant};
use dashmap::DashMap;
pub const POSITIVE_TTL: Duration = Duration::from_secs(300);
pub const NEGATIVE_TTL: Duration = Duration::from_secs(30);
pub const STALE_GRACE: Duration = Duration::from_secs(15 * 60);
const HUB_TIMEOUT: Duration = Duration::from_secs(5);
const MAX_ENTRIES: usize = 10_000;
pub const TRUST_SHAPE_ENV: &str = "ZAKURO_TRUST_KEY_SHAPE";
pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
pub fn is_master_key(presented: &str) -> bool {
let master = std::env::var("ZAKURO_MASTER_KEY").unwrap_or_default();
!master.is_empty() && ct_eq(presented.as_bytes(), master.as_bytes())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyCheck {
Valid(String),
Invalid,
Unavailable(String),
}
#[derive(Clone)]
enum Verdict {
Valid(String),
Invalid,
}
struct Entry {
verdict: Verdict,
expires: Instant,
}
impl Entry {
fn usable(&self, now: Instant) -> bool {
self.expires > now
|| (matches!(self.verdict, Verdict::Valid(_)) && self.expires + STALE_GRACE > now)
}
}
type Clock = Arc<dyn Fn() -> Instant + Send + Sync>;
pub struct KeyAuthority {
cache: DashMap<[u8; 32], Entry>,
clock: Clock,
trust_shape: bool,
}
pub(crate) fn key_digest(key: &str) -> [u8; 32] {
let d = ring::digest::digest(&ring::digest::SHA256, key.as_bytes());
let mut out = [0u8; 32];
out.copy_from_slice(d.as_ref());
out
}
pub(crate) fn key_sha256_hex(key: &str) -> String {
hex::encode(key_digest(key))
}
fn env_trusts_shape() -> bool {
matches!(
std::env::var(TRUST_SHAPE_ENV).as_deref(),
Ok("1") | Ok("true") | Ok("TRUE") | Ok("yes")
)
}
impl Default for KeyAuthority {
fn default() -> Self {
Self::new()
}
}
impl KeyAuthority {
pub fn new() -> Self {
Self {
cache: DashMap::new(),
clock: Arc::new(Instant::now),
trust_shape: env_trusts_shape(),
}
}
pub fn trusts_shape(&self) -> bool {
self.trust_shape
}
#[cfg(test)]
pub(crate) fn set_trust_shape(&mut self, on: bool) {
self.trust_shape = on;
}
#[cfg(test)]
pub(crate) fn set_clock(&mut self, clock: Clock) {
self.clock = clock;
}
#[cfg(test)]
pub(crate) fn cached_digests(&self) -> Vec<[u8; 32]> {
self.cache.iter().map(|e| *e.key()).collect()
}
pub fn check(&self, api_url: &str, key: &str) -> KeyCheck {
let digest = key_digest(key);
let now = (self.clock)();
if let Some(e) = self.cache.get(&digest) {
if e.expires > now {
return match &e.verdict {
Verdict::Valid(u) => KeyCheck::Valid(u.clone()),
Verdict::Invalid => KeyCheck::Invalid,
};
}
}
let result = fetch_from_hub(api_url, key);
match &result {
KeyCheck::Valid(u) => self.store(digest, Verdict::Valid(u.clone()), POSITIVE_TTL, now),
KeyCheck::Invalid => self.store(digest, Verdict::Invalid, NEGATIVE_TTL, now),
KeyCheck::Unavailable(why) => {
let stale = match self.cache.get(&digest) {
Some(e) if e.usable(now) => match &e.verdict {
Verdict::Valid(u) => {
Some((u.clone(), now.saturating_duration_since(e.expires)))
}
Verdict::Invalid => None,
},
_ => None,
};
match stale {
Some((uid, over)) => {
let age = (POSITIVE_TTL + over).as_secs();
eprintln!(
" [AUTH] hub unavailable ({why}); using the verdict for user {uid} validated {age}s ago"
);
return KeyCheck::Valid(uid);
}
None => {
self.cache.remove(&digest);
}
}
}
}
result
}
pub(crate) fn mark_invalid(&self, key: &str) {
let now = (self.clock)();
self.store(key_digest(key), Verdict::Invalid, NEGATIVE_TTL, now);
}
fn store(&self, digest: [u8; 32], verdict: Verdict, ttl: Duration, now: Instant) {
if self.cache.len() >= MAX_ENTRIES {
self.cache.retain(|_, e| e.usable(now));
if self.cache.len() >= MAX_ENTRIES {
self.cache
.retain(|_, e| matches!(e.verdict, Verdict::Valid(_)));
}
if self.cache.len() >= MAX_ENTRIES {
self.cache.clear();
}
}
self.cache.insert(
digest,
Entry {
verdict,
expires: now + ttl,
},
);
}
}
fn fetch_from_hub(api_url: &str, key: &str) -> KeyCheck {
let url = format!("{}/api/auth/me/api-key", api_url.trim_end_matches('/'));
let agent = ureq::Agent::new_with_config(
ureq::Agent::config_builder()
.timeout_global(Some(HUB_TIMEOUT))
.http_status_as_error(false)
.build(),
);
let resp = match agent
.get(&url)
.header("Authorization", &format!("Bearer {key}"))
.call()
{
Ok(r) => r,
Err(e) => return KeyCheck::Unavailable(format!("hub unreachable: {e}")),
};
let status = resp.status().as_u16();
match status {
200 => {}
401 | 403 => return KeyCheck::Invalid,
s => return KeyCheck::Unavailable(format!("hub returned status {s}")),
}
let body = match resp.into_body().read_to_string() {
Ok(b) => b,
Err(e) => return KeyCheck::Unavailable(format!("hub reply unreadable: {e}")),
};
let parsed: serde_json::Value = match serde_json::from_str(&body) {
Ok(v) => v,
Err(e) => return KeyCheck::Unavailable(format!("hub reply not JSON: {e}")),
};
match parsed["zakuro_user_id"].as_str().filter(|u| !u.is_empty()) {
Some(u) => KeyCheck::Valid(u.to_string()),
None => KeyCheck::Unavailable("hub reply carried no zakuro_user_id".to_string()),
}
}
#[cfg(test)]
pub(crate) mod test_hub {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
pub struct MockHub {
pub url: String,
pub hits: Arc<AtomicU64>,
}
pub fn spawn(keys: Vec<(&'static str, &'static str)>) -> MockHub {
spawn_with(
move |bearer| match keys.iter().find(|(k, _)| *k == bearer) {
Some((_, uid)) => (200, format!(r#"{{"zakuro_user_id":"{uid}"}}"#)),
None => (401, r#"{"error":"invalid"}"#.to_string()),
},
)
}
pub fn spawn_with(reply: impl Fn(&str) -> (u16, String) + Send + 'static) -> MockHub {
let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
let port = server.server_addr().to_ip().unwrap().port();
let hits = Arc::new(AtomicU64::new(0));
let seen = hits.clone();
std::thread::spawn(move || {
for req in server.incoming_requests() {
seen.fetch_add(1, Ordering::SeqCst);
let bearer = req
.headers()
.iter()
.find(|h| h.field.equiv("Authorization"))
.map(|h| h.value.as_str().trim_start_matches("Bearer ").to_string())
.unwrap_or_default();
let (status, body) = reply(&bearer);
let _ =
req.respond(tiny_http::Response::from_string(body).with_status_code(status));
}
});
MockHub {
url: format!("http://127.0.0.1:{port}"),
hits,
}
}
#[derive(Clone)]
pub struct TestClock {
base: Instant,
offset_secs: Arc<AtomicU64>,
}
impl TestClock {
pub fn new() -> Self {
Self {
base: Instant::now(),
offset_secs: Arc::new(AtomicU64::new(0)),
}
}
pub fn advance(&self, secs: u64) {
self.offset_secs.fetch_add(secs, Ordering::SeqCst);
}
pub fn as_clock(&self) -> Clock {
let c = self.clone();
Arc::new(move || c.base + Duration::from_secs(c.offset_secs.load(Ordering::SeqCst)))
}
}
}
#[cfg(test)]
mod tests {
use super::test_hub::*;
use super::*;
use std::sync::atomic::Ordering;
fn authority(clock: &TestClock) -> KeyAuthority {
let mut a = KeyAuthority::new();
a.set_clock(clock.as_clock());
a
}
#[test]
fn positive_verdict_is_cached_until_ttl_then_revalidated() {
let hub = spawn(vec![("zk_7_good", "7")]);
let clock = TestClock::new();
let a = authority(&clock);
assert_eq!(a.check(&hub.url, "zk_7_good"), KeyCheck::Valid("7".into()));
assert_eq!(a.check(&hub.url, "zk_7_good"), KeyCheck::Valid("7".into()));
assert_eq!(
hub.hits.load(Ordering::SeqCst),
1,
"second check is a cache hit"
);
clock.advance(POSITIVE_TTL.as_secs() - 1);
a.check(&hub.url, "zk_7_good");
assert_eq!(hub.hits.load(Ordering::SeqCst), 1, "still inside the TTL");
clock.advance(2);
assert_eq!(a.check(&hub.url, "zk_7_good"), KeyCheck::Valid("7".into()));
assert_eq!(
hub.hits.load(Ordering::SeqCst),
2,
"re-validated after the TTL"
);
}
#[test]
fn negative_verdict_is_cached_for_a_shorter_ttl() {
assert!(NEGATIVE_TTL < POSITIVE_TTL);
let hub = spawn(vec![]);
let clock = TestClock::new();
let a = authority(&clock);
assert_eq!(a.check(&hub.url, "zk_7_forged"), KeyCheck::Invalid);
assert_eq!(a.check(&hub.url, "zk_7_forged"), KeyCheck::Invalid);
assert_eq!(
hub.hits.load(Ordering::SeqCst),
1,
"a forged-key flood hits the hub once"
);
clock.advance(NEGATIVE_TTL.as_secs() + 1);
assert_eq!(a.check(&hub.url, "zk_7_forged"), KeyCheck::Invalid);
assert_eq!(hub.hits.load(Ordering::SeqCst), 2);
}
#[test]
fn cache_is_keyed_by_a_hash_never_the_key() {
let hub = spawn(vec![("zk_7_good", "7")]);
let clock = TestClock::new();
let a = authority(&clock);
a.check(&hub.url, "zk_7_good");
let keys = a.cached_digests();
assert_eq!(keys, vec![key_digest("zk_7_good")]);
assert_ne!(&keys[0][..], "zk_7_good".as_bytes());
assert_eq!(
hex::encode(key_digest("abc")),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
}
#[test]
fn outages_are_unavailable_and_never_cached() {
let clock = TestClock::new();
let a = authority(&clock);
assert!(matches!(
a.check("http://127.0.0.1:1", "zk_7_x"),
KeyCheck::Unavailable(_)
));
assert!(a.cached_digests().is_empty());
let hub = spawn_with(|_| (500, "boom".to_string()));
assert!(matches!(
a.check(&hub.url, "zk_7_x"),
KeyCheck::Unavailable(_)
));
assert!(a.cached_digests().is_empty());
let hub = spawn_with(|_| (200, "{}".to_string()));
assert!(matches!(
a.check(&hub.url, "zk_7_x"),
KeyCheck::Unavailable(_)
));
assert!(a.cached_digests().is_empty());
}
const DEAD: &str = "http://127.0.0.1:1";
#[test]
fn stale_valid_verdict_is_served_during_outage_within_grace() {
let hub = spawn(vec![("zk_7_good", "7")]);
let clock = TestClock::new();
let a = authority(&clock);
assert_eq!(a.check(&hub.url, "zk_7_good"), KeyCheck::Valid("7".into()));
clock.advance(POSITIVE_TTL.as_secs() + STALE_GRACE.as_secs() - 1);
assert_eq!(a.check(DEAD, "zk_7_good"), KeyCheck::Valid("7".into()));
clock.advance(2);
assert!(matches!(
a.check(DEAD, "zk_7_good"),
KeyCheck::Unavailable(_)
));
}
#[test]
fn outage_past_ttl_plus_grace_is_unavailable_and_evicts() {
let hub = spawn(vec![("zk_7_good", "7")]);
let clock = TestClock::new();
let a = authority(&clock);
a.check(&hub.url, "zk_7_good");
clock.advance(POSITIVE_TTL.as_secs() + STALE_GRACE.as_secs() + 1);
assert!(matches!(
a.check(DEAD, "zk_7_good"),
KeyCheck::Unavailable(_)
));
assert!(a.cached_digests().is_empty());
}
#[test]
fn invalid_verdict_is_not_extended_during_outage() {
let hub = spawn(vec![]);
let clock = TestClock::new();
let a = authority(&clock);
assert_eq!(a.check(&hub.url, "zk_7_forged"), KeyCheck::Invalid);
clock.advance(NEGATIVE_TTL.as_secs() + 1);
assert!(matches!(
a.check(DEAD, "zk_7_forged"),
KeyCheck::Unavailable(_)
));
}
#[test]
fn hub_invalid_answer_beats_a_stale_valid_verdict() {
let valid = spawn(vec![("zk_7_good", "7")]);
let revoked = spawn(vec![]);
let clock = TestClock::new();
let a = authority(&clock);
a.check(&valid.url, "zk_7_good");
clock.advance(POSITIVE_TTL.as_secs() + 1);
assert_eq!(a.check(&revoked.url, "zk_7_good"), KeyCheck::Invalid);
}
#[test]
fn recovering_hub_refreshes_the_entry_normally() {
let hub = spawn(vec![("zk_7_good", "7")]);
let clock = TestClock::new();
let a = authority(&clock);
a.check(&hub.url, "zk_7_good");
clock.advance(POSITIVE_TTL.as_secs() + 10);
assert_eq!(a.check(DEAD, "zk_7_good"), KeyCheck::Valid("7".into()));
assert_eq!(a.check(&hub.url, "zk_7_good"), KeyCheck::Valid("7".into()));
assert_eq!(hub.hits.load(Ordering::SeqCst), 2);
clock.advance(POSITIVE_TTL.as_secs() - 1);
a.check(&hub.url, "zk_7_good");
assert_eq!(hub.hits.load(Ordering::SeqCst), 2);
}
#[test]
fn no_prior_verdict_and_outage_is_unavailable() {
let clock = TestClock::new();
let a = authority(&clock);
assert!(matches!(
a.check(DEAD, "zk_7_good"),
KeyCheck::Unavailable(_)
));
}
}