rpki 0.19.3

A library for validating and creating RPKI data.
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
//! Certificate Revocation Lists for RPKI.
//!
//! Much like for certificates, RPKI reuses X.509 for its certificate
//! revocation lists (CRLs), limiting the values that are allowed in the
//! various fields.
//!
//! This module implements the CRLs themselves via the type [`Crl`] as well
//! as a [`CrlStore`] that can keep several CRLs which may be helpful during
//! validation.
//!
//! The RPKI CRL profile is defined in RFC 6487 based on the Internet RPIX
//! profile defined in RFC 5280.
use std::{fmt, ops};
use std::collections::HashSet;
use std::str::FromStr;
use bcder::{decode, encode};
use bcder::{Captured, Mode, OctetString, Oid, Tag};
use bcder::decode::{ContentError, DecodeError, IntoSource, Source};
use bcder::encode::PrimitiveContent;
use bytes::Bytes;
use crate::{oid, uri};
use crate::crypto::{
    KeyIdentifier, PublicKey, RpkiSignatureAlgorithm, SignatureAlgorithm,
    Signer, SigningError,
};
#[cfg(feature = "serde")] use crate::util::base64;
use super::error::VerificationError;
use super::x509::{
    Name, RepresentationError, Serial, SignedData, Time, encode_extension,
};


//------------ Crl -----------------------------------------------------------

/// An RPKI certificate revocation list.
///
/// A value of this type is the result of parsing a CRL file found in the
/// RPKI repository. You can use the `decode` function for parsing a CRL out
/// of such a file.
#[derive(Clone, Debug)]
pub struct Crl {
    /// The outer structure of the CRL.
    signed_data: SignedData,

    /// The payload of the CRL.
    tbs: TbsCertList<RevokedCertificates>,

    /// An optional cache of the serial numbers in the CRL.
    serials: Option<HashSet<Serial>>,
}

/// # Data Access
///
impl Crl {
    /// Returns a reference to the signed data wrapper.
    pub fn signed_data(&self) -> &SignedData {
        &self.signed_data
    }

    /// Returns a reference to the payload.
    ///
    /// This also available via the `AsRef` and `Deref` impls.
    pub fn as_cert_list(&self) -> &TbsCertList<RevokedCertificates> {
        &self.tbs
    }

    /// Caches the serial numbers in the CRL.
    ///
    /// Doing this will speed up calls to `contains` later on at the price
    /// of additional memory consumption.
    pub fn cache_serials(&mut self) {
        self.serials = Some(
            self.tbs.revoked_certs.iter().map(|entry| entry.user_certificate)
                .collect()
        );
    }

    /// Returns whether the given serial number is on this revocation list.
    pub fn contains(&self, serial: Serial) -> bool {
        match self.serials {
            Some(ref set) => set.contains(&serial),
            None => self.tbs.revoked_certs.contains(serial)
        }
    }
}


/// # Decode, Validate, and Encode
///
impl Crl {
    /// Parses a source as a certificate revocation list.
    pub fn decode<S: IntoSource>(
        source: S
    ) -> Result<Self, DecodeError<<S::Source as Source>::Error>> {
        Mode::Der.decode(source, Self::take_from)
    }

    /// Takes an encoded CRL from the beginning of a constructed value.
    pub fn take_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        cons.take_sequence(Self::from_constructed)
    }

    /// Takes an encoded CRL from the beginning of a constructed value.
    pub fn take_opt_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Option<Self>, DecodeError<S::Error>> {
        cons.take_opt_sequence(Self::from_constructed)
    }

    /// Parses the content of a certificate revocation list.
    pub fn from_constructed<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        let signed_data = SignedData::from_constructed(cons)?;
        let tbs = signed_data.data().clone().decode(
            TbsCertList::take_from
        ).map_err(DecodeError::convert)?;
        if tbs.signature != *signed_data.signature().algorithm() {
            return Err(cons.content_err(
                "CRL signature algorithm mismatch"
            ))
        }
        Ok(Self { signed_data, tbs, serials: None })
    }

    /// Verifies the certificate revocation list’s signature.
    ///
    /// The signature is verified against the provided public key.
    pub fn verify_signature(
        &self,
        public_key: &PublicKey
    ) -> Result<(), VerificationError> {
        self.signed_data.verify_signature(
            public_key
        ).map_err(VerificationError::new)
    }

    pub fn encode_ref(&self) -> impl encode::Values + '_ {
        self.signed_data.encode_ref()
    }

    /// Returns a captured encoding of the CRL.
    pub fn to_captured(&self) -> Captured {
        Captured::from_values(Mode::Der, self.encode_ref())
    }
}


//--- Deref and AsRef

impl ops::Deref for Crl {
    type Target = TbsCertList<RevokedCertificates>;

    fn deref(&self) -> &Self::Target {
        &self.tbs
    }
}

impl AsRef<TbsCertList<RevokedCertificates>> for Crl {
    fn as_ref(&self) -> &TbsCertList<RevokedCertificates> {
        &self.tbs
    }
}


//--- Deserialize and Serialize

#[cfg(feature = "serde")]
impl serde::Serialize for Crl {
    fn serialize<S: serde::Serializer>(
        &self, serializer: S
    ) -> Result<S::Ok, S::Error> {
        let bytes = self.to_captured().into_bytes();
        let b64 = base64::Serde.encode(&bytes);
        b64.serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Crl {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D
    ) -> Result<Self, D::Error> {
        use serde::de;

        let s = String::deserialize(deserializer)?;
        let decoded = base64::Serde.decode(&s).map_err(de::Error::custom)?;
        let bytes = bytes::Bytes::from(decoded);
        Crl::decode(bytes).map_err(de::Error::custom)
    }
}


//------------ TbsCertList ---------------------------------------------------

/// The payload of a certificate revocation list.
///
/// This type is generic over the list of revoked certificates.
#[derive(Clone, Debug)]
pub struct TbsCertList<C> {
    /// The algorithm used for signing the certificate.
    signature: RpkiSignatureAlgorithm,

    /// The name of the issuer.
    ///
    /// This isn’t really used in RPKI at all.
    issuer: Name,

    /// The time this version of the CRL was created.
    this_update: Time,

    /// The time the next version of the CRL is likely to be created.
    next_update: Time,

    /// The list of revoked certificates.
    revoked_certs: C,

    /// Authority Key Identifier
    authority_key_id: KeyIdentifier,

    /// CRL Number
    crl_number: Serial,
}

/// # Creating and Converting
///
impl<C> TbsCertList<C> {
    /// Creates a new value from the necessary data.
    pub fn new(
        signature: RpkiSignatureAlgorithm,
        issuer: Name,
        this_update: Time,
        next_update: Time,
        revoked_certs: C,
        authority_key_id: KeyIdentifier,
        crl_number: Serial
    ) -> Self {
        Self {
            signature,
            issuer,
            this_update,
            next_update,
            revoked_certs,
            authority_key_id,
            crl_number
        }
    }

    /// Converts the value into a signed CRL.
    pub fn into_crl<S: Signer>(
        self,
        signer: &S,
        key: &S::KeyId
    ) -> Result<Crl, SigningError<S::Error>>
    where
        C: IntoIterator<Item=CrlEntry>,
        <C as IntoIterator>::IntoIter: Clone
    {
        let tbs: TbsCertList<RevokedCertificates> = self.into();
        let data = Captured::from_values(Mode::Der, tbs.encode_ref());
        let signature = signer.sign(key, tbs.signature, &data)?;
        Ok(Crl {
            signed_data: SignedData::new(data, signature),
            tbs,
            serials: None,
        })
    }
}

/// # Data Access
///
impl<C> TbsCertList<C> {
    /// Returns the algorithm used by the issuer to sign the CRL.
    pub fn signature(&self) -> RpkiSignatureAlgorithm {
        self.signature
    }

    /// Sets the signature algorithm.
    pub fn set_signature(&mut self, signature: RpkiSignatureAlgorithm) {
        self.signature = signature
    }

    /// Returns a reference to the issuer name of the CRL.
    pub fn issuer(&self) -> &Name {
        &self.issuer
    }

    /// Sets the issuer name.
    pub fn set_issuer(&mut self, issuer: Name) {
        self.issuer = issuer
    }

    /// Returns the update time of this CRL.
    pub fn this_update(&self) -> Time {
        self.this_update
    }

    /// Sets the update time of this CRL.
    pub fn set_this_update(&mut self, this_update: Time) {
        self.this_update = this_update
    }

    /// Returns the time of next update if present.
    pub fn next_update(&self) -> Time {
        self.next_update
    }

    /// Returns whether the CRL’s nextUpdate time has passed.
    pub fn is_stale(&self) -> bool {
        self.next_update < Time::now()
    }

    /// Sets the time of next update.
    pub fn set_next_update(&mut self, next_update: Time) {
        self.next_update = next_update
    }

    /// Returns a reference to the list of revoked certificates.
    pub fn revoked_certs(&self) -> &C {
        &self.revoked_certs
    }

    /// Returns a mutable reference to the list of revoked certificates.
    pub fn revoked_certs_mut(&mut self) -> &mut C {
        &mut self.revoked_certs
    }

    /// Sets the list of revoked certificates.
    pub fn set_revoked_certs(&mut self, revoked_certs: C) {
        self.revoked_certs = revoked_certs
    }

    /// Returns a reference to the authority key identifier if present.
    pub fn authority_key_identifier(&self) -> &KeyIdentifier {
        &self.authority_key_id
    }

    /// Sets the authority key identifier.
    pub fn set_authority_key_identifier(&mut self, id: KeyIdentifier) {
        self.authority_key_id = id
    }

    /// Returns the CRL number.
    pub fn crl_number(&self) -> Serial {
        self.crl_number
    }

    /// Sets the CRL number.
    pub fn set_crl_number(&mut self, crl_number: Serial) {
        self.crl_number = crl_number
    }
}


/// # Decoding and Encoding
///
impl TbsCertList<RevokedCertificates> {
    /// Takes a value from the beginning of a encoded constructed value.
    pub fn take_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        cons.take_sequence(|cons| {
            // version. Technically it is optional but we need v2, so it must
            // actually be there. v2 is encoded as an integer of value 1.
            cons.skip_u8_if(1)?;
            let signature = RpkiSignatureAlgorithm::x509_take_from(cons)?;
            let issuer = Name::take_from(cons)?;
            let this_update = Time::take_from(cons)?;
            let next_update = Time::take_from(cons)?;
            let revoked_certs = RevokedCertificates::take_from(cons)?;
            let mut authority_key_id = None;
            let mut crl_number = None;
            cons.take_constructed_if(Tag::CTX_0, |cons| {
                cons.take_sequence(|cons| {
                    while let Some(()) = cons.take_opt_sequence(|cons| {
                        let id = Oid::take_from(cons)?;
                        let _critical = cons.take_opt_bool()?.unwrap_or(false);
                        let value = OctetString::take_from(cons)?;
                        Mode::Der.decode(value, |content| {
                            if id == oid::CE_AUTHORITY_KEY_IDENTIFIER {
                                Self::take_authority_key_identifier(
                                    content, &mut authority_key_id
                                )
                            }
                            else if id == oid::CE_CRL_NUMBER {
                                Self::take_crl_number(
                                    content, &mut crl_number
                                )
                            }
                            else {
                                // RFC 6487 says that no other extensions are
                                // allowed. So we fail even if there is only
                                // non-critical extension.
                                Err(content.content_err(
                                    InvalidExtension::new(id)
                                ))
                            }
                        }).map_err(DecodeError::convert)
                    })? { }
                    Ok(())
                })
            })?;
            let authority_key_id = authority_key_id.ok_or_else(|| {
                cons.content_err(
                    "missing Authority Key Identifier extension"
                )
            })?;
            let crl_number = crl_number.ok_or_else(|| {
                cons.content_err("missing CRL Number extension")
            })?;
            Ok(Self {
                signature,
                issuer,
                this_update,
                next_update,
                revoked_certs,
                authority_key_id,
                crl_number
            })
        })
    }

    /// Parses the Authority Key Identifier extension.
    fn take_authority_key_identifier<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        authority_key_id: &mut Option<KeyIdentifier>,
    ) -> Result<(), DecodeError<S::Error>> {
        if authority_key_id.is_some() {
            Err(cons.content_err(
                "duplicate Authority Key Identifier extension"
            ))
        }
        else {
            *authority_key_id = Some(
                cons.take_sequence(|cons| {
                    cons.take_value_if(Tag::CTX_0, KeyIdentifier::from_content)
                })?
            );
            Ok(())
        }
    }

    /// Parses the CRL Number extension.
    fn take_crl_number<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        crl_number: &mut Option<Serial>,
    ) -> Result<(), DecodeError<S::Error>> {
        if crl_number.is_some() {
            Err(cons.content_err("duplicate CRL Number extension"))
        }
        else {
            *crl_number = Some(Serial::take_from(cons)?);
            Ok(())
        }
    }

    /// Returns a value encoder for a reference to this value.
    pub fn encode_ref(&self) -> impl encode::Values + '_ {
        encode::sequence((
            1.encode(), // version
            self.signature.x509_encode(),
            self.issuer.encode_ref(),
            self.this_update.encode_varied(),
            self.next_update.encode_varied(),
            self.revoked_certs.encode_ref(),
            encode::sequence_as(Tag::CTX_0, 
                encode::sequence((
                    encode_extension(
                        &oid::CE_AUTHORITY_KEY_IDENTIFIER, false,
                        encode::sequence(
                            self.authority_key_id.encode_ref_as(Tag::CTX_0)
                        )
                    ),
                    encode_extension(
                        &oid::CE_CRL_NUMBER, false,
                        self.crl_number.encode()
                    ),
                ))
            )
        ))
    }
}


//--- From

impl<C> From<TbsCertList<C>> for TbsCertList<RevokedCertificates>
where
    C: IntoIterator<Item = CrlEntry>,
    <C as IntoIterator>::IntoIter: Clone
{
    fn from(list: TbsCertList<C>) -> Self {
        Self {
            signature: list.signature,
            issuer: list.issuer,
            this_update: list.this_update,
            next_update: list.next_update,
            revoked_certs: RevokedCertificates::from_iter(list.revoked_certs),
            authority_key_id: list.authority_key_id,
            crl_number: list.crl_number,
        }
    }
}

//------------ RevokedCertificates ------------------------------------------

/// The list of revoked certificates.
///
/// A value of this type wraps the bytes of the DER encoded list. You can
/// check whether a certain serial number is part of this list via the
/// `contains` method.
#[derive(Clone, Debug)]
pub struct RevokedCertificates(Captured);

impl RevokedCertificates {
    /// Create an empty RevokedCertificates.
    pub fn empty() -> Self {
        let entries: Vec<CrlEntry> = vec![];
        Self::from_iter(entries)
    }

    /// Takes a revoked certificates list from the beginning of a value.
    pub fn take_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        let res = cons.take_opt_sequence(|cons| {
            cons.capture(|cons| {
                while CrlEntry::take_opt_from(cons)?.is_some() { }
                Ok(())
            })
        })?;
        Ok(RevokedCertificates(match res {
            Some(res) => res,
            None => Captured::empty(Mode::Der)
        }))
    }

    /// Returns whether the given serial number is contained on this list.
    ///
    /// The method walks over the list, decoding it on the fly and checking
    /// each entry.
    pub fn contains(&self, serial: Serial) -> bool {
        Mode::Der.decode(self.0.as_ref(), |cons| {
            while let Some(entry) = CrlEntry::take_opt_from(cons).unwrap() {
                if entry.user_certificate == serial {
                    return Ok(true)
                }
            }
            Ok(false)
        }).unwrap()
    }

    /// Returns an iterator over the entries in the list.
    pub fn iter(&self) -> RevokedCertificatesIter {
        RevokedCertificatesIter(self.0.clone())
    }

    /// Returns a value encoder for a reference to the value.
    pub fn encode_ref(&self) -> impl encode::Values + '_ {
        (!self.0.is_empty()).then(|| {
            encode::sequence(&self.0)
        })
    }

    /// Create a value from an iterator over CRL entries.
    ///
    /// This can’t be the `FromIterator` trait because of the `Clone`
    /// requirement on `I::IntoIter`
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = CrlEntry>,
        <I as IntoIterator>::IntoIter: Clone
    {
        RevokedCertificates(Captured::from_values(
            Mode::Der, encode::iter(
                iter.into_iter().map(CrlEntry::encode)
            )
        ))
    }
}


//------------ RevokedCertificatesIter ---------------------------------------

/// An iterator over the entries in the list of revoked certificates.
#[derive(Clone, Debug)]
pub struct RevokedCertificatesIter(Captured);

impl Iterator for RevokedCertificatesIter {
    type Item = CrlEntry;

    #[allow(clippy::redundant_closure)]
    fn next(&mut self) -> Option<Self::Item> {
        self.0.decode_partial(|cons| CrlEntry::take_opt_from(cons)).unwrap()
    }
}


//------------ CrlEntry ------------------------------------------------------

/// An entry in the revoked certificates list.
#[derive(Clone, Copy, Debug)]
pub struct CrlEntry {
    /// The serial number of the revoked certificate.
    user_certificate: Serial,

    /// The time of revocation.
    revocation_date: Time,
}

impl CrlEntry {
    /// Creates a new CrlEntry for inclusion on a new Crl
    pub fn new(user_certificate: Serial, revocation_date: Time) -> Self {
        CrlEntry { user_certificate, revocation_date }
    }

    /// Takes a single CRL entry from the beginning of a constructed value.
    pub fn take_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        cons.take_sequence(Self::from_constructed)
    }

    /// Takes an optional CRL entry from the beginning of a constructed value.
    pub fn take_opt_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Option<Self>, DecodeError<S::Error>> {
        cons.take_opt_sequence(Self::from_constructed)
    }

    /// Parses the content of a CRL entry.
    pub fn from_constructed<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        Ok(CrlEntry {
            user_certificate: Serial::take_from(cons)?,
            revocation_date: Time::take_from(cons)?,
            // crlEntryExtensions are forbidden by RFC 6487.
        })
    }

    /// Returns a value encoder for the entry.
    pub fn encode(self) -> impl encode::Values {
        encode::sequence((
            self.user_certificate.encode(),
            self.revocation_date.encode_varied(),
        ))
    }
}


//--- FromStr

impl FromStr for CrlEntry {
    type Err = RepresentationError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some(pos) = s.find('@') {
            Ok(CrlEntry::new(
                Serial::from_str(&s[..pos])?,
                Time::from_str(&s[pos + 1..]).map_err(|_| RepresentationError)?
            ))
        }
        else {
            Serial::from_str(s).map(|serial| {
                CrlEntry::new(serial, Time::now())
            })
        }
    }
}


//------------ CrlStore ------------------------------------------------------

/// A place to cache CRLs for reuse.
///
/// This type allows to store CRLs you have seen in case you may need them
/// again soon. This is useful when validating the objects issued by a CA as
/// they likely all refer to the same CRL, so keeping it around makes sense.
///
/// Since the new rules for manifest handling clarify that each CA must only
/// ever have exactly one CRL at any given time, this type is now obsolete.
#[deprecated(since = "0.10.0", note = "new manifest rules only allow one CRL")]
#[allow(deprecated)]
#[derive(Clone, Debug)]
pub struct CrlStore {
    /// The CRLs in the store.
    ///
    /// This is a simple vector because most likely we’ll only ever have one.
    crls: Vec<(uri::Rsync, Crl)>,

    /// Should we cache the serials in our CRLs?
    cache_serials: bool,
}

#[allow(deprecated)]
impl CrlStore {
    /// Creates a new CRL store.
    pub fn new() -> Self {
        CrlStore {
            crls: Vec::new(),
            cache_serials: false,
        }
    }

    /// Enables caching of serial numbers in the stored CRLs.
    pub fn enable_serial_caching(&mut self) {
        self.cache_serials = true
    }

    /// Adds an entry to the CRL store.
    ///
    /// The CRL is keyed by its rsync `uri`.
    pub fn push(&mut self, uri: uri::Rsync, mut crl: Crl) {
        if self.cache_serials {
            crl.cache_serials()
        }
        self.crls.push((uri, crl))
    }

    /// Returns a reference to a CRL if it is available in the store.
    pub fn get(&self, uri: &uri::Rsync) -> Option<&Crl> {
        for (stored_uri, crl) in &self.crls {
            if *stored_uri == *uri {
                return Some(crl)
            }
        }
        None
    }
}

#[allow(deprecated)]
impl Default for CrlStore {
    fn default() -> Self {
        Self::new()
    }
}


//============ Error Types ===================================================

//------------ InvalidExtension ----------------------------------------------

/// An invalid certificate extension was encountered.
#[derive(Clone, Debug)]
pub struct InvalidExtension {
    oid: Oid<Bytes>,
}

impl InvalidExtension {
    pub(crate) fn new(oid: Oid<Bytes>) -> Self {
        InvalidExtension { oid }
    }
}

impl From<InvalidExtension> for ContentError {
    fn from(err: InvalidExtension) -> Self {
        ContentError::from_boxed(Box::new(err))
    }
}

impl fmt::Display for InvalidExtension {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "invalid extension {}", self.oid)
    }
}


//============ Tests =========================================================

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

    #[test]
    fn decode_certs() {
        Crl::decode(
            include_bytes!("../../test-data/repository/ta.crl").as_ref()
        ).unwrap();
        Crl::decode(
            include_bytes!("../../test-data/repository/ca1.crl").as_ref()
        ).unwrap();
    }

    #[test]
    #[cfg(feature = "serde")]
    fn serde_crl() {
        let der = include_bytes!("../../test-data/repository/ta.crl");
        let crl = Crl::decode(bytes::Bytes::from_static(der)).unwrap();

        let serialized = serde_json::to_string(&crl).unwrap();
        let deser_crl: Crl = serde_json::from_str(&serialized).unwrap();

        assert_eq!(
            crl.to_captured().into_bytes(),
            deser_crl.to_captured().into_bytes()
        );
    }

    #[test]
    #[cfg(feature = "serde")]
    fn compat_de_crl() {
        serde_json::from_slice::<Crl>(include_bytes!(
            "../../test-data/repository/serde-compat/crl.json"
        )).unwrap();
    }
}

#[cfg(all(test, feature="softkeys"))]
mod signer_test {
    use super::*;
    use crate::crypto::PublicKeyFormat;
    use crate::crypto::softsigner::OpenSslSigner;

    #[test]
    fn build_ta_cert() {
        // CRL with two CrlEntries.
        let signer = OpenSslSigner::new();
        let key = signer.create_key(PublicKeyFormat::Rsa).unwrap();
        let pubkey = signer.get_key_info(&key).unwrap();
        let crl = TbsCertList::new(
            Default::default(),
            pubkey.to_subject_name(),
            Time::now(),
            Time::tomorrow(),
            vec![
                CrlEntry::new(12u64.into(), Time::now()),
                CrlEntry::new(42u64.into(), Time::now())
            ],
            pubkey.key_identifier(),
            12u64.into()
        );
        let crl = crl.into_crl(&signer, &key).unwrap().to_captured();
        let crl = Crl::decode(crl.as_slice()).unwrap();
        assert_eq!(
            crl.revoked_certs().iter().collect::<Vec<_>>().len(),
            2
        );

        // CRL with no CrlEntries.
        let crl = TbsCertList::new(
            Default::default(),
            pubkey.to_subject_name(),
            Time::now(),
            Time::tomorrow(),
            vec![],
            pubkey.key_identifier(),
            12u64.into()
        );
        let crl = crl.into_crl(&signer, &key).unwrap().to_captured();
        let crl = Crl::decode(crl.as_slice()).unwrap();
        assert!(crl.revoked_certs().iter().next().is_none());
    }
}