zc2 0.0.52

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! `ZAKURO_ENV=lab|staging|prod`: the one place an environment's endpoints and
//! trust roots live (zc#503, part of the Zakuro Desktop initiative zc#493).
//!
//! A profile names, per environment:
//!   - the hub API base (what [`crate::credentials::default_api_url`] returns);
//!   - the get base (`/env`, `/zk0` and the `/zc` update mirror under it);
//!   - the OCI registry;
//!   - the update and image trust roots (ADR 0020 takes the action-token key
//!     from here too, so the lab and staging carry their own keys).
//!
//! The environment is chosen by, in order:
//!   1. `ZAKURO_ENV` in the process environment;
//!   2. `env=` in `~/.zakuro/credentials`, then `ZAKURO_ENV=` in `~/.zakuro/env`
//!      (both copied into the process env by `credentials::load_into_env`, which
//!      never overwrites a value already set);
//!   3. otherwise prod, which is exactly what zc did before profiles existed.
//!
//! Explicit per-endpoint variables still win over the profile:
//! `ZAKURO_API_URL` (hub), `ZAKURO_UPDATE_URL` (update mirror) and
//! `ZAKURO_REGISTRY` (registry). `zc doctor` prints the result and where each
//! value came from.

use crate::credentials::{PROD_API_URL, STAGING_API_URL};
use crate::verified_fetch::GET_BASE;

pub const ENV_VAR: &str = "ZAKURO_ENV";
pub const ENV_API_URL: &str = "ZAKURO_API_URL";
pub const ENV_REGISTRY: &str = "ZAKURO_REGISTRY";

/// Lab hub: nginx on :80 serves the SPA and proxies `/api/` to the hub API
/// (zak-platform-dev `lab/roles/hub.sh`), so the base has no port, like prod.
pub const LAB_API_URL: &str = "http://hub.lab.zakuro.internal";
/// Lab zak-get (`lab/roles/get.sh`): the lab's zc build under `/zc`.
pub const LAB_GET_BASE: &str = "http://get.lab.zakuro.internal";
/// Lab pull-through cache for docker.io (`lab/roles/registry.sh`).
pub const LAB_REGISTRY: &str = "registry.lab.zakuro.internal:5000";
/// Where the fleet's images are pushed (`.github/workflows/deploy.yml`).
pub const FLEET_REGISTRY: &str = "registry.local.zakuro-ai.com";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Env {
    Lab,
    Staging,
    Prod,
}

impl Env {
    /// Accepts the names zc already took for staging (`stg`, `stage`).
    /// `None` for anything else, including the empty string.
    pub fn parse(s: &str) -> Option<Env> {
        match s.trim().to_ascii_lowercase().as_str() {
            "lab" => Some(Env::Lab),
            "staging" | "stg" | "stage" => Some(Env::Staging),
            "prod" | "production" => Some(Env::Prod),
            _ => None,
        }
    }

    pub fn name(self) -> &'static str {
        match self {
            Env::Lab => "lab",
            Env::Staging => "staging",
            Env::Prod => "prod",
        }
    }

    pub fn profile(self) -> &'static Profile {
        match self {
            Env::Lab => &LAB,
            Env::Staging => &STAGING,
            Env::Prod => &PROD,
        }
    }
}

/// One environment's built-in values. Overrides are applied by [`resolve_with`].
#[derive(Debug, PartialEq, Eq)]
pub struct Profile {
    pub env: Env,
    pub api_url: &'static str,
    /// Base for `/env`, `/zk0?config=…` and the `/zc` update mirror.
    pub get_base: &'static str,
    pub registry: &'static str,
    /// Minisign public key (base64 key line) that `/zc/manifest/{platform}`
    /// must be signed with (zak-get GET-0013, zc#505). `zc update` refuses an
    /// unsigned or mismatched manifest. The same key signs the desktop
    /// updater manifest (zc#507).
    pub update_trust_root: &'static str,
    /// Public key images are verified against (cosign). Empty: not enforced yet.
    pub image_trust_root: &'static str,
    /// Whether `envs::update` fetches the legacy `/env` profile into
    /// `/opt/zakuro/etc/zk0.env`. That file is the Spark-era fleet's PATH /
    /// SPARK_* / ZAKURO_HOME defaults. A lab node gets its environment from
    /// `node.env` and has no `/opt/zakuro`, so fetching it there only logged
    /// "Error downloading env profile" on every start.
    pub legacy_env_profile: bool,
    /// Whether `zc update` may fall back to the GitHub releases when the
    /// mirror fails. Off in the lab, which must not reach the internet.
    pub github_update_fallback: bool,
}

impl Profile {
    /// The update mirror under the get base (`<get>/zc`).
    pub fn mirror_base(&self) -> String {
        format!("{}/zc", self.get_base.trim_end_matches('/'))
    }
}

/// The zakuro update signing key (minisign, key id 77A124E19F017ADE). Its
/// private half is the `ZAKURO_UPDATE_SIGNING_KEY` secret in zak-get and zc.
/// zak-get serves a copy at `/zc/update-signing.pub`. Rotation: zak-get
/// GET-0013.
pub const UPDATE_SIGNING_KEY: &str = "RWTeegGf4SShd8P0e8Yq3c03POhbarqXJt1boW2b7QDYIvGn9Cs4MvYf";

pub static PROD: Profile = Profile {
    env: Env::Prod,
    api_url: PROD_API_URL,
    get_base: GET_BASE,
    registry: FLEET_REGISTRY,
    update_trust_root: UPDATE_SIGNING_KEY,
    image_trust_root: "",
    legacy_env_profile: true,
    github_update_fallback: true,
};

/// Staging shares prod's get mirror and registry: before profiles, only the
/// hub URL followed `ZAKURO_ENV=staging`, and that stays so.
pub static STAGING: Profile = Profile {
    env: Env::Staging,
    api_url: STAGING_API_URL,
    get_base: GET_BASE,
    registry: FLEET_REGISTRY,
    update_trust_root: UPDATE_SIGNING_KEY,
    image_trust_root: "",
    legacy_env_profile: true,
    github_update_fallback: true,
};

pub static LAB: Profile = Profile {
    env: Env::Lab,
    api_url: LAB_API_URL,
    get_base: LAB_GET_BASE,
    registry: LAB_REGISTRY,
    update_trust_root: UPDATE_SIGNING_KEY,
    image_trust_root: "",
    legacy_env_profile: false,
    github_update_fallback: false,
};

/// Where a resolved value came from, for `zc doctor`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
    /// The active profile's built-in value.
    Profile,
    /// An explicit variable (named) that overrides the profile.
    Override(&'static str),
}

/// The active profile with its overrides applied.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Resolved {
    pub profile: &'static Profile,
    /// `ZAKURO_ENV` when it named no known environment (prod is used).
    pub unknown_env: Option<String>,
    pub api_url: (String, Source),
    pub mirror_base: (String, Source),
    pub registry: (String, Source),
}

fn non_empty(v: Option<String>) -> Option<String> {
    v.filter(|s| !s.trim().is_empty())
}

/// The environment `ZAKURO_ENV` selects, plus the raw value if it named none.
pub fn env_with(var: &impl Fn(&str) -> Option<String>) -> (Env, Option<String>) {
    match non_empty(var(ENV_VAR)) {
        None => (Env::Prod, None),
        Some(v) => match Env::parse(&v) {
            Some(e) => (e, None),
            None => (Env::Prod, Some(v)),
        },
    }
}

/// [`resolve`] with the variable lookup injected, so tests never touch the
/// process environment (see `credentials::HOME_ENV_LOCK` for why).
///
/// The update mirror override is returned as given; `update::mirror_base`
/// normalises and validates it.
pub fn resolve_with(var: impl Fn(&str) -> Option<String>) -> Resolved {
    let (env, unknown_env) = env_with(&var);
    let p = env.profile();
    let pick = |name: &'static str, dflt: String| match non_empty(var(name)) {
        Some(v) => (v, Source::Override(name)),
        None => (dflt, Source::Profile),
    };
    Resolved {
        profile: p,
        unknown_env,
        api_url: pick(ENV_API_URL, p.api_url.to_string()),
        mirror_base: pick(crate::update::ENV_UPDATE_URL, p.mirror_base()),
        registry: pick(ENV_REGISTRY, p.registry.to_string()),
    }
}

/// The active profile, resolved against the process environment.
pub fn resolve() -> Resolved {
    resolve_with(|k| std::env::var(k).ok())
}

/// The active profile's built-in values (no overrides).
pub fn active() -> &'static Profile {
    env_with(&|k| std::env::var(k).ok()).0.profile()
}

/// `zc doctor`'s profile section.
pub fn doctor_report(r: &Resolved) -> String {
    let src = |s: Source| match s {
        Source::Profile => "profile".to_string(),
        Source::Override(v) => v.to_string(),
    };
    let root = |k: &'static str| if k.is_empty() { "(none)" } else { k };
    let mut out = format!("profile: {}", r.profile.env.name());
    if let Some(v) = &r.unknown_env {
        out.push_str(&format!(" ({ENV_VAR}={v:?} is not lab|staging|prod)"));
    }
    out.push_str(&format!(
        "\n  hub api:    {} ({})\n  get:        {}\n  mirror:     {} ({})\n  registry:   {} ({})\n  update key: {}\n  image key:  {}",
        r.api_url.0,
        src(r.api_url.1),
        r.profile.get_base,
        r.mirror_base.0,
        src(r.mirror_base.1),
        r.registry.0,
        src(r.registry.1),
        root(r.profile.update_trust_root),
        root(r.profile.image_trust_root),
    ));
    out
}

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

    fn vars(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
        let m: HashMap<String, String> = pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        move |k| m.get(k).cloned()
    }

    /// No `ZAKURO_ENV` is prod, with exactly the values zc hard-coded before.
    #[test]
    fn default_is_the_pre_profile_behaviour() {
        let r = resolve_with(vars(&[]));
        assert_eq!(r.profile.env, Env::Prod);
        assert_eq!(
            r.api_url,
            ("https://hub.zakuro-ai.com".into(), Source::Profile)
        );
        assert_eq!(r.mirror_base.0, crate::update::MIRROR_BASE);
        assert_eq!(r.mirror_base.0, "https://get.zakuro-ai.com/zc");
        assert!(r.profile.legacy_env_profile);
        assert_eq!(r.unknown_env, None);
    }

    /// Staging moves only the hub, as `ZAKURO_ENV=staging` always did.
    #[test]
    fn staging_moves_only_the_hub() {
        for v in ["staging", "stg", "stage", " STAGING "] {
            let r = resolve_with(vars(&[(ENV_VAR, v)]));
            assert_eq!(r.profile.env, Env::Staging, "{v}");
            assert_eq!(r.api_url.0, "https://stg.api.zakuro-ai.com");
            assert_eq!(r.mirror_base.0, "https://get.zakuro-ai.com/zc");
            assert!(r.profile.legacy_env_profile);
        }
    }

    /// Done-when of zc#503: under the lab profile nothing leaves
    /// `*.lab.zakuro.internal`, and the legacy `/env` fetch is off.
    #[test]
    fn lab_names_only_lab_hosts() {
        let r = resolve_with(vars(&[(ENV_VAR, "lab")]));
        assert_eq!(r.profile.env, Env::Lab);
        assert_eq!(r.api_url.0, "http://hub.lab.zakuro.internal");
        assert_eq!(r.mirror_base.0, "http://get.lab.zakuro.internal/zc");
        assert_eq!(r.registry.0, "registry.lab.zakuro.internal:5000");
        for host in [&r.api_url.0, &r.mirror_base.0, &r.registry.0] {
            let h = host
                .trim_start_matches("http://")
                .split(['/', ':'])
                .next()
                .unwrap();
            assert!(h.ends_with(".lab.zakuro.internal"), "{host}");
        }
        assert!(!r.profile.legacy_env_profile);
        assert!(!r.profile.github_update_fallback);
    }

    #[test]
    fn explicit_variables_override_the_profile() {
        let r = resolve_with(vars(&[
            (ENV_VAR, "lab"),
            (ENV_API_URL, "http://hub.lab.zakuro.internal:8000"),
            ("ZAKURO_UPDATE_URL", "https://stg.get.zakuro-ai.com"),
            (ENV_REGISTRY, "127.0.0.1:5000"),
        ]));
        assert_eq!(r.profile.env, Env::Lab);
        assert_eq!(
            r.api_url,
            (
                "http://hub.lab.zakuro.internal:8000".into(),
                Source::Override(ENV_API_URL)
            )
        );
        assert_eq!(
            r.mirror_base,
            (
                "https://stg.get.zakuro-ai.com".into(),
                Source::Override("ZAKURO_UPDATE_URL")
            )
        );
        assert_eq!(r.registry.1, Source::Override(ENV_REGISTRY));
    }

    /// An empty or blank override is "unset", as `default_api_url` always had it.
    #[test]
    fn blank_overrides_fall_back_to_the_profile() {
        let r = resolve_with(vars(&[
            (ENV_VAR, "lab"),
            (ENV_API_URL, "  "),
            (ENV_REGISTRY, ""),
        ]));
        assert_eq!(r.api_url, (LAB_API_URL.into(), Source::Profile));
        assert_eq!(r.registry, (LAB_REGISTRY.into(), Source::Profile));
        let r = resolve_with(vars(&[(ENV_VAR, "")]));
        assert_eq!(r.profile.env, Env::Prod);
        assert_eq!(r.unknown_env, None);
    }

    /// An unknown name keeps the old fallback (prod) but is reported.
    #[test]
    fn unknown_env_falls_back_to_prod_and_is_reported() {
        let r = resolve_with(vars(&[(ENV_VAR, "dev")]));
        assert_eq!(r.profile.env, Env::Prod);
        assert_eq!(r.unknown_env.as_deref(), Some("dev"));
        assert!(doctor_report(&r).contains("\"dev\" is not lab|staging|prod"));
    }

    #[test]
    fn doctor_names_the_profile_and_each_source() {
        let r = resolve_with(vars(&[(ENV_VAR, "lab"), (ENV_REGISTRY, "r:1")]));
        let out = doctor_report(&r);
        assert!(out.starts_with("profile: lab\n"), "{out}");
        assert!(out.contains("hub api:    http://hub.lab.zakuro.internal (profile)"));
        assert!(out.contains("registry:   r:1 (ZAKURO_REGISTRY)"));
        assert!(out.contains(&format!("update key: {UPDATE_SIGNING_KEY}")));
    }

    #[test]
    fn names_round_trip() {
        for e in [Env::Lab, Env::Staging, Env::Prod] {
            assert_eq!(Env::parse(e.name()), Some(e));
            assert_eq!(e.profile().env, e);
        }
    }
}