zc2 0.0.30

P2P compute broker with credit-based 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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//! `zc init` — device-code browser authentication.
//!
//! Flow:
//!   1. POST /api/auth/cli/start  → get device_code, user_code, verification_uri, interval
//!   2. Open the browser at verification_uri
//!   3. Poll POST /api/auth/cli/poll with {device_code} every `interval` seconds
//!   4. On 200 + api_key  → save credentials, exit 0
//!      On 428            → keep polling (pending)
//!      On anything else  → print error, exit 1

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

/// Outcome of a single poll response.
pub enum Decision {
    Pending,
    Approved(String),
    Failed(String),
}

/// Truncate a raw hostname to at most 128 *characters* (never bytes — slicing
/// a multi-byte string at a raw byte offset can land mid-codepoint and
/// panic), defaulting an empty or whitespace-only name to `"zc CLI"`.
pub(crate) fn clamp_device_name(raw: &str) -> String {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return "zc CLI".to_string();
    }
    trimmed.chars().take(128).collect()
}

/// This Mac's name for its hub device key (spec §5.1: `device_name`, ≤128 chars).
pub(crate) fn device_name() -> String {
    let name = hostname::get()
        .map(|h| h.to_string_lossy().into_owned())
        .unwrap_or_default();
    clamp_device_name(&name)
}

/// Body of `POST /api/auth/cli/start`. An older hub ignores it.
pub(crate) fn start_body(device_name: &str) -> String {
    serde_json::json!({ "device_name": device_name }).to_string()
}

/// What `zc login` prints once approved: whether the hub minted a revocable
/// device key (`token_type: "device"`) or an older session token.
pub(crate) fn approved_message(poll_body: &str) -> &'static str {
    let kind = serde_json::from_str::<serde_json::Value>(poll_body)
        .ok()
        .and_then(|v| v["token_type"].as_str().map(str::to_string));
    match kind.as_deref() {
        Some("device") => {
            "✓ Signed in. Device key saved to ~/.zakuro/credentials (revoke it on the hub under Signed-in devices)."
        }
        _ => "✓ Signed in. Key saved to ~/.zakuro/credentials.",
    }
}

/// Pure decision function — maps an HTTP status + body to a `Decision`.
/// No network I/O; suitable for unit tests.
pub fn decide(http_status: u16, body: &str) -> Decision {
    match http_status {
        428 => Decision::Pending,
        200 => {
            match serde_json::from_str::<serde_json::Value>(body)
                .ok()
                .and_then(|v| v["api_key"].as_str().map(|s| s.to_string()))
            {
                Some(k) => Decision::Approved(k),
                None => Decision::Failed("approved but no api_key in response".into()),
            }
        }
        410 => Decision::Failed("code expired — run `zc init` again".into()),
        403 => Decision::Failed("authorization was denied".into()),
        404 => Decision::Failed("session not found".into()),
        s => Decision::Failed(format!("unexpected status {s}")),
    }
}

/// Print how to connect by setting an API key, listing the known dashboards.
/// Shown when browser device-code sign-in isn't available on the target.
pub fn print_connect_guidance() {
    eprintln!();
    eprintln!("To connect, grab your API key from the dashboard (Profile → API Keys), then:");
    eprintln!();
    eprintln!("  # pick your environment");
    eprintln!(
        "  export ZAKURO_API_URL={}   # production",
        crate::credentials::PROD_API_URL
    );
    eprintln!(
        "  export ZAKURO_API_URL={}   # staging",
        crate::credentials::STAGING_API_URL
    );
    eprintln!();
    eprintln!("  export ZAKURO_API_KEY=<your key>");
    eprintln!("  zc connect            # join the mesh (add --docker to use Docker)");
}

/// What `zc login` should do, given the credential state and flags. Split out
/// from `run` so the routing is unit-testable without a network or a browser.
#[derive(Debug, PartialEq)]
pub(crate) enum Plan {
    /// Signed in already: bring up the mesh instead of printing another command.
    ConnectMesh,
    /// Signed in already, but the caller asked us not to touch the network.
    ReportOnly,
    /// No usable key, or `--force`: run the device-code sign-in.
    SignIn,
}

pub(crate) fn plan(has_key: bool, force: bool, no_connect: bool) -> Plan {
    if !has_key || force {
        return Plan::SignIn;
    }
    if no_connect {
        return Plan::ReportOnly;
    }
    Plan::ConnectMesh
}

/// What to do right after credentials are saved by a fresh or forced sign-in.
/// Split out from `run` so `--no-connect` is unit-testable without a network.
#[derive(Debug, PartialEq)]
pub(crate) enum PostSignIn {
    /// Bring up the mesh and report whether it's reachable.
    ConnectMesh,
    /// The caller asked us not to touch the network.
    SkipMesh,
}

pub(crate) fn post_sign_in(no_connect: bool) -> PostSignIn {
    if no_connect {
        PostSignIn::SkipMesh
    } else {
        PostSignIn::ConnectMesh
    }
}

/// Flags accepted by `zc login` / `zc init`, parsed from an injected argument
/// list so the routing is unit-testable without touching `std::env::args()`.
#[derive(Debug, Default, PartialEq)]
pub(crate) struct LoginArgs {
    pub help: bool,
    pub staging: bool,
    pub force: bool,
    pub no_connect: bool,
}

impl LoginArgs {
    pub(crate) fn parse(args: &[String]) -> LoginArgs {
        let mut parsed = LoginArgs::default();
        for arg in args {
            match arg.as_str() {
                "--help" | "-h" => parsed.help = true,
                "--staging" => parsed.staging = true,
                "--force" => parsed.force = true,
                "--no-connect" => parsed.no_connect = true,
                _ => {}
            }
        }
        parsed
    }
}

/// `zc login --help` / `-h` usage text, printed to stdout before any
/// credential read, network call, or mesh setup.
const LOGIN_HELP: &str = "\
Usage: zc login [--staging] [--force] [--no-connect]

Sign in to Zakuro via browser device-code auth, then connect to the mesh.
`zc login` is an alias of `zc init`.

Options:
      --staging      Use the staging dashboard (same as ZAKURO_ENV=staging).
      --force        Re-authenticate even if already signed in.
      --no-connect   Skip connecting to the mesh after signing in.
  -h, --help         Print this help and exit.

URL precedence: ZAKURO_API_URL > ZAKURO_ENV=staging > production.
";

pub(crate) fn print_help() {
    print!("{LOGIN_HELP}");
}

/// What `zc login` does about this device's node key before it joins the mesh
/// (ruling L1). Without the key, the WireGuard profile request carries no
/// fingerprint, and the device stays on the account's shared mesh identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NodeKeyStep {
    /// The key is already there: nothing to do.
    Present,
    /// No key yet: create it (0600).
    Create,
    /// No key yet, but running as root: a root-owned key in the user's home
    /// would break later non-root zc runs (R13), so leave it and warn.
    SkipAsRoot,
}

/// The [`NodeKeyStep`] decision as a pure function, so it is tested without a
/// real home directory.
pub(crate) fn node_key_step(is_root: bool, key_present: bool) -> NodeKeyStep {
    match (key_present, is_root) {
        (true, _) => NodeKeyStep::Present,
        (false, false) => NodeKeyStep::Create,
        (false, true) => NodeKeyStep::SkipAsRoot,
    }
}

/// Carry out [`node_key_step`] against `<dir>/node_key` and return the step.
/// Only [`NodeKeyStep::Create`] writes, through `NodeKey::load_or_create_in`,
/// and a key that loads is never rewritten.
pub(crate) fn ensure_node_key_in(dir: Option<std::path::PathBuf>, is_root: bool) -> NodeKeyStep {
    use crate::broker::node_identity::NodeKey;
    let step = node_key_step(is_root, NodeKey::load_in(dir.clone()).is_some());
    if step == NodeKeyStep::Create {
        NodeKey::load_or_create_in(dir);
    }
    step
}

/// [`ensure_node_key_in`] against the real state dir, the one
/// `NodeKey::load_or_create` uses, with a one-line warning for root.
fn ensure_node_key() {
    if ensure_node_key_in(crate::credentials::dir(), crate::vpn::native::is_root())
        == NodeKeyStep::SkipAsRoot
    {
        eprintln!(
            "⚠ running as root: not creating ~/.zakuro/node_key; run zc login as your user so this device gets its own mesh identity"
        );
    }
}

/// Bring up mesh access and report it. Shared by both sign-in paths so a fresh
/// sign-in and an already-signed-in re-run print the same thing. `--no-connect`
/// never gets here, so it skips the node key along with the mesh.
///
/// Returns true when the mesh is reachable. Safe to call when already connected:
/// `vpn::connect` returns the live connection instead of rebuilding the tunnel.
fn connect_mesh() -> bool {
    // Before the profile request (ruling L1): with a node key, it carries this
    // device's fingerprint, and the hub can give the device its own mesh
    // identity.
    ensure_node_key();
    match crate::vpn::ensure(crate::vpn::connector::Preference::Auto) {
        Ok(crate::vpn::MeshAccess::Host) => {
            println!("✓ Mesh reachable from this host. Try `zc me`.");
            true
        }
        Ok(crate::vpn::MeshAccess::Proxy(p)) => {
            println!("✓ Mesh reachable via VPN container proxy ({p}). Try `zc me`.");
            true
        }
        Err(e) => {
            eprintln!("✗ VPN setup failed: {e}");
            eprintln!("  Retry with `zc connect`.");
            false
        }
    }
}

/// Run the `zc init` device-code flow. Returns an exit code (0 = success).
pub fn run() -> i32 {
    // Parse flags first: `--help`/`-h` must return before any credential read,
    // network call, or mesh setup.
    let args = LoginArgs::parse(&std::env::args().skip(1).collect::<Vec<_>>());
    if args.help {
        print_help();
        return 0;
    }

    crate::credentials::load_into_env();

    // `--staging` (or `ZAKURO_ENV=staging`) points init at the staging dashboard.
    // An explicit `ZAKURO_API_URL` still wins over both.
    let api_url = if args.staging && std::env::var("ZAKURO_API_URL").is_err() {
        crate::credentials::STAGING_API_URL.to_string()
    } else {
        crate::credentials::default_api_url()
    };

    let has_key = std::env::var("ZAKURO_API_KEY")
        .map(|k| !k.trim().is_empty())
        .unwrap_or(false);
    let force = args.force;
    let no_connect = args.no_connect;
    match plan(has_key, force, no_connect) {
        Plan::ReportOnly => {
            eprintln!("Already signed in (→ {api_url}).");
            eprintln!("  Connect with:   zc connect");
            eprintln!("  Re-auth with:   zc login --force");
            return 0;
        }
        Plan::ConnectMesh => {
            // Already authenticated: go straight to the mesh rather than printing
            // a second command to run. `zc login` then means "get this machine
            // ready" whatever state it starts in, matching a fresh sign-in.
            eprintln!("Already signed in (→ {api_url}).");
            eprintln!("  Connecting to the zakuro mesh…");
            // Exit 0 even when the mesh is unreachable: this command's contract
            // is "am I authenticated", it has always returned 0 here, and a
            // flaky network should not start failing scripts that re-run it.
            connect_mesh();
            return 0;
        }
        Plan::SignIn => {}
    }

    // ── start ──────────────────────────────────────────────────────────
    // Browser device-code sign-in. Not every dashboard exposes it yet; when the
    // endpoint is missing (404) or unreachable we fall back to explicit guidance
    // rather than dumping a raw error — the user can always set ZAKURO_API_KEY.
    let start_url = format!("{}/api/auth/cli/start", api_url.trim_end_matches('/'));
    let start_send = ureq::post(&start_url)
        .config()
        .http_status_as_error(false)
        .build()
        .header("Content-Type", "application/json")
        .send(start_body(&device_name()).as_str());
    let start_resp = match start_send {
        Ok(r) if r.status().as_u16() == 200 => r,
        Ok(r) if r.status().as_u16() == 404 => {
            eprintln!(
                "Browser sign-in isn't available on {api_url} (device-code endpoint not found)."
            );
            print_connect_guidance();
            // With a working key already set, this isn't a real failure.
            return if has_key { 0 } else { 1 };
        }
        Ok(r) => {
            eprintln!(
                "Sign-in could not start on {api_url}: HTTP {}",
                r.status().as_u16()
            );
            print_connect_guidance();
            return 1;
        }
        Err(e) => {
            eprintln!("Could not reach {api_url}: {e}");
            print_connect_guidance();
            return 1;
        }
    };
    let start_body = match start_resp.into_body().read_to_string() {
        Ok(s) => s,
        Err(e) => {
            eprintln!("Failed to read start response: {e}");
            return 1;
        }
    };
    let start: serde_json::Value = match serde_json::from_str(&start_body) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("Failed to parse start response: {e}");
            return 1;
        }
    };

    let device_code = start["device_code"].as_str().unwrap_or("").to_string();
    let user_code = start["user_code"].as_str().unwrap_or("");
    let verification_uri = start["verification_uri"].as_str().unwrap_or("");
    let interval = start["interval"].as_u64().unwrap_or(5);
    let expires_in = start["expires_in"].as_u64().unwrap_or(300);

    println!("\n  To sign in, open:      {verification_uri}");
    println!("  and confirm the code:  {user_code}\n");
    let _ = open_browser(verification_uri);

    // ── poll ───────────────────────────────────────────────────────────
    let poll_url = format!("{}/api/auth/cli/poll", api_url.trim_end_matches('/'));
    let poll_start = Instant::now();
    loop {
        std::thread::sleep(Duration::from_secs(interval));

        if poll_start.elapsed().as_secs() >= expires_in {
            eprintln!("\nCode expired — run `zc init` again");
            return 1;
        }

        let payload = serde_json::to_string(&serde_json::json!({"device_code": &device_code}))
            .unwrap_or_default();

        let (status, resp_body) = match ureq::post(&poll_url)
            .config()
            .http_status_as_error(false)
            .build()
            .header("Content-Type", "application/json")
            .send(payload.as_str())
        {
            Ok(r) => {
                let s = r.status().as_u16();
                let b = r.into_body().read_to_string().unwrap_or_default();
                (s, b)
            }
            Err(_) => continue, // transient network error — keep polling
        };

        match decide(status, &resp_body) {
            Decision::Pending => {
                print!(".");
                use std::io::Write;
                let _ = std::io::stdout().flush();
            }
            Decision::Approved(key) => {
                if let Err(e) = crate::credentials::save(&key, Some(&api_url)) {
                    eprintln!("\nsigned in but could not write credentials: {e}");
                    return 1;
                }
                // Export into THIS process so the mesh step below sees the key it
                // just minted — otherwise `vpn::ensure` (which reads the env) fails
                // with "p2p requires ZAKURO_API_KEY" immediately after a successful
                // sign-in.
                std::env::set_var("ZAKURO_API_KEY", &key);
                std::env::set_var("ZAKURO_API_URL", &api_url);
                println!("\n{}", approved_message(&resp_body));
                match post_sign_in(no_connect) {
                    PostSignIn::SkipMesh => {
                        println!(
                            "  Signed in. Skipping the mesh (--no-connect); connect later with zc connect."
                        );
                        return 0;
                    }
                    PostSignIn::ConnectMesh => {
                        println!("  Connecting to the zakuro mesh…");
                        // Unlike the already-signed-in path, a fresh sign-in reports a
                        // mesh failure as a failure: the user asked to get set up now
                        // and did not, so exiting 0 would misreport a half-finished
                        // setup.
                        return if connect_mesh() { 0 } else { 1 };
                    }
                }
            }
            Decision::Failed(msg) => {
                eprintln!("\n{msg}");
                return 1;
            }
        }
    }
}

pub fn open_browser(url: &str) -> std::io::Result<()> {
    let cmd = if cfg!(target_os = "macos") {
        "open"
    } else {
        "xdg-open"
    };
    std::process::Command::new(cmd)
        .arg(url)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .map(|_| ())
}

#[cfg(test)]
mod tests {
    #[test]
    fn decision_maps_statuses() {
        assert!(matches!(super::decide(428, ""), super::Decision::Pending));
        assert!(matches!(
            super::decide(200, "{\"api_key\":\"zk_1_x\"}"),
            super::Decision::Approved(ref k) if k == "zk_1_x"
        ));
        assert!(matches!(super::decide(410, ""), super::Decision::Failed(_)));
    }

    // `zc login` used to stop at "Already signed in" and print `zc vpn connect`
    // for the user to run themselves, so getting a machine ready took two
    // commands on every run after the first. It now connects the mesh itself.
    #[test]
    fn already_signed_in_connects_the_mesh() {
        assert_eq!(super::plan(true, false, false), super::Plan::ConnectMesh);
    }

    #[test]
    fn no_key_signs_in() {
        assert_eq!(super::plan(false, false, false), super::Plan::SignIn);
    }

    // --force re-auths even with a key present, and outranks --no-connect.
    #[test]
    fn force_signs_in_again() {
        assert_eq!(super::plan(true, true, false), super::Plan::SignIn);
        assert_eq!(super::plan(true, true, true), super::Plan::SignIn);
    }

    // Escape hatch for callers relying on this path having no side effects.
    #[test]
    fn no_connect_keeps_the_old_report_only_behaviour() {
        assert_eq!(super::plan(true, false, true), super::Plan::ReportOnly);
    }

    // An empty/whitespace key is not a key: `run` treats it as absent, so a
    // blank ZAKURO_API_KEY must still route to sign-in rather than the mesh.
    #[test]
    fn blank_key_is_not_signed_in() {
        assert_eq!(super::plan(false, false, true), super::Plan::SignIn);
    }

    #[test]
    fn start_sends_this_macs_device_name() {
        let body: serde_json::Value =
            serde_json::from_str(&super::start_body("jeans-mbp")).unwrap();
        assert_eq!(body, serde_json::json!({ "device_name": "jeans-mbp" }));
        let name = super::device_name();
        assert!(!name.is_empty() && name.chars().count() <= 128, "{name}");
    }

    #[test]
    fn approval_says_when_the_hub_minted_a_device_key() {
        assert!(
            super::approved_message(r#"{"api_key":"zk_1_x","token_type":"device"}"#)
                .contains("Device key")
        );
        assert_eq!(
            super::approved_message(r#"{"api_key":"x","token_type":"session","expires_in":43200}"#),
            "✓ Signed in. Key saved to ~/.zakuro/credentials."
        );
        assert_eq!(
            super::approved_message("not json"),
            "✓ Signed in. Key saved to ~/.zakuro/credentials."
        );
    }

    // A device name is truncated by characters, never bytes: slicing a
    // multi-byte string at a raw byte offset can land mid-codepoint and panic.
    #[test]
    fn device_name_clamp_truncates_multibyte_chars_not_bytes() {
        let long_multibyte: String = "é".repeat(200);
        let clamped = super::clamp_device_name(&long_multibyte);
        assert_eq!(clamped.chars().count(), 128);
    }

    #[test]
    fn device_name_clamp_defaults_empty_or_blank_to_zc_cli() {
        assert_eq!(super::clamp_device_name(""), "zc CLI");
        assert_eq!(super::clamp_device_name("   "), "zc CLI");
    }

    #[test]
    fn device_name_clamp_passes_short_names_through() {
        assert_eq!(super::clamp_device_name("jeans-mbp"), "jeans-mbp");
    }

    fn args(v: &[&str]) -> Vec<String> {
        v.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn login_args_help_long_flag() {
        let a = super::LoginArgs::parse(&args(&["--help"]));
        assert!(a.help);
    }

    #[test]
    fn login_args_help_short_flag() {
        let a = super::LoginArgs::parse(&args(&["-h"]));
        assert!(a.help);
    }

    #[test]
    fn login_args_force_and_no_connect() {
        let a = super::LoginArgs::parse(&args(&["--force", "--no-connect"]));
        assert!(a.force);
        assert!(a.no_connect);
        assert!(!a.help);
        assert!(!a.staging);
    }

    #[test]
    fn login_args_plain_sign_in_has_no_flags() {
        let a = super::LoginArgs::parse(&args(&[]));
        assert!(!a.help && !a.force && !a.no_connect && !a.staging);
    }

    #[test]
    fn login_args_staging_flag() {
        let a = super::LoginArgs::parse(&args(&["--staging"]));
        assert!(a.staging);
    }

    // After a fresh or forced sign-in, --no-connect must skip the mesh instead
    // of only affecting the already-signed-in `plan()` path.
    #[test]
    fn post_sign_in_no_connect_skips_the_mesh() {
        assert_eq!(super::post_sign_in(true), super::PostSignIn::SkipMesh);
    }

    #[test]
    fn post_sign_in_default_connects_the_mesh() {
        assert_eq!(super::post_sign_in(false), super::PostSignIn::ConnectMesh);
    }

    // Ruling L1: `zc login` gives a keyless device its own node key before it
    // joins the mesh; as root it leaves the user's home alone (R13).
    #[test]
    fn node_key_step_matrix() {
        use super::{node_key_step, NodeKeyStep};
        assert_eq!(node_key_step(false, true), NodeKeyStep::Present);
        assert_eq!(node_key_step(true, true), NodeKeyStep::Present);
        assert_eq!(node_key_step(false, false), NodeKeyStep::Create);
        assert_eq!(node_key_step(true, false), NodeKeyStep::SkipAsRoot);
    }

    /// A fresh temp dir per test, never the real `~/.zakuro`.
    fn key_dir(tag: &str) -> std::path::PathBuf {
        let d = std::env::temp_dir().join(format!("zc-init-node-key-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn login_creates_the_node_key_when_not_root() {
        let dir = key_dir("create");
        assert_eq!(
            super::ensure_node_key_in(Some(dir.clone()), false),
            super::NodeKeyStep::Create
        );
        let path = dir.join("node_key");
        assert!(path.exists(), "node_key created");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o600, "{mode:o}");
        }
        let fp = crate::vpn::profile::device_fingerprint_in(Some(dir.clone()))
            .expect("the profile request can now send this device's fingerprint");
        assert_eq!(fp.len(), 16, "{fp}");
        assert!(
            fp.chars().all(|c| matches!(c, '0'..='9' | 'a'..='f')),
            "{fp}"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn login_leaves_an_existing_node_key_alone() {
        let dir = key_dir("present");
        crate::broker::node_identity::NodeKey::load_or_create_in(Some(dir.clone()));
        let before = std::fs::read(dir.join("node_key")).unwrap();
        for is_root in [false, true] {
            assert_eq!(
                super::ensure_node_key_in(Some(dir.clone()), is_root),
                super::NodeKeyStep::Present
            );
            assert_eq!(std::fs::read(dir.join("node_key")).unwrap(), before);
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn login_as_root_creates_no_node_key() {
        let dir = key_dir("root");
        assert_eq!(
            super::ensure_node_key_in(Some(dir.clone()), true),
            super::NodeKeyStep::SkipAsRoot
        );
        assert!(!dir.join("node_key").exists());
        let _ = std::fs::remove_dir_all(&dir);
    }
}