koi-certmesh 0.4.1

Zero-config private CA, certificate enrollment, and mesh trust for the local network
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
//! Wire types for certmesh HTTP endpoints.
//!
//! These types define the JSON shapes for join requests/responses
//! and status queries. They are the public API contract.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

use crate::profiles::TrustProfile;
use crate::roster::EnrollmentState;

/// Client request to join the mesh.
///
/// The joining machine must identify itself by hostname so the CA
/// issues a certificate with the correct subject (not the CA’s own
/// hostname).
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct JoinRequest {
    /// Hostname of the machine requesting to join.
    pub hostname: String,
    /// Auth response (TOTP code or FIDO2 assertion).
    pub auth: koi_crypto::auth::AuthResponse,
    /// Optional extra SANs the joiner wants (IP addresses, aliases).
    /// The server always includes `[hostname, hostname.local]`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sans: Vec<String>,
}

/// Server response after successful enrollment.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct JoinResponse {
    pub hostname: String,
    pub ca_cert: String,
    pub service_cert: String,
    pub service_key: String,
    pub ca_fingerprint: String,
    pub cert_path: String,
}

/// Certmesh status overview (returned by GET /status).
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct CertmeshStatus {
    pub ca_initialized: bool,
    pub ca_locked: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ca_fingerprint: Option<String>,
    /// Active authentication method ("totp", "fido2", or absent if uninitialized).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth_method: Option<String>,
    pub profile: TrustProfile,
    pub enrollment_state: EnrollmentState,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enrollment_deadline: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_domain: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_subnet: Option<String>,
    pub member_count: usize,
    pub members: Vec<MemberSummary>,
}

/// Compact member summary for status display.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct MemberSummary {
    pub hostname: String,
    pub role: String,
    pub status: String,
    pub cert_fingerprint: String,
    pub cert_expires: String,
}

/// Descriptor for mDNS self-announcement of the CA.
///
/// Produced by CertmeshCore, consumed by the binary crate to
/// create an mDNS registration via MdnsCore. This avoids a
/// direct dependency between koi-certmesh and koi-mdns.
#[derive(Debug, Clone)]
pub struct CaAnnouncement {
    /// mDNS instance name (e.g. "koi-ca-stone-01").
    pub name: String,
    /// Port the CA is listening on.
    pub port: u16,
    /// TXT record key/value pairs (role, fingerprint, profile).
    pub txt: HashMap<String, String>,
}

/// Request to set a post-renewal reload hook for this host.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct SetHookRequest {
    /// Hostname of the member setting the hook.
    pub hostname: String,
    /// Shell command to run after certificate renewal.
    pub reload: String,
}

/// Response after setting a reload hook.
#[derive(Debug, Serialize, ToSchema)]
pub struct SetHookResponse {
    pub hostname: String,
    pub reload: String,
}

// ── Service Delegation - CA management via HTTP ─────────────────────

/// POST /create request - initialize a new CA via the running service.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct CreateCaRequest {
    /// Passphrase for encrypting the CA key.
    pub passphrase: String,
    /// Hex-encoded 32-byte entropy seed (collected locally by CLI).
    pub entropy_hex: String,
    /// Trust profile for the CA.
    pub profile: TrustProfile,
    /// Optional operator name (required for Organization profile).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operator: Option<String>,
    /// Optional override for initial enrollment state.
    ///
    /// `Some(true)` opens enrollment immediately, `Some(false)` starts closed.
    /// `None` uses the trust profile default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enrollment_open: Option<bool>,
    /// Optional override for whether joins require operator approval.
    ///
    /// `None` uses the trust profile default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub requires_approval: Option<bool>,
    /// Optional hex-encoded TOTP secret.
    ///
    /// When provided by a ceremony-driven client, the server uses this
    /// secret instead of generating one. The client has already shown
    /// the QR code and verified the user's authenticator app.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub totp_secret_hex: Option<String>,
}

/// POST /create response.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct CreateCaResponse {
    /// Auth setup info (TOTP URI or FIDO2 registration result).
    pub auth_setup: koi_crypto::auth::AuthSetup,
    /// SHA-256 fingerprint of the CA certificate.
    pub ca_fingerprint: String,
}

/// POST /unlock request - decrypt the CA key.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct UnlockRequest {
    pub passphrase: String,
}

/// POST /unlock response.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct UnlockResponse {
    pub success: bool,
}

/// POST /auth/rotate request - rotate the enrollment auth credential.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct RotateAuthRequest {
    pub passphrase: String,
    /// Auth method to rotate to. If None, keeps the current method.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
}

/// POST /auth/rotate response.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct RotateAuthResponse {
    /// Setup info for the new auth credential.
    pub auth_setup: koi_crypto::auth::AuthSetup,
}

/// GET /log response - audit log entries.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct AuditLogResponse {
    pub entries: String,
}

/// POST /destroy response - CA and all certmesh state removed.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct DestroyResponse {
    pub destroyed: bool,
}

// ── Phase 5 - Backup/Restore/Revocation ───────────────────────────

/// POST /backup request - create an encrypted backup bundle.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct BackupRequest {
    pub ca_passphrase: String,
    pub backup_passphrase: String,
}

/// POST /backup response - backup encoded as hex.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct BackupResponse {
    pub backup_hex: String,
    pub format: String,
    pub version: u16,
}

/// POST /restore request - restore from an encrypted backup bundle.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct RestoreRequest {
    pub backup_hex: String,
    pub backup_passphrase: String,
    pub new_passphrase: String,
}

/// POST /restore response.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct RestoreResponse {
    pub restored: bool,
}

/// POST /revoke request - revoke a member.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct RevokeRequest {
    pub hostname: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operator: Option<String>,
}

/// POST /revoke response.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct RevokeResponse {
    pub revoked: bool,
}

// ── Phase 4 - Enrollment Policy ─────────────────────────────────────

/// Request to set enrollment scope constraints.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct PolicyRequest {
    /// Domain scope constraint (e.g. "lincoln-elementary.local").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_domain: Option<String>,
    /// Subnet scope constraint as CIDR (e.g. "192.168.1.0/24").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_subnet: Option<String>,
}

/// Request to open the enrollment window.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct OpenEnrollmentRequest {
    /// Optional deadline (RFC 3339). After this time, enrollment auto-closes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deadline: Option<String>,
}

/// Enrollment policy summary for compliance display.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct PolicySummary {
    pub enrollment_state: EnrollmentState,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enrollment_deadline: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_domain: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_subnet: Option<String>,
    pub profile: TrustProfile,
    pub requires_approval: bool,
}

/// Compliance summary response.
#[derive(Debug, Serialize, ToSchema)]
pub struct ComplianceResponse {
    pub policy: PolicySummary,
    pub audit_entries: usize,
}

// ── Phase 3 - Failover + Lifecycle ──────────────────────────────────

/// POST /promote request - auth-verified CA key transfer.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct PromoteRequest {
    pub auth: koi_crypto::auth::AuthResponse,
    /// Client's ephemeral X25519 public key for DH key agreement.
    /// When present, the server encrypts the CA key with the DH-derived
    /// shared key instead of a passphrase, so the passphrase never
    /// traverses the wire.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "optional_byte_array"
    )]
    pub ephemeral_public: Option<[u8; 32]>,
}

/// POST /promote response - encrypted CA key, auth credential, and roster.
///
/// When DH key agreement is used (`ephemeral_public` is present), the
/// CA key material is encrypted with the DH-derived shared key. The
/// standby combines its own ephemeral secret with `ephemeral_public`
/// to derive the same key and decrypt. The passphrase is never sent
/// over the wire.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct PromoteResponse {
    pub encrypted_ca_key: koi_crypto::keys::EncryptedKey,
    /// Serialized auth credential (StoredAuth JSON).
    pub auth_data: serde_json::Value,
    pub roster_json: String,
    pub ca_cert_pem: String,
    /// Server's ephemeral X25519 public key for DH key agreement.
    /// Present only when the client sent an `ephemeral_public` in the request.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "optional_byte_array"
    )]
    pub ephemeral_public: Option<[u8; 32]>,
}

/// POST /renew request - CA pushes renewed cert to a member.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct RenewRequest {
    pub hostname: String,
    pub cert_pem: String,
    pub key_pem: String,
    pub ca_pem: String,
    pub fullchain_pem: String,
    pub fingerprint: String,
    pub expires: String,
}

/// POST /renew response.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct RenewResponse {
    pub hostname: String,
    pub renewed: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hook_result: Option<HookResult>,
}

/// Result of executing a reload hook after cert renewal.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct HookResult {
    pub success: bool,
    pub command: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<String>,
}

/// GET /roster response - signed manifest for standby sync.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct RosterManifest {
    pub roster_json: String,
    pub signature: Vec<u8>,
    pub ca_public_key: String,
}

/// POST /health request - member heartbeat.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct HealthRequest {
    pub hostname: String,
    pub pinned_ca_fingerprint: String,
}

/// POST /health response.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct HealthResponse {
    pub valid: bool,
    pub ca_fingerprint: String,
}

/// Serde helper for `Option<[u8; 32]>` — serializes as a hex string.
mod optional_byte_array {
    use serde::{self, Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(value: &Option<[u8; 32]>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Some(bytes) => {
                let hex = koi_common::encoding::hex_encode(bytes);
                serializer.serialize_str(&hex)
            }
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<[u8; 32]>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let opt: Option<String> = Option::deserialize(deserializer)?;
        match opt {
            Some(hex) => {
                let bytes =
                    koi_common::encoding::hex_decode(&hex).map_err(serde::de::Error::custom)?;
                if bytes.len() != 32 {
                    return Err(serde::de::Error::custom(format!(
                        "expected 32 bytes, got {}",
                        bytes.len()
                    )));
                }
                let mut arr = [0u8; 32];
                arr.copy_from_slice(&bytes);
                Ok(Some(arr))
            }
            None => Ok(None),
        }
    }
}

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

    #[test]
    fn join_request_serde_round_trip() {
        let req = JoinRequest {
            hostname: "stone-05".to_string(),
            auth: koi_crypto::auth::AuthResponse::Totp {
                code: "123456".to_string(),
            },
            sans: vec!["10.0.0.5".to_string()],
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: JoinRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.hostname, "stone-05");
        assert!(
            matches!(parsed.auth, koi_crypto::auth::AuthResponse::Totp { ref code } if code == "123456")
        );
        assert_eq!(parsed.sans, vec!["10.0.0.5"]);
    }

    #[test]
    fn join_request_without_sans_deserializes() {
        // auth field is a tagged enum; sans defaults to empty
        let json = r#"{"hostname":"stone-05","auth":{"method":"totp","code":"123456"}}"#;
        let parsed: JoinRequest = serde_json::from_str(json).unwrap();
        assert_eq!(parsed.hostname, "stone-05");
        assert!(parsed.sans.is_empty());
    }

    #[test]
    fn join_response_serializes() {
        let resp = JoinResponse {
            hostname: "stone-05".to_string(),
            ca_cert: "-----BEGIN CERTIFICATE-----\nca\n-----END CERTIFICATE-----\n".to_string(),
            service_cert: "-----BEGIN CERTIFICATE-----\nsvc\n-----END CERTIFICATE-----\n"
                .to_string(),
            service_key: "-----BEGIN PRIVATE KEY-----\nkey\n-----END PRIVATE KEY-----\n"
                .to_string(),
            ca_fingerprint: "abc123".to_string(),
            cert_path: "/home/koi/.koi/certs/stone-05".to_string(),
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("stone-05"));
        assert!(json.contains("ca_fingerprint"));
    }

    #[test]
    fn set_hook_request_serde_round_trip() {
        let req = SetHookRequest {
            hostname: "stone-01".to_string(),
            reload: "systemctl restart nginx".to_string(),
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: SetHookRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.hostname, "stone-01");
        assert_eq!(parsed.reload, "systemctl restart nginx");
    }

    #[test]
    fn set_hook_response_serializes() {
        let resp = SetHookResponse {
            hostname: "stone-01".to_string(),
            reload: "systemctl restart nginx".to_string(),
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("stone-01"));
        assert!(json.contains("systemctl restart nginx"));
    }

    #[test]
    fn ca_announcement_has_correct_fields() {
        use std::collections::HashMap;
        let mut txt = HashMap::new();
        txt.insert("role".to_string(), "primary".to_string());
        txt.insert("profile".to_string(), "just_me".to_string());

        let ann = CaAnnouncement {
            name: "koi-ca-stone-01".to_string(),
            port: 5641,
            txt,
        };
        assert_eq!(ann.name, "koi-ca-stone-01");
        assert_eq!(ann.port, 5641);
        assert_eq!(ann.txt.get("role").unwrap(), "primary");
    }

    // ── Phase 3 serde tests ──────────────────────────────────────────

    #[test]
    fn promote_request_serde_round_trip() {
        let req = PromoteRequest {
            auth: koi_crypto::auth::AuthResponse::Totp {
                code: "654321".to_string(),
            },
            ephemeral_public: None,
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: PromoteRequest = serde_json::from_str(&json).unwrap();
        assert!(
            matches!(parsed.auth, koi_crypto::auth::AuthResponse::Totp { ref code } if code == "654321")
        );
        assert!(parsed.ephemeral_public.is_none());
    }

    #[test]
    fn promote_request_with_ephemeral_public_round_trip() {
        let pub_key = [42u8; 32];
        let req = PromoteRequest {
            auth: koi_crypto::auth::AuthResponse::Totp {
                code: "654321".to_string(),
            },
            ephemeral_public: Some(pub_key),
        };
        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("ephemeral_public"));
        let parsed: PromoteRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.ephemeral_public, Some(pub_key));
    }

    #[test]
    fn promote_response_serde_round_trip() {
        let resp = PromoteResponse {
            encrypted_ca_key: koi_crypto::keys::EncryptedKey {
                ciphertext: vec![1, 2, 3],
                salt: vec![4, 5, 6],
                nonce: vec![7, 8, 9],
                kdf_params: Default::default(),
            },
            auth_data: serde_json::json!({"method": "totp", "encrypted_secret": {"ciphertext": [10], "salt": [11], "nonce": [12]}}),
            roster_json: r#"{"metadata":{}}"#.to_string(),
            ca_cert_pem: "-----BEGIN CERTIFICATE-----\nca\n-----END CERTIFICATE-----\n".to_string(),
            ephemeral_public: None,
        };
        let json = serde_json::to_string(&resp).unwrap();
        let parsed: PromoteResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.encrypted_ca_key.ciphertext, vec![1, 2, 3]);
        assert_eq!(parsed.ca_cert_pem.len(), resp.ca_cert_pem.len());
        assert!(parsed.ephemeral_public.is_none());
    }

    #[test]
    fn promote_response_with_ephemeral_public_round_trip() {
        let server_pub = [99u8; 32];
        let resp = PromoteResponse {
            encrypted_ca_key: koi_crypto::keys::EncryptedKey {
                ciphertext: vec![1, 2, 3],
                salt: vec![4, 5, 6],
                nonce: vec![7, 8, 9],
                kdf_params: Default::default(),
            },
            auth_data: serde_json::json!({"method": "totp"}),
            roster_json: "{}".to_string(),
            ca_cert_pem: "cert".to_string(),
            ephemeral_public: Some(server_pub),
        };
        let json = serde_json::to_string(&resp).unwrap();
        let parsed: PromoteResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.ephemeral_public, Some(server_pub));
    }

    #[test]
    fn renew_request_serde_round_trip() {
        let req = RenewRequest {
            hostname: "stone-05".to_string(),
            cert_pem: "cert".to_string(),
            key_pem: "key".to_string(),
            ca_pem: "ca".to_string(),
            fullchain_pem: "chain".to_string(),
            fingerprint: "abc123".to_string(),
            expires: "2026-03-15T00:00:00Z".to_string(),
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: RenewRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.hostname, "stone-05");
        assert_eq!(parsed.fingerprint, "abc123");
    }

    #[test]
    fn renew_response_serde_round_trip() {
        let resp = RenewResponse {
            hostname: "stone-05".to_string(),
            renewed: true,
            hook_result: Some(HookResult {
                success: true,
                command: "systemctl reload nginx".to_string(),
                output: Some("OK".to_string()),
            }),
        };
        let json = serde_json::to_string(&resp).unwrap();
        let parsed: RenewResponse = serde_json::from_str(&json).unwrap();
        assert!(parsed.renewed);
        assert!(parsed.hook_result.unwrap().success);
    }

    #[test]
    fn renew_response_omits_none_hook_result() {
        let resp = RenewResponse {
            hostname: "stone-05".to_string(),
            renewed: true,
            hook_result: None,
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(!json.contains("hook_result"));
    }

    #[test]
    fn hook_result_omits_none_output() {
        let hr = HookResult {
            success: false,
            command: "bad-cmd".to_string(),
            output: None,
        };
        let json = serde_json::to_string(&hr).unwrap();
        assert!(!json.contains("output"));
    }

    #[test]
    fn roster_manifest_serde_round_trip() {
        let manifest = RosterManifest {
            roster_json: r#"{"members":[]}"#.to_string(),
            signature: vec![1, 2, 3, 4, 5],
            ca_public_key: "-----BEGIN PUBLIC KEY-----\ntest\n-----END PUBLIC KEY-----\n"
                .to_string(),
        };
        let json = serde_json::to_string(&manifest).unwrap();
        let parsed: RosterManifest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.signature, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn health_request_serde_round_trip() {
        let req = HealthRequest {
            hostname: "stone-05".to_string(),
            pinned_ca_fingerprint: "abcdef".to_string(),
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: HealthRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.hostname, "stone-05");
        assert_eq!(parsed.pinned_ca_fingerprint, "abcdef");
    }

    #[test]
    fn health_response_serde_round_trip() {
        let resp = HealthResponse {
            valid: true,
            ca_fingerprint: "cafp123".to_string(),
        };
        let json = serde_json::to_string(&resp).unwrap();
        let parsed: HealthResponse = serde_json::from_str(&json).unwrap();
        assert!(parsed.valid);
        assert_eq!(parsed.ca_fingerprint, "cafp123");
    }

    // ── Phase 2 tests ──────────────────────────────────────────────────

    #[test]
    fn certmesh_status_serializes() {
        let status = CertmeshStatus {
            ca_initialized: true,
            ca_locked: false,
            ca_fingerprint: Some("abc123".to_string()),
            auth_method: None,
            profile: TrustProfile::JustMe,
            enrollment_state: EnrollmentState::Open,
            enrollment_deadline: None,
            allowed_domain: None,
            allowed_subnet: None,
            member_count: 1,
            members: vec![MemberSummary {
                hostname: "stone-01".to_string(),
                role: "primary".to_string(),
                status: "active".to_string(),
                cert_fingerprint: "abc".to_string(),
                cert_expires: "2026-03-13T00:00:00Z".to_string(),
            }],
        };
        let json = serde_json::to_string(&status).unwrap();
        assert!(json.contains("\"ca_initialized\":true"));
        assert!(json.contains("\"member_count\":1"));
    }

    #[test]
    fn certmesh_status_omits_none_policy_fields() {
        let status = CertmeshStatus {
            ca_initialized: true,
            ca_locked: false,
            ca_fingerprint: None,
            auth_method: None,
            profile: TrustProfile::JustMe,
            enrollment_state: EnrollmentState::Open,
            enrollment_deadline: None,
            allowed_domain: None,
            allowed_subnet: None,
            member_count: 0,
            members: vec![],
        };
        let json = serde_json::to_string(&status).unwrap();
        assert!(!json.contains("enrollment_deadline"));
        assert!(!json.contains("allowed_domain"));
        assert!(!json.contains("allowed_subnet"));
    }

    #[test]
    fn certmesh_status_includes_policy_when_set() {
        let status = CertmeshStatus {
            ca_initialized: true,
            ca_locked: false,
            ca_fingerprint: Some("fp-org".to_string()),
            auth_method: None,
            profile: TrustProfile::MyOrganization,
            enrollment_state: EnrollmentState::Closed,
            enrollment_deadline: Some("2026-03-01T00:00:00Z".to_string()),
            allowed_domain: Some("school.local".to_string()),
            allowed_subnet: Some("10.0.0.0/8".to_string()),
            member_count: 0,
            members: vec![],
        };
        let json = serde_json::to_string(&status).unwrap();
        assert!(json.contains("enrollment_deadline"));
        assert!(json.contains("school.local"));
        assert!(json.contains("10.0.0.0/8"));
    }

    // ── Phase 4 serde tests ──────────────────────────────────────────

    #[test]
    fn policy_request_serde_round_trip() {
        let req = PolicyRequest {
            allowed_domain: Some("lab.local".to_string()),
            allowed_subnet: Some("192.168.1.0/24".to_string()),
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: PolicyRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.allowed_domain.as_deref(), Some("lab.local"));
        assert_eq!(parsed.allowed_subnet.as_deref(), Some("192.168.1.0/24"));
    }

    #[test]
    fn policy_request_omits_none_fields() {
        let req = PolicyRequest {
            allowed_domain: None,
            allowed_subnet: None,
        };
        let json = serde_json::to_string(&req).unwrap();
        assert!(!json.contains("allowed_domain"));
        assert!(!json.contains("allowed_subnet"));
    }

    #[test]
    fn open_enrollment_request_serde_round_trip() {
        let req = OpenEnrollmentRequest {
            deadline: Some("2026-03-01T00:00:00Z".to_string()),
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: OpenEnrollmentRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.deadline.as_deref(), Some("2026-03-01T00:00:00Z"));
    }

    // ── Service delegation serde tests ──────────────────────────────

    #[test]
    fn create_ca_request_serde_round_trip() {
        let req = CreateCaRequest {
            passphrase: "hunter2".to_string(),
            entropy_hex: "0a1b2c3d".to_string(),
            profile: TrustProfile::JustMe,
            operator: None,
            enrollment_open: None,
            requires_approval: None,
            totp_secret_hex: None,
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: CreateCaRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.passphrase, "hunter2");
        assert_eq!(parsed.entropy_hex, "0a1b2c3d");
        assert_eq!(parsed.profile, TrustProfile::JustMe);
        assert!(parsed.operator.is_none());
        assert!(parsed.enrollment_open.is_none());
        assert!(parsed.requires_approval.is_none());
    }

    #[test]
    fn create_ca_request_with_operator() {
        let req = CreateCaRequest {
            passphrase: "pass".to_string(),
            entropy_hex: "ff".to_string(),
            profile: TrustProfile::MyOrganization,
            operator: Some("ops@acme.com".to_string()),
            enrollment_open: Some(false),
            requires_approval: Some(true),
            totp_secret_hex: None,
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: CreateCaRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.operator.as_deref(), Some("ops@acme.com"));
        assert_eq!(parsed.profile, TrustProfile::MyOrganization);
        assert_eq!(parsed.enrollment_open, Some(false));
        assert_eq!(parsed.requires_approval, Some(true));
    }

    #[test]
    fn create_ca_request_omits_none_operator() {
        let req = CreateCaRequest {
            passphrase: "p".to_string(),
            entropy_hex: "aa".to_string(),
            profile: TrustProfile::JustMe,
            operator: None,
            enrollment_open: None,
            requires_approval: None,
            totp_secret_hex: None,
        };
        let json = serde_json::to_string(&req).unwrap();
        assert!(!json.contains("operator"));
        assert!(!json.contains("enrollment_open"));
        assert!(!json.contains("requires_approval"));
    }

    #[test]
    fn create_ca_response_serde_round_trip() {
        let resp = CreateCaResponse {
            auth_setup: koi_crypto::auth::AuthSetup::Totp {
                totp_uri: "otpauth://totp/Koi:admin?secret=ABC123".to_string(),
            },
            ca_fingerprint: "sha256:abcdef".to_string(),
        };
        let json = serde_json::to_string(&resp).unwrap();
        let parsed: CreateCaResponse = serde_json::from_str(&json).unwrap();
        assert!(json.contains("ABC123"));
        assert_eq!(parsed.ca_fingerprint, "sha256:abcdef");
    }

    #[test]
    fn unlock_request_serde_round_trip() {
        let req = UnlockRequest {
            passphrase: "my-secret".to_string(),
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: UnlockRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.passphrase, "my-secret");
    }

    #[test]
    fn unlock_response_serde_round_trip() {
        let resp = UnlockResponse { success: true };
        let json = serde_json::to_string(&resp).unwrap();
        let parsed: UnlockResponse = serde_json::from_str(&json).unwrap();
        assert!(parsed.success);
    }

    #[test]
    fn rotate_auth_request_serde_round_trip() {
        let req = RotateAuthRequest {
            passphrase: "rotate-pass".to_string(),
            method: None,
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: RotateAuthRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.passphrase, "rotate-pass");
    }

    #[test]
    fn rotate_auth_response_serde_round_trip() {
        let resp = RotateAuthResponse {
            auth_setup: koi_crypto::auth::AuthSetup::Totp {
                totp_uri: "otpauth://totp/Koi:admin?secret=NEWBASE32".to_string(),
            },
        };
        let json = serde_json::to_string(&resp).unwrap();
        let _: RotateAuthResponse = serde_json::from_str(&json).unwrap();
        assert!(json.contains("NEWBASE32"));
    }

    #[test]
    fn audit_log_response_serde_round_trip() {
        let resp = AuditLogResponse {
            entries: "2026-02-11T00:00:00Z pond_initialized\n".to_string(),
        };
        let json = serde_json::to_string(&resp).unwrap();
        let parsed: AuditLogResponse = serde_json::from_str(&json).unwrap();
        assert!(parsed.entries.contains("pond_initialized"));
    }

    #[test]
    fn destroy_response_serde_round_trip() {
        let resp = DestroyResponse { destroyed: true };
        let json = serde_json::to_string(&resp).unwrap();
        let parsed: DestroyResponse = serde_json::from_str(&json).unwrap();
        assert!(parsed.destroyed);
    }

    #[test]
    fn certmesh_status_serde_round_trip() {
        let status = CertmeshStatus {
            ca_initialized: true,
            ca_locked: false,
            ca_fingerprint: Some("fp-round-trip".to_string()),
            auth_method: None,
            profile: TrustProfile::MyTeam,
            enrollment_state: EnrollmentState::Open,
            enrollment_deadline: Some("2026-03-01T00:00:00Z".to_string()),
            allowed_domain: None,
            allowed_subnet: None,
            member_count: 2,
            members: vec![
                MemberSummary {
                    hostname: "stone-01".to_string(),
                    role: "primary".to_string(),
                    status: "active".to_string(),
                    cert_fingerprint: "fp1".to_string(),
                    cert_expires: "2026-06-01".to_string(),
                },
                MemberSummary {
                    hostname: "stone-02".to_string(),
                    role: "member".to_string(),
                    status: "active".to_string(),
                    cert_fingerprint: "fp2".to_string(),
                    cert_expires: "2026-06-01".to_string(),
                },
            ],
        };
        let json = serde_json::to_string(&status).unwrap();
        let parsed: CertmeshStatus = serde_json::from_str(&json).unwrap();
        assert!(parsed.ca_initialized);
        assert!(!parsed.ca_locked);
        assert_eq!(parsed.profile, TrustProfile::MyTeam);
        assert_eq!(parsed.member_count, 2);
        assert_eq!(parsed.members.len(), 2);
        assert_eq!(parsed.members[0].hostname, "stone-01");
        assert_eq!(parsed.members[1].hostname, "stone-02");
    }

    #[test]
    fn certmesh_status_uninitialized_round_trip() {
        let status = CertmeshStatus {
            ca_initialized: false,
            ca_locked: false,
            ca_fingerprint: None,
            auth_method: None,
            profile: TrustProfile::JustMe,
            enrollment_state: EnrollmentState::Closed,
            enrollment_deadline: None,
            allowed_domain: None,
            allowed_subnet: None,
            member_count: 0,
            members: vec![],
        };
        let json = serde_json::to_string(&status).unwrap();
        let parsed: CertmeshStatus = serde_json::from_str(&json).unwrap();
        assert!(!parsed.ca_initialized);
        assert_eq!(parsed.member_count, 0);
        assert!(parsed.members.is_empty());
    }

    #[test]
    fn policy_summary_serializes() {
        let summary = PolicySummary {
            enrollment_state: EnrollmentState::Open,
            enrollment_deadline: Some("2026-03-01T00:00:00Z".to_string()),
            allowed_domain: Some("school.local".to_string()),
            allowed_subnet: None,
            profile: TrustProfile::MyOrganization,
            requires_approval: true,
        };
        let json = serde_json::to_string(&summary).unwrap();
        assert!(json.contains("requires_approval"));
        assert!(json.contains("school.local"));
        assert!(!json.contains("allowed_subnet"));
    }
}