Skip to main content

webpki/crl/
types.rs

1#[cfg(feature = "alloc")]
2use alloc::collections::BTreeMap;
3#[cfg(feature = "alloc")]
4use alloc::vec::Vec;
5use core::fmt::Debug;
6
7use pki_types::{SignatureVerificationAlgorithm, UnixTime};
8
9use crate::cert::lenient_certificate_serial_number;
10use crate::crl::crl_signature_err;
11use crate::der::{self, CONSTRUCTED, CONTEXT_SPECIFIC, DerIterator, FromDer, Tag};
12use crate::error::{DerTypeId, Error};
13use crate::public_values_eq;
14#[cfg(feature = "alloc")]
15use crate::signed_data::OwnedSignedData;
16use crate::signed_data::SignedData;
17use crate::subject_name::GeneralName;
18use crate::verify_cert::{Budget, PathNode, Role};
19use crate::x509::{
20    DistributionPointName, Extension, UnknownExtensionPolicy, remember_extension,
21    set_extension_once,
22};
23
24/// A RFC 5280[^1] profile Certificate Revocation List (CRL).
25///
26/// May be either an owned, or a borrowed representation.
27///
28/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
29#[derive(Debug, Hash)]
30pub enum CertRevocationList<'a> {
31    /// An owned representation of a CRL.
32    #[cfg(feature = "alloc")]
33    Owned(OwnedCertRevocationList),
34    /// A borrowed representation of a CRL.
35    Borrowed(BorrowedCertRevocationList<'a>),
36}
37
38#[cfg(feature = "alloc")]
39impl From<OwnedCertRevocationList> for CertRevocationList<'_> {
40    fn from(crl: OwnedCertRevocationList) -> Self {
41        Self::Owned(crl)
42    }
43}
44
45impl<'a> From<BorrowedCertRevocationList<'a>> for CertRevocationList<'a> {
46    fn from(crl: BorrowedCertRevocationList<'a>) -> Self {
47        Self::Borrowed(crl)
48    }
49}
50
51impl CertRevocationList<'_> {
52    /// Return the DER encoded issuer of the CRL.
53    pub fn issuer(&self) -> &[u8] {
54        match self {
55            #[cfg(feature = "alloc")]
56            CertRevocationList::Owned(crl) => crl.issuer.as_ref(),
57            CertRevocationList::Borrowed(crl) => crl.issuer.as_slice_less_safe(),
58        }
59    }
60
61    /// Return the DER encoded issuing distribution point of the CRL, if any.
62    pub fn issuing_distribution_point(&self) -> Option<&[u8]> {
63        match self {
64            #[cfg(feature = "alloc")]
65            CertRevocationList::Owned(crl) => crl.issuing_distribution_point.as_deref(),
66            CertRevocationList::Borrowed(crl) => crl
67                .issuing_distribution_point
68                .map(|idp| idp.as_slice_less_safe()),
69        }
70    }
71
72    /// Try to find a revoked certificate in the CRL by DER encoded serial number. This
73    /// may yield an error if the CRL has malformed revoked certificates.
74    pub fn find_serial(&self, serial: &[u8]) -> Result<Option<BorrowedRevokedCert<'_>>, Error> {
75        match self {
76            #[cfg(feature = "alloc")]
77            CertRevocationList::Owned(crl) => crl.find_serial(serial),
78            CertRevocationList::Borrowed(crl) => crl.find_serial(serial),
79        }
80    }
81
82    /// Returns true if the CRL can be considered authoritative for the given certificate.
83    ///
84    /// A CRL is considered authoritative for a certificate when:
85    ///   * The certificate issuer matches the CRL issuer and,
86    ///     * The certificate has no CRL distribution points, and the CRL has no issuing distribution
87    ///       point extension.
88    ///     * Or, the certificate has no CRL distribution points, but the the CRL has an issuing
89    ///       distribution point extension with a scope that includes the certificate.
90    ///     * Or, the certificate has CRL distribution points, and the CRL has an issuing
91    ///       distribution point extension with a scope that includes the certificate, and at least
92    ///       one distribution point full name is a URI type general name that can also be found in
93    ///       the CRL issuing distribution point full name general name sequence.
94    ///     * Or, the certificate has CRL distribution points, and the CRL has no issuing
95    ///       distribution point extension.
96    ///
97    /// In all other circumstances the CRL is not considered authoritative.
98    pub(crate) fn authoritative(&self, path: &PathNode<'_>) -> bool {
99        // In all cases we require that the authoritative CRL have the same issuer
100        // as the certificate. Recall we do not support indirect CRLs.
101        if self.issuer() != path.cert.issuer() {
102            return false;
103        }
104
105        let crl_idp = match self.issuing_distribution_point() {
106            // If the CRL has an issuing distribution point, parse it so we can consider its scope
107            // and compare against the cert CRL distribution points, if present.
108            Some(crl_idp) => {
109                match IssuingDistributionPoint::from_der(untrusted::Input::from(crl_idp)) {
110                    Ok(crl_idp) => crl_idp,
111                    Err(_) => return false, // Note: shouldn't happen - we verify IDP at CRL-load.
112                }
113            }
114            // If the CRL has no issuing distribution point we assume the CRL scope
115            // to be "everything" and consider the CRL authoritative for the cert based on the
116            // issuer matching. We do not need to consider the certificate's CRL distribution point
117            // extension (see also https://github.com/rustls/webpki/issues/228).
118            None => return true,
119        };
120
121        crl_idp.authoritative_for(path)
122    }
123
124    /// Verify the CRL signature using the issuer certificate and a list of supported signature
125    /// verification algorithms, consuming signature operations from the [`Budget`].
126    pub(crate) fn verify_signature(
127        &self,
128        supported_sig_algs: &[&dyn SignatureVerificationAlgorithm],
129        issuer_spki: untrusted::Input<'_>,
130        budget: &mut Budget,
131    ) -> Result<(), Error> {
132        match self {
133            #[cfg(feature = "alloc")]
134            CertRevocationList::Owned(crl) => crl.signed_data.borrow(),
135            CertRevocationList::Borrowed(crl) => SignedData {
136                data: crl.signed_data.data,
137                algorithm: crl.signed_data.algorithm,
138                signature: crl.signed_data.signature,
139            },
140        }
141        .verify(supported_sig_algs, issuer_spki, budget)
142        .map_err(crl_signature_err)
143    }
144
145    /// Checks the verification time is before the time in the CRL nextUpdate field.
146    pub(crate) fn check_expiration(&self, time: UnixTime) -> Result<(), Error> {
147        let next_update = match self {
148            #[cfg(feature = "alloc")]
149            CertRevocationList::Owned(crl) => crl.next_update,
150            CertRevocationList::Borrowed(crl) => crl.next_update,
151        };
152
153        if time >= next_update {
154            return Err(Error::CrlExpired { time, next_update });
155        }
156
157        Ok(())
158    }
159}
160
161/// Owned representation of a RFC 5280[^1] profile Certificate Revocation List (CRL).
162///
163/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
164#[cfg(feature = "alloc")]
165#[derive(Debug, Clone, Hash)]
166pub struct OwnedCertRevocationList {
167    /// A map of the revoked certificates contained in then CRL, keyed by the DER encoding
168    /// of the revoked cert's serial number.
169    revoked_certs: BTreeMap<Vec<u8>, OwnedRevokedCert>,
170
171    issuer: Vec<u8>,
172
173    issuing_distribution_point: Option<Vec<u8>>,
174
175    signed_data: OwnedSignedData,
176
177    next_update: UnixTime,
178}
179
180#[cfg(feature = "alloc")]
181impl OwnedCertRevocationList {
182    /// Try to parse the given bytes as a RFC 5280[^1] profile Certificate Revocation List (CRL).
183    ///
184    /// Webpki does not support:
185    ///   * CRL versions other than version 2.
186    ///   * CRLs missing the next update field.
187    ///   * CRLs missing certificate revocation list extensions.
188    ///   * Delta CRLs.
189    ///   * CRLs larger than (2^32)-1 bytes in size.
190    ///
191    /// See [BorrowedCertRevocationList::from_der] for more details.
192    ///
193    /// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
194    pub fn from_der(crl_der: &[u8]) -> Result<Self, Error> {
195        BorrowedCertRevocationList::from_der(crl_der)?.to_owned()
196    }
197
198    fn find_serial(&self, serial: &[u8]) -> Result<Option<BorrowedRevokedCert<'_>>, Error> {
199        // note: this is infallible for the owned representation because we process all
200        // revoked certificates at the time of construction to build the `revoked_certs` map,
201        // returning any encountered errors at that time.
202        Ok(self
203            .revoked_certs
204            .get(serial)
205            .map(|owned_revoked_cert| owned_revoked_cert.borrow()))
206    }
207}
208
209/// Borrowed representation of a RFC 5280[^1] profile Certificate Revocation List (CRL).
210///
211/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
212#[derive(Debug)]
213pub struct BorrowedCertRevocationList<'a> {
214    /// A `SignedData` structure that can be passed to `verify_signed_data`.
215    signed_data: SignedData<'a>,
216
217    /// Identifies the entity that has signed and issued this
218    /// CRL.
219    issuer: untrusted::Input<'a>,
220
221    /// An optional CRL extension that identifies the CRL distribution point and scope for the CRL.
222    issuing_distribution_point: Option<untrusted::Input<'a>>,
223
224    /// List of certificates revoked by the issuer in this CRL.
225    revoked_certs: untrusted::Input<'a>,
226
227    next_update: UnixTime,
228}
229
230impl<'a> BorrowedCertRevocationList<'a> {
231    /// Try to parse the given bytes as a RFC 5280[^1] profile Certificate Revocation List (CRL).
232    ///
233    /// Webpki does not support:
234    ///   * CRL versions other than version 2.
235    ///   * CRLs missing the next update field.
236    ///   * CRLs missing certificate revocation list extensions.
237    ///   * Delta CRLs.
238    ///   * CRLs larger than (2^32)-1 bytes in size.
239    ///
240    /// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
241    pub fn from_der(crl_der: &'a [u8]) -> Result<Self, Error> {
242        der::read_all(untrusted::Input::from(crl_der))
243    }
244
245    /// Convert the CRL to an [`OwnedCertRevocationList`]. This may error if any of the revoked
246    /// certificates in the CRL are malformed or contain unsupported features.
247    #[cfg(feature = "alloc")]
248    pub fn to_owned(&self) -> Result<OwnedCertRevocationList, Error> {
249        // Parse and collect the CRL's revoked cert entries, ensuring there are no errors. With
250        // the full set in-hand, create a lookup map by serial number for fast revocation checking.
251        let revoked_certs = self
252            .into_iter()
253            .collect::<Result<Vec<_>, _>>()?
254            .iter()
255            .map(|revoked_cert| (revoked_cert.serial_number.to_vec(), revoked_cert.to_owned()))
256            .collect::<BTreeMap<_, _>>();
257
258        Ok(OwnedCertRevocationList {
259            signed_data: self.signed_data.to_owned(),
260            issuer: self.issuer.as_slice_less_safe().to_vec(),
261            issuing_distribution_point: self
262                .issuing_distribution_point
263                .map(|idp| idp.as_slice_less_safe().to_vec()),
264            revoked_certs,
265            next_update: self.next_update,
266        })
267    }
268
269    fn remember_extension(&mut self, extension: &Extension<'a>) -> Result<(), Error> {
270        use crate::x509::ExtensionOid::*;
271
272        remember_extension(extension, UnknownExtensionPolicy::default(), |id| {
273            match id {
274                // id-ce-cRLNumber 2.5.29.20 - RFC 5280 §5.2.3
275                Standard(20) => {
276                    // RFC 5280 §5.2.3:
277                    //   CRL verifiers MUST be able to handle CRLNumber values
278                    //   up to 20 octets.  Conforming CRL issuers MUST NOT use CRLNumber
279                    //   values longer than 20 octets.
280                    //
281                    extension.value.read_all(Error::InvalidCrlNumber, |der| {
282                        let crl_number = der::nonnegative_integer(der)
283                            .map_err(|_| Error::InvalidCrlNumber)?
284                            .as_slice_less_safe();
285                        if crl_number.len() <= 20 {
286                            Ok(crl_number)
287                        } else {
288                            Err(Error::InvalidCrlNumber)
289                        }
290                    })?;
291                    // We enforce the cRLNumber is sensible, but don't retain the value for use.
292                    Ok(())
293                }
294
295                // id-ce-deltaCRLIndicator 2.5.29.27 - RFC 5280 §5.2.4
296                // We explicitly do not support delta CRLs.
297                Standard(27) => Err(Error::UnsupportedDeltaCrl),
298
299                // id-ce-issuingDistributionPoint 2.5.29.28 - RFC 5280 §5.2.4
300                // We recognize the extension and retain its value for use.
301                Standard(28) => {
302                    set_extension_once(&mut self.issuing_distribution_point, || Ok(extension.value))
303                }
304
305                // id-ce-authorityKeyIdentifier 2.5.29.35 - RFC 5280 §5.2.1, §4.2.1.1
306                // We recognize the extension but don't retain its value for use.
307                Standard(35) => Ok(()),
308
309                // Unsupported extension
310                _ => extension.unsupported(UnknownExtensionPolicy::default()),
311            }
312        })
313    }
314
315    fn find_serial(&self, serial: &[u8]) -> Result<Option<BorrowedRevokedCert<'_>>, Error> {
316        for revoked_cert_result in self {
317            match revoked_cert_result {
318                Err(e) => return Err(e),
319                Ok(revoked_cert) => {
320                    if revoked_cert.serial_number.eq(serial) {
321                        return Ok(Some(revoked_cert));
322                    }
323                }
324            }
325        }
326
327        Ok(None)
328    }
329}
330
331impl<'a> FromDer<'a> for BorrowedCertRevocationList<'a> {
332    /// Try to parse the given bytes as a RFC 5280[^1] profile Certificate Revocation List (CRL).
333    ///
334    /// Webpki does not support:
335    ///   * CRL versions other than version 2.
336    ///   * CRLs missing the next update field.
337    ///   * CRLs missing certificate revocation list extensions.
338    ///   * Delta CRLs.
339    ///   * CRLs larger than (2^32)-1 bytes in size.
340    ///
341    /// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
342    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
343        let (tbs_cert_list, signed_data) = der::nested_limited(
344            reader,
345            Tag::Sequence,
346            Error::TrailingData(Self::TYPE_ID),
347            |signed_der| SignedData::from_der(signed_der, der::MAX_DER_SIZE),
348            der::MAX_DER_SIZE,
349        )?;
350
351        let crl = tbs_cert_list.read_all(Error::BadDer, |tbs_cert_list| {
352            // RFC 5280 §5.1.2.1:
353            //   This optional field describes the version of the encoded CRL.  When
354            //   extensions are used, as required by this profile, this field MUST be
355            //   present and MUST specify version 2 (the integer value is 1).
356            // RFC 5280 §5.2:
357            //   Conforming CRL issuers are REQUIRED to include the authority key
358            //   identifier (Section 5.2.1) and the CRL number (Section 5.2.3)
359            //   extensions in all CRLs issued.
360            // As a result of the above we parse this as a required section, not OPTIONAL.
361            // NOTE: Encoded value of version 2 is 1.
362            if u8::from_der(tbs_cert_list)? != 1 {
363                return Err(Error::UnsupportedCrlVersion);
364            }
365
366            // RFC 5280 §5.1.2.2:
367            //   This field MUST contain the same algorithm identifier as the
368            //   signatureAlgorithm field in the sequence CertificateList
369            let signature = der::expect_tag(tbs_cert_list, Tag::Sequence)?;
370            if !public_values_eq(signature, signed_data.algorithm) {
371                return Err(Error::SignatureAlgorithmMismatch);
372            }
373
374            // RFC 5280 §5.1.2.3:
375            //   The issuer field MUST contain a non-empty X.500 distinguished name (DN).
376            let issuer = der::expect_tag(tbs_cert_list, Tag::Sequence)?;
377
378            // RFC 5280 §5.1.2.4:
379            //    This field indicates the issue date of this CRL.  thisUpdate may be
380            //    encoded as UTCTime or GeneralizedTime.
381            // We do not presently enforce the correct choice of UTCTime or GeneralizedTime based on
382            // whether the date is post 2050.
383            UnixTime::from_der(tbs_cert_list)?;
384
385            // While OPTIONAL in the ASN.1 module, RFC 5280 §5.1.2.5 says:
386            //   Conforming CRL issuers MUST include the nextUpdate field in all CRLs.
387            // We do not presently enforce the correct choice of UTCTime or GeneralizedTime based on
388            // whether the date is post 2050.
389            let next_update = UnixTime::from_der(tbs_cert_list)?;
390
391            // RFC 5280 §5.1.2.6:
392            //   When there are no revoked certificates, the revoked certificates list
393            //   MUST be absent
394            // TODO(@cpu): Do we care to support empty CRLs if we don't support delta CRLs?
395            let revoked_certs = if tbs_cert_list.peek(Tag::Sequence.into()) {
396                der::expect_tag_and_get_value_limited(
397                    tbs_cert_list,
398                    Tag::Sequence,
399                    der::MAX_DER_SIZE,
400                )?
401            } else {
402                untrusted::Input::from(&[])
403            };
404
405            let mut crl = BorrowedCertRevocationList {
406                signed_data,
407                issuer,
408                revoked_certs,
409                issuing_distribution_point: None,
410                next_update,
411            };
412
413            // RFC 5280 §5.1.2.7:
414            //   This field may only appear if the version is 2 (Section 5.1.2.1).  If
415            //   present, this field is a sequence of one or more CRL extensions.
416            // RFC 5280 §5.2:
417            //   Conforming CRL issuers are REQUIRED to include the authority key
418            //   identifier (Section 5.2.1) and the CRL number (Section 5.2.3)
419            //   extensions in all CRLs issued.
420            // As a result of the above we parse this as a required section, not OPTIONAL.
421            der::nested(
422                tbs_cert_list,
423                Tag::ContextSpecificConstructed0,
424                Error::MalformedExtensions,
425                |tagged| {
426                    der::nested_of_mut(
427                        tagged,
428                        Tag::Sequence,
429                        Tag::Sequence,
430                        Error::TrailingData(DerTypeId::CertRevocationListExtension),
431                        false,
432                        |extension| {
433                            // RFC 5280 §5.2:
434                            //   If a CRL contains a critical extension
435                            //   that the application cannot process, then the application MUST NOT
436                            //   use that CRL to determine the status of certificates.  However,
437                            //   applications may ignore unrecognized non-critical extensions.
438                            crl.remember_extension(&Extension::from_der(extension)?)
439                        },
440                    )
441                },
442            )?;
443
444            Ok(crl)
445        })?;
446
447        // If an issuing distribution point extension is present, parse it up-front to validate
448        // that it only uses well-formed and supported features.
449        if let Some(der) = crl.issuing_distribution_point {
450            IssuingDistributionPoint::from_der(der)?;
451        }
452
453        Ok(crl)
454    }
455
456    const TYPE_ID: DerTypeId = DerTypeId::CertRevocationList;
457}
458
459impl<'a> IntoIterator for &'a BorrowedCertRevocationList<'a> {
460    type Item = Result<BorrowedRevokedCert<'a>, Error>;
461    type IntoIter = DerIterator<'a, BorrowedRevokedCert<'a>>;
462
463    fn into_iter(self) -> Self::IntoIter {
464        DerIterator::new(self.revoked_certs)
465    }
466}
467
468impl core::hash::Hash for BorrowedCertRevocationList<'_> {
469    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
470        let Self {
471            signed_data,
472            issuer,
473            issuing_distribution_point,
474            revoked_certs,
475            next_update,
476        } = self;
477        signed_data.hash(state);
478        issuer.as_slice_less_safe().hash(state);
479        issuing_distribution_point
480            .map(|i| i.as_slice_less_safe())
481            .hash(state);
482        revoked_certs.as_slice_less_safe().hash(state);
483        next_update.hash(state);
484    }
485}
486
487pub(crate) struct IssuingDistributionPoint<'a> {
488    distribution_point: Option<untrusted::Input<'a>>,
489    pub(crate) only_contains_user_certs: bool,
490    pub(crate) only_contains_ca_certs: bool,
491    pub(crate) only_some_reasons: Option<der::BitStringFlags<'a>>,
492    pub(crate) indirect_crl: bool,
493    pub(crate) only_contains_attribute_certs: bool,
494}
495
496impl<'a> IssuingDistributionPoint<'a> {
497    pub(crate) fn from_der(der: untrusted::Input<'a>) -> Result<Self, Error> {
498        const DISTRIBUTION_POINT_TAG: u8 = CONTEXT_SPECIFIC | CONSTRUCTED;
499        const ONLY_CONTAINS_USER_CERTS_TAG: u8 = CONTEXT_SPECIFIC | 1;
500        const ONLY_CONTAINS_CA_CERTS_TAG: u8 = CONTEXT_SPECIFIC | 2;
501        const ONLY_CONTAINS_SOME_REASONS_TAG: u8 = CONTEXT_SPECIFIC | 3;
502        const INDIRECT_CRL_TAG: u8 = CONTEXT_SPECIFIC | 4;
503        const ONLY_CONTAINS_ATTRIBUTE_CERTS_TAG: u8 = CONTEXT_SPECIFIC | 5;
504
505        let mut result = IssuingDistributionPoint {
506            distribution_point: None,
507            only_contains_user_certs: false,
508            only_contains_ca_certs: false,
509            only_some_reasons: None,
510            indirect_crl: false,
511            only_contains_attribute_certs: false,
512        };
513
514        // Note: we can't use der::optional_boolean here because the distribution point
515        //       booleans are context specific primitives and der::optional_boolean expects
516        //       to unwrap a Tag::Boolean constructed value.
517        fn decode_bool(value: untrusted::Input<'_>) -> Result<bool, Error> {
518            let mut reader = untrusted::Reader::new(value);
519            let value = reader.read_byte().map_err(der::end_of_input_err)?;
520            if !reader.at_end() {
521                return Err(Error::BadDer);
522            }
523            match value {
524                0xFF => Ok(true),
525                0x00 => Ok(false), // non-conformant explicit encoding allowed for compat.
526                _ => Err(Error::BadDer),
527            }
528        }
529
530        // RFC 5280 section §4.2.1.13:
531        der::nested(
532            &mut untrusted::Reader::new(der),
533            Tag::Sequence,
534            Error::TrailingData(DerTypeId::IssuingDistributionPoint),
535            |der| {
536                while !der.at_end() {
537                    let (tag, value) = der::read_tag_and_get_value(der)?;
538                    match tag {
539                        DISTRIBUTION_POINT_TAG => {
540                            set_extension_once(&mut result.distribution_point, || Ok(value))?
541                        }
542                        ONLY_CONTAINS_USER_CERTS_TAG => {
543                            result.only_contains_user_certs = decode_bool(value)?
544                        }
545                        ONLY_CONTAINS_CA_CERTS_TAG => {
546                            result.only_contains_ca_certs = decode_bool(value)?
547                        }
548                        ONLY_CONTAINS_SOME_REASONS_TAG => {
549                            set_extension_once(&mut result.only_some_reasons, || {
550                                der::bit_string_flags(value)
551                            })?
552                        }
553                        INDIRECT_CRL_TAG => result.indirect_crl = decode_bool(value)?,
554                        ONLY_CONTAINS_ATTRIBUTE_CERTS_TAG => {
555                            result.only_contains_attribute_certs = decode_bool(value)?
556                        }
557                        _ => return Err(Error::BadDer),
558                    }
559                }
560
561                Ok(())
562            },
563        )?;
564
565        // RFC 5280 4.2.1.10:
566        //   Conforming CRLs issuers MUST set the onlyContainsAttributeCerts boolean to FALSE.
567        if result.only_contains_attribute_certs {
568            return Err(Error::MalformedExtensions);
569        }
570
571        // We don't support indirect CRLs.
572        if result.indirect_crl {
573            return Err(Error::UnsupportedIndirectCrl);
574        }
575
576        // We don't support CRLs partitioned by revocation reason.
577        if result.only_some_reasons.is_some() {
578            return Err(Error::UnsupportedRevocationReasonsPartitioning);
579        }
580
581        // We require a distribution point, and it must be a full name.
582        use DistributionPointName::*;
583        match result.names() {
584            Ok(Some(FullName(_))) => Ok(result),
585            Ok(Some(NameRelativeToCrlIssuer)) | Ok(None) => {
586                Err(Error::UnsupportedCrlIssuingDistributionPoint)
587            }
588            Err(_) => Err(Error::MalformedExtensions),
589        }
590    }
591
592    /// Return the distribution point names (if any).
593    pub(crate) fn names(&self) -> Result<Option<DistributionPointName<'a>>, Error> {
594        self.distribution_point
595            .map(|input| DistributionPointName::from_der(&mut untrusted::Reader::new(input)))
596            .transpose()
597    }
598
599    /// Returns true if the CRL can be considered authoritative for the given certificate. We make
600    /// this determination using the certificate and CRL issuers, and the distribution point names
601    /// that may be present in extensions found on both.
602    ///
603    /// We consider the CRL authoritative for the certificate if the CRL issuing distribution point
604    /// has a scope that could include the cert and if the cert has CRL distribution points, that
605    /// at least one CRL DP has a valid distribution point full name where one of the general names
606    /// is a Uniform Resource Identifier (URI) general name that can also be found in the CRL
607    /// issuing distribution point.
608    ///
609    /// We do not consider:
610    /// * Distribution point names relative to an issuer.
611    /// * General names of a type other than URI.
612    /// * Malformed names or invalid IDP or CRL DP extensions.
613    pub(crate) fn authoritative_for(&self, node: &PathNode<'a>) -> bool {
614        assert!(!self.only_contains_attribute_certs); // We check this at time of parse.
615
616        // Check that the scope of the CRL issuing distribution point could include the cert.
617        if self.only_contains_ca_certs && node.role() != Role::Issuer
618            || self.only_contains_user_certs && node.role() != Role::EndEntity
619        {
620            return false; // CRL scope excludes this cert's role.
621        }
622
623        let Some(cert_dps) = node.cert.crl_distribution_points() else {
624            // If the certificate has no distribution points, then the CRL can be authoritative
625            // based on the issuer matching and the scope including the cert.
626            return true;
627        };
628
629        for cert_dp in cert_dps {
630            let Ok(cert_dp) = cert_dp else {
631                continue; // Malformed DP, try next cert DP.
632            };
633
634            // If the certificate CRL DP was for an indirect CRL, or a CRL
635            // sharded by revocation reason, it can't match.
636            if cert_dp.crl_issuer.is_some() || cert_dp.reasons.is_some() {
637                continue; // Indirect CRL or reason-partitioned DP, try next cert DP.
638            }
639
640            let Ok(Some(DistributionPointName::FullName(dp_general_names))) = cert_dp.names()
641            else {
642                continue; // No full names or malformed, try next cert DP.
643            };
644
645            // At least one URI type name in the IDP full names must match a URI type name in the
646            // DP full names.
647            for dp_name in dp_general_names {
648                let dp_uri = match dp_name {
649                    Ok(GeneralName::UniformResourceIdentifier(dp_uri)) => dp_uri,
650                    Ok(_) => continue,  // Not a URI type name, skip.
651                    Err(_) => continue, // Malformed general name, try next name.
652                };
653
654                let Ok(Some(DistributionPointName::FullName(idp_general_names))) = self.names()
655                else {
656                    return false; // IDP has no full names or is malformed.
657                };
658
659                for idp_name in idp_general_names.flatten() {
660                    match idp_name {
661                        GeneralName::UniformResourceIdentifier(idp_uri)
662                            if dp_uri.as_slice_less_safe() == idp_uri.as_slice_less_safe() =>
663                        {
664                            return true; // DP URI matches IDP URI.
665                        }
666                        _ => continue, // Not a matching URI, try next IDP name.
667                    }
668                }
669            }
670        }
671
672        false
673    }
674}
675
676/// Owned representation of a RFC 5280[^1] profile Certificate Revocation List (CRL) revoked
677/// certificate entry.
678///
679/// Only available when the "alloc" feature is enabled.
680///
681/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
682#[cfg(feature = "alloc")]
683#[derive(Clone, Debug, Hash)]
684pub struct OwnedRevokedCert {
685    /// Serial number of the revoked certificate.
686    pub serial_number: Vec<u8>,
687
688    /// The date at which the CA processed the revocation.
689    pub revocation_date: UnixTime,
690
691    /// Identifies the reason for the certificate revocation. When absent, the revocation reason
692    /// is assumed to be RevocationReason::Unspecified. For consistency with other extensions
693    /// and to ensure only one revocation reason extension may be present we maintain this field
694    /// as optional instead of defaulting to unspecified.
695    pub reason_code: Option<RevocationReason>,
696
697    /// Provides the date on which it is known or suspected that the private key was compromised or
698    /// that the certificate otherwise became invalid. This date may be earlier than the revocation
699    /// date which is the date at which the CA processed the revocation.
700    pub invalidity_date: Option<UnixTime>,
701}
702
703#[cfg(feature = "alloc")]
704impl OwnedRevokedCert {
705    /// Convert the owned representation of this revoked cert to a borrowed version.
706    pub fn borrow(&self) -> BorrowedRevokedCert<'_> {
707        BorrowedRevokedCert {
708            serial_number: &self.serial_number,
709            revocation_date: self.revocation_date,
710            reason_code: self.reason_code,
711            invalidity_date: self.invalidity_date,
712        }
713    }
714}
715
716/// Borrowed representation of a RFC 5280[^1] profile Certificate Revocation List (CRL) revoked
717/// certificate entry.
718///
719/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
720#[derive(Debug)]
721pub struct BorrowedRevokedCert<'a> {
722    /// Serial number of the revoked certificate.
723    pub serial_number: &'a [u8],
724
725    /// The date at which the CA processed the revocation.
726    pub revocation_date: UnixTime,
727
728    /// Identifies the reason for the certificate revocation. When absent, the revocation reason
729    /// is assumed to be RevocationReason::Unspecified. For consistency with other extensions
730    /// and to ensure only one revocation reason extension may be present we maintain this field
731    /// as optional instead of defaulting to unspecified.
732    pub reason_code: Option<RevocationReason>,
733
734    /// Provides the date on which it is known or suspected that the private key was compromised or
735    /// that the certificate otherwise became invalid. This date may be earlier than the revocation
736    /// date which is the date at which the CA processed the revocation.
737    pub invalidity_date: Option<UnixTime>,
738}
739
740impl<'a> BorrowedRevokedCert<'a> {
741    /// Construct an owned representation of the revoked certificate.
742    #[cfg(feature = "alloc")]
743    pub fn to_owned(&self) -> OwnedRevokedCert {
744        OwnedRevokedCert {
745            serial_number: self.serial_number.to_vec(),
746            revocation_date: self.revocation_date,
747            reason_code: self.reason_code,
748            invalidity_date: self.invalidity_date,
749        }
750    }
751
752    fn remember_extension(&mut self, extension: &Extension<'a>) -> Result<(), Error> {
753        use crate::x509::ExtensionOid::*;
754
755        remember_extension(extension, UnknownExtensionPolicy::default(), |id| {
756            match id {
757                // id-ce-cRLReasons 2.5.29.21 - RFC 5280 §5.3.1.
758                Standard(21) => {
759                    set_extension_once(&mut self.reason_code, || der::read_all(extension.value))
760                }
761
762                // id-ce-invalidityDate 2.5.29.24 - RFC 5280 §5.3.2.
763                Standard(24) => set_extension_once(&mut self.invalidity_date, || {
764                    extension.value.read_all(Error::BadDer, UnixTime::from_der)
765                }),
766
767                // id-ce-certificateIssuer 2.5.29.29 - RFC 5280 §5.3.3.
768                //   This CRL entry extension identifies the certificate issuer associated
769                //   with an entry in an indirect CRL, that is, a CRL that has the
770                //   indirectCRL indicator set in its issuing distribution point
771                //   extension.
772                // We choose not to support indirect CRLs and so turn this into a more specific
773                // error rather than simply letting it fail as an unsupported critical extension.
774                Standard(29) => Err(Error::UnsupportedIndirectCrl),
775
776                // Unsupported extension
777                _ => extension.unsupported(UnknownExtensionPolicy::default()),
778            }
779        })
780    }
781}
782
783impl<'a> FromDer<'a> for BorrowedRevokedCert<'a> {
784    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
785        der::nested(
786            reader,
787            Tag::Sequence,
788            Error::TrailingData(DerTypeId::RevokedCertEntry),
789            |der| {
790                // RFC 5280 §4.1.2.2:
791                //    Certificate users MUST be able to handle serialNumber values up to 20 octets.
792                //    Conforming CAs MUST NOT use serialNumber values longer than 20 octets.
793                //
794                //    Note: Non-conforming CAs may issue certificates with serial numbers
795                //    that are negative or zero.  Certificate users SHOULD be prepared to
796                //    gracefully handle such certificates.
797                // Like the handling in cert.rs we choose to be lenient here, not enforcing the length
798                // of a CRL revoked certificate's serial number is less than 20 octets in encoded form.
799                let serial_number = lenient_certificate_serial_number(der)
800                    .map_err(|_| Error::InvalidSerialNumber)?
801                    .as_slice_less_safe();
802
803                let revocation_date = UnixTime::from_der(der)?;
804
805                let mut revoked_cert = BorrowedRevokedCert {
806                    serial_number,
807                    revocation_date,
808                    reason_code: None,
809                    invalidity_date: None,
810                };
811
812                // RFC 5280 §5.3:
813                //   Support for the CRL entry extensions defined in this specification is
814                //   optional for conforming CRL issuers and applications.  However, CRL
815                //   issuers SHOULD include reason codes (Section 5.3.1) and invalidity
816                //   dates (Section 5.3.2) whenever this information is available.
817                if der.at_end() {
818                    return Ok(revoked_cert);
819                }
820
821                // It would be convenient to use der::nested_of_mut here to unpack a SEQUENCE of one or
822                // more SEQUENCEs, however CAs have been mis-encoding the absence of extensions as an
823                // empty SEQUENCE so we must be tolerant of that.
824                let ext_seq = der::expect_tag(der, Tag::Sequence)?;
825                if ext_seq.is_empty() {
826                    return Ok(revoked_cert);
827                }
828
829                let mut reader = untrusted::Reader::new(ext_seq);
830                loop {
831                    der::nested(
832                        &mut reader,
833                        Tag::Sequence,
834                        Error::TrailingData(DerTypeId::RevokedCertificateExtension),
835                        |ext_der| {
836                            // RFC 5280 §5.3:
837                            //   If a CRL contains a critical CRL entry extension that the application cannot
838                            //   process, then the application MUST NOT use that CRL to determine the
839                            //   status of any certificates.  However, applications may ignore
840                            //   unrecognized non-critical CRL entry extensions.
841                            revoked_cert.remember_extension(&Extension::from_der(ext_der)?)
842                        },
843                    )?;
844                    if reader.at_end() {
845                        break;
846                    }
847                }
848
849                Ok(revoked_cert)
850            },
851        )
852    }
853
854    const TYPE_ID: DerTypeId = DerTypeId::RevokedCertificate;
855}
856
857/// Identifies the reason a certificate was revoked.
858/// See [RFC 5280 §5.3.1][1]
859///
860/// [1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5.3.1>
861#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
862#[expect(missing_docs)] // Not much to add above the code name.
863pub enum RevocationReason {
864    /// Unspecified should not be used, and is instead assumed by the absence of a RevocationReason
865    /// extension.
866    Unspecified = 0,
867    KeyCompromise = 1,
868    CaCompromise = 2,
869    AffiliationChanged = 3,
870    Superseded = 4,
871    CessationOfOperation = 5,
872    CertificateHold = 6,
873    // 7 is not used.
874    /// RemoveFromCrl only appears in delta CRLs that are unsupported.
875    RemoveFromCrl = 8,
876    PrivilegeWithdrawn = 9,
877    AaCompromise = 10,
878}
879
880impl RevocationReason {
881    /// Return an iterator over all possible [RevocationReason] variants.
882    pub fn iter() -> impl Iterator<Item = Self> {
883        use RevocationReason::*;
884        [
885            Unspecified,
886            KeyCompromise,
887            CaCompromise,
888            AffiliationChanged,
889            Superseded,
890            CessationOfOperation,
891            CertificateHold,
892            RemoveFromCrl,
893            PrivilegeWithdrawn,
894            AaCompromise,
895        ]
896        .into_iter()
897    }
898}
899
900impl<'a> FromDer<'a> for RevocationReason {
901    // RFC 5280 §5.3.1.
902    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
903        let input = der::expect_tag(reader, Tag::Enum)?;
904        Self::try_from(input.read_all(Error::BadDer, |reason| {
905            reason.read_byte().map_err(|_| Error::BadDer)
906        })?)
907    }
908
909    const TYPE_ID: DerTypeId = DerTypeId::RevocationReason;
910}
911
912impl TryFrom<u8> for RevocationReason {
913    type Error = Error;
914
915    fn try_from(value: u8) -> Result<Self, Self::Error> {
916        // See https://www.rfc-editor.org/rfc/rfc5280#section-5.3.1
917        match value {
918            0 => Ok(Self::Unspecified),
919            1 => Ok(Self::KeyCompromise),
920            2 => Ok(Self::CaCompromise),
921            3 => Ok(Self::AffiliationChanged),
922            4 => Ok(Self::Superseded),
923            5 => Ok(Self::CessationOfOperation),
924            6 => Ok(Self::CertificateHold),
925            // 7 is not used.
926            8 => Ok(Self::RemoveFromCrl),
927            9 => Ok(Self::PrivilegeWithdrawn),
928            10 => Ok(Self::AaCompromise),
929            _ => Err(Error::UnsupportedRevocationReason),
930        }
931    }
932}
933
934#[cfg(feature = "alloc")]
935#[cfg(test)]
936mod tests {
937    use core::time::Duration;
938
939    use pki_types::CertificateDer;
940    use std::println;
941
942    use super::*;
943    use crate::cert::Cert;
944    use crate::end_entity::EndEntityCert;
945    use crate::verify_cert::PartialPath;
946
947    #[test]
948    fn parse_issuing_distribution_point_ext() {
949        let crl = include_bytes!("../../tests/crls/crl.idp.valid.der");
950        let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
951
952        // We should be able to parse the issuing distribution point extension.
953        let crl_issuing_dp = crl
954            .issuing_distribution_point
955            .expect("missing crl distribution point DER");
956
957        #[cfg(feature = "alloc")]
958        {
959            // We should also be able to find the distribution point extensions bytes from
960            // an owned representation of the CRL.
961            let owned_crl = crl.to_owned().unwrap();
962            assert!(owned_crl.issuing_distribution_point.is_some());
963        }
964
965        let crl_issuing_dp = IssuingDistributionPoint::from_der(untrusted::Input::from(
966            crl_issuing_dp.as_slice_less_safe(),
967        ))
968        .expect("failed to parse issuing distribution point DER");
969
970        // We don't expect any of the bool fields to have been set true.
971        assert!(!crl_issuing_dp.only_contains_user_certs);
972        assert!(!crl_issuing_dp.only_contains_ca_certs);
973        assert!(!crl_issuing_dp.indirect_crl);
974
975        // Since the issuing distribution point doesn't specify the optional onlySomeReasons field,
976        // we shouldn't find that it was parsed.
977        assert!(crl_issuing_dp.only_some_reasons.is_none());
978
979        // We should find the expected URI distribution point name.
980        let dp_name = crl_issuing_dp
981            .names()
982            .expect("failed to parse distribution point names")
983            .expect("missing distribution point name");
984        let uri = match dp_name {
985            DistributionPointName::NameRelativeToCrlIssuer => {
986                panic!("unexpected relative dp name")
987            }
988            DistributionPointName::FullName(general_names) => {
989                general_names.map(|general_name| match general_name {
990                    Ok(GeneralName::UniformResourceIdentifier(uri)) => uri.as_slice_less_safe(),
991                    _ => panic!("unexpected general name type"),
992                })
993            }
994        }
995        .collect::<Vec<_>>();
996        let expected = &["http://crl.trustcor.ca/sub/dv-ssl-rsa-s-0.crl".as_bytes()];
997        assert_eq!(uri, expected);
998    }
999
1000    #[test]
1001    fn test_issuing_distribution_point_only_user_certs() {
1002        let crl = include_bytes!("../../tests/crls/crl.idp.only_user_certs.der");
1003        let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1004
1005        // We should be able to parse the issuing distribution point extension.
1006        let crl_issuing_dp = crl
1007            .issuing_distribution_point
1008            .expect("missing crl distribution point DER");
1009        let crl_issuing_dp = IssuingDistributionPoint::from_der(crl_issuing_dp)
1010            .expect("failed to parse issuing distribution point DER");
1011
1012        // We should find the expected bool state.
1013        assert!(crl_issuing_dp.only_contains_user_certs);
1014
1015        // The IDP shouldn't be considered authoritative for a CA Cert.
1016        let ee = CertificateDer::from(
1017            &include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.ee.der")[..],
1018        );
1019        let ee = EndEntityCert::try_from(&ee).unwrap();
1020        let ca = include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.int.a.ca.der");
1021        let ca = Cert::from_der(untrusted::Input::from(&ca[..])).unwrap();
1022
1023        let mut path = PartialPath::new(&ee);
1024        path.push(ca).unwrap();
1025
1026        assert!(!crl_issuing_dp.authoritative_for(&path.node()));
1027    }
1028
1029    #[test]
1030    fn test_issuing_distribution_point_only_ca_certs() {
1031        let crl = include_bytes!("../../tests/crls/crl.idp.only_ca_certs.der");
1032        let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1033
1034        // We should be able to parse the issuing distribution point extension.
1035        let crl_issuing_dp = crl
1036            .issuing_distribution_point
1037            .expect("missing crl distribution point DER");
1038        let crl_issuing_dp = IssuingDistributionPoint::from_der(crl_issuing_dp)
1039            .expect("failed to parse issuing distribution point DER");
1040
1041        // We should find the expected bool state.
1042        assert!(crl_issuing_dp.only_contains_ca_certs);
1043
1044        // The IDP shouldn't be considered authoritative for an EE Cert.
1045        let ee = CertificateDer::from(
1046            &include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.ee.der")[..],
1047        );
1048        let ee = EndEntityCert::try_from(&ee).unwrap();
1049        let path = PartialPath::new(&ee);
1050
1051        assert!(!crl_issuing_dp.authoritative_for(&path.node()));
1052    }
1053
1054    #[test]
1055    fn test_issuing_distribution_point_indirect() {
1056        let crl = include_bytes!("../../tests/crls/crl.idp.indirect_crl.der");
1057        // We should encounter an error parsing a CRL with an IDP extension that indicates it's an
1058        // indirect CRL.
1059        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1060        assert!(matches!(result, Err(Error::UnsupportedIndirectCrl)));
1061    }
1062
1063    #[test]
1064    fn test_issuing_distribution_only_attribute_certs() {
1065        let crl = include_bytes!("../../tests/crls/crl.idp.only_attribute_certs.der");
1066        // We should find an error when we parse a CRL with an IDP extension that indicates it only
1067        // contains attribute certs.
1068        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1069        assert!(matches!(result, Err(Error::MalformedExtensions)));
1070    }
1071
1072    #[test]
1073    fn test_issuing_distribution_only_some_reasons() {
1074        let crl = include_bytes!("../../tests/crls/crl.idp.only_some_reasons.der");
1075        // We should encounter an error parsing a CRL with an IDP extension that indicates it's
1076        // partitioned by revocation reason.
1077        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1078        assert!(matches!(
1079            result,
1080            Err(Error::UnsupportedRevocationReasonsPartitioning)
1081        ));
1082    }
1083
1084    #[test]
1085    fn test_issuing_distribution_invalid_bool() {
1086        // Created w/
1087        //   ascii2der -i tests/crls/crl.idp.invalid.bool.der.txt -o tests/crls/crl.idp.invalid.bool.der
1088        let crl = include_bytes!("../../tests/crls/crl.idp.invalid.bool.der");
1089        // We should encounter an error parsing a CRL with an IDP extension with an invalid encoded boolean.
1090        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1091        assert!(matches!(result, Err(Error::BadDer)))
1092    }
1093
1094    #[test]
1095    fn test_issuing_distribution_explicit_false_bool() {
1096        // Created w/
1097        //   ascii2der -i tests/crls/crl.idp.explicit.false.bool.der.txt -o tests/crls/crl.idp.explicit.false.bool.der
1098        let crl = include_bytes!("../../tests/crls/crl.idp.explicit.false.bool.der");
1099        let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1100
1101        // We should be able to parse the issuing distribution point extension.
1102        let crl_issuing_dp = crl
1103            .issuing_distribution_point
1104            .expect("missing crl distribution point DER");
1105        assert!(IssuingDistributionPoint::from_der(crl_issuing_dp).is_ok());
1106    }
1107
1108    #[test]
1109    fn test_issuing_distribution_unknown_tag() {
1110        // Created w/
1111        //   ascii2der -i tests/crls/crl.idp.unknown.tag.der.txt -o tests/crls/crl.idp.unknown.tag.der
1112        let crl = include_bytes!("../../tests/crls/crl.idp.unknown.tag.der");
1113        // We should encounter an error parsing a CRL with an invalid IDP extension.
1114        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1115        assert!(matches!(result, Err(Error::BadDer)));
1116    }
1117
1118    #[test]
1119    fn test_issuing_distribution_invalid_name() {
1120        // Created w/
1121        //   ascii2der -i tests/crls/crl.idp.invalid.name.der.txt -o tests/crls/crl.idp.invalid.name.der
1122        let crl = include_bytes!("../../tests/crls/crl.idp.invalid.name.der");
1123
1124        // We should encounter an error parsing a CRL with an invalid issuing distribution point name.
1125        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1126        assert!(matches!(result, Err(Error::MalformedExtensions)))
1127    }
1128
1129    #[test]
1130    fn test_issuing_distribution_relative_name() {
1131        let crl = include_bytes!("../../tests/crls/crl.idp.name_relative_to_issuer.der");
1132        // We should encounter an error parsing a CRL with an issuing distribution point extension
1133        // that has a distribution point name relative to an issuer.
1134        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1135        assert!(matches!(
1136            result,
1137            Err(Error::UnsupportedCrlIssuingDistributionPoint)
1138        ))
1139    }
1140
1141    #[test]
1142    fn test_issuing_distribution_no_name() {
1143        let crl = include_bytes!("../../tests/crls/crl.idp.no_distribution_point_name.der");
1144        // We should encounter an error parsing a CRL with an issuing distribution point extension
1145        // that has no distribution point name.
1146        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1147        assert!(matches!(
1148            result,
1149            Err(Error::UnsupportedCrlIssuingDistributionPoint)
1150        ))
1151    }
1152
1153    #[test]
1154    fn revocation_reasons() {
1155        // Test that we can convert the allowed u8 revocation reason code values into the expected
1156        // revocation reason variant.
1157        let testcases: Vec<(u8, RevocationReason)> = vec![
1158            (0, RevocationReason::Unspecified),
1159            (1, RevocationReason::KeyCompromise),
1160            (2, RevocationReason::CaCompromise),
1161            (3, RevocationReason::AffiliationChanged),
1162            (4, RevocationReason::Superseded),
1163            (5, RevocationReason::CessationOfOperation),
1164            (6, RevocationReason::CertificateHold),
1165            // Note: 7 is unused.
1166            (8, RevocationReason::RemoveFromCrl),
1167            (9, RevocationReason::PrivilegeWithdrawn),
1168            (10, RevocationReason::AaCompromise),
1169        ];
1170        for tc in testcases.iter() {
1171            let (id, expected) = tc;
1172            let actual = <u8 as TryInto<RevocationReason>>::try_into(*id)
1173                .expect("unexpected reason code conversion error");
1174            assert_eq!(actual, *expected);
1175            #[cfg(feature = "alloc")]
1176            {
1177                // revocation reasons should be Debug.
1178                println!("{actual:?}");
1179            }
1180        }
1181
1182        // Unsupported/unknown revocation reason codes should produce an error.
1183        let res = <u8 as TryInto<RevocationReason>>::try_into(7);
1184        assert!(matches!(res, Err(Error::UnsupportedRevocationReason)));
1185
1186        // The iterator should produce all possible revocation reason variants.
1187        let expected = testcases
1188            .iter()
1189            .map(|(_, reason)| *reason)
1190            .collect::<Vec<_>>();
1191        let actual = RevocationReason::iter().collect::<Vec<_>>();
1192        assert_eq!(actual, expected);
1193    }
1194
1195    #[test]
1196    // redundant clone, clone_on_copy allowed to verify derived traits.
1197    #[expect(clippy::redundant_clone)]
1198    fn test_derived_traits() {
1199        let crl =
1200            BorrowedCertRevocationList::from_der(include_bytes!("../../tests/crls/crl.valid.der"))
1201                .unwrap();
1202        println!("{crl:?}"); // BorrowedCertRevocationList should be debug.
1203
1204        let owned_crl = crl.to_owned().unwrap();
1205        println!("{owned_crl:?}"); // OwnedCertRevocationList should be debug.
1206        let _ = owned_crl.clone(); // OwnedCertRevocationList should be clone.
1207
1208        let mut revoked_certs = crl.into_iter();
1209        println!("{revoked_certs:?}"); // RevokedCert should be debug.
1210
1211        let revoked_cert = revoked_certs.next().unwrap().unwrap();
1212        println!("{revoked_cert:?}"); // BorrowedRevokedCert should be debug.
1213
1214        let owned_revoked_cert = revoked_cert.to_owned();
1215        println!("{owned_revoked_cert:?}"); // OwnedRevokedCert should be debug.
1216        let _ = owned_revoked_cert.clone(); // OwnedRevokedCert should be clone.
1217    }
1218
1219    #[test]
1220    fn test_enum_conversions() {
1221        let crl =
1222            include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1223        let borrowed_crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1224        let owned_crl = borrowed_crl.to_owned().unwrap();
1225
1226        // It should be possible to convert a BorrowedCertRevocationList to a CertRevocationList.
1227        let _crl = CertRevocationList::from(borrowed_crl);
1228        // And similar for an OwnedCertRevocationList.
1229        let _crl = CertRevocationList::from(owned_crl);
1230    }
1231
1232    #[test]
1233    fn test_crl_authoritative_issuer_mismatch() {
1234        let crl = include_bytes!("../../tests/crls/crl.valid.der");
1235        let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1236
1237        let ee = CertificateDer::from(
1238            &include_bytes!("../../tests/client_auth_revocation/no_ku_chain.ee.der")[..],
1239        );
1240        let ee = EndEntityCert::try_from(&ee).unwrap();
1241        let path = PartialPath::new(&ee);
1242
1243        // The CRL should not be authoritative for an EE issued by a different issuer.
1244        assert!(!crl.authoritative(&path.node()));
1245    }
1246
1247    #[test]
1248    fn test_crl_authoritative_no_idp_no_cert_dp() {
1249        let crl =
1250            include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1251        let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1252
1253        let ee = CertificateDer::from(
1254            &include_bytes!("../../tests/client_auth_revocation/ku_chain.ee.der")[..],
1255        );
1256        let ee = EndEntityCert::try_from(&ee).unwrap();
1257        let path = PartialPath::new(&ee);
1258
1259        // The CRL should be considered authoritative, the issuers match, the CRL has no IDP and the
1260        // cert has no CRL DPs.
1261        assert!(crl.authoritative(&path.node()));
1262    }
1263
1264    #[test]
1265    fn test_crl_expired() {
1266        let crl = include_bytes!("../../tests/crls/crl.valid.der");
1267        let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1268        //  Friday, February 2, 2024 8:26:19 PM GMT
1269        let time = UnixTime::since_unix_epoch(Duration::from_secs(1_706_905_579));
1270        assert!(matches!(
1271            crl.check_expiration(time),
1272            Err(Error::CrlExpired { .. })
1273        ));
1274    }
1275
1276    #[test]
1277    fn test_crl_not_expired() {
1278        let crl = include_bytes!("../../tests/crls/crl.valid.der");
1279        let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1280        // Wednesday, October 19, 2022 8:12:06 PM GMT
1281        let expiration_time = 1_666_210_326;
1282        let time = UnixTime::since_unix_epoch(Duration::from_secs(expiration_time - 1000));
1283
1284        assert!(matches!(crl.check_expiration(time), Ok(())));
1285    }
1286
1287    #[test]
1288    fn test_construct_owned_crl() {
1289        // It should be possible to construct an owned CRL directly from DER without needing
1290        // to build a borrowed representation first.
1291        let crl =
1292            include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1293        assert!(OwnedCertRevocationList::from_der(crl).is_ok())
1294    }
1295}