zc2 0.0.47

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
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
664
665
666
667
668
669
670
671
//! Native backend: brings the tunnel up directly on the host via wg-quick
//! (kernel WireGuard on Linux, wireguard-go on macOS). Requires root: on Linux
//! zc must run as root; on macOS a plain `zc connect` asks for `sudo` once and
//! runs only the privileged steps through it (zc#380), so the API key, node
//! key and state stay the invoking user's.

use crate::vpn::connector::Connector;
use crate::vpn::profile::WgProfile;
use crate::vpn::{Backend, ConnectionInfo, NetError, PeerStatus};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::process::Command;

const IFACE: &str = "zakuro0";

#[derive(Default)]
pub struct NativeConnector;

/// This node's WireGuard mesh IP, or `None` when unreachable by any means.
///
/// `None` is a normal state, not an error: a broker with no tunnel is still
/// authorized, just temporarily unreachable, and must register without an
/// endpoint rather than guessing one.
///
/// Delegates wholesale to [`crate::broker::discovery::get_mesh_ip`], which is
/// the detector the rest of this binary already trusts -- `/health`'s
/// `wireguard_connected`, the node-sync tick's discovery gate, and the worker
/// sync all read it. It calls `getifaddrs(3)` via the `ifaces` crate, so it
/// needs no `ip` binary (the broker image ships none), picks the interface
/// whose own IPv4 address is in the `10.13.13.0/24` mesh -- by address, so a
/// macOS `utunN` counts (`vpn::local_mesh`) -- and
/// honours the `ZAKURO_MESH_IP` / `ZAKURO_WIREGUARD_IP` overrides.
///
/// This used to try the `ip` binary and then fall back to reading a
/// `/var/run/zakuro/mesh-ip` file published by a WireGuard sidecar. Both are
/// gone: `getifaddrs` sees strictly everything `ip -o addr show zakuro0`
/// reports, from the same kernel source and without a subprocess, so the
/// binary path added nothing; and the file was a second, lagging source of
/// truth that disagreed with `get_mesh_ip()` in exactly the container where
/// it was supposed to help. The manifest still publishes that file -- the
/// broker's readiness probe is a shell with no `ip` binary and still reads
/// it -- it is simply no longer how Rust learns its own address.
pub fn mesh_ip() -> Option<String> {
    crate::broker::discovery::get_mesh_ip()
}

#[cfg(unix)]
pub(crate) fn is_root() -> bool {
    // SAFETY: geteuid() is always safe; just reads the effective uid.
    unsafe { libc::geteuid() == 0 }
}

// The native backend is wg-quick/`ip`-based and Unix-only; on other hosts the
// "requires root" guard simply always fails so callers surface their normal
// unsupported-platform error instead of a compile break (libc::geteuid does
// not exist on Windows).
#[cfg(not(unix))]
pub(crate) fn is_root() -> bool {
    false
}

/// PATH augmented with the common Homebrew + sbin locations. `sudo` resets PATH
/// to a restricted `secure_path` that excludes `/opt/homebrew/bin` (Apple Silicon)
/// and `/usr/local/bin`, so without this a `sudo zc vpn connect` fails to find a
/// `brew install`-ed `wg-quick` / `wireguard-go` even though it is installed.
///
/// The Homebrew dirs go FIRST: `wg-quick` is `#!/usr/bin/env bash` and needs
/// bash 4+, which on macOS is Homebrew's (a wireguard-tools dependency);
/// `/bin/bash` is 3.2 and fails "Version mismatch: bash 3 detected" (zc#380).
fn augmented_path() -> String {
    augmented_path_from(&std::env::var("PATH").unwrap_or_default())
}

fn augmented_path_from(base: &str) -> String {
    const BREW: &str = "/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/local/sbin";
    if base.is_empty() {
        BREW.to_string()
    } else {
        format!("{BREW}:{base}")
    }
}

/// Resolve a binary's absolute path via the augmented PATH. Returns `None` if not
/// found. Used both to detect availability and to exec by absolute path (so a
/// sudo'd run doesn't depend on Rust's program-lookup honoring a modified PATH).
fn find(bin: &str) -> Option<String> {
    let out = Command::new("sh")
        .arg("-c")
        .arg(format!("command -v {}", bin))
        .env("PATH", augmented_path())
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let p = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if p.is_empty() {
        None
    } else {
        Some(p)
    }
}

fn have(bin: &str) -> bool {
    find(bin).is_some()
}

/// What stands between this host and a native tunnel.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Readiness {
    /// No `wg-quick` / `wireguard-go` installed.
    Missing,
    /// Installed, but zc isn't root.
    NeedsRoot,
    Ready,
}

pub(crate) fn readiness_of(root: bool, tools: bool) -> Readiness {
    match (tools, root) {
        (false, _) => Readiness::Missing,
        (true, false) => Readiness::NeedsRoot,
        (true, true) => Readiness::Ready,
    }
}

pub(crate) fn readiness() -> Readiness {
    readiness_of(is_root(), have("wg-quick") || have("wireguard-go"))
}

/// Where `wg-quick` was found, for messages.
pub(crate) fn wg_quick_path() -> Option<String> {
    find("wg-quick")
}

/// Whether the native backend can bring a tunnel up: as root, or — on macOS —
/// through `sudo` when it can ask (zc#380). `can_elevate` is only consulted
/// for [`Readiness::NeedsRoot`].
pub(crate) fn usable(r: Readiness, can_elevate: &dyn Fn() -> bool) -> bool {
    match r {
        Readiness::Ready => true,
        Readiness::NeedsRoot => can_elevate(),
        Readiness::Missing => false,
    }
}

/// `sudo -n true`: cached credentials (or NOPASSWD), no prompt.
fn sudo_cached() -> bool {
    Command::new("sudo")
        .args(["-n", "true"])
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// macOS only: zc can run the tunnel steps through `sudo` — the credentials
/// are cached, or there is a terminal to ask on. Linux keeps requiring root,
/// so a non-root server with Docker still gets the sidecar, never a prompt.
fn can_elevate() -> bool {
    use std::io::IsTerminal;
    cfg!(target_os = "macos")
        && crate::vpn::host_ops_allowed("sudo -n true").is_ok()
        && have("sudo")
        && (sudo_cached() || std::io::stdin().is_terminal())
}

/// Before a tunnel change as a non-root user: prompt for `sudo` once, so the
/// `sudo -n` calls that follow find cached credentials.
fn ensure_elevated(what: &str) -> Result<(), NetError> {
    if is_root() {
        return Ok(());
    }
    crate::vpn::host_ops_allowed("sudo -v")?;
    if sudo_cached() {
        return Ok(());
    }
    eprintln!(
        "  zc needs administrator rights to {what} (WireGuard); sudo will ask for your password"
    );
    let ok = Command::new("sudo")
        .arg("-v")
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if ok {
        Ok(())
    } else {
        Err(NetError::Backend(format!(
            "sudo was refused, so zc could not {what}; re-run with `sudo zc connect`, or start Docker Desktop and use `zc connect --docker`"
        )))
    }
}

/// `program args` with `envs`, as root: directly when zc is root, otherwise
/// through `sudo -n` (credentials cached by [`ensure_elevated`]). `sudo`
/// resets the environment, so `envs` travel through `env`.
fn privileged(program: &str, args: &[&str], envs: &[(&str, String)]) -> Command {
    if is_root() {
        let mut cmd = Command::new(program);
        cmd.args(args);
        for (k, v) in envs {
            cmd.env(k, v);
        }
        cmd
    } else {
        let mut cmd = Command::new("sudo");
        cmd.args(["-n", "env"]);
        for (k, v) in envs {
            cmd.arg(format!("{k}={v}"));
        }
        cmd.arg(program).args(args);
        cmd
    }
}

/// The device name `wg` needs. On macOS wg-quick runs the tunnel as `utunN`
/// and records it in `/var/run/wireguard/zakuro0.name` (root-only); `wg`
/// only knows `<device>.sock` and never reads that file, so `wg show zakuro0`
/// fails there even with the tunnel up (zc#380). Linux: `zakuro0` itself.
fn wg_device() -> String {
    if !cfg!(target_os = "macos") {
        return IFACE.to_string();
    }
    let name_file = format!("/var/run/wireguard/{IFACE}.name");
    privileged("cat", &[&name_file], &[])
        .stdin(std::process::Stdio::null())
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| device_from_name_file(&String::from_utf8_lossy(&o.stdout)))
        .unwrap_or_else(|| IFACE.to_string())
}

/// The `utunN` in a wg-quick `.name` file; `None` for anything else.
fn device_from_name_file(text: &str) -> Option<String> {
    let name = text.trim();
    (name.starts_with("utun") && name[4..].chars().all(|c| c.is_ascii_digit()) && name.len() > 4)
        .then(|| name.to_string())
}

/// `wg show <device> [field]`, as root. `None` when it fails: no tunnel, or no
/// root and no cached sudo.
fn wg_show(field: Option<&str>) -> Option<String> {
    let wg_bin = find("wg").unwrap_or_else(|| "wg".to_string());
    let device = wg_device();
    let mut args = vec!["show", device.as_str()];
    args.extend(field);
    let out = privileged(&wg_bin, &args, &[("PATH", augmented_path())])
        .stdin(std::process::Stdio::null())
        .output()
        .ok()?;
    out.status
        .success()
        .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}

/// `wg show zakuro0 latest-handshakes` for the mesh probe. `None` when it
/// can't be read: no root and no cached sudo.
pub(crate) fn latest_handshakes() -> Option<String> {
    if !is_root() && !sudo_cached() {
        return None;
    }
    wg_show(Some("latest-handshakes"))
}

/// True when `address` (`10.13.13.6/24`) is on a local interface: zc's own
/// `utunN` still carries it. Needs no root, unlike `wg show`.
fn address_is_local(address: &str) -> bool {
    let ip = address.split('/').next().unwrap_or(address);
    crate::vpn::local_mesh().is_some_and(|m| m.ip == ip)
}

/// Write the conf where wg-quick reads it, 0600. As a non-root user the text
/// goes to `sudo sh` on stdin, so the private key never lands in a temp file.
fn install_conf(conf_text: &str) -> Result<(), NetError> {
    if is_root() {
        std::fs::create_dir_all("/etc/wireguard")
            .map_err(|e| NetError::Backend(format!("mkdir /etc/wireguard: {}", e)))?;
        std::fs::write(conf_path(), conf_text)
            .map_err(|e| NetError::Backend(format!("writing conf: {}", e)))?;
        #[cfg(unix)]
        std::fs::set_permissions(conf_path(), std::fs::Permissions::from_mode(0o600))
            .map_err(|e| NetError::Backend(format!("chmod conf: {}", e)))?;
        return Ok(());
    }
    use std::io::Write;
    let script = format!(
        "mkdir -p /etc/wireguard && umask 077 && cat > {}",
        conf_path().display()
    );
    let mut child = privileged("sh", &["-c", &script], &[])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .map_err(|e| NetError::Backend(format!("writing conf via sudo: {}", e)))?;
    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(conf_text.as_bytes())
            .map_err(|e| NetError::Backend(format!("writing conf via sudo: {}", e)))?;
    }
    let out = child
        .wait_with_output()
        .map_err(|e| NetError::Backend(format!("writing conf via sudo: {}", e)))?;
    if out.status.success() {
        Ok(())
    } else {
        Err(NetError::Backend(format!(
            "writing conf via sudo: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        )))
    }
}

fn conf_path() -> std::path::PathBuf {
    // wg-quick uses the filename as the interface name.
    std::path::PathBuf::from("/etc/wireguard").join(format!("{}.conf", IFACE))
}

fn wg_quick(action: &str) -> Result<String, NetError> {
    crate::vpn::host_ops_allowed(&format!("wg-quick {action} {IFACE}"))?;
    let wg_quick_bin = find("wg-quick").unwrap_or_else(|| "wg-quick".to_string());
    // Give wg-quick (and its own lookup of `wireguard-go`) the Homebrew paths, so
    // it works under sudo's restricted PATH.
    let mut envs = vec![("PATH", augmented_path())];
    // macOS has no kernel WireGuard — force the userspace implementation for
    // the wg-quick subprocess only (avoids mutating the process environment).
    if cfg!(target_os = "macos") {
        envs.push((
            "WG_QUICK_USERSPACE_IMPLEMENTATION",
            "wireguard-go".to_string(),
        ));
    }
    let mut cmd = privileged(&wg_quick_bin, &[action, IFACE], &envs);
    cmd.stdin(std::process::Stdio::null());
    crate::vpn::vlog(&format!("run: {} {} {}", wg_quick_bin, action, IFACE));
    let out = cmd
        .output()
        .map_err(|e| NetError::Backend(format!("wg-quick: {}", e)))?;
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    if crate::vpn::verbose() {
        for l in stdout.lines().chain(stderr.lines()) {
            crate::vpn::vlog(&format!("wg-quick {}: {}", action, l));
        }
    }
    if out.status.success() {
        Ok(stdout.to_string())
    } else {
        Err(NetError::Backend(stderr.trim().to_string()))
    }
}

impl Connector for NativeConnector {
    fn available(&self) -> bool {
        usable(readiness(), &can_elevate)
    }

    fn connect(&self, profile: &WgProfile) -> Result<ConnectionInfo, NetError> {
        crate::vpn::host_ops_allowed("native connect")?;
        let conf_text = profile
            .to_conf()
            .map_err(|e| NetError::Backend(format!("invalid profile: {}", e)))?;
        ensure_elevated("bring the mesh tunnel up")?;
        install_conf(&conf_text)?;

        let _ = wg_quick("down"); // idempotent: clear any stale link
        wg_quick("up")?;

        // Verify the tunnel is actually up via `wg show`. On macOS wg-quick
        // maps IFACE to a `utunN` device (there is no `ip` command and no
        // `zakuro0` interface); `wg_device` resolves it. The address is taken
        // from the profile rather than parsing Linux-only `ip -4 addr`.
        crate::vpn::vlog("verifying tunnel via wg show");
        let shown = wg_show(None);
        if crate::vpn::verbose() {
            for l in shown.as_deref().unwrap_or("(wg show failed)").lines() {
                crate::vpn::vlog(&format!("wg show: {}", l));
            }
        }
        let up = shown.is_some();
        if !up {
            return Err(NetError::Backend(
                "tunnel did not come up (run `zc vpn connect --verbose` for details)".into(),
            ));
        }
        let address = profile.interface.address.clone();
        crate::vpn::vlog(&format!("tunnel up: {} address {}", IFACE, address));

        let info = ConnectionInfo {
            backend: Backend::Native,
            address,
            link: IFACE.to_string(),
            peers: read_peers(),
            host_routable: true,
            proxy: None,
            relay: None,
        };
        // Non-fatal: the tunnel is already up. Under `sudo zc connect`, save()
        // re-owns the state dir back to the invoking user; via the sudo steps
        // (zc#380) zc already is that user.
        crate::vpn::state::save_or_warn(&info);
        Ok(info)
    }

    fn status(&self) -> Result<Option<ConnectionInfo>, NetError> {
        if crate::vpn::host_ops_allowed("wg show").is_err() {
            return Ok(None);
        }
        let saved = crate::vpn::state::load();
        // Without root (and no cached sudo) `wg show` can't answer; the
        // recorded address still being on a local interface can (zc#380).
        if saved.as_ref().is_some_and(|s| address_is_local(&s.address)) {
            return Ok(saved);
        }
        if wg_show(None).is_none() {
            return Ok(None);
        }
        // zc's tunnel is up but unrecorded (a connect that failed after
        // `wg-quick up`): adopt it as native, so `connect` doesn't record it as
        // a host tunnel and `disconnect` still takes it down.
        Ok(saved.or_else(|| {
            crate::vpn::local_mesh().map(|m| ConnectionInfo {
                backend: Backend::Native,
                address: format!("{}/24", m.ip),
                link: IFACE.to_string(),
                peers: read_peers(),
                host_routable: true,
                proxy: None,
                relay: None,
            })
        }))
    }

    fn disconnect(&self) -> Result<(), NetError> {
        // Nothing native to take down: don't ask a Docker user for sudo.
        if !is_root() && !conf_path().exists() {
            let _ = crate::vpn::state::clear();
            return Ok(());
        }
        ensure_elevated("bring the mesh tunnel down")?;
        let _ = wg_quick("down");
        // The conf holds this device's private key; it is rewritten on connect.
        if crate::vpn::host_ops_allowed("rm the wg conf").is_ok() {
            let conf = conf_path();
            let _ = privileged("rm", &["-f", &conf.to_string_lossy()], &[])
                .stdin(std::process::Stdio::null())
                .output();
        }
        let _ = crate::vpn::state::clear();
        Ok(())
    }
}

/// Read peers from `wg show zakuro0` on the host. Best-effort.
fn read_peers() -> Vec<PeerStatus> {
    let allowed = wg_show(Some("allowed-ips")).unwrap_or_default();
    let hs = wg_show(Some("latest-handshakes"))
        .map(|text| {
            text.lines()
                .filter_map(|l| l.split_whitespace().nth(1))
                .filter_map(|s| s.parse::<u64>().ok())
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    allowed
        .lines()
        .enumerate()
        .filter_map(|(i, line)| {
            let cidr = line.split_whitespace().nth(1)?;
            let ip = cidr.split('/').next()?.to_string();
            let secs = hs.get(i).copied();
            Some(PeerStatus {
                ip,
                last_handshake_secs: secs.filter(|s| *s > 0),
                reachable: secs.map(|s| s > 0).unwrap_or(false),
            })
        })
        .collect()
}

#[cfg(test)]
mod tests {
    /// Serializes mutation of the mesh-IP env overrides across this module's
    /// tests (`std::env` is process-global), matching the lock pattern used
    /// elsewhere in this crate for the same reason.
    static MESH_IP_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    struct MeshIpEnvGuard {
        _guard: std::sync::MutexGuard<'static, ()>,
        prev_mesh: Option<String>,
        prev_wg: Option<String>,
    }

    impl MeshIpEnvGuard {
        /// Take the lock, then force the mesh-IP overrides to `value`
        /// (`None` clears both). Holding the lock for the whole test is what
        /// keeps the two tests in this module from observing each other's
        /// override — `std::env` is process-global and the test runner is
        /// threaded, so an unlocked reader here races its sibling writer.
        fn set(value: Option<&str>) -> Self {
            let guard = MESH_IP_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
            let prev_mesh = std::env::var("ZAKURO_MESH_IP").ok();
            let prev_wg = std::env::var("ZAKURO_WIREGUARD_IP").ok();
            std::env::remove_var("ZAKURO_WIREGUARD_IP");
            match value {
                Some(v) => std::env::set_var("ZAKURO_MESH_IP", v),
                None => std::env::remove_var("ZAKURO_MESH_IP"),
            }
            Self {
                _guard: guard,
                prev_mesh,
                prev_wg,
            }
        }
    }

    impl Drop for MeshIpEnvGuard {
        fn drop(&mut self) {
            match &self.prev_mesh {
                Some(v) => std::env::set_var("ZAKURO_MESH_IP", v),
                None => std::env::remove_var("ZAKURO_MESH_IP"),
            }
            match &self.prev_wg {
                Some(v) => std::env::set_var("ZAKURO_WIREGUARD_IP", v),
                None => std::env::remove_var("ZAKURO_WIREGUARD_IP"),
            }
        }
    }

    /// Fix A/E: `vpn::native::mesh_ip()` and `discovery::get_mesh_ip()` are the
    /// same detector, so they can never disagree. Before this fix `mesh_ip()`
    /// shelled out to `ip` and then read a sidecar file, honouring neither
    /// override -- so in-container it reported "down" while `/health`'s
    /// `wireguard_connected`, computed from `get_mesh_ip()`, reported connected.
    #[test]
    fn mesh_ip_agrees_with_discovery_get_mesh_ip_under_env_override() {
        let _env = MeshIpEnvGuard::set(Some("10.13.13.42"));
        assert_eq!(
            super::mesh_ip(),
            crate::broker::discovery::get_mesh_ip(),
            "mesh_ip() must be the same detector as discovery::get_mesh_ip()"
        );
        assert_eq!(super::mesh_ip().as_deref(), Some("10.13.13.42"));

        // The contract `mesh_endpoint_for` depends on: a bare IP, never a
        // CIDR and never a URL, so `format!("{ip}:{port}")` is dialable.
        let ip = super::mesh_ip().expect("override always resolves");
        assert!(!ip.contains('/'), "mesh_ip must strip any prefix length");
        assert!(!ip.contains("://"), "mesh_ip must not be a URL");
    }

    /// The same agreement must hold with NO override in play, which is the
    /// container case: both detectors fall through to `getifaddrs`.
    ///
    /// Takes the same lock as the override test — without it this reads
    /// `ZAKURO_MESH_IP` while its sibling is mid-`set_var` and fails
    /// intermittently (observed ~25% of runs).
    #[test]
    fn mesh_ip_agrees_with_discovery_get_mesh_ip_in_the_ambient_environment() {
        let _env = MeshIpEnvGuard::set(None);
        assert_eq!(super::mesh_ip(), crate::broker::discovery::get_mesh_ip());
    }

    /// zc#211: `wg-quick` re-execs itself through `sudo`, so on a host with
    /// passwordless sudo a unit test that reached it brought `zakuro0` down.
    #[test]
    fn wg_quick_is_refused_in_unit_tests() {
        assert!(matches!(
            super::wg_quick("down"),
            Err(crate::vpn::NetError::Refused(_))
        ));
    }

    /// zc#380: `wg` needs the `utunN` wg-quick recorded, not `zakuro0`.
    #[test]
    fn name_file_yields_the_utun_device() {
        use super::device_from_name_file;
        assert_eq!(device_from_name_file("utun7\n").as_deref(), Some("utun7"));
        assert_eq!(device_from_name_file("utun12").as_deref(), Some("utun12"));
        assert_eq!(device_from_name_file(""), None);
        assert_eq!(device_from_name_file("utun"), None);
        assert_eq!(device_from_name_file("utun7; rm -rf x"), None);
    }

    /// zc#380: Homebrew's bash 4+ must shadow macOS's /bin/bash 3.2 for
    /// wg-quick's `#!/usr/bin/env bash`, whatever order the user's PATH has.
    #[test]
    fn homebrew_dirs_precede_the_system_bash() {
        let p = super::augmented_path_from("/usr/bin:/bin:/opt/homebrew/bin");
        let dirs: Vec<_> = p.split(':').collect();
        let brew = dirs.iter().position(|d| *d == "/opt/homebrew/bin").unwrap();
        let system = dirs.iter().position(|d| *d == "/bin").unwrap();
        assert!(brew < system, "{p}");
        assert_eq!(
            super::augmented_path_from(""),
            "/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/local/sbin"
        );
    }

    #[test]
    fn readiness_separates_missing_tools_from_missing_root() {
        use super::{readiness_of, Readiness};
        assert_eq!(readiness_of(false, false), Readiness::Missing);
        assert_eq!(readiness_of(true, false), Readiness::Missing);
        assert_eq!(readiness_of(false, true), Readiness::NeedsRoot);
        assert_eq!(readiness_of(true, true), Readiness::Ready);
    }

    /// zc#380: installed but not root is usable exactly when zc can elevate,
    /// and the elevation probe only runs for that case.
    #[test]
    fn needs_root_is_usable_only_when_sudo_can_be_asked() {
        use super::{usable, Readiness};
        assert!(usable(Readiness::NeedsRoot, &|| true));
        assert!(!usable(Readiness::NeedsRoot, &|| false));
        let never = || -> bool { panic!("probed sudo without needing it") };
        assert!(usable(Readiness::Ready, &never));
        assert!(!usable(Readiness::Missing, &never));
    }

    /// Without root, every privileged step goes through `sudo -n env …`, the
    /// environment included (sudo resets it).
    #[test]
    fn privileged_wraps_in_sudo_when_not_root() {
        if super::is_root() {
            return;
        }
        let cmd = super::privileged("wg-quick", &["up", "zakuro0"], &[("PATH", "/p".into())]);
        assert_eq!(cmd.get_program(), "sudo");
        let args: Vec<_> = cmd
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert_eq!(args, ["-n", "env", "PATH=/p", "wg-quick", "up", "zakuro0"]);
    }

    /// The elevation guard refuses in unit tests, like every other host change.
    #[test]
    fn sudo_is_refused_in_unit_tests() {
        if super::is_root() {
            return;
        }
        assert!(matches!(
            super::ensure_elevated("test"),
            Err(crate::vpn::NetError::Refused(_))
        ));
    }

    /// `connect()` writes `/etc/wireguard/zakuro0.conf` and runs `wg-quick up`;
    /// in a unit test it must refuse before doing either.
    #[test]
    fn native_connect_is_refused_in_unit_tests() {
        use crate::vpn::connector::Connector;
        let profile: crate::vpn::profile::WgProfile = serde_json::from_str(
            r#"{
            "interface": { "private_key": "MKCl4DM7FbX1sFUiFd8VqKzdIGUMwJ28rTgFYezsclc=", "address": "10.13.13.6/24" },
            "peer": { "public_key": "/Lzp+YIUBrNgdABzyR221uhfx2uOWi4m5ZAdgxXzhFs=",
                      "endpoint": "144.202.121.242:51822", "allowed_ips": "10.13.13.0/24",
                      "persistent_keepalive": 25 }
        }"#,
        )
        .expect("sample profile parses");
        assert!(matches!(
            super::NativeConnector.connect(&profile),
            Err(crate::vpn::NetError::Refused(_))
        ));
    }
}