zc2 0.0.46

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! Hub-validated user keys (#384, ADR ZC-0008 / ZC-0012).
//!
//! In remote mode (a hub/API URL is configured) the identity a request is
//! billed to must come from the hub, never from the SHAPE of the Bearer key.
//! `zk_{uid}_{secret}` embeds the uid in clear, so trusting the shape lets
//! anyone who knows a uid spend that user's balance with any made-up secret.
//!
//! [`KeyAuthority`] asks the hub (`GET /api/auth/me/api-key`, the same call
//! `zc me` and the startup handshake make) who a key belongs to, and caches
//! the verdict so the hub stays off the hot path:
//!
//! * positive verdicts for [`POSITIVE_TTL`], negative for [`NEGATIVE_TTL`]
//!   (so a flood of forged keys does not become a flood of hub calls);
//! * keyed by SHA-256 of the key, never the key itself;
//! * hub unreachable / 5xx / timeout / unparseable reply is NOT cached and
//!   surfaces as [`KeyCheck::Unavailable`] (-> 503): fail closed, never fall
//!   back to the key's shape.
//!
//! `ZAKURO_TRUST_KEY_SHAPE=1` restores the old shape-only behaviour. It is an
//! emergency opt-out only and logs a loud warning at broker start.

use std::sync::Arc;
use std::time::{Duration, Instant};

use dashmap::DashMap;

/// How long a hub "yes, this key is user N" is trusted.
pub const POSITIVE_TTL: Duration = Duration::from_secs(300);
/// How long a hub "no" is remembered (shorter: a freshly issued key should
/// not stay refused for long).
pub const NEGATIVE_TTL: Duration = Duration::from_secs(30);
/// Hub round-trip budget per validation.
const HUB_TIMEOUT: Duration = Duration::from_secs(5);
/// Soft cap on cached verdicts; past it, expired entries are swept and, if
/// that is not enough, negatives are dropped (a forged-key flood must not
/// grow memory without bound).
const MAX_ENTRIES: usize = 10_000;

/// Env var for the emergency opt-out.
pub const TRUST_SHAPE_ENV: &str = "ZAKURO_TRUST_KEY_SHAPE";

/// Outcome of asking the hub about a key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyCheck {
    /// The hub says this key belongs to this `zakuro_user_id`.
    Valid(String),
    /// The hub says the key is not valid.
    Invalid,
    /// The hub could not give an answer (transport error, 5xx, timeout,
    /// malformed reply). Must map to 503, never to the key's shape.
    Unavailable(String),
}

#[derive(Clone)]
enum Verdict {
    Valid(String),
    Invalid,
}

struct Entry {
    verdict: Verdict,
    expires: Instant,
}

type Clock = Arc<dyn Fn() -> Instant + Send + Sync>;

pub struct KeyAuthority {
    cache: DashMap<[u8; 32], Entry>,
    clock: Clock,
    trust_shape: bool,
}

/// SHA-256 of the key: the only form in which a key is ever cached.
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
}

/// Lowercase hex SHA-256 of the key: the digest the hub stores as
/// `users.api_key_hash` / `device_keys.key_hash`, sent as
/// `X-Zakuro-User-Key-Sha256` on settlements (#404).
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(),
        }
    }

    /// Whether the emergency shape-only opt-out is on.
    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;
    }

    /// Replace the clock (tests).
    #[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()
    }

    /// Validate `key` against the hub at `api_url`, via the cache.
    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(_) => {
                // Never cache an outage; drop any stale verdict too.
                self.cache.remove(&digest);
            }
        }
        result
    }

    /// Remember that the hub's uid disagreed with the key's shape.
    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.expires > 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,
            },
        );
    }
}

/// One uncached `GET /api/auth/me/api-key` with `key` as the Bearer token.
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))
            // Judge status ourselves: 401 means "invalid", 5xx "unavailable".
            .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()),
    }
}

/// A local stand-in for the hub's `/api/auth/me/api-key`, shared by the tests
/// of this module, the ledger and the broker handlers. Never a live system.
#[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>,
    }

    /// Serves `{"zakuro_user_id": uid}` for each `(key, uid)` in `keys`, 401
    /// for anything else, and counts every request.
    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,
        }
    }

    /// A clock the test can push forward.
    #[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());
        // SHA-256("abc"), the standard test vector.
        assert_eq!(
            hex::encode(key_digest("abc")),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }

    #[test]
    fn outages_are_unavailable_and_never_cached() {
        let clock = TestClock::new();
        let a = authority(&clock);
        // Nothing listens on port 1.
        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());

        // A 200 with no uid is a hub fault, not a verdict.
        let hub = spawn_with(|_| (200, "{}".to_string()));
        assert!(matches!(
            a.check(&hub.url, "zk_7_x"),
            KeyCheck::Unavailable(_)
        ));
        assert!(a.cached_digests().is_empty());
    }
}