zlayer-types 0.14.2

Shared wire types for the ZLayer platform — API DTOs, OCI image references, and related serde types.
Documentation
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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
//! IPC wire protocol between the main `zlayer` daemon and `zlayer-overlayd`.
//!
//! `zlayer-overlayd` is a standalone, long-lived daemon that owns every
//! mechanism touching the overlay/network plane (the `WireGuard` device +
//! adapter, peers, `AllowedIPs`/service subnets, IP allocation, DNS, NAT,
//! Linux bridges + veth/netns attach, and the Windows HCN Internal network +
//! endpoints). The main `zlayer` daemon keeps the cluster brain (Raft, the
//! scheduler, the service registry, container/HCS process lifecycle) and
//! drives overlayd over a length-prefixed-JSON IPC channel (a Unix domain
//! socket on Unix, a named pipe on Windows).
//!
//! This module is that channel's **wire contract** — the only thing both
//! sides must agree on. It lives in `zlayer-types` (a leaf crate) so the
//! daemon, the overlayd server, and the overlayd client can all depend on it
//! without a dependency cycle.
//!
//! ## Framing
//!
//! One connection multiplexes request/response and server→client event push.
//! Each frame is a [`OverlaydFrame`] serialized as JSON and written with a
//! `u32` little-endian length prefix (the framing itself lives in
//! `zlayer-overlayd`'s transport module, not here). The main daemon sends
//! [`OverlaydFrame::Request`]s each carrying a client-chosen `id`; overlayd
//! replies with a [`OverlaydFrame::Response`] echoing that `id`, and may at
//! any time push an unsolicited [`OverlaydFrame::Event`].
//!
//! ## Wire-type conventions
//!
//! - Windows HCN GUIDs cross the wire as **bare lowercase strings**
//!   (`aabbccdd-eeff-...`, no braces) — `windows::core::GUID` is not
//!   `serde`-serializable and `zlayer-types` must not depend on `windows`.
//! - CIDRs cross as `String` (e.g. `"10.200.0.0/28"`); endpoints as `String`
//!   (`"host:port"`, kept textual so an unresolved/hostname endpoint survives).
//! - Addresses use [`std::net::IpAddr`] (serde-serializable via `std`).

use std::net::IpAddr;

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use serde::{Deserialize, Serialize};

pub use crate::nat_wire::{NatCandidateWire, NatConfigSpec};
pub use crate::overlay::{OverlayConfig, OverlayMode};

/// Wire-protocol version. Bump on any breaking change to the frame/request/
/// response/event shapes so a version-skewed daemon/overlayd pair can detect
/// the mismatch instead of silently misparsing.
pub const PROTOCOL_VERSION: u32 = 1;

/// A multiplexed frame on the overlayd IPC connection.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "frame", rename_all = "snake_case")]
pub enum OverlaydFrame {
    /// Main daemon → overlayd. `id` is echoed back on the matching response.
    Request { id: u64, request: OverlaydRequest },
    /// overlayd → main daemon, answering the request with the same `id`.
    Response { id: u64, response: OverlaydResponse },
    /// overlayd → main daemon, unsolicited (no `id`).
    Event(OverlaydEvent),
}

/// Identifies the container overlayd must wire into the overlay. The agent
/// owns the container's process/compute-system lifecycle and hands overlayd
/// just enough to attach it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "platform", rename_all = "snake_case")]
pub enum AttachHandle {
    /// Linux: the container's PID. overlayd opens `/proc/<pid>/ns/net` and
    /// creates the veth pair into that network namespace.
    LinuxPid { pid: u32 },
    /// Windows: the HCS container id (+ the IP the agent reserved, if any).
    /// overlayd creates the HCN endpoint + per-container namespace on its HCN
    /// Internal network and returns the bare-lowercase namespace GUID
    /// ([`AttachResult::namespace_guid`]) for the agent to embed in the
    /// compute-system document's `Container.Networking.Namespace`.
    WindowsContainer {
        container_id: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        ip: Option<IpAddr>,
    },
    /// A guest that manages its own overlay interface (the macOS VZ-Linux VM
    /// runtime). overlayd cannot enter the guest's netns (it is a VM, not a host
    /// process), so instead of building a veth it **allocates the overlay
    /// identity** — keypair, address, and the current peer set — registers the
    /// generated public key in the mesh, and returns it as
    /// [`OverlaydResponse::GuestConfig`]. The caller ships that config into the
    /// guest (over vsock) where a kernel `WireGuard` device is brought up. `id` is
    /// the opaque container id used to scope the allocation + the registered
    /// peer so `DetachContainer` can release it.
    GuestManaged { id: String },
    /// Host-shared native macOS container (Seatbelt, native-VZ, libkrun): no
    /// per-container netns/PID and no in-guest `WireGuard`. overlayd allocates a
    /// distinct overlay `/32` from the node slice and adds it as a `utun` alias
    /// so it is locally deliverable; the agent then forwards
    /// `<overlay_ip>:port` to the container's local delivery address. Detach +
    /// bookkeeping are keyed by `id` (like `GuestManaged`).
    HostShared { id: String },
}

/// A request from the main daemon to overlayd.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum OverlaydRequest {
    /// Push this node's Raft id (cluster-brain context overlayd scopes by).
    SetLocalNodeId { node_id: u64 },
    /// Push this node's `WireGuard` public key (base64).
    SetLocalWgPubkey { pubkey: String },

    /// Bring up (or reuse) this node's base/global overlay. Idempotent: if the
    /// overlay network already exists (recorded in overlayd's marker), it is
    /// reused rather than recreated. This is the only place the base overlay
    /// is created; it is torn down only on a full uninstall.
    SetupGlobalOverlay {
        deployment: String,
        instance_id: String,
        /// Full cluster CIDR, e.g. `"10.200.0.0/16"`.
        cluster_cidr: String,
        /// This node's per-node slice, e.g. `"10.200.0.0/28"`. `None` until the
        /// leader assigns one.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        slice_cidr: Option<String>,
        wg_port: u16,
        /// When true, a host-adapter (utun/Wintun) bringup failure is FATAL
        /// instead of degrading to a VM-only overlay. Set by the daemon when the
        /// node runs a host-shared runtime (macOS Seatbelt/native-VZ/libkrun)
        /// where the host adapter IS the container data path. `#[serde(default)]`
        /// keeps a pre-field daemon's payload decoding (false = old behavior).
        #[serde(default)]
        host_adapter_mandatory: bool,
        /// Full NAT-traversal configuration for this node's overlay.
        ///
        /// `None` (or any omitted sub-field) means "no explicit NAT config" and
        /// overlayd falls back to its built-in `NatConfig::default()`. This
        /// replaced the previous `nat_enabled: bool`, which silently dropped the
        /// operator's `--stun-server`/`--turn-server`/`--relay-server-bind`
        /// flags (overlayd only ever saw the enabled toggle). `#[serde(default)]`
        /// keeps a pre-`nat` daemon's payload (no `nat` field) decoding cleanly.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        nat: Option<NatConfigSpec>,
    },
    /// Tear down the node's base overlay (e.g. on full uninstall).
    TeardownGlobalOverlay,

    /// Create the per-service overlay segment (Linux bridge / Windows HCN
    /// Internal network) for `service`. Returns [`OverlaydResponse::BridgeName`].
    SetupServiceOverlay { service: String, mode: OverlayMode },
    /// Remove the per-service overlay segment.
    TeardownServiceOverlay { service: String },

    /// Allocate (or, with `ip` set on a later attach, validate) an overlay IP
    /// from the node slice for a container on `service`.
    AllocateIp { service: String, join_global: bool },
    /// Return an overlay IP to the allocator.
    ReleaseIp { ip: IpAddr },

    /// Wire a container into the overlay. Returns [`OverlaydResponse::Attached`].
    AttachContainer {
        handle: AttachHandle,
        service: String,
        join_global: bool,
        /// When true, overlayd reclaims the per-service bridge once the LAST
        /// container detaches (ephemeral/per-job networks). When false, the bridge
        /// persists across scale-to-0 (managed services). Defaults false for
        /// back-compat with older clients.
        #[serde(default)]
        ephemeral: bool,
        /// When `Some(network)`, this attach joins the named **isolated** network:
        /// overlayd records the member in that network's membership set and
        /// enforces Docker-style L3 isolation (the member reaches its own
        /// network's members + the daemon node IP + egress, but NOT other
        /// networks' members or arbitrary cluster overlay IPs). `None` = the flat
        /// cluster mesh (today's behavior). Defaults `None` for older clients.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        isolation_network: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        dns_server: Option<IpAddr>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        dns_domain: Option<String>,
    },
    /// Tear down a container's overlay attachment and release its IP.
    DetachContainer { handle: AttachHandle },

    /// Add a `WireGuard` peer to the base overlay.
    AddPeer {
        #[serde(flatten)]
        peer: PeerSpec,
        #[serde(default)]
        scope: PeerScope,
    },
    /// Remove a peer by its base64 public key.
    RemovePeer {
        pubkey: String,
        #[serde(default)]
        scope: PeerScope,
    },
    /// Plumb a service subnet into a peer's `AllowedIPs`.
    AddAllowedIp {
        pubkey: String,
        cidr: String,
        #[serde(default)]
        scope: PeerScope,
    },
    /// Remove a service subnet from a peer's `AllowedIPs`.
    RemoveAllowedIp {
        pubkey: String,
        cidr: String,
        #[serde(default)]
        scope: PeerScope,
    },

    /// Mint a short-lived unprivileged `WireGuard` edge peer: allocate an
    /// overlay identity keyed by `name`, register it in the mesh, and return
    /// it as [`OverlaydResponse::EdgeConfig`]. Minted peers die with overlayd
    /// — provisioners re-mint rather than persist a config.
    MintEdgePeer {
        /// Caller-chosen handle the peer is minted (and later revoked) under.
        name: String,
        /// Seconds until the peer expires and is swept from the mesh.
        ttl_secs: u64,
        /// Overlay CIDRs the edge peer may reach. Empty for a sender that
        /// omits the field; `#[serde(default)]` keeps such payloads decoding.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        allow: Vec<String>,
        /// The EXTERNAL `advertise_addr:overlay_port` endpoint the edge peer
        /// dials, supplied by the daemon — never the local overlay IP (the
        /// edge peer sits outside the overlay until its first handshake).
        node_endpoint: String,
    },
    /// Revoke a minted edge peer by name. Idempotent: revoking an unknown or
    /// already-expired name succeeds.
    RevokeEdgePeer { name: String },
    /// List currently minted edge peers. Returns [`OverlaydResponse::EdgePeers`].
    ListEdgePeers,

    /// Register an overlay DNS A/AAAA record.
    RegisterDns { name: String, ip: IpAddr },
    /// Remove an overlay DNS record.
    UnregisterDns { name: String },

    /// Write a macOS `/etc/resolver/<zone>` scoped-resolver file pointing at the
    /// node's overlay DNS. Privileged (root-only path); the rootless daemon asks
    /// the ROOT overlayd to perform it. macOS-only handler; no-op elsewhere.
    WriteScopedResolver {
        zone: String,
        node_ip: IpAddr,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        port: Option<u16>,
    },
    /// Remove a macOS `/etc/resolver/<zone>` scoped-resolver file.
    RemoveScopedResolver { zone: String },

    /// Reclaim orphaned per-service host bridges (and their stale device/
    /// container veths) that no live deployment still owns. The daemon computes
    /// `live_bridge_names` from storage — the full set of `zl-…-b` bridge names
    /// every currently-restored service SHOULD own — and overlayd deletes every
    /// `zl-…-b` bridge link NOT in that set (plus releases its subnet/AllowedIPs
    /// when recoverable), so a bridge left behind by a crashed/forgotten
    /// deployment is swept on the next daemon startup. Names are passed (rather
    /// than overlayd reaching into storage) to keep overlayd storage-free.
    /// Returns [`OverlaydResponse::PrunedBridges`].
    PruneOrphanBridges { live_bridge_names: Vec<String> },

    /// Snapshot overlay state for diagnostics. Returns [`OverlaydResponse::Status`].
    Status,
    /// Run one NAT-traversal maintenance tick (probe/refresh endpoints).
    NatTick,
    /// Snapshot the live NAT-traversal state (local candidates, per-peer
    /// connection types, last refresh). Returns [`OverlaydResponse::NatStatus`].
    NatStatus,
    /// Ask overlayd to shut down gracefully (drops the adapter).
    Shutdown,
}

/// overlayd's answer to an [`OverlaydRequest`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "result", rename_all = "snake_case")]
pub enum OverlaydResponse {
    /// Generic success with no payload.
    Ok,
    /// An allocated/validated overlay IP (`AllocateIp`).
    Ip { ip: IpAddr },
    /// A completed container attach.
    Attached(AttachResult),
    /// The overlay identity for a guest-managed attach
    /// ([`AttachHandle::GuestManaged`]): the keypair, allocated address, and the
    /// peer set the guest should configure on its own `WireGuard` device.
    GuestConfig(GuestOverlayConfig),
    /// The interface/bridge/network name created (`SetupServiceOverlay`,
    /// `SetupGlobalOverlay`).
    BridgeName { name: String },
    /// A diagnostics snapshot (`Status`).
    Status(StatusSnapshot),
    /// A live NAT-traversal snapshot (`NatStatus`).
    NatStatus(NatStatusWire),
    /// The orphaned bridges/veths reclaimed by `PruneOrphanBridges`.
    PrunedBridges { reclaimed: Vec<String> },
    /// A dedicated per-service overlay device's identity (`SetupServiceOverlay`
    /// in Dedicated mode). Not yet produced by the server — the server still
    /// returns [`OverlaydResponse::BridgeName`] for now; this variant is the
    /// wire contract for a later task that switches Dedicated setup over.
    ServiceOverlay(ServiceOverlayInfo),
    /// The minted edge peer's portable config (`MintEdgePeer`).
    EdgeConfig(EdgeConfig),
    /// The currently minted edge peers (`ListEdgePeers`).
    EdgePeers { peers: Vec<EdgePeerStatus> },
    /// The request failed; `message` is a human-readable reason.
    Err { message: String },
}

/// Identity of a dedicated per-service overlay device, reported by
/// `SetupServiceOverlay` once Dedicated mode is wired up. Shared-mode setups
/// leave the `wg_*`/`overlay_ip`/`subnet` fields `None`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServiceOverlayInfo {
    pub name: String,
    pub mode: crate::overlay::OverlayMode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wg_public_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wg_port: Option<u16>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub overlay_ip: Option<std::net::IpAddr>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subnet: Option<String>,
}

/// Result of [`OverlaydRequest::AttachContainer`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttachResult {
    /// The container's overlay IP.
    pub ip: IpAddr,
    /// Windows only: the bare-lowercase HCN namespace GUID the agent embeds in
    /// the compute-system document. `None` on Linux (no HCN namespace).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace_guid: Option<String>,
}

/// Overlay identity returned for a guest-managed attach
/// ([`AttachHandle::GuestManaged`] → [`OverlaydResponse::GuestConfig`]).
///
/// The host allocated the address from the node slice, generated the keypair,
/// and registered `public_key` in the mesh (so peers route to the guest). The
/// caller ships everything except `public_key` into the guest; `public_key` is
/// echoed back so the caller can record/deregister the peer it represents.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GuestOverlayConfig {
    /// The guest's allocated overlay address.
    pub overlay_ip: IpAddr,
    /// Prefix length of the overlay network (interface address + on-link route).
    pub prefix_len: u8,
    /// Base64 `WireGuard` private key for the guest's overlay endpoint.
    pub private_key: String,
    /// Base64 `WireGuard` public key matching `private_key` (registered in the
    /// mesh by overlayd; echoed for the caller's bookkeeping).
    pub public_key: String,
    /// UDP port the guest's `WireGuard` device should listen on.
    pub listen_port: u16,
    /// The peers the guest should configure (other nodes/containers).
    pub peers: Vec<PeerSpec>,
    /// Overlay DNS resolver IP for the container, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dns_server: Option<IpAddr>,
    /// Overlay DNS search domain, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dns_domain: Option<String>,
}

/// Shape version stamped into every [`EdgeConfig`] (and its token form). Bump
/// on any breaking change to the `EdgeConfig` shape so a version-skewed
/// decoder rejects the token instead of silently misparsing it.
pub const EDGE_CONFIG_VERSION: u32 = 1;

/// Prefix identifying an [`EdgeConfig`] token string. The `1` is the token
/// FORMAT version (prefix + base64 compact JSON); the payload's
/// [`EDGE_CONFIG_VERSION`] is checked separately after decoding.
const EDGE_TOKEN_PREFIX: &str = "zledge1.";

/// Portable artifact for a minted edge peer
/// ([`OverlaydRequest::MintEdgePeer`] → [`OverlaydResponse::EdgeConfig`]):
/// everything a short-lived unprivileged `WireGuard` edge process needs to
/// join the overlay. Minted peers die with overlayd — provisioners re-mint
/// rather than persist and reuse a config.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
pub struct EdgeConfig {
    /// Always [`EDGE_CONFIG_VERSION`] for configs minted by this build;
    /// [`EdgeConfig::from_token`] rejects anything else.
    pub version: u32,
    /// The caller-chosen handle the peer was minted under.
    pub name: String,
    /// The edge peer's allocated overlay address.
    #[schema(value_type = String, example = "10.200.0.9")]
    pub overlay_ip: IpAddr,
    /// Prefix length of the overlay network (interface address + on-link route).
    pub prefix_len: u8,
    /// Base64 `WireGuard` private key for the edge peer's device.
    pub private_key: String,
    /// Base64 `WireGuard` public key matching `private_key` (registered in the
    /// mesh by overlayd; echoed for the caller's bookkeeping).
    pub public_key: String,
    /// The peers the edge should configure (the minting node, at least). Each
    /// [`PeerSpec::allowed_ips`] is a comma-separated CIDR list by the
    /// established convention — vzagent splits on `','`.
    pub peers: Vec<PeerSpec>,
    /// Overlay DNS resolver IP for the edge peer, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schema(value_type = Option<String>, example = "10.200.0.1")]
    pub dns_server: Option<IpAddr>,
    /// Overlay DNS search domain, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dns_domain: Option<String>,
    /// Unix-seconds when the peer expires and is swept from the mesh.
    pub expires_at_unix: u64,
}

impl EdgeConfig {
    /// Encode the config as a single `zledge1.`-prefixed URL-safe-base64
    /// (no padding) string of its compact-JSON form, suitable for CLI flags /
    /// env vars (the prefix-versioned CLI-string idiom, cf.
    /// `WorkerBootstrapToken::to_cli_string` in `zlayer-secrets`).
    ///
    /// # Panics
    ///
    /// Never in practice: `EdgeConfig` JSON-serializes infallibly (no
    /// non-string map keys, no fallible `Serialize` impls).
    #[must_use]
    pub fn to_token(&self) -> String {
        let json = serde_json::to_string(self)
            .expect("EdgeConfig JSON serialization is infallible (no non-string map keys)");
        format!("{EDGE_TOKEN_PREFIX}{}", URL_SAFE_NO_PAD.encode(json))
    }

    /// Decode a token previously produced by [`Self::to_token`].
    ///
    /// # Errors
    ///
    /// Returns [`EdgeTokenError::BadPrefix`] when the `zledge1.` prefix is
    /// missing, [`EdgeTokenError::Decode`] / [`EdgeTokenError::Parse`] on
    /// base64 / JSON failure, and [`EdgeTokenError::UnsupportedVersion`] when
    /// the payload's `version` is not [`EDGE_CONFIG_VERSION`].
    pub fn from_token(token: &str) -> Result<Self, EdgeTokenError> {
        let encoded = token
            .strip_prefix(EDGE_TOKEN_PREFIX)
            .ok_or(EdgeTokenError::BadPrefix)?;
        let bytes = URL_SAFE_NO_PAD.decode(encoded)?;
        // Probe the version before the full parse so a future-versioned token
        // whose shape drifted reports the version mismatch, not a parse error.
        let probe: EdgeConfigVersionProbe = serde_json::from_slice(&bytes)?;
        if probe.version != EDGE_CONFIG_VERSION {
            return Err(EdgeTokenError::UnsupportedVersion {
                found: probe.version,
            });
        }
        Ok(serde_json::from_slice(&bytes)?)
    }
}

/// Minimal deserialization target for the version pre-check in
/// [`EdgeConfig::from_token`] (unknown fields are ignored, so a
/// future-versioned payload still yields its `version`).
#[derive(Deserialize)]
struct EdgeConfigVersionProbe {
    version: u32,
}

/// Errors from [`EdgeConfig::from_token`].
#[derive(Debug, thiserror::Error)]
pub enum EdgeTokenError {
    /// The token does not start with the `zledge1.` prefix.
    #[error("edge token missing `{EDGE_TOKEN_PREFIX}` prefix")]
    BadPrefix,
    /// The portion after the prefix is not valid URL-safe base64.
    #[error("edge token base64 decode failed: {0}")]
    Decode(#[from] base64::DecodeError),
    /// The decoded payload is not valid `EdgeConfig` JSON.
    #[error("edge token JSON parse failed: {0}")]
    Parse(#[from] serde_json::Error),
    /// The payload's `version` differs from this build's [`EDGE_CONFIG_VERSION`].
    #[error("unsupported edge config version {found} (expected {EDGE_CONFIG_VERSION})")]
    UnsupportedVersion {
        /// The version the token carried.
        found: u32,
    },
}

/// Live status of one minted edge peer, reported by
/// [`OverlaydRequest::ListEdgePeers`] → [`OverlaydResponse::EdgePeers`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
pub struct EdgePeerStatus {
    /// The handle the peer was minted under.
    pub name: String,
    /// The peer's allocated overlay address.
    #[schema(value_type = String, example = "10.200.0.9")]
    pub overlay_ip: IpAddr,
    /// Base64 `WireGuard` public key registered for the peer.
    pub public_key: String,
    /// Unix-seconds when the peer was minted.
    pub minted_at_unix: u64,
    /// Unix-seconds when the peer expires and is swept from the mesh.
    pub expires_at_unix: u64,
    /// Last successful handshake, Unix seconds; `None` if never.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_handshake_unix_secs: Option<i64>,
    /// The overlay CIDRs granted at mint time (the accepted `allow` list).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub allowed: Vec<String>,
}

/// Which overlay device a peer / `AllowedIP` op targets. `Global` (default, and
/// the only value pre-Dedicated senders emit) = the single cluster transport.
/// `Service` = that service's dedicated per-service transport.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(tag = "scope", rename_all = "snake_case")]
pub enum PeerScope {
    #[default]
    Global,
    Service {
        service: String,
    },
}

/// A `WireGuard` peer to add to the base overlay. Mirrors
/// `zlayer_overlay::PeerInfo` but with wire-safe field types.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
pub struct PeerSpec {
    /// base64 `WireGuard` public key.
    pub public_key: String,
    /// `host:port` (textual so an unresolved/hostname endpoint survives).
    pub endpoint: String,
    /// Comma-separated CIDR list (e.g. `"10.200.0.5/32,10.200.1.0/24"`).
    pub allowed_ips: String,
    /// Persistent-keepalive interval, in seconds (0 = disabled).
    pub persistent_keepalive_secs: u64,
    /// NAT-traversal candidates the peer advertised at join time (host /
    /// server-reflexive / relay addresses it can be reached on). overlayd feeds
    /// these into `NatTraversal::connect_to_peer` to hole-punch / relay toward
    /// the peer when a direct endpoint doesn't establish a handshake. Empty for
    /// a pre-NAT sender; `#[serde(default)]` keeps such payloads decoding.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<NatCandidateWire>,
}

/// An unsolicited notification pushed from overlayd to the main daemon.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum OverlaydEvent {
    /// A peer's liveness changed (handshake seen / lost).
    PeerHealthChanged { pubkey: String, healthy: bool },
    /// NAT traversal moved a peer to a new endpoint.
    NatEndpointChanged { pubkey: String, endpoint: String },
}

/// Diagnostics snapshot returned by [`OverlaydRequest::Status`].
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatusSnapshot {
    /// Base overlay interface name (e.g. `"zl-overlay0"`), if up.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interface: Option<String>,
    /// This node's overlay IP, if assigned.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub node_ip: Option<IpAddr>,
    /// This node's `WireGuard` public key (base64), if up.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub public_key: Option<String>,
    /// Full cluster CIDR.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub overlay_cidr: Option<String>,
    /// This node's per-node slice CIDR.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slice_cidr: Option<String>,
    /// Number of base-overlay peers.
    pub peer_count: u32,
    /// Number of per-service overlays set up on this node.
    pub service_count: u32,
    /// Per-peer status.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub peers: Vec<PeerStatus>,
    /// Per dedicated per-service overlay device status. Empty unless one or
    /// more services run in `OverlayMode::Dedicated` on this node.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dedicated_services: Vec<DedicatedServiceStatus>,
}

/// Status of a single dedicated per-service overlay device within a
/// [`StatusSnapshot`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DedicatedServiceStatus {
    pub service: String,
    pub interface: String,
    pub public_key: String,
    pub listen_port: u16,
    pub overlay_ip: std::net::IpAddr,
    pub subnet: String,
    pub peer_count: u32,
}

/// Per-peer status within a [`StatusSnapshot`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerStatus {
    pub public_key: String,
    pub endpoint: String,
    pub allowed_ips: String,
    /// Last successful handshake, Unix seconds; `0` if never.
    pub last_handshake_unix_secs: i64,
}

/// Live NAT-traversal snapshot returned by [`OverlaydRequest::NatStatus`].
///
/// Wire mirror of `zlayer_overlay::NatStatusSnapshot` (which `zlayer-types`
/// cannot reference — it lives behind the `nat` feature). The agent shim
/// converts this back into `NatStatusSnapshot` for the API layer.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct NatStatusWire {
    /// Locally gathered ICE candidates.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<NatCandidateWire>,
    /// Per-peer NAT connectivity entries.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub peers: Vec<NatPeerWire>,
    /// Unix-epoch seconds of the last successful candidate gather / STUN refresh.
    #[serde(default)]
    pub last_refresh: u64,
}

/// Per-peer NAT connectivity entry within a [`NatStatusWire`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NatPeerWire {
    /// Peer node id, or the base64 public key when no node id is available.
    pub node_id: String,
    /// Connection type as a lowercase string
    /// (`"direct"` / `"hole-punched"` / `"relayed"` / `"unreachable"`).
    pub connection_type: String,
    /// Selected remote endpoint (`host:port`), if one has been negotiated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub remote_endpoint: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::nat_wire::{RelayServerSpec, TurnServerSpec};

    /// A frame round-trips through JSON unchanged (the core wire guarantee).
    fn roundtrip(frame: &OverlaydFrame) {
        let json = serde_json::to_string(frame).expect("serialize");
        let back: OverlaydFrame = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(frame, &back, "frame must round-trip; json was {json}");
    }

    #[test]
    fn request_frames_round_trip() {
        roundtrip(&OverlaydFrame::Request {
            id: 1,
            request: OverlaydRequest::SetupGlobalOverlay {
                deployment: "prod".into(),
                instance_id: "42".into(),
                cluster_cidr: "10.200.0.0/16".into(),
                slice_cidr: Some("10.200.0.0/28".into()),
                wg_port: 51820,
                host_adapter_mandatory: true,
                nat: Some(NatConfigSpec {
                    enabled: true,
                    stun_servers: vec!["stun.l.google.com:19302".into()],
                    turn_servers: vec![TurnServerSpec {
                        addr: "turn.example.com:3478".into(),
                        username: "u".into(),
                        credential: "p".into(),
                    }],
                    hole_punch_timeout_secs: 15,
                    stun_refresh_interval_secs: 60,
                    max_candidate_pairs: 10,
                    relay_server: Some(RelayServerSpec {
                        listen_port: 3478,
                        external_addr: "1.2.3.4:3478".into(),
                        max_sessions: 100,
                        auth_credential: Some("cluster-secret".into()),
                    }),
                }),
            },
        });
        roundtrip(&OverlaydFrame::Request {
            id: 2,
            request: OverlaydRequest::AttachContainer {
                handle: AttachHandle::WindowsContainer {
                    container_id: "ctr-abc".into(),
                    ip: Some("10.200.0.5".parse().unwrap()),
                },
                service: "web".into(),
                join_global: false,
                ephemeral: false,
                isolation_network: None,
                dns_server: Some("10.200.0.1".parse().unwrap()),
                dns_domain: Some("overlay".into()),
            },
        });
        roundtrip(&OverlaydFrame::Request {
            id: 3,
            request: OverlaydRequest::AttachContainer {
                handle: AttachHandle::LinuxPid { pid: 4242 },
                service: "web".into(),
                join_global: true,
                ephemeral: false,
                isolation_network: Some("job-net".into()),
                dns_server: None,
                dns_domain: None,
            },
        });
    }

    #[test]
    fn response_and_event_frames_round_trip() {
        roundtrip(&OverlaydFrame::Response {
            id: 2,
            response: OverlaydResponse::Attached(AttachResult {
                ip: "10.200.0.5".parse().unwrap(),
                namespace_guid: Some("aabbccdd-eeff-0011-2233-445566778899".into()),
            }),
        });
        roundtrip(&OverlaydFrame::Response {
            id: 9,
            response: OverlaydResponse::Err {
                message: "no slice assigned".into(),
            },
        });
        roundtrip(&OverlaydFrame::Event(OverlaydEvent::PeerHealthChanged {
            pubkey: "base64key".into(),
            healthy: false,
        }));
    }

    #[test]
    fn prune_orphan_bridges_round_trips() {
        roundtrip(&OverlaydFrame::Request {
            id: 30,
            request: OverlaydRequest::PruneOrphanBridges {
                live_bridge_names: vec!["zl-prod-0-web-b".into(), "zl-prod-0-api-b".into()],
            },
        });
        roundtrip(&OverlaydFrame::Response {
            id: 30,
            response: OverlaydResponse::PrunedBridges {
                reclaimed: vec!["zl-1ca4568944-b".into(), "zl-81c6bc17c7-b".into()],
            },
        });
    }

    #[test]
    fn status_snapshot_round_trips_and_defaults() {
        roundtrip(&OverlaydFrame::Response {
            id: 7,
            response: OverlaydResponse::Status(StatusSnapshot {
                interface: Some("zl-overlay0".into()),
                node_ip: Some("10.200.0.1".parse().unwrap()),
                peer_count: 2,
                service_count: 1,
                peers: vec![PeerStatus {
                    public_key: "k".into(),
                    endpoint: "1.2.3.4:51820".into(),
                    allowed_ips: "10.200.0.2/32".into(),
                    last_handshake_unix_secs: 0,
                }],
                ..StatusSnapshot::default()
            }),
        });
    }

    fn sample_peer() -> PeerSpec {
        PeerSpec {
            public_key: "base64key".into(),
            endpoint: "1.2.3.4:51820".into(),
            allowed_ips: "10.200.0.2/32".into(),
            persistent_keepalive_secs: 25,
            candidates: vec![
                NatCandidateWire {
                    candidate_type: "host".into(),
                    address: "192.168.1.5:51820".into(),
                    priority: 100,
                },
                NatCandidateWire {
                    candidate_type: "server-reflexive".into(),
                    address: "203.0.113.5:51820".into(),
                    priority: 50,
                },
            ],
        }
    }

    #[test]
    fn peer_ops_round_trip_both_scopes() {
        // AddPeer, global (default) + service scope.
        roundtrip(&OverlaydFrame::Request {
            id: 1,
            request: OverlaydRequest::AddPeer {
                peer: sample_peer(),
                scope: PeerScope::Global,
            },
        });
        roundtrip(&OverlaydFrame::Request {
            id: 2,
            request: OverlaydRequest::AddPeer {
                peer: sample_peer(),
                scope: PeerScope::Service {
                    service: "web".into(),
                },
            },
        });
        // RemovePeer.
        roundtrip(&OverlaydFrame::Request {
            id: 3,
            request: OverlaydRequest::RemovePeer {
                pubkey: "k".into(),
                scope: PeerScope::Global,
            },
        });
        roundtrip(&OverlaydFrame::Request {
            id: 4,
            request: OverlaydRequest::RemovePeer {
                pubkey: "k".into(),
                scope: PeerScope::Service {
                    service: "web".into(),
                },
            },
        });
        // AddAllowedIp.
        roundtrip(&OverlaydFrame::Request {
            id: 5,
            request: OverlaydRequest::AddAllowedIp {
                pubkey: "k".into(),
                cidr: "10.200.1.0/24".into(),
                scope: PeerScope::Global,
            },
        });
        roundtrip(&OverlaydFrame::Request {
            id: 6,
            request: OverlaydRequest::AddAllowedIp {
                pubkey: "k".into(),
                cidr: "10.200.1.0/24".into(),
                scope: PeerScope::Service {
                    service: "web".into(),
                },
            },
        });
        // RemoveAllowedIp.
        roundtrip(&OverlaydFrame::Request {
            id: 7,
            request: OverlaydRequest::RemoveAllowedIp {
                pubkey: "k".into(),
                cidr: "10.200.1.0/24".into(),
                scope: PeerScope::Global,
            },
        });
        roundtrip(&OverlaydFrame::Request {
            id: 8,
            request: OverlaydRequest::RemoveAllowedIp {
                pubkey: "k".into(),
                cidr: "10.200.1.0/24".into(),
                scope: PeerScope::Service {
                    service: "web".into(),
                },
            },
        });
    }

    #[test]
    fn add_peer_without_scope_defaults_to_global() {
        // A pre-Dedicated sender emits no `scope` field. The frame is tagged
        // `frame: "request"`, the request `op: "add_peer"`, and `PeerSpec` is
        // flattened so its fields sit at the request level.
        let json = r#"{
            "frame": "request",
            "id": 11,
            "request": {
                "op": "add_peer",
                "public_key": "base64key",
                "endpoint": "1.2.3.4:51820",
                "allowed_ips": "10.200.0.2/32",
                "persistent_keepalive_secs": 25
            }
        }"#;
        let frame: OverlaydFrame = serde_json::from_str(json).expect("deserialize");
        match frame {
            OverlaydFrame::Request {
                request: OverlaydRequest::AddPeer { scope, peer },
                ..
            } => {
                assert_eq!(scope, PeerScope::Global);
                assert_eq!(peer.public_key, "base64key");
                // A pre-NAT sender omits `candidates`; it must default to empty.
                assert!(peer.candidates.is_empty());
            }
            other => panic!("expected AddPeer request, got {other:?}"),
        }
    }

    /// `SetupGlobalOverlay` from a pre-`nat` daemon omits the `nat` field
    /// entirely; it must deserialize to `nat: None` (overlayd then uses its
    /// built-in `NatConfig::default()`), proving the wire change is backward
    /// compatible.
    #[test]
    fn setup_global_overlay_without_nat_field_defaults_to_none() {
        let json = r#"{
            "frame": "request",
            "id": 12,
            "request": {
                "op": "setup_global_overlay",
                "deployment": "prod",
                "instance_id": "1",
                "cluster_cidr": "10.200.0.0/16",
                "wg_port": 51820
            }
        }"#;
        let frame: OverlaydFrame = serde_json::from_str(json).expect("deserialize");
        match frame {
            OverlaydFrame::Request {
                request: OverlaydRequest::SetupGlobalOverlay { nat, .. },
                ..
            } => assert!(nat.is_none(), "missing nat field must default to None"),
            other => panic!("expected SetupGlobalOverlay, got {other:?}"),
        }
    }

    /// An `AddPeer` carrying NAT candidates round-trips with the candidate list
    /// intact (the join-time candidate exchange the connect-half relies on).
    #[test]
    fn add_peer_with_candidates_round_trips() {
        roundtrip(&OverlaydFrame::Request {
            id: 40,
            request: OverlaydRequest::AddPeer {
                peer: sample_peer(),
                scope: PeerScope::Global,
            },
        });
    }

    /// The `NatStatus` request and its `NatStatus` response round-trip, including
    /// candidates + per-peer connection types.
    #[test]
    fn nat_status_request_and_response_round_trip() {
        roundtrip(&OverlaydFrame::Request {
            id: 41,
            request: OverlaydRequest::NatStatus,
        });
        roundtrip(&OverlaydFrame::Response {
            id: 41,
            response: OverlaydResponse::NatStatus(NatStatusWire {
                candidates: vec![NatCandidateWire {
                    candidate_type: "host".into(),
                    address: "192.168.1.5:51820".into(),
                    priority: 100,
                }],
                peers: vec![NatPeerWire {
                    node_id: "base64peerkey".into(),
                    connection_type: "hole-punched".into(),
                    remote_endpoint: Some("203.0.113.9:51820".into()),
                }],
                last_refresh: 1_700_000_000,
            }),
        });
        // Empty snapshot round-trips too (default shape).
        roundtrip(&OverlaydFrame::Response {
            id: 42,
            response: OverlaydResponse::NatStatus(NatStatusWire::default()),
        });
    }

    #[test]
    fn service_overlay_response_round_trips_both_shapes() {
        // Shared shape: identity fields are None.
        roundtrip(&OverlaydFrame::Response {
            id: 20,
            response: OverlaydResponse::ServiceOverlay(ServiceOverlayInfo {
                name: "web".into(),
                mode: crate::overlay::OverlayMode::Shared,
                wg_public_key: None,
                wg_port: None,
                overlay_ip: None,
                subnet: None,
            }),
        });
        // Dedicated shape: all identity fields populated.
        roundtrip(&OverlaydFrame::Response {
            id: 21,
            response: OverlaydResponse::ServiceOverlay(ServiceOverlayInfo {
                name: "web".into(),
                mode: crate::overlay::OverlayMode::Dedicated,
                wg_public_key: Some("svc-key".into()),
                wg_port: Some(51821),
                overlay_ip: Some("10.201.0.1".parse().unwrap()),
                subnet: Some("10.201.0.0/24".into()),
            }),
        });
    }

    #[test]
    fn status_snapshot_with_dedicated_service_round_trips() {
        roundtrip(&OverlaydFrame::Response {
            id: 22,
            response: OverlaydResponse::Status(StatusSnapshot {
                interface: Some("zl-overlay0".into()),
                node_ip: Some("10.200.0.1".parse().unwrap()),
                peer_count: 1,
                service_count: 1,
                dedicated_services: vec![DedicatedServiceStatus {
                    service: "web".into(),
                    interface: "zl-svc-web0".into(),
                    public_key: "svc-key".into(),
                    listen_port: 51821,
                    overlay_ip: "10.201.0.1".parse().unwrap(),
                    subnet: "10.201.0.0/24".into(),
                    peer_count: 3,
                }],
                ..StatusSnapshot::default()
            }),
        });
    }

    fn sample_edge_config() -> EdgeConfig {
        EdgeConfig {
            version: EDGE_CONFIG_VERSION,
            name: "ci-runner-7".into(),
            overlay_ip: "10.200.0.9".parse().unwrap(),
            prefix_len: 16,
            private_key: "edge-priv-b64".into(),
            public_key: "edge-pub-b64".into(),
            peers: vec![sample_peer()],
            dns_server: Some("10.200.0.1".parse().unwrap()),
            dns_domain: Some("overlay".into()),
            expires_at_unix: 1_700_000_600,
        }
    }

    #[test]
    fn edge_peer_requests_round_trip() {
        roundtrip(&OverlaydFrame::Request {
            id: 50,
            request: OverlaydRequest::MintEdgePeer {
                name: "ci-runner-7".into(),
                ttl_secs: 600,
                allow: vec!["10.200.0.0/16".into(), "10.201.0.0/24".into()],
                node_endpoint: "203.0.113.7:51820".into(),
            },
        });
        roundtrip(&OverlaydFrame::Request {
            id: 51,
            request: OverlaydRequest::RevokeEdgePeer {
                name: "ci-runner-7".into(),
            },
        });
        roundtrip(&OverlaydFrame::Request {
            id: 52,
            request: OverlaydRequest::ListEdgePeers,
        });
    }

    #[test]
    fn edge_peer_responses_round_trip() {
        roundtrip(&OverlaydFrame::Response {
            id: 50,
            response: OverlaydResponse::EdgeConfig(sample_edge_config()),
        });
        roundtrip(&OverlaydFrame::Response {
            id: 52,
            response: OverlaydResponse::EdgePeers {
                peers: vec![EdgePeerStatus {
                    name: "ci-runner-7".into(),
                    overlay_ip: "10.200.0.9".parse().unwrap(),
                    public_key: "edge-pub-b64".into(),
                    minted_at_unix: 1_700_000_000,
                    expires_at_unix: 1_700_000_600,
                    last_handshake_unix_secs: Some(1_700_000_030),
                    allowed: vec!["10.200.0.0/16".into()],
                }],
            },
        });
        // A never-handshaked, no-grant peer round-trips too (both optional
        // fields skipped on the wire).
        roundtrip(&OverlaydFrame::Response {
            id: 53,
            response: OverlaydResponse::EdgePeers {
                peers: vec![EdgePeerStatus {
                    name: "fresh".into(),
                    overlay_ip: "10.200.0.10".parse().unwrap(),
                    public_key: "k".into(),
                    minted_at_unix: 1_700_000_000,
                    expires_at_unix: 1_700_000_600,
                    last_handshake_unix_secs: None,
                    allowed: vec![],
                }],
            },
        });
    }

    /// A sender that omits `allow` entirely must decode to an empty grant
    /// list (`#[serde(default)]`), proving the field is optional on the wire.
    #[test]
    fn mint_edge_peer_without_allow_defaults_to_empty() {
        let json = r#"{
            "frame": "request",
            "id": 54,
            "request": {
                "op": "mint_edge_peer",
                "name": "ci-runner-7",
                "ttl_secs": 600,
                "node_endpoint": "203.0.113.7:51820"
            }
        }"#;
        let frame: OverlaydFrame = serde_json::from_str(json).expect("deserialize");
        match frame {
            OverlaydFrame::Request {
                request:
                    OverlaydRequest::MintEdgePeer {
                        name,
                        ttl_secs,
                        allow,
                        node_endpoint,
                    },
                ..
            } => {
                assert_eq!(name, "ci-runner-7");
                assert_eq!(ttl_secs, 600);
                assert!(
                    allow.is_empty(),
                    "missing allow field must default to empty"
                );
                assert_eq!(node_endpoint, "203.0.113.7:51820");
            }
            other => panic!("expected MintEdgePeer request, got {other:?}"),
        }
    }

    #[test]
    fn edge_config_token_round_trips() {
        let config = sample_edge_config();
        let token = config.to_token();
        assert!(token.starts_with("zledge1."), "token was {token}");
        let back = EdgeConfig::from_token(&token).expect("decode");
        assert_eq!(config, back);
    }

    #[test]
    fn edge_config_token_rejects_bad_prefix() {
        let err = EdgeConfig::from_token("zledge2.abc").expect_err("must reject");
        assert!(matches!(err, EdgeTokenError::BadPrefix), "got {err:?}");
    }

    #[test]
    fn edge_config_token_rejects_bad_base64() {
        let err = EdgeConfig::from_token("zledge1.!!!not-base64!!!").expect_err("must reject");
        assert!(matches!(err, EdgeTokenError::Decode(_)), "got {err:?}");
    }

    #[test]
    fn edge_config_token_rejects_non_json_payload() {
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        use base64::Engine as _;

        let token = format!("zledge1.{}", URL_SAFE_NO_PAD.encode("not json"));
        let err = EdgeConfig::from_token(&token).expect_err("must reject");
        assert!(matches!(err, EdgeTokenError::Parse(_)), "got {err:?}");
    }

    #[test]
    fn edge_config_token_rejects_wrong_version() {
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        use base64::Engine as _;

        // A future-versioned payload: valid base64 + JSON, but version 2. The
        // version probe must report the mismatch, not a parse error.
        let mut value = serde_json::to_value(sample_edge_config()).expect("to_value");
        value["version"] = serde_json::json!(EDGE_CONFIG_VERSION + 1);
        let token = format!("zledge1.{}", URL_SAFE_NO_PAD.encode(value.to_string()));
        let err = EdgeConfig::from_token(&token).expect_err("must reject");
        assert!(
            matches!(
                err,
                EdgeTokenError::UnsupportedVersion { found } if found == EDGE_CONFIG_VERSION + 1
            ),
            "got {err:?}"
        );
    }
}