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
//! WireGuard profile: dashboard JSON ⇄ wg-quick conf text.

use crate::vpn::NetError;
use serde::Deserialize;
use std::time::Duration;

#[derive(Clone, Deserialize)]
pub struct WgInterface {
    pub private_key: String,
    pub address: String,
}

impl std::fmt::Debug for WgInterface {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WgInterface")
            .field("private_key", &"<redacted>")
            .field("address", &self.address)
            .finish()
    }
}

#[derive(Clone, Deserialize)]
pub struct WgPeer {
    pub public_key: String,
    #[serde(default)]
    pub preshared_key: Option<String>,
    pub endpoint: String,
    pub allowed_ips: String,
    #[serde(default)]
    pub persistent_keepalive: Option<u32>,
}

impl std::fmt::Debug for WgPeer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WgPeer")
            .field("public_key", &self.public_key)
            .field(
                "preshared_key",
                &self.preshared_key.as_ref().map(|_| "<redacted>"),
            )
            .field("endpoint", &self.endpoint)
            .field("allowed_ips", &self.allowed_ips)
            .field("persistent_keepalive", &self.persistent_keepalive)
            .finish()
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct WgProfile {
    pub interface: WgInterface,
    pub peer: WgPeer,
    #[serde(default)]
    pub mesh_subnet: Option<String>,
    /// The node fingerprint the hub named this profile's peer after
    /// (mesh-routes §0). `Some` only when the hub echoed the `X-Zakuro-Node`
    /// zc sent, so a per-device identity is never claimed for a legacy
    /// per-user profile.
    #[serde(default)]
    pub node: Option<String>,
}

impl WgProfile {
    /// Render to canonical wg-quick configuration text.
    ///
    /// Every field that ends up in the conf is validated first: values are
    /// rejected if they contain a newline/CR or have leading/trailing
    /// whitespace (config-injection guard), and each field must match its
    /// expected shape (44-char base64 keys, CIDR addresses, host:port
    /// endpoint). Any violation returns `NetError::Profile`.
    pub fn to_conf(&self) -> Result<String, NetError> {
        validate_key("PrivateKey", &self.interface.private_key)?;
        validate_cidr("Address", &self.interface.address)?;
        validate_key("PublicKey", &self.peer.public_key)?;
        if let Some(psk) = &self.peer.preshared_key {
            validate_key("PresharedKey", psk)?;
        }
        validate_cidr("AllowedIPs", &self.peer.allowed_ips)?;
        validate_endpoint(&self.peer.endpoint)?;
        // persistent_keepalive is a u32, so it can never inject; no check needed.

        let mut s = String::new();
        s.push_str("[Interface]\n");
        s.push_str(&format!("PrivateKey = {}\n", self.interface.private_key));
        s.push_str(&format!("Address = {}\n", self.interface.address));
        // MTU is load-bearing, not tuning. wg-quick's default (1420 for a 1500
        // underlay) is too large whenever the path to the endpoint is itself
        // encapsulated or otherwise under 1500, and the failure is silent and
        // deeply confusing: small responses pass, large ones vanish. Measured
        // on the live mesh, /health (small) answered in 22ms while /workers
        // (large) hung for 30s on four of five brokers, which read as "the
        // fleet is down" rather than "packets over ~1300 bytes are dropped".
        // 1280 is the IPv6 minimum MTU -- every path must carry it, so it is
        // the one value that cannot black-hole. Override with ZAKURO_WG_MTU.
        s.push_str(&format!("MTU = {}\n", mtu()));
        s.push('\n');
        s.push_str("[Peer]\n");
        s.push_str(&format!("PublicKey = {}\n", self.peer.public_key));
        if let Some(psk) = &self.peer.preshared_key {
            s.push_str(&format!("PresharedKey = {}\n", psk));
        }
        s.push_str(&format!("AllowedIPs = {}\n", self.peer.allowed_ips));
        if let Some(k) = self.peer.persistent_keepalive {
            s.push_str(&format!("PersistentKeepalive = {}\n", k));
        }
        s.push_str(&format!("Endpoint = {}\n", self.peer.endpoint));
        Ok(s)
    }

    /// The mesh subnet to advertise, preferring the explicit field and
    /// falling back to the peer's AllowedIPs.
    pub fn mesh_subnet(&self) -> &str {
        self.mesh_subnet
            .as_deref()
            .unwrap_or(&self.peer.allowed_ips)
    }
}

/// Reject control characters and surrounding whitespace that could smuggle
/// extra wg-quick directives onto a config line.
fn validate_no_ctrl(label: &str, v: &str) -> Result<(), NetError> {
    if v.contains('\n') || v.contains('\r') {
        return Err(NetError::Profile(format!(
            "{}: value contains a line break",
            label
        )));
    }
    if v.trim() != v {
        return Err(NetError::Profile(format!(
            "{}: value has leading/trailing whitespace",
            label
        )));
    }
    if v.is_empty() {
        return Err(NetError::Profile(format!("{}: empty value", label)));
    }
    Ok(())
}

/// WireGuard keys (private/public/preshared) are 32-byte values rendered as
/// standard base64: 43 chars + a single `=` pad = 44 chars total.
fn validate_key(label: &str, v: &str) -> Result<(), NetError> {
    validate_no_ctrl(label, v)?;
    let ok = v.len() == 44
        && v.ends_with('=')
        && v[..43]
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/');
    if !ok {
        return Err(NetError::Profile(format!(
            "{}: not a 44-char base64 WireGuard key",
            label
        )));
    }
    Ok(())
}

/// Validate a CIDR like `10.13.13.6/24` (IPv4 or IPv6) — an IP plus a numeric
/// prefix length. Parsed with the std library, no extra deps.
/// WireGuard MTU to write into the generated conf.
///
/// 1280 (the IPv6 minimum) rather than wg-quick's 1420 default: any path that
/// works at all must carry 1280, so this value cannot black-hole. A too-large
/// MTU fails silently and asymmetrically -- small requests succeed, large ones
/// disappear -- which is far harder to diagnose than the few bytes of overhead
/// this costs.
fn mtu() -> u32 {
    std::env::var("ZAKURO_WG_MTU")
        .ok()
        .and_then(|v| v.trim().parse::<u32>().ok())
        .filter(|m| (576..=1500).contains(m))
        .unwrap_or(1280)
}

fn validate_cidr(label: &str, v: &str) -> Result<(), NetError> {
    validate_no_ctrl(label, v)?;
    let (ip, prefix) = v
        .split_once('/')
        .ok_or_else(|| NetError::Profile(format!("{}: missing /prefix in CIDR", label)))?;
    let addr: std::net::IpAddr = ip
        .parse()
        .map_err(|_| NetError::Profile(format!("{}: invalid IP in CIDR", label)))?;
    let bits: u8 = prefix
        .parse()
        .map_err(|_| NetError::Profile(format!("{}: invalid prefix length", label)))?;
    let max = if addr.is_ipv4() { 32 } else { 128 };
    if bits > max {
        return Err(NetError::Profile(format!(
            "{}: prefix length out of range",
            label
        )));
    }
    Ok(())
}

/// Validate `host:port` — host is an IP or a DNS name, port is 1..=65535.
fn validate_endpoint(v: &str) -> Result<(), NetError> {
    validate_no_ctrl("Endpoint", v)?;
    let (host, port) = v
        .rsplit_once(':')
        .ok_or_else(|| NetError::Profile("Endpoint: missing :port".to_string()))?;
    if host.is_empty() {
        return Err(NetError::Profile("Endpoint: empty host".to_string()));
    }
    let p: u16 = port
        .parse()
        .map_err(|_| NetError::Profile("Endpoint: invalid port".to_string()))?;
    if p == 0 {
        return Err(NetError::Profile(
            "Endpoint: port must be 1..=65535".to_string(),
        ));
    }
    // Host: accept a bare IP (incl. bracketed IPv6) or a DNS hostname made of
    // [A-Za-z0-9.-]; this excludes spaces and config-control characters.
    let host_inner = host.trim_start_matches('[').trim_end_matches(']');
    let valid_host = host_inner.parse::<std::net::IpAddr>().is_ok()
        || host_inner
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-');
    if !valid_host || host_inner.is_empty() {
        return Err(NetError::Profile("Endpoint: invalid host".to_string()));
    }
    Ok(())
}

/// The header that carries this device's node fingerprint to the hub
/// (mesh-routes §0).
pub const NODE_HEADER: &str = "X-Zakuro-Node";

/// Fetch this node's WireGuard profile.
///
/// Order:
///   1. `ZAKURO_WG_PROFILE_FILE` — a local JSON file (test/dev escape hatch).
///   2. Dashboard: `GET {ZAKURO_API_URL}/api/broker/config/wireguard` with
///      `X-Broker-Api-Key: $ZAKURO_API_KEY` and, when this device already has
///      a node key, its fingerprint in `X-Zakuro-Node` (see
///      [`fetch_from_hub`]).
pub fn fetch_wg_profile() -> Result<WgProfile, NetError> {
    // Local file override (test/dev escape hatch) — honored ONLY with an
    // explicit opt-in so a release broker can't be pointed at an
    // attacker-controlled WireGuard profile via env alone (audit M4).
    let allow_file = std::env::var("ZAKURO_ALLOW_FILE_PROFILE")
        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
        .unwrap_or(false);
    if allow_file {
        if let Ok(path) = std::env::var("ZAKURO_WG_PROFILE_FILE") {
            if !path.trim().is_empty() {
                let body = std::fs::read_to_string(&path)
                    .map_err(|e| NetError::Fetch(format!("reading {}: {}", path, e)))?;
                return serde_json::from_str(&body).map_err(|e| NetError::Profile(e.to_string()));
            }
        }
    }

    let api_key = match std::env::var("ZAKURO_API_KEY") {
        Ok(k) if !k.trim().is_empty() => k,
        _ => return Err(NetError::NoApiKey),
    };
    // Through the shared resolver, not a second hard-coded default: this one
    // had drifted to my.zakuro-ai.com (NXDOMAIN) and, unlike the rest of zc,
    // ignored ZAKURO_ENV entirely -- so `ZAKURO_ENV=staging zc` would fetch a
    // WireGuard profile from production while every other command used staging.
    let api_url = crate::credentials::default_api_url();
    let node = device_fingerprint();
    if node.is_none() {
        eprintln!(
            "⚠ no node key yet: this device shares your account's mesh identity until the agent or `zc login` creates ~/.zakuro/node_key"
        );
    }
    fetch_from_hub(&api_url, &api_key, node.as_deref())
}

/// The hub half of [`fetch_wg_profile`]. `node`, when `Some`, goes in
/// [`NODE_HEADER`]: a hub with per-device peers provisions `zc-{uid}-{node}`
/// for this device and echoes `node` back, while an older hub (or a `None`
/// request) ignores/omits the header, answers the shared per-user profile and
/// echoes nothing. The echo is kept only when it equals the fingerprint sent.
pub(crate) fn fetch_from_hub(
    api_url: &str,
    api_key: &str,
    node: Option<&str>,
) -> Result<WgProfile, NetError> {
    let endpoint = format!(
        "{}/api/broker/config/wireguard",
        api_url.trim_end_matches('/')
    );
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_connect(Some(Duration::from_secs(10)))
            .timeout_recv_response(Some(Duration::from_secs(10)))
            .http_status_as_error(false)
            .build(),
    );
    let mut req = agent.get(&endpoint).header("X-Broker-Api-Key", api_key);
    if let Some(n) = node {
        req = req.header(NODE_HEADER, n);
    }
    let resp = req.call().map_err(|e| NetError::Fetch(e.to_string()))?;

    // Defensive: with http_status_as_error(false), non-2xx returns Ok(resp), so
    // we handle the status manually here.
    if resp.status().as_u16() != 200 {
        let status = resp.status();
        let body = resp
            .into_body()
            .read_to_string()
            .unwrap_or_else(|_| "<no body>".into());
        return Err(NetError::Fetch(format!("status {}: {}", status, body)));
    }
    let body = resp
        .into_body()
        .read_to_string()
        .map_err(|e| NetError::Fetch(e.to_string()))?;
    let mut profile: WgProfile =
        serde_json::from_str(&body).map_err(|e| NetError::Profile(e.to_string()))?;
    profile.node = profile.node.filter(|echoed| Some(echoed.as_str()) == node);
    Ok(profile)
}

/// This device's node-key fingerprint against an explicit directory: 16
/// lowercase hex characters, the first 8 bytes of SHA-256 of its Ed25519
/// public key ([`NodeKey::fingerprint`](crate::broker::node_identity::NodeKey::fingerprint)).
/// `None` when no `node_key` file exists there yet — this never creates one.
pub(crate) fn device_fingerprint_in(dir: Option<std::path::PathBuf>) -> Option<String> {
    crate::broker::node_identity::NodeKey::load_in(dir).map(|k| k.fingerprint())
}

/// This device's node-key fingerprint, or `None` if the agent or `zc login`
/// hasn't created `~/.zakuro/node_key` (or `$ZAKURO_HOME/node_key`) yet.
/// It's the node identity the broker registers with the hub:
/// `node_sync::register_node` sends the public key, and the roster and
/// `zc://node-<fp>` use this fingerprint of it. Read-only: never creates a
/// key (mesh-routes Task 1 override).
pub fn device_fingerprint() -> Option<String> {
    device_fingerprint_in(crate::credentials::dir())
}

#[cfg(test)]
mod tests {
    /// The MTU is the difference between "the mesh works" and "large responses
    /// silently vanish". Measured live: at wg-quick's 1420 default, four of five
    /// brokers hung for 30s on a large response while answering /health in 22ms.
    #[test]
    fn conf_pins_a_safe_mtu() {
        let p: WgProfile = serde_json::from_str(SAMPLE).expect("parse");
        let conf = p.to_conf().expect("valid profile");
        assert!(
            conf.contains("MTU = 1280"),
            "conf must pin an MTU that no path can black-hole:\n{conf}"
        );
        // It belongs to [Interface]; wg-quick ignores it under [Peer].
        let iface = conf.split("[Peer]").next().unwrap();
        assert!(
            iface.contains("MTU ="),
            "MTU must be in [Interface]:\n{conf}"
        );
    }

    #[test]
    fn mtu_is_overridable_within_sane_bounds() {
        // Out-of-range and garbage values fall back rather than producing a
        // conf that cannot carry a packet.
        for bad in ["0", "99", "9000", "abc", ""] {
            std::env::set_var("ZAKURO_WG_MTU", bad);
            assert_eq!(
                super::mtu(),
                1280,
                "{bad:?} should fall back to the default"
            );
        }
        std::env::set_var("ZAKURO_WG_MTU", "1400");
        assert_eq!(super::mtu(), 1400);
        std::env::remove_var("ZAKURO_WG_MTU");
    }

    use super::*;

    const SAMPLE: &str = r#"{
        "interface": { "private_key": "MKCl4DM7FbX1sFUiFd8VqKzdIGUMwJ28rTgFYezsclc=", "address": "10.13.13.6/24" },
        "peer": {
            "public_key": "/Lzp+YIUBrNgdABzyR221uhfx2uOWi4m5ZAdgxXzhFs=",
            "preshared_key": "dZBQTKaxfPxmAidvugeQ0yNUfG25k8aqJ/q2xFNSPC0=",
            "endpoint": "144.202.121.242:51822",
            "allowed_ips": "10.13.13.0/24",
            "persistent_keepalive": 25
        },
        "mesh_subnet": "10.99.0.0/16"
    }"#;

    #[test]
    fn parses_and_renders_conf() {
        let p: WgProfile = serde_json::from_str(SAMPLE).expect("parse");
        let conf = p.to_conf().expect("render");
        assert!(conf.contains("[Interface]"));
        assert!(conf.contains("PrivateKey = MKCl4DM7FbX1sFUiFd8VqKzdIGUMwJ28rTgFYezsclc="));
        assert!(conf.contains("Address = 10.13.13.6/24"));
        assert!(conf.contains("[Peer]"));
        assert!(conf.contains("PublicKey = /Lzp+YIUBrNgdABzyR221uhfx2uOWi4m5ZAdgxXzhFs="));
        assert!(conf.contains("PresharedKey = dZBQTKaxfPxmAidvugeQ0yNUfG25k8aqJ/q2xFNSPC0="));
        assert!(conf.contains("AllowedIPs = 10.13.13.0/24"));
        assert!(conf.contains("PersistentKeepalive = 25"));
        assert!(conf.contains("Endpoint = 144.202.121.242:51822"));
        assert_eq!(p.mesh_subnet(), "10.99.0.0/16");
    }

    #[test]
    fn mesh_subnet_falls_back_to_allowed_ips() {
        let json = 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"}}"#;
        let p: WgProfile = serde_json::from_str(json).unwrap();
        assert_eq!(p.mesh_subnet(), "10.13.13.0/24");
        let conf = p.to_conf().expect("render");
        assert!(!conf.contains("PresharedKey")); // omitted when absent
        assert!(!conf.contains("PersistentKeepalive")); // omitted when absent
    }

    // ---- C6: profile-field validation ----

    fn base_profile() -> WgProfile {
        serde_json::from_str(SAMPLE).expect("parse sample")
    }

    #[test]
    fn valid_profile_renders_ok() {
        let conf = base_profile()
            .to_conf()
            .expect("valid profile should render");
        assert!(conf.contains("Endpoint = 144.202.121.242:51822"));
    }

    #[test]
    fn rejects_newline_injection_in_private_key() {
        let mut p = base_profile();
        // Attacker-controlled value smuggling an extra config directive.
        p.interface.private_key =
            "MKCl4DM7FbX1sFUiFd8VqKzdIGUMwJ28rTgFYezsclc=\nPostUp = curl evil".into();
        match p.to_conf() {
            Err(NetError::Profile(_)) => {}
            other => panic!("expected Profile error, got {:?}", other),
        }
    }

    #[test]
    fn rejects_cr_injection_in_endpoint() {
        let mut p = base_profile();
        p.peer.endpoint = "144.202.121.242:51822\rPostUp = id".into();
        assert!(matches!(p.to_conf(), Err(NetError::Profile(_))));
    }

    #[test]
    fn rejects_leading_whitespace_in_address() {
        let mut p = base_profile();
        p.interface.address = " 10.13.13.6/24".into();
        assert!(matches!(p.to_conf(), Err(NetError::Profile(_))));
    }

    #[test]
    fn rejects_non_base64_key() {
        let mut p = base_profile();
        p.peer.public_key = "not-a-valid-44-char-base64-key".into();
        assert!(matches!(p.to_conf(), Err(NetError::Profile(_))));
    }

    #[test]
    fn rejects_address_without_cidr() {
        let mut p = base_profile();
        p.interface.address = "10.13.13.6".into(); // missing /prefix
        assert!(matches!(p.to_conf(), Err(NetError::Profile(_))));
    }

    #[test]
    fn rejects_endpoint_without_port() {
        let mut p = base_profile();
        p.peer.endpoint = "144.202.121.242".into();
        assert!(matches!(p.to_conf(), Err(NetError::Profile(_))));
    }

    #[test]
    fn rejects_bad_preshared_key() {
        let mut p = base_profile();
        p.peer.preshared_key = Some("short".into());
        assert!(matches!(p.to_conf(), Err(NetError::Profile(_))));
    }

    #[test]
    fn fetch_profile_sources() {
        // Scenario 1: file override wins.
        let dir = std::env::temp_dir().join(format!("zc-vpn-prof-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("wg.json");
        std::fs::write(&path, SAMPLE).unwrap();

        // Scenario 1: file override wins ONLY with the explicit opt-in.
        std::env::set_var("ZAKURO_ALLOW_FILE_PROFILE", "1");
        std::env::set_var("ZAKURO_WG_PROFILE_FILE", &path);
        let p = super::fetch_wg_profile().expect("fetch from file");
        assert_eq!(p.interface.address, "10.13.13.6/24");

        // Scenario 1b: without the opt-in, the file path is IGNORED (falls
        // through to the API path → NoApiKey since no key is set).
        std::env::remove_var("ZAKURO_ALLOW_FILE_PROFILE");
        std::env::remove_var("ZAKURO_API_KEY");
        match super::fetch_wg_profile() {
            Err(crate::vpn::NetError::NoApiKey) => {}
            other => panic!(
                "file profile must be ignored without opt-in, got {:?}",
                other
            ),
        }

        // Scenario 2: no file + no key => NoApiKey.
        std::env::remove_var("ZAKURO_WG_PROFILE_FILE");
        std::env::remove_var("ZAKURO_API_KEY");
        match super::fetch_wg_profile() {
            Err(crate::vpn::NetError::NoApiKey) => {}
            other => panic!("expected NoApiKey, got {:?}", other),
        }

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn debug_redacts_secrets() {
        let p: WgProfile = serde_json::from_str(SAMPLE).unwrap();
        let dbg = format!("{:?}", p);
        assert!(
            !dbg.contains("MKCl4DM7FbX1sFUiFd8VqKzdIGUMwJ28rTgFYezsclc="),
            "private key leaked: {}",
            dbg
        );
        assert!(
            !dbg.contains("dZBQTKaxfPxmAidvugeQ0yNUfG25k8aqJ/q2xFNSPC0="),
            "preshared key leaked: {}",
            dbg
        );
        assert!(dbg.contains("<redacted>"));
    }

    /// A one-shot fake hub: answers one request with `body` and hands back the
    /// raw request it received.
    fn fake_hub(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
        use std::io::{Read, Write};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let mut req = Vec::new();
            let mut buf = [0u8; 1024];
            while !req.windows(4).any(|w| w == b"\r\n\r\n") {
                match stream.read(&mut buf) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => req.extend_from_slice(&buf[..n]),
                }
            }
            let _ = tx.send(String::from_utf8_lossy(&req).into_owned());
            let reply = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len()
            );
            let _ = stream.write_all(reply.as_bytes());
        });
        (url, rx)
    }

    const FP: &str = "0123456789abcdef";

    /// A profile as a hub with per-device peers answers it: `node` echoes the
    /// fingerprint the peer was named after.
    const PER_DEVICE: &str = r#"{
        "interface": { "private_key": "MKCl4DM7FbX1sFUiFd8VqKzdIGUMwJ28rTgFYezsclc=", "address": "10.13.13.31/24" },
        "peer": { "public_key": "/Lzp+YIUBrNgdABzyR221uhfx2uOWi4m5ZAdgxXzhFs=",
                  "endpoint": "144.202.121.242:51822", "allowed_ips": "10.13.13.0/24" },
        "node": "0123456789abcdef"
    }"#;

    #[test]
    fn fetch_sends_this_devices_node_fingerprint() {
        let (url, seen) = fake_hub(SAMPLE);
        super::fetch_from_hub(&url, "zk_test_key", Some(FP)).expect("profile");
        let req = seen.recv().unwrap().to_ascii_lowercase();
        assert!(
            req.starts_with("get /api/broker/config/wireguard "),
            "{req}"
        );
        assert!(req.contains("x-broker-api-key: zk_test_key\r\n"), "{req}");
        assert!(req.contains("x-zakuro-node: 0123456789abcdef\r\n"), "{req}");
    }

    #[test]
    fn a_hub_that_echoes_the_fingerprint_marks_the_profile_per_device() {
        let (url, _seen) = fake_hub(PER_DEVICE);
        let p = super::fetch_from_hub(&url, "zk_test_key", Some(FP)).unwrap();
        assert_eq!(p.node.as_deref(), Some(FP));
        assert_eq!(p.interface.address, "10.13.13.31/24");
    }

    #[test]
    fn a_legacy_or_mismatched_answer_is_not_per_device() {
        let (url, _seen) = fake_hub(SAMPLE); // an older hub: no `node` at all
        assert_eq!(
            super::fetch_from_hub(&url, "zk_test_key", Some(FP))
                .unwrap()
                .node,
            None
        );
        let (url, _seen) = fake_hub(PER_DEVICE);
        assert_eq!(
            super::fetch_from_hub(&url, "zk_test_key", Some("fedcba9876543210"))
                .unwrap()
                .node,
            None,
            "an echo of another fingerprint is not this device's identity"
        );
    }

    #[test]
    fn fetch_without_a_node_key_sends_no_header_and_keeps_no_echo() {
        let (url, seen) = fake_hub(PER_DEVICE); // even a hub that WOULD echo a node
        let p = super::fetch_from_hub(&url, "zk_test_key", None).unwrap();
        let req = seen.recv().unwrap().to_ascii_lowercase();
        assert!(
            !req.contains("x-zakuro-node"),
            "no fingerprint to send: {req}"
        );
        assert_eq!(
            p.node, None,
            "an echo can't be claimed as this device's identity when none was sent"
        );
    }

    #[test]
    fn device_fingerprint_in_reads_only_never_creates() {
        let dir =
            std::env::temp_dir().join(format!("zc-vpn-fp-{}-{}", std::process::id(), line!()));
        std::fs::create_dir_all(&dir).unwrap();

        assert_eq!(super::device_fingerprint_in(Some(dir.clone())), None);
        assert!(
            !dir.join("node_key").exists(),
            "device_fingerprint_in must never create a node_key"
        );

        let k = crate::broker::node_identity::NodeKey::load_or_create_in(Some(dir.clone()));
        assert_eq!(
            super::device_fingerprint_in(Some(dir.clone())),
            Some(k.fingerprint())
        );

        let _ = std::fs::remove_dir_all(&dir);
    }
}