krill 0.9.0

Resource Public Key Infrastructure (RPKI) daemon
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
use std::cmp::Ordering;
use std::fmt;
use std::net::IpAddr;
use std::ops::Deref;
use std::str::FromStr;

use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

use rpki::resources::{AsBlocks, AsId, IpBlocks, IpBlocksBuilder, Prefix};
use rpki::roa::RoaIpAddress;

use crate::commons::api::ResourceSet;
use crate::daemon::ca::RouteAuthorizationUpdates;

//------------ RoaAggregateKey ---------------------------------------------

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct RoaAggregateKey {
    asn: AsNumber,
    group: Option<u32>,
}

impl RoaAggregateKey {
    pub fn new(asn: AsNumber, group: Option<u32>) -> Self {
        RoaAggregateKey { asn, group }
    }

    pub fn asn(&self) -> AsNumber {
        self.asn
    }

    pub fn group(&self) -> Option<u32> {
        self.group
    }
}

impl fmt::Display for RoaAggregateKey {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.group {
            None => write!(f, "AS{}", self.asn),
            Some(nr) => write!(f, "AS{}-{}", self.asn, nr),
        }
    }
}

impl FromStr for RoaAggregateKey {
    type Err = RoaAggregateKeyFmtError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut parts = s.split('-');

        let asn_part = parts.next().ok_or_else(|| RoaAggregateKeyFmtError::string(s))?;

        if !asn_part.starts_with("AS") || asn_part.len() < 3 {
            return Err(RoaAggregateKeyFmtError::string(s));
        }

        let asn = AsNumber::from_str(&asn_part[2..]).map_err(|_| RoaAggregateKeyFmtError::string(s))?;

        let group = if let Some(group) = parts.next() {
            let group = u32::from_str(group).map_err(|_| RoaAggregateKeyFmtError::string(s))?;
            Some(group)
        } else {
            None
        };

        if parts.next().is_some() {
            Err(RoaAggregateKeyFmtError::string(s))
        } else {
            Ok(RoaAggregateKey { asn, group })
        }
    }
}

/// We use RoaGroup as (json) map keys and therefore we need it
/// to be serializable to a single simple string.
impl Serialize for RoaAggregateKey {
    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.to_string().serialize(s)
    }
}

/// We use RoaGroup as (json) map keys and therefore we need it
/// to be deserializable from a single simple string.
impl<'de> Deserialize<'de> for RoaAggregateKey {
    fn deserialize<D>(d: D) -> Result<RoaAggregateKey, D::Error>
    where
        D: Deserializer<'de>,
    {
        let string = String::deserialize(d)?;
        RoaAggregateKey::from_str(string.as_str()).map_err(de::Error::custom)
    }
}

/// Ordering is based on ASN first, and group second if there are
/// multiple keys for the same ASN. Note: we don't currently use
/// such groups. It's here in case we want to give users more
/// options in future.
impl Ord for RoaAggregateKey {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.asn.cmp(&other.asn) {
            Ordering::Equal => self.group.cmp(&other.group),
            Ordering::Greater => Ordering::Greater,
            Ordering::Less => Ordering::Less,
        }
    }
}

impl PartialOrd for RoaAggregateKey {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

//------------ AuthorizationFmtError -------------------------------------

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RoaAggregateKeyFmtError(String);

impl fmt::Display for RoaAggregateKeyFmtError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Invalid ROA Group format ({})", self.0)
    }
}

impl RoaAggregateKeyFmtError {
    fn string(s: &str) -> Self {
        RoaAggregateKeyFmtError(s.to_string())
    }
}

//------------ RoaDefinition -----------------------------------------------

/// This type defines the definition of a Route Origin Authorization (ROA), i.e.
/// the originating asn, IPv4 or IPv6 prefix, and optionally a max length.
#[derive(Clone, Copy, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct RoaDefinition {
    asn: AsNumber,
    prefix: TypedPrefix,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_length: Option<u8>,
}

impl RoaDefinition {
    pub fn new(asn: AsNumber, prefix: TypedPrefix, max_length: Option<u8>) -> Self {
        RoaDefinition {
            asn,
            prefix,
            max_length,
        }
    }

    pub fn explicit_max_length(self) -> Self {
        RoaDefinition {
            asn: self.asn,
            prefix: self.prefix,
            max_length: Some(self.effective_max_length()),
        }
    }

    pub fn as_roa_ip_address(&self) -> RoaIpAddress {
        RoaIpAddress::new(*self.prefix.prefix(), self.max_length)
    }

    pub fn asn(&self) -> AsNumber {
        self.asn
    }

    pub fn prefix(&self) -> TypedPrefix {
        self.prefix
    }

    pub fn max_length(&self) -> Option<u8> {
        self.max_length
    }

    pub fn effective_max_length(&self) -> u8 {
        match self.max_length {
            None => self.prefix.addr_len(),
            Some(len) => len,
        }
    }

    pub fn nr_of_specific_prefixes(&self) -> u128 {
        let pfx_len = self.prefix.addr_len();
        let max_len = self.effective_max_length();

        // 10.0.0.0/8-8 -> 1   2^0
        // 10.0.0.0/8-9 -> 2   2^1
        // 10.0.0.0/8-10 -> 4  2^2
        // 10.0.0.0/8-11 -> 8  2^3

        1u128 << (max_len - pfx_len)
    }

    pub fn max_length_valid(&self) -> bool {
        if let Some(max_length) = self.max_length {
            match self.prefix {
                TypedPrefix::V4(_) => max_length >= self.prefix.addr_len() && max_length <= 32,
                TypedPrefix::V6(_) => max_length >= self.prefix.addr_len() && max_length <= 128,
            }
        } else {
            true
        }
    }

    /// Returns `true` if the this definition includes the other definition.
    pub fn includes(&self, other: &RoaDefinition) -> bool {
        self.asn == other.asn
            && self.prefix.matching_or_less_specific(&other.prefix)
            && self.effective_max_length() >= other.effective_max_length()
    }

    /// Returns `true` if this is an AS0 definition which overlaps the other.
    pub fn overlaps(&self, other: &RoaDefinition) -> bool {
        self.prefix.matching_or_less_specific(&other.prefix) || other.prefix.matching_or_less_specific(&self.prefix)
    }
}

impl FromStr for RoaDefinition {
    type Err = AuthorizationFmtError;

    // "192.168.0.0/16 => 64496"
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut parts = s.split("=>");

        let prefix_part = parts.next().ok_or_else(|| AuthorizationFmtError::auth(s))?;
        let mut prefix_parts = prefix_part.split('-');
        let prefix_str = prefix_parts.next().ok_or_else(|| AuthorizationFmtError::auth(s))?;

        let prefix = TypedPrefix::from_str(&prefix_str.trim())?;

        let max_length = match prefix_parts.next() {
            None => None,
            Some(length_str) => Some(u8::from_str(&length_str.trim()).map_err(|_| AuthorizationFmtError::auth(s))?),
        };

        let asn_str = parts.next().ok_or_else(|| AuthorizationFmtError::auth(s))?;
        if parts.next().is_some() {
            return Err(AuthorizationFmtError::auth(s));
        }
        let origin = AsNumber::from_str(&asn_str.trim())?;

        Ok(RoaDefinition {
            asn: origin,
            prefix,
            max_length,
        })
    }
}

impl fmt::Debug for RoaDefinition {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", &self)
    }
}

impl fmt::Display for RoaDefinition {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.max_length {
            None => write!(f, "{} => {}", self.prefix, self.asn),
            Some(length) => write!(f, "{}-{} => {}", self.prefix, length, self.asn),
        }
    }
}

impl Ord for RoaDefinition {
    fn cmp(&self, other: &Self) -> Ordering {
        let mut ordering = self.prefix.cmp(&other.prefix);

        if ordering == Ordering::Equal {
            ordering = self.effective_max_length().cmp(&other.effective_max_length());
        }

        if ordering == Ordering::Equal {
            ordering = self.asn.cmp(&other.asn);
        }

        ordering
    }
}

impl PartialOrd for RoaDefinition {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl AsRef<TypedPrefix> for RoaDefinition {
    fn as_ref(&self) -> &TypedPrefix {
        &self.prefix
    }
}

#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct RoaDefinitions(Vec<RoaDefinition>);

impl fmt::Display for RoaDefinitions {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for def in self.0.iter() {
            writeln!(f, "{}", def)?;
        }
        Ok(())
    }
}

//------------ RouteAuthorizationUpdates -----------------------------------

/// This type defines a delta of Route Authorizations, i.e. additions or removals
/// of authorizations of tuples of (Prefix, Max Length, ASN) that ultimately
/// are put into ROAs by a CA, in as far as the CA has the required prefixes
/// on its resource certificates.
///
/// Multiple updates are sent as a single delta, because it's important that
/// all authorizations for a given prefix are published together in order to
/// avoid invalidating announcements.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct RoaDefinitionUpdates {
    added: Vec<RoaDefinition>,
    removed: Vec<RoaDefinition>,
}

impl RoaDefinitionUpdates {
    pub fn is_empty(&self) -> bool {
        self.added.is_empty() && self.removed.is_empty()
    }

    pub fn new(added: Vec<RoaDefinition>, removed: Vec<RoaDefinition>) -> Self {
        RoaDefinitionUpdates { added, removed }
    }

    /// Unpack this and return all added (left), and all removed (right) route
    /// authorizations.
    pub fn unpack(self) -> (Vec<RoaDefinition>, Vec<RoaDefinition>) {
        (self.added, self.removed)
    }

    pub fn empty() -> Self {
        Self::default()
    }

    pub fn add(&mut self, add: RoaDefinition) {
        self.added.push(add);
    }

    pub fn added(&self) -> &Vec<RoaDefinition> {
        &self.added
    }

    pub fn removed(&self) -> &Vec<RoaDefinition> {
        &self.removed
    }

    pub fn remove(&mut self, rem: RoaDefinition) {
        self.removed.push(rem);
    }
}

impl Default for RoaDefinitionUpdates {
    fn default() -> Self {
        RoaDefinitionUpdates {
            added: vec![],
            removed: vec![],
        }
    }
}

impl fmt::Display for RoaDefinitionUpdates {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for a in &self.added {
            writeln!(f, "A: {}", a)?;
        }
        for r in &self.removed {
            writeln!(f, "R: {}", r)?;
        }
        Ok(())
    }
}

impl FromStr for RoaDefinitionUpdates {
    type Err = AuthorizationFmtError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut added = vec![];
        let mut removed = vec![];

        for line in s.lines() {
            let line = match line.find('#') {
                None => &line,
                Some(pos) => &line[..pos],
            };
            let line = line.trim();

            if line.is_empty() {
                continue;
            } else if let Some(stripped) = line.strip_prefix("A:") {
                let auth = RoaDefinition::from_str(stripped.trim())?;
                added.push(auth);
            } else if let Some(stripped) = line.strip_prefix("R:") {
                let auth = RoaDefinition::from_str(stripped.trim())?;
                removed.push(auth);
            } else {
                return Err(AuthorizationFmtError::delta(line));
            }
        }

        Ok(RoaDefinitionUpdates { added, removed })
    }
}

impl From<RouteAuthorizationUpdates> for RoaDefinitionUpdates {
    fn from(auth_updates: RouteAuthorizationUpdates) -> Self {
        let (auth_added, auth_removed) = auth_updates.unpack();
        let added = auth_added.into_iter().map(|a| a.into()).collect();
        let removed = auth_removed.into_iter().map(|a| a.into()).collect();
        RoaDefinitionUpdates { added, removed }
    }
}

//------------ TypedPrefix -------------------------------------------------
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub enum TypedPrefix {
    V4(Ipv4Prefix),
    V6(Ipv6Prefix),
}

impl TypedPrefix {
    pub fn prefix(&self) -> &Prefix {
        self.as_ref()
    }

    pub fn ip_addr(&self) -> IpAddr {
        match self {
            TypedPrefix::V4(v4) => IpAddr::V4(v4.0.to_v4()),
            TypedPrefix::V6(v6) => IpAddr::V6(v6.0.to_v6()),
        }
    }

    fn matches_type(&self, other: &TypedPrefix) -> bool {
        match &self {
            TypedPrefix::V4(_) => match other {
                TypedPrefix::V4(_) => true,
                TypedPrefix::V6(_) => false,
            },
            TypedPrefix::V6(_) => match other {
                TypedPrefix::V4(_) => false,
                TypedPrefix::V6(_) => true,
            },
        }
    }

    pub fn matching_or_less_specific(&self, other: &TypedPrefix) -> bool {
        self.matches_type(other)
            && self.prefix().min().le(&other.prefix().min())
            && self.prefix().max().ge(&other.prefix().max())
    }
}

impl FromStr for TypedPrefix {
    type Err = AuthorizationFmtError;

    fn from_str(prefix: &str) -> Result<Self, Self::Err> {
        if prefix.contains('.') {
            Ok(TypedPrefix::V4(Ipv4Prefix(
                Prefix::from_v4_str(prefix.trim()).map_err(|_| AuthorizationFmtError::pfx(prefix))?,
            )))
        } else {
            Ok(TypedPrefix::V6(Ipv6Prefix(
                Prefix::from_v6_str(prefix.trim()).map_err(|_| AuthorizationFmtError::pfx(prefix))?,
            )))
        }
    }
}

impl fmt::Debug for TypedPrefix {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", &self)
    }
}

impl fmt::Display for TypedPrefix {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            TypedPrefix::V4(pfx) => pfx.fmt(f),
            TypedPrefix::V6(pfx) => pfx.fmt(f),
        }
    }
}

impl Ord for TypedPrefix {
    fn cmp(&self, other: &Self) -> Ordering {
        let mut ordering = self.addr().cmp(&other.addr());
        if ordering == Ordering::Equal {
            ordering = self.addr_len().cmp(&other.addr_len())
        }
        ordering
    }
}

impl PartialOrd for TypedPrefix {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl AsRef<Prefix> for TypedPrefix {
    fn as_ref(&self) -> &Prefix {
        match self {
            TypedPrefix::V4(v4) => &v4.0,
            TypedPrefix::V6(v6) => &v6.0,
        }
    }
}

impl Deref for TypedPrefix {
    type Target = Prefix;

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

impl Serialize for TypedPrefix {
    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.to_string().serialize(s)
    }
}

impl<'de> Deserialize<'de> for TypedPrefix {
    fn deserialize<D>(d: D) -> Result<TypedPrefix, D::Error>
    where
        D: Deserializer<'de>,
    {
        let string = String::deserialize(d)?;
        TypedPrefix::from_str(string.as_str()).map_err(de::Error::custom)
    }
}

impl From<TypedPrefix> for ResourceSet {
    fn from(tp: TypedPrefix) -> ResourceSet {
        match tp {
            TypedPrefix::V4(v4) => {
                let mut builder = IpBlocksBuilder::new();
                builder.push(v4.0);
                let blocks = builder.finalize();

                ResourceSet::new(AsBlocks::empty(), blocks, IpBlocks::empty())
            }
            TypedPrefix::V6(v6) => {
                let mut builder = IpBlocksBuilder::new();
                builder.push(v6.0);
                let blocks = builder.finalize();

                ResourceSet::new(AsBlocks::empty(), IpBlocks::empty(), blocks)
            }
        }
    }
}

//------------ Ipv4Prefix --------------------------------------------------
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct Ipv4Prefix(Prefix);

impl AsRef<Prefix> for Ipv4Prefix {
    fn as_ref(&self) -> &Prefix {
        &self.0
    }
}

impl fmt::Display for Ipv4Prefix {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}/{}", self.0.to_v4(), self.0.addr_len())
    }
}

impl fmt::Debug for Ipv4Prefix {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", &self)
    }
}

//------------ Ipv6Prefix --------------------------------------------------
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct Ipv6Prefix(Prefix);

impl AsRef<Prefix> for Ipv6Prefix {
    fn as_ref(&self) -> &Prefix {
        &self.0
    }
}

impl fmt::Display for Ipv6Prefix {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}/{}", self.0.to_v6(), self.0.addr_len())
    }
}

impl fmt::Debug for Ipv6Prefix {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", &self)
    }
}

//------------ AsNumber ----------------------------------------------------

#[derive(Clone, Copy, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct AsNumber(u32);

impl AsNumber {
    pub fn new(number: u32) -> Self {
        AsNumber(number)
    }

    pub fn zero() -> Self {
        AsNumber(0)
    }
}

impl From<AsNumber> for AsId {
    fn from(asn: AsNumber) -> Self {
        AsId::from(asn.0)
    }
}

impl FromStr for AsNumber {
    type Err = AuthorizationFmtError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();
        let number = u32::from_str(s).map_err(|_| AuthorizationFmtError::asn(s))?;
        Ok(AsNumber(number))
    }
}

impl fmt::Debug for AsNumber {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", &self)
    }
}

impl fmt::Display for AsNumber {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Ord for AsNumber {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.cmp(&other.0)
    }
}

impl PartialOrd for AsNumber {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

//------------ AuthorizationFmtError -------------------------------------

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AuthorizationFmtError {
    Pfx(String),
    Asn(String),
    Auth(String),
    Delta(String),
}

impl fmt::Display for AuthorizationFmtError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AuthorizationFmtError::Pfx(s) => write!(f, "Invalid prefix string: {}", s),
            AuthorizationFmtError::Asn(s) => write!(f, "Invalid asn in string: {}", s),
            AuthorizationFmtError::Auth(s) => write!(f, "Invalid authorization string: {}", s),
            AuthorizationFmtError::Delta(s) => write!(f, "Invalid authorization delta string: {}", s),
        }
    }
}

impl AuthorizationFmtError {
    fn pfx(s: &str) -> Self {
        AuthorizationFmtError::Pfx(s.to_string())
    }

    fn asn(s: &str) -> Self {
        AuthorizationFmtError::Asn(s.to_string())
    }

    pub fn auth(s: &str) -> Self {
        AuthorizationFmtError::Auth(s.to_string())
    }

    pub fn delta(s: &str) -> Self {
        AuthorizationFmtError::Delta(s.to_string())
    }
}

//------------ Tests -------------------------------------------------------

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

    use crate::test::definition;

    #[test]
    fn parse_delta() {
        let delta = concat!(
            "# Some comment\n",
            "  # Indented comment\n",
            "\n", // empty line
            "A: 192.168.0.0/16 => 64496 # inline comment\n",
            "A: 192.168.1.0/24 => 64496\n",
            "R: 192.168.3.0/24 => 64496\n",
        );

        let expected = {
            let added = vec![
                definition("192.168.0.0/16 => 64496"),
                definition("192.168.1.0/24 => 64496"),
            ];

            let removed = vec![definition("192.168.3.0/24 => 64496")];
            RoaDefinitionUpdates::new(added, removed)
        };

        let parsed = RoaDefinitionUpdates::from_str(delta).unwrap();
        assert_eq!(expected, parsed);

        let re_parsed = RoaDefinitionUpdates::from_str(&parsed.to_string()).unwrap();
        assert_eq!(parsed, re_parsed);
    }

    #[test]
    fn parse_type_prefix() {
        assert!(TypedPrefix::from_str("192.168.0.0/16").is_ok());
        assert!(TypedPrefix::from_str("2001:db8::/32").is_ok());
    }

    #[test]
    fn normalize_roa_definition_json() {
        let def = definition("192.168.0.0/16 => 64496");
        let json = serde_json::to_string(&def).unwrap();
        let expected = "{\"asn\":64496,\"prefix\":\"192.168.0.0/16\"}";
        assert_eq!(json, expected);

        let def = definition("192.168.0.0/16-24 => 64496");
        let json = serde_json::to_string(&def).unwrap();
        let expected = "{\"asn\":64496,\"prefix\":\"192.168.0.0/16\",\"max_length\":24}";
        assert_eq!(json, expected);
    }

    #[test]
    fn serde_roa_definition() {
        fn parse_ser_de_print_definition(s: &str) {
            let def = definition(s);
            let ser = serde_json::to_string(&def).unwrap();
            let de = serde_json::from_str(&ser).unwrap();
            assert_eq!(def, de);
            assert_eq!(s, de.to_string().as_str())
        }

        parse_ser_de_print_definition("192.168.0.0/16 => 64496");
        parse_ser_de_print_definition("192.168.0.0/16-24 => 64496");
        parse_ser_de_print_definition("2001:db8::/32 => 64496");
        parse_ser_de_print_definition("2001:db8::/32-48 => 64496");
    }

    #[test]
    fn roa_max_length() {
        fn valid_max_length(s: &str) {
            let def = RoaDefinition::from_str(s).unwrap();
            assert!(def.max_length_valid())
        }

        fn invalid_max_length(s: &str) {
            let def = RoaDefinition::from_str(s).unwrap();
            assert!(!def.max_length_valid())
        }

        valid_max_length("192.168.0.0/16 => 64496");
        valid_max_length("192.168.0.0/16-16 => 64496");
        valid_max_length("192.168.0.0/16-24 => 64496");
        valid_max_length("192.168.0.0/16-32 => 64496");
        valid_max_length("2001:db8::/32 => 64496");
        valid_max_length("2001:db8::/32-32 => 64496");
        valid_max_length("2001:db8::/32-48 => 64496");
        valid_max_length("2001:db8::/32-128 => 64496");

        invalid_max_length("192.168.0.0/16-15 => 64496");
        invalid_max_length("192.168.0.0/16-33 => 64496");
        invalid_max_length("2001:db8::/32-31 => 64496");
        invalid_max_length("2001:db8::/32-129 => 64496");
    }

    #[test]
    fn roa_includes() {
        let covering = definition("192.168.0.0/16-20 => 64496");

        let included_no_ml = definition("192.168.0.0/16 => 64496");
        let included_more_specific = definition("192.168.0.0/20 => 64496");

        let allowing_more_specific = definition("192.168.0.0/16-24 => 64496");
        let more_specific = definition("192.168.3.0/24 => 64496");
        let other_asn = definition("192.168.3.0/24 => 64497");

        assert!(covering.includes(&included_no_ml));
        assert!(covering.includes(&included_more_specific));

        assert!(!covering.includes(&more_specific));
        assert!(!covering.includes(&allowing_more_specific));
        assert!(!covering.includes(&other_asn));
    }

    #[test]
    fn roa_group_string() {
        let roa_group_asn_only = RoaAggregateKey {
            asn: AsNumber::new(0),
            group: None,
        };

        let roa_group_asn_only_expected_str = "AS0";
        assert_eq!(roa_group_asn_only.to_string().as_str(), roa_group_asn_only_expected_str);

        let roa_group_asn_only_expected = RoaAggregateKey::from_str(roa_group_asn_only_expected_str).unwrap();
        assert_eq!(roa_group_asn_only, roa_group_asn_only_expected)
    }

    #[test]
    fn roa_nr_specific_pfx() {
        fn check(def: &str, expected: u128) {
            let def = definition(def);
            let calculated = def.nr_of_specific_prefixes();
            assert_eq!(calculated, expected);
        }

        check("10.0.0.0/15-15 => 64496", 1);
        check("10.0.0.0/15-16 => 64496", 2);
        check("10.0.0.0/15-17 => 64496", 4);
        check("10.0.0.0/15-18 => 64496", 8);
    }
}