koi-certmesh 0.5.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
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
//! 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 serde::{Deserialize, Serialize};
use utoipa::ToSchema;

use crate::roster::{CertPolicy, 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). Absent when enrolling with an invite token.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth: Option<koi_crypto::auth::AuthResponse>,
    /// Single-use, hostname-bound enrollment invite token (ADR-015 F2).
    /// Mutually exclusive with `auth`; when present it is the join credential.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub invite_token: Option<String>,
    /// PKCS#10 CSR (PEM) generated by the joining member (ADR-015 F1).
    ///
    /// The member generates its own keypair and sends only this CSR — the CA
    /// signs it and **never sees the private key**. Required for remote
    /// enrollment; the CA refuses to generate member keys server-side.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub csr: Option<String>,
    /// 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>,
}

/// Request to mint an enrollment invite token (operator-only, DAT-gated).
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct InviteRequest {
    /// Hostname the invite authorizes (bound at mint time).
    pub hostname: String,
    /// Time-to-live in minutes. Non-positive falls back to the default (60).
    #[serde(default)]
    pub ttl_mins: i64,
}

/// Response carrying a freshly minted invite token (returned exactly once).
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct InviteResponse {
    /// The one-time invite **code** — deliver to the joining host out of band.
    ///
    /// The code is `<secret>.<ca_fingerprint>` (ADR-017 F3): the joiner pins the
    /// embedded fingerprint and preflights the CA before sending its CSR, and the
    /// CA consumes only the secret half. The plaintext secret exists only here.
    pub token: String,
    /// Hostname this invite is bound to.
    pub hostname: String,
    /// RFC 3339 absolute expiry.
    pub expires_at: String,
    /// The CA fingerprint embedded in the invite code (also carried separately for
    /// JSON consumers). The joiner pins this and aborts the join if the CA it
    /// reaches advertises a different fingerprint (ADR-017 F3).
    pub ca_fingerprint: String,
}

// ── Member-side key custody (ADR-015 F1, local daemon endpoints) ─────

/// Ask the local daemon to generate this member's keypair and a CSR.
///
/// The daemon generates the keypair, persists the private key locally (0600),
/// and returns only the CSR — the key never leaves the daemon, and the CLI
/// never sees it.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct MemberCsrRequest {
    /// Hostname (subject CN) for the member certificate.
    pub hostname: String,
    /// Extra SANs the member wants in its cert (IPs/aliases).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sans: Vec<String>,
}

/// Response carrying the member's CSR (PEM). The private key stays on the daemon.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct MemberCsrResponse {
    pub csr: String,
}

/// Ask the local daemon to install a CA-signed cert next to the member key.
///
/// When `ca_endpoint` + `ca_fingerprint` are supplied (the normal join flow), the
/// daemon also persists the **member renewal state** (`certmesh/member.json`) so
/// the background loop can later pull a rotate-key renewal from the CA over mTLS
/// (ADR-017 F6). They are optional so a bare cert install (e.g. re-install) still
/// works without re-arming renewal.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct InstallCertRequest {
    /// Hostname whose key was prepared via [`MemberCsrRequest`].
    pub hostname: String,
    /// The CA-signed leaf certificate (PEM).
    pub cert_pem: String,
    /// The CA root certificate (PEM) to install + trust.
    pub ca_pem: String,
    /// The CA endpoint the joiner reached (e.g. `http://ca-host:5641`). The host
    /// component is the mTLS renewal target. Absent → renewal state not armed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ca_endpoint: Option<String>,
    /// The pinned CA fingerprint (from the join response). Absent → not armed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ca_fingerprint: Option<String>,
    /// SANs the member requested (persisted so renewal CSRs carry the same set).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sans: Vec<String>,
    /// CA-held lifecycle policy from the join response (drives the renew schedule).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy: Option<CertPolicy>,
}

/// Response after installing the member cert locally.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct InstallCertResponse {
    pub installed: bool,
    pub cert_path: 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,
    /// The member private key. **Empty** for the CSR-based flow (ADR-015 F1) —
    /// the member generated and kept its own key, so the CA has nothing to
    /// return here. Only ever populated by the legacy CA-generates path.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub service_key: String,
    pub ca_fingerprint: String,
    /// Path where the CA wrote cert files, if any. Empty for CSR-based joins —
    /// the member persists its own cert locally.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub cert_path: String,
    /// CA-held lifecycle policy (ADR-017). The member persists this so its
    /// background loop renews on the CA's schedule (`renew_threshold_days`) and
    /// knows its grace window (`grace_days`). Phase 2's signed bundle refreshes it.
    #[serde(default)]
    pub policy: CertPolicy,
}

/// Certmesh status overview (returned by GET /status).
///
/// The security posture is reported as the two real booleans
/// (`enrollment_open`, `requires_approval`); `enrollment_state` is the
/// open/closed wire enum derived from `enrollment_open`.
#[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", or absent if uninitialized).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth_method: Option<String>,
    /// Whether the mesh is currently accepting new members.
    pub enrollment_open: bool,
    /// Whether joins require operator approval at the CA.
    pub requires_approval: bool,
    pub enrollment_state: EnrollmentState,
    pub member_count: usize,
    /// Monotonic roster sequence (ADR-017 F8) — the trust bundle's `seq`.
    #[serde(default)]
    pub seq: u64,
    /// CA-held certificate lifecycle policy (ADR-017).
    #[serde(default)]
    pub policy: CertPolicy,
    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,
}

/// 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.
///
/// The security posture is carried as the two real booleans the roster
/// stores (`enrollment_open`, `requires_approval`) plus `auto_unlock`, the
/// create-time decision of whether to save the passphrase to the vault so
/// the daemon boots unlocked. The named presets are resolved to these
/// booleans by the ceremony/CLI before this request is built.
#[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,
    /// Optional operator name (recorded in the audit log).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operator: Option<String>,
    /// Whether the mesh starts accepting new members.
    #[serde(default)]
    pub enrollment_open: bool,
    /// Whether joins require operator approval at the CA.
    #[serde(default)]
    pub requires_approval: bool,
    /// Whether to save the passphrase to the vault for automatic unlock on boot.
    #[serde(default)]
    pub auto_unlock: 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).
    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,
}

/// Enrollment toggle summary (open/close-enrollment responses).
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct EnrollmentSummary {
    pub enrollment_state: EnrollmentState,
}

// ── 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 — **member-initiated, CSR-only** rotate-key renewal
/// (ADR-017 F6). The member generates a fresh keypair locally and sends only the
/// CSR over mTLS; the CA signs it. The CA **never** generates or receives a
/// member private key, on enroll *or* renew. Authorized by the mTLS client cert
/// (the caller's CN must equal `hostname`).
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct RenewRequest {
    pub hostname: String,
    /// PKCS#10 CSR (PEM) for the member's freshly rotated keypair.
    pub csr: String,
}

/// POST /renew response — the CA-signed leaf (no private key).
///
/// The member installs the leaf next to its locally held new key and runs its own
/// reload hook; the CA performs no hook execution on the member's behalf.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct RenewResponse {
    pub hostname: String,
    /// The renewed CA-signed leaf certificate (PEM).
    pub service_cert: String,
    /// The CA root certificate (PEM).
    pub ca_cert: String,
    /// The CA fingerprint, for the member to cross-check against its pin.
    pub ca_fingerprint: String,
    /// RFC 3339 absolute expiry of the renewed leaf.
    pub expires: String,
}

/// 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>,
}

/// 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: "node-05".to_string(),
            auth: Some(koi_crypto::auth::AuthResponse::Totp {
                code: "123456".to_string(),
            }),
            invite_token: None,
            csr: None,
            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, "node-05");
        assert!(
            matches!(parsed.auth, Some(koi_crypto::auth::AuthResponse::Totp { ref code }) if code == "123456")
        );
        assert!(parsed.invite_token.is_none());
        assert_eq!(parsed.sans, vec!["10.0.0.5"]);
    }

    #[test]
    fn join_request_with_invite_token_round_trip() {
        let json = r#"{"hostname":"node-06","invite_token":"deadbeef"}"#;
        let parsed: JoinRequest = serde_json::from_str(json).unwrap();
        assert_eq!(parsed.hostname, "node-06");
        assert!(parsed.auth.is_none());
        assert_eq!(parsed.invite_token.as_deref(), Some("deadbeef"));
        assert!(parsed.sans.is_empty());
        // Re-serialization omits the absent auth field (happy path = no nulls).
        let reser = serde_json::to_string(&parsed).unwrap();
        assert!(!reser.contains("\"auth\""));
    }

    #[test]
    fn join_request_with_csr_round_trip() {
        let json = r#"{"hostname":"web-01","invite_token":"deadbeef","csr":"-----BEGIN CERTIFICATE REQUEST-----\nx\n-----END CERTIFICATE REQUEST-----\n"}"#;
        let parsed: JoinRequest = serde_json::from_str(json).unwrap();
        assert!(parsed
            .csr
            .as_deref()
            .unwrap()
            .contains("CERTIFICATE REQUEST"));
        assert!(parsed.auth.is_none());
    }

    #[test]
    fn member_csr_request_round_trip() {
        let parsed: MemberCsrRequest =
            serde_json::from_str(r#"{"hostname":"web-01","sans":["10.0.0.9"]}"#).unwrap();
        assert_eq!(parsed.hostname, "web-01");
        assert_eq!(parsed.sans, vec!["10.0.0.9"]);
        // sans defaults to empty.
        let bare: MemberCsrRequest = serde_json::from_str(r#"{"hostname":"web-01"}"#).unwrap();
        assert!(bare.sans.is_empty());
    }

    #[test]
    fn install_cert_request_round_trip() {
        let req = InstallCertRequest {
            hostname: "web-01".to_string(),
            cert_pem: "CERT".to_string(),
            ca_pem: "CA".to_string(),
            ca_endpoint: Some("http://ca-host:5641".to_string()),
            ca_fingerprint: Some("deadbeef".to_string()),
            sans: vec!["web-01".to_string()],
            policy: Some(CertPolicy::default()),
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: InstallCertRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.hostname, "web-01");
        assert_eq!(parsed.cert_pem, "CERT");
        assert_eq!(parsed.ca_endpoint.as_deref(), Some("http://ca-host:5641"));
        assert_eq!(parsed.ca_fingerprint.as_deref(), Some("deadbeef"));

        // Bare install (no renewal coords) still round-trips.
        let bare: InstallCertRequest =
            serde_json::from_str(r#"{"hostname":"web-01","cert_pem":"C","ca_pem":"CA"}"#).unwrap();
        assert!(bare.ca_endpoint.is_none());
        assert!(bare.policy.is_none());
    }

    #[test]
    fn invite_request_defaults_ttl() {
        let parsed: InviteRequest = serde_json::from_str(r#"{"hostname":"web-01"}"#).unwrap();
        assert_eq!(parsed.hostname, "web-01");
        assert_eq!(parsed.ttl_mins, 0);
    }

    #[test]
    fn invite_response_round_trip() {
        let resp = InviteResponse {
            token: "abc123.deadbeef".to_string(),
            hostname: "web-01".to_string(),
            expires_at: "2026-06-18T12:00:00Z".to_string(),
            ca_fingerprint: "deadbeef".to_string(),
        };
        let json = serde_json::to_string(&resp).unwrap();
        let parsed: InviteResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.token, "abc123.deadbeef");
        assert_eq!(parsed.hostname, "web-01");
        assert_eq!(parsed.ca_fingerprint, "deadbeef");
    }

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

    #[test]
    fn join_response_serializes() {
        let resp = JoinResponse {
            hostname: "node-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/node-05".to_string(),
            policy: CertPolicy::default(),
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("node-05"));
        assert!(json.contains("ca_fingerprint"));
    }

    #[test]
    fn set_hook_request_serde_round_trip() {
        let req = SetHookRequest {
            hostname: "node-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, "node-01");
        assert_eq!(parsed.reload, "systemctl restart nginx");
    }

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

    // ── 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_is_csr_only_no_key() {
        // ADR-017 F6: the renewal request carries ONLY a CSR — never a private
        // key. The struct has no `key_pem` field; assert the wire shape too.
        let req = RenewRequest {
            hostname: "node-05".to_string(),
            csr: "-----BEGIN CERTIFICATE REQUEST-----\nx\n-----END CERTIFICATE REQUEST-----\n"
                .to_string(),
        };
        let json = serde_json::to_string(&req).unwrap();
        assert!(
            !json.contains("key"),
            "renew request must never carry a key"
        );
        let parsed: RenewRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.hostname, "node-05");
        assert!(parsed.csr.contains("CERTIFICATE REQUEST"));
    }

    #[test]
    fn renew_response_carries_cert_not_key() {
        let resp = RenewResponse {
            hostname: "node-05".to_string(),
            service_cert: "-----BEGIN CERTIFICATE-----\nsvc\n-----END CERTIFICATE-----\n"
                .to_string(),
            ca_cert: "-----BEGIN CERTIFICATE-----\nca\n-----END CERTIFICATE-----\n".to_string(),
            ca_fingerprint: "abc123".to_string(),
            expires: "2026-09-15T00:00:00Z".to_string(),
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(
            !json.contains("PRIVATE KEY"),
            "renew response must never carry a private key"
        );
        let parsed: RenewResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.hostname, "node-05");
        assert!(parsed.service_cert.contains("BEGIN CERTIFICATE"));
        assert_eq!(parsed.ca_fingerprint, "abc123");
    }

    #[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 health_request_serde_round_trip() {
        let req = HealthRequest {
            hostname: "node-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, "node-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,
            enrollment_open: true,
            requires_approval: false,
            enrollment_state: EnrollmentState::Open,
            member_count: 1,
            seq: 0,
            policy: CertPolicy::default(),
            members: vec![MemberSummary {
                hostname: "node-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"));
        assert!(json.contains("\"enrollment_open\":true"));
        assert!(json.contains("\"requires_approval\":false"));
    }

    #[test]
    fn certmesh_status_reports_posture_booleans() {
        let status = CertmeshStatus {
            ca_initialized: true,
            ca_locked: false,
            ca_fingerprint: Some("fp-org".to_string()),
            auth_method: None,
            enrollment_open: false,
            requires_approval: true,
            enrollment_state: EnrollmentState::Closed,
            member_count: 0,
            seq: 0,
            policy: CertPolicy::default(),
            members: vec![],
        };
        let json = serde_json::to_string(&status).unwrap();
        assert!(json.contains("\"enrollment_open\":false"));
        assert!(json.contains("\"requires_approval\":true"));
        assert!(json.contains("\"enrollment_state\":\"closed\""));
    }

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

    #[test]
    fn create_ca_request_serde_round_trip() {
        let req = CreateCaRequest {
            passphrase: "hunter2".to_string(),
            entropy_hex: "0a1b2c3d".to_string(),
            operator: None,
            enrollment_open: true,
            requires_approval: false,
            auto_unlock: 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.passphrase, "hunter2");
        assert_eq!(parsed.entropy_hex, "0a1b2c3d");
        assert!(parsed.operator.is_none());
        assert!(parsed.enrollment_open);
        assert!(!parsed.requires_approval);
        assert!(parsed.auto_unlock);
    }

    #[test]
    fn create_ca_request_with_operator() {
        let req = CreateCaRequest {
            passphrase: "pass".to_string(),
            entropy_hex: "ff".to_string(),
            operator: Some("ops@acme.com".to_string()),
            enrollment_open: false,
            requires_approval: true,
            auto_unlock: false,
            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!(!parsed.enrollment_open);
        assert!(parsed.requires_approval);
        assert!(!parsed.auto_unlock);
    }

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

    #[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 ca_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("ca_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,
            enrollment_open: true,
            requires_approval: true,
            enrollment_state: EnrollmentState::Open,
            member_count: 2,
            seq: 5,
            policy: CertPolicy::default(),
            members: vec![
                MemberSummary {
                    hostname: "node-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: "node-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!(parsed.enrollment_open);
        assert!(parsed.requires_approval);
        assert_eq!(parsed.member_count, 2);
        assert_eq!(parsed.members.len(), 2);
        assert_eq!(parsed.members[0].hostname, "node-01");
        assert_eq!(parsed.members[1].hostname, "node-02");
    }

    #[test]
    fn certmesh_status_uninitialized_round_trip() {
        let status = CertmeshStatus {
            ca_initialized: false,
            ca_locked: false,
            ca_fingerprint: None,
            auth_method: None,
            enrollment_open: false,
            requires_approval: false,
            enrollment_state: EnrollmentState::Closed,
            member_count: 0,
            seq: 0,
            policy: CertPolicy::default(),
            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 enrollment_summary_serializes() {
        let summary = EnrollmentSummary {
            enrollment_state: EnrollmentState::Open,
        };
        let json = serde_json::to_string(&summary).unwrap();
        assert!(json.contains("\"enrollment_state\":\"open\""));
    }
}