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
//! Promotion, roster sync, and failover detection.
//!
//! - **Promotion**: transfers the encrypted CA key + auth credential to a standby.
//! - **Roster sync**: standby periodically pulls a signed roster manifest.
//! - **Failover detection**: monitors mDNS presence; after grace period,
//!   standby with the lowest hostname takes over.

use std::time::{Duration, Instant};

use koi_crypto::auth::AuthState;
use koi_crypto::key_agreement::EphemeralKeyPair;
use koi_crypto::keys::{self, CaKeyPair};
use koi_crypto::signing;
use zeroize::Zeroize;

use crate::ca::CaState;
use crate::error::CertmeshError;
use crate::protocol::{PromoteResponse, RosterManifest};
use crate::roster::Roster;

/// Grace period before a standby considers the primary dead.
pub const FAILOVER_GRACE_SECS: u64 = 60;

/// How often the standby syncs the roster from the primary.
pub const ROSTER_SYNC_INTERVAL_SECS: u64 = 300; // 5 minutes

// ── Promotion ──────────────────────────────────────────────────────

/// Package the CA key, auth credential, roster, and CA cert for transfer to a standby.
///
/// When `client_public_key` is provided, the server generates its own
/// ephemeral X25519 key pair, derives a shared key via Diffie-Hellman,
/// and encrypts the CA key material with that shared key. The standby
/// combines its own ephemeral secret with the server's public key to
/// derive the same shared key locally -- the passphrase never crosses
/// the wire.
///
/// The `client_public_key` is required — promotion without DH key
/// agreement is not supported.
pub fn prepare_promotion(
    ca: &CaState,
    auth_state: &AuthState,
    roster: &Roster,
    client_public_key: &[u8; 32],
) -> Result<PromoteResponse, CertmeshError> {
    let server_kp = EphemeralKeyPair::generate();
    let server_pub = server_kp.public_key_bytes();
    let mut shared_key = server_kp
        .derive_shared_key(client_public_key)
        .map_err(|e| CertmeshError::PromotionFailed(format!("key derivation: {e}")))?;
    let shared_key_hex =
        koi_crypto::secret::SecretString::new(koi_common::encoding::hex_encode(&shared_key));
    shared_key.zeroize();
    let encrypted_ca_key = keys::encrypt_key(&ca.key, shared_key_hex.as_ref())?;

    // Serialize auth state for transfer.
    //
    // Auth data is encrypted with the DH-derived shared key (same key
    // that protects the CA key). The standby derives the same shared key
    // from the DH exchange and decrypts both CA key and auth state.
    let auth_data = match auth_state {
        AuthState::Totp(secret) => {
            let encrypted_totp = koi_crypto::totp::encrypt_secret(secret, shared_key_hex.as_ref())?;
            serde_json::to_value(&koi_crypto::auth::StoredAuth::Totp {
                encrypted_secret: encrypted_totp,
            })
            .map_err(|e| CertmeshError::Internal(format!("auth serialize: {e}")))?
        }
        AuthState::Fido2(cred) => serde_json::to_value(koi_crypto::auth::store_fido2(cred.clone()))
            .map_err(|e| CertmeshError::Internal(format!("auth serialize: {e}")))?,
    };

    let roster_json = serde_json::to_string(roster)
        .map_err(|e| CertmeshError::Internal(format!("roster serialization failed: {e}")))?;

    Ok(PromoteResponse {
        encrypted_ca_key,
        auth_data,
        roster_json,
        ca_cert_pem: ca.cert_pem.clone(),
        ephemeral_public: Some(server_pub),
    })
}

/// Accept a promotion response and decrypt the CA key and auth credential.
///
/// The CA key is decrypted using the DH-derived shared key from the
/// ephemeral key pair exchange. Auth data is decrypted with an empty
/// passphrase (the server encrypts it that way for wire transfer).
pub fn accept_promotion(
    response: &PromoteResponse,
    our_keypair: EphemeralKeyPair,
) -> Result<(CaKeyPair, AuthState, Roster), CertmeshError> {
    let server_pub = response.ephemeral_public.as_ref().ok_or_else(|| {
        CertmeshError::PromotionFailed("server did not provide ephemeral public key".into())
    })?;
    let mut shared_key = our_keypair
        .derive_shared_key(server_pub)
        .map_err(|e| CertmeshError::PromotionFailed(format!("key derivation: {e}")))?;
    let shared_key_hex =
        koi_crypto::secret::SecretString::new(koi_common::encoding::hex_encode(&shared_key));
    shared_key.zeroize();
    let ca_key = keys::decrypt_key(&response.encrypted_ca_key, shared_key_hex.as_ref())
        .map_err(|e| CertmeshError::PromotionFailed(format!("CA key DH decryption: {e}")))?;

    // Auth data is encrypted with the same DH-derived shared key
    let stored: koi_crypto::auth::StoredAuth = serde_json::from_value(response.auth_data.clone())
        .map_err(|e| {
        CertmeshError::PromotionFailed(format!("auth data deserialization: {e}"))
    })?;
    let auth_state = stored
        .unlock(shared_key_hex.as_ref())
        .map_err(|e| CertmeshError::PromotionFailed(format!("auth unlock: {e}")))?;

    let roster: Roster = serde_json::from_str(&response.roster_json)
        .map_err(|e| CertmeshError::PromotionFailed(format!("roster deserialization: {e}")))?;

    Ok((ca_key, auth_state, roster))
}

// ── Roster Sync ────────────────────────────────────────────────────

/// Build a signed roster manifest for standby sync.
///
/// The primary serializes the roster to JSON, signs it with the CA's
/// ECDSA key, and packages the signature + public key for verification.
pub fn build_signed_manifest(
    ca: &CaState,
    roster: &Roster,
) -> Result<RosterManifest, CertmeshError> {
    let roster_json = serde_json::to_string(roster)
        .map_err(|e| CertmeshError::Internal(format!("roster serialization failed: {e}")))?;

    let signature = signing::sign_bytes(&ca.key, roster_json.as_bytes());
    let ca_public_key = ca
        .key
        .public_key_pem()
        .map_err(|e| CertmeshError::Crypto(e.to_string()))?;

    Ok(RosterManifest {
        roster_json,
        signature,
        ca_public_key,
    })
}

/// Verify a roster manifest's signature and deserialize the roster.
///
/// The standby calls this after receiving a `RosterManifest` from the primary.
/// Returns the verified roster if the signature is valid.
pub fn verify_manifest(manifest: &RosterManifest) -> Result<Roster, CertmeshError> {
    let valid = signing::verify_signature(
        &manifest.ca_public_key,
        manifest.roster_json.as_bytes(),
        &manifest.signature,
    );

    if !valid {
        return Err(CertmeshError::InvalidManifest);
    }

    serde_json::from_str(&manifest.roster_json)
        .map_err(|e| CertmeshError::Internal(format!("roster deserialization: {e}")))
}

// ── Failover Detection ─────────────────────────────────────────────

/// Determine whether the primary has been absent long enough to trigger failover.
///
/// `primary_absent_since` is `Some(instant)` when the primary was last seen
/// disappearing from mDNS. Returns `true` if the grace period has elapsed.
pub fn should_promote(primary_absent_since: Option<Instant>, grace: Duration) -> bool {
    match primary_absent_since {
        Some(since) => since.elapsed() >= grace,
        None => false,
    }
}

/// Deterministic tiebreaker: lower hostname wins.
///
/// When two standbys detect the same failover condition, the one with
/// the lexicographically lower hostname takes over. This prevents
/// split-brain scenarios without needing distributed consensus.
pub fn tiebreaker_wins(my_hostname: &str, other_hostname: &str) -> bool {
    my_hostname < other_hostname
}

/// Check mDNS service records for an active primary with the expected CA fingerprint.
///
/// Scans the TXT records of `_certmesh._tcp` services for a `role=primary`
/// entry whose `fingerprint` matches our pinned CA fingerprint.
/// Returns the endpoint (host:port) of the matching primary, if found.
pub fn find_active_primary(
    ca_fingerprint: &str,
    services: &[(String, u16, std::collections::HashMap<String, String>)],
) -> Option<String> {
    for (host, port, txt) in services {
        let is_primary = txt.get("role").map(|r| r == "primary").unwrap_or(false);
        let fp_matches = txt
            .get("fingerprint")
            .map(|fp| koi_crypto::pinning::fingerprints_match(fp, ca_fingerprint))
            .unwrap_or(false);

        if is_primary && fp_matches {
            return Some(format!("{host}:{port}"));
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ca;
    use crate::profiles::TrustProfile;
    use crate::roster::{MemberRole, MemberStatus, Roster, RosterMember};
    use chrono::Utc;
    use std::collections::HashMap;

    fn test_paths() -> crate::CertmeshPaths {
        crate::CertmeshPaths::with_data_dir(koi_common::test::ensure_data_dir(
            "koi-certmesh-failover-tests",
        ))
    }

    fn make_test_ca() -> CaState {
        ca::create_ca("test-pass", &[42u8; 32], &test_paths())
            .unwrap()
            .0
    }

    fn make_test_roster() -> Roster {
        let mut r = Roster::new(TrustProfile::JustMe, None);
        r.members.push(RosterMember {
            hostname: "stone-01".to_string(),
            role: MemberRole::Primary,
            enrolled_at: Utc::now(),
            enrolled_by: None,
            cert_fingerprint: "fp-abc".to_string(),
            cert_expires: Utc::now(),
            cert_sans: vec!["stone-01".to_string()],
            cert_path: String::new(),
            status: MemberStatus::Active,
            reload_hook: None,
            last_seen: None,
            pinned_ca_fingerprint: None,
            proxy_entries: Vec::new(),
        });
        r
    }

    // ── Promotion tests ────────────────────────────────────────────

    #[test]
    fn promotion_round_trip_with_dh() {
        let ca = make_test_ca();
        let totp = koi_crypto::totp::generate_secret();
        let auth_state = AuthState::Totp(totp);
        let roster = make_test_roster();

        // Client generates ephemeral keypair
        let client_kp = koi_crypto::key_agreement::EphemeralKeyPair::generate();
        let client_pub = client_kp.public_key_bytes();

        let response = prepare_promotion(&ca, &auth_state, &roster, &client_pub).unwrap();

        // Verify encrypted material is non-empty
        assert!(!response.encrypted_ca_key.ciphertext.is_empty());
        assert!(!response.auth_data.is_null());
        assert!(!response.roster_json.is_empty());
        assert!(response.ca_cert_pem.contains("BEGIN CERTIFICATE"));
        assert!(response.ephemeral_public.is_some());

        // Accept on the standby side using DH
        let (ca_key, accepted_auth, accepted_roster) =
            accept_promotion(&response, client_kp).unwrap();

        // Verify the decrypted key produces the same public key
        assert_eq!(
            ca_key.public_key_pem().unwrap(),
            ca.key.public_key_pem().unwrap()
        );
        // Verify auth state survived the round-trip
        assert_eq!(accepted_auth.method_name(), "totp");
        // Verify roster survived
        assert_eq!(accepted_roster.members.len(), 1);
        assert_eq!(accepted_roster.members[0].hostname, "stone-01");
    }

    #[test]
    fn promotion_missing_server_ephemeral_key_fails() {
        let ca = make_test_ca();
        let totp = koi_crypto::totp::generate_secret();
        let auth_state = AuthState::Totp(totp);
        let roster = make_test_roster();

        let client_kp = koi_crypto::key_agreement::EphemeralKeyPair::generate();
        let client_pub = client_kp.public_key_bytes();
        let mut response = prepare_promotion(&ca, &auth_state, &roster, &client_pub).unwrap();

        // Remove the server's ephemeral key — acceptance must fail
        response.ephemeral_public = None;
        let result = accept_promotion(&response, client_kp);
        assert!(matches!(result, Err(CertmeshError::PromotionFailed(_))));
    }

    #[test]
    fn promotion_dh_wrong_keypair_fails() {
        let ca = make_test_ca();
        let totp = koi_crypto::totp::generate_secret();
        let auth_state = AuthState::Totp(totp);
        let roster = make_test_roster();

        let client_kp = koi_crypto::key_agreement::EphemeralKeyPair::generate();
        let client_pub = client_kp.public_key_bytes();

        let response = prepare_promotion(&ca, &auth_state, &roster, &client_pub).unwrap();

        // Try to accept with a DIFFERENT keypair -- should fail
        let wrong_kp = koi_crypto::key_agreement::EphemeralKeyPair::generate();
        let result = accept_promotion(&response, wrong_kp);
        assert!(matches!(result, Err(CertmeshError::PromotionFailed(_))));
    }

    // ── Roster sync tests ──────────────────────────────────────────

    #[test]
    fn manifest_sign_verify_round_trip() {
        let ca = make_test_ca();
        let roster = make_test_roster();

        let manifest = build_signed_manifest(&ca, &roster).unwrap();
        assert!(!manifest.signature.is_empty());
        assert!(!manifest.ca_public_key.is_empty());

        let verified_roster = verify_manifest(&manifest).unwrap();
        assert_eq!(verified_roster.members.len(), 1);
        assert_eq!(verified_roster.members[0].hostname, "stone-01");
    }

    #[test]
    fn tampered_manifest_fails_verification() {
        let ca = make_test_ca();
        let roster = make_test_roster();

        let mut manifest = build_signed_manifest(&ca, &roster).unwrap();
        // Tamper with the roster JSON
        manifest.roster_json = manifest.roster_json.replace("stone-01", "evil-host");

        let result = verify_manifest(&manifest);
        assert!(matches!(result, Err(CertmeshError::InvalidManifest)));
    }

    #[test]
    fn wrong_key_manifest_fails_verification() {
        let ca1 = make_test_ca();
        let (ca2, _) = ca::create_ca("other-pass", &[99u8; 32], &test_paths()).unwrap();
        let roster = make_test_roster();

        let mut manifest = build_signed_manifest(&ca1, &roster).unwrap();
        // Replace the public key with a different CA's key
        manifest.ca_public_key = ca2.key.public_key_pem().unwrap();

        let result = verify_manifest(&manifest);
        assert!(matches!(result, Err(CertmeshError::InvalidManifest)));
    }

    // ── Failover detection tests ───────────────────────────────────

    #[test]
    fn should_promote_false_when_no_absence() {
        assert!(!should_promote(None, Duration::from_secs(60)));
    }

    #[test]
    fn should_promote_false_within_grace() {
        let since = Instant::now();
        assert!(!should_promote(Some(since), Duration::from_secs(60)));
    }

    #[test]
    fn should_promote_true_after_grace() {
        // Use a zero grace period so the check passes immediately
        let since = Instant::now() - Duration::from_secs(1);
        assert!(should_promote(Some(since), Duration::from_secs(0)));
    }

    #[test]
    fn tiebreaker_lower_hostname_wins() {
        assert!(tiebreaker_wins("alpha", "bravo"));
        assert!(!tiebreaker_wins("bravo", "alpha"));
        assert!(!tiebreaker_wins("alpha", "alpha")); // tie = neither wins
    }

    #[test]
    fn tiebreaker_is_case_sensitive() {
        // Uppercase sorts before lowercase in ASCII
        assert!(tiebreaker_wins("Alpha", "alpha"));
    }

    // ── find_active_primary tests ──────────────────────────────────

    #[test]
    fn find_active_primary_matches_fingerprint() {
        let fp = "abc123";
        let mut txt = HashMap::new();
        txt.insert("role".to_string(), "primary".to_string());
        txt.insert("fingerprint".to_string(), fp.to_string());

        let services = vec![("stone-01.local".to_string(), 5641u16, txt)];
        let result = find_active_primary(fp, &services);
        assert_eq!(result.as_deref(), Some("stone-01.local:5641"));
    }

    #[test]
    fn find_active_primary_skips_standby() {
        let fp = "abc123";
        let mut txt = HashMap::new();
        txt.insert("role".to_string(), "standby".to_string());
        txt.insert("fingerprint".to_string(), fp.to_string());

        let services = vec![("stone-02.local".to_string(), 5641u16, txt)];
        let result = find_active_primary(fp, &services);
        assert!(result.is_none());
    }

    #[test]
    fn find_active_primary_wrong_fingerprint() {
        let mut txt = HashMap::new();
        txt.insert("role".to_string(), "primary".to_string());
        txt.insert("fingerprint".to_string(), "wrong-fp".to_string());

        let services = vec![("stone-01.local".to_string(), 5641u16, txt)];
        let result = find_active_primary("correct-fp", &services);
        assert!(result.is_none());
    }

    #[test]
    fn find_active_primary_empty_services() {
        let result = find_active_primary("abc123", &[]);
        assert!(result.is_none());
    }

    // ── Promotion edge cases ────────────────────────────────────────

    #[test]
    fn promotion_dh_preserves_roster_metadata() {
        let ca = make_test_ca();
        let totp = koi_crypto::totp::generate_secret();
        let auth = koi_crypto::auth::AuthState::Totp(totp);
        let mut roster = make_test_roster();
        roster.metadata.operator = Some("ops-team".to_string());

        let client_kp = koi_crypto::key_agreement::EphemeralKeyPair::generate();
        let client_pub = client_kp.public_key_bytes();

        let response = prepare_promotion(&ca, &auth, &roster, &client_pub).unwrap();
        let (_, _, accepted_roster) = accept_promotion(&response, client_kp).unwrap();
        assert_eq!(
            accepted_roster.metadata.operator.as_deref(),
            Some("ops-team")
        );
        assert_eq!(
            accepted_roster.metadata.trust_profile,
            roster.metadata.trust_profile
        );
    }

    #[test]
    fn promotion_dh_with_empty_roster() {
        let ca = make_test_ca();
        let totp = koi_crypto::totp::generate_secret();
        let auth = koi_crypto::auth::AuthState::Totp(totp);
        let roster = Roster::new(TrustProfile::JustMe, None);
        assert!(roster.members.is_empty());

        let client_kp = koi_crypto::key_agreement::EphemeralKeyPair::generate();
        let client_pub = client_kp.public_key_bytes();

        let response = prepare_promotion(&ca, &auth, &roster, &client_pub).unwrap();
        let (_, _, accepted_roster) = accept_promotion(&response, client_kp).unwrap();
        assert!(accepted_roster.members.is_empty());
    }

    // ── Manifest edge cases ─────────────────────────────────────────

    #[test]
    fn manifest_with_empty_roster() {
        let ca = make_test_ca();
        let roster = Roster::new(TrustProfile::JustMe, None);

        let manifest = build_signed_manifest(&ca, &roster).unwrap();
        let verified = verify_manifest(&manifest).unwrap();
        assert!(verified.members.is_empty());
    }

    #[test]
    fn manifest_with_multiple_members() {
        let ca = make_test_ca();
        let mut roster = make_test_roster();
        roster.members.push(RosterMember {
            hostname: "stone-02".to_string(),
            role: MemberRole::Standby,
            enrolled_at: Utc::now(),
            enrolled_by: None,
            cert_fingerprint: "fp-def".to_string(),
            cert_expires: Utc::now(),
            cert_sans: vec!["stone-02".to_string()],
            cert_path: String::new(),
            status: MemberStatus::Active,
            reload_hook: None,
            last_seen: None,
            pinned_ca_fingerprint: None,
            proxy_entries: Vec::new(),
        });
        roster.members.push(RosterMember {
            hostname: "stone-03".to_string(),
            role: MemberRole::Member,
            enrolled_at: Utc::now(),
            enrolled_by: None,
            cert_fingerprint: "fp-ghi".to_string(),
            cert_expires: Utc::now(),
            cert_sans: vec!["stone-03".to_string()],
            cert_path: String::new(),
            status: MemberStatus::Active,
            reload_hook: None,
            last_seen: None,
            pinned_ca_fingerprint: None,
            proxy_entries: Vec::new(),
        });

        let manifest = build_signed_manifest(&ca, &roster).unwrap();
        let verified = verify_manifest(&manifest).unwrap();
        assert_eq!(verified.members.len(), 3);
    }

    #[test]
    fn manifest_tampered_signature_fails() {
        let ca = make_test_ca();
        let roster = make_test_roster();

        let mut manifest = build_signed_manifest(&ca, &roster).unwrap();
        // Flip a byte in the signature
        if let Some(byte) = manifest.signature.first_mut() {
            *byte ^= 0xFF;
        }
        assert!(matches!(
            verify_manifest(&manifest),
            Err(CertmeshError::InvalidManifest)
        ));
    }

    #[test]
    fn manifest_empty_signature_fails() {
        let ca = make_test_ca();
        let roster = make_test_roster();

        let mut manifest = build_signed_manifest(&ca, &roster).unwrap();
        manifest.signature = vec![];
        assert!(matches!(
            verify_manifest(&manifest),
            Err(CertmeshError::InvalidManifest)
        ));
    }

    #[test]
    fn manifest_empty_public_key_fails() {
        let ca = make_test_ca();
        let roster = make_test_roster();

        let mut manifest = build_signed_manifest(&ca, &roster).unwrap();
        manifest.ca_public_key = String::new();
        assert!(matches!(
            verify_manifest(&manifest),
            Err(CertmeshError::InvalidManifest)
        ));
    }

    // ── Failover detection edge cases ───────────────────────────────

    #[test]
    fn should_promote_at_exact_boundary() {
        // Test with a grace period that just barely elapsed
        let grace = Duration::from_millis(50);
        let since = Instant::now() - Duration::from_millis(60);
        assert!(should_promote(Some(since), grace));
    }

    #[test]
    fn should_promote_with_zero_grace() {
        // Zero grace = instant promotion
        let since = Instant::now();
        // Even though "now", with zero grace it should be true (elapsed >= 0)
        assert!(should_promote(Some(since), Duration::ZERO));
    }

    // ── Tiebreaker edge cases ───────────────────────────────────────

    #[test]
    fn tiebreaker_with_numeric_hostnames() {
        // Lexicographic: "1" < "2" < "10" (string, not numeric)
        assert!(tiebreaker_wins("1", "2"));
        // "10" < "2" lexicographically
        assert!(tiebreaker_wins("10", "2"));
    }

    #[test]
    fn tiebreaker_with_empty_hostname() {
        // Empty string sorts before anything
        assert!(tiebreaker_wins("", "any"));
        assert!(!tiebreaker_wins("any", ""));
    }

    #[test]
    fn tiebreaker_with_common_prefixes() {
        assert!(tiebreaker_wins("node-01", "node-02"));
        assert!(!tiebreaker_wins("node-02", "node-01"));
    }

    // ── find_active_primary edge cases ──────────────────────────────

    #[test]
    fn find_active_primary_multiple_primaries_returns_first() {
        let fp = "abc123";
        let mut txt1 = HashMap::new();
        txt1.insert("role".to_string(), "primary".to_string());
        txt1.insert("fingerprint".to_string(), fp.to_string());

        let mut txt2 = HashMap::new();
        txt2.insert("role".to_string(), "primary".to_string());
        txt2.insert("fingerprint".to_string(), fp.to_string());

        let services = vec![
            ("stone-01.local".to_string(), 5641u16, txt1),
            ("stone-02.local".to_string(), 5642u16, txt2),
        ];
        let result = find_active_primary(fp, &services);
        // Should return the first match
        assert_eq!(result.as_deref(), Some("stone-01.local:5641"));
    }

    #[test]
    fn find_active_primary_missing_role_key() {
        let fp = "abc123";
        let mut txt = HashMap::new();
        // No "role" key at all
        txt.insert("fingerprint".to_string(), fp.to_string());

        let services = vec![("stone-01.local".to_string(), 5641u16, txt)];
        assert!(find_active_primary(fp, &services).is_none());
    }

    #[test]
    fn find_active_primary_missing_fingerprint_key() {
        let mut txt = HashMap::new();
        txt.insert("role".to_string(), "primary".to_string());
        // No "fingerprint" key at all

        let services = vec![("stone-01.local".to_string(), 5641u16, txt)];
        assert!(find_active_primary("abc123", &services).is_none());
    }

    #[test]
    fn find_active_primary_mixed_roles() {
        let fp = "abc123";

        let mut txt_standby = HashMap::new();
        txt_standby.insert("role".to_string(), "standby".to_string());
        txt_standby.insert("fingerprint".to_string(), fp.to_string());

        let mut txt_member = HashMap::new();
        txt_member.insert("role".to_string(), "member".to_string());
        txt_member.insert("fingerprint".to_string(), fp.to_string());

        let mut txt_primary = HashMap::new();
        txt_primary.insert("role".to_string(), "primary".to_string());
        txt_primary.insert("fingerprint".to_string(), fp.to_string());

        let services = vec![
            ("standby.local".to_string(), 5641u16, txt_standby),
            ("member.local".to_string(), 5641u16, txt_member),
            ("primary.local".to_string(), 5641u16, txt_primary),
        ];
        // Should skip standby and member, find primary
        let result = find_active_primary(fp, &services);
        assert_eq!(result.as_deref(), Some("primary.local:5641"));
    }
}