ostrya-fetch 0.3.0

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

use std::io::BufReader;
use std::sync::Arc;

use ostrya_rt as rt;
use rustls::ClientConfig;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
use rustls::{DigitallySignedStruct, SignatureScheme};

use super::{Error, Result};

/// The trust setting that a fetcher verifies a server certificate with.
///
/// The default is [`System`](TrustRoots::System). No variant checks
/// revocation, because the anchored path configures no CRL.
///
/// All TLS connections use the `graviola` crypto provider of rustls. The
/// provider is Rust and assembly, with formally verified assembly where it is
/// available. It adds no C code and no `cc` build dependency.
///
/// # Bypass variants
///
/// [`DangerousAcceptAnyChain`](TrustRoots::DangerousAcceptAnyChain) and
/// [`DangerousAcceptAny`](TrustRoots::DangerousAcceptAny) bypass the
/// verification of the server certificate. They are for an origin whose
/// certificate the operator does not want to check. Under a bypass variant,
/// the fetcher reads no trust store.
///
/// Both variants verify the handshake signature, so the peer proves that it
/// holds the private key of the certificate that it presents. Nobody vouches
/// for that certificate, so the peer is not authenticated.
///
/// An active attacker on the path can present a certificate of its own, and
/// the handshake completes. A credential sent to such an origin goes to the
/// party that answers the connection.
///
/// The cleartext credential checks of the fetcher read the scheme alone, so a
/// credential goes to a bypass origin. The `ostree` command and `curl -k` also
/// send it. The operator who selects a bypass accepts this risk.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum TrustRoots {
    /// The certificates that the host system trusts.
    #[default]
    System,
    /// The PEM-encoded certificates in this blob, and no other certificates.
    ///
    /// If the blob does not decode as PEM, holds no certificate, or holds a
    /// certificate that the root store refuses, [`Fetcher::new`] returns
    /// [`Error::Fetch`].
    ///
    /// [`Fetcher::new`]: crate::Fetcher::new
    Pem(Vec<u8>),
    /// A bypass that accepts any server chain and keeps the host name check.
    ///
    /// The chain needs no trust anchor. The fetcher checks no expiry and no
    /// key usage, so a client certificate or a CA certificate passes as a
    /// server leaf. The certificate must carry the host name that the request
    /// names. [`TrustRoots`](TrustRoots#bypass-variants) states the risk.
    DangerousAcceptAnyChain,
    /// A bypass that accepts any server certificate, with no host name check.
    ///
    /// This variant is
    /// [`DangerousAcceptAnyChain`](TrustRoots::DangerousAcceptAnyChain) with
    /// the host name check removed. The certificate can carry any name.
    /// [`TrustRoots`](TrustRoots#bypass-variants) states the risk.
    DangerousAcceptAny,
}

/// A client certificate and its private key, for TLS client authentication.
///
/// Both are PEM-encoded. A remote that authenticates its clients with TLS
/// needs an identity.
#[derive(Clone, Eq, PartialEq)]
pub struct ClientIdentity {
    /// The client certificate, followed by any intermediate certificates.
    ///
    /// If the blob holds no certificate, [`Fetcher::new`] returns
    /// [`Error::Fetch`].
    ///
    /// [`Fetcher::new`]: crate::Fetcher::new
    pub cert_chain_pem: Vec<u8>,
    /// The private key of the client certificate.
    ///
    /// The blob holds one section or more. The fetcher reads the first
    /// section whose armor label names a private key, and that section
    /// selects the path:
    ///
    /// - A `PRIVATE KEY`, `RSA PRIVATE KEY`, or `EC PRIVATE KEY` section is
    ///   read as it is.
    /// - An `ENCRYPTED PRIVATE KEY` section is PKCS#8 under PBES2.
    ///   [`key_passphrase`](ClientIdentity::key_passphrase) decrypts it.
    ///
    /// If the blob holds no private key section, [`Fetcher::new`] returns
    /// [`Error::Fetch`].
    ///
    /// [`Fetcher::new`]: crate::Fetcher::new
    pub key_pem: Vec<u8>,
    /// The passphrase of an encrypted PKCS#8 private key.
    ///
    /// If this is set and the key section carries no encryption, the fetcher
    /// refuses the key. A passphrase that decrypts nothing hides a
    /// configuration mistake.
    ///
    /// # Algorithms
    ///
    /// - Ciphers: AES-128-CBC, AES-192-CBC, and AES-256-CBC.
    /// - Key derivation functions: PBKDF2 with an HMAC-SHA-2 pseudorandom
    ///   function, and scrypt.
    ///
    /// # Key derivation cost
    ///
    /// The key file sets the cost of the key derivation. The iteration count
    /// of PBKDF2 and the cost parameter of scrypt come from the file. A file
    /// with an extreme parameter uses that much processor time or memory. The
    /// operator supplies the key file, so ostrya applies no bound to either
    /// parameter.
    ///
    /// # Refusals
    ///
    /// [`Fetcher::new`] returns [`Error::Fetch`], with a message of its own,
    /// in each of these cases:
    ///
    /// - The key is encrypted, and no passphrase is set.
    /// - A passphrase is set, and the key section carries no encryption.
    /// - The passphrase does not decrypt the key.
    /// - This build has no implementation of the PBES2 cipher or key
    ///   derivation function. The message names the OID. DES, 3DES, and
    ///   PBKDF2 with an HMAC-SHA-1 pseudorandom function get this refusal.
    /// - The key is under PKCS#5 PBES1, which the `pkcs5` crate parses and
    ///   does not decrypt. The message names PBES1. `pkcs5` recognizes six
    ///   PBES1 OIDs, and an OID outside that set gives a DER decoding failure.
    ///   A corrupted document gives the same failure, so the two cases look
    ///   the same.
    /// - The key is in the legacy OpenSSL traditional PEM format, with a
    ///   `Proc-Type: 4,ENCRYPTED` header line in the section. The message
    ///   names the `openssl pkcs8 -topk8` conversion, which gives a PKCS#8
    ///   key. This refusal applies with or without a passphrase.
    ///
    /// [`Fetcher::new`]: crate::Fetcher::new
    pub key_passphrase: Option<String>,
}

/// Redacts the private key and the passphrase.
///
/// A logged configuration holds neither. The key shows as its length in
/// bytes, and the passphrase shows as `"<redacted>"` if it is set. The
/// certificate chain is public material and shows in full.
impl std::fmt::Debug for ClientIdentity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClientIdentity")
            .field("cert_chain_pem", &self.cert_chain_pem)
            .field(
                "key_pem",
                &format!("<{} bytes redacted>", self.key_pem.len()),
            )
            .field(
                "key_passphrase",
                &self.key_passphrase.as_ref().map(|_| "<redacted>"),
            )
            .finish()
    }
}

/// The TLS options of a fetcher.
///
/// The default trusts the host system store, [`TrustRoots::System`], and
/// presents no client certificate.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct TlsOptions {
    /// The trust setting for the server certificate.
    pub roots: TrustRoots,
    /// The client certificate to present, for a remote that requires one.
    ///
    /// The fetcher presents the certificate to the origin that a request
    /// names, the origin of a mirror or of a URL target. A redirect hop at
    /// another origin gets no certificate. [`Fetcher::fetch`] states the
    /// redirect rules.
    ///
    /// [`Fetcher::fetch`]: crate::Fetcher::fetch
    pub client_identity: Option<ClientIdentity>,
}

/// The client configurations one fetcher opens its connections with.
#[derive(Debug)]
pub(crate) struct ClientConfigs {
    /// What a connection to the origin a route named is opened with. It
    /// presents the configured client certificate.
    pub(crate) with_identity: Arc<ClientConfig>,
    /// What a connection to a redirect hop at any other origin is opened with.
    /// It presents no client certificate. With none configured this is the
    /// other field's own `Arc`.
    pub(crate) without_identity: Arc<ClientConfig>,
    /// `true` if a handshake has what it needs to verify the peer. A store
    /// with no anchor reaches here for a fetcher whose mirrors are all
    /// cleartext, which opens no handshake to reach them. The caller refuses
    /// a fetch that opens one, from the origin of the route or from a redirect
    /// hop. A bypass variant of [`TrustRoots`] reads no store and reports
    /// `true`, because its handshake consults no anchor and completes.
    pub(crate) has_trust_anchors: bool,
}

/// Builds the shared client configurations.
///
/// `http2` selects whether ALPN offers `h2`. `https` tells whether any mirror
/// is reached over TLS, which makes an empty system trust store fatal.
/// `reaches_tls` tells whether any fetch can open a handshake, through a
/// mirror, a URL target, or a redirect. Without it, [`TrustRoots::System`]
/// reads no store and gives the empty one. `https` implies `reaches_tls`.
pub(crate) async fn client_config(
    options: &TlsOptions,
    http2: bool,
    https: bool,
    reaches_tls: bool,
) -> Result<ClientConfigs> {
    let provider = Arc::new(rustls_graviola::default_provider());
    let verification = verification(&options.roots, https, reaches_tls, &provider).await?;
    let has_trust_anchors = match &verification {
        Verification::Anchors(store) => !store.is_empty(),
        Verification::Bypass(_) => true,
    };
    let alpn = if http2 {
        vec![b"h2".to_vec(), b"http/1.1".to_vec()]
    } else {
        vec![b"http/1.1".to_vec()]
    };
    let mut plain = shared(&provider, &verification)?.with_no_client_auth();
    plain.alpn_protocols = alpn.clone();
    let without_identity = Arc::new(plain);
    // The certificate half is built only where a certificate is configured, so
    // a fetcher without one holds one configuration under two names.
    let with_identity = match &options.client_identity {
        Some(identity) => {
            let chain = parse_certs(&identity.cert_chain_pem)?;
            if chain.is_empty() {
                return Err(Error::Fetch(
                    "client certificate holds no certificate".into(),
                ));
            }
            let key = parse_key(&identity.key_pem, identity.key_passphrase.as_deref()).await?;
            let mut config = shared(&provider, &verification)?
                .with_client_auth_cert(chain, key)
                .map_err(|e| Error::Fetch(format!("client certificate rejected: {e}")))?;
            config.alpn_protocols = alpn;
            Arc::new(config)
        }
        None => without_identity.clone(),
    };
    Ok(ClientConfigs {
        with_identity,
        without_identity,
        has_trust_anchors,
    })
}

/// Builds the TLS configuration of an HTTP server from PEM bytes.
///
/// The inputs are the certificate chain, the private key, and the passphrase
/// of an encrypted key. With `client_ca_pem`, the server verifies a client
/// certificate against that CA. A client that presents a certificate must
/// present one that the CA signed. A client that presents none completes the
/// handshake.
///
/// The key is read as the key of a [`ClientIdentity`] is read, with the same
/// refusals. ALPN offers `h2`, then `http/1.1`.
///
/// # Errors
///
/// - [`Error::Fetch`] if `cert_chain_pem` does not decode as PEM, or holds no
///   certificate.
/// - [`Error::Fetch`] if `key_pem` holds no private key that decodes, or if a
///   refusal of [`ClientIdentity::key_passphrase`] applies.
/// - [`Error::Fetch`] if the crypto provider supports no default protocol
///   version.
/// - [`Error::Fetch`] if `client_ca_pem` does not decode as PEM, holds no
///   certificate, or holds a certificate that the root store refuses.
/// - [`Error::Fetch`] if rustls refuses the client certificate verifier that
///   it builds from `client_ca_pem`.
/// - [`Error::Fetch`] if rustls refuses the certificate chain with the key,
///   for example a key of another certificate.
pub async fn server_config(
    cert_chain_pem: &[u8],
    key_pem: &[u8],
    key_passphrase: Option<&str>,
    client_ca_pem: Option<&[u8]>,
) -> Result<Arc<rustls::ServerConfig>> {
    let provider = Arc::new(rustls_graviola::default_provider());
    let chain = parse_certs(cert_chain_pem)?;
    if chain.is_empty() {
        return Err(Error::Fetch(
            "server certificate holds no certificate".into(),
        ));
    }
    let key = parse_key(key_pem, key_passphrase).await?;
    let builder = rustls::ServerConfig::builder_with_provider(provider.clone())
        .with_safe_default_protocol_versions()
        .map_err(|e| Error::Fetch(format!("tls setup: {e}")))?;
    let builder = match client_ca_pem {
        Some(pem) => {
            let verifier = rustls::server::WebPkiClientVerifier::builder_with_provider(
                Arc::new(pem_store(pem)?),
                provider,
            )
            .allow_unauthenticated()
            .build()
            .map_err(|e| Error::Fetch(format!("client ca rejected: {e}")))?;
            builder.with_client_cert_verifier(verifier)
        }
        None => builder.with_no_client_auth(),
    };
    let mut config = builder
        .with_single_cert(chain, key)
        .map_err(|e| Error::Fetch(format!("server certificate rejected: {e}")))?;
    config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
    Ok(Arc::new(config))
}

/// Returns the builder state that both client configurations hold.
///
/// The state is the crypto provider, the protocol versions, and the
/// verification of the server certificate. Both share the store and the
/// bypass verifier by `Arc`, so the store is parsed once and held once.
fn shared(
    provider: &Arc<rustls::crypto::CryptoProvider>,
    verification: &Verification,
) -> Result<rustls::ConfigBuilder<ClientConfig, rustls::client::WantsClientCert>> {
    let builder = ClientConfig::builder_with_provider(provider.clone())
        .with_safe_default_protocol_versions()
        .map_err(|e| Error::Fetch(format!("tls setup: {e}")))?;
    Ok(match verification {
        Verification::Anchors(store) => builder.with_root_certificates(store.clone()),
        Verification::Bypass(verifier) => builder
            .dangerous()
            .with_custom_certificate_verifier(verifier.clone()),
    })
}

/// How the client configurations verify the server certificate.
enum Verification {
    /// Against these trust anchors, which is the full check.
    Anchors(Arc<rustls::RootCertStore>),
    /// Against this verifier, which drops part of the check.
    Bypass(Arc<dyn ServerCertVerifier>),
}

/// Resolves the trust setting into what the configurations verify with.
///
/// `https` tells whether a handshake will consult the anchors, and
/// `reaches_tls` tells whether any handshake can open. A bypass variant and
/// [`TrustRoots::System`] without `reaches_tls` read nothing, so they touch no
/// file system and no blocking pool.
async fn verification(
    roots: &TrustRoots,
    https: bool,
    reaches_tls: bool,
    provider: &Arc<rustls::crypto::CryptoProvider>,
) -> Result<Verification> {
    Ok(match roots {
        TrustRoots::System if !reaches_tls => {
            Verification::Anchors(Arc::new(rustls::RootCertStore::empty()))
        }
        TrustRoots::System => Verification::Anchors(Arc::new(system_store(https).await?)),
        TrustRoots::Pem(pem) => Verification::Anchors(Arc::new(pem_store(pem)?)),
        TrustRoots::DangerousAcceptAnyChain => Verification::Bypass(Arc::new(AcceptAnyChain {
            provider: provider.clone(),
            check_name: true,
        })),
        TrustRoots::DangerousAcceptAny => Verification::Bypass(Arc::new(AcceptAnyChain {
            provider: provider.clone(),
            check_name: false,
        })),
    })
}

/// The verifier that the bypass variants of [`TrustRoots`] install.
///
/// It accepts the chain that the server presents with no trust anchor, no
/// expiry check, and no key-usage check. The anchored path holds the leaf to
/// webpki's `KeyUsage::server_auth`, and this verifier holds it to nothing. So
/// a client certificate or a CA certificate passes as a server leaf. Neither
/// path checks revocation.
///
/// `check_name` selects whether the end-entity certificate must carry the name
/// that the request names. That is the one difference between
/// [`TrustRoots::DangerousAcceptAnyChain`] and [`TrustRoots::DangerousAcceptAny`].
///
/// The three signature members delegate to the crypto provider, so the
/// handshake signature is verified as under the full check. That proves
/// possession of the private key of a certificate that nobody vouches for, so
/// it authenticates no peer.
#[derive(Debug)]
struct AcceptAnyChain {
    provider: Arc<rustls::crypto::CryptoProvider>,
    check_name: bool,
}

impl ServerCertVerifier for AcceptAnyChain {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        _intermediates: &[CertificateDer<'_>],
        server_name: &ServerName<'_>,
        _ocsp_response: &[u8],
        _now: UnixTime,
    ) -> std::result::Result<ServerCertVerified, rustls::Error> {
        if self.check_name {
            let cert = rustls::server::ParsedCertificate::try_from(end_entity)?;
            rustls::client::verify_server_name(&cert, server_name)?;
        }
        Ok(ServerCertVerified::assertion())
    }

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

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

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.provider
            .signature_verification_algorithms
            .supported_schemes()
    }
}

#[cfg(test)]
thread_local! {
    /// The reads of the host trust store that this thread started.
    pub(crate) static SYSTEM_STORE_READS: std::cell::Cell<usize> =
        const { std::cell::Cell::new(0) };
}

/// Assembles the trust anchors that the host system holds. `https` tells
/// whether a handshake will consult them.
async fn system_store(https: bool) -> Result<rustls::RootCertStore> {
    #[cfg(test)]
    SYSTEM_STORE_READS.with(|reads| reads.set(reads.get() + 1));
    let mut store = rustls::RootCertStore::empty();
    // The read and the parse of the host store are file system work, so they
    // run on the blocking pool, away from the executor thread of the caller.
    // The certificates come back as bytes. The add to the store does no I/O.
    let (certs, detail) = rt::unblock(|| {
        let loaded = rustls_native_certs::load_native_certs();
        let detail = loaded.errors.first().map(|e| e.to_string());
        (loaded.certs, detail)
    })
    .await;
    for cert in certs {
        // The loop skips a malformed certificate in the system store, as other
        // consumers of that store do.
        let _ = store.add(cert);
    }
    // A host without a CA bundle holds no anchors. That fails a fetcher with
    // an `https` mirror, because its handshake needs them. A cleartext-only
    // fetcher opens no handshake, so it keeps the empty store.
    if store.is_empty() && https {
        let detail = detail.unwrap_or_else(|| "the system trust store is empty".to_string());
        return Err(Error::Fetch(format!("no trusted certificates: {detail}")));
    }
    Ok(store)
}

/// Assembles the trust anchors that a PEM blob holds.
fn pem_store(pem: &[u8]) -> Result<rustls::RootCertStore> {
    let mut store = rustls::RootCertStore::empty();
    for cert in parse_certs(pem)? {
        store
            .add(cert)
            .map_err(|e| Error::Fetch(format!("trust anchor rejected: {e}")))?;
    }
    if store.is_empty() {
        return Err(Error::Fetch("trust anchors hold no certificate".into()));
    }
    Ok(store)
}

/// Decodes each certificate in a PEM blob.
fn parse_certs(pem: &[u8]) -> Result<Vec<CertificateDer<'static>>> {
    rustls_pemfile::certs(&mut BufReader::new(pem))
        .collect::<std::result::Result<Vec<_>, _>>()
        .map_err(|e| Error::Fetch(format!("certificate pem: {e}")))
}

/// The armor label of an encrypted PKCS#8 section, which this module
/// decrypts.
const ENCRYPTED_KEY_LABEL: &[u8] = b"ENCRYPTED PRIVATE KEY";

/// The armor labels `rustls_pemfile` reads a private key out of.
const PLAIN_KEY_LABELS: [&[u8]; 3] = [b"PRIVATE KEY", b"RSA PRIVATE KEY", b"EC PRIVATE KEY"];

/// The header that a legacy OpenSSL traditional encrypted PEM carries on a
/// line of its own inside the section.
///
/// RFC 7468 allows no header, so the PEM readers here stop on such a section.
/// The fetcher finds the line first and names the conversion. RFC 1421 makes
/// the space after the colon optional.
const LEGACY_ENCRYPTED_HEADER: &[u8] = b"Proc-Type:";

/// The value of that header in an encrypted section.
const LEGACY_ENCRYPTED_VALUE: &[u8] = b"4,ENCRYPTED";

/// The first section of a PEM blob whose armor label names a private key.
enum KeySection<'a> {
    /// An `ENCRYPTED PRIVATE KEY` section, cut out of the blob, so the
    /// decoder sees that section and nothing around it.
    Encrypted(&'a [u8]),
    /// A section under a label that `rustls_pemfile` reads a key from.
    Plain(&'a [u8]),
}

/// Decodes the private key that a PEM blob holds.
///
/// The first section whose armor label names a private key selects the path.
/// So a blob with a certificate and a key, or with two plain keys, reads as
/// `rustls_pemfile` reads it. An `ENCRYPTED PRIVATE KEY` section in front of a
/// plain key is a difference: that reader does not know the label and skips
/// to the plain key.
///
/// `passphrase` decrypts an `ENCRYPTED PRIVATE KEY` section. A passphrase on a
/// section that carries no encryption is refused, because a passphrase that
/// decrypts nothing hides a configuration mistake.
async fn parse_key(pem: &[u8], passphrase: Option<&str>) -> Result<PrivateKeyDer<'static>> {
    match first_key_section(pem) {
        Some(KeySection::Encrypted(section)) => decrypt_key(section, passphrase).await,
        Some(KeySection::Plain(section)) => {
            if is_legacy_encrypted(section) {
                return Err(Error::Fetch(
                    "private key pem is in the legacy openssl encrypted format. \
                     convert the key to pkcs#8 with `openssl pkcs8 -topk8`"
                        .into(),
                ));
            }
            if passphrase.is_some() {
                return Err(Error::Fetch(
                    "a passphrase is set for a private key pem that carries no encryption".into(),
                ));
            }
            read_plain_key(pem)
        }
        // A blob with no private-key section holds no key, whatever else it
        // carries. `rustls_pemfile` reports that.
        None => read_plain_key(pem),
    }
}

/// Reads the key that `rustls_pemfile` finds first. The section scan selects
/// that section before this call.
fn read_plain_key(pem: &[u8]) -> Result<PrivateKeyDer<'static>> {
    rustls_pemfile::private_key(&mut BufReader::new(pem))
        .map_err(|e| Error::Fetch(format!("private key pem: {e}")))?
        .ok_or_else(|| Error::Fetch("private key pem holds no key".into()))
}

/// Finds the first section whose armor label names a private key.
///
/// A key blob is a small configuration buffer, so this walks its lines. The
/// walk skips a certificate section and a section under any other label.
fn first_key_section(pem: &[u8]) -> Option<KeySection<'_>> {
    for (start, end) in line_ranges(pem, 0) {
        let Some(label) = armor_label(pem[start..end].trim_ascii(), b"BEGIN") else {
            continue;
        };
        if label == ENCRYPTED_KEY_LABEL {
            return Some(KeySection::Encrypted(section_at(pem, start, label)));
        }
        if PLAIN_KEY_LABELS.contains(&label) {
            return Some(KeySection::Plain(section_at(pem, start, label)));
        }
    }
    None
}

/// Returns the bytes of the section that opens at `begin`.
///
/// The bytes run from that line through the end of the matching end line. A
/// section with no end line runs to the end of the blob, and the decoder
/// reports it as no key.
fn section_at<'a>(pem: &'a [u8], begin: usize, label: &[u8]) -> &'a [u8] {
    for (start, end) in line_ranges(pem, begin) {
        if armor_label(pem[start..end].trim_ascii(), b"END") == Some(label) {
            return &pem[begin..end];
        }
    }
    &pem[begin..]
}

/// Returns the label of a PEM armor line.
///
/// The line is `-----BEGIN <label>-----` for the keyword `BEGIN` and
/// `-----END <label>-----` for `END`. A line that is neither gives `None`.
fn armor_label<'a>(line: &'a [u8], keyword: &[u8]) -> Option<&'a [u8]> {
    line.strip_prefix(b"-----".as_slice())?
        .strip_prefix(keyword)?
        .strip_prefix(b" ".as_slice())?
        .strip_suffix(b"-----".as_slice())
}

/// Returns `true` if a section carries the header of the legacy OpenSSL
/// traditional encrypted PEM.
///
/// The header opens a line of its own, so the same text in the free space
/// around a section reads as free text.
fn is_legacy_encrypted(section: &[u8]) -> bool {
    line_ranges(section, 0).any(|(start, end)| {
        section[start..end]
            .trim_ascii()
            .strip_prefix(LEGACY_ENCRYPTED_HEADER)
            .is_some_and(|value| value.trim_ascii_start() == LEGACY_ENCRYPTED_VALUE)
    })
}

/// Returns the byte range of each line of `pem` from `from`. Each range holds
/// the newline that ends its line.
fn line_ranges(pem: &[u8], from: usize) -> impl Iterator<Item = (usize, usize)> + '_ {
    let mut offset = from;
    std::iter::from_fn(move || {
        let start = offset;
        if start >= pem.len() {
            return None;
        }
        offset = pem[start..]
            .iter()
            .position(|byte| *byte == b'\n')
            .map_or(pem.len(), |index| start + index + 1);
        Some((start, offset))
    })
}

/// Decrypts an encrypted PKCS#8 section with `passphrase`.
///
/// PBKDF2 and scrypt are slow by design, and the key file sets how slow, so
/// the work runs on the blocking pool, away from the executor thread of the
/// caller. The closure owns its inputs, which costs one copy of the section
/// and one of the passphrase for each fetcher.
async fn decrypt_key(section: &[u8], passphrase: Option<&str>) -> Result<PrivateKeyDer<'static>> {
    let Some(passphrase) = passphrase else {
        return Err(Error::Fetch(
            "private key pem is encrypted, and no passphrase is set".into(),
        ));
    };
    let section = section.to_vec();
    let passphrase = passphrase.to_string();
    rt::unblock(move || decrypt_pkcs8(&section, &passphrase)).await
}

/// Decodes an encrypted PKCS#8 section and decrypts it.
///
/// If the decoder reads no document from the section, the error is the error
/// of an empty blob, because neither holds a key.
fn decrypt_pkcs8(section: &[u8], passphrase: &str) -> Result<PrivateKeyDer<'static>> {
    let no_key = || Error::Fetch("private key pem holds no key".into());
    let text = std::str::from_utf8(section).map_err(|_| no_key())?;
    let (_, document) = pkcs8::SecretDocument::from_pem(text).map_err(|_| no_key())?;
    // The document names the cipher and the key derivation function by OID.
    // The decoder refuses an OID that it has no implementation for. DES and
    // 3DES are compiled out, so a PBES2 key under either stops here.
    let info = document
        .decode_msg::<pkcs8::EncryptedPrivateKeyInfo<'_>>()
        .map_err(|e| match e.kind() {
            pkcs8::der::ErrorKind::OidUnknown { oid } => unsupported_algorithm(&oid),
            _ => Error::Fetch(format!("encrypted private key pem: {e}")),
        })?;
    let key = info.decrypt(passphrase).map_err(|e| match e {
        // A wrong passphrase derives a wrong key, and the plaintext of that
        // key carries invalid padding. `pkcs5` reports a padding failure as
        // `EncryptFailed` on the decryption path and on the encryption path.
        // It constructs `DecryptFailed` nowhere.
        pkcs8::Error::EncryptedPrivateKey(pkcs8::pkcs5::Error::EncryptFailed) => {
            Error::Fetch("the passphrase does not decrypt the private key".into())
        }
        // A PBES2 pseudorandom function that is compiled out gives this
        // error. An unknown cipher OID gives the decoder error.
        pkcs8::Error::EncryptedPrivateKey(pkcs8::pkcs5::Error::UnsupportedAlgorithm { oid }) => {
            unsupported_algorithm(&oid)
        }
        // `pkcs5` parses PBES1 and decrypts none of it.
        pkcs8::Error::EncryptedPrivateKey(pkcs8::pkcs5::Error::NoPbes1CryptSupport) => {
            Error::Fetch(
                "private key pem is encrypted under pkcs#5 pbes1, \
                 which this build does not decrypt"
                    .into(),
            )
        }
        other => Error::Fetch(format!("encrypted private key: {other}")),
    })?;
    Ok(PrivateKeyDer::Pkcs8(key.as_bytes().to_vec().into()))
}

/// Returns the refusal for an algorithm that this build has no implementation
/// of. The document names the algorithm by OID, and the message does too.
fn unsupported_algorithm(oid: &pkcs8::ObjectIdentifier) -> Error {
    Error::Fetch(format!(
        "private key pem is encrypted with algorithm {oid}, \
         which this build does not decrypt"
    ))
}

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

    const CA_PEM: &[u8] = include_bytes!("../../../tests/fixtures/tls/ca.pem");
    const CLIENT_CERT_PEM: &[u8] = include_bytes!("../../../tests/fixtures/tls/client.pem");
    const CLIENT_KEY_PEM: &[u8] = include_bytes!("../../../tests/fixtures/tls/client.key.pem");
    /// The same key, in PKCS#8 under PBES2 with AES-256-CBC.
    const CLIENT_KEY_ENC_PEM: &[u8] =
        include_bytes!("../../../tests/fixtures/tls/client.key.enc.pem");
    /// The same key, in the legacy OpenSSL traditional encrypted PEM.
    const CLIENT_KEY_LEGACY_PEM: &[u8] =
        include_bytes!("../../../tests/fixtures/tls/client.key.legacy.pem");
    /// The same key, in PKCS#8 under PBES1 with pbeWithMD5AndDES-CBC.
    const CLIENT_KEY_PBES1_PEM: &[u8] =
        include_bytes!("../../../tests/fixtures/tls/client.key.pbes1.pem");
    /// The passphrase that `tests/fixtures/tls/generate.sh` encrypts all
    /// three with.
    const KEY_PASSPHRASE: &str = "ostrya test passphrase";

    /// Builds the configurations from a client key and its passphrase, so a
    /// test states the one pair that it checks.
    fn configs_for_key(key_pem: &[u8], passphrase: Option<&str>) -> Result<ClientConfigs> {
        block_on(client_config(
            &TlsOptions {
                roots: TrustRoots::Pem(CA_PEM.to_vec()),
                client_identity: Some(ClientIdentity {
                    cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
                    key_pem: key_pem.to_vec(),
                    key_passphrase: passphrase.map(str::to_string),
                }),
            },
            true,
            true,
            true,
        ))
    }

    #[test]
    fn alpn_offers_h2_first_unless_disabled() {
        let options = TlsOptions {
            roots: TrustRoots::Pem(CA_PEM.to_vec()),
            client_identity: None,
        };
        let with_h2 = block_on(client_config(&options, true, true, true)).unwrap();
        assert_eq!(
            with_h2.without_identity.alpn_protocols,
            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
        );
        let without = block_on(client_config(&options, false, true, true)).unwrap();
        assert_eq!(
            without.without_identity.alpn_protocols,
            vec![b"http/1.1".to_vec()]
        );
    }

    /// A configuration built from its own anchors reports that it holds them,
    /// for each scheme of the mirrors.
    #[test]
    fn pem_anchors_are_reported_as_held() {
        let options = TlsOptions {
            roots: TrustRoots::Pem(CA_PEM.to_vec()),
            client_identity: None,
        };
        for (https, reaches_tls) in [(true, true), (false, true), (false, false)] {
            let configs = block_on(client_config(&options, true, https, reaches_tls)).unwrap();
            assert!(configs.has_trust_anchors, "https={https} {reaches_tls}");
        }
    }

    /// A configured client certificate makes two separate configurations
    /// with the same ALPN offer. With no certificate, the two are one `Arc`.
    #[test]
    fn a_client_identity_is_accepted() {
        let options = TlsOptions {
            roots: TrustRoots::Pem(CA_PEM.to_vec()),
            client_identity: Some(ClientIdentity {
                cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
                key_pem: CLIENT_KEY_PEM.to_vec(),
                key_passphrase: None,
            }),
        };
        let configs = block_on(client_config(&options, true, true, true)).unwrap();
        assert!(!Arc::ptr_eq(
            &configs.with_identity,
            &configs.without_identity
        ));
        assert_eq!(
            configs.with_identity.alpn_protocols,
            configs.without_identity.alpn_protocols
        );

        let options = TlsOptions {
            roots: TrustRoots::Pem(CA_PEM.to_vec()),
            client_identity: None,
        };
        let configs = block_on(client_config(&options, true, true, true)).unwrap();
        assert!(Arc::ptr_eq(
            &configs.with_identity,
            &configs.without_identity
        ));
    }

    /// A bypass variant builds with no anchors and reports that a handshake
    /// can proceed. With no client identity, the two configurations are one
    /// `Arc`. `tests/fetch_no_trust_store.rs` checks that the host store is
    /// not read. It runs the constructor in a child process with an empty
    /// store.
    #[test]
    fn a_bypass_needs_no_trust_store() {
        for roots in [
            TrustRoots::DangerousAcceptAnyChain,
            TrustRoots::DangerousAcceptAny,
        ] {
            let options = TlsOptions {
                roots: roots.clone(),
                client_identity: None,
            };
            for (https, reaches_tls) in [(true, true), (false, true), (false, false)] {
                let configs = block_on(client_config(&options, true, https, reaches_tls)).unwrap();
                assert!(configs.has_trust_anchors, "{roots:?} https={https}");
                assert!(Arc::ptr_eq(
                    &configs.with_identity,
                    &configs.without_identity
                ));
            }
        }
    }

    /// A client identity with a bypass builds two configurations. Both verify
    /// with the one bypass verifier.
    #[test]
    fn a_bypass_carries_a_client_identity() {
        for roots in [
            TrustRoots::DangerousAcceptAnyChain,
            TrustRoots::DangerousAcceptAny,
        ] {
            let options = TlsOptions {
                roots,
                client_identity: Some(ClientIdentity {
                    cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
                    key_pem: CLIENT_KEY_PEM.to_vec(),
                    key_passphrase: None,
                }),
            };
            let configs = block_on(client_config(&options, true, true, true)).unwrap();
            assert!(!Arc::ptr_eq(
                &configs.with_identity,
                &configs.without_identity
            ));
            assert!(configs.has_trust_anchors);
        }
    }

    #[test]
    fn empty_trust_anchors_and_bad_keys_are_rejected() {
        let no_roots = TlsOptions {
            roots: TrustRoots::Pem(b"not a certificate\n".to_vec()),
            client_identity: None,
        };
        let err = block_on(client_config(&no_roots, true, true, true)).unwrap_err();
        assert!(err.to_string().contains("no certificate"), "{err}");

        // A well-formed PEM blob that holds a certificate and no key.
        let no_key = TlsOptions {
            roots: TrustRoots::Pem(CA_PEM.to_vec()),
            client_identity: Some(ClientIdentity {
                cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
                key_pem: CA_PEM.to_vec(),
                key_passphrase: None,
            }),
        };
        let err = block_on(client_config(&no_key, true, true, true)).unwrap_err();
        assert!(err.to_string().contains("no key"), "{err}");

        let unparsable_key = TlsOptions {
            roots: TrustRoots::Pem(CA_PEM.to_vec()),
            client_identity: Some(ClientIdentity {
                cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
                key_pem: b"-----BEGIN PRIVATE KEY-----\n".to_vec(),
                key_passphrase: None,
            }),
        };
        let err = block_on(client_config(&unparsable_key, true, true, true)).unwrap_err();
        assert!(err.to_string().contains("private key pem"), "{err}");
    }

    /// An encrypted PKCS#8 key with its passphrase builds the two
    /// configurations, the same as the key that carries no encryption.
    #[test]
    fn an_encrypted_client_key_is_decrypted() {
        let configs = configs_for_key(CLIENT_KEY_ENC_PEM, Some(KEY_PASSPHRASE)).unwrap();
        assert!(!Arc::ptr_eq(
            &configs.with_identity,
            &configs.without_identity
        ));
    }

    /// Each refusal of the encrypted-key path names its own case:
    ///
    /// - a wrong passphrase
    /// - an encrypted key with no passphrase
    /// - a passphrase on a key that carries no encryption
    /// - the legacy OpenSSL format
    #[test]
    fn the_encrypted_key_refusals_name_their_case() {
        let err = configs_for_key(CLIENT_KEY_ENC_PEM, Some("not the passphrase")).unwrap_err();
        assert_eq!(
            err.to_string(),
            "fetch: the passphrase does not decrypt the private key"
        );

        let err = configs_for_key(CLIENT_KEY_ENC_PEM, None).unwrap_err();
        assert_eq!(
            err.to_string(),
            "fetch: private key pem is encrypted, and no passphrase is set"
        );

        let err = configs_for_key(CLIENT_KEY_PEM, Some(KEY_PASSPHRASE)).unwrap_err();
        assert_eq!(
            err.to_string(),
            "fetch: a passphrase is set for a private key pem that carries no \
             encryption"
        );

        // The legacy form is refused with or without a passphrase. The message
        // names the conversion that gives a readable key.
        for passphrase in [Some(KEY_PASSPHRASE), None] {
            let err = configs_for_key(CLIENT_KEY_LEGACY_PEM, passphrase).unwrap_err();
            assert_eq!(
                err.to_string(),
                "fetch: private key pem is in the legacy openssl encrypted \
                 format. convert the key to pkcs#8 with `openssl pkcs8 -topk8`"
            );
        }
    }

    /// The formatted identity carries neither the private key nor the
    /// passphrase, so a logged fetcher configuration carries neither. The key
    /// is stated by its length. The certificate chain is public material and
    /// is formatted in full.
    #[test]
    fn debug_redacts_the_key_and_the_passphrase() {
        // A `Debug` leak costs most for a key that carries no encryption. A
        // pull configures that case.
        let identity = ClientIdentity {
            cert_chain_pem: CLIENT_CERT_PEM.to_vec(),
            key_pem: CLIENT_KEY_PEM.to_vec(),
            key_passphrase: Some(KEY_PASSPHRASE.to_string()),
        };
        let text = format!("{identity:?}");
        assert!(!text.contains(KEY_PASSPHRASE), "{text}");
        assert!(
            text.contains("key_passphrase: Some(\"<redacted>\")"),
            "{text}"
        );
        for line in std::str::from_utf8(CLIENT_KEY_PEM)
            .unwrap()
            .lines()
            .filter(|line| !line.starts_with("-----"))
        {
            assert!(!text.contains(line), "{line} in {text}");
        }
        assert!(
            text.contains(&format!("<{} bytes redacted>", CLIENT_KEY_PEM.len())),
            "{text}"
        );
        assert!(text.contains("cert_chain_pem: ["), "{text}");

        let without = ClientIdentity {
            key_passphrase: None,
            ..identity
        };
        let text = format!("{without:?}");
        assert!(text.contains("key_passphrase: None"), "{text}");
        assert!(!text.contains(KEY_PASSPHRASE), "{text}");
    }

    /// The encrypted section is read whatever is around it: a trailing blank
    /// line, or the certificate that the usual bundle carries in front of the
    /// key. The decoder sees that one section, cut out of the blob.
    #[test]
    fn an_encrypted_key_is_read_out_of_a_longer_blob() {
        let blobs = [
            [CLIENT_KEY_ENC_PEM, b"\n"].concat(),
            [CLIENT_CERT_PEM, CLIENT_KEY_ENC_PEM].concat(),
            [CLIENT_KEY_ENC_PEM, CLIENT_CERT_PEM].concat(),
        ];
        for blob in blobs {
            let configs = configs_for_key(&blob, Some(KEY_PASSPHRASE)).unwrap();
            assert!(!Arc::ptr_eq(
                &configs.with_identity,
                &configs.without_identity
            ));
        }
    }

    /// The first section whose label names a private key selects the path. So
    /// a blob with an encrypted key and a plain key is read as the first one.
    #[test]
    fn the_first_key_section_decides_the_path() {
        // Encrypted first: the passphrase decrypts it. With no passphrase, the
        // key is refused, and the plain key behind it is not read.
        let encrypted_first = [CLIENT_KEY_ENC_PEM, CLIENT_KEY_PEM].concat();
        configs_for_key(&encrypted_first, Some(KEY_PASSPHRASE)).unwrap();
        let err = configs_for_key(&encrypted_first, None).unwrap_err();
        assert_eq!(
            err.to_string(),
            "fetch: private key pem is encrypted, and no passphrase is set"
        );

        // Plain first: it is read as it is. A passphrase is refused, although
        // an encrypted section is behind it.
        let plain_first = [CLIENT_KEY_PEM, CLIENT_KEY_ENC_PEM].concat();
        configs_for_key(&plain_first, None).unwrap();
        let err = configs_for_key(&plain_first, Some(KEY_PASSPHRASE)).unwrap_err();
        assert_eq!(
            err.to_string(),
            "fetch: a passphrase is set for a private key pem that carries no \
             encryption"
        );
    }

    /// The legacy header is read inside the section that carries it. A plain
    /// key in front of a legacy key is read. The same text in the free space
    /// around a plain key reads as free text.
    #[test]
    fn the_legacy_header_is_read_inside_its_own_section() {
        let plain_first = [CLIENT_KEY_PEM, CLIENT_KEY_LEGACY_PEM].concat();
        configs_for_key(&plain_first, None).unwrap();

        let with_note = [
            b"Proc-Type: 4,ENCRYPTED\n".as_slice(),
            b"# Proc-Type: 4,ENCRYPTED\n".as_slice(),
            CLIENT_KEY_PEM,
        ]
        .concat();
        configs_for_key(&with_note, None).unwrap();
    }

    /// RFC 1421 makes the space after the colon optional. The header is
    /// found with or without the space.
    #[test]
    fn the_legacy_header_is_named_without_the_space() {
        let text = std::str::from_utf8(CLIENT_KEY_LEGACY_PEM)
            .unwrap()
            .replace("Proc-Type: 4,ENCRYPTED", "Proc-Type:4,ENCRYPTED");
        let err = configs_for_key(text.as_bytes(), Some(KEY_PASSPHRASE)).unwrap_err();
        assert_eq!(
            err.to_string(),
            "fetch: private key pem is in the legacy openssl encrypted \
             format. convert the key to pkcs#8 with `openssl pkcs8 -topk8`"
        );
    }

    /// A key under PKCS#5 PBES1 is refused, and the message names PBES1.
    #[test]
    fn a_pbes1_key_is_refused_by_name() {
        let err = configs_for_key(CLIENT_KEY_PBES1_PEM, Some(KEY_PASSPHRASE)).unwrap_err();
        assert_eq!(
            err.to_string(),
            "fetch: private key pem is encrypted under pkcs#5 pbes1, \
             which this build does not decrypt"
        );
    }

    const SERVER_CERT_PEM: &[u8] = include_bytes!("../../../tests/fixtures/tls/server.pem");
    const SERVER_KEY_PEM: &[u8] = include_bytes!("../../../tests/fixtures/tls/server.key.pem");

    /// A server configuration offers `h2` then `http/1.1`, with and without a
    /// client CA.
    #[test]
    fn a_server_config_offers_h2_and_http1() {
        for ca in [None, Some(CA_PEM)] {
            let config =
                block_on(server_config(SERVER_CERT_PEM, SERVER_KEY_PEM, None, ca)).unwrap();
            assert_eq!(
                config.alpn_protocols,
                [b"h2".to_vec(), b"http/1.1".to_vec()]
            );
        }
    }

    /// The key loaders of the client identity read the server key. So an
    /// encrypted key is decrypted with its passphrase and refused without
    /// one.
    #[test]
    fn a_server_config_reads_an_encrypted_key() {
        block_on(server_config(
            CLIENT_CERT_PEM,
            CLIENT_KEY_ENC_PEM,
            Some(KEY_PASSPHRASE),
            None,
        ))
        .unwrap();
        let err = block_on(server_config(
            CLIENT_CERT_PEM,
            CLIENT_KEY_ENC_PEM,
            None,
            None,
        ))
        .unwrap_err();
        assert!(err.to_string().contains("passphrase"), "{err}");
    }

    /// An empty chain, a key of another certificate, and a CA blob with no
    /// certificate are each refused.
    #[test]
    fn a_server_config_refuses_bad_material() {
        let refused = |cert: &[u8], key: &[u8], ca: Option<&[u8]>| {
            block_on(server_config(cert, key, None, ca))
                .unwrap_err()
                .to_string()
        };
        assert!(refused(b"", SERVER_KEY_PEM, None).contains("no certificate"));
        assert!(refused(SERVER_CERT_PEM, CLIENT_KEY_PEM, None).contains("rejected"));
        assert!(refused(SERVER_CERT_PEM, SERVER_KEY_PEM, Some(b"")).contains("no certificate"));
    }
}