zc2 0.0.48

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! Zero-trust floor (ADR ZC-0012): the enforcement defaults and counters.
//!
//! Every decision here takes the broker state, so a test pins one broker
//! without touching process env (the same pattern as
//! `BrokerState::enforce_node_sig_override`). An explicit env var always wins;
//! with it unset the default depends on whether the broker has a hub:
//!
//! | knob                         | env unset, hub configured             | env unset, no hub |
//! |------------------------------|---------------------------------------|-------------------|
//! | `ZAKURO_ENFORCE_NODE_SIG`    | enforce once a roster has been loaded | permissive        |
//! | `ZAKURO_REQUIRE_VOUCHER`     | required                              | optional          |
//! | `ZAKURO_REQUIRE_SIG_V2`      | off                                   | off               |
//! | `ZAKURO_EARN_BINDING`        | `observe`                             | `observe`         |
//! | `ZAKURO_REQUIRE_WORKER_KEY`  | off                                   | off               |
//! | `ZAKURO_ROSTER_MAX_AGE`      | 86400 s (only with a hub + enforcement) | n/a             |
//!
//! `ZAKURO_EARN_BINDING=enforce` is safe once `earn_binding.unknown_job` stays
//! 0 on a mesh: every earn is then bound by a record of this node's own
//! (`bound`) or by the hub's receipt for the requester's debit
//! (`bound_by_receipt`, see `earn_receipt`).
//!
//! "Hub configured" means a non-blank `ZAKURO_API_URL` AND `ZAKURO_API_KEY`.

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::OnceLock;

use super::BrokerState;

/// Default roster staleness bound: a day.
pub const ROSTER_MAX_AGE_DEFAULT_SECS: u64 = 86_400;

/// Parse an on/off env value: `1|true|yes|on` -> `Some(true)`,
/// `0|false|no|off` -> `Some(false)`, anything else (including unset and
/// empty) -> `None`, i.e. "not decided, use the default".
pub(crate) fn parse_flag(v: Option<&str>) -> Option<bool> {
    match v?.trim().to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Some(true),
        "0" | "false" | "no" | "off" => Some(false),
        _ => None,
    }
}

fn env_flag(name: &str) -> Option<bool> {
    parse_flag(std::env::var(name).ok().as_deref())
}

/// What `/peer/earn` does with an earn it cannot tie to a job this node ran.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EarnBindingMode {
    /// Book as today, log and count the class (default: a missed path would
    /// silently cost an owner real payouts).
    Observe,
    /// Refuse non-bound earns with 409.
    Enforce,
}

impl EarnBindingMode {
    pub(crate) fn parse(v: Option<&str>) -> Self {
        match v.map(|s| s.trim().to_ascii_lowercase()).as_deref() {
            Some("enforce") => Self::Enforce,
            _ => Self::Observe,
        }
    }
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Observe => "observe",
            Self::Enforce => "enforce",
        }
    }
}

/// Counters and per-broker test overrides for the zero-trust floor.
pub struct ZeroTrust {
    /// Unix secs this process started: the replay floor (see `ReplayGuard`).
    pub started_at: u64,
    /// Unix secs of the last successful roster fetch (0 = unknown). Seeded
    /// from the cache file at start-up so it survives a restart.
    pub roster_fetched_at: AtomicU64,
    /// Requests accepted on the v1 signature alone.
    pub sig_v1_only_seen: AtomicU64,
    /// Worker registrations without a key from a non-loopback address.
    pub keyless_worker_nonloopback: AtomicU64,
    /// `/peer/earn` classification counters.
    pub earn_bound: AtomicU64,
    pub earn_unknown_job: AtomicU64,
    pub earn_over_amount: AtomicU64,
    pub earn_wrong_requester: AtomicU64,
    /// Earns with no record on this node that a hub receipt bound
    /// (`earn_receipt`), and the receipts that did not, by reason.
    pub earn_bound_by_receipt: AtomicU64,
    pub earn_receipt_fetch_failed: AtomicU64,
    pub earn_receipt_unverified: AtomicU64,
    pub earn_receipt_not_settled: AtomicU64,
    pub earn_receipt_wrong_executor: AtomicU64,
    pub earn_receipt_reused: AtomicU64,
    /// Offers whose voucher named a requester node / offer hash that did not
    /// match what arrived (refused 402), and vouchers that carry neither
    /// (accepted: minted by a hub or a requester without the binding).
    pub voucher_binding_refused: AtomicU64,
    pub voucher_unbound_seen: AtomicU64,
    /// Voucher redeems the hub answered with a terminal refusal (409: it
    /// never minted that nonce): dropped from the retry queue.
    pub voucher_redeem_refused: AtomicU64,
    /// Peer results by receipt state, counted by the requester before paying.
    pub receipt_verified: AtomicU64,
    pub receipt_missing: AtomicU64,
    pub receipt_invalid: AtomicU64,
    pub(crate) voucher_override: OnceLock<bool>,
    pub(crate) sig_v2_override: OnceLock<bool>,
    pub(crate) earn_mode_override: OnceLock<EarnBindingMode>,
    pub(crate) worker_key_override: OnceLock<bool>,
    pub(crate) roster_max_age_override: OnceLock<u64>,
    pub(crate) earn_after_receipt_override: OnceLock<bool>,
}

impl Default for ZeroTrust {
    fn default() -> Self {
        Self::new()
    }
}

impl ZeroTrust {
    pub fn new() -> Self {
        Self {
            started_at: super::node_identity::now_secs(),
            roster_fetched_at: AtomicU64::new(0),
            sig_v1_only_seen: AtomicU64::new(0),
            keyless_worker_nonloopback: AtomicU64::new(0),
            earn_bound: AtomicU64::new(0),
            earn_unknown_job: AtomicU64::new(0),
            earn_over_amount: AtomicU64::new(0),
            earn_wrong_requester: AtomicU64::new(0),
            earn_bound_by_receipt: AtomicU64::new(0),
            earn_receipt_fetch_failed: AtomicU64::new(0),
            earn_receipt_unverified: AtomicU64::new(0),
            earn_receipt_not_settled: AtomicU64::new(0),
            earn_receipt_wrong_executor: AtomicU64::new(0),
            earn_receipt_reused: AtomicU64::new(0),
            voucher_binding_refused: AtomicU64::new(0),
            voucher_unbound_seen: AtomicU64::new(0),
            voucher_redeem_refused: AtomicU64::new(0),
            receipt_verified: AtomicU64::new(0),
            receipt_missing: AtomicU64::new(0),
            receipt_invalid: AtomicU64::new(0),
            voucher_override: OnceLock::new(),
            sig_v2_override: OnceLock::new(),
            earn_mode_override: OnceLock::new(),
            worker_key_override: OnceLock::new(),
            roster_max_age_override: OnceLock::new(),
            earn_after_receipt_override: OnceLock::new(),
        }
    }

    pub(crate) fn bump(c: &AtomicU64) {
        c.fetch_add(1, Ordering::Relaxed);
    }

    pub fn load(c: &AtomicU64) -> u64 {
        c.load(Ordering::Relaxed)
    }

    /// Record a successful roster fetch (or the cache file's own timestamp).
    pub fn note_roster_fetched(&self, at: u64) {
        self.roster_fetched_at.store(at, Ordering::Relaxed);
    }
}

impl BrokerState {
    /// A hub is configured: a non-blank API URL and API key.
    pub fn hub_configured(&self) -> bool {
        let set = |v: &Option<String>| v.as_deref().is_some_and(|s| !s.trim().is_empty());
        set(&self.config.api_url) && set(&self.config.api_key)
    }

    /// Are `/peer/*` node signatures enforced? Test override, else
    /// `ZAKURO_ENFORCE_NODE_SIG`, else: enforce iff a hub is configured AND a
    /// roster has been loaded (from the hub or the disk cache). A hubless or
    /// local broker has no roster to check against and stays permissive.
    pub fn node_sig_enforced(&self) -> bool {
        self.enforce_node_sig_override
            .get()
            .copied()
            .or_else(|| env_flag("ZAKURO_ENFORCE_NODE_SIG"))
            .unwrap_or_else(|| self.hub_configured() && !self.node_roster.is_empty())
    }

    /// Are dashboard vouchers required for foreign jobs? Test override, else
    /// `ZAKURO_REQUIRE_VOUCHER`, else: iff a hub is configured.
    pub fn voucher_required(&self) -> bool {
        self.zt
            .voucher_override
            .get()
            .copied()
            .or_else(|| env_flag("ZAKURO_REQUIRE_VOUCHER"))
            .unwrap_or_else(|| self.hub_configured())
    }

    /// `ZAKURO_REQUIRE_SIG_V2`: refuse requests that carry only the v1 signature.
    pub fn require_sig_v2(&self) -> bool {
        self.zt
            .sig_v2_override
            .get()
            .copied()
            .or_else(|| env_flag("ZAKURO_REQUIRE_SIG_V2"))
            .unwrap_or(false)
    }

    /// `ZAKURO_EARN_BINDING=observe|enforce` (default observe).
    pub fn earn_binding_mode(&self) -> EarnBindingMode {
        self.zt
            .earn_mode_override
            .get()
            .copied()
            .unwrap_or_else(|| {
                EarnBindingMode::parse(std::env::var("ZAKURO_EARN_BINDING").ok().as_deref())
            })
    }

    /// `ZAKURO_REQUIRE_WORKER_KEY`: refuse keyless non-loopback registrations.
    pub fn require_worker_key(&self) -> bool {
        self.zt
            .worker_key_override
            .get()
            .copied()
            .or_else(|| env_flag("ZAKURO_REQUIRE_WORKER_KEY"))
            .unwrap_or(false)
    }

    /// `ZAKURO_EARN_AFTER_RECEIPT`: this broker, as a requester, sends the
    /// payout of a job whose debit it tracks only once the hub has committed
    /// the debit and answered its receipt, and attaches that receipt. Off by
    /// default: the payout then goes out right after the job, as before, and an
    /// executor that never saw the job classifies it `unknown_job`.
    pub fn earn_after_receipt(&self) -> bool {
        self.zt
            .earn_after_receipt_override
            .get()
            .copied()
            .or_else(|| env_flag("ZAKURO_EARN_AFTER_RECEIPT"))
            .unwrap_or(false)
    }

    /// `ZAKURO_ROSTER_MAX_AGE` seconds (default one day).
    pub fn roster_max_age_secs(&self) -> u64 {
        self.zt
            .roster_max_age_override
            .get()
            .copied()
            .unwrap_or_else(|| {
                std::env::var("ZAKURO_ROSTER_MAX_AGE")
                    .ok()
                    .and_then(|v| v.trim().parse().ok())
                    .unwrap_or(ROSTER_MAX_AGE_DEFAULT_SECS)
            })
    }

    /// Seconds since the roster was last fetched successfully, `None` when
    /// that was never recorded.
    pub fn roster_age_secs(&self) -> Option<u64> {
        match self.zt.roster_fetched_at.load(Ordering::Relaxed) {
            0 => None,
            at => Some(super::node_identity::now_secs().saturating_sub(at)),
        }
    }

    /// With a hub configured and enforcement on, a roster older than
    /// [`roster_max_age_secs`](Self::roster_max_age_secs) is not trusted: a node
    /// revoked since cannot be told from a live one. An unknown age (roster
    /// set without a fetch) is not stale.
    pub fn roster_stale(&self) -> bool {
        self.hub_configured()
            && self.node_sig_enforced()
            && self
                .roster_age_secs()
                .is_some_and(|a| a > self.roster_max_age_secs())
    }

    /// The zc build the hub roster lists for node `fp` (`zc://node-<fp>` or
    /// bare), when it sent one.
    pub fn hub_build_for(&self, fp: &str) -> Option<crate::build_id::BuildId> {
        let fp = super::node_identity::strip_node_arg(fp);
        self.node_builds.iter().find_map(|e| {
            (super::node_identity::fingerprint_of_pubkey_b64(e.key()).as_deref() == Some(fp))
                .then(|| e.value().clone())
        })
    }

    /// The `zero_trust` object served on `/health`.
    pub fn zero_trust_health(&self) -> serde_json::Value {
        let zt = &self.zt;
        serde_json::json!({
            "node_sig": if self.node_sig_enforced() { "enforced" } else { "permissive" },
            "voucher": if self.voucher_required() { "required" } else { "optional" },
            "sig_v2": if self.require_sig_v2() { "required" } else { "optional" },
            "sig_v1_only_seen": ZeroTrust::load(&zt.sig_v1_only_seen),
            "roster_age_secs": self.roster_age_secs(),
            "roster_stale": self.roster_stale(),
            "keyless_worker_nonloopback": ZeroTrust::load(&zt.keyless_worker_nonloopback),
            "worker_key": if self.require_worker_key() { "required" } else { "optional" },
            "earn_binding": {
                "mode": self.earn_binding_mode().as_str(),
                "bound": ZeroTrust::load(&zt.earn_bound),
                "unknown_job": ZeroTrust::load(&zt.earn_unknown_job),
                "over_amount": ZeroTrust::load(&zt.earn_over_amount),
                "wrong_requester": ZeroTrust::load(&zt.earn_wrong_requester),
                "bound_by_receipt": ZeroTrust::load(&zt.earn_bound_by_receipt),
                "receipt_rejected": {
                    "fetch_failed": ZeroTrust::load(&zt.earn_receipt_fetch_failed),
                    "unverified": ZeroTrust::load(&zt.earn_receipt_unverified),
                    "not_settled": ZeroTrust::load(&zt.earn_receipt_not_settled),
                    "wrong_executor": ZeroTrust::load(&zt.earn_receipt_wrong_executor),
                    "reused": ZeroTrust::load(&zt.earn_receipt_reused),
                },
            },
            "voucher_binding": {
                "refused": ZeroTrust::load(&zt.voucher_binding_refused),
                "unbound_seen": ZeroTrust::load(&zt.voucher_unbound_seen),
            },
            // Refused on the first try (not queued) plus dropped from the retry queue.
            "voucher_redeem_refused":
                ZeroTrust::load(&zt.voucher_redeem_refused) + self.voucher_retry.refused(),
            "receipts": {
                "verified": ZeroTrust::load(&zt.receipt_verified),
                "missing": ZeroTrust::load(&zt.receipt_missing),
                "invalid": ZeroTrust::load(&zt.receipt_invalid),
            },
            "voucher_redeem_queue": self.voucher_retry.depth(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn flag_parsing() {
        for t in ["1", "true", "TRUE", "yes", "on", " On "] {
            assert_eq!(parse_flag(Some(t)), Some(true), "{t}");
        }
        for f in ["0", "false", "no", "off", "OFF"] {
            assert_eq!(parse_flag(Some(f)), Some(false), "{f}");
        }
        for u in ["", "maybe", "2"] {
            assert_eq!(parse_flag(Some(u)), None, "{u}");
        }
        assert_eq!(parse_flag(None), None);
    }

    #[test]
    fn earn_mode_defaults_to_observe() {
        assert_eq!(EarnBindingMode::parse(None), EarnBindingMode::Observe);
        assert_eq!(EarnBindingMode::parse(Some("")), EarnBindingMode::Observe);
        assert_eq!(
            EarnBindingMode::parse(Some("bogus")),
            EarnBindingMode::Observe
        );
        assert_eq!(
            EarnBindingMode::parse(Some("Enforce")),
            EarnBindingMode::Enforce
        );
    }
}