ai-memory 0.7.1

AI-agnostic persistent memory system — MCP server, HTTP API, and CLI for any AI platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
// Copyright 2026 AlphaOne LLC
// SPDX-License-Identifier: Apache-2.0

//! TLS / mTLS configuration and verifiers for the HTTP daemon.
//!
//! Wave 4 (v0.6.3) — extracted verbatim from `src/main.rs`. Three layers:
//!
//! 1. **Layer 1** — server-side TLS via `axum-server` + rustls.
//!    `load_rustls_config` parses a PEM cert + PEM key (PKCS#8 / RSA / SEC1)
//!    and surfaces operator-friendly errors instead of letting rustls' wrapped
//!    IO errors bubble up. TLS misconfiguration is the #1 new-deploy footgun.
//!
//! 2. **Layer 2** — mTLS with SHA-256 client-cert fingerprint allowlist.
//!    `load_mtls_rustls_config` builds a rustls `ServerConfig` that:
//!      - presents the local cert/key (same as Layer 1),
//!      - demands a client certificate on every connection,
//!      - accepts the client cert only if its SHA-256 fingerprint appears on
//!        the operator-configured allowlist. Any other cert — including ones
//!        signed by trusted CAs — is rejected. This is the fastest path to
//!        "only authorised peers can even connect" without depending on a
//!        PKI/CA ecosystem. Fingerprint pinning is a well-understood primitive
//!        (HTTP Public Key Pinning, SSH host keys).
//!
//!    The allowlist parser tolerates:
//!      - blank lines and `#` full-line comments,
//!      - trailing inline comments (issue #358),
//!      - optional `:` separators in the hex,
//!      - an optional leading `sha256:` marker (forward-compat).
//!    It rejects embedded whitespace inside the hex run (issue #338) so
//!    soft-wrap copy-paste artefacts surface a clear "unexpected character"
//!    error rather than a misleading length error further down.
//!
//! 3. **Layer 2 (client side)** — `build_rustls_client_config` builds a
//!    `rustls::ClientConfig` with client-cert auth and a "dangerously-accept-
//!    any-server-cert" verifier. Used by the sync-daemon to present its
//!    client cert on every outbound request while connecting to peers with
//!    self-signed server certs. Peer authenticity is established on the
//!    other direction (they verify us via `--mtls-allowlist`).
//!
//! Every public symbol below is move-extracted byte-for-byte from `main.rs`
//! at the W3 commit, with `pub` added for cross-module visibility. Behaviour
//! must remain bit-for-bit identical at the call sites.

use anyhow::{Context, Result};
use std::collections::HashSet;
use std::path::Path;
use std::sync::Arc;

/// v0.7.0 H3 — pin the rustls protocol-version floor to TLS 1.2 with TLS 1.3
/// preferred. Listed in descending preference order; rustls negotiates the
/// highest protocol both peers support. TLS 1.0 / 1.1 are deliberately
/// omitted: they have known weaknesses (BEAST, POODLE, no AEAD) and are
/// disabled in every modern client (Chrome ≥ 84, Firefox ≥ 78, Safari ≥ 13).
pub const SUPPORTED_PROTOCOL_VERSIONS: &[&rustls::SupportedProtocolVersion] =
    &[&rustls::version::TLS13, &rustls::version::TLS12];

/// v0.7.0 H4 — emit a `tracing::warn!` when the on-disk TLS key file is
/// world- or group-readable. On Unix, "loose" means
/// `mode & 0o077 != 0` — any bit in the group/world triad is set.
///
/// We intentionally do **not** refuse to load. Operators may have
/// deliberately set up a shared-group keymat layout (e.g. nginx-style
/// `ssl-cert` group), and refusing here would regress those flows.
/// Warning is the right surface: loud in `journalctl`, scrapable by
/// the SIEM, but never blocks startup.
///
/// On non-Unix targets the check is a no-op (Windows ACLs are richer
/// than `st_mode` bits and would warrant a separate audit).
fn warn_if_key_perms_loose(path: &Path) {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt as _;
        if let Ok(meta) = std::fs::metadata(path) {
            let mode = meta.mode() & 0o777;
            if mode & 0o077 != 0 {
                tracing::warn!(
                    target: "ai_memory::tls",
                    path = %path.display(),
                    mode = format!("{mode:#o}"),
                    "TLS private key file is group- or world-accessible \
                     (mode {mode:#o}); recommended permissions are 0600. \
                     Loading anyway — operator may have intentional shared-group setup."
                );
            }
        }
    }
    #[cfg(not(unix))]
    {
        // Windows uses ACLs, not POSIX modes. A separate audit would be
        // needed to surface "Everyone has Read" — out of v0.7.0 scope.
        let _ = path;
    }
}

/// Load a PEM cert + PEM key (PKCS#8 or RSA) into an `axum-server`
/// rustls config. Returns an error with a specific message for the
/// operator rather than letting rustls' wrapped IO error bubble up —
/// TLS misconfigurations are the #1 new-deploy footgun.
///
/// **v0.7.0 H3** — protocol versions are pinned to TLS 1.3 (preferred)
/// + TLS 1.2 (floor). See [`SUPPORTED_PROTOCOL_VERSIONS`].
///
/// **v0.7.0 H4** — private key file permissions are checked before
/// loading; loose permissions surface as a WARN but do not refuse.
pub async fn load_rustls_config(
    cert_path: &Path,
    key_path: &Path,
) -> Result<axum_server::tls_rustls::RustlsConfig> {
    warn_if_key_perms_loose(key_path);
    let cert_pem = tokio::fs::read(cert_path)
        .await
        .with_context(|| format!("failed to read TLS cert from {}", cert_path.display()))?;
    let key_pem = tokio::fs::read(key_path)
        .await
        .with_context(|| format!("failed to read TLS key from {}", key_path.display()))?;

    // v0.7.0 H3 — `RustlsConfig::from_pem` doesn't expose protocol-
    // version pinning. We build a `rustls::ServerConfig` directly with
    // `with_protocol_versions(&[TLS13, TLS12])`, then wrap it for
    // axum_server. Same parser surface, but with the version floor
    // bolted on.
    let certs = rustls_pki_pem_iter_certs(&cert_pem)?;
    let key = rustls_pki_pem_parse_private_key(&key_pem)?;
    let server_config =
        rustls::ServerConfig::builder_with_protocol_versions(SUPPORTED_PROTOCOL_VERSIONS)
            .with_no_client_auth()
            .with_single_cert(certs, key)
            .context(
                "failed to build rustls ServerConfig — ensure PEM-encoded (cert may be fullchain; \
         key must be PKCS#8 or RSA)",
            )?;
    Ok(axum_server::tls_rustls::RustlsConfig::from_config(
        Arc::new(server_config),
    ))
}

// ---------------------------------------------------------------------------
// Layer 2 — mTLS with SHA-256 fingerprint allowlist.
// ---------------------------------------------------------------------------

/// Load a rustls server config with client-cert-fingerprint verification.
pub async fn load_mtls_rustls_config(
    cert_path: &Path,
    key_path: &Path,
    allowlist_path: &Path,
) -> Result<axum_server::tls_rustls::RustlsConfig> {
    let allowlist = load_fingerprint_allowlist(allowlist_path).await?;
    if allowlist.is_empty() {
        anyhow::bail!(
            "mTLS allowlist at {} is empty — refuse to start rather than silently accept all peers",
            allowlist_path.display()
        );
    }

    warn_if_key_perms_loose(key_path);
    let cert_pem = tokio::fs::read(cert_path)
        .await
        .with_context(|| format!("failed to read TLS cert from {}", cert_path.display()))?;
    let key_pem = tokio::fs::read(key_path)
        .await
        .with_context(|| format!("failed to read TLS key from {}", key_path.display()))?;

    let certs: Vec<rustls::pki_types::CertificateDer<'static>> =
        rustls_pki_pem_iter_certs(&cert_pem)?;
    let key = rustls_pki_pem_parse_private_key(&key_pem)?;

    let verifier = Arc::new(FingerprintAllowlistVerifier { allowlist });
    // v0.7.0 H3 — same protocol-version pinning as the non-mTLS server
    // config above. TLS 1.3 preferred, TLS 1.2 floor.
    let server_config =
        rustls::ServerConfig::builder_with_protocol_versions(SUPPORTED_PROTOCOL_VERSIONS)
            .with_client_cert_verifier(verifier)
            .with_single_cert(certs, key)
            .context("failed to build rustls ServerConfig for mTLS")?;

    Ok(axum_server::tls_rustls::RustlsConfig::from_config(
        Arc::new(server_config),
    ))
}

/// v0.7.0 #1581 — production acceptor for the TLS / mTLS `serve` path:
/// the rustls acceptor wrapped around [`axum_server::accept::NoDelayAcceptor`]
/// so `TCP_NODELAY` is set on every accepted socket BEFORE the handshake.
///
/// # Why (the #1579 P3 fleet finding)
///
/// `serve()` used to bind via `axum_server::bind_rustls`, whose inner
/// `DefaultAcceptor` is a no-op — Nagle's algorithm stayed enabled on every
/// accepted socket. After a TLS 1.3 handshake the server flushes the
/// NewSessionTicket records as a small TCP segment ahead of the first
/// response; with Nagle on, the response segment is then held until the
/// ticket segment is ACKed, and the client kernel's delayed-ACK timer
/// (40 ms minimum on Linux) is what finally supplies that ACK. Net effect:
/// the FIRST request of every fresh mTLS connection paid a fixed ~40 ms
/// stall that no later request on the same connection repeats — measured
/// fleet-wide on all 9 intra-region do-1461 peer pairs (first-request TTFB
/// ~52–57 ms vs ~5–8 ms reused, RTT 2–3 ms) and reproduced on loopback
/// (~41 ms gap between `time_appconnect` and `time_starttransfer` vs
/// ~2 ms for a reused connection).
///
/// Setting `TCP_NODELAY` disables Nagle so the response goes out the
/// moment it's written. The client side of federation sync was never
/// affected: reqwest defaults `tcp_nodelay(true)`, as does curl ≥ 7.50.
///
/// # Security
///
/// This is a pure socket-option change ahead of the handshake. The
/// verifier chain — [`FingerprintAllowlistVerifier`], `client_auth_mandatory`,
/// the protocol-version floor — is byte-identical to what
/// `axum_server::bind_rustls` constructs. Equivalence is pinned by
/// `tests/mtls_nodelay_acceptor.rs` (allowlisted cert accepted, unknown
/// cert rejected, absent cert rejected, on BOTH acceptor shapes).
pub fn serve_rustls_acceptor(
    config: &axum_server::tls_rustls::RustlsConfig,
) -> axum_server::tls_rustls::RustlsAcceptor<axum_server::accept::NoDelayAcceptor> {
    axum_server::tls_rustls::RustlsAcceptor::new(config.clone())
        .acceptor(axum_server::accept::NoDelayAcceptor::new())
}

/// Parse the allowlist file: one SHA-256 fingerprint per line, case-insensitive
/// hex with optional `:` separators. Empty lines and `#` comments are skipped.
pub async fn load_fingerprint_allowlist(path: &Path) -> Result<HashSet<[u8; 32]>> {
    let text = tokio::fs::read_to_string(path)
        .await
        .with_context(|| format!("failed to read mTLS allowlist from {}", path.display()))?;
    let mut set = HashSet::new();
    for (lineno, raw) in text.lines().enumerate() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        // Issue #358: tolerate inline trailing comments — anything after `#`
        // on a non-comment line is dropped before the strict hex/colon
        // validation below. Safe because `#` is not a valid hex/colon char,
        // so it cannot appear in a legitimate SHA-256 fingerprint.
        let line = line.split('#').next().unwrap_or("").trim();
        if line.is_empty() {
            continue;
        }
        // Accept a leading `sha256:` marker for forward-compat with richer formats.
        let hex_part = line.strip_prefix("sha256:").unwrap_or(line);
        // Ultrareview #338: reject any non-hex, non-colon character —
        // including embedded whitespace/tabs. Previously the parser
        // stripped only `:` and relied on the length check to catch
        // whitespace, but silent acceptance of copy-paste artefacts
        // (e.g. soft-wraps producing internal spaces) would produce
        // misleading parse errors further down rather than a clear
        // "whitespace not allowed" signal. Keep it strict.
        if let Some(bad) = hex_part
            .chars()
            .find(|c| !c.is_ascii_hexdigit() && *c != ':')
        {
            anyhow::bail!(
                "mTLS allowlist line {}: unexpected character {:?} — \
                 entries must be 64 hex chars with optional `:` separators",
                lineno + 1,
                bad
            );
        }
        let hex_clean: String = hex_part.chars().filter(|c| *c != ':').collect();
        if hex_clean.len() != 64 {
            anyhow::bail!(
                "mTLS allowlist line {}: expected 64 hex chars (optionally with `:` separators), got {}",
                lineno + 1,
                hex_clean.len()
            );
        }
        let mut bytes = [0u8; 32];
        for i in 0..32 {
            bytes[i] = u8::from_str_radix(&hex_clean[i * 2..i * 2 + 2], 16)
                .with_context(|| format!("mTLS allowlist line {}: invalid hex", lineno + 1))?;
        }
        set.insert(bytes);
    }
    Ok(set)
}

pub fn rustls_pki_pem_iter_certs(
    pem: &[u8],
) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>> {
    use rustls::pki_types::pem::PemObject as _;
    let mut cursor = std::io::Cursor::new(pem);
    let certs: Vec<_> = rustls::pki_types::CertificateDer::pem_reader_iter(&mut cursor)
        .collect::<std::result::Result<Vec<_>, _>>()
        .context("failed to parse TLS cert PEM")?;
    if certs.is_empty() {
        anyhow::bail!("TLS cert PEM contained no certificates");
    }
    Ok(certs)
}

pub fn rustls_pki_pem_parse_private_key(
    pem: &[u8],
) -> Result<rustls::pki_types::PrivateKeyDer<'static>> {
    use rustls::pki_types::pem::PemObject as _;
    let mut cursor = std::io::Cursor::new(pem);
    let key = rustls::pki_types::PrivateKeyDer::from_pem_reader(&mut cursor)
        .context("failed to parse TLS key PEM — expected PKCS#8, RSA, or SEC1")?;
    Ok(key)
}

/// Custom `ClientCertVerifier` that accepts only client certs whose SHA-256
/// DER fingerprint is on the allowlist. Ignores CA chain — fingerprint
/// pinning is the trust anchor here, same model as SSH `known_hosts`.
#[derive(Debug)]
pub struct FingerprintAllowlistVerifier {
    pub allowlist: HashSet<[u8; 32]>,
}

impl rustls::server::danger::ClientCertVerifier for FingerprintAllowlistVerifier {
    fn offer_client_auth(&self) -> bool {
        true
    }

    fn client_auth_mandatory(&self) -> bool {
        true
    }

    fn root_hint_subjects(&self) -> &[rustls::DistinguishedName] {
        &[]
    }

    fn verify_client_cert(
        &self,
        end_entity: &rustls::pki_types::CertificateDer<'_>,
        _intermediates: &[rustls::pki_types::CertificateDer<'_>],
        _now: rustls::pki_types::UnixTime,
    ) -> std::result::Result<rustls::server::danger::ClientCertVerified, rustls::Error> {
        use sha2::{Digest, Sha256};
        let fp: [u8; 32] = Sha256::digest(end_entity.as_ref()).into();
        if allowlist_contains_ct(&self.allowlist, &fp) {
            Ok(rustls::server::danger::ClientCertVerified::assertion())
        } else {
            Err(rustls::Error::General(format!(
                "client cert fingerprint {} not in mTLS allowlist",
                hex_short(&fp)
            )))
        }
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &rustls::pki_types::CertificateDer<'_>,
        dss: &rustls::DigitallySignedStruct,
    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        rustls::crypto::verify_tls12_signature(
            message,
            cert,
            dss,
            &rustls::crypto::ring::default_provider().signature_verification_algorithms,
        )
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &rustls::pki_types::CertificateDer<'_>,
        dss: &rustls::DigitallySignedStruct,
    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        rustls::crypto::verify_tls13_signature(
            message,
            cert,
            dss,
            &rustls::crypto::ring::default_provider().signature_verification_algorithms,
        )
    }

    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
        rustls::crypto::ring::default_provider()
            .signature_verification_algorithms
            .supported_schemes()
    }
}

pub fn hex_short(fp: &[u8; 32]) -> String {
    use std::fmt::Write as _;
    let mut s = String::with_capacity(12);
    for b in &fp[..6] {
        let _ = write!(s, "{b:02x}");
    }
    s.push('');
    s
}

/// v0.7.0 M1 — constant-time allowlist membership check.
///
/// `HashSet::contains` is O(1) but the SipHash probe + early-exit
/// comparison both leak timing signal: the response time of a verify
/// handshake correlates with whether the offered fingerprint hash-
/// collides with any allowlist entry (and, on collision, how many
/// bytes match). A remote attacker who can observe TLS handshake
/// timing can in principle enumerate the allowlist that way.
///
/// We walk every entry in the allowlist on every call and XOR-fold
/// each byte through `subtle::ConstantTimeEq`. The result is the
/// OR-reduction of "this entry matched" across every entry — same
/// per-call cost regardless of whether a match exists or where in
/// the iteration order it sits. `subtle` is the RustCrypto-default
/// constant-time primitive (used by ring, ed25519-dalek, etc.).
///
/// Cost is O(N · 32) bytes per handshake. With a 1000-entry
/// allowlist that's 32 KB of memory comparison — well below the
/// dozens of milliseconds of cryptographic handshake work that
/// precedes it. The timing-attack threat dominates the perf cost.
fn allowlist_contains_ct(allowlist: &HashSet<[u8; 32]>, fp: &[u8; 32]) -> bool {
    use subtle::ConstantTimeEq as _;
    let mut found: subtle::Choice = subtle::Choice::from(0);
    for entry in allowlist {
        // `ct_eq` returns a `Choice` (0 or 1) without branching on
        // the comparison outcome — the inner XOR-fold runs the full
        // 32 bytes every call.
        found |= entry.ct_eq(fp);
    }
    bool::from(found)
}

/// Build a rustls `ClientConfig` with client-cert auth and a
/// "dangerously-accept-any-server-cert" verifier. Used by the
/// sync-daemon to present its client cert on every outbound request
/// while connecting to peers with self-signed server certs. Peer
/// authenticity is established on the other direction (they verify
/// us via `--mtls-allowlist`).
pub async fn build_rustls_client_config(
    cert_path: &Path,
    key_path: &Path,
) -> Result<rustls::ClientConfig> {
    warn_if_key_perms_loose(key_path);
    let cert_pem = tokio::fs::read(cert_path)
        .await
        .with_context(|| format!("failed to read client cert from {}", cert_path.display()))?;
    let key_pem = tokio::fs::read(key_path)
        .await
        .with_context(|| format!("failed to read client key from {}", key_path.display()))?;

    let certs = rustls_pki_pem_iter_certs(&cert_pem)?;
    let key = rustls_pki_pem_parse_private_key(&key_pem)?;

    // SAFETY: we accept any server cert because the server authenticates
    // US via our client cert fingerprint (Layer 2's trust anchor), not
    // via server-cert validation. Server-cert pinning is a Layer 2b
    // refinement tracked in #224.
    //
    // v0.7.0 S6-LOW1 de-silencing: emit a once-per-process operator-visible
    // warn so the disabled server-cert verification posture is observable in
    // the daemon log rather than buried in the source. The compensating
    // control (peer client-cert fingerprint pinning via `--mtls-allowlist`)
    // is documented on `DangerousAnyServerVerifier`.
    static WARN_ONCE: std::sync::Once = std::sync::Once::new();
    WARN_ONCE.call_once(|| {
        tracing::warn!(
            target: "federation::tls",
            "federation client TLS accepts ANY server certificate (server-cert \
             verification is OFF); peer authenticity relies entirely on the peer \
             fingerprint-pinning our client cert via --mtls-allowlist. Front the \
             federation port with a server-cert-pinning reverse proxy on hostile \
             networks. See docs/runbook/federation-tls.md (#224)."
        );
    });
    let config = rustls::ClientConfig::builder()
        .dangerous()
        .with_custom_certificate_verifier(Arc::new(DangerousAnyServerVerifier))
        .with_client_auth_cert(certs, key)
        .context("failed to build rustls ClientConfig with client cert")?;
    Ok(config)
}

/// `ServerCertVerifier` that accepts any peer certificate. Safe ONLY when
/// paired with a strong reverse authentication channel — in our case the
/// peer's `--mtls-allowlist` fingerprint-pins our client cert.
///
/// # v0.7.0 S6-LOW1 — threat model and compensating control
///
/// This verifier is intentionally permissive on the SERVER cert and is
/// the documented compensating-with-mTLS control for issue #224. The
/// security argument has three legs that must all hold for the
/// resulting channel to remain trustworthy:
///
/// 1. **Client cert is the actual authn primitive.** The peer
///    fingerprint-pins our client cert via `--mtls-allowlist`. A
///    misbehaving server cannot complete the TLS handshake unless our
///    client cert's SHA-256 is on its allowlist; an attacker who has
///    spoofed DNS but lacks our client key is filtered at the peer's
///    `ClientCertVerifier`.
/// 2. **Sync traffic is single-purpose.** The federation channel only
///    carries `/api/v1/sync/push` + `/api/v1/sync/since` payloads. The
///    receiver still validates every memory through
///    `validate::validate_memory`, signs/verifies every link through
///    the H3 verify path, and gates every write through the per-agent
///    quota (S6-M2). A man-in-the-middle would gain nothing by
///    impersonating a server we'd already authenticate ourselves to.
/// 3. **Pinning server certs is a v0.8.0 refinement.** Layer-2b
///    server-cert pinning lands when the `--peer-fingerprint` flag is
///    added (tracked in #224 follow-up). At that point this verifier
///    is replaced with a fingerprint allowlist-checking variant. Until
///    then, operators are explicitly informed via the operator runbook
///    (`docs/runbook/federation-tls.md`) that:
///       - both peers MUST set `--mtls-allowlist` to fingerprint-pin
///         each other's CLIENT cert,
///       - server-cert presentation is not currently authenticated
///         beyond TLS handshake completion,
///       - any deployment that exposes the federation port to a
///         hostile network MUST front the daemon with a reverse proxy
///         that performs server-side cert pinning.
///
/// **Do not use this verifier outside the federation sync-daemon
/// path.** The MCP / CLI / HTTP-app paths use the default rustls
/// verifier with platform roots. Removing the `Dangerous` prefix from
/// the type name would obscure the trade-off and is rejected.
#[derive(Debug)]
pub struct DangerousAnyServerVerifier;

impl rustls::client::danger::ServerCertVerifier for DangerousAnyServerVerifier {
    fn verify_server_cert(
        &self,
        _end_entity: &rustls::pki_types::CertificateDer<'_>,
        _intermediates: &[rustls::pki_types::CertificateDer<'_>],
        _server_name: &rustls::pki_types::ServerName<'_>,
        _ocsp_response: &[u8],
        _now: rustls::pki_types::UnixTime,
    ) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
        Ok(rustls::client::danger::ServerCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &rustls::pki_types::CertificateDer<'_>,
        dss: &rustls::DigitallySignedStruct,
    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        rustls::crypto::verify_tls12_signature(
            message,
            cert,
            dss,
            &rustls::crypto::ring::default_provider().signature_verification_algorithms,
        )
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &rustls::pki_types::CertificateDer<'_>,
        dss: &rustls::DigitallySignedStruct,
    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        rustls::crypto::verify_tls13_signature(
            message,
            cert,
            dss,
            &rustls::crypto::ring::default_provider().signature_verification_algorithms,
        )
    }

    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
        rustls::crypto::ring::default_provider()
            .signature_verification_algorithms
            .supported_schemes()
    }
}

// ---------------------------------------------------------------------------
// Unit tests — pure-function and verifier coverage. Integration tests
// (anything requiring on-disk PEM fixtures end-to-end) live in
// `tests/tls_integration.rs` so the bin's compile time stays small.
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
    use super::*;
    use rustls::server::danger::ClientCertVerifier;

    /// Convenience: write `body` to a temp file and return the temp file
    /// (kept so the caller can `tmp.path()`).
    fn write_tmp(body: &str) -> tempfile::NamedTempFile {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(tmp.path(), body).unwrap();
        tmp
    }

    // -----------------------------------------------------------------------
    // Allowlist parser
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_allowlist_empty_file_errors() {
        // An empty allowlist file produces an empty set. The "refuse to
        // start" check lives in `load_mtls_rustls_config`, not the parser
        // — so the parser succeeds with zero entries.
        let tmp = write_tmp("");
        let set = load_fingerprint_allowlist(tmp.path()).await.unwrap();
        assert!(set.is_empty());
    }

    #[tokio::test]
    async fn test_allowlist_only_comments_errors() {
        // Comment-only file should likewise produce an empty set; the
        // empty-allowlist guard is enforced one layer up.
        let tmp = write_tmp("# header\n# more\n  # indented\n");
        let set = load_fingerprint_allowlist(tmp.path()).await.unwrap();
        assert!(set.is_empty());
    }

    #[tokio::test]
    async fn test_allowlist_single_valid_fp() {
        let fp = "a".repeat(64);
        let tmp = write_tmp(&format!("{fp}\n"));
        let set = load_fingerprint_allowlist(tmp.path()).await.unwrap();
        assert_eq!(set.len(), 1);
        assert!(set.contains(&[0xaa; 32]));
    }

    #[tokio::test]
    async fn test_allowlist_with_colons() {
        let fp = format!("{}:{}", "b".repeat(32), "b".repeat(32));
        let tmp = write_tmp(&format!("{fp}\n"));
        let set = load_fingerprint_allowlist(tmp.path()).await.unwrap();
        assert_eq!(set.len(), 1);
        assert!(set.contains(&[0xbb; 32]));
    }

    #[tokio::test]
    async fn test_allowlist_sha256_prefix() {
        let fp = format!("sha256:{}", "c".repeat(64));
        let tmp = write_tmp(&format!("{fp}\n"));
        let set = load_fingerprint_allowlist(tmp.path()).await.unwrap();
        assert_eq!(set.len(), 1);
        assert!(set.contains(&[0xcc; 32]));
    }

    /// Issue #358 — trailing inline comment after a fingerprint must parse.
    #[tokio::test]
    async fn test_allowlist_inline_comment() {
        let fp = "d".repeat(64);
        let body = format!("{fp}  # node-1 mTLS\n");
        let tmp = write_tmp(&body);
        let set = load_fingerprint_allowlist(tmp.path()).await.unwrap();
        assert_eq!(set.len(), 1);
        assert!(set.contains(&[0xdd; 32]));
    }

    #[tokio::test]
    async fn test_allowlist_too_short_errors() {
        let tmp = write_tmp(&"a".repeat(63));
        let err = load_fingerprint_allowlist(tmp.path()).await.unwrap_err();
        assert!(
            err.to_string().contains("expected 64 hex chars"),
            "got: {err}"
        );
    }

    #[tokio::test]
    async fn test_allowlist_too_long_errors() {
        let tmp = write_tmp(&"a".repeat(65));
        let err = load_fingerprint_allowlist(tmp.path()).await.unwrap_err();
        assert!(
            err.to_string().contains("expected 64 hex chars"),
            "got: {err}"
        );
    }

    #[tokio::test]
    async fn test_allowlist_invalid_hex_errors() {
        // 64 chars, but `z` is non-hex → must hit the strict char check.
        let mut s = "a".repeat(63);
        s.push('z');
        let tmp = write_tmp(&s);
        let err = load_fingerprint_allowlist(tmp.path()).await.unwrap_err();
        assert!(
            err.to_string().contains("unexpected character"),
            "got: {err}"
        );
    }

    /// Issue #338 — embedded whitespace inside the hex run must error
    /// with "unexpected character", not silently get stripped.
    #[tokio::test]
    async fn test_allowlist_embedded_whitespace_errors() {
        let body = format!("{} {}\n", "a".repeat(32), "a".repeat(32));
        let tmp = write_tmp(&body);
        let err = load_fingerprint_allowlist(tmp.path()).await.unwrap_err();
        assert!(
            err.to_string().contains("unexpected character"),
            "got: {err}"
        );
    }

    #[tokio::test]
    async fn test_allowlist_tab_in_hex_errors() {
        let body = format!("{}\t{}\n", "a".repeat(32), "a".repeat(32));
        let tmp = write_tmp(&body);
        let err = load_fingerprint_allowlist(tmp.path()).await.unwrap_err();
        assert!(
            err.to_string().contains("unexpected character"),
            "got: {err}"
        );
    }

    #[tokio::test]
    async fn test_allowlist_blank_lines_skipped() {
        let fp = "a".repeat(64);
        let body = format!("\n\n  \n{fp}\n\n   \n");
        let tmp = write_tmp(&body);
        let set = load_fingerprint_allowlist(tmp.path()).await.unwrap();
        assert_eq!(set.len(), 1);
    }

    #[tokio::test]
    async fn test_allowlist_multiple_entries() {
        let fp_a = "a".repeat(64);
        let fp_b = "b".repeat(64);
        let fp_c = format!("{}:{}", "c".repeat(32), "c".repeat(32));
        let body = format!(
            "# header\n\
             {fp_a}\n\
             sha256:{fp_b}\n\
             {fp_c}\n"
        );
        let tmp = write_tmp(&body);
        let set = load_fingerprint_allowlist(tmp.path()).await.unwrap();
        assert_eq!(set.len(), 3);
        assert!(set.contains(&[0xaa; 32]));
        assert!(set.contains(&[0xbb; 32]));
        assert!(set.contains(&[0xcc; 32]));
    }

    #[tokio::test]
    async fn test_allowlist_duplicate_entries_dedup() {
        let fp = "e".repeat(64);
        let body = format!("{fp}\n{fp}\n{fp}\n");
        let tmp = write_tmp(&body);
        let set = load_fingerprint_allowlist(tmp.path()).await.unwrap();
        // HashSet collapses dupes — exactly one fingerprint registered.
        assert_eq!(set.len(), 1);
        assert!(set.contains(&[0xee; 32]));
    }

    // -----------------------------------------------------------------------
    // PEM parsers
    // -----------------------------------------------------------------------

    #[test]
    fn test_pem_iter_certs_empty_errors() {
        let err = rustls_pki_pem_iter_certs(b"").unwrap_err();
        // No certs at all → either parse-error or "contained no certificates".
        // The empty input is not a parse failure, it's just zero certs.
        assert!(
            err.to_string().contains("no certificates")
                || err.to_string().contains("failed to parse"),
            "got: {err}"
        );
    }

    #[test]
    fn test_pem_iter_certs_garbage_errors() {
        let err = rustls_pki_pem_iter_certs(b"not a pem file\n").unwrap_err();
        assert!(
            err.to_string().contains("no certificates")
                || err.to_string().contains("failed to parse"),
            "got: {err}"
        );
    }

    #[test]
    fn test_pem_iter_certs_single_cert() {
        let pem = std::fs::read("tests/fixtures/tls/valid_cert.pem")
            .expect("regenerate fixtures via tests/fixtures/tls/regenerate.sh");
        let certs = rustls_pki_pem_iter_certs(&pem).unwrap();
        assert_eq!(
            certs.len(),
            1,
            "expected exactly one cert in valid_cert.pem"
        );
    }

    #[test]
    fn test_pem_iter_certs_chain() {
        let pem = std::fs::read("tests/fixtures/tls/cert_chain.pem")
            .expect("regenerate fixtures via tests/fixtures/tls/regenerate.sh");
        let certs = rustls_pki_pem_iter_certs(&pem).unwrap();
        assert!(
            certs.len() >= 2,
            "expected leaf + intermediate, got {}",
            certs.len()
        );
    }

    #[test]
    fn test_pem_parse_pkcs8_key() {
        let pem = std::fs::read("tests/fixtures/tls/valid_key_pkcs8.pem")
            .expect("regenerate fixtures via tests/fixtures/tls/regenerate.sh");
        let key = rustls_pki_pem_parse_private_key(&pem).unwrap();
        // PKCS#8 envelopes RSA / ECDSA / Ed25519. The discriminant tells us
        // rustls picked the right branch — any PrivateKeyDer variant is fine.
        let _ = key;
    }

    #[test]
    fn test_pem_parse_rsa_key() {
        let pem = std::fs::read("tests/fixtures/tls/valid_key_rsa.pem")
            .expect("regenerate fixtures via tests/fixtures/tls/regenerate.sh");
        let key = rustls_pki_pem_parse_private_key(&pem).unwrap();
        let _ = key;
    }

    #[test]
    fn test_pem_parse_sec1_key() {
        let pem = std::fs::read("tests/fixtures/tls/valid_key_sec1.pem")
            .expect("regenerate fixtures via tests/fixtures/tls/regenerate.sh");
        let key = rustls_pki_pem_parse_private_key(&pem).unwrap();
        let _ = key;
    }

    #[test]
    fn test_pem_parse_garbage_errors() {
        let err = rustls_pki_pem_parse_private_key(b"not a pem file\n").unwrap_err();
        assert!(err.to_string().contains("failed to parse TLS key PEM"));
    }

    // -----------------------------------------------------------------------
    // hex_short
    // -----------------------------------------------------------------------

    #[test]
    fn test_hex_short_format() {
        // 6 bytes prefix → 12 hex chars + ellipsis.
        let mut fp = [0u8; 32];
        fp[0] = 0xde;
        fp[1] = 0xad;
        fp[2] = 0xbe;
        fp[3] = 0xef;
        fp[4] = 0x12;
        fp[5] = 0x34;
        // Bytes 6..32 must NOT appear in the output.
        for (i, slot) in fp.iter_mut().enumerate().skip(6) {
            *slot = (i as u8).wrapping_mul(7);
        }
        assert_eq!(hex_short(&fp), "deadbeef1234…");
    }

    #[test]
    fn test_hex_short_truncates_to_6_bytes() {
        let fp = [0xff; 32];
        let s = hex_short(&fp);
        // Strip the trailing ellipsis (`…` is 3 bytes in UTF-8).
        let hex_only = s.trim_end_matches('');
        assert_eq!(hex_only.len(), 12, "expected 6 bytes = 12 hex chars");
        assert_eq!(hex_only, "ffffffffffff");
    }

    // -----------------------------------------------------------------------
    // FingerprintAllowlistVerifier
    // -----------------------------------------------------------------------

    #[test]
    fn test_verifier_accepts_allowlisted_fp() {
        use sha2::{Digest, Sha256};
        // Synthesize a "cert" — the verifier doesn't validate ASN.1 here,
        // only hashes the DER bytes. Any byte slice works; we just need
        // the fingerprint and the cert bytes to match.
        let fake_cert = b"fake certificate DER bytes for fingerprint test";
        let fp: [u8; 32] = Sha256::digest(fake_cert).into();
        let mut allowlist = HashSet::new();
        allowlist.insert(fp);
        let verifier = FingerprintAllowlistVerifier { allowlist };
        let cert = rustls::pki_types::CertificateDer::from(fake_cert.to_vec());
        let now = rustls::pki_types::UnixTime::now();
        let result = verifier.verify_client_cert(&cert, &[], now);
        assert!(result.is_ok(), "expected accept, got: {result:?}");
    }

    #[test]
    fn test_verifier_rejects_unknown_fp() {
        let allowlist = HashSet::new();
        let verifier = FingerprintAllowlistVerifier { allowlist };
        let cert = rustls::pki_types::CertificateDer::from(b"unknown".to_vec());
        let now = rustls::pki_types::UnixTime::now();
        let err = verifier.verify_client_cert(&cert, &[], now).unwrap_err();
        assert!(
            err.to_string().contains("not in mTLS allowlist"),
            "got: {err}"
        );
    }

    #[test]
    fn test_verifier_error_includes_truncated_fp() {
        let allowlist = HashSet::new();
        let verifier = FingerprintAllowlistVerifier { allowlist };
        let cert_bytes = b"some cert that won't be in the allowlist";
        let cert = rustls::pki_types::CertificateDer::from(cert_bytes.to_vec());
        let now = rustls::pki_types::UnixTime::now();
        let err = verifier.verify_client_cert(&cert, &[], now).unwrap_err();
        let msg = err.to_string();
        // Compute the expected truncated fp prefix and assert it's present.
        use sha2::{Digest, Sha256};
        let fp: [u8; 32] = Sha256::digest(cert_bytes).into();
        let short = hex_short(&fp);
        assert!(msg.contains(&short), "expected fp {short} in: {msg}");
        // And the trailing `…` must be there — the fp must be truncated,
        // not full-length.
        assert!(msg.contains(''), "expected truncation marker in: {msg}");
    }

    #[test]
    fn test_verifier_offer_client_auth_returns_true() {
        let verifier = FingerprintAllowlistVerifier {
            allowlist: HashSet::new(),
        };
        assert!(verifier.offer_client_auth());
    }

    #[test]
    fn test_verifier_client_auth_mandatory_returns_true() {
        let verifier = FingerprintAllowlistVerifier {
            allowlist: HashSet::new(),
        };
        assert!(verifier.client_auth_mandatory());
        // Also exercise root_hint_subjects — it's a one-line getter that
        // would otherwise sit at zero coverage.
        assert_eq!(verifier.root_hint_subjects().len(), 0);
    }

    /// Build a bogus `DigitallySignedStruct` from the on-the-wire byte
    /// format: 2-byte big-endian scheme + 2-byte big-endian signature
    /// length + N signature bytes. `DigitallySignedStruct::new` is
    /// crate-private in rustls 0.23, but the wire decoder is reachable
    /// through `rustls::internal::msgs::codec::{Codec, Reader}`.
    fn bogus_dss() -> rustls::DigitallySignedStruct {
        use rustls::internal::msgs::codec::{Codec, Reader};
        // ED25519 = 0x0807. Sig length = 0x0040 (64). Then 64 zero bytes.
        let mut wire = Vec::with_capacity(4 + 64);
        wire.extend_from_slice(&[0x08, 0x07]);
        wire.extend_from_slice(&[0x00, 0x40]);
        wire.extend_from_slice(&[0u8; 64]);
        let mut reader = Reader::init(&wire);
        rustls::DigitallySignedStruct::read(&mut reader)
            .expect("hand-rolled wire bytes must round-trip the Codec")
    }

    /// Exercise the rustls `verify_tls{12,13}_signature` + `supported_verify_schemes`
    /// trait methods on `FingerprintAllowlistVerifier`. We feed them a
    /// deliberately invalid signature so the underlying ring-backed
    /// verifier returns Err — that's fine, the test only asserts the
    /// method runs to completion (covers the body) without panicking.
    #[test]
    fn test_verifier_signature_methods_run() {
        let _ = rustls::crypto::ring::default_provider().install_default();
        let verifier = FingerprintAllowlistVerifier {
            allowlist: HashSet::new(),
        };
        // supported_verify_schemes is pure — must return non-empty.
        let schemes = verifier.supported_verify_schemes();
        assert!(
            !schemes.is_empty(),
            "ring provider must expose at least one signature scheme"
        );

        // verify_tls{12,13}_signature: feed bogus inputs and expect Err.
        let cert = rustls::pki_types::CertificateDer::from(vec![0u8; 32]);
        let dss = bogus_dss();
        let _ = verifier.verify_tls12_signature(b"bogus message", &cert, &dss);
        let _ = verifier.verify_tls13_signature(b"bogus message", &cert, &dss);
    }

    // -----------------------------------------------------------------------
    // DangerousAnyServerVerifier — the sync-daemon's client-side verifier.
    // verify_server_cert always Ok; the signature methods delegate to the
    // ring provider exactly like the server-side verifier above.
    // -----------------------------------------------------------------------

    #[test]
    fn test_dangerous_any_server_verifier_accepts_any_cert() {
        use rustls::client::danger::ServerCertVerifier;
        let _ = rustls::crypto::ring::default_provider().install_default();
        let verifier = DangerousAnyServerVerifier;
        let cert = rustls::pki_types::CertificateDer::from(b"any bytes here".to_vec());
        let server_name = rustls::pki_types::ServerName::try_from("example.com").unwrap();
        let now = rustls::pki_types::UnixTime::now();
        let result = verifier.verify_server_cert(&cert, &[], &server_name, &[], now);
        assert!(
            result.is_ok(),
            "DangerousAnyServerVerifier accepts any cert (compensating mTLS control)"
        );
    }

    #[test]
    fn test_dangerous_any_server_verifier_signature_methods_run() {
        use rustls::client::danger::ServerCertVerifier;
        let _ = rustls::crypto::ring::default_provider().install_default();
        let verifier = DangerousAnyServerVerifier;
        let schemes = verifier.supported_verify_schemes();
        assert!(!schemes.is_empty());

        let cert = rustls::pki_types::CertificateDer::from(vec![0u8; 32]);
        let dss = bogus_dss();
        let _ = verifier.verify_tls12_signature(b"bogus message", &cert, &dss);
        let _ = verifier.verify_tls13_signature(b"bogus message", &cert, &dss);
    }

    // -----------------------------------------------------------------------
    // build_rustls_client_config — exercises the sync-daemon's outbound
    // TLS config path. Covers both the happy and the missing-cert error
    // paths so the entire function body is reached by unit tests.
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_build_rustls_client_config_happy_path() {
        let _ = rustls::crypto::ring::default_provider().install_default();
        let cert = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/tls/valid_cert.pem");
        let key = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/tls/valid_key_pkcs8.pem");
        let config = build_rustls_client_config(&cert, &key)
            .await
            .expect("client config build with valid cert+key");
        // The returned ClientConfig is opaque; if the ?-cascade above
        // returned Ok, every parser branch and the builder ran.
        drop(config);
    }

    // -----------------------------------------------------------------------
    // H3 — TLS version pinning. Both server configs MUST negotiate only
    // TLS 1.2 or TLS 1.3; legacy versions are off the table.
    // -----------------------------------------------------------------------

    #[test]
    fn test_supported_protocol_versions_pinned_to_tls12_and_tls13() {
        // The exported constant must list exactly TLS 1.3 (preferred) and
        // TLS 1.2 (floor) in that order. If a future rustls upgrade adds
        // a fourth `SupportedProtocolVersion` we want this test to fail
        // so the H3 review surfaces the change.
        assert_eq!(
            SUPPORTED_PROTOCOL_VERSIONS.len(),
            2,
            "expected exactly 2 pinned versions (TLS 1.3 + TLS 1.2)"
        );
        // rustls's `SupportedProtocolVersion::version` exposes the
        // wire-level `ProtocolVersion` enum. TLS 1.3 = 0x0304,
        // TLS 1.2 = 0x0303 (per RFC 8446 §4.1.2 / RFC 5246 §A.1).
        let v0 = SUPPORTED_PROTOCOL_VERSIONS[0].version;
        let v1 = SUPPORTED_PROTOCOL_VERSIONS[1].version;
        assert_eq!(v0, rustls::ProtocolVersion::TLSv1_3, "TLS 1.3 preferred");
        assert_eq!(v1, rustls::ProtocolVersion::TLSv1_2, "TLS 1.2 floor");
    }

    #[tokio::test]
    async fn test_load_rustls_config_pins_tls13_and_tls12() {
        // End-to-end: build a real ServerConfig via the production
        // helper and assert it accepts ONLY TLS 1.2 + TLS 1.3.
        let _ = rustls::crypto::ring::default_provider().install_default();
        let cert = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/tls/valid_cert.pem");
        let key = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/tls/valid_key_pkcs8.pem");

        // `rustls::ServerConfig`'s `versions` field is private in 0.23+,
        // so we assert version pinning at the input layer (the
        // `SUPPORTED_PROTOCOL_VERSIONS` constant the production builder
        // consumes) and rely on the test above
        // (`test_supported_protocol_versions_pinned_to_tls12_and_tls13`)
        // for the strict version-list assertion. Here we just confirm
        // the production async path consumes that constant successfully.
        let _config = load_rustls_config(&cert, &key)
            .await
            .expect("load_rustls_config must succeed with valid fixtures");

        // And exercise the mTLS path's protocol pinning by building a
        // FingerprintAllowlistVerifier + ServerConfig with the same
        // version-list input the production builder uses. A successful
        // build is sufficient — rustls refuses to construct a
        // ServerConfig if the version list is empty or malformed.
        let cert_pem = std::fs::read(&cert).unwrap();
        let key_pem = std::fs::read(&key).unwrap();
        let certs = rustls_pki_pem_iter_certs(&cert_pem).unwrap();
        let signing_key = rustls_pki_pem_parse_private_key(&key_pem).unwrap();
        let _server_config =
            rustls::ServerConfig::builder_with_protocol_versions(SUPPORTED_PROTOCOL_VERSIONS)
                .with_no_client_auth()
                .with_single_cert(certs, signing_key)
                .expect("ServerConfig with pinned versions must build");
    }

    // -----------------------------------------------------------------------
    // H4 — loose-permission warning. The check is best-effort + WARN-only
    // by design; we exercise the path on Unix where it has observable
    // semantics, and confirm it's a no-op when permissions are tight.
    // -----------------------------------------------------------------------

    /// Shared `MakeWriter` shim for the H4 WARN-capture tests. Uses an
    /// `Arc<Mutex<Vec<u8>>>` so the test can inspect every byte the
    /// subscriber emitted after the WARN call. Defined outside the
    /// per-test fn so the `MakeWriter` impl is namespace-stable.
    #[cfg(unix)]
    #[derive(Clone, Default)]
    struct WarnBuf(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);

    #[cfg(unix)]
    impl std::io::Write for WarnBuf {
        fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(b);
            Ok(b.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    #[cfg(unix)]
    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for WarnBuf {
        type Writer = WarnBuf;
        fn make_writer(&'a self) -> Self::Writer {
            self.clone()
        }
    }

    #[cfg(unix)]
    #[test]
    fn test_warn_if_key_perms_loose_emits_warn_on_world_readable() {
        use std::os::unix::fs::PermissionsExt as _;
        use tracing::Level;

        let sink = WarnBuf::default();
        let buf = sink.0.clone();
        let subscriber = tracing_subscriber::fmt()
            .with_max_level(Level::WARN)
            .with_writer(sink)
            .without_time()
            .finish();

        let key = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(key.path(), b"dummy keymat").unwrap();
        std::fs::set_permissions(key.path(), std::fs::Permissions::from_mode(0o644)).unwrap();

        tracing::subscriber::with_default(subscriber, || {
            warn_if_key_perms_loose(key.path());
        });

        let captured = String::from_utf8(buf.lock().unwrap().clone()).unwrap();
        assert!(
            captured.contains("group- or world-accessible"),
            "expected WARN about loose perms, got: {captured:?}"
        );
        assert!(
            captured.contains("0600"),
            "expected guidance pointer to 0600 in WARN, got: {captured:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_warn_if_key_perms_loose_silent_on_0600() {
        use std::os::unix::fs::PermissionsExt as _;
        use tracing::Level;

        let sink = WarnBuf::default();
        let buf = sink.0.clone();
        let subscriber = tracing_subscriber::fmt()
            .with_max_level(Level::WARN)
            .with_writer(sink)
            .without_time()
            .finish();

        let key = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(key.path(), b"dummy keymat").unwrap();
        std::fs::set_permissions(key.path(), std::fs::Permissions::from_mode(0o600)).unwrap();

        tracing::subscriber::with_default(subscriber, || {
            warn_if_key_perms_loose(key.path());
        });

        let captured = String::from_utf8(buf.lock().unwrap().clone()).unwrap();
        assert!(
            !captured.contains("group- or world-accessible"),
            "0600 perms must NOT trigger the WARN; got: {captured:?}"
        );
    }

    // -----------------------------------------------------------------------
    // M1 — constant-time allowlist membership. We can't assert timing
    // directly in a unit test (jitter / scheduler noise), but we can
    // assert the correctness of the function on a populated allowlist
    // and on a near-miss (single-byte difference) to confirm the
    // XOR-fold runs the full 32 bytes before reporting.
    // -----------------------------------------------------------------------

    #[test]
    fn test_allowlist_contains_ct_matches_real_entry() {
        let mut allowlist = HashSet::new();
        allowlist.insert([0xaa; 32]);
        allowlist.insert([0xbb; 32]);
        allowlist.insert([0xcc; 32]);
        assert!(allowlist_contains_ct(&allowlist, &[0xbb; 32]));
    }

    #[test]
    fn test_allowlist_contains_ct_rejects_one_byte_off() {
        let mut allowlist = HashSet::new();
        allowlist.insert([0xaa; 32]);
        let mut near = [0xaa; 32];
        near[31] = 0xab; // single-byte flip
        assert!(!allowlist_contains_ct(&allowlist, &near));
    }

    #[test]
    fn test_allowlist_contains_ct_empty_allowlist_rejects() {
        let allowlist = HashSet::new();
        assert!(!allowlist_contains_ct(&allowlist, &[0u8; 32]));
    }

    #[tokio::test]
    async fn test_build_rustls_client_config_missing_cert_errors() {
        let cert = std::path::PathBuf::from("/does/not/exist/cert.pem");
        let key = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/tls/valid_key_pkcs8.pem");
        let err = build_rustls_client_config(&cert, &key)
            .await
            .expect_err("missing client cert must error");
        assert!(
            err.to_string().contains("failed to read client cert"),
            "got: {err}"
        );
    }

    // -----------------------------------------------------------------------
    // C-5 (#699): close the `load_mtls_rustls_config` gap.
    //
    // The mTLS server config path was completely uncovered at lib-tier
    // (38 lines / 38 misses → tls.rs sat at 92.94%). These tests drive
    // the happy path against the real PEM fixtures, the empty-allowlist
    // refusal, and the read-error branches for the cert + key paths.
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_load_mtls_rustls_config_happy_path() {
        let _ = rustls::crypto::ring::default_provider().install_default();
        let cert = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/tls/valid_cert.pem");
        let key = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/tls/valid_key_pkcs8.pem");
        // Build a single-entry allowlist on disk; the parser converts hex
        // into a [u8; 32] which goes into the verifier. Hex content is
        // irrelevant to the builder — it just needs to be non-empty so
        // the empty-allowlist refusal does not trip.
        let allowlist = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(allowlist.path(), format!("{}\n", "a".repeat(64))).unwrap();

        let config = load_mtls_rustls_config(&cert, &key, allowlist.path())
            .await
            .expect("mTLS server config build with valid cert+key+allowlist");
        // Returned RustlsConfig is opaque; success of the ?-cascade is
        // the contract.
        drop(config);
    }

    #[tokio::test]
    async fn test_load_mtls_rustls_config_empty_allowlist_refuses() {
        // Line 148-152: the operator-friendly refusal when an allowlist
        // file parses but contains zero fingerprints. We deliberately
        // never reach the cert/key reads.
        let cert = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/tls/valid_cert.pem");
        let key = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/tls/valid_key_pkcs8.pem");
        let allowlist = tempfile::NamedTempFile::new().unwrap();
        // Comment-only allowlist — parses successfully, but the set is empty.
        std::fs::write(allowlist.path(), "# nothing here\n").unwrap();

        let err = load_mtls_rustls_config(&cert, &key, allowlist.path())
            .await
            .expect_err("empty allowlist must refuse to start");
        let msg = err.to_string();
        assert!(
            msg.contains("empty") && msg.contains("refuse"),
            "expected refuse-to-start error, got: {msg}"
        );
    }

    #[tokio::test]
    async fn test_load_mtls_rustls_config_missing_cert_errors() {
        // Line 156-158: cert-read failure path inside the mTLS builder.
        let cert = std::path::PathBuf::from("/does/not/exist/mtls-cert.pem");
        let key = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/tls/valid_key_pkcs8.pem");
        let allowlist = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(allowlist.path(), format!("{}\n", "b".repeat(64))).unwrap();

        let err = load_mtls_rustls_config(&cert, &key, allowlist.path())
            .await
            .expect_err("missing cert must error");
        assert!(
            err.to_string().contains("failed to read TLS cert"),
            "got: {err}"
        );
    }

    #[tokio::test]
    async fn test_load_mtls_rustls_config_missing_key_errors() {
        // Line 159-161: key-read failure path inside the mTLS builder.
        let cert = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/tls/valid_cert.pem");
        let key = std::path::PathBuf::from("/does/not/exist/mtls-key.pem");
        let allowlist = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(allowlist.path(), format!("{}\n", "c".repeat(64))).unwrap();

        let err = load_mtls_rustls_config(&cert, &key, allowlist.path())
            .await
            .expect_err("missing key must error");
        assert!(
            err.to_string().contains("failed to read TLS key"),
            "got: {err}"
        );
    }

    #[tokio::test]
    async fn test_load_mtls_rustls_config_missing_allowlist_errors() {
        // The first read inside load_mtls_rustls_config — the allowlist
        // file itself — must surface a clean error envelope when the
        // file does not exist.
        let cert = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/tls/valid_cert.pem");
        let key = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/tls/valid_key_pkcs8.pem");
        let allowlist = std::path::PathBuf::from("/does/not/exist/allowlist.txt");

        let err = load_mtls_rustls_config(&cert, &key, &allowlist)
            .await
            .expect_err("missing allowlist must error");
        assert!(
            err.to_string().contains("failed to read mTLS allowlist"),
            "got: {err}"
        );
    }
}