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#[derive(Debug, Hash)]
30pub enum CertRevocationList<'a> {
31 #[cfg(feature = "alloc")]
33 Owned(OwnedCertRevocationList),
34 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 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 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 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 pub(crate) fn authoritative(&self, path: &PathNode<'_>) -> bool {
99 if self.issuer() != path.cert.issuer() {
102 return false;
103 }
104
105 let crl_idp = match self.issuing_distribution_point() {
106 Some(crl_idp) => {
109 match IssuingDistributionPoint::from_der(untrusted::Input::from(crl_idp)) {
110 Ok(crl_idp) => crl_idp,
111 Err(_) => return false, }
113 }
114 None => return true,
119 };
120
121 crl_idp.authoritative_for(path)
122 }
123
124 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 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#[cfg(feature = "alloc")]
165#[derive(Debug, Clone, Hash)]
166pub struct OwnedCertRevocationList {
167 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 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 Ok(self
203 .revoked_certs
204 .get(serial)
205 .map(|owned_revoked_cert| owned_revoked_cert.borrow()))
206 }
207}
208
209#[derive(Debug)]
213pub struct BorrowedCertRevocationList<'a> {
214 signed_data: SignedData<'a>,
216
217 issuer: untrusted::Input<'a>,
220
221 issuing_distribution_point: Option<untrusted::Input<'a>>,
223
224 revoked_certs: untrusted::Input<'a>,
226
227 next_update: UnixTime,
228}
229
230impl<'a> BorrowedCertRevocationList<'a> {
231 pub fn from_der(crl_der: &'a [u8]) -> Result<Self, Error> {
242 der::read_all(untrusted::Input::from(crl_der))
243 }
244
245 #[cfg(feature = "alloc")]
248 pub fn to_owned(&self) -> Result<OwnedCertRevocationList, Error> {
249 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 Standard(20) => {
276 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 Ok(())
293 }
294
295 Standard(27) => Err(Error::UnsupportedDeltaCrl),
298
299 Standard(28) => {
302 set_extension_once(&mut self.issuing_distribution_point, || Ok(extension.value))
303 }
304
305 Standard(35) => Ok(()),
308
309 _ => 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 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 if u8::from_der(tbs_cert_list)? != 1 {
363 return Err(Error::UnsupportedCrlVersion);
364 }
365
366 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 let issuer = der::expect_tag(tbs_cert_list, Tag::Sequence)?;
377
378 UnixTime::from_der(tbs_cert_list)?;
384
385 let next_update = UnixTime::from_der(tbs_cert_list)?;
390
391 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 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 crl.remember_extension(&Extension::from_der(extension)?)
439 },
440 )
441 },
442 )?;
443
444 Ok(crl)
445 })?;
446
447 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 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), _ => Err(Error::BadDer),
527 }
528 }
529
530 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 if result.only_contains_attribute_certs {
568 return Err(Error::MalformedExtensions);
569 }
570
571 if result.indirect_crl {
573 return Err(Error::UnsupportedIndirectCrl);
574 }
575
576 if result.only_some_reasons.is_some() {
578 return Err(Error::UnsupportedRevocationReasonsPartitioning);
579 }
580
581 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 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 pub(crate) fn authoritative_for(&self, node: &PathNode<'a>) -> bool {
614 assert!(!self.only_contains_attribute_certs); if self.only_contains_ca_certs && node.role() != Role::Issuer
618 || self.only_contains_user_certs && node.role() != Role::EndEntity
619 {
620 return false; }
622
623 let Some(cert_dps) = node.cert.crl_distribution_points() else {
624 return true;
627 };
628
629 for cert_dp in cert_dps {
630 let Ok(cert_dp) = cert_dp else {
631 continue; };
633
634 if cert_dp.crl_issuer.is_some() || cert_dp.reasons.is_some() {
637 continue; }
639
640 let Ok(Some(DistributionPointName::FullName(dp_general_names))) = cert_dp.names()
641 else {
642 continue; };
644
645 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, Err(_) => continue, };
653
654 let Ok(Some(DistributionPointName::FullName(idp_general_names))) = self.names()
655 else {
656 return false; };
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; }
666 _ => continue, }
668 }
669 }
670 }
671
672 false
673 }
674}
675
676#[cfg(feature = "alloc")]
683#[derive(Clone, Debug, Hash)]
684pub struct OwnedRevokedCert {
685 pub serial_number: Vec<u8>,
687
688 pub revocation_date: UnixTime,
690
691 pub reason_code: Option<RevocationReason>,
696
697 pub invalidity_date: Option<UnixTime>,
701}
702
703#[cfg(feature = "alloc")]
704impl OwnedRevokedCert {
705 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#[derive(Debug)]
721pub struct BorrowedRevokedCert<'a> {
722 pub serial_number: &'a [u8],
724
725 pub revocation_date: UnixTime,
727
728 pub reason_code: Option<RevocationReason>,
733
734 pub invalidity_date: Option<UnixTime>,
738}
739
740impl<'a> BorrowedRevokedCert<'a> {
741 #[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 Standard(21) => {
759 set_extension_once(&mut self.reason_code, || der::read_all(extension.value))
760 }
761
762 Standard(24) => set_extension_once(&mut self.invalidity_date, || {
764 extension.value.read_all(Error::BadDer, UnixTime::from_der)
765 }),
766
767 Standard(29) => Err(Error::UnsupportedIndirectCrl),
775
776 _ => 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 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 if der.at_end() {
818 return Ok(revoked_cert);
819 }
820
821 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 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#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
862#[expect(missing_docs)] pub enum RevocationReason {
864 Unspecified = 0,
867 KeyCompromise = 1,
868 CaCompromise = 2,
869 AffiliationChanged = 3,
870 Superseded = 4,
871 CessationOfOperation = 5,
872 CertificateHold = 6,
873 RemoveFromCrl = 8,
876 PrivilegeWithdrawn = 9,
877 AaCompromise = 10,
878}
879
880impl RevocationReason {
881 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 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 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 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 let crl_issuing_dp = crl
954 .issuing_distribution_point
955 .expect("missing crl distribution point DER");
956
957 #[cfg(feature = "alloc")]
958 {
959 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 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 assert!(crl_issuing_dp.only_some_reasons.is_none());
978
979 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 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 assert!(crl_issuing_dp.only_contains_user_certs);
1014
1015 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 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 assert!(crl_issuing_dp.only_contains_ca_certs);
1043
1044 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 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 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 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 let crl = include_bytes!("../../tests/crls/crl.idp.invalid.bool.der");
1089 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 let crl = include_bytes!("../../tests/crls/crl.idp.explicit.false.bool.der");
1099 let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1100
1101 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 let crl = include_bytes!("../../tests/crls/crl.idp.unknown.tag.der");
1113 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 let crl = include_bytes!("../../tests/crls/crl.idp.invalid.name.der");
1123
1124 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 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 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 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 (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 println!("{actual:?}");
1179 }
1180 }
1181
1182 let res = <u8 as TryInto<RevocationReason>>::try_into(7);
1184 assert!(matches!(res, Err(Error::UnsupportedRevocationReason)));
1185
1186 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 #[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:?}"); let owned_crl = crl.to_owned().unwrap();
1205 println!("{owned_crl:?}"); let _ = owned_crl.clone(); let mut revoked_certs = crl.into_iter();
1209 println!("{revoked_certs:?}"); let revoked_cert = revoked_certs.next().unwrap().unwrap();
1212 println!("{revoked_cert:?}"); let owned_revoked_cert = revoked_cert.to_owned();
1215 println!("{owned_revoked_cert:?}"); let _ = owned_revoked_cert.clone(); }
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 let _crl = CertRevocationList::from(borrowed_crl);
1228 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 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 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 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 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 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}