zc2 0.0.45

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
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
//! Dashboard round-trips for the zero-trust mesh: register this node's signing
//! pubkey, pull the authorized-node roster + the dashboard's voucher-signing
//! pubkey, and obtain a signed job voucher before dispatch.
//!
//! Contract (dashboard side, `zak-dashboard`):
//!   POST /api/broker/node/register  {node_pubkey, mesh_endpoint?, deploy_runtime?, hub_allocation?, presence?}
//!                                                        (X-Broker-Api-Key: zk_…)
//!   GET  /api/broker/node/roster    → [{node_pubkey, revoked}]
//!   GET  /api/broker/mesh/owner-ips → {ips, complete}   (zc#212)
//!   GET  /api/broker/voucher/pubkey → {pubkey, pubkeys?}
//!   POST /api/broker/voucher        {budget_credits}     → {signed_json, sig}

use std::time::Duration;

fn base(api_url: &str) -> &str {
    api_url.trim_end_matches('/')
}

/// Build the JSON payload for `register_node`. Omits an optional key entirely
/// when its value is `None` — absent means "unchanged" server-side, so a
/// tunnel flap must not send an explicit `null` that would clear a
/// previously-stored address, and a caller that cannot answer whether this
/// host runs containers must not overwrite what the hub already recorded.
/// Split out from `register_node` so this contract has direct test coverage.
///
/// `deploy_runtime` is sent explicitly when known, `false` included: a host
/// whose container runtime stopped working is exactly the case the field
/// exists for, and omitting it there would leave the hub advertising the node
/// as still able to host deployments.
#[cfg(test)]
fn register_payload(
    node_pubkey: &str,
    mesh_endpoint: Option<&str>,
    runtime: Option<&crate::broker::deploy::RuntimeProbe>,
    hub_allocation: Option<&crate::hub_allocation::HubAllocation>,
) -> String {
    register_payload_with(node_pubkey, mesh_endpoint, runtime, hub_allocation, None)
}

/// The node's key fingerprint, as `presence.node_key_fp`: the first 8 bytes
/// of SHA-256 of the raw 32-byte Ed25519 public key, as 16 lowercase hex
/// characters -- `NodeKey::fingerprint()`, the `<fp>` of `zc://node-<fp>` and
/// the `node` claim of a `zakuro://` link (ZC-0020). The hub recomputes it
/// from `node_pubkey` and drops a presence whose fingerprint differs. `None`
/// when `node_pubkey` is not standard base64.
pub fn node_key_fp(node_pubkey_b64: &str) -> Option<String> {
    use base64::Engine;
    let raw = base64::engine::general_purpose::STANDARD
        .decode(node_pubkey_b64.trim())
        .ok()?;
    let d = ring::digest::digest(&ring::digest::SHA256, &raw);
    Some(hex::encode(&d.as_ref()[..8]))
}

/// `presence` (ADR ZC-0019 §6): who is running on this node, so the hub can
/// show "Desktop connected" and target `zakuro://` actions at it.
///
/// ```json
/// {"node_key_fp": "<16 hex>", "agent_version": "0.0.44",
///  "app_version": "0.3.1" | null, "app": "desktop" | null,
///  "os": "macos" | "linux", "arch": "aarch64" | "x86_64" | ...}
/// ```
///
/// `app`/`app_version` come from `<zc dir>/agent/app.json`, which the
/// desktop app writes (docs/agent-api.md, "The app file"); both are `null`
/// when it is absent, unreadable, or names a pid that is gone.
pub fn presence(
    node_pubkey_b64: &str,
    agent_dir: Option<&std::path::Path>,
) -> Option<serde_json::Value> {
    let fp = node_key_fp(node_pubkey_b64)?;
    #[cfg(unix)]
    let app = agent_dir
        .and_then(|d| crate::agent::files::running_app(d, crate::agent::supervisor::is_alive));
    // No agent (and so no desktop app beside it) on other platforms yet.
    #[cfg(not(unix))]
    let app: Option<(String, String)> = agent_dir.and(None);
    let (app, app_version) = match app {
        Some((a, v)) => (Some(a), Some(v)),
        None => (None, None),
    };
    Some(serde_json::json!({
        "node_key_fp": fp,
        "agent_version": env!("CARGO_PKG_VERSION"),
        "app_version": app_version,
        "app": app,
        "os": std::env::consts::OS,
        "arch": std::env::consts::ARCH,
    }))
}

fn register_payload_with(
    node_pubkey: &str,
    mesh_endpoint: Option<&str>,
    runtime: Option<&crate::broker::deploy::RuntimeProbe>,
    hub_allocation: Option<&crate::hub_allocation::HubAllocation>,
    presence: Option<serde_json::Value>,
) -> String {
    let mut body = serde_json::Map::new();
    body.insert("node_pubkey".to_string(), node_pubkey.into());
    if let Some(ep) = mesh_endpoint {
        body.insert("mesh_endpoint".to_string(), ep.into());
    }
    if let Some(probe) = runtime {
        // Bool kept for hubs that predate the detail object (zc#473).
        body.insert("deploy_runtime".to_string(), probe.available.into());
        body.insert("deploy_runtime_detail".to_string(), probe.to_json());
    }
    // Which zc this node is running, so the hub — and the marketplace listing
    // built on it — can say so without probing the mesh itself. The hub is
    // the only place that sees every node, including ones this broker has no
    // route to, so version skew is only fully visible from there.
    if let Ok(v) = serde_json::to_value(crate::build_id::current()) {
        body.insert("zc_build".to_string(), v);
    }
    // Lent capacity (zc#472). Omitted when never configured; `enabled: false`
    // is sent so `--disable` reaches the hub.
    if let Some(a) = hub_allocation {
        body.insert("hub_allocation".to_string(), a.to_payload());
    }
    // Presence (ADR ZC-0019 §6). Optional and additive: a hub that predates
    // it ignores the key.
    if let Some(p) = presence {
        body.insert("presence".to_string(), p);
    }
    serde_json::Value::Object(body).to_string()
}

/// Register this node's Ed25519 public key with the dashboard (idempotent).
///
/// `deploy_runtime` reports whether this host can run a deployment at all
/// (`deploy::runtime_available`). The hub decides broker eligibility from it:
/// without it a live broker with no usable container runtime is offered as a
/// deployment host and everything placed there sits `pending` forever. `None`
/// leaves whatever the hub already recorded untouched.
pub fn register_node(
    api_url: &str,
    api_key: &str,
    node_pubkey: &str,
    mesh_endpoint: Option<&str>,
    runtime: Option<&crate::broker::deploy::RuntimeProbe>,
) -> Result<(), String> {
    let endpoint = format!("{}/api/broker/node/register", base(api_url));
    let state_dir = crate::credentials::dir();
    let hub_allocation = state_dir.as_deref().and_then(crate::hub_allocation::load);
    let agent_dir = state_dir.as_deref().map(|d| d.join("agent"));
    let payload = register_payload_with(
        node_pubkey,
        mesh_endpoint,
        runtime,
        hub_allocation.as_ref(),
        presence(node_pubkey, agent_dir.as_deref()),
    );
    let resp = ureq::post(&endpoint)
        .config()
        .timeout_global(Some(Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", api_key)
        .header("Content-Type", "application/json")
        .send(payload.as_str())
        .map_err(|e| e.to_string())?;
    let code = resp.status().as_u16();
    if (200..300).contains(&code) {
        // The hub's account-level placement default rides on the register
        // response (zc#474), as does a Hub-side change to the lent-capacity
        // opt-in (zc#472). An unreadable body is the same as neither.
        let body = resp.into_body().read_to_string().unwrap_or_default();
        apply_register_response(&body);
        if let Some(dir) = state_dir.as_deref() {
            crate::hub_allocation::apply_register_response(dir, &body);
        }
        Ok(())
    } else {
        Err(format!("register_node HTTP {code}"))
    }
}

/// Read `default_placement` from a register response and install it as the
/// broker's hub default. Null or absent clears it; an unknown value logs a
/// warning and clears it too.
pub fn apply_register_response(body: &str) {
    crate::broker::placement::set_hub_default(parse_default_placement(body));
}

fn parse_default_placement(body: &str) -> Option<crate::broker::placement::Placement> {
    let v: serde_json::Value = serde_json::from_str(body).ok()?;
    match v.get("default_placement")? {
        serde_json::Value::Null => None,
        serde_json::Value::String(s) => match crate::broker::placement::Placement::parse(s) {
            Ok(p) => Some(p),
            Err(e) => {
                eprintln!("warning: hub default_placement ignored: {e}");
                None
            }
        },
        other => {
            eprintln!("warning: hub default_placement ignored: not a string: {other}");
            None
        }
    }
}

/// Parse a roster response body: `[{"node_pubkey": "...", "revoked": bool}, …]`
/// → `(pubkey, revoked)` pairs. Unknown/malformed entries are skipped.
pub fn parse_roster(body: &str) -> Vec<(String, bool)> {
    let v: serde_json::Value = match serde_json::from_str(body) {
        Ok(v) => v,
        Err(_) => return Vec::new(),
    };
    v.as_array()
        .map(|arr| {
            arr.iter()
                .filter_map(|e| {
                    let pk = e.get("node_pubkey")?.as_str()?.to_string();
                    let revoked = e.get("revoked").and_then(|r| r.as_bool()).unwrap_or(false);
                    Some((pk, revoked))
                })
                .collect()
        })
        .unwrap_or_default()
}

/// Parse `mesh_endpoint`s from a roster body → `(pubkey, "ip:port")` pairs.
/// Entries with a null or absent endpoint are skipped: they are authorized
/// nodes with no tunnel up, which is normal, not malformed.
pub fn parse_endpoints(body: &str) -> Vec<(String, String)> {
    let v: serde_json::Value = match serde_json::from_str(body) {
        Ok(v) => v,
        Err(_) => return Vec::new(),
    };
    v.as_array()
        .map(|arr| {
            arr.iter()
                .filter_map(|e| {
                    let pk = e.get("node_pubkey")?.as_str()?.to_string();
                    let ep = e.get("mesh_endpoint")?.as_str()?.to_string();
                    Some((pk, ep))
                })
                .collect()
        })
        .unwrap_or_default()
}

/// Request the roster and read the response body (shared by `fetch_roster`
/// and `fetch_roster_full` so the HTTP round-trip is implemented once).
fn fetch_roster_body(api_url: &str, api_key: &str) -> Result<String, String> {
    let endpoint = format!("{}/api/broker/node/roster", base(api_url));
    let resp = ureq::get(&endpoint)
        .config()
        .timeout_global(Some(Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", api_key)
        .call()
        .map_err(|e| e.to_string())?;
    if resp.status().as_u16() != 200 {
        return Err(format!("fetch_roster HTTP {}", resp.status().as_u16()));
    }
    resp.into_body().read_to_string().map_err(|e| e.to_string())
}

/// Fetch the authorized-node roster from the dashboard.
pub fn fetch_roster(api_url: &str, api_key: &str) -> Result<Vec<(String, bool)>, String> {
    Ok(parse_roster(&fetch_roster_body(api_url, api_key)?))
}

/// `(pubkey_b64, revoked)` authorization pairs, as `parse_roster` returns them.
pub type RosterEntries = Vec<(String, bool)>;

/// `(pubkey_b64, "ip:port")` mesh endpoints, as `parse_endpoints` returns them.
pub type RosterEndpoints = Vec<(String, String)>;

/// Fetch the roster once and return both authorization pairs and endpoints.
///
/// `fetch_roster` reads and discards the body, so a caller that also wants
/// endpoints would have to poll again. This is the tick-loop path, polled by
/// every broker, so it stays one request.
pub fn fetch_roster_full(
    api_url: &str,
    api_key: &str,
) -> Result<(RosterEntries, RosterEndpoints), String> {
    let body = fetch_roster_body(api_url, api_key)?;
    Ok((parse_roster(&body), parse_endpoints(&body)))
}

/// The mesh addresses that belong to the calling broker's owner, as the hub
/// reports them on `GET /api/broker/mesh/owner-ips` (zc#212): the owner's own
/// broker nodes plus their VPN peer. `complete` is false when the hub could
/// not look the VPN peer up; `ips` then holds the broker nodes only.
#[derive(Debug, Clone, PartialEq)]
pub struct OwnerMeshIps {
    pub ips: Vec<std::net::IpAddr>,
    pub complete: bool,
}

/// Parse `{"ips": ["10.13.13.22", …], "complete": bool}`. Entries that are not
/// IP addresses are skipped, and a missing `complete` reads as false. A body
/// without an `ips` array is `None`, never "the owner has no addresses",
/// which would lock the owner out of their own environments.
pub fn parse_owner_ips(body: &str) -> Option<OwnerMeshIps> {
    let v: serde_json::Value = serde_json::from_str(body).ok()?;
    let ips = v
        .get("ips")?
        .as_array()?
        .iter()
        .filter_map(|ip| ip.as_str()?.parse().ok())
        .collect();
    let complete = v.get("complete").and_then(|c| c.as_bool()).unwrap_or(false);
    Some(OwnerMeshIps { ips, complete })
}

/// `GET {api_url}/api/broker/mesh/owner-ips` for the owner of `api_key`.
pub fn fetch_owner_ips(api_url: &str, api_key: &str) -> Result<OwnerMeshIps, String> {
    let endpoint = format!("{}/api/broker/mesh/owner-ips", base(api_url));
    let resp = ureq::get(&endpoint)
        .config()
        .timeout_global(Some(Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", api_key)
        .call()
        .map_err(|e| e.to_string())?;
    let code = resp.status().as_u16();
    if code != 200 {
        return Err(format!("fetch_owner_ips HTTP {code}"));
    }
    let body = resp
        .into_body()
        .read_to_string()
        .map_err(|e| e.to_string())?;
    parse_owner_ips(&body).ok_or_else(|| "fetch_owner_ips: unexpected response body".to_string())
}

/// Parse the voucher-pubkey response into the acceptable key set. Prefers
/// `pubkeys` (current first, then previous keys still honoured) when present
/// and non-empty; falls back to the legacy single `pubkey`. Duplicates dropped.
pub fn parse_voucher_pubkeys(body: &str) -> Result<Vec<String>, String> {
    let v: serde_json::Value = serde_json::from_str(body).map_err(|e| e.to_string())?;
    let mut keys: Vec<String> = Vec::new();
    if let Some(arr) = v.get("pubkeys").and_then(|p| p.as_array()) {
        for k in arr.iter().filter_map(|k| k.as_str()) {
            if !k.is_empty() && !keys.iter().any(|e| e == k) {
                keys.push(k.to_string());
            }
        }
    }
    if keys.is_empty() {
        if let Some(k) = v
            .get("pubkey")
            .and_then(|p| p.as_str())
            .filter(|k| !k.is_empty())
        {
            keys.push(k.to_string());
        }
    }
    if keys.is_empty() {
        return Err("voucher pubkey response missing `pubkey`/`pubkeys`".into());
    }
    Ok(keys)
}

/// Fetch the dashboard's acceptable voucher-signing public keys (b64).
pub fn fetch_voucher_pubkey(api_url: &str) -> Result<Vec<String>, String> {
    let endpoint = format!("{}/api/broker/voucher/pubkey", base(api_url));
    let resp = ureq::get(&endpoint)
        .config()
        .timeout_global(Some(Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .call()
        .map_err(|e| e.to_string())?;
    if resp.status().as_u16() != 200 {
        return Err(format!(
            "fetch_voucher_pubkey HTTP {}",
            resp.status().as_u16()
        ));
    }
    let text = resp
        .into_body()
        .read_to_string()
        .map_err(|e| e.to_string())?;
    parse_voucher_pubkeys(&text)
}

/// Obtain a dashboard-signed job voucher. Returns `(signed_json, sig)` — the
/// exact bytes the dashboard signed plus its signature (see `voucher.rs`).
pub fn obtain_voucher(
    api_url: &str,
    api_key: &str,
    budget_credits: f64,
) -> Result<(String, String), String> {
    let endpoint = format!("{}/api/broker/voucher", base(api_url));
    let payload = serde_json::json!({ "budget_credits": budget_credits }).to_string();
    let resp = ureq::post(&endpoint)
        .config()
        .timeout_global(Some(Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", api_key)
        .header("Content-Type", "application/json")
        .send(payload.as_str())
        .map_err(|e| e.to_string())?;
    if resp.status().as_u16() != 200 {
        return Err(format!("obtain_voucher HTTP {}", resp.status().as_u16()));
    }
    let text = resp
        .into_body()
        .read_to_string()
        .map_err(|e| e.to_string())?;
    let v: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
    let signed_json = v
        .get("signed_json")
        .and_then(|s| s.as_str())
        .ok_or("voucher response missing `signed_json`")?
        .to_string();
    let sig = v
        .get("sig")
        .and_then(|s| s.as_str())
        .ok_or("voucher response missing `sig`")?
        .to_string();
    Ok((signed_json, sig))
}

/// Redeem a voucher's nonce at the dashboard (double-spend guard). Returns
/// `Ok(true)` on first redemption, `Ok(false)` if already spent. Best-effort:
/// the caller logs failures and continues (settlement rides the existing path).
pub fn redeem_voucher(
    api_url: &str,
    api_key: &str,
    task_nonce: &str,
    actual_cost: f64,
) -> Result<bool, String> {
    let endpoint = format!("{}/api/broker/voucher/redeem", base(api_url));
    let payload =
        serde_json::json!({ "task_nonce": task_nonce, "actual_cost": actual_cost }).to_string();
    let resp = ureq::post(&endpoint)
        .config()
        .timeout_global(Some(Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", api_key)
        .header("Content-Type", "application/json")
        .send(payload.as_str())
        .map_err(|e| e.to_string())?;
    if resp.status().as_u16() != 200 {
        return Err(format!("redeem_voucher HTTP {}", resp.status().as_u16()));
    }
    let text = resp
        .into_body()
        .read_to_string()
        .map_err(|e| e.to_string())?;
    let v: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
    Ok(v.get("redeemed").and_then(|r| r.as_bool()).unwrap_or(false))
}

#[cfg(test)]
mod tests {
    #[test]
    fn register_response_default_placement_cases() {
        use crate::broker::placement::{resolve, Placement};
        // The hub default is process-global: exercise every case in one test.
        apply_register_response(r#"{"default_placement":"best_price_mesh"}"#);
        assert_eq!(resolve(None), (Placement::BestPriceMesh, "hub_default"));
        // A request-level policy still wins.
        assert_eq!(resolve(Some(Placement::MeshOnly)).0, Placement::MeshOnly);
        apply_register_response(r#"{"default_placement":"mesh_only"}"#);
        assert_eq!(resolve(None).0, Placement::MeshOnly);
        apply_register_response(r#"{"default_placement":null}"#);
        assert_eq!(resolve(None), (Placement::OwnFirst, "default"));
        apply_register_response(r#"{"default_placement":"own_first"}"#);
        assert_eq!(resolve(None), (Placement::OwnFirst, "hub_default"));
        apply_register_response(r#"{"ok":true}"#);
        assert_eq!(resolve(None), (Placement::OwnFirst, "default"));
        apply_register_response(r#"{"default_placement":"mesh_only"}"#);
        apply_register_response(r#"{"default_placement":"cheapest"}"#);
        assert_eq!(resolve(None), (Placement::OwnFirst, "default"));
        apply_register_response("not json");
        assert_eq!(resolve(None), (Placement::OwnFirst, "default"));
    }

    use super::*;

    /// Presence (ADR ZC-0019 §6) rides on the register payload.
    #[cfg(unix)]
    #[test]
    fn register_payload_carries_presence_when_given_and_omits_it_otherwise() {
        let none: serde_json::Value =
            serde_json::from_str(&super::register_payload("PUBKEY", None, None, None)).unwrap();
        assert!(none.get("presence").is_none());

        let key = crate::broker::node_identity::NodeKey::generate();
        let pk = key.public_b64();
        let p = super::presence(&pk, None).unwrap();
        assert_eq!(
            p["node_key_fp"].as_str(),
            Some(key.fingerprint().as_str()),
            "the node's own fingerprint, as in zc://node-<fp>"
        );
        assert_eq!(p["agent_version"], env!("CARGO_PKG_VERSION"));
        assert_eq!(p["os"], std::env::consts::OS);
        assert_eq!(p["arch"], std::env::consts::ARCH);
        assert!(p["app"].is_null() && p["app_version"].is_null());
        assert!(super::presence("not base64!", None).is_none());

        let d = std::env::temp_dir().join(format!("zc-presence-{}", std::process::id()));
        std::fs::create_dir_all(&d).unwrap();
        std::fs::write(
            d.join(crate::agent::files::APP_FILE),
            r#"{"v":1,"app":"desktop","app_version":"0.3.1"}"#,
        )
        .unwrap();
        let p = super::presence(&pk, Some(&d)).unwrap();
        assert_eq!(
            (p["app"].as_str(), p["app_version"].as_str()),
            (Some("desktop"), Some("0.3.1"))
        );
        let _ = std::fs::remove_dir_all(&d);

        let body: serde_json::Value = serde_json::from_str(&super::register_payload_with(
            &pk,
            None,
            None,
            None,
            Some(p.clone()),
        ))
        .unwrap();
        assert_eq!(body["presence"], p);
        assert_eq!(body["node_pubkey"], pk.as_str());
    }

    /// The hub is the only vantage point that sees every node, so the build
    /// has to reach it — `/health` only tells you about nodes you can already
    /// route to.
    #[test]
    fn register_payload_reports_which_zc_this_node_runs() {
        let payload = super::register_payload("PUBKEY", None, None, None);
        let v: serde_json::Value = serde_json::from_str(&payload).unwrap();
        let build = &v["zc_build"];
        assert!(build.is_object(), "zc_build must be sent: {payload}");
        assert_eq!(
            build["version"],
            serde_json::Value::String(crate::build_id::current().version.clone()),
            "and must be THIS binary's version"
        );
    }

    #[test]
    fn register_payload_omits_mesh_endpoint_key_when_none() {
        let payload = super::register_payload("PUBKEY", None, None, None);
        let v: serde_json::Value = serde_json::from_str(&payload).unwrap();
        assert_eq!(v["node_pubkey"], "PUBKEY");
        assert!(
            v.get("mesh_endpoint").is_none(),
            "mesh_endpoint key must be absent, not null: {payload}"
        );
        assert!(
            !payload.contains("mesh_endpoint"),
            "payload must not mention mesh_endpoint at all: {payload}"
        );
    }

    #[test]
    fn register_payload_includes_exact_mesh_endpoint_when_some() {
        let payload = super::register_payload("PUBKEY", Some("10.13.13.6:9000"), None, None);
        let v: serde_json::Value = serde_json::from_str(&payload).unwrap();
        assert_eq!(v["node_pubkey"], "PUBKEY");
        assert_eq!(v["mesh_endpoint"], "10.13.13.6:9000");
    }

    fn ok_probe() -> crate::broker::deploy::RuntimeProbe {
        use crate::broker::deploy::runtime::*;
        classify_probe(
            CliOutcome::Exited {
                success: true,
                stderr: String::new(),
            },
            &HostFacts {
                socket_path: "/var/run/docker.sock".into(),
                socket_exists: true,
                containerd_socket: false,
            },
            "2026-10-20T00:00:00Z".into(),
        )
    }

    fn denied_probe() -> crate::broker::deploy::RuntimeProbe {
        use crate::broker::deploy::runtime::*;
        classify_probe(
            CliOutcome::Exited {
                success: false,
                stderr: "permission denied while trying to connect to the Docker daemon socket"
                    .into(),
            },
            &HostFacts {
                socket_path: "/var/run/docker.sock".into(),
                socket_exists: true,
                containerd_socket: false,
            },
            "2026-10-20T00:00:00Z".into(),
        )
    }

    #[test]
    fn register_payload_reports_a_usable_deploy_runtime() {
        let payload =
            super::register_payload("PUBKEY", Some("10.13.13.6:9000"), Some(&ok_probe()), None);
        let v: serde_json::Value = serde_json::from_str(&payload).unwrap();
        assert_eq!(v["node_pubkey"], "PUBKEY");
        assert_eq!(v["mesh_endpoint"], "10.13.13.6:9000");
        assert_eq!(v["deploy_runtime"], true);
        assert_eq!(v["deploy_runtime_detail"]["available"], true);
        assert_eq!(v["deploy_runtime_detail"]["runtime"], "docker");
        assert!(v["deploy_runtime_detail"]["error"].is_null());
    }

    #[test]
    fn register_payload_reports_a_missing_deploy_runtime_as_explicit_false() {
        // The case the field exists for: a live broker with no docker must
        // say so, not stay silent and keep being offered as a deploy host.
        let payload = super::register_payload("PUBKEY", None, Some(&denied_probe()), None);
        let v: serde_json::Value = serde_json::from_str(&payload).unwrap();
        assert_eq!(
            v.get("deploy_runtime"),
            Some(&serde_json::Value::Bool(false)),
            "deploy_runtime=false must be sent explicitly: {payload}"
        );
        let d = &v["deploy_runtime_detail"];
        assert_eq!(d["available"], false);
        assert_eq!(d["error"], "permission_denied");
        assert!(d["detail"]
            .as_str()
            .unwrap()
            .contains("/var/run/docker.sock"));
        assert!(d["checked_at"].as_str().is_some());
    }

    #[test]
    fn register_payload_omits_deploy_runtime_when_unknown() {
        // Absent means "unchanged" server-side, same rule `mesh_endpoint`
        // follows — an unknown value must not clear a stored one.
        let payload = super::register_payload("PUBKEY", None, None, None);
        assert!(
            !payload.contains("deploy_runtime"),
            "payload must not mention deploy_runtime at all: {payload}"
        );
    }

    #[test]
    fn parse_roster_reads_pairs_and_defaults_revoked() {
        let body = r#"[
            {"node_pubkey":"AAA","revoked":true},
            {"node_pubkey":"BBB"},
            {"nope":1}
        ]"#;
        let r = parse_roster(body);
        assert_eq!(r.len(), 2);
        assert_eq!(r[0], ("AAA".to_string(), true));
        assert_eq!(r[1], ("BBB".to_string(), false));
    }

    #[test]
    fn parse_roster_handles_garbage() {
        assert!(parse_roster("not json").is_empty());
        assert!(parse_roster("{}").is_empty());
    }

    #[test]
    fn parses_endpoints_skipping_absent_and_null() {
        let body = r#"[
            {"node_pubkey":"A","revoked":false,"mesh_endpoint":"10.13.13.6:9000"},
            {"node_pubkey":"B","revoked":false,"mesh_endpoint":null},
            {"node_pubkey":"C","revoked":false}
        ]"#;
        assert_eq!(
            super::parse_endpoints(body),
            vec![("A".to_string(), "10.13.13.6:9000".to_string())]
        );
    }

    #[test]
    fn parse_roster_still_reads_bodies_without_endpoints() {
        // An older dashboard omits the field entirely; authorization must
        // keep working.
        let body = r#"[{"node_pubkey":"A","revoked":false}]"#;
        assert_eq!(super::parse_roster(body), vec![("A".to_string(), false)]);
        assert!(super::parse_endpoints(body).is_empty());
    }

    #[test]
    fn parse_owner_ips_reads_addresses_and_completeness() {
        let got =
            parse_owner_ips(r#"{"ips":["10.13.13.22","10.13.13.5"],"complete":true}"#).unwrap();
        let want: Vec<std::net::IpAddr> = vec![
            "10.13.13.22".parse().unwrap(),
            "10.13.13.5".parse().unwrap(),
        ];
        assert_eq!(got.ips, want);
        assert!(got.complete);
    }

    #[test]
    fn parse_owner_ips_skips_entries_that_are_not_addresses() {
        let got = parse_owner_ips(r#"{"ips":["10.13.13.22","zakuro0",7,null],"complete":false}"#)
            .unwrap();
        assert_eq!(got.ips.len(), 1);
        assert!(!got.complete);
    }

    #[test]
    fn parse_owner_ips_reads_a_missing_complete_as_incomplete() {
        assert!(!parse_owner_ips(r#"{"ips":[]}"#).unwrap().complete);
    }

    #[test]
    fn parse_owner_ips_rejects_bodies_without_an_ips_array() {
        for body in ["not json", "{}", r#"{"ips":"10.13.13.22"}"#, "[]"] {
            assert_eq!(parse_owner_ips(body), None, "{body}");
        }
    }

    use std::io::{Read, Write};
    use std::net::TcpListener;

    /// Minimal mock: serve a fixed JSON body for one request, capture the request line.
    fn mock_once(status: u16, body: &'static str) -> (std::thread::JoinHandle<String>, u16) {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        let h = std::thread::spawn(move || {
            let (mut s, _) = listener.accept().unwrap();
            // read until headers + full Content-Length body are in (a single read
            // can return before the body bytes arrive)
            let mut raw = Vec::new();
            let mut buf = [0u8; 2048];
            loop {
                let n = s.read(&mut buf).unwrap_or(0);
                if n == 0 {
                    break;
                }
                raw.extend_from_slice(&buf[..n]);
                let text = String::from_utf8_lossy(&raw);
                if let Some(hdr_end) = text.find("\r\n\r\n") {
                    let want: usize = text
                        .lines()
                        .find_map(|l| {
                            l.to_ascii_lowercase()
                                .strip_prefix("content-length:")
                                .map(|v| v.trim().parse().unwrap_or(0))
                        })
                        .unwrap_or(0);
                    if raw.len() >= hdr_end + 4 + want {
                        break;
                    }
                }
            }
            let req = String::from_utf8_lossy(&raw).to_string();
            let resp = format!(
                "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len()
            );
            let _ = s.write_all(resp.as_bytes());
            req
        });
        (h, port)
    }

    // Network round-trip tests: reliable in isolation, but the blocking mock
    // server can starve under the full suite's fd/CPU pressure. Run explicitly
    // with `cargo test -- --ignored`. The parse logic above is always covered.
    #[test]
    #[ignore = "network mock; run with --ignored"]
    fn fetch_roster_parses_live_response() {
        let (h, port) = mock_once(
            200,
            r#"[{"node_pubkey":"AAA","revoked":false},{"node_pubkey":"BBB","revoked":true}]"#,
        );
        let url = format!("http://127.0.0.1:{port}");
        let roster = fetch_roster(&url, "zk_1_x").unwrap();
        let req = h.join().unwrap();
        assert!(req.starts_with("GET /api/broker/node/roster"));
        assert!(req
            .to_ascii_lowercase()
            .contains("x-broker-api-key: zk_1_x"));
        assert_eq!(roster.len(), 2);
        assert_eq!(roster[1], ("BBB".to_string(), true));
    }

    #[test]
    #[ignore = "network mock; run with --ignored"]
    fn obtain_voucher_extracts_signed_json_and_sig() {
        let (h, port) = mock_once(200, r#"{"signed_json":"{\"v\":1}","sig":"deadbeef"}"#);
        let url = format!("http://127.0.0.1:{port}");
        let (signed, sig) = obtain_voucher(&url, "zk_1_x", 5.0).unwrap();
        let req = h.join().unwrap();
        assert!(req.starts_with("POST /api/broker/voucher"));
        assert!(req.contains("budget_credits"));
        assert_eq!(signed, "{\"v\":1}");
        assert_eq!(sig, "deadbeef");
    }

    #[test]
    fn parse_voucher_pubkeys_single_key_shape() {
        let keys = parse_voucher_pubkeys(r#"{"pubkey":"AAA"}"#).unwrap();
        assert_eq!(keys, vec!["AAA".to_string()]);
    }

    #[test]
    fn register_payload_carries_hub_allocation_after_zc_build() {
        let a = crate::hub_allocation::HubAllocation {
            enabled: true,
            vram_gb: 8,
            ram_gb: 16,
            disk_gb: 50,
            purpose: vec!["inference".into(), "warmup".into()],
        };
        let payload = super::register_payload("PUBKEY", None, None, Some(&a));
        let v: serde_json::Value = serde_json::from_str(&payload).unwrap();
        assert_eq!(
            v["hub_allocation"],
            serde_json::json!({"enabled": true, "vram_gb": 8, "ram_gb": 16, "disk_gb": 50, "purpose": ["inference", "warmup"]})
        );
    }

    #[test]
    fn register_payload_sends_disabled_hub_allocation_and_omits_unset() {
        let a = crate::hub_allocation::HubAllocation {
            enabled: false,
            vram_gb: 0,
            ram_gb: 4,
            disk_gb: 10,
            purpose: vec!["inference".into()],
        };
        let v: serde_json::Value =
            serde_json::from_str(&super::register_payload("PUBKEY", None, None, Some(&a))).unwrap();
        assert_eq!(v["hub_allocation"]["enabled"], false);
        let none = super::register_payload("PUBKEY", None, None, None);
        assert!(!none.contains("hub_allocation"), "{none}");
    }

    #[test]
    fn parse_voucher_pubkeys_set_shape_prefers_pubkeys() {
        let keys =
            parse_voucher_pubkeys(r#"{"pubkey":"AAA","pubkeys":["AAA","BBB","AAA"]}"#).unwrap();
        assert_eq!(keys, vec!["AAA".to_string(), "BBB".to_string()]);
        // pubkeys wins over a differing legacy field.
        let keys = parse_voucher_pubkeys(r#"{"pubkey":"X","pubkeys":["AAA"]}"#).unwrap();
        assert_eq!(keys, vec!["AAA".to_string()]);
    }

    #[test]
    fn parse_voucher_pubkeys_empty_set_falls_back_and_missing_errors() {
        let keys = parse_voucher_pubkeys(r#"{"pubkey":"AAA","pubkeys":[]}"#).unwrap();
        assert_eq!(keys, vec!["AAA".to_string()]);
        assert!(parse_voucher_pubkeys(r#"{}"#).is_err());
        assert!(parse_voucher_pubkeys("not json").is_err());
    }
}