rpgpie 0.9.0

Experimental high level API for rPGP
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
use std::time::SystemTime;

use pgp::{
    composed::{SignedKeyDetails, SignedPublicKey, SignedPublicSubKey},
    crypto::{aead::AeadAlgorithm, hash::HashAlgorithm, sym::SymmetricKeyAlgorithm},
    packet::{Features, Signature, SubpacketData, SubpacketType, UserId},
    types::{
        Duration,
        Fingerprint,
        KeyDetails,
        KeyId,
        KeyVersion,
        SignedUser,
        SignedUserAttribute,
        Tag,
        Timestamp,
    },
};

use crate::{
    Error,
    certificate::{Certificate, SignatureVerifier},
    key::{ComponentKeyPub, SignedComponentKeyPub},
    policy,
    primary_userid::primary_user_id_binding_at,
    signature,
    signature::SigStack,
    util,
};

/// A layer on top of [Certificate] that filters out any signatures that we don't consider valid.
///
/// A `Checked` certificate only contains Signatures that have been verified to be cryptographically
/// correct.
/// See <https://openpgp.dev/book/verification.html#when-are-signatures-valid>
///
/// This is a precondition for signatures being considered fully valid, but by itself insufficient.
///
/// Note: The checked representation currently removes all third-party signatures
/// (because they can't be cryptographically checked in the context of looking at an individual
/// certificate).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Checked {
    /// Unfiltered view of the SignedPublicKey that this Checked was created from
    original: SignedPublicKey,

    /// Checked and filtered representation of the original SignedPublicKey
    cspk: SignedPublicKey,

    /// Cached value for efficient third-party fp checks
    primary_fingerprint: Fingerprint,

    /// Cached value for efficient third-party fp checks
    primary_key_id: KeyId,
}

impl Checked {
    /// Produce a `Checked` view onto a `Certificate`.
    ///
    /// This operation checks all self-signatures for cryptographic validity, as well as
    /// conformance to policy.
    ///
    /// Third party signatures are not currently handled.
    pub fn new(cert: Certificate) -> Self {
        // Make a copy of all parts of the SignedPublicKey and drop all signatures that:
        // - are not cryptographically correct
        // - don't pass our policy checks (`signature_acceptable`)

        // TODO: store bad self-sigs and third-party sigs in a separate place

        // TODO: go look for any (valid/correct) hard revocations for the full cert,
        // and encode the result in a simple "cert is hard revoked" flag:
        //
        // -> any user id binding that claims to be primary
        // -> or direct signatures on the primary

        // TODO: Which parts of validity checking can/should be moved to [SigStack]?

        let original = cert.spk;

        // primary
        let primary = original.primary_key.clone();
        let primary_created = primary.created_at();

        // details
        let revocation_signatures: Vec<_> = original
            .details
            .revocation_signatures
            .iter()
            .filter(|s| signature::signature_acceptable(s)) // FIXME: could this filter out any important revocations?
            .filter(|s| signature::not_older_than(s, primary_created))
            .filter(|s| s.verify_key(&original.primary_key).is_ok())
            .cloned()
            .collect();

        let direct_signatures: Vec<_> = original
            .details
            .direct_signatures
            .iter()
            .filter(|s| signature::signature_acceptable(s))
            .filter(|s| signature::not_older_than(s, primary_created))
            .filter(|s| s.verify_key(&original.primary_key).is_ok())
            .cloned()
            .collect();

        let users: Vec<SignedUser> = original
            .details
            .users
            .iter()
            .map(|su| {
                let id = su.id.clone();
                let signatures = su
                    .signatures
                    .iter()
                    .filter(|s| signature::signature_acceptable(s))
                    .filter(|s| signature::not_older_than(s, primary_created))
                    .filter(|s| s.verify_certification(&primary, Tag::UserId, &id).is_ok())
                    .cloned()
                    .collect();

                SignedUser { id, signatures }
            })
            .collect();

        let user_attributes: Vec<SignedUserAttribute> = original
            .details
            .user_attributes
            .iter()
            .map(|sua| {
                let attr = sua.attr.clone();
                let signatures = sua
                    .signatures
                    .iter()
                    .filter(|s| signature::signature_acceptable(s))
                    .filter(|s| signature::not_older_than(s, primary_created))
                    .filter(|s| {
                        s.verify_certification(&primary, Tag::UserAttribute, &attr)
                            .is_ok()
                    })
                    .cloned()
                    .collect();

                SignedUserAttribute { attr, signatures }
            })
            .collect();

        let details = SignedKeyDetails {
            revocation_signatures,
            direct_signatures,
            users,
            user_attributes,
        };

        // subkeys
        let subkeys = original
            .public_subkeys
            .iter()
            .map(|sk| {
                let key = sk.key.clone();
                let signatures = sk
                    .signatures
                    .iter()
                    .filter(|s| signature::signature_acceptable(s))
                    .filter(|s| signature::not_older_than(s, primary_created))
                    .filter(|s| {
                        if let Err(e) = s.verify_subkey_binding(&original.primary_key, &key) {
                            log::warn!("Ignoring bad key binding signature {s:#?}: {e:?}");
                            return false;
                        }

                        // If there is an embedded back signature, we reject the entire signature if the back signature is cryptographically invalid
                        for embedded in s
                            .config()
                            .map(|c| &c.hashed_subpackets)
                            .into_iter()
                            .flatten()
                            .filter(|sp| sp.typ() == SubpacketType::EmbeddedSignature)
                        {
                            match &embedded.data {
                                SubpacketData::EmbeddedSignature(backsig) => {
                                    if !signature::signature_acceptable(backsig) {
                                        log::warn!(
                                            "Ignoring signature because of unacceptable embedded signature {backsig:#?}"
                                        );

                                        return false;
                                    }

                                    // FIXME: reject if signature creation time is before subkey creation time

                                    if let Err(e) =
                                        backsig.verify_primary_key_binding(
                                            &key,
                                            &original.primary_key,
                                        )
                                    {
                                        log::warn!(
                                            "Ignoring signature because embedded signature doesn't verify as correct {backsig:#?}: {e:?}"
                                        );

                                        return false;
                                    }
                                }
                                _ => unreachable!("no other subpacket types should come up, here"),
                            }
                        }

                        true
                    })
                    .cloned()
                    .collect();
                SignedPublicSubKey { key, signatures }
            })
            .collect();

        // combine
        let cspk = SignedPublicKey::new(primary, details, subkeys);

        log::debug!("Checked cert: {cspk:#?}");

        let primary_key_id = original.primary_key.legacy_key_id();
        let primary_fingerprint = original.primary_key.fingerprint();

        Self {
            original,
            cspk,
            primary_key_id,
            primary_fingerprint,
        }
    }

    // --- basic accessors

    /// The checked subset of the underlying SignedPublicKey.
    ///
    /// This contains only self-signatures that are cryptographically verified, and considered
    /// valid by our policy.
    pub fn as_signed_public_key(&self) -> &SignedPublicKey {
        &self.cspk
    }

    /// The fingerprint of this Certificate
    pub fn fingerprint(&self) -> &Fingerprint {
        &self.primary_fingerprint
    }

    /// The key id of this Certificate
    pub fn key_id(&self) -> KeyId {
        self.primary_key_id
    }

    /// Get the creation time of the certificate (the creation time of the primary key)
    pub fn primary_creation_time(&self) -> Timestamp {
        self.cspk.primary_key.created_at()
    }

    /// The primary key of this `Checked`
    pub(crate) fn primary_key(&self) -> SignedComponentKeyPub {
        let mut sigs: Vec<_> = self.cspk.details.revocation_signatures.clone();
        sigs.append(&mut self.cspk.details.direct_signatures.clone());

        SignedComponentKeyPub::Primary((self.cspk.clone(), sigs))
    }

    /// An iterator over all subkeys of this `Checked`
    pub(crate) fn subkeys(&self) -> impl Iterator<Item = SignedComponentKeyPub> + '_ {
        self.cspk.public_subkeys.iter().map(|spsk| {
            SignedComponentKeyPub::Subkey((
                spsk.clone(),
                self.cspk.details.direct_signatures.clone(),
            ))
        })
    }

    /// An iterator over the primary and all subkeys of this `Checked`
    pub(crate) fn component_keys(&self) -> impl Iterator<Item = SignedComponentKeyPub> + '_ {
        std::iter::once(self.primary_key()).chain(self.subkeys())
    }

    /// List all User IDs
    pub fn user_ids(&self) -> &[SignedUser] {
        &self.cspk.details.users
    }

    /// List all User Attributes
    pub fn user_attributes(&self) -> &[SignedUserAttribute] {
        &self.cspk.details.user_attributes
    }

    // --- semantics functionality

    /// Return the primary User ID
    pub fn primary_user_id(&self) -> Option<&SignedUser> {
        let now = Timestamp::now();

        crate::primary_userid::primary_user_id(
            &self.cspk.details,
            now,
            self.primary_creation_time(),
        )
    }

    /// Get the active direct key signature at `reference`.
    fn active_dks_at(&self, reference: Timestamp) -> Option<&Signature> {
        // combine direct_signatures+revocation_signatures
        SigStack::from_iter(
            self.cspk
                .details
                .direct_signatures
                .iter()
                .chain(self.cspk.details.revocation_signatures.iter()),
        )
        .active_at(reference, self.primary_creation_time())
    }

    /// Find the active metadata-bearing signature for the certificate.
    ///
    /// For v6 certificates, this is the active direct key self-signature.
    ///
    /// For earlier certificate versions, it is usually the active self-signature of the
    /// primary user id. However, a direct key self-signature can be used as well.
    /// If both types of self-signature exist, this will pick the one with the later creation time.
    pub fn active_certificate_self_signature_at(&self, reference: Timestamp) -> Option<&Signature> {
        match self.cspk.version() {
            KeyVersion::V2 | KeyVersion::V3 | KeyVersion::V4 => {
                let uid_binding = primary_user_id_binding_at(
                    &self.cspk.details,
                    reference,
                    self.primary_creation_time(),
                );
                let direct_sig = self.active_dks_at(reference);

                match (uid_binding, direct_sig) {
                    (None, None) => None,
                    (Some(a), None) | (None, Some(a)) => Some(a),
                    (Some(a), Some(b)) => Some(util::newer(a, b)),
                }
            }

            KeyVersion::V6 => self.active_dks_at(reference),

            _ => None,
        }
    }

    /// Return key expiration "duration" of the primary key.
    ///
    /// If the `Duration` is `None`, or if it is "zero", the key doesn't expire.
    fn primary_expiration_duration(&self, reference: Timestamp) -> Option<Duration> {
        self.active_certificate_self_signature_at(reference)
            .and_then(Signature::key_expiration_time)
    }

    /// Return expiration time of the primary key, or `None` if the key doesn't expire
    fn primary_expiration_time(&self, reference: Timestamp) -> Option<Timestamp> {
        self.primary_expiration_duration(reference)
            // if the value is zero, we don't have a key expiration
            .filter(|d| d.as_secs() != 0)
            .map(|d| self.cspk.primary_key.created_at().as_secs() + d.as_secs())
            .map(Timestamp::from_secs)
    }

    /// Is the primary key (and thus the certificate as a whole) valid at `reference` time?
    ///
    /// The primary is invalid if it is expired, revoked, or has no acceptable binding
    /// self-signature.
    ///
    /// It is also invalid it its public key algorithm is considered insufficient at the reference
    /// time.
    pub fn primary_valid_at(&self, reference: Timestamp) -> Result<bool, Error> {
        log::debug!(
            "checking primary key validity at {:?}",
            SystemTime::from(reference)
        );

        // It's not ok if `reference` is before key creation time
        if reference < self.primary_creation_time() {
            log::debug!(" reference time predates primary key creation");
            return Ok(false);
        }

        // If the primary is using an insufficiently strong public key algorithm
        // (i.e. unacceptable at the reference time), we reject its use
        let pp = self.cspk.primary_key.public_params();
        if !policy::acceptable_pk_algorithm(pp, reference) {
            log::debug!(" primary key uses unacceptable public parameters {pp:?}");
            return Ok(false);
        }

        if let Some(expiration) = self.primary_expiration_time(reference) {
            if expiration < reference {
                log::debug!(" primary key expired {expiration:?}");
                return Ok(false);
            }
        }

        // Check that a valid primary user id binding or dks exist at the reference time.
        // (This includes checking that the binding signatures use an acceptable public key
        // algorithm.)
        let Some(active) = self.active_certificate_self_signature_at(reference) else {
            log::debug!(" no valid primary key binding");
            return Ok(false);
        };

        // Is the primary revoked at the reference time?
        if signature::is_revocation(active) {
            log::debug!(" primary key is revoked");
            return Ok(false);
        }

        log::debug!(" primary key is valid");
        Ok(true)
    }

    /// Is the full certificate revoked at `reference` time?
    ///
    /// This takes into account the semantics of hard and soft revocation.
    pub fn revoked_at(&self, reference: Timestamp) -> bool {
        let Some(active) = self.active_certificate_self_signature_at(reference) else {
            log::debug!(" no valid primary key binding");
            return false;
        };

        signature::is_revocation(active)
    }

    // --- preferences/features metadata lookup

    /// The preferred `SymmetricKeyAlgorithm` setting for this certificate
    pub fn preferred_symmetric_key_algo(
        &self,
        reference: Timestamp,
    ) -> Option<&[SymmetricKeyAlgorithm]> {
        self.active_certificate_self_signature_at(reference)
            .map(Signature::preferred_symmetric_algs)
    }

    /// The preferred `AeadAlgorithm` setting for this certificate
    pub fn preferred_aead_algo(
        &self,
        reference: Timestamp,
    ) -> Option<&[(SymmetricKeyAlgorithm, AeadAlgorithm)]> {
        self.active_certificate_self_signature_at(reference)
            .map(Signature::preferred_aead_algs)
    }

    /// The preferred `HashAlgorithm` setting for this certificate
    pub fn preferred_hash_algo(&self, reference: Timestamp) -> Option<&[HashAlgorithm]> {
        self.active_certificate_self_signature_at(reference)
            .map(Signature::preferred_hash_algs)
    }

    /// The `Features` setting of this Certificate
    pub fn features(&self, reference: Timestamp) -> Option<&Features> {
        self.active_certificate_self_signature_at(reference)
            .and_then(Signature::features)
    }

    // --- component key selectors

    /// List all valid subkeys at the reference time.
    pub fn valid_subkeys_at(&self, reference: Timestamp) -> Vec<ComponentKeyPub> {
        // If the primary key is invalid, there are no valid subkeys
        if matches!(self.primary_valid_at(reference), Err(_) | Ok(false)) {
            return vec![];
        }

        // Filter based on validity
        self.subkeys()
            .filter(|sckp| policy::acceptable_pk_algorithm(sckp.public_params(), reference))
            .filter(|sckp| sckp.is_component_subkey_valid_at(reference))
            .map(Into::into)
            .collect()
    }

    /// A baseline set of generically valid component keys.
    ///
    /// No component keys are returned if the certificate as a whole in invalid.
    /// Individual component keys are returned if they are validly bound, and use a public key
    /// mechanism that we accept at the reference time.
    ///
    /// This function is intended for further filtering by callers, to limit component keys more
    /// specifically for concrete use cases.
    fn valid_component_keys_at(&self, reference: Timestamp) -> Vec<SignedComponentKeyPub> {
        // If the primary key is invalid, there are no valid subkeys
        if matches!(self.primary_valid_at(reference), Err(_) | Ok(false)) {
            return vec![];
        }

        // Filter based on validity
        self.component_keys()
            .filter(|sckp| policy::acceptable_pk_algorithm(sckp.public_params(), reference))
            .filter(|sckp| sckp.is_component_subkey_valid_at(reference))
            .collect()
    }

    /// List all valid component keys that are encryption capable.
    ///
    /// The resulting set of [ComponentKeyPub] can be used to encrypt data.
    pub fn valid_encryption_capable_component_keys(&self) -> Vec<ComponentKeyPub> {
        let reference = Timestamp::now();

        self.valid_component_keys_at(reference)
            .into_iter()
            .filter(|sckp| sckp.valid_encryption_algo())
            .filter(|sckp| sckp.is_encryption_capable(reference))
            .map(Into::into)
            .collect()
    }

    /// Get a set of [SignatureVerifier] objects, one for each valid component key that is
    /// appropriate to use for data signatures.
    ///
    /// This includes a check that the binding signature must have an embedded back signature
    /// (we have a `Checked`, so we can assume that if a back signature exists at all, it is
    /// acceptable).
    pub fn valid_signing_capable_component_keys_at(
        &self,
        reference: Timestamp,
    ) -> Vec<SignatureVerifier> {
        log::debug!("valid_signing_capable_component_keys_at {reference:?}");

        self.valid_component_keys_at(reference)
            .into_iter()
            .filter(|sckp| sckp.is_signing_capable(reference))
            .filter(|sckp| sckp.has_valid_backsig_at(reference, self.primary_creation_time()))
            .map(ComponentKeyPub::from)
            .map(|ckey| SignatureVerifier::new(ckey, self.cspk.primary_key.created_at()))
            .collect()
    }

    /// Get a set of [ComponentKeyPub] objects, one for each valid component key that is
    /// appropriate to use for authentication.
    pub fn valid_authentication_capable_component_keys(
        &self,
        reference: Timestamp,
    ) -> Vec<ComponentKeyPub> {
        self.valid_component_keys_at(reference)
            .into_iter()
            .filter(|sckp| sckp.is_authentication_capable(reference))
            .map(Into::into)
            .collect()
    }

    // --- third party signature helpers

    /// Was this signature potentially issued by a third party?
    ///
    /// This checks if any issuer key id or fingerprint subpacket matches the primary key id or
    /// fingerprint of `self`.
    fn maybe_third_party(&self, s: &Signature) -> bool {
        let mut maybe_third_party = false;

        let issuers = s.issuer_key_id();
        if !issuers.is_empty() && issuers.into_iter().any(|x| x != &self.primary_key_id) {
            maybe_third_party = true
        };

        let issuer_fps = s.issuer_fingerprint();
        if !issuer_fps.is_empty()
            && issuer_fps
                .into_iter()
                .any(|x| x != &self.primary_fingerprint)
        {
            maybe_third_party = true
        };

        maybe_third_party
    }

    /// Get all third-party certifications for all User IDs
    pub fn user_id_third_party_certifications(&self) -> Vec<(UserId, Vec<&Signature>)> {
        let mut res = vec![];

        for su in &self.original.details.users {
            let id = su.id.clone();
            let sigs = su
                .signatures
                .iter()
                .filter(|s| self.maybe_third_party(s))
                .collect();

            res.push((id, sigs));
        }

        res
    }

    pub fn direct_third_party_certifications(&self) -> Vec<&Signature> {
        self.original
            .details
            .direct_signatures
            .iter()
            .chain(&self.original.details.revocation_signatures)
            .filter(|s| self.maybe_third_party(s))
            .collect()
    }
}

impl From<Certificate> for Checked {
    fn from(value: Certificate) -> Self {
        Checked::new(value)
    }
}

impl From<Checked> for Certificate {
    fn from(value: Checked) -> Self {
        value.cspk.into()
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]

    use std::time::SystemTime;

    use chrono::DateTime;
    use pgp::types::Timestamp;

    use crate::certificate::Checked;

    fn load_cert(filename: &str) -> Checked {
        let mut read = std::fs::File::open(filename).expect("open");
        let c = crate::certificate::Certificate::load(&mut read).expect("load");

        assert_eq!(c.len(), 1);

        Checked::from(c.into_iter().next().expect("asserted"))
    }

    fn expiration_at(c: &Checked, at: &str) -> Timestamp {
        let rfc3339 = DateTime::parse_from_rfc3339(at).expect("parse at");

        let time: SystemTime = rfc3339.into();
        c.primary_expiration_time(time.try_into().expect("time fits in u32"))
            .expect("some")
    }

    #[test]
    fn test_dsa() {
        // This certificate uses a DSA primary (which is used for all self-signatures).
        //
        // Note that we consider DSA invalid from February 3, 2023 forward (see [policy]).
        //
        // Thus, self-signatures that are newer than this cutoff are ignored -
        // so the self-signature on the primary User ID from 2024-06-03 is considered invalid,
        // and the key is considered expired at 2024-06-07T19:57:03Z.
        let checked = load_cert("tests/608B00ABE1DAA3501C5FF91AE58271326F9F4937");

        // --- validity of the primary ---

        // key is not revoked
        assert!(
            !checked.revoked_at(
                SystemTime::from(
                    DateTime::parse_from_rfc3339("2025-01-01T23:59:00Z").expect("parse date")
                )
                .try_into()
                .expect("time fits in u32"),
            )
        );

        // valid at 2020-01-01T23:59:00Z
        assert!(
            checked
                .primary_valid_at(
                    SystemTime::from(
                        DateTime::parse_from_rfc3339("2020-01-01T23:59:00Z").expect("parse date")
                    )
                    .try_into()
                    .expect("time fits in u32"),
                )
                .expect("primary_valid_at")
        );

        let exp = expiration_at(&checked, "2020-01-01T23:59:00Z");
        assert_eq!(
            exp,
            SystemTime::from(
                DateTime::parse_from_rfc3339("2020-08-03T13:32:24Z").expect("parse date")
            )
            .try_into()
            .expect("time fits in u32"),
        );

        let exp = expiration_at(&checked, "2021-01-01T23:59:00Z");
        assert_eq!(
            exp,
            SystemTime::from(
                DateTime::parse_from_rfc3339("2022-07-06T17:06:34Z").expect("parse date")
            )
            .try_into()
            .expect("time fits in u32"),
        );

        let exp = expiration_at(&checked, "2024-01-01T23:59:00Z");
        assert_eq!(
            exp,
            SystemTime::from(
                DateTime::parse_from_rfc3339("2024-06-07T19:57:03Z").expect("parse date")
            )
            .try_into()
            .expect("time fits in u32"),
        );

        // not valid at 2024-07-01T23:59:00Z
        assert!(
            !checked
                .primary_valid_at(
                    SystemTime::from(
                        DateTime::parse_from_rfc3339("2024-07-01T23:59:00Z").expect("parse date")
                    )
                    .try_into()
                    .expect("time fits in u32"),
                )
                .expect("primary_valid_at")
        );

        // --- encryption subkey ---

        let enc = checked.valid_encryption_capable_component_keys();
        assert_eq!(enc.len(), 0);

        // TODO: if we had a [valid_encryption_capable_component_keys_at] fn, we could test for
        //  - historical validity of the old ElGamal encryption key, and
        //  - the switch to the RSA encryption key on 2017-08-02.

        // --- signature component key (the primary key) ---
        let sig = checked.valid_signing_capable_component_keys_at(
            SystemTime::from(
                DateTime::parse_from_rfc3339("2022-07-01T23:59:00Z").expect("parse date"),
            )
            .try_into()
            .expect("time fits in u32"),
        );
        assert_eq!(sig.len(), 1);

        let sig = checked.valid_signing_capable_component_keys_at(
            SystemTime::from(
                DateTime::parse_from_rfc3339("2024-07-01T23:59:00Z").expect("parse date"),
            )
            .try_into()
            .expect("time fits in u32"),
        );
        assert_eq!(sig.len(), 0);
    }
}