routinator 0.15.1

An RPKI relying party software.
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
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
896
897
898
899
900
901
//! Collecting payload during validation.
//!
//! This module contains the types necessary to collect payload during a
//! validation run. It is a private module. The public types of this module
//! are re-exported by the parent.
//!
//! [`ValidationReport`] collects the data derived from validating each
//! publication point. This data is derived by [`PubPointProcessor`] which
//! is used by the [`Engine`][crate::engine::Engine] during a validation run.
//! The resources of each publication point are stored in [`PubPoint`].
//! 
//! [`RejectedResources`] and its [`RejectedResourcesBuilder`] collect
//! prefixes and AS numbers from certificates for which publication points
//! had to be rejected so we can avoid partial VRP coverage.

use std::cmp;
use std::collections::hash_map;
use std::collections::HashMap;
use std::sync::Arc;
use crossbeam_queue::SegQueue;
use log::{info, warn};
use rpki::uri;
use rpki::crypto::keys::KeyIdentifier;
use rpki::repository::aspa::AsProviderAttestation;
use rpki::repository::cert::{Cert, ResourceCert};
use rpki::repository::resources::{
    AsBlock, AsBlocks, IpBlock, IpBlocks, IpBlocksBuilder,
};
use rpki::repository::roa::RouteOriginAttestation;
use rpki::repository::tal::{Tal, TalUri};
use rpki::repository::x509::{Time, Validity};
use rpki::resources::{Asn, Prefix, SmallAsnSet};
use rpki::rtr::payload::{Aspa, RouteOrigin, RouterKey};
use rpki::rtr::pdu::{ProviderAsns, RouterKeyInfo};
use crate::config::{Config, FilterPolicy};
use crate::engine::{CaCert, Engine, ProcessPubPoint, ProcessRun};
use crate::error::{Failed, RunFailed};
use crate::metrics::{Metrics, PayloadMetrics, VrpMetrics};
use crate::slurm::LocalExceptions;
use super::info::{PayloadInfo, PublishInfo};
use super::snapshot::PayloadSnapshot;


//------------ ValidationReport ----------------------------------------------

/// The payload set resulting from a validation run.
#[derive(Debug)]
pub struct ValidationReport {
    /// The data from all the valid publication points.
    ///
    /// When a publication point has been successfully validated, it pushes
    /// its data to this queue.
    pub_points: SegQueue<PubPoint>,

    /// Filter for invalid resources.
    ///
    /// If a publication point is rejected, the resources from its CA
    /// certificate are added to this.
    rejected: RejectedResourcesBuilder,

    /// Should we log rejected resources?
    log_rejected: bool,

    /// Should we include BGPsec router keys?
    enable_bgpsec: bool,

    /// Should we include ASPA objects?
    enable_aspa: bool,

    /// Should we filter IPv4 prefixes longer than a certain length?
    limit_v4_len: Option<u8>,

    /// Should we filter IPv6 prefixes longer than a certain length?
    limit_v6_len: Option<u8>,

    /// How are we dealing with unsafe VRPs?
    unsafe_vrps: FilterPolicy,
}

impl ValidationReport {
    /// Creates a new, empty validation report.
    pub fn new(config: &Config) -> Self {
        ValidationReport {
            pub_points: Default::default(),
            rejected: Default::default(),
            log_rejected: config.unsafe_vrps.log(),
            enable_bgpsec: config.enable_bgpsec,
            enable_aspa: config.enable_aspa,
            limit_v4_len: config.limit_v4_len,
            limit_v6_len: config.limit_v6_len,
            unsafe_vrps: config.unsafe_vrps,
        }
    }

    /// Creates a new validation report by running the engine.
    pub fn process(
        engine: &Engine, config: &Config, initial: bool,
    ) -> Result<(Self, Metrics), RunFailed> {
        let report = Self::new(config);
        let mut run = engine.start(&report, initial)?;
        run.process()?;
        run.cleanup()?;
        let metrics = run.done();
        Ok((report, metrics))
    }

    /// Converts the report into a payload snapshot.
    pub fn into_snapshot(
        self,
        exceptions: &LocalExceptions,
        metrics: &mut Metrics,
    ) -> PayloadSnapshot {
        let mut builder = SnapshotBuilder::new(
            self.rejected.finalize(), self.unsafe_vrps,
            exceptions,
        );
        while let Some(point) = self.pub_points.pop() {
            builder.process_pub_point(point, metrics)
        }
        builder.finalize(metrics)
    }
}

impl<'a> ProcessRun for &'a ValidationReport {
    type PubPoint = PubPointProcessor<'a>;

    fn process_ta(
        &self,
        _tal: &Tal, _uri: &TalUri, cert: &CaCert,
        tal_index: usize,
    ) -> Result<Option<Self::PubPoint>, Failed> {
        Ok(Some(
            PubPointProcessor {
                report: self,
                pub_point: PubPoint::new_ta(cert, tal_index),
                validity: cert.cert().validity(),
                point_stale: cert.cert().validity().not_after(),
            }
        ))
    }
}


//------------ PubPointProcessor ---------------------------------------------

/// Collects all the data for a publication point.
///
/// This type is used during validation of a publication point. It collects
/// all the published data and eventually contributes it to a validation
/// report.
#[derive(Clone, Debug)]
pub struct PubPointProcessor<'a> {
    /// The validation report payload is contributed to.
    report: &'a ValidationReport,

    /// The data being collected.
    pub_point: PubPoint,

    /// The (combined) validity of the publication point.
    validity: Validity,

    /// When will this publication point become stale.
    point_stale: Time,
}

impl ProcessPubPoint for PubPointProcessor<'_> {
    fn repository_index(&mut self, repository_index: usize) {
        self.pub_point.repository_index = Some(repository_index)
    }

    fn point_validity(&mut self, manifest: Validity, stale: Time) {
        self.pub_point.refresh = cmp::min(
            self.pub_point.refresh, 
            cmp::min(manifest.not_after(), stale)
        );
        self.validity = self.validity.trim(manifest);
        self.point_stale = cmp::min(self.point_stale, stale);
    }

    fn want(&self, _uri: &uri::Rsync) -> Result<bool, Failed> {
        // While we actually only care for some types, we want everything
        // processed for statistics.
        Ok(true)
    }

    fn process_ca(
        &mut self, _uri: &uri::Rsync, cert: &CaCert,
    ) -> Result<Option<Self>, Failed> {
        Ok(Some(
            PubPointProcessor {
                report: self.report,
                pub_point: PubPoint::new_ca(&self.pub_point, cert),
                validity: self.validity.trim(cert.cert().validity()),
                point_stale: cmp::min(
                    self.point_stale, cert.cert().validity().not_after()
                ),
            }
        ))
    }

    fn process_router_cert(
        &mut self, uri: &uri::Rsync, cert: Cert, ca_cert: &CaCert,
    ) -> Result<(), Failed> {
        if !self.report.enable_bgpsec {
            return Ok(())
        }
        if
            cert.as_resources().is_inherited()
            || !cert.as_resources().is_present()
        {
            warn!(
                "{uri}: router certificate does not contain AS resources."
            );
            return Ok(())
        }
        let asns = match cert.as_resources().to_blocks() {
            Ok(blocks) => blocks,
            Err(_) => {
                warn!(
                    "{uri}: router certificate contains invalid AS resources."
                );
                return Ok(())
            }
        };
        let id = cert.subject_key_identifier();
        let key = cert.subject_public_key_info();
        if !key.allow_router_cert() {
            warn!(
                "{uri}: router certificate has invalid key algorithm."
            );
            return Ok(())
        }
        let key = match RouterKeyInfo::new(key.to_info_bytes()) {
            Ok(key) => key,
            Err(_) => {
                warn!(
                    "{uri}: excessively large key in router certificate."
                );
                return Ok(())
            }
        };
        self.pub_point.update_refresh(cert.validity().not_after());
        self.pub_point.add_router_key(
            asns, id, key,
            Arc::new(PublishInfo::router_cert(
                &cert, uri, ca_cert.cert().tal().clone(),
                self.validity, self.point_stale,
            )),
        );
        Ok(())
    }

    fn process_roa(
        &mut self,
        _uri: &uri::Rsync,
        cert: ResourceCert,
        route: RouteOriginAttestation
    ) -> Result<(), Failed> {
        if self.pub_point.add_roa(
            route,
            Arc::new(PublishInfo::signed_object(
                &cert, self.validity, self.point_stale
            )),
            self.report.limit_v4_len, self.report.limit_v6_len,
        ) {
            self.pub_point.update_refresh(cert.validity().not_after());
        }
        Ok(())
    }

    fn process_aspa(
        &mut self,
        _uri: &uri::Rsync,
        cert: ResourceCert,
        aspa: AsProviderAttestation
    ) -> Result<(), Failed> {
        if !self.report.enable_aspa {
            return Ok(())
        }
        self.pub_point.update_refresh(cert.validity().not_after());
        self.pub_point.add_aspa(
            aspa,
            Arc::new(PublishInfo::signed_object(
                &cert, self.validity, self.point_stale
            ))
        );
        Ok(())
    }

    fn restart(&mut self) -> Result<(), Failed> {
        self.pub_point.restart();
        Ok(())
    }

    fn commit(self) {
        if !self.pub_point.is_empty() {
            self.report.pub_points.push(self.pub_point);
        }
    }

    fn cancel(self, cert: &CaCert) {
        if self.report.log_rejected {
            warn!(
                "CA for {} rejected, resources marked as unsafe:",
                cert.ca_repository()
            );
            for block in cert.cert().v4_resources().iter() {
                warn!("   {}", block.display_v4());
            }
            for block in cert.cert().v6_resources().iter() {
                warn!("   {}", block.display_v6());
            }
            for block in cert.cert().as_resources().iter() {
                warn!("   {block}");
            }
        }
        self.report.rejected.extend_from_cert(cert);
    }
}


//------------ PubPoint ------------------------------------------------------

/// The raw data published by a publication point.
///
/// This type collects all the data published so it is available for later
/// processing.
#[derive(Clone, Debug)]
pub struct PubPoint {
    /// The list of valid route origins.
    origins: Vec<PubRouteOrigin>,

    /// The list of valid router keys.
    router_keys: Vec<PubRouterKey>,

    /// The list of valid ASPA payload.
    aspas: Vec<PubAspa>,

    /// The time when the publication point needs to be refreshed.
    refresh: Time,

    /// The initial value of `refresh`.
    ///
    /// We need this for restarting processing.
    orig_refresh: Time,

    /// The index of the TALs for the payload in the metrics.
    tal_index: usize,

    /// The index of the repository containing the payload in the metrics.
    repository_index: Option<usize>,
}

impl PubPoint {
    /// Creates a new publication point.
    fn new(refresh: Time, tal_index: usize) -> Self {
        PubPoint {
            origins: Vec::new(),
            router_keys: Vec::new(),
            aspas: Vec::new(),
            refresh,
            orig_refresh: refresh,
            tal_index,
            repository_index: None,
        }
    }

    /// Creates a new publication point for a trust anchor CA.
    fn new_ta(cert: &CaCert, tal_index: usize) -> Self {
        Self::new(cert.cert().validity().not_after(), tal_index)
    }

    /// Creates a new publication for a regular CA.
    fn new_ca(parent: &PubPoint, cert: &CaCert) -> Self {
        Self::new(
            cmp::min(
                parent.refresh, cert.cert().validity().not_after()
            ),
            parent.tal_index,
        )
    }

    /// Returns whether there is nothing published via this point.
    pub fn is_empty(&self) -> bool {
        self.origins.is_empty()
        && self.router_keys.is_empty()
        && self.aspas.is_empty()
    }

    /// Updates the refresh time to be no later than the given time.
    fn update_refresh(&mut self, refresh: Time) {
        self.refresh = cmp::min(self.refresh, refresh)
    }

    /// Restarts processing for the publication point.
    fn restart(&mut self) {
        self.origins.clear();
        self.router_keys.clear();
        self.aspas.clear();
        self.refresh = self.orig_refresh;
    }

    /// Adds the content of a ROA to the payload.
    fn add_roa(
        &mut self,
        roa: RouteOriginAttestation,
        info: Arc<PublishInfo>,
        limit_v4_len: Option<u8>,
        limit_v6_len: Option<u8>,
    ) -> bool {
        let mut any = false;
        for origin in roa.iter_origins() {
            let limit = if origin.prefix.prefix().is_v4() {
                limit_v4_len
            }
            else {
                limit_v6_len
            };
            if let Some(limit) = limit {
                if origin.prefix.prefix().len() > limit {
                    continue;
                }
            }
            self.origins.push(PubRouteOrigin { origin, info: info.clone() });
            any = true;
        }
        any
    }

    /// Adds the content of a router key to the payload.
    fn add_router_key(
        &mut self,
        asns: AsBlocks,
        key_id: KeyIdentifier,
        key_info: RouterKeyInfo,
        info: Arc<PublishInfo>,
    ) {
        self.router_keys.push(
            PubRouterKey { asns, key_id, key_info, info }
        );
    }

    /// Adds the content of an ASPA object to the payload.
    fn add_aspa(
        &mut self,
        aspa: AsProviderAttestation,
        info: Arc<PublishInfo>,
    ) {
        self.aspas.push(
            PubAspa {
                customer: aspa.customer_as(),
                providers: aspa.provider_as_set().to_set(),
                info
            }
        )
    }
}


//------------ PubRouteOrigin ------------------------------------------------

/// The payload of a published route origin.
#[derive(Clone, Debug)]
pub struct PubRouteOrigin {
    /// The route origin to be published.
    pub origin: RouteOrigin,

    /// Information on the source of the payload.
    pub info: Arc<PublishInfo>,
}


//------------ PubRouterKey --------------------------------------------------

/// The raw information from a router key certificate.
#[derive(Clone, Debug)]
pub struct PubRouterKey {
    /// The ASNs which use the router key.
    pub asns: AsBlocks,

    /// The key identifier.
    pub key_id: KeyIdentifier,

    /// The key itself.
    pub key_info: RouterKeyInfo,

    /// Information on the source of the payload.
    pub info: Arc<PublishInfo>,
}


//------------ PubAspa -------------------------------------------------------

/// The raw information from a published ASPA object.
#[derive(Clone, Debug)]
pub struct PubAspa {
    /// The customer AS of the ASPA.
    pub customer: Asn,

    /// The set of providers.
    pub providers: SmallAsnSet,

    /// Information on the source of the payload.
    pub info: Arc<PublishInfo>,
}


//------------ RejectedResources ---------------------------------------------

/// The resources from publication points that had to be rejected.
#[derive(Clone, Debug)]
pub struct RejectedResources {
    v4: IpBlocks,
    v6: IpBlocks,
}

impl RejectedResources {
    /// Checks whether a prefix should be kept.
    pub fn keep_prefix(&self, prefix: Prefix) -> bool {
        let raw = rpki::repository::resources::Prefix::new(
            prefix.addr(), prefix.len()
        );
        if prefix.is_v4() {
            !self.v4.intersects_block(raw)
        }
        else {
            !self.v6.intersects_block(raw)
        }
    }
}


//------------ RejectedResourcesBuilder --------------------------------------

/// A builder for invalid resources encountered during validation.
#[derive(Debug, Default)]
struct RejectedResourcesBuilder {
    /// The queue of rejected IP blocks.
    ///
    /// The first element is whether the block is for IPv4.
    addrs: SegQueue<(bool, IpBlock)>,

    /// The queue of rejected AS blocks.
    asns: SegQueue<AsBlock>,
}

impl RejectedResourcesBuilder {
    fn extend_from_cert(&self, cert: &CaCert) {
        for block in cert.cert().v4_resources().iter().filter(|block|
            !block.is_slash_zero()
        ) {
            self.addrs.push((true, block));
        }
        for block in cert.cert().v6_resources().iter().filter(|block|
            !block.is_slash_zero()
        ) {
            self.addrs.push((false, block));
        }
        for block in cert.cert().as_resources().iter().filter(|block|
            !block.is_whole_range()
        ) {
            self.asns.push(block)
        }
    }

    fn finalize(self) -> RejectedResources {
        let mut v4 = IpBlocksBuilder::new();
        let mut v6 = IpBlocksBuilder::new();
        while let Some((is_v4, block)) = self.addrs.pop() {
            if is_v4 {
                v4.push(block);
            }
            else {
                v6.push(block);
            }
        }
        RejectedResources {
            v4: v4.finalize(),
            v6: v6.finalize(),
        }
    }
}


//------------ SnapshotBuilder -----------------------------------------------

/// Helps turning the report into a payload snapshot.
struct SnapshotBuilder<'a> {
    /// The collected route origins.
    origins: HashMap<RouteOrigin, PayloadInfo>,

    /// The collected router keys.
    router_keys: HashMap<RouterKey, PayloadInfo>,

    /// The collected ASPA payload.
    ///
    /// The key is the customer ASN.
    aspas: HashMap<Asn, (SmallAsnSet, PayloadInfo)>,

    /// The list of rejected resources.
    rejected: RejectedResources,

    /// How are we dealing with unsafe VRPs?
    unsafe_vrps: FilterPolicy,

    /// Are unsafe VRPs present?
    unsafe_vrps_present: bool,

    /// The time when this snapshot needs to be refreshed at the latest.
    refresh: Option<Time>,

    exceptions: &'a LocalExceptions,
}

impl<'a> SnapshotBuilder<'a> {
    fn new(
        rejected: RejectedResources,
        unsafe_vrps: FilterPolicy,
        exceptions: &'a LocalExceptions,
        
    ) -> Self {
        Self {
            origins: Default::default(),
            router_keys: Default::default(),
            aspas: Default::default(),
            rejected,
            unsafe_vrps,
            unsafe_vrps_present: false,
            refresh: None,
            exceptions,
        }
    }


    fn process_pub_point(
        &mut self, point: PubPoint, metrics: &mut Metrics
    ) {
        let mut metrics = AllVrpMetrics::new(
            metrics, point.tal_index, point.repository_index,
        );
        self.update_refresh(point.refresh);
        point.origins.into_iter().for_each(|item| {
            self.process_origin(item, &mut metrics)
        });
        point.router_keys.into_iter().for_each(|item| {
            self.process_key(item, &mut metrics)
        });
        point.aspas.into_iter().for_each(|item| {
            self.process_aspa(item, &mut metrics)
        });
    }

    /// Updates the refresh time.
    fn update_refresh(&mut self, refresh: Time) {
        self.refresh = match self.refresh {
            Some(old) => Some(cmp::min(old, refresh)),
            None => Some(refresh)
        }
    }

    fn process_origin(
        &mut self, origin: PubRouteOrigin, metrics: &mut AllVrpMetrics,
    ) {
        let v4 = origin.origin.is_v4();
        metrics.update_origin(v4, |m| m.valid += 1);

        // Is the prefix in the rejected resources?
        if !self.rejected.keep_prefix(origin.origin.prefix.prefix()) {
            self.unsafe_vrps_present = true;
            match self.unsafe_vrps {
                FilterPolicy::Accept => {
                    // Don’t count, don’t warn ...
                }
                FilterPolicy::Warn => {
                    metrics.update_origin(v4, |m| m.marked_unsafe += 1);
                    info!(
                        "Encountered potentially unsafe VRP \
                         ({}/{}-{}, {})",
                        origin.origin.prefix.addr(),
                        origin.origin.prefix.prefix_len(),
                        origin.origin.prefix.resolved_max_len(),
                        origin.origin.asn
                    );
                }
                FilterPolicy::Reject => {
                    metrics.update_origin(v4, |m| m.marked_unsafe += 1);
                    warn!(
                        "Filtering potentially unsafe VRP \
                         ({}/{}-{}, {})",
                        origin.origin.prefix.addr(),
                        origin.origin.prefix.prefix_len(),
                        origin.origin.prefix.resolved_max_len(),
                        origin.origin.asn
                    );
                    return
                }
            }
        }

        // Is the origin to be filtered locally?
        if self.exceptions.drop_origin(origin.origin) {
            metrics.update_origin(v4, |m| m.locally_filtered += 1);
            return
        }

        // Insert the origin. If we have it already, we need to
        // update its info instead.
        match self.origins.entry(origin.origin) {
            hash_map::Entry::Vacant(entry) => {
                entry.insert(origin.info.into());
                metrics.update_origin(v4, |m| m.contributed += 1);
            }
            hash_map::Entry::Occupied(mut entry) => {
                entry.get_mut().add_published(origin.info);
                metrics.update_origin(v4, |m| m.duplicate += 1);
            }
        }
    }

    fn process_key(
        &mut self, key: PubRouterKey, metrics: &mut AllVrpMetrics,
    ) {
        metrics.update(|m| m.router_keys.valid += key.asns.asn_count());

        // Now for each ASN.
        for asn in key.asns.iter_asns() {
            let router_key = RouterKey::new(
                key.key_id, asn, key.key_info.clone()
            );

            // Is the key to be filtered locally?
            if self.exceptions.drop_router_key(&router_key) {
                metrics.update(|m| m.router_keys.locally_filtered += 1);
                continue
            }

            // Insert the key. If we have it already, we need to
            // update its info instead.
            match self.router_keys.entry(router_key) {
                hash_map::Entry::Vacant(entry) => {
                    entry.insert(key.info.clone().into());
                    metrics.update(|m| m.router_keys.contributed += 1);
                }
                hash_map::Entry::Occupied(mut entry) => {
                    entry.get_mut().add_published(key.info.clone());
                    metrics.update(|m| m.router_keys.duplicate += 1);
                }
            }
        }
    }

    fn process_aspa(&mut self, aspa: PubAspa, metrics: &mut AllVrpMetrics) {
        metrics.update(|m| m.aspas.valid += 1);

        // SLURM filtering goes here ...

        match self.aspas.entry(aspa.customer) {
            hash_map::Entry::Vacant(entry) => {
                entry.insert((aspa.providers, aspa.info.into()));
                metrics.update(|m| m.aspas.contributed += 1);
            }
            hash_map::Entry::Occupied(mut entry) => {
                let entry = entry.get_mut();
                entry.0 = entry.0.union(&aspa.providers).collect();
                entry.1.add_published(aspa.info);
                metrics.update(|m| m.aspas.duplicate += 1);
            }
        }
    }

    fn finalize(mut self, metrics: &mut Metrics) -> PayloadSnapshot {
        if self.unsafe_vrps_present && self.unsafe_vrps.log()  {
            warn!(
                "For more information on unsafe VRPs, see \
                 https://routinator.docs.nlnetlabs.nl\
                 /en/stable/unsafe-vrps.html"
            );
        }

        self.insert_assertions(metrics);
        metrics.finalize();
        self.into_snapshot(metrics)
    }

    fn insert_assertions(&mut self, metrics: &mut Metrics) {
        for (origin, info) in self.exceptions.origin_assertions() {
            match self.origins.entry(origin) {
                hash_map::Entry::Vacant(entry) => {
                    entry.insert(info.into());
                    if origin.is_v4() {
                        metrics.local.v4_origins.contributed += 1;
                        metrics.snapshot.payload.v4_origins.contributed += 1;
                    }
                    else {
                        metrics.local.v6_origins.contributed += 1;
                        metrics.snapshot.payload.v6_origins.contributed += 1;
                    }
                }
                hash_map::Entry::Occupied(mut entry) => {
                    entry.get_mut().add_local(info);
                    if origin.is_v4() {
                        metrics.local.v4_origins.duplicate += 1;
                        metrics.snapshot.payload.v4_origins.duplicate += 1;
                    }
                    else {
                        metrics.local.v6_origins.duplicate += 1;
                        metrics.snapshot.payload.v6_origins.duplicate += 1;
                    }
                }
            }
        }

        for (key, info) in self.exceptions.router_key_assertions() {
            match self.router_keys.entry(key) {
                hash_map::Entry::Vacant(entry) => {
                    entry.insert(info.into());
                    metrics.local.router_keys.contributed += 1;
                    metrics.snapshot.payload.router_keys.contributed += 1;
                }
                hash_map::Entry::Occupied(mut entry) => {
                    entry.get_mut().add_local(info);
                    metrics.local.router_keys.duplicate += 1;
                    metrics.snapshot.payload.router_keys.duplicate += 1;
                }
            }
        }

        // XXX ASPA assertions.
    }

    fn into_snapshot(self, metrics: &mut Metrics) -> PayloadSnapshot {
        PayloadSnapshot::new(
            self.origins.into_iter(),
            self.router_keys.into_iter(),
            self.aspas.into_iter().filter_map(
                |(customer, (providers, info))| {
                    match ProviderAsns::try_from_iter(providers.iter()) {
                        Ok(providers) => {
                            Some((Aspa::new(customer, providers), info))
                        }
                        Err(_) => {
                            warn!(
                                "Ignoring excessively large ASPA for {} \
                                 with {} provider ASNs.",
                                customer, providers.len()
                            );
                            metrics.snapshot.large_aspas += 1;
                            None
                        }
                    }
                }
            ),
            self.refresh,
        )
    }
}


//------------ AllVrpMetrics -------------------------------------------------

/// A helper struct to simplify changing all VRP metrics for a repository.
pub struct AllVrpMetrics<'a> {
    tal: &'a mut PayloadMetrics,
    repo: Option<&'a mut PayloadMetrics>,
    all: &'a mut PayloadMetrics,
}

impl<'a> AllVrpMetrics<'a> {
    pub fn new(
        metrics: &'a mut Metrics, tal_index: usize, repo_index: Option<usize>,
    ) -> Self {
        AllVrpMetrics {
            tal: &mut metrics.tals[tal_index].payload,
            repo: match repo_index {
                Some(index) => Some(&mut metrics.repositories[index].payload),
                None => None
            },
            all: &mut metrics.snapshot.payload,
        }
    }

    pub fn update(&mut self, op: impl Fn(&mut PayloadMetrics)) {
        op(self.tal);
        if let Some(ref mut repo) = self.repo {
            op(repo)
        }
        op(self.all)
    }

    pub fn update_origin(&mut self, v4: bool, op: impl Fn(&mut VrpMetrics)) {
        self.update(|metrics| {
            if v4 {
                op(&mut metrics.v4_origins)
            }
            else {
                op(&mut metrics.v6_origins)
            }
        })
    }
}