plecto-control 0.3.7

Plecto's control plane: declarative manifest, OCI artifact loading, filter-chain dispatch, and atomic hot reload.
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
//! TLS termination config (ADR 000014): build a rustls `ServerConfig` from the manifest's
//! `[[tls]]` certs at load/reload. Cert selection is by SNI — a per-host cert, falling back to a
//! host-less default; if neither matches, the handshake is refused (no cert to present), which is
//! fail-closed. Building here (not in the server) means a bad cert aborts the whole build, so a
//! failed reload never swaps in a TLS config that cannot serve, and the config rides `ActiveConfig`
//! behind the same `ArcSwap` as the filter set. Sync rustls + the `aws_lc_rs` provider (ADR
//! 000051 — one crypto backend shared with the QUIC config and the host's `sigstore` dependency);
//! the async acceptor lives in `plecto-server`. Session resumption is stateless (ADR 000052): by
//! default one process-lifetime ticket key (6h rotation / 12h window, node-local per ADR 000053),
//! or — opt-in via `[resumption]` (ADR 000062) — cert-bound keys derived from a shared file
//! (`stek.rs`) so tickets resume across replicas. Either way: no stateful session cache, 0-RTT
//! refused as an invariant.

use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, LazyLock, OnceLock};

use rustls::ServerConfig;
use rustls::crypto::aws_lc_rs as provider;
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::server::{ClientHello, NoServerSessionStorage, ProducesTickets, ResolvesServerCert};
use rustls::sign::CertifiedKey;
use sha2::{Digest, Sha256};

use crate::error::ControlError;
use crate::manifest::{ClientAuth, Resumption, TlsCert};
use crate::stek::SharedStekTicketer;

/// SNI cert selection (ADR 000014): a per-host cert map plus an optional default. `resolve` is
/// called by rustls during the handshake with the client's SNI; no match and no default → `None`,
/// and rustls fails the handshake (fail-closed — Plecto presents no cert it was not configured to).
#[derive(Debug)]
struct SniResolver {
    by_host: HashMap<String, Arc<CertifiedKey>>,
    default: Option<Arc<CertifiedKey>>,
}

impl ResolvesServerCert for SniResolver {
    fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
        hello
            .server_name()
            .and_then(|name| {
                // The map keys are lowercased at build; a wire SNI is almost always lowercase
                // already, so the common case looks up borrowed — the lowercasing allocation is
                // paid only when a client actually sent uppercase.
                if name.bytes().any(|b| b.is_ascii_uppercase()) {
                    self.by_host.get(&name.to_ascii_lowercase())
                } else {
                    self.by_host.get(name)
                }
            })
            .cloned()
            .or_else(|| self.default.clone())
    }
}

/// The process-lifetime session-ticket producer (ADR 000052): `aws_lc_rs::Ticketer` = rustls'
/// `TicketRotator` over RFC 5077 §4 self-encrypted tickets, 6h key rotation with a 12h acceptance
/// window (current + previous key). ONE instance for the whole process — shared by the TCP and
/// QUIC configs (a ticket obtained over either resumes on both; both configs present the same
/// certs via the shared `SniResolver`, so rustls' cross-config resumption caveat does not bite)
/// and, critically, surviving manifest reloads: rebuilding the `ServerConfig`s must not invalidate
/// outstanding tickets. Keys live in process memory only, node-local (ADR 000053) — never on disk,
/// never in the manifest.
///
/// **Exception — `[listen.client_auth]`:** when mTLS gates access, the build uses a per-CA-content
/// ticketer (`client_auth_ticketer`), never this process-wide producer. TLS 1.3 PSK resumption
/// skips CertificateRequest, so ticket keys must be isolated from the anonymous context and
/// rotate with the trust roots that authenticated the peer.
fn shared_ticketer() -> Result<Arc<dyn ProducesTickets>, ControlError> {
    static TICKETER: OnceLock<Arc<dyn ProducesTickets>> = OnceLock::new();
    if let Some(ticketer) = TICKETER.get() {
        return Ok(ticketer.clone());
    }
    // Fallible init outside `get_or_init` (which can't return errors): the race where two threads
    // both construct is benign — one wins the OnceLock, the loser's keys are dropped unissued.
    let fresh = provider::Ticketer::new().map_err(|e| ControlError::TlsCert {
        host: None,
        path: String::new(),
        reason: format!("session-ticket key init: {e}"),
    })?;
    Ok(TICKETER.get_or_init(|| fresh).clone())
}

/// Ticket producer for an mTLS-enabled build, keyed by the CA bundle's content digest: a reload
/// that leaves the CA bytes unchanged keeps outstanding tickets resumable (no full-handshake
/// stampede for an unrelated config edit), while a CA rotation re-keys so no ticket outlives the
/// trust roots that authenticated its peer (TLS 1.3 PSK resumption skips CertificateRequest).
/// Never the process-wide anonymous ticketer: an anonymous-era ticket must not resume once
/// client_auth gates access. The map holds one entry per distinct CA content seen this process —
/// operator-driven rotations, so bounded in practice.
fn client_auth_ticketer(ca_bytes: &[u8]) -> Result<Arc<dyn ProducesTickets>, ControlError> {
    type ByCaDigest = HashMap<[u8; 32], Arc<dyn ProducesTickets>>;
    static BY_CA: LazyLock<parking_lot::Mutex<ByCaDigest>> =
        LazyLock::new(|| parking_lot::Mutex::new(HashMap::new()));
    let digest: [u8; 32] = Sha256::digest(ca_bytes).into();
    let mut by_ca = BY_CA.lock();
    if let Some(ticketer) = by_ca.get(&digest) {
        return Ok(ticketer.clone());
    }
    let fresh = provider::Ticketer::new().map_err(|e| ControlError::TlsCert {
        host: None,
        path: String::new(),
        reason: format!("client-auth session-ticket key init: {e}"),
    })?;
    by_ca.insert(digest, fresh.clone());
    Ok(fresh)
}

/// The TLS configs built from `[[tls]]`: the TCP config (HTTP/1.1 + HTTP/2 via ALPN, ADR 000015)
/// and the QUIC config (HTTP/3, ADR 000016). Both share one SNI cert resolver, so a host's cert is
/// presented identically over TCP and QUIC.
pub(crate) struct TlsConfigs {
    /// HTTP/1.1 + HTTP/2 over TCP: ALPN `[h2, http/1.1]`, TLS 1.2 + 1.3.
    pub(crate) tcp: Arc<ServerConfig>,
    /// HTTP/3 over QUIC: ALPN `[h3]`, TLS 1.3 only.
    pub(crate) quic: Arc<ServerConfig>,
}

/// Build the TCP + QUIC TLS `ServerConfig`s from the manifest's `[[tls]]` entries, or `None` when
/// there are none (the server then serves plain HTTP/1.1, no h3). Any unreadable / unparsable /
/// duplicate cert is a fail-closed `ControlError` that aborts the caller's build (ADR 000014). The
/// TCP config advertises ALPN `[h2, http/1.1]` (h2 preferred, ADR 000015); the QUIC config
/// advertises `[h3]` and is TLS-1.3 only (QUIC mandates 1.3, RFC 9001). Both share one `SniResolver`.
///
/// `client_auth` carries the CA bundle's bytes alongside the manifest section: the caller reads
/// the file ONCE (`Manifest::read_client_auth_ca`) and shares it between the config version and
/// the verifier built here, so the two can never describe different trust roots.
pub(crate) fn build_server_configs(
    entries: &[TlsCert],
    resumption: Option<&Resumption>,
    client_auth: Option<(&ClientAuth, &[u8])>,
    base_dir: &Path,
) -> Result<Option<TlsConfigs>, ControlError> {
    // ADR 000062 (b) / 000078: TLS 1.3 resumption accepts a ticket without re-running
    // client-certificate verification (CertificateRequest is omitted under a resumption PSK;
    // rustls restores the chain from the ticket instead). A shared STEK lets that ticket open
    // on every replica — amplifying stolen-ticket blast radius and the CVE-2025-23419-class
    // cross-context risk — so refuse the combination. Per-node resumption stays available:
    // the ticket still carries the verified identity, and its keys never leave this node.
    if let (Some(resumption), Some(_)) = (resumption, client_auth) {
        return Err(ControlError::Stek {
            path: resumption.stek_file.clone(),
            reason: "[resumption] shared STEK cannot be combined with [listen.client_auth]: a \
                     cross-replica ticket would resume without re-running client-certificate \
                     verification (ADR 000062 (b) / 000078) — drop [resumption] to keep \
                     per-node resumption"
                .to_string(),
        });
    }
    if entries.is_empty() {
        // `[resumption]` without any `[[tls]]` is a config mistake, not a no-op: the operator
        // asked for cross-replica resumption on a proxy that terminates no TLS. Fail closed.
        if let Some(resumption) = resumption {
            return Err(ControlError::Stek {
                path: resumption.stek_file.clone(),
                reason: "[resumption] requires at least one [[tls]] cert (ticket keys bind to \
                         the cert set, ADR 000062)"
                    .to_string(),
            });
        }
        // Same shape for `[listen.client_auth]`: there is no TLS handshake to authenticate a
        // client on, so the section is a mistake, not a no-op.
        if let Some((auth, _)) = client_auth {
            return Err(ControlError::ClientAuthCa {
                path: auth.ca_path.clone(),
                reason: "[listen.client_auth] requires at least one [[tls]] cert — a plain-HTTP \
                         listener has no handshake to verify a client certificate in"
                    .to_string(),
            });
        }
        return Ok(None);
    }

    let mut by_host: HashMap<String, Arc<CertifiedKey>> = HashMap::new();
    let mut default: Option<Arc<CertifiedKey>> = None;
    let mut all_certified: Vec<Arc<CertifiedKey>> = Vec::with_capacity(entries.len());
    for entry in entries {
        let certified = Arc::new(load_certified_key(entry, base_dir)?);
        all_certified.push(certified.clone());
        match &entry.host {
            Some(host) => {
                if by_host
                    .insert(host.to_ascii_lowercase(), certified)
                    .is_some()
                {
                    return Err(tls_err(entry, "duplicate cert for this SNI host"));
                }
            }
            None => {
                if default.replace(certified).is_some() {
                    return Err(tls_err(entry, "more than one default (host-less) cert"));
                }
            }
        }
    }

    // One resolver, shared by both configs (Arc clone): SNI selects the same cert over TCP and QUIC.
    let resolver = Arc::new(SniResolver { by_host, default });
    // One ticket producer, ditto: stateless TLS 1.3 resumption over both paths. Default is the
    // per-node process-lifetime key (ADR 000052); `[resumption]` swaps in the shared cert-bound
    // ticketer (ADR 000062) — rebuilt each build, which is safe because its keys are a pure
    // function of (key file, cert set): unchanged inputs re-derive the same keys across reloads.
    // `[listen.client_auth]` uses the per-CA-content ticketer: a CA rotation re-keys (PSK
    // resumption must not outlive the verifier), an unrelated reload keeps tickets valid.
    let ticketer: Arc<dyn ProducesTickets> = match (resumption, client_auth) {
        (Some(resumption), _) => SharedStekTicketer::from_manifest(
            resumption,
            base_dir,
            cert_set_binding(&all_certified, resumption)?,
        )?,
        (None, Some((_, ca_bytes))) => client_auth_ticketer(ca_bytes)?,
        (None, None) => shared_ticketer()?,
    };

    // Downstream client-certificate verification ([listen.client_auth], ADR 000078): one
    // required-mode verifier for BOTH configs — the granularity is the listener, and TCP + QUIC
    // are two wire faces of the same one. `None` = today's no-client-auth listener.
    let client_verifier = client_auth
        .map(|(auth, ca_bytes)| build_client_verifier(auth, ca_bytes))
        .transpose()?;

    // TCP: HTTP/1.1 + HTTP/2 via ALPN (h2 preferred, ADR 000015), TLS 1.2 + 1.3.
    let tcp_builder = ServerConfig::builder_with_provider(Arc::new(provider::default_provider()))
        .with_safe_default_protocol_versions()
        .map_err(provider_init_err)?;
    let mut tcp = match &client_verifier {
        Some(verifier) => tcp_builder.with_client_cert_verifier(verifier.clone()),
        None => tcp_builder.with_no_client_auth(),
    }
    .with_cert_resolver(resolver.clone());
    tcp.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];

    // QUIC: HTTP/3, ALPN `h3`, TLS 1.3 only (ADR 000016). 0-RTT stays disabled: `max_early_data_size`
    // is left at its default 0, so the server refuses TLS early data. A gateway must not forward
    // early-data requests to upstreams that may not emit 425 (Too Early) (RFC 8470), so refusing it
    // outright is the only safe choice here. The stateless ticketer below refuses it a second way
    // (rustls only configures early data when the ticketer is DISabled) — but the invariant test
    // pins `max_early_data_size == 0` on its own, so a rustls behavior change cannot reopen 0-RTT.
    let quic_builder = ServerConfig::builder_with_provider(Arc::new(provider::default_provider()))
        .with_protocol_versions(&[&rustls::version::TLS13])
        .map_err(provider_init_err)?;
    let mut quic = match &client_verifier {
        Some(verifier) => quic_builder.with_client_cert_verifier(verifier.clone()),
        None => quic_builder.with_no_client_auth(),
    }
    .with_cert_resolver(resolver);
    quic.alpn_protocols = vec![b"h3".to_vec()];

    // Stateless session resumption (ADR 000052), replacing the implicit rustls default (a
    // 256-entry stateful cache whose tickets are lookup keys). The self-encrypted ticket carries
    // the session; per-session server memory is ZERO and there is no cache-size knob to fall off —
    // the same bounded-memory discipline as native rate limit (ADR 000033, CWE-770). TLS 1.2
    // clients get RFC 5077 stateless tickets from the same producer; 1.2 session-ID resumption is
    // gone with the cache, which is the point.
    for config in [&mut tcp, &mut quic] {
        config.ticketer = ticketer.clone();
        config.session_storage = Arc::new(NoServerSessionStorage {});
    }

    Ok(Some(TlsConfigs {
        tcp: Arc::new(tcp),
        quic: Arc::new(quic),
    }))
}

/// Build the required-mode client-certificate verifier from `[listen.client_auth]` (ADR 000078).
/// `ca_path` holds trust ANCHORS only — a client's intermediates belong in the chain the client
/// presents, per X.509 path building. Required mode is the only mode: a peer presenting no (or
/// an untrusted) certificate fails the handshake, since "request but allow none" only pays off
/// once verified identities propagate to filters — declared deferred by the ADR. Certificate
/// revocation (CRL/OCSP) is likewise out of this slice: no CRLs are configured, matching that
/// declared deferral.
fn build_client_verifier(
    auth: &ClientAuth,
    ca_bytes: &[u8],
) -> Result<Arc<dyn rustls::server::danger::ClientCertVerifier>, ControlError> {
    let err = |reason: String| ControlError::ClientAuthCa {
        path: auth.ca_path.clone(),
        reason,
    };
    let certs = CertificateDer::pem_slice_iter(ca_bytes)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| err(format!("bad CA PEM: {e}")))?;
    if certs.is_empty() {
        return Err(err("no certificates in CA PEM".to_string()));
    }
    let mut roots = rustls::RootCertStore::empty();
    let (added, _ignored) = roots.add_parsable_certificates(certs);
    if added == 0 {
        return Err(err("no usable trust anchor in CA PEM".to_string()));
    }
    rustls::server::WebPkiClientVerifier::builder_with_provider(
        Arc::new(roots),
        Arc::new(provider::default_provider()),
    )
    .build()
    .map_err(|e| err(format!("client verifier: {e}")))
}

/// Build the rustls `ClientConfig` for one `[upstream.tls]` entry (ADR 000042): server
/// certificate verification is ALWAYS on — against the manifest's CA bundle when `ca_path` is
/// set (replacing, not extending, the webpki roots: an internal-CA deployment trusts exactly its
/// CA), else against the webpki (Mozilla) roots. ALPN is left unset here BY CONTRACT: the fast
/// path's HTTPS connector owns it (hyper-rustls rejects a pre-populated list) and advertises
/// `[h2, http/1.1]` — the negotiation result, not manifest config, selects the upstream protocol.
/// Built at load/reload like the server configs above, so a bad CA fails the build closed.
/// When `client_cert_path`/`client_key_path` declare an identity (upstream mTLS, ADR 000078),
/// every TLS leg to this upstream presents it — forwarded requests and health probes share the
/// connector this config feeds.
pub(crate) fn build_upstream_client_config(
    upstream_name: &str,
    tls: &crate::manifest::UpstreamTls,
    base_dir: &Path,
) -> Result<Arc<rustls::ClientConfig>, ControlError> {
    let mut roots = rustls::RootCertStore::empty();
    match &tls.ca_path {
        Some(ca_path) => {
            let err = |reason: String| ControlError::UpstreamTlsCa {
                upstream: upstream_name.to_string(),
                path: ca_path.clone(),
                reason,
            };
            let bytes = std::fs::read(base_dir.join(ca_path))
                .map_err(|e| err(format!("read failed: {e}")))?;
            let certs = CertificateDer::pem_slice_iter(&bytes)
                .collect::<Result<Vec<_>, _>>()
                .map_err(|e| err(format!("bad CA PEM: {e}")))?;
            if certs.is_empty() {
                return Err(err("no certificates in CA PEM".to_string()));
            }
            let (added, _ignored) = roots.add_parsable_certificates(certs);
            if added == 0 {
                return Err(err("no usable root certificate in CA PEM".to_string()));
            }
        }
        None => {
            roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
        }
    }
    let builder =
        rustls::ClientConfig::builder_with_provider(Arc::new(provider::default_provider()))
            .with_safe_default_protocol_versions()
            .map_err(provider_init_err)?
            .with_root_certificates(roots);
    let config = match (&tls.client_cert_path, &tls.client_key_path) {
        (None, None) => builder.with_no_client_auth(),
        (Some(cert_path), Some(key_path)) => {
            let cerr = |path: &str, reason: String| ControlError::UpstreamClientCert {
                upstream: upstream_name.to_string(),
                path: path.to_string(),
                reason,
            };
            let cert_bytes = std::fs::read(base_dir.join(cert_path))
                .map_err(|e| cerr(cert_path, format!("read failed: {e}")))?;
            let chain = CertificateDer::pem_slice_iter(&cert_bytes)
                .collect::<Result<Vec<_>, _>>()
                .map_err(|e| cerr(cert_path, format!("bad cert PEM: {e}")))?;
            if chain.is_empty() {
                return Err(cerr(
                    cert_path,
                    "no certificates in client cert PEM".to_string(),
                ));
            }
            let key_file = base_dir.join(key_path);
            owner_only(&key_file).map_err(|reason| cerr(key_path, reason))?;
            // Same Zeroizing discipline as `read_key` for [[tls]] server keys: wipe the source
            // PEM buffer after `PrivateKeyDer` has copied the material.
            let key_bytes = zeroize::Zeroizing::new(
                std::fs::read(&key_file)
                    .map_err(|e| cerr(key_path, format!("read failed: {e}")))?,
            );
            let key = PrivateKeyDer::from_pem_slice(&key_bytes)
                .map_err(|e| cerr(key_path, format!("bad key PEM: {e}")))?;
            builder
                .with_client_auth_cert(chain, key)
                .map_err(|e| cerr(cert_path, format!("client cert/key rejected: {e}")))?
        }
        (Some(path), None) | (None, Some(path)) => {
            return Err(ControlError::UpstreamClientCert {
                upstream: upstream_name.to_string(),
                path: path.clone(),
                reason: "client_cert_path and client_key_path must be set together — half an \
                         identity cannot be presented (fail-closed)"
                    .to_string(),
            });
        }
    };
    Ok(Arc::new(config))
}

/// The ADR 000062 (d) key-file discipline applied to this slice's new private keys: reject
/// group/other readability outright (unix; other platforms have no mode bits to check). The
/// pre-existing `[[tls]]` server keys are NOT checked — retrofitting would break running
/// configs, a separate decision (ADR 000078 grill 確定 6).
fn owner_only(path: &Path) -> Result<(), String> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(path)
            .map_err(|e| format!("read failed: {e}"))?
            .permissions()
            .mode();
        if mode & 0o077 != 0 {
            return Err(format!(
                "file mode {:o} is readable by group/other — chmod 600 (owner-only) required",
                mode & 0o777
            ));
        }
    }
    #[cfg(not(unix))]
    {
        let _ = path;
    }
    Ok(())
}

/// Parse one `[upstream.tls] sni` verification-name override into a rustls `ServerName` (ADR
/// 000050). Fail-closed at build, like the CA bundle above: a name that parses as neither a DNS
/// name nor an IP address aborts the reconcile before the registry mutates, rather than letting
/// every TLS leg to this upstream fail at request time.
pub(crate) fn parse_upstream_sni(
    upstream_name: &str,
    sni: &str,
) -> Result<rustls::pki_types::ServerName<'static>, ControlError> {
    rustls::pki_types::ServerName::try_from(sni.to_string()).map_err(|e| {
        ControlError::UpstreamTlsSni {
            upstream: upstream_name.to_string(),
            sni: sni.to_string(),
            reason: e.to_string(),
        }
    })
}

/// The cert-set binding identity fed to the shared-STEK key schedule (ADR 000062 (a)): SHA-256
/// over the sorted, deduplicated SPKI SHA-256 fingerprints of every `[[tls]]` cert. SPKI (the
/// RFC 7469 pin basis), not the whole cert: the key pair is the cryptographic identity, so a
/// routine renewal under the same key keeps outstanding tickets resumable, while any cert-set
/// difference between deployments derives disjoint ticket keys. `ProducesTickets` is per-config
/// (rustls cannot tell the ticketer which SNI cert a handshake selected), so the binding is the
/// SET — cross-SNI acceptance inside one config is separately refused by rustls' own SNI match
/// on resumption (`resumedata.sni == sni`, pinned by an E2E test).
///
/// The SPKI comes from the loaded private key (`SigningKey::public_key`), not from parsing the
/// cert: `load_certified_key` already verified they match (`keys_match`), and this avoids an
/// X.509 parser dependency. A provider that cannot expose it fails the build closed — shared
/// STEK without a binding identity is exactly the unbound sharing the ADR rejects.
fn cert_set_binding(
    certified: &[Arc<CertifiedKey>],
    resumption: &Resumption,
) -> Result<[u8; 32], ControlError> {
    use sha2::{Digest, Sha256};
    let mut fingerprints: Vec<[u8; 32]> = Vec::with_capacity(certified.len());
    for certified_key in certified {
        let spki = certified_key
            .key
            .public_key()
            .ok_or_else(|| ControlError::Stek {
                path: resumption.stek_file.clone(),
                reason:
                    "a [[tls]] key's SPKI is unavailable from the provider; shared STEK cannot \
                     bind tickets to the cert set (ADR 000062 (a))"
                        .to_string(),
            })?;
        fingerprints.push(Sha256::digest(spki.as_ref()).into());
    }
    fingerprints.sort_unstable();
    fingerprints.dedup();
    let mut hasher = Sha256::new();
    for fingerprint in &fingerprints {
        hasher.update(fingerprint);
    }
    Ok(hasher.finalize().into())
}

/// A rustls provider/version init failure (not a per-cert fault) mapped to a fail-closed error.
fn provider_init_err(e: rustls::Error) -> ControlError {
    ControlError::TlsCert {
        host: None,
        path: String::new(),
        reason: format!("rustls provider init: {e}"),
    }
}

/// Read + parse one `[[tls]]` entry's PEM cert chain and private key into a `CertifiedKey`.
fn load_certified_key(entry: &TlsCert, base_dir: &Path) -> Result<CertifiedKey, ControlError> {
    let cert_chain = read_certs(entry, base_dir)?;
    if cert_chain.is_empty() {
        return Err(tls_err(entry, "no certificates in cert_path PEM"));
    }
    let key = read_key(entry, base_dir)?;
    let signing_key = provider::sign::any_supported_type(&key)
        .map_err(|e| tls_err(entry, &format!("unsupported private key: {e}")))?;
    let certified = CertifiedKey::new(cert_chain, signing_key);
    // `CertifiedKey::new` does NOT verify the private key matches the leaf certificate, so a
    // mismatched cert/key pair would build successfully and then fail EVERY TLS handshake at
    // runtime — contradicting this module's fail-closed-at-build contract. Verify here. `Unknown`
    // (the provider can't expose the key's SPKI) is not a mismatch — accept it, mirroring rustls'
    // own `CertifiedKey::from_der`. The `aws_lc_rs` provider does expose it, so a real mismatch is
    // caught.
    match certified.keys_match() {
        Ok(()) | Err(rustls::Error::InconsistentKeys(rustls::InconsistentKeys::Unknown)) => {}
        Err(e) => return Err(tls_err(entry, &format!("cert/key mismatch: {e}"))),
    }
    Ok(certified)
}

fn read_certs(
    entry: &TlsCert,
    base_dir: &Path,
) -> Result<Vec<CertificateDer<'static>>, ControlError> {
    let bytes = std::fs::read(base_dir.join(&entry.cert_path))
        .map_err(|e| tls_err_path(entry, &entry.cert_path, &format!("read failed: {e}")))?;
    // PEM parsing lives in rustls-pki-types now (rustls-pemfile is unmaintained, RUSTSEC-2025-0134).
    CertificateDer::pem_slice_iter(&bytes)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| tls_err_path(entry, &entry.cert_path, &format!("bad cert PEM: {e}")))
}

fn read_key(entry: &TlsCert, base_dir: &Path) -> Result<PrivateKeyDer<'static>, ControlError> {
    // `Zeroizing`: `PrivateKeyDer` wipes its own copy on drop, but the source PEM buffer would
    // otherwise linger in freed heap — wipe it too (same discipline as the STEK IKM read).
    let bytes = zeroize::Zeroizing::new(
        std::fs::read(base_dir.join(&entry.key_path))
            .map_err(|e| tls_err_path(entry, &entry.key_path, &format!("read failed: {e}")))?,
    );
    // `from_pem_slice` returns the first private key, or a typed error if there is none / it is
    // malformed — so the previous "no key" branch folds into the error path.
    PrivateKeyDer::from_pem_slice(&bytes)
        .map_err(|e| tls_err_path(entry, &entry.key_path, &format!("bad key PEM: {e}")))
}

fn tls_err(entry: &TlsCert, reason: &str) -> ControlError {
    tls_err_path(entry, &entry.cert_path, reason)
}

fn tls_err_path(entry: &TlsCert, path: &str, reason: &str) -> ControlError {
    ControlError::TlsCert {
        host: entry.host.clone(),
        path: path.to_string(),
        reason: reason.to_string(),
    }
}

impl crate::Control {
    /// The active TLS server config (ADR 000014), or `None` for plain HTTP/1.1. The fast-path
    /// server reads this per accepted connection, so a reload's new certs apply to new connections
    /// while in-flight ones keep the cert they negotiated with.
    pub fn tls_config(&self) -> Option<Arc<ServerConfig>> {
        self.active.load().tls.clone()
    }

    /// The active QUIC TLS config for HTTP/3 (ADR 000016): ALPN `h3`, TLS 1.3, sharing the TCP
    /// config's SNI cert resolver. `None` whenever there is no `[[tls]]` (h3 requires TLS, so it is
    /// only offered alongside TLS termination). The fast-path server reads this once to decide
    /// whether to bind a QUIC listener and what to advertise via `Alt-Svc`.
    pub fn quic_tls_config(&self) -> Option<Arc<ServerConfig>> {
        self.active.load().quic_tls.clone()
    }
}

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

    /// A 64-byte owner-only key file + `[resumption]` entry in `dir` (shared STEK, ADR 000062).
    fn resumption_entry(dir: &Path, fill: u8) -> Resumption {
        let path = dir.join("stek.key");
        std::fs::write(&path, [fill; crate::stek::STEK_FILE_LEN]).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
        }
        Resumption {
            stek_file: path.to_str().unwrap().to_string(),
            max_age_hours: 24,
        }
    }

    /// A fresh self-signed cert written to a temp dir, plus a host-less (default) `[[tls]]` entry.
    fn default_cert_entry() -> (tempfile::TempDir, TlsCert) {
        let generated = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
        let dir = tempfile::tempdir().unwrap();
        let cert_path = dir.path().join("cert.pem");
        let key_path = dir.path().join("key.pem");
        std::fs::write(&cert_path, generated.cert.pem()).unwrap();
        std::fs::write(&key_path, generated.key_pair.serialize_pem()).unwrap();
        let entry = TlsCert {
            host: None,
            cert_path: cert_path.to_str().unwrap().to_string(),
            key_path: key_path.to_str().unwrap().to_string(),
        };
        (dir, entry)
    }

    #[test]
    fn builds_tcp_and_quic_configs_with_distinct_alpn() {
        let (dir, entry) = default_cert_entry();
        let configs = build_server_configs(&[entry], None, None, dir.path())
            .unwrap()
            .expect("a cert entry yields TCP + QUIC configs");
        // TCP advertises h2 then http/1.1 (ADR 000015); QUIC advertises only h3 (ADR 000016).
        assert_eq!(
            configs.tcp.alpn_protocols,
            vec![b"h2".to_vec(), b"http/1.1".to_vec()],
            "TCP ALPN is h2 then http/1.1"
        );
        assert_eq!(
            configs.quic.alpn_protocols,
            vec![b"h3".to_vec()],
            "QUIC ALPN is h3 only"
        );
    }

    #[test]
    fn stateless_resumption_invariants() {
        // ADR 000052's invariants, pinned per path so a rustls default change (or a refactor that
        // touches only one config) cannot silently reintroduce the stateful cache or 0-RTT.
        let (dir, entry) = default_cert_entry();
        let configs = build_server_configs(&[entry], None, None, dir.path())
            .unwrap()
            .expect("a cert entry yields TCP + QUIC configs");
        for (label, config) in [("tcp", &configs.tcp), ("quic", &configs.quic)] {
            assert!(
                config.ticketer.enabled(),
                "{label}: stateless session tickets are issued (ADR 000052)"
            );
            assert_eq!(
                config.ticketer.lifetime(),
                12 * 60 * 60,
                "{label}: 12h acceptance window (6h rotation, current + previous key)"
            );
            assert!(
                !config.session_storage.can_cache(),
                "{label}: no stateful session cache — per-session server memory stays zero"
            );
            assert_eq!(
                config.max_early_data_size, 0,
                "{label}: 0-RTT stays refused (ADR 000016 / RFC 8470), independent of the \
                 ticketer-exclusivity rustls happens to enforce today"
            );
        }
    }

    #[test]
    fn ticket_key_is_process_wide_across_paths_and_builds() {
        // One ticket producer for TCP + QUIC (a ticket obtained over either resumes on both), and
        // the SAME producer across rebuilds — a manifest reload must not invalidate outstanding
        // tickets (ADR 000052: process-lifetime, node-local key).
        let (dir, entry) = default_cert_entry();
        let a = build_server_configs(std::slice::from_ref(&entry), None, None, dir.path())
            .unwrap()
            .unwrap();
        let b = build_server_configs(&[entry], None, None, dir.path())
            .unwrap()
            .unwrap();
        assert!(
            Arc::ptr_eq(&a.tcp.ticketer, &a.quic.ticketer),
            "TCP and QUIC share one ticket producer"
        );
        assert!(
            Arc::ptr_eq(&a.tcp.ticketer, &b.tcp.ticketer),
            "a rebuild (reload) keeps the process-lifetime ticket key"
        );
    }

    #[test]
    fn no_tls_entries_yields_none() {
        assert!(
            build_server_configs(&[], None, None, std::path::Path::new("."))
                .unwrap()
                .is_none(),
            "no [[tls]] means no TLS/QUIC configs (plain HTTP/1.1, no h3)"
        );
    }

    #[test]
    fn mismatched_cert_and_key_is_rejected() {
        // a cert paired with a DIFFERENT private key must fail the build (fail-closed), not
        // go live and fail every TLS handshake at runtime. Cross two self-signed pairs.
        let a = rcgen::generate_simple_self_signed(vec!["a.example".to_string()]).unwrap();
        let b = rcgen::generate_simple_self_signed(vec!["b.example".to_string()]).unwrap();
        let dir = tempfile::tempdir().unwrap();
        let cert_path = dir.path().join("cert.pem");
        let key_path = dir.path().join("key.pem");
        std::fs::write(&cert_path, a.cert.pem()).unwrap(); // cert A
        std::fs::write(&key_path, b.key_pair.serialize_pem()).unwrap(); // key B (mismatch)
        let entry = TlsCert {
            host: None,
            cert_path: cert_path.to_str().unwrap().to_string(),
            key_path: key_path.to_str().unwrap().to_string(),
        };
        let err = match build_server_configs(&[entry], None, None, dir.path()) {
            Err(e) => e,
            Ok(_) => panic!("a mismatched cert/key pair must be rejected at build"),
        };
        assert!(matches!(err, ControlError::TlsCert { .. }));
    }

    // ----- ADR 000062: [resumption] shared STEK -----

    #[test]
    fn shared_stek_keeps_the_resumption_invariants() {
        // ADR 000062 (c): opting into the shared ticketer changes the KEY, not the posture —
        // stateless tickets on, no session cache, 0-RTT refused, on both paths. The lifetime
        // hint becomes max_age_hours (the acceptance window the key file discipline enforces).
        let (dir, entry) = default_cert_entry();
        let resumption = resumption_entry(dir.path(), 7);
        let configs = build_server_configs(&[entry], Some(&resumption), None, dir.path())
            .unwrap()
            .unwrap();
        for (label, config) in [("tcp", &configs.tcp), ("quic", &configs.quic)] {
            assert!(config.ticketer.enabled(), "{label}: tickets are issued");
            assert_eq!(
                config.ticketer.lifetime(),
                24 * 60 * 60,
                "{label}: the hint is max_age_hours, not the per-node 12h"
            );
            assert!(!config.session_storage.can_cache(), "{label}: no cache");
            assert_eq!(
                config.max_early_data_size, 0,
                "{label}: 0-RTT stays refused"
            );
        }
        assert!(
            Arc::ptr_eq(&configs.tcp.ticketer, &configs.quic.ticketer),
            "TCP and QUIC share the one shared-STEK producer (same cert set → same keys)"
        );
    }

    #[test]
    fn shared_stek_rebuilds_derive_interchangeable_keys() {
        // The reload story (ADR 000062): unlike the per-node OnceLock, each build constructs a
        // FRESH ticketer — outstanding tickets survive anyway because the keys are a pure
        // function of (file, cert set). Pin that: a ticket sealed by build A opens in build B.
        let (dir, entry) = default_cert_entry();
        let resumption = resumption_entry(dir.path(), 7);
        let a = build_server_configs(
            std::slice::from_ref(&entry),
            Some(&resumption),
            None,
            dir.path(),
        )
        .unwrap()
        .unwrap();
        let b = build_server_configs(&[entry], Some(&resumption), None, dir.path())
            .unwrap()
            .unwrap();
        assert!(
            !Arc::ptr_eq(&a.tcp.ticketer, &b.tcp.ticketer),
            "sanity: rebuilds construct distinct ticketer objects"
        );
        let ticket = a.tcp.ticketer.encrypt(b"session-state").unwrap();
        assert_eq!(
            b.tcp.ticketer.decrypt(&ticket).as_deref(),
            Some(&b"session-state"[..]),
            "a reload (or another replica) re-derives the same keys"
        );
    }

    #[test]
    fn shared_stek_binds_tickets_to_the_cert_set() {
        // ADR 000062 (a) at the build level: same key file, different cert → the ticket does not
        // cross (the USENIX'25 cross-listener class, killed in the key schedule).
        let (dir_a, entry_a) = default_cert_entry();
        let (dir_b, entry_b) = default_cert_entry(); // a different self-signed key pair
        let resumption = resumption_entry(dir_a.path(), 7);
        let a = build_server_configs(&[entry_a], Some(&resumption), None, dir_a.path())
            .unwrap()
            .unwrap();
        let b = build_server_configs(&[entry_b], Some(&resumption), None, dir_b.path())
            .unwrap()
            .unwrap();
        let ticket = a.tcp.ticketer.encrypt(b"session-state").unwrap();
        assert_eq!(
            b.tcp.ticketer.decrypt(&ticket),
            None,
            "a deployment with a different cert set must not accept the ticket"
        );
    }

    #[test]
    fn resumption_without_tls_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let resumption = resumption_entry(dir.path(), 7);
        let err = match build_server_configs(&[], Some(&resumption), None, dir.path()) {
            Err(e) => e,
            Ok(_) => panic!("[resumption] with no [[tls]] must fail the build"),
        };
        assert!(matches!(err, ControlError::Stek { .. }));
    }

    #[test]
    fn shared_stek_bad_file_fails_the_build_closed() {
        // Wrong length and (on unix) loose permissions abort the build like a bad cert.
        let (dir, entry) = default_cert_entry();
        let mut resumption = resumption_entry(dir.path(), 7);
        std::fs::write(&resumption.stek_file, [7u8; 48]).unwrap();
        let err = match build_server_configs(
            std::slice::from_ref(&entry),
            Some(&resumption),
            None,
            dir.path(),
        ) {
            Err(e) => e,
            Ok(_) => panic!("a 48-byte file must be rejected"),
        };
        assert!(matches!(err, ControlError::Stek { .. }));

        // Out-of-range max_age_hours is rejected before the file is touched.
        resumption = resumption_entry(dir.path(), 7);
        resumption.max_age_hours = 169;
        let err = match build_server_configs(&[entry], Some(&resumption), None, dir.path()) {
            Err(e) => e,
            Ok(_) => panic!("max_age_hours over the RFC 8446 cap must be rejected"),
        };
        assert!(matches!(err, ControlError::Stek { .. }));
    }

    // ----- ADR 000078: mTLS — [listen.client_auth] / [upstream.tls] client identity -----

    /// A `[listen.client_auth]` whose `ca_path` file holds `ca_pem`, written into `dir`.
    fn client_auth_entry(dir: &Path, ca_pem: &[u8]) -> ClientAuth {
        let path = dir.join("client-ca.pem");
        std::fs::write(&path, ca_pem).unwrap();
        ClientAuth {
            ca_path: path.to_str().unwrap().to_string(),
        }
    }

    /// A PEM trust anchor a client_auth test can point `ca_path` at.
    fn some_ca_pem() -> Vec<u8> {
        rcgen::generate_simple_self_signed(vec!["client-ca".to_string()])
            .unwrap()
            .cert
            .pem()
            .into_bytes()
    }

    /// A fresh self-signed client identity (cert + owner-only key PEM) for `[upstream.tls]`.
    fn upstream_client_identity(dir: &Path) -> (String, String) {
        let generated = rcgen::generate_simple_self_signed(vec!["plecto".to_string()]).unwrap();
        let cert_path = dir.join("client-cert.pem");
        let key_path = dir.join("client-key.pem");
        std::fs::write(&cert_path, generated.cert.pem()).unwrap();
        std::fs::write(&key_path, generated.key_pair.serialize_pem()).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&key_path, std::fs::Permissions::from_mode(0o600)).unwrap();
        }
        (
            cert_path.to_str().unwrap().to_string(),
            key_path.to_str().unwrap().to_string(),
        )
    }

    fn upstream_tls_with_identity(
        cert: Option<String>,
        key: Option<String>,
    ) -> crate::manifest::UpstreamTls {
        crate::manifest::UpstreamTls {
            client_cert_path: cert,
            client_key_path: key,
            ..Default::default()
        }
    }

    #[test]
    fn upstream_client_cert_without_key_fails_closed() {
        let dir = tempfile::tempdir().unwrap();
        let (cert, _key) = upstream_client_identity(dir.path());
        let tls = upstream_tls_with_identity(Some(cert), None);
        let err = match build_upstream_client_config("u", &tls, dir.path()) {
            Err(e) => e,
            Ok(_) => panic!("client_cert_path without client_key_path must fail the build"),
        };
        assert!(matches!(err, ControlError::UpstreamClientCert { .. }));
    }

    #[test]
    fn upstream_client_key_without_cert_fails_closed() {
        let dir = tempfile::tempdir().unwrap();
        let (_cert, key) = upstream_client_identity(dir.path());
        let tls = upstream_tls_with_identity(None, Some(key));
        let err = match build_upstream_client_config("u", &tls, dir.path()) {
            Err(e) => e,
            Ok(_) => panic!("client_key_path without client_cert_path must fail the build"),
        };
        assert!(matches!(err, ControlError::UpstreamClientCert { .. }));
    }

    #[test]
    fn upstream_client_identity_is_loaded_into_the_config() {
        let dir = tempfile::tempdir().unwrap();
        let (cert, key) = upstream_client_identity(dir.path());
        let tls = upstream_tls_with_identity(Some(cert), Some(key));
        let config = build_upstream_client_config("u", &tls, dir.path()).unwrap();
        assert!(
            config.client_auth_cert_resolver.has_certs(),
            "the declared client identity must be presented when the upstream requests one"
        );
    }

    #[cfg(unix)]
    #[test]
    fn upstream_client_key_readable_by_group_fails_closed() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let (cert, key) = upstream_client_identity(dir.path());
        std::fs::set_permissions(&key, std::fs::Permissions::from_mode(0o640)).unwrap();
        let tls = upstream_tls_with_identity(Some(cert), Some(key));
        let err = match build_upstream_client_config("u", &tls, dir.path()) {
            Err(e) => e,
            Ok(_) => panic!("a group-readable client key must fail the build (ADR 000062 (d))"),
        };
        assert!(matches!(err, ControlError::UpstreamClientCert { .. }));
    }

    #[test]
    fn client_auth_ticketer_is_isolated_and_rotates_with_the_ca() {
        // mTLS builds must not share the process-wide anonymous ticketer: enabling client_auth
        // after anonymous tickets were issued would otherwise let those tickets resume without a
        // CertificateRequest (RFC 8446 PSK). Within one CA generation tickets survive unrelated
        // reloads (no full-handshake stampede); rotating the CA bytes re-keys, so no ticket
        // outlives the trust roots that authenticated its peer.
        let (dir, entry) = default_cert_entry();
        let without = build_server_configs(std::slice::from_ref(&entry), None, None, dir.path())
            .unwrap()
            .unwrap();
        let ca = some_ca_pem();
        let auth = client_auth_entry(dir.path(), &ca);
        let with = build_server_configs(
            std::slice::from_ref(&entry),
            None,
            Some((&auth, ca.as_slice())),
            dir.path(),
        )
        .unwrap()
        .unwrap();
        assert!(
            !Arc::ptr_eq(&without.tcp.ticketer, &with.tcp.ticketer),
            "client_auth must not reuse the anonymous process-wide ticketer"
        );
        let again = build_server_configs(
            std::slice::from_ref(&entry),
            None,
            Some((&auth, ca.as_slice())),
            dir.path(),
        )
        .unwrap()
        .unwrap();
        assert!(
            Arc::ptr_eq(&with.tcp.ticketer, &again.tcp.ticketer),
            "an unchanged CA keeps tickets valid across rebuilds (reload continuity)"
        );
        let rotated_ca = some_ca_pem();
        let rotated = build_server_configs(
            &[entry],
            None,
            Some((&auth, rotated_ca.as_slice())),
            dir.path(),
        )
        .unwrap()
        .unwrap();
        assert!(
            !Arc::ptr_eq(&with.tcp.ticketer, &rotated.tcp.ticketer),
            "a CA rotation re-keys the ticketer (tickets cannot outlive the verifier's roots)"
        );
        assert!(
            Arc::ptr_eq(&with.tcp.ticketer, &with.quic.ticketer),
            "TCP and QUIC still share one ticketer within a single build"
        );
    }

    #[test]
    fn client_auth_with_shared_stek_fails_closed() {
        // ADR 000062 (b) / 000078: shared STEK × client auth amplifies resume-without-reverify
        // across replicas — the combination is refused.
        let (dir, entry) = default_cert_entry();
        let resumption = resumption_entry(dir.path(), 7);
        let ca = some_ca_pem();
        let auth = client_auth_entry(dir.path(), &ca);
        let err = match build_server_configs(
            &[entry],
            Some(&resumption),
            Some((&auth, ca.as_slice())),
            dir.path(),
        ) {
            Err(e) => e,
            Ok(_) => {
                panic!("[listen.client_auth] with [resumption] shared STEK must fail the build")
            }
        };
        assert!(matches!(err, ControlError::Stek { .. }));
    }

    /// Pump TLS records between a client and server until neither side wants I/O.
    fn pump_tls(client: &mut rustls::ClientConnection, server: &mut rustls::ServerConnection) {
        loop {
            let mut progressed = false;
            while client.wants_write() {
                let mut buf = Vec::new();
                let n = client.write_tls(&mut buf).unwrap();
                if n == 0 {
                    break;
                }
                server.read_tls(&mut &buf[..]).unwrap();
                server.process_new_packets().unwrap();
                progressed = true;
            }
            while server.wants_write() {
                let mut buf = Vec::new();
                let n = server.write_tls(&mut buf).unwrap();
                if n == 0 {
                    break;
                }
                client.read_tls(&mut &buf[..]).unwrap();
                client.process_new_packets().unwrap();
                progressed = true;
            }
            if !progressed {
                break;
            }
        }
    }

    /// Grill 確定 4 load-bearing claim: with OUR `ServerConfig` (required client auth + per-node
    /// ticketer), a resumed handshake restores `peer_certificates` from the ticket — identity is
    /// preserved even though CertificateRequest is not re-sent (RFC 8446 / 9846 under PSK).
    #[test]
    fn client_auth_peer_certificates_survive_per_node_resumption() {
        let (dir, entry) = default_cert_entry();
        let client_id =
            rcgen::generate_simple_self_signed(vec!["plecto-client".to_string()]).unwrap();
        let ca = client_id.cert.pem().into_bytes();
        let auth = client_auth_entry(dir.path(), &ca);
        let configs = build_server_configs(
            std::slice::from_ref(&entry),
            None,
            Some((&auth, ca.as_slice())),
            dir.path(),
        )
        .unwrap()
        .expect("client-auth listener yields TCP + QUIC configs");

        let server_pem = std::fs::read(&entry.cert_path).unwrap();
        let server_certs: Vec<CertificateDer<'static>> =
            CertificateDer::pem_slice_iter(&server_pem)
                .collect::<Result<Vec<_>, _>>()
                .unwrap();
        let mut roots = rustls::RootCertStore::empty();
        roots.add(server_certs[0].clone()).unwrap();

        let client_config = Arc::new(
            rustls::ClientConfig::builder_with_provider(Arc::new(provider::default_provider()))
                .with_safe_default_protocol_versions()
                .unwrap()
                .with_root_certificates(roots)
                .with_client_auth_cert(
                    vec![CertificateDer::from(client_id.cert.der().to_vec())],
                    PrivateKeyDer::try_from(client_id.key_pair.serialize_der()).unwrap(),
                )
                .unwrap(),
        );

        let server_name = rustls::pki_types::ServerName::try_from("localhost").unwrap();
        let mut client =
            rustls::ClientConnection::new(client_config.clone(), server_name.clone()).unwrap();
        let mut server = rustls::ServerConnection::new(configs.tcp.clone()).unwrap();
        for _ in 0..64 {
            pump_tls(&mut client, &mut server);
            if !client.is_handshaking() && !server.is_handshaking() {
                break;
            }
        }
        assert!(
            !client.is_handshaking() && !server.is_handshaking(),
            "full handshake must complete"
        );
        // Drain NewSessionTicket into the client's session cache.
        for _ in 0..16 {
            pump_tls(&mut client, &mut server);
        }
        let full_chain = server
            .peer_certificates()
            .expect("full handshake must expose the verified client chain")
            .to_vec();
        assert!(
            !full_chain.is_empty(),
            "verified client chain must be non-empty"
        );
        assert_eq!(
            client.handshake_kind(),
            Some(rustls::HandshakeKind::Full),
            "first connection is a full handshake"
        );

        let mut client2 = rustls::ClientConnection::new(client_config, server_name).unwrap();
        let mut server2 = rustls::ServerConnection::new(configs.tcp).unwrap();
        for _ in 0..64 {
            pump_tls(&mut client2, &mut server2);
            if !client2.is_handshaking() && !server2.is_handshaking() {
                break;
            }
        }
        assert_eq!(
            client2.handshake_kind(),
            Some(rustls::HandshakeKind::Resumed),
            "second connection must resume with the per-node ticket"
        );
        let resumed_chain = server2
            .peer_certificates()
            .expect("resumed handshake must restore peer_certificates from the ticket")
            .to_vec();
        assert_eq!(
            resumed_chain, full_chain,
            "ticket-restored identity must match the originally verified chain"
        );
    }

    #[test]
    fn client_auth_without_tls_entries_fails_closed() {
        let dir = tempfile::tempdir().unwrap();
        let ca = some_ca_pem();
        let auth = client_auth_entry(dir.path(), &ca);
        let err = match build_server_configs(&[], None, Some((&auth, ca.as_slice())), dir.path()) {
            Err(e) => e,
            Ok(_) => panic!("[listen.client_auth] with no [[tls]] must fail the build"),
        };
        assert!(matches!(err, ControlError::ClientAuthCa { .. }));
    }

    #[test]
    fn client_auth_ca_with_no_usable_root_fails_closed() {
        let (dir, entry) = default_cert_entry();
        let auth = client_auth_entry(dir.path(), b"not a pem at all");
        let err = match build_server_configs(
            &[entry],
            None,
            Some((&auth, b"not a pem at all".as_slice())),
            dir.path(),
        ) {
            Err(e) => e,
            Ok(_) => panic!("an unusable client-auth CA bundle must fail the build"),
        };
        assert!(matches!(err, ControlError::ClientAuthCa { .. }));
    }
}