asupersync 0.3.0

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! TLS certificate and key types.
//!
//! These types wrap rustls types to provide a more ergonomic API
//! and decouple the public interface from rustls internals.

#[cfg(feature = "tls")]
use rustls_pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, PrivateSec1KeyDer};

use std::collections::BTreeSet;
use std::io::BufReader;
use std::path::Path;
use std::sync::Arc;

use super::error::TlsError;

/// A DER-encoded X.509 certificate.
#[derive(Clone, Debug)]
pub struct Certificate {
    #[cfg(feature = "tls")]
    inner: CertificateDer<'static>,
    #[cfg(not(feature = "tls"))]
    _data: Vec<u8>,
}

impl Certificate {
    /// Create a certificate from DER-encoded bytes.
    #[inline]
    #[cfg(feature = "tls")]
    pub fn from_der(der: impl Into<Vec<u8>>) -> Self {
        Self {
            inner: CertificateDer::from(der.into()),
        }
    }

    /// Create a certificate from DER-encoded bytes (fallback when TLS is disabled).
    #[inline]
    #[cfg(not(feature = "tls"))]
    pub fn from_der(der: impl Into<Vec<u8>>) -> Self {
        Self { _data: der.into() }
    }

    /// Parse certificates from PEM-encoded data.
    ///
    /// Returns all certificates found in the PEM data.
    #[cfg(feature = "tls")]
    pub fn from_pem(pem: &[u8]) -> Result<Vec<Self>, TlsError> {
        let mut reader = BufReader::new(pem);
        let certs: Vec<_> = rustls_pemfile::certs(&mut reader)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| TlsError::Certificate(e.to_string()))?;

        if certs.is_empty() {
            return Err(TlsError::Certificate("no certificates found in PEM".into()));
        }

        Ok(certs.into_iter().map(|c| Self { inner: c }).collect())
    }

    /// Parse certificates from PEM-encoded data (fallback when TLS is disabled).
    #[cfg(not(feature = "tls"))]
    pub fn from_pem(_pem: &[u8]) -> Result<Vec<Self>, TlsError> {
        Err(TlsError::Configuration("tls feature not enabled".into()))
    }

    /// Load certificates from a PEM file.
    pub fn from_pem_file(path: impl AsRef<Path>) -> Result<Vec<Self>, TlsError> {
        let pem = std::fs::read(path.as_ref())
            .map_err(|e| TlsError::Certificate(format!("reading file: {e}")))?;
        Self::from_pem(&pem)
    }

    /// Get the raw DER bytes.
    #[inline]
    #[cfg(feature = "tls")]
    pub fn as_der(&self) -> &[u8] {
        self.inner.as_ref()
    }

    /// Get the raw DER bytes (fallback when TLS is disabled).
    #[inline]
    #[cfg(not(feature = "tls"))]
    pub fn as_der(&self) -> &[u8] {
        &self._data
    }

    /// Get the inner rustls certificate.
    #[inline]
    #[cfg(feature = "tls")]
    pub(crate) fn into_inner(self) -> CertificateDer<'static> {
        self.inner
    }
}

/// A chain of X.509 certificates (leaf first, then intermediates).
#[derive(Clone, Debug, Default)]
pub struct CertificateChain {
    certs: Vec<Certificate>,
}

impl CertificateChain {
    /// Create an empty certificate chain.
    #[inline]
    pub fn new() -> Self {
        Self { certs: Vec::new() }
    }

    /// Create a certificate chain from a single certificate.
    pub fn from_cert(cert: Certificate) -> Self {
        Self { certs: vec![cert] }
    }

    /// Add a certificate to the chain.
    pub fn push(&mut self, cert: Certificate) {
        self.certs.push(cert);
    }

    /// Get the number of certificates in the chain.
    pub fn len(&self) -> usize {
        self.certs.len()
    }

    /// Check if the chain is empty.
    pub fn is_empty(&self) -> bool {
        self.certs.is_empty()
    }

    /// Load certificate chain from a PEM file.
    pub fn from_pem_file(path: impl AsRef<Path>) -> Result<Self, TlsError> {
        let certs = Certificate::from_pem_file(path)?;
        Ok(Self::from(certs))
    }

    /// Parse certificate chain from PEM-encoded data.
    pub fn from_pem(pem: &[u8]) -> Result<Self, TlsError> {
        let certs = Certificate::from_pem(pem)?;
        Ok(Self::from(certs))
    }

    /// Convert to rustls certificate chain.
    #[cfg(feature = "tls")]
    pub(crate) fn into_inner(self) -> Vec<CertificateDer<'static>> {
        self.certs
            .into_iter()
            .map(Certificate::into_inner)
            .collect()
    }
}

impl From<Vec<Certificate>> for CertificateChain {
    fn from(certs: Vec<Certificate>) -> Self {
        Self { certs }
    }
}

impl IntoIterator for CertificateChain {
    type Item = Certificate;
    type IntoIter = std::vec::IntoIter<Certificate>;

    fn into_iter(self) -> Self::IntoIter {
        self.certs.into_iter()
    }
}

/// A private key for TLS authentication.
#[derive(Clone)]
pub struct PrivateKey {
    #[cfg(feature = "tls")]
    inner: Arc<PrivateKeyDer<'static>>,
    #[cfg(not(feature = "tls"))]
    _data: Vec<u8>,
}

impl PrivateKey {
    /// Create a private key from PKCS#8 DER-encoded bytes.
    #[cfg(feature = "tls")]
    pub fn from_pkcs8_der(der: impl Into<Vec<u8>>) -> Self {
        Self {
            inner: Arc::new(PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(der.into()))),
        }
    }

    /// Create a private key from PKCS#8 DER-encoded bytes (fallback when TLS is disabled).
    #[cfg(not(feature = "tls"))]
    pub fn from_pkcs8_der(der: impl Into<Vec<u8>>) -> Self {
        Self { _data: der.into() }
    }

    /// Parse a private key from PEM-encoded data.
    ///
    /// Supports PKCS#8, PKCS#1 (RSA), and SEC1 (EC) formats.
    #[cfg(feature = "tls")]
    pub fn from_pem(pem: &[u8]) -> Result<Self, TlsError> {
        let mut reader = BufReader::new(pem);

        // Try PKCS#8 first
        let pkcs8_keys: Vec<_> = rustls_pemfile::pkcs8_private_keys(&mut reader)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| TlsError::Certificate(e.to_string()))?;

        if let Some(key) = pkcs8_keys.into_iter().next() {
            return Ok(Self {
                inner: Arc::new(PrivateKeyDer::Pkcs8(key)),
            });
        }

        // Try RSA (PKCS#1)
        let mut reader = BufReader::new(pem);
        let rsa_keys: Vec<_> = rustls_pemfile::rsa_private_keys(&mut reader)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| TlsError::Certificate(e.to_string()))?;

        if let Some(key) = rsa_keys.into_iter().next() {
            return Ok(Self {
                inner: Arc::new(PrivateKeyDer::Pkcs1(key)),
            });
        }

        // Try EC (SEC1)
        let mut reader = BufReader::new(pem);
        let ec_keys: Vec<_> = rustls_pemfile::ec_private_keys(&mut reader)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| TlsError::Certificate(e.to_string()))?;

        if let Some(key) = ec_keys.into_iter().next() {
            return Ok(Self {
                inner: Arc::new(PrivateKeyDer::Sec1(key)),
            });
        }

        Err(TlsError::Certificate("no private key found in PEM".into()))
    }

    /// Parse a private key from PEM-encoded data (fallback when TLS is disabled).
    #[cfg(not(feature = "tls"))]
    pub fn from_pem(_pem: &[u8]) -> Result<Self, TlsError> {
        Err(TlsError::Configuration("tls feature not enabled".into()))
    }

    /// Load a private key from a PEM file.
    pub fn from_pem_file(path: impl AsRef<Path>) -> Result<Self, TlsError> {
        let pem = std::fs::read(path.as_ref())
            .map_err(|e| TlsError::Certificate(format!("reading file: {e}")))?;
        Self::from_pem(&pem)
    }

    /// Create a private key from SEC1 (EC) DER-encoded bytes.
    #[cfg(feature = "tls")]
    pub fn from_sec1_der(der: impl Into<Vec<u8>>) -> Self {
        Self {
            inner: Arc::new(PrivateKeyDer::Sec1(PrivateSec1KeyDer::from(der.into()))),
        }
    }

    /// Create a private key from SEC1 (EC) DER-encoded bytes (fallback when TLS is disabled).
    #[cfg(not(feature = "tls"))]
    pub fn from_sec1_der(der: impl Into<Vec<u8>>) -> Self {
        Self { _data: der.into() }
    }

    /// Get the inner rustls private key.
    #[cfg(feature = "tls")]
    pub(crate) fn clone_inner(&self) -> PrivateKeyDer<'static> {
        (*self.inner).clone_key()
    }
}

impl std::fmt::Debug for PrivateKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PrivateKey")
            .field("type", &"[redacted]")
            .finish()
    }
}

/// A store of trusted root certificates.
#[derive(Clone, Debug)]
pub struct RootCertStore {
    #[cfg(feature = "tls")]
    inner: rustls::RootCertStore,
    #[cfg(not(feature = "tls"))]
    certs: Vec<Certificate>,
}

impl Default for RootCertStore {
    fn default() -> Self {
        Self::empty()
    }
}

impl RootCertStore {
    /// Create an empty root certificate store.
    #[cfg(feature = "tls")]
    pub fn empty() -> Self {
        Self {
            inner: rustls::RootCertStore::empty(),
        }
    }

    /// Create an empty root certificate store (fallback when TLS is disabled).
    #[cfg(not(feature = "tls"))]
    pub fn empty() -> Self {
        Self { certs: Vec::new() }
    }

    /// Add a certificate to the store.
    #[cfg(feature = "tls")]
    pub fn add(&mut self, cert: &Certificate) -> Result<(), crate::tls::TlsError> {
        self.inner
            .add(cert.clone().into_inner())
            .map_err(|e| crate::tls::TlsError::Certificate(e.to_string()))
    }

    /// Add a certificate to the store (fallback when TLS is disabled).
    #[cfg(not(feature = "tls"))]
    pub fn add(&mut self, cert: &Certificate) -> Result<(), crate::tls::TlsError> {
        self.certs.push(cert.clone());
        Ok(())
    }

    /// Get the number of certificates in the store.
    #[cfg(feature = "tls")]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Get the number of certificates in the store (fallback when TLS is disabled).
    #[cfg(not(feature = "tls"))]
    pub fn len(&self) -> usize {
        self.certs.len()
    }

    /// Check if the store is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Add certificates from a PEM file.
    ///
    /// Returns the number of certificates successfully added.
    pub fn add_pem_file(&mut self, path: impl AsRef<Path>) -> Result<usize, TlsError> {
        let certs = Certificate::from_pem_file(path)?;
        let mut count = 0;
        for cert in &certs {
            if self.add(cert).is_ok() {
                count += 1;
            }
        }
        Ok(count)
    }

    /// Extend with webpki root certificates.
    ///
    /// Requires the `tls-webpki-roots` feature.
    #[cfg(feature = "tls-webpki-roots")]
    pub fn extend_from_webpki_roots(&mut self) {
        self.inner
            .extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
    }

    /// Extend with webpki root certificates (fallback when feature is disabled).
    #[cfg(not(feature = "tls-webpki-roots"))]
    pub fn extend_from_webpki_roots(&mut self) {
        // No-op when feature is disabled
    }

    /// Extend with native/platform root certificates.
    ///
    /// On Linux, this typically reads from /etc/ssl/certs.
    /// On macOS, this uses the system keychain.
    /// On Windows, this uses the Windows certificate store.
    ///
    /// Requires the `tls-native-roots` feature.
    #[cfg(feature = "tls-native-roots")]
    pub fn extend_from_native_roots(&mut self) -> Result<usize, TlsError> {
        let result = rustls_native_certs::load_native_certs();
        let mut count = 0;
        for cert in result.certs {
            if self
                .inner
                .add(rustls_pki_types::CertificateDer::from(cert.to_vec()))
                .is_ok()
            {
                count += 1;
            }
        }
        Ok(count)
    }

    /// Extend with native/platform root certificates (fallback when feature is disabled).
    #[cfg(not(feature = "tls-native-roots"))]
    pub fn extend_from_native_roots(&mut self) -> Result<usize, TlsError> {
        Err(TlsError::Configuration(
            "tls-native-roots feature not enabled".into(),
        ))
    }

    /// Convert to rustls root cert store.
    #[cfg(feature = "tls")]
    pub(crate) fn into_inner(self) -> rustls::RootCertStore {
        self.inner
    }
}

/// A certificate pin for certificate pinning.
///
/// Certificate pinning adds an additional layer of security by verifying
/// that the server's certificate matches a known value.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum CertificatePin {
    /// Pin by SPKI (Subject Public Key Info) SHA-256 hash.
    ///
    /// This is the recommended pinning method as it survives certificate
    /// renewal as long as the same key pair is used.
    SpkiSha256(Vec<u8>),

    /// Pin by certificate SHA-256 hash.
    ///
    /// This pins the entire certificate, so you need to update pins
    /// when certificates are renewed.
    CertSha256(Vec<u8>),
}

impl CertificatePin {
    /// Create a SPKI SHA-256 pin from a base64-encoded hash.
    pub fn spki_sha256_base64(base64_hash: &str) -> Result<Self, TlsError> {
        use base64::Engine;
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(base64_hash)
            .map_err(|e| TlsError::Certificate(format!("invalid base64: {e}")))?;
        if bytes.len() != 32 {
            return Err(TlsError::Certificate(format!(
                "SPKI SHA-256 hash must be 32 bytes, got {}",
                bytes.len()
            )));
        }
        Ok(Self::SpkiSha256(bytes))
    }

    /// Create a certificate SHA-256 pin from a base64-encoded hash.
    pub fn cert_sha256_base64(base64_hash: &str) -> Result<Self, TlsError> {
        use base64::Engine;
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(base64_hash)
            .map_err(|e| TlsError::Certificate(format!("invalid base64: {e}")))?;
        if bytes.len() != 32 {
            return Err(TlsError::Certificate(format!(
                "certificate SHA-256 hash must be 32 bytes, got {}",
                bytes.len()
            )));
        }
        Ok(Self::CertSha256(bytes))
    }

    /// Create a SPKI SHA-256 pin from raw bytes.
    pub fn spki_sha256(hash: impl Into<Vec<u8>>) -> Result<Self, TlsError> {
        let bytes = hash.into();
        if bytes.len() != 32 {
            return Err(TlsError::Certificate(format!(
                "SPKI SHA-256 hash must be 32 bytes, got {}",
                bytes.len()
            )));
        }
        Ok(Self::SpkiSha256(bytes))
    }

    /// Create a certificate SHA-256 pin from raw bytes.
    pub fn cert_sha256(hash: impl Into<Vec<u8>>) -> Result<Self, TlsError> {
        let bytes = hash.into();
        if bytes.len() != 32 {
            return Err(TlsError::Certificate(format!(
                "certificate SHA-256 hash must be 32 bytes, got {}",
                bytes.len()
            )));
        }
        Ok(Self::CertSha256(bytes))
    }

    /// Compute the SPKI SHA-256 pin for a certificate.
    ///
    /// This hashes the DER-encoded `SubjectPublicKeyInfo` structure from the
    /// certificate, which is the pinning form that survives certificate
    /// renewal as long as the key pair stays the same.
    #[cfg(feature = "tls")]
    pub fn compute_spki_sha256(cert: &Certificate) -> Result<Self, TlsError> {
        use ring::digest::{SHA256, digest};

        let (_, parsed) = x509_parser::parse_x509_certificate(cert.as_der())
            .map_err(|e| TlsError::Certificate(format!("failed to parse certificate DER: {e}")))?;
        let hash = digest(&SHA256, parsed.public_key().raw);
        Ok(Self::SpkiSha256(hash.as_ref().to_vec()))
    }

    /// Compute the SPKI SHA-256 pin for a certificate (fallback when TLS is disabled).
    #[cfg(not(feature = "tls"))]
    pub fn compute_spki_sha256(_cert: &Certificate) -> Result<Self, TlsError> {
        Err(TlsError::Configuration("tls feature not enabled".into()))
    }

    /// Compute the certificate SHA-256 pin for a certificate.
    #[cfg(feature = "tls")]
    pub fn compute_cert_sha256(cert: &Certificate) -> Result<Self, TlsError> {
        use ring::digest::{SHA256, digest};
        let hash = digest(&SHA256, cert.as_der());
        Ok(Self::CertSha256(hash.as_ref().to_vec()))
    }

    /// Compute the certificate SHA-256 pin for a certificate (fallback when TLS is disabled).
    #[cfg(not(feature = "tls"))]
    pub fn compute_cert_sha256(_cert: &Certificate) -> Result<Self, TlsError> {
        Err(TlsError::Configuration("tls feature not enabled".into()))
    }

    /// Get the pin as a base64-encoded string.
    pub fn to_base64(&self) -> String {
        use base64::Engine;
        match self {
            Self::SpkiSha256(bytes) | Self::CertSha256(bytes) => {
                base64::engine::general_purpose::STANDARD.encode(bytes)
            }
        }
    }

    /// Get the hash bytes.
    pub fn hash_bytes(&self) -> &[u8] {
        match self {
            Self::SpkiSha256(bytes) | Self::CertSha256(bytes) => bytes,
        }
    }
}

/// A set of certificate pins for pinning validation.
///
/// The set supports multiple pins to allow for key rotation without downtime.
#[derive(Clone, Debug)]
pub struct CertificatePinSet {
    pins: BTreeSet<CertificatePin>,
    /// Whether to enforce pinning (fail if no pins match) or just warn.
    enforce: bool,
}

impl Default for CertificatePinSet {
    /// Default pin set is empty with enforcement enabled (secure-by-default).
    fn default() -> Self {
        Self::new()
    }
}

impl CertificatePinSet {
    /// Create a new empty pin set.
    pub fn new() -> Self {
        Self {
            pins: BTreeSet::new(),
            enforce: true,
        }
    }

    /// Create a pin set with enforcement disabled (report-only mode).
    pub fn report_only() -> Self {
        Self {
            pins: BTreeSet::new(),
            enforce: false,
        }
    }

    /// Add a pin to the set.
    pub fn add(&mut self, pin: CertificatePin) {
        self.pins.insert(pin);
    }

    /// Add a pin to the set (builder pattern).
    pub fn with_pin(mut self, pin: CertificatePin) -> Self {
        self.add(pin);
        self
    }

    /// Add a SPKI SHA-256 pin from base64.
    pub fn add_spki_sha256_base64(&mut self, base64_hash: &str) -> Result<(), TlsError> {
        self.add(CertificatePin::spki_sha256_base64(base64_hash)?);
        Ok(())
    }

    /// Add a certificate SHA-256 pin from base64.
    pub fn add_cert_sha256_base64(&mut self, base64_hash: &str) -> Result<(), TlsError> {
        self.add(CertificatePin::cert_sha256_base64(base64_hash)?);
        Ok(())
    }

    /// Check if the set is empty.
    pub fn is_empty(&self) -> bool {
        self.pins.is_empty()
    }

    /// Get the number of pins.
    pub fn len(&self) -> usize {
        self.pins.len()
    }

    /// Check if enforcement is enabled.
    pub fn is_enforcing(&self) -> bool {
        self.enforce
    }

    /// Set whether to enforce pinning.
    pub fn set_enforce(&mut self, enforce: bool) {
        self.enforce = enforce;
    }

    /// Validate a certificate against the pin set.
    ///
    /// Returns Ok(true) if a pin matches, Ok(false) if no pins match but
    /// enforcement is disabled, or Err if no pins match and enforcement is enabled.
    #[cfg(feature = "tls")]
    pub fn validate(&self, cert: &Certificate) -> Result<bool, TlsError> {
        if self.pins.is_empty() {
            return Ok(true);
        }

        // Compute pin types on demand so malformed certificate material only
        // affects the pin types the set actually needs.
        let spki_pin = CertificatePin::compute_spki_sha256(cert).ok();
        let cert_pin = CertificatePin::compute_cert_sha256(cert).ok();

        // Check if any pin matches
        if spki_pin.as_ref().is_some_and(|p| self.pins.contains(p))
            || cert_pin.as_ref().is_some_and(|p| self.pins.contains(p))
        {
            return Ok(true);
        }

        // No match
        if self.enforce {
            let expected: Vec<String> = self.pins.iter().map(CertificatePin::to_base64).collect();
            let actual = spki_pin
                .as_ref()
                .or(cert_pin.as_ref())
                .map_or_else(|| "<unavailable>".to_string(), CertificatePin::to_base64);
            Err(TlsError::PinMismatch { expected, actual })
        } else {
            #[cfg(feature = "tracing-integration")]
            tracing::warn!(
                expected = ?self.pins.iter().map(CertificatePin::to_base64).collect::<Vec<_>>(),
                actual_spki = %spki_pin.as_ref().map_or_else(|| "<unavailable>".to_string(), CertificatePin::to_base64),
                actual_cert = %cert_pin.as_ref().map_or_else(|| "<unavailable>".to_string(), CertificatePin::to_base64),
                "Certificate pin mismatch (report-only mode)"
            );
            Ok(false)
        }
    }

    /// Validate a certificate against the pin set (fallback when TLS is disabled).
    #[cfg(not(feature = "tls"))]
    pub fn validate(&self, _cert: &Certificate) -> Result<bool, TlsError> {
        Err(TlsError::Configuration("tls feature not enabled".into()))
    }

    /// Get an iterator over the pins.
    pub fn iter(&self) -> impl Iterator<Item = &CertificatePin> {
        self.pins.iter()
    }
}

impl FromIterator<CertificatePin> for CertificatePinSet {
    fn from_iter<I: IntoIterator<Item = CertificatePin>>(iter: I) -> Self {
        Self {
            pins: iter.into_iter().collect(),
            enforce: true,
        }
    }
}

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

    #[cfg(feature = "tls")]
    const TEST_CERT_PEM: &[u8] = br"-----BEGIN CERTIFICATE-----
MIIDGjCCAgKgAwIBAgIUEOa/xZnL2Xclme2QSueCrHSMLnEwDQYJKoZIhvcNAQEL
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MDIyNjIyMjk1MloXDTM2MDIy
NDIyMjk1MlowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEAx1JqCHpDIHPR4H1LDrb3gHVCzoKujANyHdOKw7CTLKdz
JbDybwJYqZ8vZpq0xwhYKpHdGO4yv7yLT7a2kThq3MrxohfXp9tv1Dop7siTQiWT
7uGYJzh1bOhw7ElLJc8bW/mBf7ksMyqkX8/8mRXRWqqDv3dKe5CrSt2Pqti9tYH0
DcT2fftUGT14VvL/Fq1kWPM16ebTRCFp/4ki/Th7SzFvTN99L45MAilHZFefRSzc
9xN1qQZNm7lT6oo0zD3wmOy70iiasqpLrmG51TRdbnBnGH6CIHvUIl3rCDteUuj1
pB9lh67qt5kipCn4+8zceXmUaO/nmRawC7Vz+6AsTwIDAQABo2QwYjALBgNVHQ8E
BAMCBLAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwFAYDVR0RBA0wC4IJbG9jYWxob3N0
MAkGA1UdEwQCMAAwHQYDVR0OBBYEFEGZkeJqxBWpc24NHkE8k5PM8gTyMA0GCSqG
SIb3DQEBCwUAA4IBAQAzfQ4na2v1VhK/dyhC89rMHPN/8OX7CGWwrpWlEOYtpMds
OyQKTZjdz8aFSFl9rvnyGRHrdo4J1RoMGNR5wt1XQ7+k3l/iEWRlSRw+JU6+jqsx
xfjik55Dji36pN7ARGW4ADBpc3yTOHFhaH41GpSZ6s/2KdGG2gifo7UGNdkdgL60
nxRt1tfapaNtzpi90TfDx2w6MQmkNMKVOowbYX/zUY7kklJLP8KWTwXO7eovtIpr
FPAy+SbPl3+sqPbes5IqAQO9jhjb0w0/5RlSTPtiKetb6gAA7Yqw+yZWkBN0WDye
Lru15URJw9pE1Uae8IuzyzHiF1fnn45swnvW3Szb
-----END CERTIFICATE-----";
    #[cfg(feature = "tls")]
    const TEST_CERT_SPKI_SHA256_BASE64: &str = "Wic7R2QEWx8m0gjc0UYQD4iTxorg2Q51QmvN8HuCprc=";

    #[test]
    fn certificate_from_der() {
        // Minimal self-signed certificate DER (just test parsing doesn't panic)
        let cert = Certificate::from_der(vec![0x30, 0x00]);
        assert_eq!(cert.as_der().len(), 2);
    }

    #[test]
    fn certificate_chain_operations() {
        let chain = CertificateChain::new();
        assert!(chain.is_empty());
        assert_eq!(chain.len(), 0);

        let mut chain = CertificateChain::new();
        chain.push(Certificate::from_der(vec![1, 2, 3]));
        assert!(!chain.is_empty());
        assert_eq!(chain.len(), 1);
    }

    #[test]
    fn certificate_chain_from_cert() {
        let cert = Certificate::from_der(vec![1, 2, 3]);
        let chain = CertificateChain::from_cert(cert);
        assert_eq!(chain.len(), 1);
    }

    #[test]
    fn root_cert_store_empty() {
        let store = RootCertStore::empty();
        assert!(store.is_empty());
        assert_eq!(store.len(), 0);
    }

    #[test]
    fn certificate_pin_spki_base64_valid() {
        // Valid 32-byte SHA-256 hash in base64
        let hash = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
        let pin = CertificatePin::spki_sha256_base64(hash).unwrap();
        assert!(matches!(pin, CertificatePin::SpkiSha256(_)));
        assert_eq!(pin.hash_bytes().len(), 32);
        assert_eq!(pin.to_base64(), hash);
    }

    #[test]
    fn certificate_pin_cert_base64_valid() {
        // Valid 32-byte SHA-256 hash in base64
        let hash = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
        let pin = CertificatePin::cert_sha256_base64(hash).unwrap();
        assert!(matches!(pin, CertificatePin::CertSha256(_)));
        assert_eq!(pin.hash_bytes().len(), 32);
    }

    #[test]
    fn certificate_pin_invalid_base64() {
        let result = CertificatePin::spki_sha256_base64("not valid base64!!!");
        assert!(result.is_err());
    }

    #[test]
    fn certificate_pin_wrong_length() {
        // Valid base64 but wrong length (16 bytes instead of 32)
        let short_hash = "AAAAAAAAAAAAAAAAAAAAAA==";
        let result = CertificatePin::spki_sha256_base64(short_hash);
        assert!(result.is_err());
    }

    #[test]
    fn certificate_pin_from_raw_bytes_valid() {
        let bytes = vec![0u8; 32];
        let pin = CertificatePin::spki_sha256(bytes).unwrap();
        assert_eq!(pin.hash_bytes().len(), 32);
    }

    #[test]
    fn certificate_pin_from_raw_bytes_wrong_length() {
        let bytes = vec![0u8; 16];
        let result = CertificatePin::spki_sha256(bytes);
        assert!(result.is_err());
    }

    #[cfg(feature = "tls")]
    #[test]
    fn certificate_pin_compute_spki_sha256_known_answer() {
        let cert = Certificate::from_pem(TEST_CERT_PEM).unwrap().remove(0);
        let pin = CertificatePin::compute_spki_sha256(&cert).unwrap();
        assert_eq!(pin.to_base64(), TEST_CERT_SPKI_SHA256_BASE64);
    }

    #[cfg(feature = "tls")]
    #[test]
    fn certificate_pin_compute_spki_sha256_rejects_invalid_der() {
        let cert = Certificate::from_der(vec![0x30, 0x00]);
        let err = CertificatePin::compute_spki_sha256(&cert).unwrap_err();
        match err {
            TlsError::Certificate(message) => {
                assert!(message.contains("failed to parse certificate DER"));
            }
            other => panic!("expected certificate error, got {other:?}"),
        }
    }

    #[cfg(feature = "tls")]
    #[test]
    fn pin_set_validate_accepts_matching_spki_pin() {
        let cert = Certificate::from_pem(TEST_CERT_PEM).unwrap().remove(0);
        let pin = CertificatePin::compute_spki_sha256(&cert).unwrap();
        let mut set = CertificatePinSet::new();
        set.add(pin);
        assert!(set.validate(&cert).unwrap());
    }

    #[test]
    fn pin_set_operations() {
        let mut set = CertificatePinSet::new();
        assert!(set.is_empty());
        assert!(set.is_enforcing());

        let pin = CertificatePin::spki_sha256(vec![0u8; 32]).unwrap();
        set.add(pin);
        assert!(!set.is_empty());
        assert_eq!(set.len(), 1);
    }

    #[test]
    fn pin_set_report_only_mode() {
        let set = CertificatePinSet::report_only();
        assert!(!set.is_enforcing());
    }

    #[test]
    fn pin_set_builder_pattern() {
        let pin = CertificatePin::spki_sha256(vec![0u8; 32]).unwrap();
        let set = CertificatePinSet::new().with_pin(pin);
        assert_eq!(set.len(), 1);
    }

    #[test]
    fn pin_set_add_from_base64() {
        let mut set = CertificatePinSet::new();
        let hash = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
        set.add_spki_sha256_base64(hash).unwrap();
        set.add_cert_sha256_base64(hash).unwrap();
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn pin_set_from_iterator() {
        let set: CertificatePinSet = (0..3)
            .map(|i| CertificatePin::spki_sha256(vec![i; 32]).unwrap())
            .collect();
        assert_eq!(set.len(), 3);
    }

    #[test]
    fn pin_set_empty_validates_any() {
        let set = CertificatePinSet::new();
        // Empty set should allow any certificate
        #[cfg(feature = "tls")]
        {
            // We'd need a real cert to test, so just verify the method exists
            let _ = &set;
        }
        #[cfg(not(feature = "tls"))]
        {
            let _ = &set;
        }
    }

    #[test]
    fn pin_equality_and_hash() {
        let pin1 = CertificatePin::spki_sha256(vec![1u8; 32]).unwrap();
        let pin2 = CertificatePin::spki_sha256(vec![1u8; 32]).unwrap();
        let pin3 = CertificatePin::spki_sha256(vec![2u8; 32]).unwrap();

        assert_eq!(pin1, pin2);
        assert_ne!(pin1, pin3);

        // Test hash by adding to HashSet
        let mut set = std::collections::BTreeSet::new();
        set.insert(pin1);
        assert!(set.contains(&pin2));
        assert!(!set.contains(&pin3));
    }

    #[test]
    fn private_key_debug_is_redacted() {
        #[cfg(feature = "tls")]
        {
            // Just verify Debug impl exists and doesn't expose key material
            let key = PrivateKey::from_pkcs8_der(vec![0u8; 32]);
            let debug_str = format!("{key:?}");
            assert!(debug_str.contains("redacted"));
            assert!(!debug_str.contains('0'));
        }
    }

    #[test]
    fn error_variants_display() {
        use super::super::error::TlsError;

        let expired = TlsError::CertificateExpired {
            expired_at: 1_000_000,
            description: "test cert".to_string(),
        };
        let display = format!("{expired}");
        assert!(display.contains("expired"));
        assert!(display.contains("1000000"));

        let not_yet = TlsError::CertificateNotYetValid {
            valid_from: 2_000_000,
            description: "test cert".to_string(),
        };
        let display = format!("{not_yet}");
        assert!(display.contains("not valid"));
        assert!(display.contains("2000000"));

        let chain = TlsError::ChainValidation("chain error".to_string());
        let display = format!("{chain}");
        assert!(display.contains("chain"));

        let pin_mismatch = TlsError::PinMismatch {
            expected: vec!["pin1".to_string(), "pin2".to_string()],
            actual: "actual_pin".to_string(),
        };
        let display = format!("{pin_mismatch}");
        assert!(display.contains("mismatch"));
        assert!(display.contains("actual_pin"));
    }
}