alktls 0.1.0

Shared TLS setup types: server and client rustls configs, cert resolvers, verifiers, and ACME state-machine wiring, transport-agnostic and shareable across transports.
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
//! Server-side TLS configuration: [`TlsServerConfig`],
//! [`build_rustls_server_config`], [`RawKeyCertResolver`],
//! [`VerifyPresentedCertVerifier`], [`AcceptAnyCertVerifier`],
//! [`SelfSignedCert`] / [`generate_self_signed_cert`], and the ACME path
//! (feature `acme`).

use std::sync::Arc;

#[cfg(feature = "acme")]
use tracing::{debug, error, warn};

#[cfg(feature = "acme")]
use crate::identity::AcmeDirectory;
use crate::identity::{Ed25519SecretKey, TlsIdentity};
use crate::signing::Ed25519SigningKey;

use crate::fingerprint::extract_ed25519_raw_key_from_spki;
use crate::TlsError;

/// Server-side TLS configuration, transport-agnostic. Built once from a
/// [`TlsIdentity`] + ALPN list, shared across transports via
/// [`Arc`] (not `Clone` — it holds the ACME task's
/// `JoinHandle`).
///
/// Not `Clone` for v1 (review 001 §N-3, decided): even under
/// `default = []`, where the struct carries no ACME `JoinHandle`, the
/// non-Clone posture is kept so the API is identical across feature
/// configurations — conditional `Clone` would be an API difference
/// between feature sets; share via [`Arc`] and revisit
/// only if a concrete consumer demands it.
#[allow(dead_code)]
pub struct TlsServerConfig {
    pub(crate) rustls_config: rustls::ServerConfig,
    #[cfg(feature = "acme")]
    pub(crate) acme_handle: Option<tokio::task::JoinHandle<()>>,
}

impl TlsServerConfig {
    /// Build a server config from a [`TlsIdentity`] and ALPN list.
    /// ACME identities spawn a background cert-renewal task.
    ///
    /// ALPN asymmetry: ACME identities always serve `acme-tls/1`, so it
    /// is appended to the caller's list here (idempotently — a caller
    /// who already includes it gets a single entry); non-ACME identities
    /// use the ALPN list verbatim.
    pub async fn new(tls_identity: &TlsIdentity, alpns: &[Vec<u8>]) -> Result<Self, TlsError> {
        match tls_identity {
            TlsIdentity::Acme {
                domains,
                cache_dir,
                directory,
                contact,
            } => {
                #[cfg(feature = "acme")]
                {
                    Self::new_acme(domains, cache_dir, directory, contact, alpns).await
                }
                #[cfg(not(feature = "acme"))]
                {
                    let _ = (domains, cache_dir, directory, contact, alpns);
                    Err(TlsError::AcmeConfig(
                        "ACME feature not enabled but TlsIdentity::Acme configured".to_string(),
                    ))
                }
            }
            _ => {
                let server_config = build_rustls_server_config(tls_identity, alpns)?;
                Ok(Self {
                    rustls_config: server_config,
                    #[cfg(feature = "acme")]
                    acme_handle: None,
                })
            }
        }
    }

    #[cfg(feature = "acme")]
    async fn new_acme(
        domains: &[String],
        cache_dir: &std::path::Path,
        directory: &AcmeDirectory,
        contact: &[String],
        alpns: &[Vec<u8>],
    ) -> Result<Self, TlsError> {
        use rustls_acme::caches::DirCache;
        use rustls_acme::{AcmeConfig, EventError, EventOk};

        if domains.is_empty() {
            return Err(TlsError::AcmeConfig(
                "TlsIdentity::Acme requires a non-empty domain list".to_string(),
            ));
        }

        let acme_config = AcmeConfig::new(domains.to_vec())
            .cache(DirCache::new(cache_dir.to_path_buf()))
            .directory(directory.url())
            .contact(contact.iter().map(|c| c.as_str()));

        let state = acme_config.state();
        let resolver = state.resolver();

        let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
        let mut config = rustls::ServerConfig::builder_with_provider(provider.clone())
            .with_safe_default_protocol_versions()?
            .with_client_cert_verifier(Arc::new(VerifyPresentedCertVerifier::new(&provider)))
            .with_cert_resolver(resolver);
        config.max_early_data_size = u32::MAX;

        let mut alpn = alpns.to_vec();
        if !alpn.contains(&b"acme-tls/1".to_vec()) {
            alpn.push(b"acme-tls/1".to_vec());
        }
        config.alpn_protocols = alpn;

        let domains_owned: Vec<String> = domains.to_vec();
        let handle = tokio::spawn(async move {
            use futures::StreamExt;
            let mut state = state;
            while let Some(event) = state.next().await {
                match event {
                    Ok(EventOk::DeployedCachedCert) => {
                        debug!(domains = ?domains_owned, "ACME: deployed cached certificate");
                    }
                    Ok(EventOk::DeployedNewCert) => {
                        debug!(domains = ?domains_owned, "ACME: deployed new certificate");
                    }
                    Ok(EventOk::CertCacheStore) => {
                        debug!(domains = ?domains_owned, "ACME: certificate stored to cache");
                    }
                    Ok(EventOk::AccountCacheStore) => {
                        debug!(domains = ?domains_owned, "ACME: account stored to cache");
                    }
                    Err(EventError::CertCacheLoad(e)) => {
                        error!(domains = ?domains_owned, error = ?e, "ACME: certificate cache load failed");
                    }
                    Err(EventError::AccountCacheLoad(e)) => {
                        error!(domains = ?domains_owned, error = ?e, "ACME: account cache load failed");
                    }
                    Err(EventError::CertCacheStore(e)) => {
                        warn!(domains = ?domains_owned, error = ?e, "ACME: certificate cache store failed");
                    }
                    Err(EventError::AccountCacheStore(e)) => {
                        warn!(domains = ?domains_owned, error = ?e, "ACME: account cache store failed");
                    }
                    Err(EventError::CachedCertParse(e)) => {
                        error!(domains = ?domains_owned, error = ?e, "ACME: cached certificate parse failed");
                    }
                    Err(EventError::Order(e)) => {
                        warn!(domains = ?domains_owned, error = ?e, "ACME: certificate order failed, will retry");
                    }
                    Err(EventError::NewCertParse(e)) => {
                        error!(domains = ?domains_owned, error = ?e, "ACME: new certificate parse failed");
                    }
                }
            }
        });

        Ok(Self {
            rustls_config: config,
            acme_handle: Some(handle),
        })
    }

    /// Wrap the inner rustls config for the noq QUIC transport.
    ///
    /// Takes `&self` (ADR-004): the inner rustls config is `Clone`
    /// (Arc-shared resolvers), so one [`TlsServerConfig`] can feed a noq
    /// endpoint and a TCP+TLS acceptor without contortions.
    #[cfg(feature = "noq")]
    pub fn for_noq(&self) -> Result<noq::ServerConfig, TlsError> {
        use noq::crypto::rustls::QuicServerConfig;
        let quic_server_config = QuicServerConfig::try_from(self.rustls_config.clone())?;
        Ok(noq::ServerConfig::with_crypto(Arc::new(quic_server_config)))
    }

    /// Wrap the inner rustls config for the TCP+TLS transport. Infallible
    /// — `TlsAcceptor::from(Arc<ServerConfig>)` cannot fail.
    #[cfg(feature = "tcp")]
    pub fn for_tcp_tls(&self) -> tokio_rustls::TlsAcceptor {
        tokio_rustls::TlsAcceptor::from(Arc::new(self.rustls_config.clone()))
    }

    /// Borrow the inner config for transport wrappers the crate does not
    /// cover.
    pub fn rustls_config(&self) -> &rustls::ServerConfig {
        &self.rustls_config
    }
}

/// Build the inner `rustls::ServerConfig` for the non-ACME identity
/// variants: `X509`, `RawKey`, `SelfSigned`. The `Acme` arm is defensive —
/// ACME is dispatched by [`TlsServerConfig::new`] to `new_acme` and
/// reaching the builder with it is a config error.
pub fn build_rustls_server_config(
    tls_identity: &TlsIdentity,
    alpns: &[Vec<u8>],
) -> Result<rustls::ServerConfig, TlsError> {
    let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
    let client_verifier: Arc<dyn rustls::server::danger::ClientCertVerifier> =
        Arc::new(VerifyPresentedCertVerifier::new(&provider));
    match tls_identity {
        TlsIdentity::X509 { cert, key } => {
            let cert_chain = crate::pem::load_cert_chain(cert)?;
            let private_key = crate::pem::load_private_key(key)?;
            let mut config = rustls::ServerConfig::builder_with_provider(provider)
                .with_safe_default_protocol_versions()?
                .with_client_cert_verifier(client_verifier)
                .with_single_cert(cert_chain, private_key)?;
            config.alpn_protocols = alpns.to_vec();
            config.max_early_data_size = u32::MAX;
            Ok(config)
        }
        TlsIdentity::RawKey(secret_key) => {
            let resolver = Arc::new(RawKeyCertResolver::new(secret_key));
            let mut config = rustls::ServerConfig::builder_with_provider(provider)
                .with_safe_default_protocol_versions()?
                .with_client_cert_verifier(client_verifier)
                .with_cert_resolver(resolver);
            config.alpn_protocols = alpns.to_vec();
            config.max_early_data_size = u32::MAX;
            Ok(config)
        }
        TlsIdentity::SelfSigned => {
            let cert = generate_self_signed_cert()?;
            let mut config = rustls::ServerConfig::builder_with_provider(provider)
                .with_safe_default_protocol_versions()?
                .with_client_cert_verifier(client_verifier)
                .with_single_cert(cert.cert_chain, cert.private_key)?;
            config.alpn_protocols = alpns.to_vec();
            config.max_early_data_size = u32::MAX;
            Ok(config)
        }
        TlsIdentity::Acme { .. } => Err(TlsError::AcmeConfig(
            "TlsIdentity::Acme is handled by TlsServerConfig::new_acme, not \
             build_rustls_server_config"
                .to_string(),
        )),
    }
}

/// The cert material behind the [`TlsIdentity::SelfSigned`] server path:
/// a single rcgen-generated DER cert plus its PKCS#8 private key.
///
/// Validity facts (review 001 §C-1, verified against rcgen 0.13's
/// `CertificateParams::default()`): the generated cert is valid
/// 1975→4096 — i.e. **never expires in practice** — and carries **no
/// SANs**, so CA verification of it fails as expected for a dev cert.
/// Pinning its `SHA256:` fingerprint therefore outlives any plausible
/// deployment by design; if a tighter validity is ever wanted,
/// `CertificateParams::not_before` / `not_after` are additive params.
pub struct SelfSignedCert {
    /// The self-signed leaf certificate (DER). No SANs, validity
    /// 1975→4096 (see the type's doc).
    pub cert_chain: Vec<rustls::pki_types::CertificateDer<'static>>,
    /// The matching private key (PKCS#8 DER).
    pub private_key: rustls::pki_types::PrivateKeyDer<'static>,
}

/// Generate a self-signed dev certificate (rcgen), in-memory.
///
/// Dev-posture facts (review 001 §C-1): rcgen's `default()` params make
/// the cert **valid 1975→4096** (never expires in practice) and leave it
/// **without SANs** — CA verification of it always fails, so this cert
/// pairs only with fingerprint-pinning (`SHA256:` of the DER) or with
/// clients that don't verify against a CA. It can never *fail* the way
/// an ACME or ops-managed cert can. If a tighter validity is ever
/// wanted, `not_before` / `not_after` are additive
/// `CertificateParams` fields.
pub fn generate_self_signed_cert() -> Result<SelfSignedCert, TlsError> {
    use rcgen::{CertificateParams, KeyPair};
    let key_pair = KeyPair::generate()?;
    let params = CertificateParams::default();
    let cert = params.self_signed(&key_pair)?;
    let cert_der = cert.der().clone();
    let key_der = rustls::pki_types::PrivateKeyDer::Pkcs8(
        rustls::pki_types::PrivatePkcs8KeyDer::from(key_pair.serialize_der()),
    );
    Ok(SelfSignedCert {
        cert_chain: vec![cert_der],
        private_key: key_der,
    })
}

/// Server-side client-cert verifier that verifies the presented
/// identity's proof-of-possession: **request, don't require, verify
/// possession**. The default client-cert verifier on every
/// [`TlsServerConfig`] path (ADR-008, resolving OQ-TLS-09).
///
/// Like [`AcceptAnyCertVerifier`], it asks for a client cert (X.509 or
/// RFC 7250 raw key) so the endpoint can extract the fingerprint via
/// `peer_identity()`, does not require one, and does not verify the
/// presented cert against a CA — a self-signed X.509 chain or a bare
/// RFC 7250 SPKI is acceptable presentation. Unlike
/// `AcceptAnyCertVerifier`, the client's **CertificateVerify signature
/// is verified** against the presented cert's public key:
///
/// - An Ed25519 SPKI presentation routes to
///   `verify_tls13_signature_with_raw_key` (and its TLS 1.2
///   equivalent routing) — the same routing the client-side
///   `FingerprintPinVerifier` uses.
/// - An X.509 presentation routes to the standard
///   `verify_tls12_signature` / `verify_tls13_signature`.
///
/// A presented cert is therefore only usable by the party holding the
/// matching private key: presenting a victim's public cert/SPKI bytes
/// under an attacker's key fails the CertificateVerify check (the
/// impersonation posture pinned by `tests/impersonation_posture.rs`
/// under the permissive escape hatch). The extracted fingerprint is
/// authenticated as "this party holds the private key for the
/// presented public identity" — a real proof-of-possession, though
/// still *not* a name/CA check (self-signed chains remain valid
/// presentation; who a fingerprint maps to stays the auth layer's
/// concern, ADR-005).
///
/// Clients that present no cert are unaffected — there is nothing to
/// verify, and `client_auth_mandatory() == false`.
///
/// # Client-cert-type negotiation (ADR-007, review 001 §N-4)
///
/// `requires_raw_public_keys()` stays on the rustls trait default
/// (`false`) on **both** this verifier and [`AcceptAnyCertVerifier`] —
/// do not "fix" it to `true`. `false` is the request-but-don't-require
/// shape: the verifier *requests* a client cert and accepts **both cert
/// types** (X.509 or RFC 7250 raw key); setting `true` would reject
/// every X.509 client. Post-ADR-007, the crate's own
/// [`RawKeyClientCertResolver`](crate::RawKeyClientCertResolver)
/// presents the SPKI under the **X.509 offer** unconditionally
/// (`only_raw_public_keys() == false` — the extension is an offer
/// format, not an identity statement), so a raw-key client against this
/// crate's servers never sends a raw-only offer. The
/// `IncorrectCertificateTypeExtension` rejection of a raw-only client
/// offer (rustls `server/hs.rs::process_cert_type_extension`'s
/// `(false, true, false)` arm) can therefore only arise from a
/// *foreign* rustls resolver with `only_raw_public_keys() == true` — an
/// interop boundary of the request-not-require shape: it fails closed,
/// never a downgrade. The full mechanism lives in
/// [ADR-007](../docs/architecture/decisions/007-cert-type-negotiation.md)
/// — do not re-derive it here. A raw-key *server* presentation
/// (`RawKeyCertResolver`, `only_raw_public_keys() == true` on the
/// server-cert side) is the other knob (`server_certificate_types`) and
/// is unaffected by this verifier.
///
/// `supported_verify_schemes()` returns the same nine-scheme list as
/// `AcceptAnyCertVerifier` (the load-bearing list, pinned by an
/// exact-list test). `requires_raw_public_keys()` stays `false` — the
/// verifier accepts both cert types (ADR-007), pinned by
/// `server_verifiers_keep_requires_raw_public_keys_default_false`.
///
/// Use [`AcceptAnyCertVerifier`] only if a deployment deliberately
/// needs the no-pop posture (e.g. an auth layer that owns
/// challenge-response and wants handshake-speed over strictness); the
/// permissive posture is still pinned by `tests/impersonation_posture.rs`
/// when this verifier is explicitly installed.
pub struct VerifyPresentedCertVerifier {
    supported: rustls::crypto::WebPkiSupportedAlgorithms,
}

impl VerifyPresentedCertVerifier {
    pub fn new(provider: &Arc<rustls::crypto::CryptoProvider>) -> Self {
        Self {
            supported: provider.signature_verification_algorithms,
        }
    }
}

impl std::fmt::Debug for VerifyPresentedCertVerifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VerifyPresentedCertVerifier").finish()
    }
}

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

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

    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,
    ) -> Result<rustls::server::danger::ClientCertVerified, rustls::Error> {
        Ok(rustls::server::danger::ClientCertVerified::assertion())
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &rustls::pki_types::CertificateDer<'_>,
        dss: &rustls::DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        if extract_ed25519_raw_key_from_spki(cert.as_ref()).is_some() {
            let spki = rustls::pki_types::SubjectPublicKeyInfoDer::from(cert.as_ref().to_vec());
            rustls::crypto::verify_tls13_signature_with_raw_key(
                message,
                &spki,
                dss,
                &self.supported,
            )
        } else {
            rustls::crypto::verify_tls13_signature(message, cert, dss, &self.supported)
        }
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &rustls::pki_types::CertificateDer<'_>,
        dss: &rustls::DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        if extract_ed25519_raw_key_from_spki(cert.as_ref()).is_some() {
            let spki = rustls::pki_types::SubjectPublicKeyInfoDer::from(cert.as_ref().to_vec());
            rustls::crypto::verify_tls13_signature_with_raw_key(
                message,
                &spki,
                dss,
                &self.supported,
            )
        } else {
            rustls::crypto::verify_tls12_signature(message, cert, dss, &self.supported)
        }
    }

    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
        nine_supported_verify_schemes()
    }
}

fn nine_supported_verify_schemes() -> Vec<rustls::SignatureScheme> {
    vec![
        rustls::SignatureScheme::ED25519,
        rustls::SignatureScheme::ECDSA_NISTP256_SHA256,
        rustls::SignatureScheme::ECDSA_NISTP384_SHA384,
        rustls::SignatureScheme::RSA_PSS_SHA256,
        rustls::SignatureScheme::RSA_PSS_SHA384,
        rustls::SignatureScheme::RSA_PSS_SHA512,
        rustls::SignatureScheme::RSA_PKCS1_SHA256,
        rustls::SignatureScheme::RSA_PKCS1_SHA384,
        rustls::SignatureScheme::RSA_PKCS1_SHA512,
    ]
}

/// Server-side "request-but-don't-require" client cert verifier
/// (alknet ADR-034).
///
/// Asks for a client TLS cert (X.509 or RFC 7250 raw key) so the endpoint
/// can extract the fingerprint via `peer_identity()`, but does not require
/// one and does not verify the presented cert against a CA. The TLS crate
/// hands over the fingerprint string; matching it against peer records
/// (`IdentityProvider::resolve_from_fingerprint`) is the auth layer's
/// concern, outside this crate (alktls ADR-005).
///
/// # The presented signature is NOT verified (no proof-of-possession)
///
/// The client's CertificateVerify signature is never checked against the
/// presented cert's public key: `verify_client_cert` accepts any cert and
/// the `verify_tls12_signature`/`verify_tls13_signature` methods assert
/// validity unconditionally. Consequently **the fingerprint this verifier
/// lets the server extract is attacker-suppliable**: any party that
/// observes a peer's public cert bytes (X.509) or SPKI (RFC 7250) can
/// complete a handshake presenting those bytes under its own key, and
/// `peer_certificates()` yields the victim's cert — every downstream
/// fingerprint decision (scopes, tokens, resumption) is then made against
/// a spoofed identity. The auth layer's peer table cannot detect this: the
/// fingerprint it is handed *is* the victim's. Until the caller enforces
/// possession (challenge-response over the established channel is the
/// pattern), treat the extracted fingerprint as an unauthenticated claim,
/// not proof of identity.
///
/// **Not the default** (ADR-008): [`VerifyPresentedCertVerifier`] is the
/// default client-cert verifier on every [`TlsServerConfig`] path — it
/// has the same request-not-require shape plus the CertificateVerify
/// possession check. Install this type explicitly only when a
/// deployment deliberately wants the no-pop posture. The spoofable
/// behavior is pinned by `tests/impersonation_posture.rs` (both cert
/// types, against a server configured with this verifier) — a change
/// must update that test together with this doc.
///
/// **Server-side only.** This must not be reused as a client-side
/// `ServerCertVerifier` — client-side verification is alknet ADR-034's
/// selection matrix (see the client module): CA verification for unknown
/// X.509 remotes, fingerprint pinning for known peers, fail closed for
/// unknown raw keys. Unlike the client-side pin verifier, this type has
/// **no proof-of-possession check** (see above).
///
/// For the client-cert-type negotiation boundary (`requires_raw_public_keys()`
/// stays `false`, raw-only offers rejected), see
/// [`VerifyPresentedCertVerifier`]'s "Client-cert-type negotiation" section —
/// the same shape and rationale apply verbatim to this type.
pub struct AcceptAnyCertVerifier;

impl std::fmt::Debug for AcceptAnyCertVerifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AcceptAnyCertVerifier").finish()
    }
}

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

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

    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,
    ) -> Result<rustls::server::danger::ClientCertVerified, rustls::Error> {
        Ok(rustls::server::danger::ClientCertVerified::assertion())
    }

    fn verify_tls13_signature(
        &self,
        _message: &[u8],
        _cert: &rustls::pki_types::CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn verify_tls12_signature(
        &self,
        _message: &[u8],
        _cert: &rustls::pki_types::CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
        nine_supported_verify_schemes()
    }
}

/// Presents an [`Ed25519SecretKey`] as an RFC 7250 raw public key server
/// certificate: the SPKI DER (Ed25519 OID + 32-byte key) is the "cert",
/// `only_raw_public_keys() == true`, and the signing key is the shared
/// [`Ed25519SigningKey`] helper.
pub struct RawKeyCertResolver {
    key: Arc<rustls::sign::CertifiedKey>,
}

impl RawKeyCertResolver {
    pub fn new(secret_key: &Ed25519SecretKey) -> Self {
        let signing_key = Arc::new(Ed25519SigningKey::new(secret_key.clone()));
        let public_key = signing_key.spki_public_key();
        let cert = rustls::pki_types::CertificateDer::from(public_key.to_vec());
        let certified_key = rustls::sign::CertifiedKey::new(vec![cert], signing_key);
        Self {
            key: Arc::new(certified_key),
        }
    }
}

impl rustls::server::ResolvesServerCert for RawKeyCertResolver {
    fn resolve(
        &self,
        _client_hello: rustls::server::ClientHello<'_>,
    ) -> Option<Arc<rustls::sign::CertifiedKey>> {
        Some(Arc::clone(&self.key))
    }

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

impl std::fmt::Debug for RawKeyCertResolver {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RawKeyCertResolver").finish()
    }
}

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

    #[test]
    fn raw_key_cert_resolver_only_raw_public_keys() {
        use rustls::server::ResolvesServerCert;
        let sk = Ed25519SecretKey::generate();
        let resolver = RawKeyCertResolver::new(&sk);
        assert!(resolver.only_raw_public_keys());
    }

    #[test]
    fn self_signed_cert_generation_produces_cert_and_key() {
        let cert = generate_self_signed_cert().expect("self-signed cert generates");
        assert!(!cert.cert_chain.is_empty());
        assert!(!cert.private_key.secret_der().is_empty());
    }

    #[tokio::test]
    async fn tls_setup_x509_returns_no_acme_state() {
        use rcgen::{CertificateParams, KeyPair};
        let key_pair = KeyPair::generate().unwrap();
        let params = CertificateParams::default();
        let cert = params.self_signed(&key_pair).unwrap();
        let cert_pem = cert.pem();
        let key_pem = key_pair.serialize_pem();

        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, cert_pem).unwrap();
        std::fs::write(&key_path, key_pem).unwrap();

        let tls_identity = TlsIdentity::X509 {
            cert: cert_path,
            key: key_path,
        };
        let setup = TlsServerConfig::new(&tls_identity, &[b"alktls/test".to_vec()])
            .await
            .expect("X509 tls setup should succeed");
        let _ = setup.rustls_config;
        #[cfg(feature = "acme")]
        assert!(setup.acme_handle.is_none());
    }

    #[test]
    fn build_rustls_server_config_raw_key_succeeds() {
        let sk = Ed25519SecretKey::generate();
        let identity = TlsIdentity::RawKey(sk);
        let alpns = vec![b"alktls/test".to_vec(), b"alktls/call".to_vec()];
        let config = build_rustls_server_config(&identity, &alpns).expect("raw key config builds");
        assert_eq!(config.alpn_protocols, alpns);
        assert_eq!(config.max_early_data_size, u32::MAX);
    }

    #[test]
    fn build_rustls_server_config_self_signed_succeeds() {
        let identity = TlsIdentity::SelfSigned;
        let alpns = vec![b"alktls/test".to_vec()];
        let config =
            build_rustls_server_config(&identity, &alpns).expect("self-signed config builds");
        assert_eq!(config.alpn_protocols, alpns);
        assert_eq!(config.max_early_data_size, u32::MAX);
    }

    #[test]
    fn build_rustls_server_config_acme_returns_config_error() {
        let identity = TlsIdentity::Acme {
            domains: vec!["example.com".to_string()],
            cache_dir: std::path::PathBuf::from("/tmp/alktls-acme-test"),
            directory: crate::identity::AcmeDirectory::Staging,
            contact: vec!["mailto:dev@example.com".to_string()],
        };
        let err = build_rustls_server_config(&identity, &[])
            .expect_err("Acme identity must not reach the plain builder");
        assert!(
            matches!(err, TlsError::AcmeConfig(_)),
            "the defensive Acme arm must surface as TlsError::AcmeConfig, got {err:?}"
        );
    }

    #[cfg(feature = "noq")]
    #[test]
    fn for_noq_round_trips_raw_key_config() {
        let sk = Ed25519SecretKey::generate();
        let rustls_config =
            build_rustls_server_config(&TlsIdentity::RawKey(sk), &[b"alktls/test".to_vec()])
                .expect("rustls config builds");
        let config = TlsServerConfig {
            rustls_config,
            #[cfg(feature = "acme")]
            acme_handle: None,
        };
        let noq_config = config.for_noq().expect("noq config converts");
        let _ = noq_config;
    }

    #[test]
    fn accept_any_cert_verifier_offers_and_does_not_require_client_auth() {
        use rustls::server::danger::ClientCertVerifier;
        let verifier = AcceptAnyCertVerifier;
        assert!(verifier.offer_client_auth());
        assert!(!verifier.client_auth_mandatory());
        assert!(verifier.root_hint_subjects().is_empty());
    }

    fn dss_with_scheme(
        scheme: rustls::SignatureScheme,
        signature: Vec<u8>,
    ) -> rustls::DigitallySignedStruct {
        use rustls::internal::msgs::codec::{Codec, Reader};
        let mut encoded = Vec::new();
        scheme.encode(&mut encoded);
        (signature.len() as u16).encode(&mut encoded);
        encoded.extend_from_slice(&signature);
        rustls::DigitallySignedStruct::read(&mut Reader::init(&encoded))
            .expect("DigitallySignedStruct decodes from its wire encoding")
    }

    #[test]
    fn verify_presented_cert_verifier_tls12_signature_routes_ed25519_spki_through_raw_key_path() {
        use rustls::server::danger::ClientCertVerifier;

        let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
        let verifier = VerifyPresentedCertVerifier::new(&provider);

        let sk = Ed25519SecretKey::generate();
        let raw_key = sk.public().to_bytes();
        let spki_der =
            rustls::sign::public_key_to_spki(&rustls::pki_types::alg_id::ED25519, raw_key).to_vec();
        let message = b"alktls verify-presented tls12 raw-key routing";
        let signature = sk.sign(message).to_bytes().to_vec();
        let dss = dss_with_scheme(rustls::SignatureScheme::ED25519, signature);
        let cert = rustls::pki_types::CertificateDer::from(spki_der);

        let result = verifier.verify_tls12_signature(message, &cert, &dss);
        assert!(
            result.is_ok(),
            "TLS 1.2 signature for an Ed25519 SPKI presentation must route \
             through the raw-key path and verify, got: {result:?}"
        );

        let forged = dss_with_scheme(rustls::SignatureScheme::ED25519, vec![0u8; 64]);
        let tampered = verifier.verify_tls12_signature(b"tampered", &cert, &forged);
        assert!(
            tampered.is_err(),
            "a signature that does not verify must fail the possession check"
        );
    }

    #[test]
    fn verify_presented_cert_verifier_tls12_signature_routes_x509_through_standard_path() {
        use rustls::server::danger::ClientCertVerifier;

        let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
        let verifier = VerifyPresentedCertVerifier::new(&provider);

        let key_pair = rcgen::KeyPair::generate().expect("ECDSA P-256 key gen");
        let cert = rcgen::CertificateParams::default()
            .self_signed(&key_pair)
            .expect("self-signed cert");
        let cert_der = cert.der().clone();

        let signing_key = rustls::crypto::aws_lc_rs::sign::any_ecdsa_type(
            &rustls::pki_types::PrivateKeyDer::Pkcs8(rustls::pki_types::PrivatePkcs8KeyDer::from(
                key_pair.serialize_der(),
            )),
        )
        .expect("ECDSA signing key loads");
        let message = b"alktls verify-presented tls12 x509 routing";
        let signature = signing_key
            .choose_scheme(&[rustls::SignatureScheme::ECDSA_NISTP256_SHA256])
            .expect("ECDSA_NISTP256_SHA256 must be offered")
            .sign(message)
            .expect("signing must succeed");
        let dss = dss_with_scheme(rustls::SignatureScheme::ECDSA_NISTP256_SHA256, signature);

        let result = verifier.verify_tls12_signature(message, &cert_der, &dss);
        assert!(
            result.is_ok(),
            "TLS 1.2 signature for an X.509 presentation must route through the \
             standard verification path and verify, got: {result:?}"
        );

        let wrong_key = rcgen::KeyPair::generate().expect("other key gen");
        let other_signing_key = rustls::crypto::aws_lc_rs::sign::any_ecdsa_type(
            &rustls::pki_types::PrivateKeyDer::Pkcs8(rustls::pki_types::PrivatePkcs8KeyDer::from(
                wrong_key.serialize_der(),
            )),
        )
        .expect("other ECDSA signing key loads");
        let wrong_signature = other_signing_key
            .choose_scheme(&[rustls::SignatureScheme::ECDSA_NISTP256_SHA256])
            .expect("ECDSA_NISTP256_SHA256 must be offered")
            .sign(message)
            .expect("signing must succeed");
        let wrong_key_dss = dss_with_scheme(
            rustls::SignatureScheme::ECDSA_NISTP256_SHA256,
            wrong_signature,
        );
        let tampered = verifier.verify_tls12_signature(message, &cert_der, &wrong_key_dss);
        assert!(
            tampered.is_err(),
            "a valid signature under a different key must fail the possession check"
        );
    }

    #[test]
    fn verify_presented_cert_verifier_tls12_signature_rejects_mismatched_message() {
        use rustls::server::danger::ClientCertVerifier;

        let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
        let verifier = VerifyPresentedCertVerifier::new(&provider);

        let sk = Ed25519SecretKey::generate();
        let raw_key = sk.public().to_bytes();
        let spki_der =
            rustls::sign::public_key_to_spki(&rustls::pki_types::alg_id::ED25519, raw_key).to_vec();
        let signature = sk.sign(b"the real message").to_bytes().to_vec();
        let dss = dss_with_scheme(rustls::SignatureScheme::ED25519, signature);
        let cert = rustls::pki_types::CertificateDer::from(spki_der);

        let result = verifier.verify_tls12_signature(b"a different message", &cert, &dss);
        assert!(
            result.is_err(),
            "a signature over a different message must fail the possession check"
        );
    }

    #[test]
    fn server_verifiers_keep_requires_raw_public_keys_default_false() {
        use rustls::server::danger::ClientCertVerifier;
        assert!(
            !AcceptAnyCertVerifier.requires_raw_public_keys(),
            "the request-not-require shape must accept both cert types; requires_raw_public_keys() == true would reject every X.509 client (ADR-007, review 001 N-4)"
        );
        let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
        let verifier = VerifyPresentedCertVerifier::new(&provider);
        assert!(
            !verifier.requires_raw_public_keys(),
            "the default verifier must keep the trait default; a raw-only demand is the interop boundary documented under ADR-007"
        );
    }

    #[test]
    fn accept_any_cert_verifier_verifies_any_client_cert() {
        use rustls::pki_types::{CertificateDer, UnixTime};
        use rustls::server::danger::ClientCertVerifier;
        let verifier = AcceptAnyCertVerifier;
        let cert = CertificateDer::from(b"fake-cert-der".to_vec());
        let result = verifier.verify_client_cert(&cert, &[], UnixTime::now());
        assert!(
            result.is_ok(),
            "AcceptAnyCertVerifier must accept any client cert"
        );
    }

    #[test]
    fn accept_any_cert_verifier_supported_schemes_are_the_nine_pinned() {
        use rustls::server::danger::ClientCertVerifier;
        let verifier = AcceptAnyCertVerifier;
        let schemes = verifier.supported_verify_schemes();
        assert_eq!(
            schemes,
            vec![
                rustls::SignatureScheme::ED25519,
                rustls::SignatureScheme::ECDSA_NISTP256_SHA256,
                rustls::SignatureScheme::ECDSA_NISTP384_SHA384,
                rustls::SignatureScheme::RSA_PSS_SHA256,
                rustls::SignatureScheme::RSA_PSS_SHA384,
                rustls::SignatureScheme::RSA_PSS_SHA512,
                rustls::SignatureScheme::RSA_PKCS1_SHA256,
                rustls::SignatureScheme::RSA_PKCS1_SHA384,
                rustls::SignatureScheme::RSA_PKCS1_SHA512,
            ]
        );
    }

    #[test]
    fn accept_any_cert_verifier_debug_is_implemented() {
        let verifier = AcceptAnyCertVerifier;
        let s = format!("{verifier:?}");
        assert!(s.contains("AcceptAnyCertVerifier"));
    }

    #[test]
    fn accept_any_cert_verifier_tls12_signature_asserts_without_possession_check() {
        use rustls::server::danger::ClientCertVerifier;

        let verifier = AcceptAnyCertVerifier;
        let cert = rustls::pki_types::CertificateDer::from(b"not even a cert".to_vec());
        let dss = dss_with_scheme(rustls::SignatureScheme::ED25519, vec![0u8; 64]);
        let result = verifier.verify_tls12_signature(b"any message", &cert, &dss);
        assert!(
            result.is_ok(),
            "the escape hatch must assert TLS 1.2 signature validity \
             unconditionally (the documented no-pop posture), got: {result:?}"
        );
    }

    #[test]
    fn verify_presented_cert_verifier_supported_schemes_are_the_nine_pinned() {
        use rustls::server::danger::ClientCertVerifier;

        let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
        let verifier = VerifyPresentedCertVerifier::new(&provider);
        assert_eq!(
            verifier.supported_verify_schemes(),
            nine_supported_verify_schemes(),
            "the default verifier must report the same nine-scheme list as the \
             escape hatch (the load-bearing list)"
        );
    }

    #[test]
    fn raw_key_cert_resolver_debug_is_implemented() {
        let sk = Ed25519SecretKey::generate();
        let resolver = RawKeyCertResolver::new(&sk);
        let s = format!("{resolver:?}");
        assert!(s.contains("RawKeyCertResolver"));
    }

    #[cfg(feature = "tcp")]
    #[tokio::test]
    async fn new_x509_for_tcp_tls_and_rustls_config_round_trip() {
        use rcgen::{CertificateParams, KeyPair};
        let key_pair = KeyPair::generate().unwrap();
        let cert = CertificateParams::default().self_signed(&key_pair).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, cert.pem()).unwrap();
        std::fs::write(&key_path, key_pair.serialize_pem()).unwrap();
        let identity = TlsIdentity::X509 {
            cert: cert_path,
            key: key_path,
        };
        let alpn = vec![b"alktls/test".to_vec()];
        let setup = TlsServerConfig::new(&identity, &alpn)
            .await
            .expect("X509 config builds");
        let rc = setup.rustls_config();
        assert_eq!(rc.alpn_protocols, alpn);
        assert_eq!(rc.max_early_data_size, u32::MAX);
        let _acceptor = setup.for_tcp_tls();
    }

    #[cfg(feature = "tcp")]
    #[tokio::test]
    async fn new_raw_key_for_tcp_tls_and_rustls_config_round_trip() {
        let identity = TlsIdentity::RawKey(Ed25519SecretKey::generate());
        let alpn = vec![b"alktls/test".to_vec()];
        let setup = TlsServerConfig::new(&identity, &alpn)
            .await
            .expect("raw key config builds");
        let rc = setup.rustls_config();
        assert_eq!(rc.alpn_protocols, alpn);
        assert_eq!(rc.max_early_data_size, u32::MAX);
        let _acceptor = setup.for_tcp_tls();
    }

    #[cfg(feature = "tcp")]
    #[tokio::test]
    async fn new_self_signed_for_tcp_tls_and_rustls_config_round_trip() {
        let identity = TlsIdentity::SelfSigned;
        let alpn = vec![b"alktls/test".to_vec()];
        let setup = TlsServerConfig::new(&identity, &alpn)
            .await
            .expect("self-signed config builds");
        let rc = setup.rustls_config();
        assert_eq!(rc.alpn_protocols, alpn);
        assert_eq!(rc.max_early_data_size, u32::MAX);
        let _acceptor = setup.for_tcp_tls();
    }

    #[cfg(feature = "acme")]
    #[tokio::test]
    async fn new_acme_spawns_and_appends_acme_tls_alpn() {
        let dir = tempfile::tempdir().unwrap();
        let identity = TlsIdentity::Acme {
            domains: vec!["localhost".to_string()],
            cache_dir: dir.path().join("cache"),
            directory: crate::identity::AcmeDirectory::Custom(
                "http://127.0.0.1:9/directory".to_string(),
            ),
            contact: vec!["mailto:dev@example.com".to_string()],
        };
        let alpn = vec![b"alktls/test".to_vec()];
        let setup = TlsServerConfig::new(&identity, &alpn)
            .await
            .expect("ACME config builds without awaiting the order");
        let rc = setup.rustls_config();
        assert_eq!(rc.max_early_data_size, u32::MAX);
        assert_eq!(
            rc.alpn_protocols,
            vec![b"alktls/test".to_vec(), b"acme-tls/1".to_vec()]
        );
        assert!(
            setup.acme_handle.is_some(),
            "the event-loop task must be spawned and its handle stored"
        );
    }

    #[cfg(feature = "acme")]
    #[tokio::test]
    async fn new_acme_caller_supplied_acme_tls_alpn_is_not_duplicated() {
        let dir = tempfile::tempdir().unwrap();
        let identity = TlsIdentity::Acme {
            domains: vec!["localhost".to_string()],
            cache_dir: dir.path().join("cache"),
            directory: crate::identity::AcmeDirectory::Custom(
                "http://127.0.0.1:9/directory".to_string(),
            ),
            contact: vec!["mailto:dev@example.com".to_string()],
        };
        let alpn = vec![b"alktls/test".to_vec(), b"acme-tls/1".to_vec()];
        let setup = TlsServerConfig::new(&identity, &alpn)
            .await
            .expect("ACME config builds without awaiting the order");
        assert_eq!(
            setup.rustls_config().alpn_protocols,
            vec![b"alktls/test".to_vec(), b"acme-tls/1".to_vec()],
            "a caller-supplied acme-tls/1 must yield exactly one entry"
        );
    }

    #[cfg(feature = "acme")]
    #[tokio::test]
    async fn new_acme_empty_domains_returns_config_error() {
        let dir = tempfile::tempdir().unwrap();
        let identity = TlsIdentity::Acme {
            domains: vec![],
            cache_dir: dir.path().join("cache"),
            directory: crate::identity::AcmeDirectory::Staging,
            contact: vec!["mailto:dev@example.com".to_string()],
        };
        let err = TlsServerConfig::new(&identity, &[b"alktls/test".to_vec()])
            .await
            .err()
            .expect("empty domain list must not construct an ACME config");
        assert!(
            matches!(err, TlsError::AcmeConfig(_)),
            "empty domains must surface as TlsError::AcmeConfig, got {err:?}"
        );
    }

    #[cfg(not(feature = "acme"))]
    #[tokio::test]
    async fn new_acme_identity_without_feature_returns_config_error() {
        let identity = TlsIdentity::Acme {
            domains: vec!["example.com".to_string()],
            cache_dir: std::path::PathBuf::from("/tmp/alktls-acme-test"),
            directory: crate::identity::AcmeDirectory::Staging,
            contact: vec!["mailto:dev@example.com".to_string()],
        };
        let err = match TlsServerConfig::new(&identity, &[]).await {
            Ok(_) => panic!("Acme identity must fail without the acme feature"),
            Err(e) => e,
        };
        assert!(
            matches!(err, TlsError::AcmeConfig(_)),
            "expected TlsError::AcmeConfig, got {err:?}"
        );
    }
}