1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
//! A certificate store abstraction.
//!
//! A [`Network`] accesses certificates via the [`Store`] interface.
//!
//! [`Network`]: crate::Network
use std::collections::HashMap;
use std::collections::HashSet;
use std::time::SystemTime;
use std::ops::Deref;
use std::rc::Rc;
use sequoia_openpgp as openpgp;
use openpgp::Fingerprint;
use openpgp::KeyHandle;
use openpgp::KeyID;
use openpgp::Result;
use openpgp::cert::prelude::*;
use openpgp::policy::Policy;
use openpgp::packet::Signature;
use openpgp::packet::UserID;
use crate::CertificationSet;
use crate::CertSynopsis;
use crate::Certification;
use crate::Depth;
use crate::TRACE;
mod raw_certs;
pub use raw_certs::RawCerts;
mod cert_slice;
pub use cert_slice::CertSlice;
mod synopsis_slice;
pub use synopsis_slice::SynopsisSlice;
mod keyserver;
pub use keyserver::KeyServer;
/// [`Store`] specific error codes.
#[non_exhaustive]
#[derive(thiserror::Error, Debug, Clone, PartialEq)]
pub enum StoreError {
/// No certificate was found.
#[error("{0} was not found")]
NotFound(KeyHandle),
}
/// The different ways that a backend may return a certificate.
///
/// Depending on the backend, a different representation may be more
/// efficient.
///
/// A `CertObject` derefs to a `Cert`. To get a `ValidCert`, call
/// `with_policy` directly on the `CertObject`. This will use the
/// cached `ValidCert`, if any.
pub enum CertObject<'a> {
/// All ValidCert's must use the same policy and reference time.
///
/// This is the ideal return type.
ValidCert(ValidCert<'a>),
/// A reference to a certificate.
///
/// This representation allows the frontend to cache the
/// `ValidCert`.
CertRef(&'a Cert),
/// An owned `Cert`.
///
/// If the backend must return a `Cert`, then that's okay. But
/// this means that the front end can't cache the `ValidCert`,
/// because [Rust doesn't allow self referential structs].
///
/// [Rust doesn't allow self referential structs]: https://users.rust-lang.org/t/how-can-we-teach-people-about-self-referential-types/65362
Cert(Cert),
/// A reference counted `Cert`.
///
/// If the backend must return a `Cert`, then that's okay. But
/// this means that the front end can't cache the `ValidCert`,
/// because [Rust doesn't allow self referential structs].
///
/// [Rust doesn't allow self referential structs]: https://users.rust-lang.org/t/how-can-we-teach-people-about-self-referential-types/65362
RcCert(Rc<Cert>),
}
impl<'a> CertObject<'a> {
/// Returns a `ValidCert`.
///
/// If the `CertObject` already contains a `ValidCert`, then the
/// `policy` and `t` parameters must match the `ValidCert`'s
/// policy and reference time.
pub fn with_policy<'b>(&'b self, policy: &'b dyn Policy, t: SystemTime)
-> Result<ValidCert<'b>>
where 'a: 'b
{
match self {
CertObject::ValidCert(vc) => Ok(vc.clone()),
CertObject::CertRef(cert) => {
cert.with_policy(policy, t)
},
CertObject::Cert(cert) => {
cert.with_policy(policy, t)
},
CertObject::RcCert(cert) => {
cert.with_policy(policy, t)
},
}
}
}
impl<'a> Deref for CertObject<'a> {
type Target = Cert;
fn deref(&self) -> &Self::Target {
self.cert()
}
}
impl<'a> CertObject<'a> {
/// Returns a reference to the underlying `Cert`.
pub fn cert(&self) -> &Cert {
match self {
CertObject::ValidCert(vc) => vc.cert(),
CertObject::CertRef(cert) => cert,
CertObject::Cert(cert) => cert,
CertObject::RcCert(cert) => cert.as_ref(),
}
}
}
/// Returns certificates from a backing store.
pub trait Backend {
/// Returns the certificates matching the handle.
///
/// Returns [`StoreError::NotFound`] if the certificate is not found.
///
/// The caller may assume that looking up a fingerprint returns at
/// most one certificate.
fn cert_object<'a>(&'a self, kh: &KeyHandle) -> Result<Vec<CertObject<'a>>>;
/// Returns the corresponding certificate, if any.
///
/// Returns [`StoreError::NotFound`] if the certificate is not found.
///
/// The default implementation is implemented in terms of
/// [`Backend::cert_object`].
fn cert_object_by_fpr<'a>(&'a self, fingerprint: &Fingerprint)
-> Result<CertObject<'a>>
{
let kh = KeyHandle::from(fingerprint.clone());
self.cert_object(&kh)
.and_then(|v| {
assert!(v.len() <= 1);
v.into_iter().next()
.ok_or(StoreError::NotFound(kh).into())
})
}
/// Lists all of the certificates.
fn list_cert_objects<'a>(&'a self)
-> Box<dyn Iterator<Item=Fingerprint> + 'a>;
/// Returns all of the certificates.
///
/// The default implementation is implemented in terms of
/// [`Backend::list_cert_objects`] and
/// [`Backend::cert_object_by_fpr`]. Many backends will be able
/// to do this more efficiently.
fn cert_objects<'a>(&'a self) -> Box<dyn Iterator<Item=CertObject<'a>> + 'a> {
Box::new(self.list_cert_objects()
.filter_map(|fpr| {
self.cert_object_by_fpr(&fpr).ok()
}))
}
/// Returns all certifications on a certificate.
///
/// `target`'s policy and reference time is used to determine what
/// certificates are valid. Only active valid certifications are
/// returned. (A certification is active if it is the newest
/// valid certification of a particular binding as of the
/// reference time.)
///
/// Example:
///
/// ```text
/// 0xA certifies <Carol, 0xC>. \ CertificationSet
/// 0xA certifies <Caroline, 0xC>. /
/// 0xB certifies <Carol, 0xC>. > CertificationSet
/// ```
///
/// The entry for 0xC has two `CertificationSet`s: one for those
/// made by 0xA and one for those made by 0xB.
///
/// An implementation may (but need not) use the `min_depth`
/// parameter to filter the the certifications it returns. The
/// `min_depth` parameter says that the caller is only interested
/// in certifications for which the trust depth is at least
/// `min_depth`. If an implementation returns certifications
/// whose trust depth is less than `min_depth` the caller must
/// ignore them.
fn redges(&self, target: ValidCert, min_depth: Depth) -> Vec<CertificationSet>
{
tracer!(TRACE, "Backend::redges");
t!("({}, {}; {})",
target.fingerprint(),
target.primary_userid()
.map(|ua| String::from_utf8_lossy(ua.userid().value()))
.unwrap_or("<unknown>".into()),
min_depth);
let reference_time = target.time();
// certifications is all of the certifications for a given
// <Cert, User ID>. Returns the active certification, if any,
// and any issuers that should be retried with a min_depth of 0.
let get_active = |ua: &UserIDAmalgamation,
certifications: &[&Signature],
min_depth: Depth,
// If some, only return certifications by these
// issuers.
filter: Option<HashSet<KeyID>>|
-> (Vec<Certification>, HashSet<KeyID>)
{
t!("Looking for active signatures: min depth: {}", min_depth);
let mut valid_certifications: Vec<Certification> = Vec::new();
// If we've already seen a valid certification from the
// Issuer on the current <Cert, UserID> binding.
let mut seen: HashMap<Fingerprint, std::time::SystemTime>
= HashMap::new();
// If we skipped a certification due to the min_depth
// constraint, and then find another certification that
// does pass the constraint, we need to recheck the first
// one, as it would be preferred. We do this in a second
// pass.
let mut skipped: HashSet<KeyID> = HashSet::new();
let mut retry: HashSet<KeyID> = HashSet::new();
'cert: for certification in certifications {
// Check that the certification is valid:
//
// - Find the issuer.
// - Verify the signature.
//
// If we don't have a certificate for the alleged issuer,
// then we ignore the certification.
let certification_time =
if let Some(t) = certification.signature_creation_time() {
t
} else {
continue;
};
let alleged_issuers = certification.get_issuers();
if min_depth > 0.into() {
let depth = certification.trust_signature()
.map(|(depth, _amount)| depth)
.unwrap_or(0);
if Depth::from(depth as usize) < min_depth {
for alleged_issuer in alleged_issuers {
let keyid = KeyID::from(alleged_issuer);
t!("Skipping {} for {:02X}{:02X} as depth \
of {} is less than the minimum {}",
keyid,
certification.digest_prefix()[0],
certification.digest_prefix()[1],
depth, min_depth);
skipped.insert(keyid);
}
continue;
} else {
// It's okay.
t!("Checking {:02X}{:02X} as depth \
of {} is at least the minimum of {}",
certification.digest_prefix()[0],
certification.digest_prefix()[1],
depth, min_depth);
}
}
// Improve tracing: distinguish between we don't have
// the issuer's certificate and we have it, but the
// signature is invalid.
let mut invalid_sig: Option<(KeyHandle, _)> = None;
for alleged_issuer in alleged_issuers.into_iter() {
let alleged_issuer_keyid = KeyID::from(&alleged_issuer);
if skipped.get(&alleged_issuer_keyid).is_some() {
// We skipped a newer certification (due to
// the min_depth filter) so even if this older
// one is valid, it might not be active. Add
// this to the `retry` list so that we try
// this issuer again without the depth filter.
t!("Skipped possible certification from {}, \
queuing to retry with no depth constraints",
alleged_issuer_keyid);
retry.insert(alleged_issuer_keyid);
continue;
}
if let Some(ref filter) = filter {
// Are we interested in certifications from
// this certificate?
if ! filter.get(&alleged_issuer_keyid).is_some() {
continue;
} else {
t!("Reconsidering certification {:02X}{:02X}, \
which is possibly from {}",
certification.digest_prefix()[0],
certification.digest_prefix()[1],
alleged_issuer_keyid);
}
}
match self.cert_object(&alleged_issuer) {
Ok(alleged_issuers) => {
for alleged_issuer in alleged_issuers.into_iter() {
let alleged_issuer_fpr
= alleged_issuer.fingerprint();
if let Some(saw) = seen.get(&alleged_issuer_fpr)
{
if saw > &certification_time {
// We already have a newer
// certification from this
// issuer.
t!("Skipping certification \
by {} for <{:?}, {}> at {:?}: \
saw a newer one.",
alleged_issuer_fpr,
ua.userid(), target.keyid(),
certification_time);
continue;
}
}
let alleged_issuer = match alleged_issuer
.with_policy(target.policy(), reference_time)
{
Ok(c) => c,
Err(err) => {
t!("Ignoring possible certification \
by {}: {}",
alleged_issuer_fpr, err);
continue;
}
};
let r = Certification::try_from_signature(
&alleged_issuer, Some(ua), &target,
certification);
match r {
Ok(c) => {
t!("Using certification {:02X}{:02X} \
by {} for <{:?}, {}> at {:?}: \
{}/{}.",
certification.digest_prefix()[0],
certification.digest_prefix()[1],
alleged_issuer_fpr,
ua.userid(), target.keyid(),
c.creation_time(),
c.depth(),
c.amount());
valid_certifications.push(c);
seen.insert(alleged_issuer_fpr,
certification_time);
continue 'cert;
}
Err(err) => {
invalid_sig = Some(
(alleged_issuer_fpr.into(), err));
}
}
}
}
Err(err) => {
invalid_sig = Some((alleged_issuer, err));
}
}
}
if let Some((keyid, err)) = invalid_sig {
t!("Invalid certification {:02X}{:02X} \
by {} for <{:?}, {}>: {}",
certification.digest_prefix()[0],
certification.digest_prefix()[1],
keyid, ua.userid(), target.keyid(),
err);
} else {
t!("Certification {:02X}{:02X} for <{:?}, {}>: \
missing issuer's certificate ({}).",
certification.digest_prefix()[0],
certification.digest_prefix()[1],
ua.userid(), target.keyid(),
certification.get_issuers()
.first()
.map(|h| h.to_string())
.unwrap_or("(no issuer subkeys)".into())
);
}
}
(valid_certifications, retry)
};
let mut valid_certifications = Vec::new();
for ua in target.userids() {
// Skip invalid User IDs.
if let Err(_) = std::str::from_utf8(ua.userid().value()) {
t!("{}: Non-UTF-8 User ID ({:?}) skipped.",
target.keyid(),
String::from_utf8_lossy(ua.userid().value()));
continue;
}
// We iterate over all of the certifications. We need to
// be careful: we only want the newest certification for a
// given <Issuer, <Cert, UserID>> tuple.
let mut certifications: Vec<_> = ua.certifications()
// Filter out certifications made after the reference time.
.filter(|c| {
if let Some(ct) = c.signature_creation_time() {
ct <= reference_time
} else {
false
}
})
.collect();
t!("<{}, {}>: {} third-party certifications",
target.fingerprint(),
String::from_utf8_lossy(ua.userid().value()),
certifications.len());
// Sort the certifications so that the newest comes first.
certifications.sort_by(|a, b| {
a.signature_creation_time().cmp(&b.signature_creation_time())
.reverse()
});
let (c, retry) = get_active(&ua, &certifications, min_depth, None);
valid_certifications.extend(c);
if ! retry.is_empty() {
assert!(min_depth > 0.into());
t!("Retrying: depth filter excludes some, but not all \
certifications for: {}",
retry.iter()
.map(|k| k.to_hex())
.collect::<Vec<String>>()
.join(", "));
let (c, retry) = get_active(
&ua, &certifications, Depth::from(0), Some(retry));
valid_certifications.extend(c);
assert!(retry.is_empty());
}
}
t!("Merging certifications.");
CertificationSet::from_certifications(
valid_certifications, reference_time)
}
/// Prefills the cache.
///
/// Prefilling the cache makes sense when you plan to examine most
/// nodes and edges in the network. It doesn't make sense if you
/// are just authenticating a single or a few bindings.
///
/// This function may be multi-threaded.
///
/// Errors should be silently ignored and propagated when the
/// operation in question is executed directly.
fn precompute(&self) {
}
}
impl<T> Backend for Box<T>
where T: Backend + ?Sized
{
fn cert_object<'a>(&'a self, kh: &KeyHandle) -> Result<Vec<CertObject<'a>>> {
self.as_ref().cert_object(kh)
}
fn cert_object_by_fpr<'a>(&'a self, fingerprint: &Fingerprint)
-> Result<CertObject<'a>>
{
self.as_ref().cert_object_by_fpr(fingerprint)
}
/// Lists all of the certificates.
fn list_cert_objects<'a>(&'a self)
-> Box<dyn Iterator<Item=Fingerprint> + 'a>
{
self.as_ref().list_cert_objects()
}
fn cert_objects<'a>(&'a self) -> Box<dyn Iterator<Item=CertObject<'a>> + 'a> {
self.as_ref().cert_objects()
}
fn redges(&self, target: ValidCert, min_depth: Depth) -> Vec<CertificationSet>
{
self.as_ref().redges(target, min_depth)
}
}
pub trait Store {
/// Returns the reference time.
fn reference_time(&self) -> SystemTime;
/// Lists all of the certificates.
fn list<'a>(&'a self) -> Box<dyn Iterator<Item=Fingerprint> + 'a>;
/// Returns all of the certificates.
fn certs<'a>(&'a self) -> Box<dyn Iterator<Item=CertSynopsis> + 'a> {
Box::new(self.list()
.filter_map(|fpr| {
self.cert_by_fpr(&fpr).ok()
}))
}
/// Returns the certificates matching the handle.
///
/// Returns [`StoreError::NotFound`] if the certificate is not
/// found. This function SHOULD NOT return an empty vector if the
/// certificate is not found.
///
/// The caller may assume that looking up a fingerprint returns at
/// most one certificate.
fn cert(&self, kh: &KeyHandle) -> Result<Vec<CertSynopsis>>;
/// Returns the corresponding certificate, if any.
///
/// Returns [`StoreError::NotFound`] if the certificate is not
/// found. This function SHOULD NOT return an empty vector if the
/// certificate is not found.
fn cert_by_fpr(&self, fingerprint: &Fingerprint)
-> Result<CertSynopsis>
{
let kh = KeyHandle::from(fingerprint.clone());
self.cert(&kh)
.and_then(|v| {
assert!(v.len() <= 1);
v.into_iter().next()
.ok_or(StoreError::NotFound(kh).into())
})
}
/// Returns a certification set for the specified certificate.
///
/// A `CertificateSet` is returned for the certificate itself as
/// well as for each User ID (self signed or not) that has a
/// cryptographically valid certification.
///
/// Returns [`StoreError::NotFound`] if the certificate is not
/// found. This function SHOULD NOT return an empty vector if the
/// certificate is not found.
///
/// An implementation may (but need not) use the `min_depth`
/// parameter to filter the the certifications it returns. The
/// `min_depth` parameter says that the caller is only interested
/// in certifications for which the trust depth is at least
/// `min_depth`. If an implementation returns certifications
/// whose trust depth is less than `min_depth` the caller must
/// ignore them.
fn certifications_of(&self, target: &Fingerprint, min_depth: Depth)
-> Result<Vec<CertificationSet>>;
/// Returns all third-party certifications of the specified
/// certificate.
///
/// Returns [`StoreError::NotFound`] if the certificate is not
/// found. This function SHOULD NOT return an empty vector if the
/// certificate is not found.
fn third_party_certifications_of(&self, fpr: &Fingerprint)
-> Vec<Certification>
{
self.certifications_of(fpr, 0.into())
.unwrap_or(Vec::new())
.into_iter().flat_map(|cs| {
cs.certifications()
.flat_map(|(_userid, certifications)| {
certifications
})
.cloned()
.collect::<Vec<_>>()
.into_iter()
})
.collect::<Vec<_>>()
}
/// Returns all User IDs that were certified for the specified
/// certificate.
///
/// This returns both self-signed User IDs, and User IDs certified
/// by third-parties for the specified certificate. The result is
/// deduped.
///
/// Returns [`StoreError::NotFound`] if the certificate is not
/// found. This function SHOULD NOT return an empty vector if the
/// certificate is not found.
fn certified_userids_of(&self, fpr: &Fingerprint)
-> Vec<UserID>
{
if let Ok(cert) = self.cert_by_fpr(fpr) {
let mut userids: Vec<UserID> = self
.third_party_certifications_of(&cert.fingerprint())
.into_iter()
.filter_map(|c| c.userid().map(Clone::clone))
.chain(cert.userids().map(|u| u.userid().clone()))
.collect();
userids.sort_unstable();
userids.dedup();
userids
} else {
Vec::new()
}
}
/// Returns all User IDs that were certified.
///
/// This returns both self-signed User IDs, and User IDs certified
/// by third-parties. The result is deduped.
fn certified_userids(&self)
-> Vec<(Fingerprint, UserID)>
{
let mut userids = self.certs().flat_map(|cert| {
let fpr = cert.fingerprint();
let userids = cert.userids().map(|u| {
(fpr.clone(), u.userid().clone())
}).collect::<Vec<(Fingerprint, UserID)>>();
self
.third_party_certifications_of(&fpr)
.into_iter()
.filter_map(move |c| {
c.userid().map(|u| (fpr.clone(), u.clone()))
})
.chain(userids)
}).collect::<Vec<(Fingerprint, UserID)>>();
userids.sort_unstable();
userids.dedup();
userids
}
/// Returns all certificates that may have the specified User ID.
///
/// This returns both self-signed User IDs, and User IDs certified
/// by third-parties. It is okay for this function to return
/// false positives, i.e., certificates that on closer inspection
/// shouldn't be associated with that User ID.
fn with_userid(&self, userid: UserID) -> Vec<Fingerprint> {
self.certified_userids()
.into_iter()
.filter_map(|(fpr, u)| {
if u == userid {
Some(fpr)
} else {
None
}
})
.collect()
}
/// Returns all certificates that may have a User ID with the
/// specified email address.
///
/// This returns both self-signed User IDs, and User IDs certified
/// by third-parties. It is okay for this function to return
/// false positives, i.e., certificates that on closer inspection
/// shouldn't be associated with that User ID.
fn with_email(&self, email: &str) -> Vec<(Fingerprint, UserID)> {
let userid_check = UserID::from(format!("<{}>", email));
if let Ok(Some(email_check)) = userid_check.email() {
if email != email_check {
// Does not appear to be an email address.
return Vec::new();
}
} else {
// Does not appear to be an email address.
return Vec::new();
}
let email_normalized = userid_check.email_normalized()
.expect("checked").expect("checked");
self.certified_userids()
.into_iter()
.filter_map(|(fpr, u)| {
if let Ok(Some(e)) = u.email_normalized() {
if e == email_normalized {
return Some((fpr, u));
}
}
None
})
.collect()
}
}
impl<T> Store for Box<T>
where T: Store + ?Sized
{
/// Returns the reference time.
fn reference_time(&self) -> SystemTime {
self.as_ref().reference_time()
}
/// Lists all of the certificates.
fn list<'a>(&'a self) -> Box<dyn Iterator<Item=Fingerprint> + 'a> {
self.as_ref().list()
}
/// Returns all of the certificates.
fn certs<'a>(&'a self) -> Box<dyn Iterator<Item=CertSynopsis> + 'a> {
self.as_ref().certs()
}
fn cert(&self, kh: &KeyHandle) -> Result<Vec<CertSynopsis>> {
self.as_ref().cert(kh)
}
fn cert_by_fpr(&self, fingerprint: &Fingerprint)
-> Result<CertSynopsis>
{
self.as_ref().cert_by_fpr(fingerprint)
}
fn certifications_of(&self, target: &Fingerprint, min_depth: Depth)
-> Result<Vec<CertificationSet>>
{
self.as_ref().certifications_of(target, min_depth)
}
fn third_party_certifications_of(&self, fpr: &Fingerprint)
-> Vec<Certification>
{
self.as_ref().third_party_certifications_of(fpr)
}
fn certified_userids_of(&self, fpr: &Fingerprint)
-> Vec<UserID>
{
self.as_ref().certified_userids_of(fpr)
}
fn certified_userids(&self)
-> Vec<(Fingerprint, UserID)>
{
self.as_ref().certified_userids()
}
fn with_userid(&self, userid: UserID) -> Vec<Fingerprint> {
self.as_ref().with_userid(userid)
}
fn with_email(&self, email: &str) -> Vec<(Fingerprint, UserID)> {
self.as_ref().with_email(email)
}
}
/// A workaround to create a `Box<dyn Store + Backend>`.
///
/// We can't directly do: `Box<dyn Store + Backend>`. That only works
/// for auto traits like `Send` and `Sync`. Instead we need to use a
/// special trait that depends on all of the traits that we care
/// about.
pub trait StorePlusBackend: Store + Backend {
}
impl<T> StorePlusBackend for T
where T: Store + Backend
{
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
use std::time::UNIX_EPOCH;
use sequoia_openpgp as openpgp;
use openpgp::cert::raw::RawCert;
use openpgp::cert::raw::RawCertParser;
use openpgp::parse::Parse;
use openpgp::policy::StandardPolicy;
use crate::Network;
use crate::Query;
#[test]
#[allow(unused)]
fn override_certification() -> Result<()> {
tracer!(true, "override_certification");
let p = &StandardPolicy::new();
let alice_fpr: Fingerprint =
"B4259E0C1D764615CA560EE57E10F6E7AC1D0A4E"
.parse().expect("valid fingerprint");
let alice_uid
= UserID::from("<alice@example.org>");
let bob_fpr: Fingerprint =
"3E2CBBFE672E101E0061D55C60FCD2B055FFB4A2"
.parse().expect("valid fingerprint");
let bob_uid
= UserID::from("<bob@example.org>");
// Certified by: B4259E0C1D764615CA560EE57E10F6E7AC1D0A4E
// Certified by: B4259E0C1D764615CA560EE57E10F6E7AC1D0A4E
let carol_fpr: Fingerprint =
"2C6CA00307C776386646C76757CCD98BEB17EA38"
.parse().expect("valid fingerprint");
let carol_uid
= UserID::from("<carol@example.org>");
// Certified by: 3E2CBBFE672E101E0061D55C60FCD2B055FFB4A2
let bytes = &crate::testdata::data("override.pgp");
let certs = RawCertParser::from_bytes(bytes)?;
let certs: Vec<RawCert> = certs
.map(|c| c.expect("Valid certificate"))
.collect();
// date '+%s' -u -d '2023-01-14 01:00:00'
let jan14 = UNIX_EPOCH + Duration::new(1673658000, 0);
// date '+%s' -u -d '2023-01-16 01:00:00'
let jan16 = UNIX_EPOCH + Duration::new(1673830800, 0);
// Alice certified Bob twice. Once on the 14th as a trusted
// introducer, and once on the 15 using a normal
// certification.
// On the 14th, Bob should be a trusted introducer.
t!("Jan 14, Bob");
let n = Network::from_raw_certs(&certs, p, Some(jan14))?;
let r = Query::new(&n, &[ alice_fpr.clone() ]);
let got = r.authenticate(bob_uid.clone(),
bob_fpr.clone(),
120);
assert!(got.amount() == 120);
t!("Jan 14, Carol");
let n = Network::from_raw_certs(&certs, p, Some(jan14))?;
let r = Query::new(&n, &[ alice_fpr.clone() ]);
let got = r.authenticate(carol_uid.clone(),
carol_fpr.clone(),
120);
assert!(got.amount() == 120);
// On the 16th, Bob should be a trusted introducer.
t!("Jan 16, Bob");
let n = Network::from_raw_certs(&certs, p, jan16)?;
let r = Query::new(&n, &[ alice_fpr.clone() ]);
let got = r.authenticate(bob_uid.clone(),
bob_fpr.clone(),
120);
assert!(got.amount() == 120);
t!("Jan 16, Carol");
let n = Network::from_raw_certs(&certs, p, jan16)?;
let r = Query::new(&n, &[ alice_fpr.clone() ]);
let got = r.authenticate(carol_uid.clone(),
carol_fpr.clone(),
120);
assert!(got.amount() == 0);
eprintln!("{:?}", n);
Ok(())
}
}