Debian Codegraph @

src/iana.rs

raw
1 //! The IANA RDAP Bootstrap Registries.
2
3 use {
4 ipnet::{Ipv4Net, Ipv6Net},
5 prefix_trie::PrefixMap,
6 serde::{Deserialize, Serialize},
7 thiserror::Error,
8 };
9
10 /// IANA registry variants for RDAP.
11 #[derive(Debug, Serialize, Deserialize, Clone)]
12 pub enum IanaRegistryType {
13 RdapBootstrapDns,
14 RdapBootstrapAsn,
15 RdapBootstrapIpv4,
16 RdapBootstrapIpv6,
17 RdapObjectTags,
18 }
19
20 impl IanaRegistryType {
21 /// Get the URL for an IANA RDAP registry.
22 pub fn url(&self) -> &str {
23 match self {
24 Self::RdapBootstrapDns => "https://data.iana.org/rdap/dns.json",
25 Self::RdapBootstrapAsn => "https://data.iana.org/rdap/asn.json",
26 Self::RdapBootstrapIpv4 => "https://data.iana.org/rdap/ipv4.json",
27 Self::RdapBootstrapIpv6 => "https://data.iana.org/rdap/ipv6.json",
28 Self::RdapObjectTags => "https://data.iana.org/rdap/object-tags.json",
29 }
30 }
31
32 /// Get the filename in the URL for the IANA RDAP registry.
33 pub fn file_name(&self) -> &str {
34 let url = self.url();
35 url.rsplit('/')
36 .next()
37 .expect("unexpected error: cannot get filename from url")
38 }
39 }
40
41 /// Classes of IANA registries.
42 #[derive(Debug, Serialize, Deserialize, Clone)]
43 #[serde(untagged)]
44 pub enum IanaRegistry {
45 RdapBootstrapRegistry(RdapBootstrapRegistry),
46 // might add IANA registrar IDs later
47 }
48
49 /// Represents an IANA RDAP bootstrap registry.
50 #[derive(Debug, Serialize, Deserialize, Clone)]
51 pub struct RdapBootstrapRegistry {
52 pub version: String,
53 pub publication: String,
54 pub description: Option<String>,
55 pub services: Vec<Vec<Vec<String>>>,
56 }
57
58 pub trait BootstrapRegistry {
59 fn get_dns_bootstrap_urls(
60 &self,
61 ldh: &str,
62 ) -> Result<Option<Vec<String>>, BootstrapRegistryError>;
63 fn get_asn_bootstrap_urls(
64 &self,
65 asn: &str,
66 ) -> Result<Option<Vec<String>>, BootstrapRegistryError>;
67 fn get_ipv4_bootstrap_urls(
68 &self,
69 ipv4: &str,
70 ) -> Result<Option<Vec<String>>, BootstrapRegistryError>;
71 fn get_ipv6_bootstrap_urls(
72 &self,
73 ipv6: &str,
74 ) -> Result<Option<Vec<String>>, BootstrapRegistryError>;
75 fn get_tag_bootstrap_urls(
76 &self,
77 tag: &str,
78 ) -> Result<Option<Vec<String>>, BootstrapRegistryError>;
79 }
80
81 /// Errors from processing IANA RDAP bootstrap registries.
82 #[derive(Debug, Error)]
83 pub enum BootstrapRegistryError {
84 #[error("Empty Service")]
85 EmptyService,
86 #[error("Empty URL Set")]
87 EmptyUrlSet,
88 #[error("Invalid Bootstrap Input")]
89 InvalidBootstrapInput,
90 #[error("Invalid Bootstrap Service")]
91 InvalidBootstrapService,
92 }
93
94 impl BootstrapRegistry for IanaRegistry {
95 /// Get the URLs from the IANA domain bootstrap registry.
96 fn get_dns_bootstrap_urls(
97 &self,
98 ldh: &str,
99 ) -> Result<Option<Vec<String>>, BootstrapRegistryError> {
100 let mut longest_match: Option<(usize, Vec<String>)> = None;
101 let Self::RdapBootstrapRegistry(bootstrap) = self;
102 for service in &bootstrap.services {
103 let tlds = service
104 .first()
105 .ok_or(BootstrapRegistryError::EmptyService)?;
106 for tld in tlds {
107 // if the ldh domain ends with the tld or the tld is the empty string which means the root
108 if ldh.ends_with(tld) || tld.is_empty() {
109 let urls = service.last().ok_or(BootstrapRegistryError::EmptyUrlSet)?;
110 let longest = longest_match.get_or_insert_with(|| (tld.len(), urls.to_owned()));
111 if longest.0 < tld.len() {
112 *longest = (tld.len(), urls.to_owned());
113 }
114 }
115 }
116 }
117 Ok(longest_match.map(|m| m.1))
118 }
119
120 /// Get the URLS from the IANA autnum bootstrap registry.
121 fn get_asn_bootstrap_urls(
122 &self,
123 asn: &str,
124 ) -> Result<Option<Vec<String>>, BootstrapRegistryError> {
125 let autnum = asn
126 .trim_start_matches(|c| -> bool { matches!(c, 'a' | 'A' | 's' | 'S') })
127 .parse::<u32>()
128 .map_err(|_| BootstrapRegistryError::InvalidBootstrapInput)?;
129 let Self::RdapBootstrapRegistry(bootstrap) = self;
130 for service in &bootstrap.services {
131 let as_ranges = service
132 .first()
133 .ok_or(BootstrapRegistryError::EmptyService)?;
134 for range in as_ranges {
135 let as_split = range.split('-').collect::<Vec<&str>>();
136 let start_as = as_split
137 .first()
138 .ok_or(BootstrapRegistryError::InvalidBootstrapService)?
139 .parse::<u32>()
140 .map_err(|_| BootstrapRegistryError::InvalidBootstrapInput)?;
141 let end_as = as_split
142 .last()
143 .ok_or(BootstrapRegistryError::InvalidBootstrapService)?
144 .parse::<u32>()
145 .map_err(|_| BootstrapRegistryError::InvalidBootstrapService)?;
146 if start_as <= autnum && end_as >= autnum {
147 let urls = service.last().ok_or(BootstrapRegistryError::EmptyUrlSet)?;
148 return Ok(Some(urls.to_owned()));
149 }
150 }
151 }
152 Ok(None)
153 }
154
155 /// Get the URLs from the IANA IPv4 bootstrap registry.
156 fn get_ipv4_bootstrap_urls(
157 &self,
158 ipv4: &str,
159 ) -> Result<Option<Vec<String>>, BootstrapRegistryError> {
160 let mut pm: PrefixMap<Ipv4Net, Vec<String>> = PrefixMap::new();
161 let Self::RdapBootstrapRegistry(bootstrap) = self;
162 for service in &bootstrap.services {
163 let urls = service.last().ok_or(BootstrapRegistryError::EmptyService)?;
164 for cidr in service
165 .first()
166 .ok_or(BootstrapRegistryError::InvalidBootstrapService)?
167 {
168 pm.insert(
169 cidr.parse()
170 .map_err(|_| BootstrapRegistryError::InvalidBootstrapService)?,
171 urls.clone(),
172 );
173 }
174 }
175 let net = pm.get_lpm(
176 &ipv4
177 .parse::<Ipv4Net>()
178 .map_err(|_| BootstrapRegistryError::InvalidBootstrapInput)?,
179 );
180 Ok(net.map(|n| n.1.to_owned()))
181 }
182
183 /// Get the URLs from the IANA IPv6 bootstrap registry.
184 fn get_ipv6_bootstrap_urls(
185 &self,
186 ipv6: &str,
187 ) -> Result<Option<Vec<String>>, BootstrapRegistryError> {
188 let mut pm: PrefixMap<Ipv6Net, Vec<String>> = PrefixMap::new();
189 let Self::RdapBootstrapRegistry(bootstrap) = self;
190 for service in &bootstrap.services {
191 let urls = service.last().ok_or(BootstrapRegistryError::EmptyService)?;
192 for cidr in service
193 .first()
194 .ok_or(BootstrapRegistryError::InvalidBootstrapService)?
195 {
196 pm.insert(
197 cidr.parse()
198 .map_err(|_| BootstrapRegistryError::InvalidBootstrapService)?,
199 urls.clone(),
200 );
201 }
202 }
203 let net = pm.get_lpm(
204 &ipv6
205 .parse::<Ipv6Net>()
206 .map_err(|_| BootstrapRegistryError::InvalidBootstrapInput)?,
207 );
208 Ok(net.map(|n| n.1.to_owned()))
209 }
210
211 /// Get the URLs from the IANA object tag bootstrap registry.
212 fn get_tag_bootstrap_urls(
213 &self,
214 tag: &str,
215 ) -> Result<Option<Vec<String>>, BootstrapRegistryError> {
216 let Self::RdapBootstrapRegistry(bootstrap) = self;
217 for service in &bootstrap.services {
218 let object_tag = service
219 .get(1)
220 .ok_or(BootstrapRegistryError::InvalidBootstrapService)?
221 .first()
222 .ok_or(BootstrapRegistryError::EmptyService)?;
223 if object_tag.eq_ignore_ascii_case(tag) {
224 let urls = service.last().ok_or(BootstrapRegistryError::EmptyUrlSet)?;
225 return Ok(Some(urls.to_owned()));
226 }
227 }
228 Ok(None)
229 }
230 }
231
232 /// Prefer HTTPS urls.
233 pub fn get_preferred_url(urls: Vec<String>) -> Result<String, BootstrapRegistryError> {
234 if urls.is_empty() {
235 Err(BootstrapRegistryError::EmptyUrlSet)
236 } else {
237 let url = urls
238 .iter()
239 .find(|s| s.starts_with("https://"))
240 .unwrap_or_else(|| urls.first().unwrap());
241 Ok(url.to_owned())
242 }
243 }
244
245 #[cfg(test)]
246 #[allow(non_snake_case)]
247 mod tests {
248 use rstest::rstest;
249
250 use crate::iana::{BootstrapRegistry, get_preferred_url};
251
252 use super::{IanaRegistry, IanaRegistryType};
253
254 #[rstest]
255 #[case(IanaRegistryType::RdapBootstrapDns, "dns.json")]
256 #[case(IanaRegistryType::RdapBootstrapAsn, "asn.json")]
257 #[case(IanaRegistryType::RdapBootstrapIpv4, "ipv4.json")]
258 #[case(IanaRegistryType::RdapBootstrapIpv6, "ipv6.json")]
259 #[case(IanaRegistryType::RdapObjectTags, "object-tags.json")]
260 fn GIVEN_registry_WHEN_get_file_name_THEN_correct_result(
261 #[case] registry: IanaRegistryType,
262 #[case] expected: &str,
263 ) {
264 // GIVEN in parameters
265
266 // WHEN
267 let actual = registry.file_name();
268
269 // THEN
270 assert_eq!(actual, expected);
271 }
272
273 #[test]
274 fn GIVEN_domain_bootstrap_WHEN_deserialize_THEN_success() {
275 // GIVEN
276 let bootstrap = r#"
277 {
278 "version": "1.0",
279 "publication": "2024-01-07T10:11:12Z",
280 "description": "Some text",
281 "services": [
282 [
283 ["net", "com"],
284 [
285 "https://registry.example.com/myrdap/"
286 ]
287 ],
288 [
289 ["org", "mytld"],
290 [
291 "https://example.org/"
292 ]
293 ],
294 [
295 ["xn--zckzah"],
296 [
297 "https://example.net/rdap/xn--zckzah/",
298 "http://example.net/rdap/xn--zckzah/"
299 ]
300 ]
301 ]
302 }
303 "#;
304
305 // WHEN
306 let actual = serde_json::from_str::<IanaRegistry>(bootstrap);
307
308 // THEN
309 actual.unwrap();
310 }
311
312 #[test]
313 fn GIVEN_one_url_WHEN_preferred_urls_THEN_that_is_the_one() {
314 // GIVEN
315 let urls = vec!["http://foo.example".to_string()];
316
317 // WHEN
318 let actual = get_preferred_url(urls).expect("cannot get preferred url");
319
320 // THEN
321 assert_eq!(actual, "http://foo.example");
322 }
323
324 #[test]
325 fn GIVEN_one_http_and_https_url_WHEN_preferred_urls_THEN_return_https() {
326 // GIVEN
327 let urls = vec![
328 "http://foo.example".to_string(),
329 "https://foo.example".to_string(),
330 ];
331
332 // WHEN
333 let actual = get_preferred_url(urls).expect("cannot get preferred url");
334
335 // THEN
336 assert_eq!(actual, "https://foo.example");
337 }
338
339 #[test]
340 fn GIVEN_domain_bootstrap_with_matching_WHEN_find_THEN_url_matches() {
341 // GIVEN
342 let bootstrap = r#"
343 {
344 "version": "1.0",
345 "publication": "2024-01-07T10:11:12Z",
346 "description": "Some text",
347 "services": [
348 [
349 ["net", "com"],
350 [
351 "https://registry.example.com/myrdap/"
352 ]
353 ],
354 [
355 ["org", "mytld"],
356 [
357 "https://example.org/"
358 ]
359 ]
360 ]
361 }
362 "#;
363 let iana =
364 serde_json::from_str::<IanaRegistry>(bootstrap).expect("cannot parse domain bootstrap");
365
366 // WHEN
367 let actual = iana.get_dns_bootstrap_urls("foo.org");
368
369 // THEN
370 assert_eq!(
371 actual
372 .expect("no vec")
373 .expect("no urls")
374 .first()
375 .expect("vec is empty"),
376 "https://example.org/"
377 );
378 }
379
380 #[test]
381 fn GIVEN_domain_bootstrap_with_two_matching_WHEN_find_THEN_return_longest_match() {
382 // GIVEN
383 let bootstrap = r#"
384 {
385 "version": "1.0",
386 "publication": "2024-01-07T10:11:12Z",
387 "description": "Some text",
388 "services": [
389 [
390 ["co.uk"],
391 [
392 "https://registry.co.uk/"
393 ]
394 ],
395 [
396 ["uk"],
397 [
398 "https://registry.uk/"
399 ]
400 ]
401 ]
402 }
403 "#;
404 let iana =
405 serde_json::from_str::<IanaRegistry>(bootstrap).expect("cannot parse domain bootstrap");
406
407 // WHEN
408 let actual = iana.get_dns_bootstrap_urls("foo.co.uk");
409
410 // THEN
411 assert_eq!(
412 actual
413 .expect("no vec")
414 .expect("no urls")
415 .first()
416 .expect("vec is empty"),
417 "https://registry.co.uk/"
418 );
419 }
420
421 #[test]
422 fn GIVEN_domain_bootstrap_with_root_WHEN_find_THEN_url_matches() {
423 // GIVEN
424 let bootstrap = r#"
425 {
426 "version": "1.0",
427 "publication": "2024-01-07T10:11:12Z",
428 "description": "Some text",
429 "services": [
430 [
431 ["net", "com"],
432 [
433 "https://registry.example.com/myrdap/"
434 ]
435 ],
436 [
437 [""],
438 [
439 "https://example.org/"
440 ]
441 ]
442 ]
443 }
444 "#;
445 let iana =
446 serde_json::from_str::<IanaRegistry>(bootstrap).expect("cannot parse domain bootstrap");
447
448 // WHEN
449 let actual = iana.get_dns_bootstrap_urls("foo.org");
450
451 // THEN
452 assert_eq!(
453 actual
454 .expect("no vec")
455 .expect("no urls")
456 .first()
457 .expect("vec is empty"),
458 "https://example.org/"
459 );
460 }
461
462 #[test]
463 fn GIVEN_autnum_bootstrap_with_match_WHEN_find_with_string_THEN_return_match() {
464 // GIVEN
465 let bootstrap = r#"
466 {
467 "version": "1.0",
468 "publication": "2024-01-07T10:11:12Z",
469 "description": "RDAP Bootstrap file for example registries.",
470 "services": [
471 [
472 ["64496-64496"],
473 [
474 "https://rir3.example.com/myrdap/"
475 ]
476 ],
477 [
478 ["64497-64510", "65536-65551"],
479 [
480 "https://example.org/"
481 ]
482 ],
483 [
484 ["64512-65534"],
485 [
486 "http://example.net/rdaprir2/",
487 "https://example.net/rdaprir2/"
488 ]
489 ]
490 ]
491 }
492 "#;
493 let iana =
494 serde_json::from_str::<IanaRegistry>(bootstrap).expect("cannot parse autnum bootstrap");
495
496 // WHEN
497 let actual = iana.get_asn_bootstrap_urls("as64498");
498
499 // THEN
500 assert_eq!(
501 actual
502 .expect("no vec")
503 .expect("no urls")
504 .first()
505 .expect("vec is empty"),
506 "https://example.org/"
507 );
508 }
509
510 #[rstest]
511 #[case(64497u32, "https://example.org/")]
512 #[case(64498u32, "https://example.org/")]
513 #[case(64510u32, "https://example.org/")]
514 #[case(65536u32, "https://example.org/")]
515 #[case(65537u32, "https://example.org/")]
516 #[case(64513u32, "http://example.net/rdaprir2/")]
517 fn GIVEN_autnum_bootstrap_with_match_WHEN_find_with_number_THEN_return_match(
518 #[case] asn: u32,
519 #[case] bootstrap_url: &str,
520 ) {
521 // GIVEN
522 let bootstrap = r#"
523 {
524 "version": "1.0",
525 "publication": "2024-01-07T10:11:12Z",
526 "description": "RDAP Bootstrap file for example registries.",
527 "services": [
528 [
529 ["64496-64496"],
530 [
531 "https://rir3.example.com/myrdap/"
532 ]
533 ],
534 [
535 ["64497-64510", "65536-65551"],
536 [
537 "https://example.org/"
538 ]
539 ],
540 [
541 ["64512-65534"],
542 [
543 "http://example.net/rdaprir2/",
544 "https://example.net/rdaprir2/"
545 ]
546 ]
547 ]
548 }
549 "#;
550 let iana =
551 serde_json::from_str::<IanaRegistry>(bootstrap).expect("cannot parse autnum bootstrap");
552
553 // WHEN
554 let actual = iana.get_asn_bootstrap_urls(&asn.to_string());
555
556 // THEN
557 assert_eq!(
558 actual
559 .expect("no vec")
560 .expect("no urls")
561 .first()
562 .expect("vec is empty"),
563 bootstrap_url
564 );
565 }
566
567 #[test]
568 fn GIVEN_ipv4_bootstrap_with_match_WHEN_find_with_ip_address_THEN_return_match() {
569 // GIVEN
570 let bootstrap = r#"
571 {
572 "version": "1.0",
573 "publication": "2024-01-07T10:11:12Z",
574 "description": "RDAP Bootstrap file for example registries.",
575 "services": [
576 [
577 ["198.51.100.0/24", "192.0.0.0/8"],
578 [
579 "https://rir1.example.com/myrdap/"
580 ]
581 ],
582 [
583 ["203.0.113.0/24", "192.0.2.0/24"],
584 [
585 "https://example.org/"
586 ]
587 ],
588 [
589 ["203.0.113.0/28"],
590 [
591 "https://example.net/rdaprir2/",
592 "http://example.net/rdaprir2/"
593 ]
594 ]
595 ]
596 }
597 "#;
598 let iana =
599 serde_json::from_str::<IanaRegistry>(bootstrap).expect("cannot parse ipv4 bootstrap");
600
601 // WHEN
602 let actual = iana.get_ipv4_bootstrap_urls("198.51.100.1/32");
603
604 // THEN
605 assert_eq!(
606 actual
607 .expect("no vec")
608 .expect("no urls")
609 .first()
610 .expect("vec is empty"),
611 "https://rir1.example.com/myrdap/"
612 );
613 }
614
615 #[test]
616 fn GIVEN_ipv4_bootstrap_with_match_WHEN_find_with_cidr_THEN_return_match() {
617 // GIVEN
618 let bootstrap = r#"
619 {
620 "version": "1.0",
621 "publication": "2024-01-07T10:11:12Z",
622 "description": "RDAP Bootstrap file for example registries.",
623 "services": [
624 [
625 ["198.51.100.0/24", "192.0.0.0/8"],
626 [
627 "https://rir1.example.com/myrdap/"
628 ]
629 ],
630 [
631 ["203.0.113.0/24", "192.0.2.0/24"],
632 [
633 "https://example.org/"
634 ]
635 ],
636 [
637 ["203.0.113.0/28"],
638 [
639 "https://example.net/rdaprir2/",
640 "http://example.net/rdaprir2/"
641 ]
642 ]
643 ]
644 }
645 "#;
646 let iana =
647 serde_json::from_str::<IanaRegistry>(bootstrap).expect("cannot parse ipv4 bootstrap");
648
649 // WHEN
650 let actual = iana.get_ipv4_bootstrap_urls("203.0.113.0/24");
651
652 // THEN
653 assert_eq!(
654 actual
655 .expect("no vec")
656 .expect("no urls")
657 .first()
658 .expect("vec is empty"),
659 "https://example.org/"
660 );
661 }
662
663 #[test]
664 fn GIVEN_ipv6_bootstrap_with_match_WHEN_find_with_ip_address_THEN_return_match() {
665 // GIVEN
666 let bootstrap = r#"
667 {
668 "version": "1.0",
669 "publication": "2024-01-07T10:11:12Z",
670 "description": "RDAP Bootstrap file for example registries.",
671 "services": [
672 [
673 ["2001:db8::/34"],
674 [
675 "https://rir2.example.com/myrdap/"
676 ]
677 ],
678 [
679 ["2001:db8:4000::/36", "2001:db8:ffff::/48"],
680 [
681 "https://example.org/"
682 ]
683 ],
684 [
685 ["2001:db8:1000::/36"],
686 [
687 "https://example.net/rdaprir2/",
688 "http://example.net/rdaprir2/"
689 ]
690 ]
691 ]
692 }
693 "#;
694 let iana =
695 serde_json::from_str::<IanaRegistry>(bootstrap).expect("cannot parse ipv6 bootstrap");
696
697 // WHEN
698 let actual = iana.get_ipv6_bootstrap_urls("2001:db8::1/128");
699
700 // THEN
701 assert_eq!(
702 actual
703 .expect("no vec")
704 .expect("no urls")
705 .first()
706 .expect("vec is empty"),
707 "https://rir2.example.com/myrdap/"
708 );
709 }
710
711 #[test]
712 fn GIVEN_ipv6_bootstrap_with_match_WHEN_find_with_ip_cidr_THEN_return_match() {
713 // GIVEN
714 let bootstrap = r#"
715 {
716 "version": "1.0",
717 "publication": "2024-01-07T10:11:12Z",
718 "description": "RDAP Bootstrap file for example registries.",
719 "services": [
720 [
721 ["2001:db8::/34"],
722 [
723 "https://rir2.example.com/myrdap/"
724 ]
725 ],
726 [
727 ["2001:db8:4000::/36", "2001:db8:ffff::/48"],
728 [
729 "https://example.org/"
730 ]
731 ],
732 [
733 ["2001:db8:1000::/36"],
734 [
735 "https://example.net/rdaprir2/",
736 "http://example.net/rdaprir2/"
737 ]
738 ]
739 ]
740 }
741 "#;
742 let iana =
743 serde_json::from_str::<IanaRegistry>(bootstrap).expect("cannot parse ipv6 bootstrap");
744
745 // WHEN
746 let actual = iana.get_ipv6_bootstrap_urls("2001:db8:4000::/36");
747
748 // THEN
749 assert_eq!(
750 actual
751 .expect("no vec")
752 .expect("no urls")
753 .first()
754 .expect("vec is empty"),
755 "https://example.org/"
756 );
757 }
758
759 #[test]
760 fn GIVEN_tag_bootstrap_with_match_WHEN_find_with_tag_THEN_return_match() {
761 // GIVEN
762 let bootstrap = r#"
763 {
764 "version": "1.0",
765 "publication": "YYYY-MM-DDTHH:MM:SSZ",
766 "description": "RDAP bootstrap file for service provider object tags",
767 "services": [
768 [
769 ["[email protected]"],
770 ["YYYY"],
771 [
772 "https://example.com/rdap/"
773 ]
774 ],
775 [
776 ["[email protected]"],
777 ["ZZ54"],
778 [
779 "http://rdap.example.org/"
780 ]
781 ],
782 [
783 ["[email protected]"],
784 ["1754"],
785 [
786 "https://example.net/rdap/",
787 "http://example.net/rdap/"
788 ]
789 ]
790 ]
791 }
792 "#;
793 let iana =
794 serde_json::from_str::<IanaRegistry>(bootstrap).expect("cannot parse tag bootstrap");
795
796 // WHEN
797 let actual = iana.get_tag_bootstrap_urls("YYYY");
798
799 // THEN
800 assert_eq!(
801 actual
802 .expect("no vec")
803 .expect("no urls")
804 .first()
805 .expect("vec is empty"),
806 "https://example.com/rdap/"
807 );
808 }
809 }