zc2 0.0.53

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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
//! Per-node Ed25519 identity: signs every /peer/* request; verified against the
//! dashboard-synced roster. Zero-trust replacement for the shared ZAKURO_PEER_KEY.

use base64::Engine;
use ring::signature::{self, Ed25519KeyPair, KeyPair};
use std::sync::Mutex;
use std::time::Instant;

const SKEW_SECS: u64 = 30;
const B64: base64::engine::general_purpose::GeneralPurpose =
    base64::engine::general_purpose::STANDARD;

pub struct NodeKey {
    pkcs8: Vec<u8>,
    pair: Ed25519KeyPair,
}

impl NodeKey {
    /// Generate a fresh Ed25519 node keypair.
    pub fn generate() -> NodeKey {
        let rng = ring::rand::SystemRandom::new();
        let doc = Ed25519KeyPair::generate_pkcs8(&rng).expect("pkcs8 gen");
        let pkcs8 = doc.as_ref().to_vec();
        let pair = Ed25519KeyPair::from_pkcs8(&pkcs8).expect("from pkcs8");
        NodeKey { pkcs8, pair }
    }

    /// Reconstruct from persisted PKCS#8 DER bytes.
    pub fn from_pkcs8(der: &[u8]) -> Result<NodeKey, String> {
        let pair = Ed25519KeyPair::from_pkcs8(der).map_err(|e| e.to_string())?;
        Ok(NodeKey {
            pkcs8: der.to_vec(),
            pair,
        })
    }

    pub fn pkcs8_bytes(&self) -> &[u8] {
        &self.pkcs8
    }

    pub fn public_b64(&self) -> String {
        B64.encode(self.pair.public_key().as_ref())
    }

    pub fn sign(&self, msg: &[u8]) -> String {
        B64.encode(self.pair.sign(msg).as_ref())
    }

    /// 16-char lowercase hex fingerprint (first 8 bytes of SHA-256 of the raw public key).
    pub fn fingerprint(&self) -> String {
        use ring::digest::{digest, SHA256};
        let d = digest(&SHA256, self.pair.public_key().as_ref());
        d.as_ref()[..8]
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect()
    }

    /// Key-derived node identity URI.
    pub fn node_uri(&self) -> String {
        format!("zc://node-{}", self.fingerprint())
    }
}

/// Strip an optional `zc://` prefix, then an optional `node-` prefix.
/// Used to reduce a `?node=` filter/target arg down to its fingerprint form.
pub(crate) fn strip_node_arg(arg: &str) -> &str {
    let s = arg.strip_prefix("zc://").unwrap_or(arg);
    s.strip_prefix("node-").unwrap_or(s)
}

/// Same match semantics as [`node_filter_matches`], but against an already-known
/// fingerprint (e.g. a peer's, read off a worker's `node` handle) rather than
/// this process's own [`NodeKey`]. Never falls back to a hostname/label match.
pub(crate) fn fp_matches_node_arg(fp: &str, arg: &str) -> bool {
    strip_node_arg(arg) == fp
}

/// True iff `arg` (optionally `zc://`-prefixed, optionally `node-`-prefixed) reduces,
/// via that stripping, to exactly `key.fingerprint()`. Never falls back to a
/// hostname/label comparison — anything else returns false.
pub fn node_filter_matches(key: &NodeKey, arg: &str) -> bool {
    fp_matches_node_arg(&key.fingerprint(), arg)
}

impl NodeKey {
    /// Load the node key from the state dir, creating it (0600) on first run.
    ///
    /// The directory is `$ZAKURO_HOME`, else `~/.zakuro` — see
    /// [`crate::credentials::dir`] for why a container depends on the former.
    pub fn load_or_create() -> NodeKey {
        Self::load_or_create_in(crate::credentials::dir())
    }

    /// Read and parse `<dir>/node_key`. Returns `None` when the file is
    /// absent or doesn't parse. Never writes.
    pub fn load_in(dir: Option<std::path::PathBuf>) -> Option<NodeKey> {
        let path = dir.map(|d| d.join("node_key"))?;
        let der = std::fs::read(&path).ok()?;
        NodeKey::from_pkcs8(&der).ok()
    }

    /// [`load_in`](Self::load_in) against [`crate::credentials::dir`].
    pub fn load() -> Option<NodeKey> {
        Self::load_in(crate::credentials::dir())
    }

    /// [`load_or_create`](Self::load_or_create) against an explicit directory.
    ///
    /// Exists so the persistence behaviour can be tested without redirecting
    /// `HOME`/`ZAKURO_HOME`: those are process-global, and `envs::update()`
    /// rewrites arbitrary keys from config, so a test that sets them races
    /// every other test that boots a broker.
    pub fn load_or_create_in(dir: Option<std::path::PathBuf>) -> NodeKey {
        if let Some(k) = Self::load_in(dir.clone()) {
            return k;
        }
        let path = dir.map(|d| d.join("node_key"));
        let k = NodeKey::generate();
        if let Some(p) = &path {
            if let Some(dir) = p.parent() {
                let _ = std::fs::create_dir_all(dir);
            }
            if std::fs::write(p, k.pkcs8_bytes()).is_ok() {
                #[cfg(unix)]
                {
                    use std::os::unix::fs::PermissionsExt;
                    let _ = std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o600));
                }
            }
        }
        k
    }

    /// Build the signed (v1) headers for an outbound `/peer/*` request. This is
    /// the format every released build verifies; QUIC offers stay on it.
    pub fn sign_headers(&self, method: &str, path: &str, body: &[u8]) -> Vec<(String, String)> {
        self.sign_headers_v2(method, path, "", body, None)
    }

    /// Dual-signed headers (ZC-0012): the v1 headers exactly as
    /// [`sign_headers`](Self::sign_headers) produces them (0.0.46 receivers
    /// verify those and ignore the rest), plus, when the recipient's
    /// fingerprint `aud` is known, a v2 signature (`X-Node-Sig2`) over
    /// [`canonical_v2`] -- which also binds the query string and the audience --
    /// and `X-Node-Aud`. Same nonce and timestamp for both.
    pub fn sign_headers_v2(
        &self,
        method: &str,
        path: &str,
        query: &str,
        body: &[u8],
        aud: Option<&str>,
    ) -> Vec<(String, String)> {
        let nonce = gen_nonce();
        let ts = now_secs();
        let sig = self.sign(canonical(method, path, body, &nonce, ts).as_bytes());
        let mut out = vec![
            ("X-Node-Id".to_string(), self.public_b64()),
            ("X-Node-Sig".to_string(), sig),
            ("X-Node-Nonce".to_string(), nonce.clone()),
            ("X-Node-Ts".to_string(), ts.to_string()),
        ];
        if let Some(aud) = aud.filter(|a| !a.is_empty()) {
            let sig2 =
                self.sign(canonical_v2(method, path, query, body, &nonce, ts, aud).as_bytes());
            out.push(("X-Node-Sig2".to_string(), sig2));
            out.push(("X-Node-Aud".to_string(), aud.to_string()));
        }
        out
    }
}

/// Fingerprint of a base64-encoded Ed25519 public key: SHA-256 of the decoded
/// raw pubkey bytes, first 8 bytes as lowercase hex. Matches `NodeKey::fingerprint()`
/// for the corresponding key. `None` if `pubkey_b64` doesn't decode.
pub fn fingerprint_of_pubkey_b64(pubkey_b64: &str) -> Option<String> {
    use ring::digest::{digest, SHA256};
    let raw = B64.decode(pubkey_b64).ok()?;
    let d = digest(&SHA256, &raw);
    Some(
        d.as_ref()[..8]
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect(),
    )
}

/// Current unix time in seconds (0 if the clock is before the epoch).
pub fn now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// 128-bit random nonce as lowercase hex.
pub fn gen_nonce() -> String {
    use ring::rand::SecureRandom;
    let mut buf = [0u8; 16];
    ring::rand::SystemRandom::new()
        .fill(&mut buf)
        .expect("rng fill");
    buf.iter().map(|b| format!("{:02x}", b)).collect()
}

/// Which signature format a request was accepted under.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SigVersion {
    V1,
    V2,
}

/// What a receiver adds to the v1 check: its own fingerprint (the audience a
/// v2 signature must name), whether v1-only requests are refused, and the
/// request's query string (v2 signs `path?query`).
#[derive(Debug, Clone, Copy, Default)]
pub struct VerifyCtx<'a> {
    pub query: &'a str,
    /// This node's fingerprint. `None` = audience unknown: v2 headers are
    /// ignored and the v1 signature decides (legacy callers and tests).
    pub self_fp: Option<&'a str>,
    /// Refuse a request that carries only the v1 signature.
    pub require_v2: bool,
}

/// Verify a signed `/peer/*` request under the v1 rules only. Kept for callers
/// that have no receiver identity; the broker uses [`verify_request_ctx`].
#[allow(clippy::too_many_arguments)]
pub fn verify_request(
    is_rostered: &dyn Fn(&str) -> bool,
    guard: &ReplayGuard,
    method: &str,
    path: &str,
    body: &[u8],
    header: &dyn Fn(&str) -> Option<String>,
    now: u64,
) -> Result<String, String> {
    verify_request_ctx(
        is_rostered,
        guard,
        method,
        path,
        body,
        header,
        now,
        &VerifyCtx::default(),
    )
    .map(|(signer, _)| signer)
}

/// Verify a signed `/peer/*` request. `is_rostered` gates the signer pubkey
/// against the synced roster; `header` fetches a request header by name.
/// When the request carries the v2 headers they alone decide (the audience must
/// be this node, the signature covers the query and the audience); a request
/// with only v1 headers is accepted under the v1 rules unless
/// `ctx.require_v2`. Returns the verified signer pubkey (b64) and the format.
#[allow(clippy::too_many_arguments)]
pub fn verify_request_ctx(
    is_rostered: &dyn Fn(&str) -> bool,
    guard: &ReplayGuard,
    method: &str,
    path: &str,
    body: &[u8],
    header: &dyn Fn(&str) -> Option<String>,
    now: u64,
    ctx: &VerifyCtx<'_>,
) -> Result<(String, SigVersion), String> {
    let node_id = header("X-Node-Id").ok_or("missing X-Node-Id")?;
    let sig = header("X-Node-Sig").ok_or("missing X-Node-Sig")?;
    let nonce = header("X-Node-Nonce").ok_or("missing X-Node-Nonce")?;
    let ts: u64 = header("X-Node-Ts")
        .and_then(|s| s.parse().ok())
        .ok_or("missing/invalid X-Node-Ts")?;
    if !is_rostered(&node_id) {
        return Err("node not in roster (or revoked)".into());
    }
    // v2 is only considered when this node knows who it is.
    let v2 = match (ctx.self_fp, header("X-Node-Sig2")) {
        (Some(fp), Some(sig2)) => Some((fp, sig2)),
        _ => None,
    };
    if v2.is_none() && ctx.require_v2 {
        return Err("signature v2 required (X-Node-Sig2 + X-Node-Aud)".into());
    }
    if let Some((fp, sig2)) = v2 {
        let aud = header("X-Node-Aud").unwrap_or_default();
        if aud != fp {
            return Err("signature addressed to another node".into());
        }
        if !guard.fresh(&nonce, ts, now) {
            return Err("stale timestamp or replayed nonce".into());
        }
        let msg = canonical_v2(method, path, ctx.query, body, &nonce, ts, &aud);
        if !verify_sig(&node_id, msg.as_bytes(), &sig2) {
            return Err("bad signature".into());
        }
        return Ok((node_id, SigVersion::V2));
    }
    if !guard.fresh(&nonce, ts, now) {
        return Err("stale timestamp or replayed nonce".into());
    }
    if !verify_sig(
        &node_id,
        canonical(method, path, body, &nonce, ts).as_bytes(),
        &sig,
    ) {
        return Err("bad signature".into());
    }
    Ok((node_id, SigVersion::V1))
}

/// Lowercase hex SHA-256 of a request body.
pub fn sha256_hex(body: &[u8]) -> String {
    let d = ring::digest::digest(&ring::digest::SHA256, body);
    d.as_ref().iter().map(|b| format!("{:02x}", b)).collect()
}

/// Canonical string a node signs for a `/peer/*` request.
pub fn canonical(method: &str, path: &str, body: &[u8], nonce: &str, ts: u64) -> String {
    format!("{method}\n{path}\n{}\n{nonce}\n{ts}", sha256_hex(body))
}

/// Canonical string of the v2 signature: the v1 fields with the query string
/// folded into the path (`path?query` when the query is non-empty) and the
/// recipient's fingerprint appended, so a signature cannot be replayed against
/// another route's query or another node. The `v2` tag keeps the two formats
/// from ever being valid for each other.
pub fn canonical_v2(
    method: &str,
    path: &str,
    query: &str,
    body: &[u8],
    nonce: &str,
    ts: u64,
    aud: &str,
) -> String {
    let target = if query.is_empty() {
        path.to_string()
    } else {
        format!("{path}?{query}")
    };
    format!(
        "v2\n{method}\n{target}\n{}\n{nonce}\n{ts}\n{aud}",
        sha256_hex(body)
    )
}

/// Verify an Ed25519 signature (all b64) over `msg`.
pub fn verify_sig(pubkey_b64: &str, msg: &[u8], sig_b64: &str) -> bool {
    let pk = match B64.decode(pubkey_b64) {
        Ok(v) => v,
        Err(_) => return false,
    };
    let sig = match B64.decode(sig_b64) {
        Ok(v) => v,
        Err(_) => return false,
    };
    let upk = signature::UnparsedPublicKey::new(&signature::ED25519, pk);
    upk.verify(msg, &sig).is_ok()
}

/// Anti-replay: rejects reused nonces and timestamps outside a ±30s window.
///
/// The nonce memory is in-process only, so a restart forgets every nonce; a
/// request captured before the restart could otherwise be replayed inside its
/// skew window. The guard therefore also refuses any timestamp older than the
/// moment it was created (`floor`, this process's start time when built with
/// [`at_boot`](Self::at_boot)). Consequence: a sender whose clock runs behind
/// this node's may be refused for up to the skew window after a restart; it
/// retries with a fresh signature and gets through once its clock passes the
/// floor.
pub struct ReplayGuard {
    seen: Mutex<std::collections::HashMap<String, Instant>>,
    floor: u64,
}

impl Default for ReplayGuard {
    fn default() -> Self {
        Self::new()
    }
}

impl ReplayGuard {
    /// A guard with no start-time floor (tests, tools).
    pub fn new() -> Self {
        Self::with_floor(0)
    }

    /// The production guard: refuses timestamps from before this process began.
    pub fn at_boot() -> Self {
        Self::with_floor(now_secs())
    }

    /// A guard that refuses any timestamp below `floor` (unix secs).
    pub fn with_floor(floor: u64) -> Self {
        ReplayGuard {
            seen: Mutex::new(std::collections::HashMap::new()),
            floor,
        }
    }

    /// True iff `ts` is within ±30s of `now`, not before the floor, AND `nonce`
    /// was not seen before.
    pub fn fresh(&self, nonce: &str, ts: u64, now: u64) -> bool {
        if now.abs_diff(ts) > SKEW_SECS || ts < self.floor {
            return false;
        }
        let mut m = self.seen.lock().unwrap();
        m.retain(|_, t| t.elapsed().as_secs() < 60);
        if m.contains_key(nonce) {
            return false;
        }
        m.insert(nonce.to_string(), Instant::now());
        true
    }
}

#[cfg(test)]
mod fp_tests {
    use super::*;
    #[test]
    fn fingerprint_is_stable_and_unique() {
        let a = NodeKey::generate();
        let der = a.pkcs8_bytes().to_vec();
        let a2 = NodeKey::from_pkcs8(&der).unwrap();
        assert_eq!(a.fingerprint(), a2.fingerprint()); // stable across reload
        assert_eq!(a.fingerprint().len(), 16);
        assert!(a
            .fingerprint()
            .chars()
            .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));
        let b = NodeKey::generate();
        assert_ne!(a.fingerprint(), b.fingerprint()); // unique per key
        assert_eq!(a.node_uri(), format!("zc://node-{}", a.fingerprint()));
    }

    #[test]
    fn node_filter_matches_fingerprint_not_hostname() {
        let key = NodeKey::generate();
        let fp = key.fingerprint();
        assert!(super::node_filter_matches(&key, &format!("zc://node-{fp}")));
        assert!(super::node_filter_matches(&key, &format!("node-{fp}"))); // bare accepted
        assert!(!super::node_filter_matches(&key, "node-lxd")); // hostname rejected
        assert!(!super::node_filter_matches(&key, "zc://node-lxd"));
    }
}

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

    #[test]
    fn sign_verify_roundtrip() {
        let k = NodeKey::generate();
        let msg = b"hello mesh";
        let sig = k.sign(msg);
        assert!(verify_sig(&k.public_b64(), msg, &sig));
        assert!(!verify_sig(&k.public_b64(), b"tampered", &sig));
    }

    #[test]
    fn persist_roundtrip() {
        let k = NodeKey::generate();
        let der = k.pkcs8_bytes().to_vec();
        let k2 = NodeKey::from_pkcs8(&der).unwrap();
        assert_eq!(k.public_b64(), k2.public_b64());
    }

    #[test]
    fn canonical_is_stable() {
        let c = canonical("POST", "/peer/tasks/offer", b"{}", "abc", 1000);
        assert_eq!(
            c,
            "POST\n/peer/tasks/offer\n44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a\nabc\n1000"
        );
    }

    /// Was written against `HOME`; now drives the directory directly. The key
    /// facts here -- same identity on reload, and 0600 on the file -- are
    /// properties of the persistence, not of how the path was resolved, and
    /// resolving it from the environment only made the test racy. Precedence
    /// is covered purely by `zakuro_home_outranks_home_and_empty_does_not_count`.
    #[test]
    fn load_or_create_persists() {
        let tmp =
            std::env::temp_dir().join(format!("zc-nodekey-{}-{}", std::process::id(), line!()));
        std::fs::create_dir_all(&tmp).unwrap();

        let k1 = NodeKey::load_or_create_in(Some(tmp.clone()));
        let k2 = NodeKey::load_or_create_in(Some(tmp.clone()));
        assert_eq!(k1.public_b64(), k2.public_b64());
        // file exists and is 0600
        let p = tmp.join("node_key");
        assert!(p.exists());
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&p).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o600);
        }

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

    /// A containerised broker has no durable `$HOME`. Keeping the identity on
    /// a mounted volume is how it survives a restart -- and for weeks it did
    /// not, because `credentials::dir()` read only `HOME`, so the volume
    /// stayed empty and every restart registered a brand-new node.
    ///
    /// Deliberately drives `load_or_create_in` with explicit paths rather than
    /// redirecting `ZAKURO_HOME`. An earlier version of this test set the
    /// variable and failed on CI: `envs::update()` rewrites arbitrary keys
    /// from config, so a concurrent test that boots a broker can move it
    /// mid-assertion. Locking cannot fix that, because those writers do not
    /// take the lock.
    #[test]
    fn a_mounted_volume_keeps_a_node_identity_across_restarts() {
        let base = std::env::temp_dir().join(format!(
            "zc-nodekey-volume-{}-{}",
            std::process::id(),
            line!()
        ));
        let mounted = base.join("volume"); // stands in for the PVC
        std::fs::create_dir_all(&mounted).unwrap();

        let k1 = NodeKey::load_or_create_in(Some(mounted.clone()));
        assert!(
            mounted.join("node_key").exists(),
            "key must land on the volume"
        );

        // Restart with the volume still attached: same identity.
        let k2 = NodeKey::load_or_create_in(Some(mounted.clone()));
        assert_eq!(k1.public_b64(), k2.public_b64());

        // A different (empty) directory is a different node -- which is
        // exactly what an unmounted volume produced on every restart.
        let elsewhere = base.join("ephemeral");
        std::fs::create_dir_all(&elsewhere).unwrap();
        let k3 = NodeKey::load_or_create_in(Some(elsewhere));
        assert_ne!(k1.public_b64(), k3.public_b64());

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

    /// `load_in` is read-only: an empty directory yields `None` and creates
    /// no file, while a key written by `load_or_create_in` comes back with
    /// the same fingerprint (mesh-routes Task 1 override).
    #[test]
    fn load_in_never_creates_and_matches_load_or_create_in() {
        let dir = std::env::temp_dir().join(format!(
            "zc-nodekey-loadin-{}-{}",
            std::process::id(),
            line!()
        ));
        std::fs::create_dir_all(&dir).unwrap();

        assert!(NodeKey::load_in(Some(dir.clone())).is_none());
        assert!(
            !dir.join("node_key").exists(),
            "load_in must never create node_key"
        );

        let created = NodeKey::load_or_create_in(Some(dir.clone()));
        let loaded = NodeKey::load_in(Some(dir.clone())).expect("key now exists");
        assert_eq!(created.fingerprint(), loaded.fingerprint());

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

    /// The precedence rule, with no environment mutation anywhere.
    #[test]
    fn zakuro_home_outranks_home_and_empty_does_not_count() {
        use crate::credentials::dir_from;
        use std::ffi::OsString;
        let v = |s: &str| Some(OsString::from(s));

        // A container points ZAKURO_HOME at its mounted volume.
        assert_eq!(
            dir_from(v("/var/lib/zakuro"), v("/root")),
            Some(std::path::PathBuf::from("/var/lib/zakuro"))
        );
        // Unset falls back to $HOME/.zakuro -- every non-container install.
        assert_eq!(
            dir_from(None, v("/root")),
            Some(std::path::PathBuf::from("/root/.zakuro"))
        );
        // Empty is not a directory. Treating it as one would resolve the node
        // key to a bare "node_key" in the process CWD.
        assert_eq!(
            dir_from(v(""), v("/root")),
            Some(std::path::PathBuf::from("/root/.zakuro"))
        );
        // Neither set: no state dir, and the caller must cope rather than
        // silently write somewhere arbitrary.
        assert_eq!(dir_from(None, None), None);
    }

    #[test]
    fn sign_headers_verify_request_roundtrip() {
        let k = NodeKey::generate();
        let body = br#"{"fn":"greet"}"#;
        let hdrs = k.sign_headers("POST", "/peer/tasks/offer", body);
        let get = |name: &str| -> Option<String> {
            hdrs.iter().find(|(h, _)| h == name).map(|(_, v)| v.clone())
        };
        let guard = ReplayGuard::new();
        let signer = k.public_b64();
        let rostered = |id: &str| id == signer;
        let now = now_secs();
        // happy path returns the signer pubkey
        let got = verify_request(
            &rostered,
            &guard,
            "POST",
            "/peer/tasks/offer",
            body,
            &get,
            now,
        )
        .unwrap();
        assert_eq!(got, signer);

        // unknown roster id → reject (fresh guard to avoid replay masking)
        let g2 = ReplayGuard::new();
        assert!(verify_request(
            &|_| false,
            &g2,
            "POST",
            "/peer/tasks/offer",
            body,
            &get,
            now
        )
        .is_err());

        // tampered body → bad signature
        let g3 = ReplayGuard::new();
        assert!(verify_request(
            &rostered,
            &g3,
            "POST",
            "/peer/tasks/offer",
            b"{}",
            &get,
            now
        )
        .is_err());

        // replay (same guard, same nonce) → reject
        assert!(verify_request(
            &rostered,
            &guard,
            "POST",
            "/peer/tasks/offer",
            body,
            &get,
            now
        )
        .is_err());
    }

    #[test]
    fn nonce_is_random_and_hex() {
        let a = gen_nonce();
        let b = gen_nonce();
        assert_eq!(a.len(), 32);
        assert_ne!(a, b);
        assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
    }

    fn hdr_fn(h: &[(String, String)]) -> impl Fn(&str) -> Option<String> + '_ {
        move |name: &str| h.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone())
    }

    fn ctx<'a>(query: &'a str, fp: &'a str, require_v2: bool) -> VerifyCtx<'a> {
        VerifyCtx {
            query,
            self_fp: Some(fp),
            require_v2,
        }
    }

    /// A v2-signed GET carries the query string in its signature: altering the
    /// query after signing fails, the same query passes.
    #[test]
    fn v2_signature_covers_the_query_string() {
        let k = NodeKey::generate();
        let recipient = NodeKey::generate();
        let fp = recipient.fingerprint();
        let h = k.sign_headers_v2("GET", "/peer/balance", "user_id=alice", b"", Some(&fp));
        let signer = k.public_b64();
        let rostered = |id: &str| id == signer;
        let now = now_secs();
        let get = hdr_fn(&h);

        let altered = verify_request_ctx(
            &rostered,
            &ReplayGuard::new(),
            "GET",
            "/peer/balance",
            b"",
            &get,
            now,
            &ctx("user_id=mallory", &fp, false),
        );
        assert!(altered.is_err(), "query altered after signing must fail");

        let ok = verify_request_ctx(
            &rostered,
            &ReplayGuard::new(),
            "GET",
            "/peer/balance",
            b"",
            &get,
            now,
            &ctx("user_id=alice", &fp, false),
        )
        .unwrap();
        assert_eq!(ok, (signer.clone(), SigVersion::V2));

        // v1 headers alone say nothing about the query: it is exactly the gap v2 closes.
        assert!(verify_request(
            &rostered,
            &ReplayGuard::new(),
            "GET",
            "/peer/balance",
            b"",
            &get,
            now
        )
        .is_ok());
    }

    /// A signature addressed to node X is refused by node Y.
    #[test]
    fn v2_signature_addressed_to_another_node_is_refused() {
        let k = NodeKey::generate();
        let x = NodeKey::generate();
        let y = NodeKey::generate();
        let h = k.sign_headers_v2("POST", "/peer/reserve", "", b"{}", Some(&x.fingerprint()));
        let signer = k.public_b64();
        let rostered = |id: &str| id == signer;
        let get = hdr_fn(&h);
        let now = now_secs();
        let at_y = verify_request_ctx(
            &rostered,
            &ReplayGuard::new(),
            "POST",
            "/peer/reserve",
            b"{}",
            &get,
            now,
            &ctx("", &y.fingerprint(), false),
        );
        assert!(at_y.unwrap_err().contains("another node"));
        let at_x = verify_request_ctx(
            &rostered,
            &ReplayGuard::new(),
            "POST",
            "/peer/reserve",
            b"{}",
            &get,
            now,
            &ctx("", &x.fingerprint(), false),
        );
        assert_eq!(at_x.unwrap().1, SigVersion::V2);
    }

    /// Re-pointing the audience header at the verifier does not help: the
    /// signature covers the audience.
    #[test]
    fn v2_audience_header_is_signed() {
        let k = NodeKey::generate();
        let x = NodeKey::generate();
        let y = NodeKey::generate();
        let mut h = k.sign_headers_v2("POST", "/peer/reserve", "", b"{}", Some(&x.fingerprint()));
        for (name, v) in h.iter_mut() {
            if name == "X-Node-Aud" {
                *v = y.fingerprint();
            }
        }
        let signer = k.public_b64();
        let get = hdr_fn(&h);
        let r = verify_request_ctx(
            &|id: &str| id == signer,
            &ReplayGuard::new(),
            "POST",
            "/peer/reserve",
            b"{}",
            &get,
            now_secs(),
            &ctx("", &y.fingerprint(), false),
        );
        assert_eq!(r.unwrap_err(), "bad signature");
    }

    /// v1-only passes by default (and is reported as V1); the require flag refuses it.
    /// The v1 headers of a dual-signed request are byte-for-byte what 0.0.46 sends.
    #[test]
    fn v1_only_passes_by_default_and_fails_when_v2_is_required() {
        let k = NodeKey::generate();
        let me = NodeKey::generate();
        let fp = me.fingerprint();
        let h = k.sign_headers("POST", "/peer/earn", b"{}");
        assert!(h
            .iter()
            .all(|(n, _)| n != "X-Node-Sig2" && n != "X-Node-Aud"));
        let signer = k.public_b64();
        let rostered = |id: &str| id == signer;
        let get = hdr_fn(&h);
        let now = now_secs();
        let ok = verify_request_ctx(
            &rostered,
            &ReplayGuard::new(),
            "POST",
            "/peer/earn",
            b"{}",
            &get,
            now,
            &ctx("", &fp, false),
        )
        .unwrap();
        assert_eq!(ok.1, SigVersion::V1);
        let refused = verify_request_ctx(
            &rostered,
            &ReplayGuard::new(),
            "POST",
            "/peer/earn",
            b"{}",
            &get,
            now,
            &ctx("", &fp, true),
        );
        assert!(refused.unwrap_err().contains("v2 required"));

        // A dual-signed request's v1 half is the v1 signature of the same nonce/ts.
        let dual = k.sign_headers_v2("POST", "/peer/earn", "", b"{}", Some(&fp));
        let d = hdr_fn(&dual);
        assert!(verify_request(
            &rostered,
            &ReplayGuard::new(),
            "POST",
            "/peer/earn",
            b"{}",
            &d,
            now
        )
        .is_ok());
        assert_eq!(
            d("X-Node-Nonce"),
            dual.iter()
                .find(|(n, _)| n == "X-Node-Nonce")
                .map(|(_, v)| v.clone())
        );
    }

    /// The restart floor: a request stamped before this process began is
    /// refused even though it is inside the skew window and its nonce is unseen.
    #[test]
    fn a_pre_boot_timestamp_is_refused() {
        let g = ReplayGuard::with_floor(1000);
        assert!(!g.fresh("pre", 990, 1000), "ts before boot floor");
        assert!(g.fresh("post", 1000, 1000), "ts at the floor is fine");
        assert!(g.fresh("later", 1005, 1005));
        // end to end through verify_request
        let k = NodeKey::generate();
        let h = k.sign_headers("GET", "/peer/peers", b"");
        let signer = k.public_b64();
        let get = hdr_fn(&h);
        let now = now_secs();
        let booted_after = ReplayGuard::with_floor(now + 5);
        assert!(verify_request(
            &|id: &str| id == signer,
            &booted_after,
            "GET",
            "/peer/peers",
            b"",
            &get,
            now
        )
        .is_err());
    }

    #[test]
    fn replay_and_skew() {
        let g = ReplayGuard::new();
        assert!(g.fresh("n1", 1000, 1010)); // 10s skew ok, first use
        assert!(!g.fresh("n1", 1000, 1010)); // replay
        assert!(!g.fresh("n2", 1000, 1040)); // 40s skew rejected
        assert!(!g.fresh("n3", 1040, 1000)); // future skew rejected
    }
}