zc2 0.0.52

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use std::collections::HashMap;
use std::io::Write;
use std::path::PathBuf;

/// Serialises the remaining tests that redirect `HOME` / `ZAKURO_HOME`, or
/// `ZAKURO_STATE_DIR` (the vpn connection-state dir), and the tests that set
/// `ZAKURO_MASTER_KEY` (the broker's admin key and billing-mode switch).
///
/// Environment variables are process-global and `cargo test` is multi-threaded
/// by default, so without this two such tests interleave and the failure
/// surfaces in whichever one lost the race rather than the one that moved the
/// variable.
///
/// **This lock is a mitigation, not a guarantee.** It only orders tests that
/// take it, and `envs::update()` calls `set_var` over whatever keys a config
/// file carries -- so any test that boots a broker can still move these
/// variables without ever touching the lock. That is why serialising alone
/// did not fix CI. The durable answer is not to depend on the environment:
/// see [`dir_from`] and `NodeKey::load_or_create_in`, which take their inputs
/// as arguments. Prefer those in new tests; this remains for the ones that
/// genuinely exercise the env-reading path.
///
/// Poisoning is ignored on purpose -- a panic in one test must not cascade
/// into unrelated failures in every other test that wants the lock.
#[cfg(test)]
pub(crate) static HOME_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Where zc keeps per-node state: the Ed25519 node key, the roster cache, the
/// peer list.
///
/// `ZAKURO_HOME` wins when set, and is the state directory ITSELF -- the same
/// meaning `common::create_directories` already gives it when it makes
/// `config/`, `lib/`, `logs/` directly underneath. Honouring it here is not a
/// convenience: a containerised broker has no persistent `$HOME`, so mounting
/// a volume and pointing `ZAKURO_HOME` at it was the documented way to keep a
/// node's identity across restarts -- and this function ignoring the variable
/// silently defeated it. The k8s fleet ran that way for weeks: the volume was
/// mounted and empty, every restart minted a fresh keypair, re-registered as a
/// brand-new node, and orphaned the previous roster entry. Three accounts had
/// accumulated 25+ dead keys each by the time anyone looked.
///
/// Falls back to `$HOME/.zakuro`, which is what every non-container install
/// uses and what the LXC fleet pins via a systemd `Environment=HOME=/root`.
/// In the unit-test binary the fallback is a scratch directory instead; see
/// [`fallback_home`].
pub fn dir() -> Option<PathBuf> {
    dir_from(std::env::var_os("ZAKURO_HOME"), fallback_home())
}

/// The home directory state falls back to when no override is set: `$HOME`.
#[cfg(not(test))]
pub(crate) fn fallback_home() -> Option<std::ffi::OsString> {
    std::env::var_os("HOME")
}

/// In the unit-test binary, only a HOME that a test pointed into the temp dir
/// is kept. Any other one -- the developer's, or a broker host's real home --
/// is swapped for a per-process scratch directory, so a test that saves node
/// state without redirecting anything never writes the real `~/.zakuro`
/// (zc#211: the deploy drive tests rewrote a live broker's `deployments.json`).
#[cfg(test)]
pub(crate) fn fallback_home() -> Option<std::ffi::OsString> {
    Some(test_fallback_home(std::env::var_os("HOME"), &std::env::temp_dir()).into_os_string())
}

/// The unit-test rule of [`fallback_home`], as a pure function of its inputs.
#[cfg(test)]
pub(crate) fn test_fallback_home(
    home: Option<std::ffi::OsString>,
    tmp: &std::path::Path,
) -> PathBuf {
    match home {
        Some(h) if std::path::Path::new(&h).starts_with(tmp) => PathBuf::from(h),
        _ => tmp.join(format!("zc-test-home-{}", std::process::id())),
    }
}

/// The precedence rule itself, as a pure function of the two values.
///
/// Split out so it can be tested without touching process-global environment
/// variables. That is not tidiness: `envs::update()` calls `set_var` over
/// whatever keys a config file carries, so ANY concurrently running test that
/// boots a broker can move `ZAKURO_HOME` out from under a test that set it.
/// A test that mutates the environment cannot be made reliable by locking,
/// because the writers it races with do not take the lock.
pub fn dir_from(
    zakuro_home: Option<std::ffi::OsString>,
    home: Option<std::ffi::OsString>,
) -> Option<PathBuf> {
    if let Some(h) = zakuro_home {
        if !h.is_empty() {
            return Some(PathBuf::from(h));
        }
    }
    home.map(|h| PathBuf::from(h).join(".zakuro"))
}

/// Set on every process of an extra node (`zc node run` and its broker) to
/// the machine's own zakuro home. A node has its own `ZAKURO_HOME` (identity,
/// policy, deployments), but what is one per machine stays under this one:
/// the sandbox VM's work-dir mount, its size, and the admission lock.
pub const MACHINE_HOME_ENV: &str = "ZAKURO_MACHINE_HOME";

/// The machine's zakuro home: [`MACHINE_HOME_ENV`] when set, else [`dir`]
/// (they are the same directory for the main node).
pub fn machine_dir() -> Option<PathBuf> {
    machine_dir_from(std::env::var_os(MACHINE_HOME_ENV), dir())
}

pub(crate) fn machine_dir_from(
    machine: Option<std::ffi::OsString>,
    node: Option<PathBuf>,
) -> Option<PathBuf> {
    match machine {
        Some(m) if !m.is_empty() => Some(PathBuf::from(m)),
        _ => node,
    }
}

/// Production dashboard API base URL.
///
/// hub, not `my`: `my.zakuro-ai.com` has no DNS record at all (NXDOMAIN,
/// checked against 1.1.1.1 on 2026-09-06 — no A, AAAA or CNAME, only the zone
/// SOA). Every zc command without `ZAKURO_ENV=staging` therefore failed to
/// *resolve* rather than failing to authenticate, which is why it read as a
/// network problem instead of a wrong constant.
///
/// `hub.zakuro-ai.com` is the live prod host: a Cloudflare-proxied CNAME onto
/// the tunnel, publicly reachable, serving `/api/`. Prod has no `api.` split
/// yet — that needs a tunnel ingress rule, not just DNS — so unlike staging
/// below, the browser host and the machine host are the same name here. When
/// `api.hub.zakuro-ai.com` exists, this moves to it and the two match again.
pub const PROD_API_URL: &str = "https://hub.zakuro-ai.com";
/// Staging dashboard API base URL.
///
/// stg.api is the canonical MACHINE host, following the `stg.api.<service>`
/// convention. It is the same hub Service and the same paths as stg.hub --
/// the hub serves the whole dashboard API in-process, including
/// `/api/auth/cli/token` and `/api/auth/cli/join`, which `enroll` needs.
///
/// stg.hub remains the canonical BROWSER host and keeps the device-flow
/// `/activate` page and the Google OAuth callback, so those URLs are built
/// from the server's own DASHBOARD_BASE_URL and are unaffected by this.
/// The retired stg-my / stg.my-api are gone entirely.
pub const STAGING_API_URL: &str = "https://stg.api.zakuro-ai.com";

/// Resolve the dashboard API base URL, in precedence order:
///   1. `ZAKURO_API_URL` (explicit override) — used verbatim when non-empty.
///   2. the `ZAKURO_ENV` profile's hub (`lab`, `staging|stg|stage`, `prod`).
///   3. otherwise → production.
///
/// The per-environment values live in [`crate::profile`], so `ZAKURO_ENV`
/// flips every zc command (init, broker, enroll, info, …) at once.
pub fn default_api_url() -> String {
    crate::profile::resolve().api_url.0
}

pub fn path() -> Option<PathBuf> {
    dir().map(|d| d.join("credentials"))
}

pub fn parse(text: &str) -> HashMap<String, String> {
    let mut m = HashMap::new();
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let line = line.strip_prefix("export ").unwrap_or(line);
        if let Some((k, v)) = line.split_once('=') {
            m.insert(k.trim().to_string(), v.trim().to_string());
        }
    }
    m
}

pub fn save(api_key: &str, api_url: Option<&str>) -> std::io::Result<()> {
    let d = dir().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no HOME"))?;
    std::fs::create_dir_all(&d)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700)).ok();
    }
    let p = d.join("credentials");
    let mut body = format!("api_key={}\n", api_key);
    if let Some(u) = api_url {
        body.push_str(&format!("api_url={}\n", u));
    }
    let mut f = std::fs::File::create(&p)?;
    f.write_all(body.as_bytes())?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600)).ok();
    }
    Ok(())
}

/// Rewrite a stored API URL that names the decommissioned `my.zakuro-ai.com`
/// host (NXDOMAIN) to the production hub, so installs that saved it at
/// `zc init` time are not stuck. Any other URL is returned unchanged.
pub fn migrate_legacy_api_url(url: &str) -> String {
    let rest = url
        .trim()
        .strip_prefix("https://")
        .or_else(|| url.trim().strip_prefix("http://"));
    if let Some(rest) = rest {
        let host = rest.split(['/', ':']).next().unwrap_or("");
        if host.eq_ignore_ascii_case("my.zakuro-ai.com") {
            return PROD_API_URL.to_string();
        }
    }
    url.to_string()
}

/// Fill ZAKURO_API_KEY / ZAKURO_API_URL / ZAKURO_ENV from stored config when
/// unset. Precedence: process env > ~/.zakuro/credentials > ~/.zakuro/env.
/// The profile key is `env=` in credentials and `ZAKURO_ENV=` in env.
pub fn load_into_env() {
    let creds = path().and_then(|p| std::fs::read_to_string(p).ok());
    let env_file = dir().and_then(|d| std::fs::read_to_string(d.join("env")).ok());
    set_if_unset(
        crate::profile::ENV_VAR,
        stored_env(creds.as_deref(), env_file.as_deref()).as_ref(),
    );
    if let Some(p) = path() {
        if let Ok(text) = std::fs::read_to_string(&p) {
            let m = parse(&text);
            set_if_unset("ZAKURO_API_KEY", m.get("api_key"));
            set_if_unset(
                "ZAKURO_API_URL",
                m.get("api_url").map(|u| migrate_legacy_api_url(u)).as_ref(),
            );
        }
    }
    if let Some(d) = dir() {
        if let Ok(text) = std::fs::read_to_string(d.join("env")) {
            let m = parse(&text);
            set_if_unset("ZAKURO_API_KEY", m.get("ZAKURO_API_KEY"));
            set_if_unset(
                "ZAKURO_API_URL",
                m.get("ZAKURO_API_URL")
                    .map(|u| migrate_legacy_api_url(u))
                    .as_ref(),
            );
        }
    }
}

/// The profile stored in config: `env=` in credentials, else `ZAKURO_ENV=` in
/// the env file. Blank values count as unset. A `ZAKURO_ENV` already in the
/// process env beats both (`set_if_unset`).
fn stored_env(credentials: Option<&str>, env_file: Option<&str>) -> Option<String> {
    let get = |text: Option<&str>, key: &str| {
        text.and_then(|t| parse(t).remove(key))
            .filter(|v| !v.trim().is_empty())
    };
    get(credentials, "env").or_else(|| get(env_file, crate::profile::ENV_VAR))
}

fn set_if_unset(var: &str, value: Option<&String>) {
    if std::env::var(var).is_err() {
        if let Some(v) = value {
            if !v.is_empty() {
                std::env::set_var(var, v);
            }
        }
    }
}

/// Where `zc connect` stores the mesh's shared peer key (`ZAKURO_PEER_KEY`)
/// handed out by the hub, so a broker started on this machine can join the
/// mesh as a PEER (QUIC transport, `/peer/*`) without the operator pasting the
/// secret by hand. Sibling of `credentials` (0600 in a 0700 dir).
pub fn mesh_peer_key_path() -> Option<PathBuf> {
    dir().map(|d| d.join("mesh_peer_key"))
}

/// The stored mesh peer key, if `zc connect` saved one.
pub fn load_mesh_peer_key() -> Option<String> {
    let p = mesh_peer_key_path()?;
    let text = std::fs::read_to_string(p).ok()?;
    let k = text.trim();
    if k.is_empty() {
        None
    } else {
        Some(k.to_string())
    }
}

pub fn save_mesh_peer_key(key: &str) -> std::io::Result<()> {
    let d = dir().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no HOME"))?;
    std::fs::create_dir_all(&d)?;
    let p = d.join("mesh_peer_key");
    let mut f = std::fs::File::create(&p)?;
    f.write_all(key.trim().as_bytes())?;
    f.write_all(b"\n")?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600)).ok();
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    #[test]
    fn parse_prefers_env_else_file() {
        let txt = "api_key=zk_1_abc\napi_url=http://x\n";
        let m = super::parse(txt);
        assert_eq!(m.get("api_key").unwrap(), "zk_1_abc");
        assert_eq!(m.get("api_url").unwrap(), "http://x");
    }

    #[test]
    fn parse_strips_export_prefix() {
        let m = super::parse("export ZAKURO_API_URL=https://stg\n# c\nZAKURO_API_KEY=zk_1_a\n");
        assert_eq!(m.get("ZAKURO_API_URL").unwrap(), "https://stg");
        assert_eq!(m.get("ZAKURO_API_KEY").unwrap(), "zk_1_a");
    }

    /// stg-my is retired; staging machine traffic addresses stg.api. This constant is
    /// compiled into every installed binary, so it is pinned by value here --
    /// the pre-existing `envs_are_prod_then_staging` test compares against the
    /// constant itself and so would pass no matter what host it names.
    #[test]
    fn staging_points_at_stg_api_not_the_retired_stg_my() {
        assert_eq!(
            super::STAGING_API_URL,
            "https://stg.api.zakuro-ai.com",
            "staging must address stg.api, the machine host; stg-my is decommissioned"
        );
        assert_eq!(
            super::PROD_API_URL,
            "https://hub.zakuro-ai.com",
            "prod must name a host that resolves; my.zakuro-ai.com is NXDOMAIN"
        );
    }

    /// The config key's order: credentials `env=`, then the env file's
    /// `ZAKURO_ENV=`; a blank value is skipped.
    #[test]
    fn stored_env_prefers_credentials_then_env_file() {
        let creds = "api_key=zk_1_a\nenv=lab\n";
        let envf = "ZAKURO_ENV=staging\n";
        assert_eq!(
            super::stored_env(Some(creds), Some(envf)).as_deref(),
            Some("lab")
        );
        assert_eq!(
            super::stored_env(Some("api_key=zk_1_a\n"), Some(envf)).as_deref(),
            Some("staging")
        );
        assert_eq!(
            super::stored_env(Some("env=\n"), Some("export ZAKURO_ENV=lab\n")).as_deref(),
            Some("lab")
        );
        assert_eq!(super::stored_env(None, None), None);
    }

    #[test]
    fn legacy_my_host_migrates_to_hub() {
        let m = super::parse("api_key=zk_1_abc\napi_url=https://my.zakuro-ai.com\n");
        let u = super::migrate_legacy_api_url(m.get("api_url").unwrap());
        assert_eq!(u, "https://hub.zakuro-ai.com");
        assert_eq!(
            super::migrate_legacy_api_url("https://my.zakuro-ai.com/"),
            super::PROD_API_URL
        );
        assert_eq!(
            super::migrate_legacy_api_url("http://MY.zakuro-ai.com:8080/x"),
            super::PROD_API_URL
        );
    }

    #[test]
    fn migration_leaves_other_urls_alone() {
        for u in [
            "https://stg.api.zakuro-ai.com",
            "https://hub.zakuro-ai.com",
            "http://x",
            "https://notmy.zakuro-ai.com",
            "https://my.zakuro-ai.com.evil.example",
        ] {
            assert_eq!(super::migrate_legacy_api_url(u), u);
        }
    }

    /// zc#211: a unit test that saves node state without redirecting anything
    /// must land in a scratch directory, never the real `~/.zakuro` (the
    /// deploy drive tests rewrote a live broker's `deployments.json`). A HOME
    /// that a test pointed into the temp dir is kept, which is what the
    /// `enroll` and `roster_cache` tests rely on.
    #[test]
    fn unit_tests_swap_a_real_home_for_a_scratch_one() {
        let tmp = std::path::Path::new("/scratch");
        let scratch = super::test_fallback_home(Some("/home/foo".into()), tmp);
        assert!(scratch.starts_with(tmp), "{}", scratch.display());
        assert_eq!(super::test_fallback_home(None, tmp), scratch);
        assert_eq!(
            super::test_fallback_home(Some("/scratch/zc-enroll-test-1".into()), tmp),
            std::path::PathBuf::from("/scratch/zc-enroll-test-1")
        );
    }

    #[test]
    fn dir_never_falls_back_outside_the_temp_dir_in_unit_tests() {
        let home = std::path::PathBuf::from(super::fallback_home().expect("always set in tests"));
        assert!(home.starts_with(std::env::temp_dir()), "{}", home.display());
        assert_eq!(
            super::dir_from(None, Some(home.clone().into_os_string())),
            Some(home.join(".zakuro"))
        );
    }
}