Debian Codegraph @

src/response/mod.rs

raw
1 //! RDAP structures for parsing and creating RDAP responses.
2 use std::{any::TypeId, collections::HashSet};
3
4 use {
5 cidr,
6 serde::{Deserialize, Serialize},
7 serde_json::Value,
8 thiserror::Error,
9 };
10
11 use strum::Display as EnumDisplay;
12
13 use crate::media_types::RDAP_MEDIA_TYPE;
14
15 #[doc(inline)]
16 pub use autnum::*;
17 #[doc(inline)]
18 pub use common::*;
19 #[doc(inline)]
20 pub use domain::*;
21 #[doc(inline)]
22 pub use entity::*;
23 #[doc(inline)]
24 pub use error::*;
25 #[doc(inline)]
26 pub use help::*;
27 #[doc(inline)]
28 pub use lenient::*;
29 #[doc(inline)]
30 pub use nameserver::*;
31 #[doc(inline)]
32 pub use network::*;
33 #[doc(inline)]
34 pub use obj_common::*;
35 #[doc(inline)]
36 pub use rir_search::*;
37 #[doc(inline)]
38 pub use rpki::*;
39 #[doc(inline)]
40 pub use search::*;
41 #[doc(inline)]
42 pub use types::*;
43 #[doc(inline)]
44 pub use values::*;
45
46 pub(crate) mod autnum;
47 pub(crate) mod common;
48 pub(crate) mod domain;
49 pub(crate) mod entity;
50 pub(crate) mod error;
51 pub(crate) mod help;
52 pub mod jscontact; // JSContact is not a maintstream extension, yet.
53 pub(crate) mod lenient;
54 pub(crate) mod nameserver;
55 pub(crate) mod network;
56 pub(crate) mod obj_common;
57 pub mod redacted; // RFC 9537 is not a mainstream extension.
58 pub(crate) mod rir_search; // RFC 9910 RIR Search
59 pub(crate) mod rpki; // RPKI extension (draft-ietf-regext-rdap-rpki)
60 pub(crate) mod search;
61 pub mod ttl; // ttl0 extension
62 pub(crate) mod types;
63 pub(crate) mod values;
64
65 /// An error caused be processing an RDAP response.
66 ///
67 /// This is caused because the JSON constituting the
68 /// RDAP response has a problem that cannot be overcome.
69 ///
70 /// Do not confuse this with [Rfc9083Error].
71 #[derive(Debug, Error)]
72 pub enum RdapResponseError {
73 /// The JSON type is incorrect.
74 #[error("Wrong JSON type: {0}")]
75 WrongJsonType(String),
76
77 /// The type of RDAP response is unknown.
78 #[error("Unknown RDAP response.")]
79 UnknownRdapResponse,
80
81 /// An error has occurred parsing the JSON.
82 #[error(transparent)]
83 SerdeJson(#[from] serde_json::Error),
84
85 /// An error with parsing an IP address.
86 #[error(transparent)]
87 AddrParse(#[from] std::net::AddrParseError),
88
89 /// An error caused with parsing a CIDR address.
90 #[error(transparent)]
91 CidrParse(#[from] cidr::errors::NetworkParseError),
92
93 /// The type of RDAP response is unknown.
94 #[error("Network type must either be 'v4' or 'v6'.")]
95 InvalidNetworkType,
96 }
97
98 /// The various types of RDAP response.
99 ///
100 /// It can be parsed from JSON using serde:
101 ///
102 /// ```rust
103 /// use icann_rdap_common::response::RdapResponse;
104 ///
105 /// let json = r#"
106 /// {
107 /// "objectClassName": "ip network",
108 /// "links": [
109 /// {
110 /// "value": "http://localhost:3000/rdap/ip/10.0.0.0/16",
111 /// "rel": "self",
112 /// "href": "http://localhost:3000/rdap/ip/10.0.0.0/16",
113 /// "type": "application/rdap+json"
114 /// }
115 /// ],
116 /// "events": [
117 /// {
118 /// "eventAction": "registration",
119 /// "eventDate": "2023-06-16T22:56:49.594173356+00:00"
120 /// },
121 /// {
122 /// "eventAction": "last changed",
123 /// "eventDate": "2023-06-16T22:56:49.594189140+00:00"
124 /// }
125 /// ],
126 /// "startAddress": "10.0.0.0",
127 /// "endAddress": "10.0.255.255",
128 /// "ipVersion": "v4"
129 /// }
130 /// "#;
131 ///
132 /// let rdap: RdapResponse = serde_json::from_str(json).unwrap();
133 /// assert!(matches!(rdap, RdapResponse::Network(_)));
134 /// ```
135 #[derive(Serialize, Deserialize, Clone, EnumDisplay, PartialEq, Debug)]
136 #[serde(untagged, try_from = "Value")]
137 pub enum RdapResponse {
138 // Object Classes
139 Entity(Box<Entity>),
140 Domain(Box<Domain>),
141 Nameserver(Box<Nameserver>),
142 Autnum(Box<Autnum>),
143 Network(Box<Network>),
144
145 // Search Results
146 DomainSearchResults(Box<DomainSearchResults>),
147 EntitySearchResults(Box<EntitySearchResults>),
148 NameserverSearchResults(Box<NameserverSearchResults>),
149 IpSearchResults(Box<IpSearchResults>),
150 AutnumSearchResults(Box<AutnumSearchResults>),
151
152 // RPKI (draft-ietf-regext-rdap-rpki)
153 Rpki1Roa(Box<Rpk1Roa>),
154 Rpki1Aspa(Box<Rpk1Aspa>),
155 Rpki1X509ResourceCert(Box<Rpk1X509ResourceCert>),
156 Rpki1RoaSearchResults(Box<Rpk1RoaSearchResults>),
157 Rpki1AspaSearchResults(Box<Rpk1AspaSearchResults>),
158 Rpki1X509ResourceCertSearchResults(Box<Rpk1X509ResourceCertSearchResults>),
159
160 // Error
161 ErrorResponse(Box<Rfc9083Error>),
162
163 // Help
164 Help(Box<Help>),
165 // These are all boxed to keep the variant size aligned.
166 // While not completely necessary for all these variants today,
167 // this will prevent an API change in the future when new items
168 // are added to each variant when supporting future RDAP extensions.
169 }
170
171 impl TryFrom<Value> for RdapResponse {
172 type Error = RdapResponseError;
173
174 fn try_from(value: Value) -> Result<Self, Self::Error> {
175 let response = if let Some(object) = value.as_object() {
176 object
177 } else {
178 return Err(RdapResponseError::WrongJsonType(
179 "response is not an object".to_string(),
180 ));
181 };
182
183 // if it has an objectClassName
184 if let Some(class_name) = response.get("objectClassName") {
185 if let Some(name_str) = class_name.as_str() {
186 return match name_str {
187 "domain" => Ok(serde_json::from_value::<Domain>(value)?.to_response()),
188 "entity" => Ok(serde_json::from_value::<Entity>(value)?.to_response()),
189 "nameserver" => Ok(serde_json::from_value::<Nameserver>(value)?.to_response()),
190 "autnum" => Ok(serde_json::from_value::<Autnum>(value)?.to_response()),
191 "ip network" => Ok(serde_json::from_value::<Network>(value)?.to_response()),
192 "rpki1_roa" => Ok(serde_json::from_value::<Rpk1Roa>(value)?.to_response()),
193 "rpki1_aspa" => Ok(serde_json::from_value::<Rpk1Aspa>(value)?.to_response()),
194 "rpki1_x509ResourceCert" => {
195 Ok(serde_json::from_value::<Rpk1X509ResourceCert>(value)?.to_response())
196 }
197 _ => Err(RdapResponseError::UnknownRdapResponse),
198 };
199 } else {
200 return Err(RdapResponseError::WrongJsonType(
201 "'objectClassName' is not a string".to_string(),
202 ));
203 }
204 };
205
206 // else if it is a domain search result
207 if let Some(result) = response.get("domainSearchResults") {
208 if result.is_array() {
209 return Ok(serde_json::from_value::<DomainSearchResults>(value)?.to_response());
210 } else {
211 return Err(RdapResponseError::WrongJsonType(
212 "'domainSearchResults' is not an array".to_string(),
213 ));
214 }
215 }
216 // else if it is an entity search result
217 if let Some(result) = response.get("entitySearchResults") {
218 if result.is_array() {
219 return Ok(serde_json::from_value::<EntitySearchResults>(value)?.to_response());
220 } else {
221 return Err(RdapResponseError::WrongJsonType(
222 "'entitySearchResults' is not an array".to_string(),
223 ));
224 }
225 }
226 // else if it is a nameserver search result
227 if let Some(result) = response.get("nameserverSearchResults") {
228 if result.is_array() {
229 return Ok(serde_json::from_value::<NameserverSearchResults>(value)?.to_response());
230 } else {
231 return Err(RdapResponseError::WrongJsonType(
232 "'nameserverSearchResults' is not an array".to_string(),
233 ));
234 }
235 }
236 // else if it is an IP search result
237 if let Some(result) = response.get("ipSearchResults") {
238 if result.is_array() {
239 return Ok(serde_json::from_value::<IpSearchResults>(value)?.to_response());
240 } else {
241 return Err(RdapResponseError::WrongJsonType(
242 "'ipSearchResults' is not an array".to_string(),
243 ));
244 }
245 }
246 // else if it is an autnum search result
247 if let Some(result) = response.get("autnumSearchResults") {
248 if result.is_array() {
249 return Ok(serde_json::from_value::<AutnumSearchResults>(value)?.to_response());
250 } else {
251 return Err(RdapResponseError::WrongJsonType(
252 "'autnumSearchResults' is not an array".to_string(),
253 ));
254 }
255 }
256 // else if it is an rpki1_roa search result
257 if let Some(result) = response.get("rpki1_roaSearchResults") {
258 if result.is_array() {
259 return Ok(serde_json::from_value::<Rpk1RoaSearchResults>(value)?.to_response());
260 } else {
261 return Err(RdapResponseError::WrongJsonType(
262 "'rpki1_roaSearchResults' is not an array".to_string(),
263 ));
264 }
265 }
266 // else if it is an rpki1_aspa search result
267 if let Some(result) = response.get("rpki1_aspaSearchResults") {
268 if result.is_array() {
269 return Ok(serde_json::from_value::<Rpk1AspaSearchResults>(value)?.to_response());
270 } else {
271 return Err(RdapResponseError::WrongJsonType(
272 "'rpki1_aspaSearchResults' is not an array".to_string(),
273 ));
274 }
275 }
276 // else if it is an rpki1_x509ResourceCert search result
277 if let Some(result) = response.get("rpki1_x509ResourceCertSearchResults") {
278 if result.is_array() {
279 return Ok(
280 serde_json::from_value::<Rpk1X509ResourceCertSearchResults>(value)?
281 .to_response(),
282 );
283 } else {
284 return Err(RdapResponseError::WrongJsonType(
285 "'rpki1_x509ResourceCertSearchResults' is not an array".to_string(),
286 ));
287 }
288 }
289
290 // else if it has an errorCode
291 if let Some(result) = response.get("errorCode") {
292 if result.is_u64() {
293 return Ok(serde_json::from_value::<Rfc9083Error>(value)?.to_response());
294 } else {
295 return Err(RdapResponseError::WrongJsonType(
296 "'errorCode' is not an unsigned integer".to_string(),
297 ));
298 }
299 }
300
301 // else if it has a notices then it is help response at this point
302 if let Some(result) = response.get("notices") {
303 if result.is_array() {
304 return Ok(serde_json::from_value::<Help>(value)?.to_response());
305 } else {
306 return Err(RdapResponseError::WrongJsonType(
307 "'notices' is not an array".to_string(),
308 ));
309 }
310 }
311 Err(RdapResponseError::UnknownRdapResponse)
312 }
313 }
314
315 impl RdapResponse {
316 pub fn get_type(&self) -> TypeId {
317 match self {
318 Self::Entity(_) => TypeId::of::<Entity>(),
319 Self::Domain(_) => TypeId::of::<Domain>(),
320 Self::Nameserver(_) => TypeId::of::<Nameserver>(),
321 Self::Autnum(_) => TypeId::of::<Autnum>(),
322 Self::Network(_) => TypeId::of::<Network>(),
323 Self::DomainSearchResults(_) => TypeId::of::<DomainSearchResults>(),
324 Self::EntitySearchResults(_) => TypeId::of::<EntitySearchResults>(),
325 Self::NameserverSearchResults(_) => TypeId::of::<NameserverSearchResults>(),
326 Self::IpSearchResults(_) => TypeId::of::<IpSearchResults>(),
327 Self::AutnumSearchResults(_) => TypeId::of::<AutnumSearchResults>(),
328 Self::Rpki1Roa(_) => TypeId::of::<Rpk1Roa>(),
329 Self::Rpki1Aspa(_) => TypeId::of::<Rpk1Aspa>(),
330 Self::Rpki1X509ResourceCert(_) => TypeId::of::<Rpk1X509ResourceCert>(),
331 Self::Rpki1RoaSearchResults(_) => TypeId::of::<Rpk1RoaSearchResults>(),
332 Self::Rpki1AspaSearchResults(_) => TypeId::of::<Rpk1AspaSearchResults>(),
333 Self::Rpki1X509ResourceCertSearchResults(_) => {
334 TypeId::of::<Rpk1X509ResourceCertSearchResults>()
335 }
336 Self::ErrorResponse(_) => TypeId::of::<crate::response::Rfc9083Error>(),
337 Self::Help(_) => TypeId::of::<Help>(),
338 }
339 }
340
341 pub fn get_links(&self) -> Option<&Links> {
342 match self {
343 Self::Entity(e) => e.object_common.links.as_ref(),
344 Self::Domain(d) => d.object_common.links.as_ref(),
345 Self::Nameserver(n) => n.object_common.links.as_ref(),
346 Self::Autnum(a) => a.object_common.links.as_ref(),
347 Self::Network(n) => n.object_common.links.as_ref(),
348 Self::Rpki1Roa(r) => r.object_common.links.as_ref(),
349 Self::Rpki1Aspa(r) => r.object_common.links.as_ref(),
350 Self::Rpki1X509ResourceCert(r) => r.object_common.links.as_ref(),
351 Self::DomainSearchResults(_)
352 | Self::EntitySearchResults(_)
353 | Self::NameserverSearchResults(_)
354 | Self::IpSearchResults(_)
355 | Self::AutnumSearchResults(_)
356 | Self::Rpki1RoaSearchResults(_)
357 | Self::Rpki1AspaSearchResults(_)
358 | Self::Rpki1X509ResourceCertSearchResults(_)
359 | Self::ErrorResponse(_)
360 | Self::Help(_) => None,
361 }
362 }
363
364 pub fn get_conformance(&self) -> Option<&RdapConformance> {
365 match self {
366 Self::Entity(e) => e.common.rdap_conformance.as_ref(),
367 Self::Domain(d) => d.common.rdap_conformance.as_ref(),
368 Self::Nameserver(n) => n.common.rdap_conformance.as_ref(),
369 Self::Autnum(a) => a.common.rdap_conformance.as_ref(),
370 Self::Network(n) => n.common.rdap_conformance.as_ref(),
371 Self::DomainSearchResults(s) => s.common.rdap_conformance.as_ref(),
372 Self::EntitySearchResults(s) => s.common.rdap_conformance.as_ref(),
373 Self::NameserverSearchResults(s) => s.common.rdap_conformance.as_ref(),
374 Self::IpSearchResults(s) => s.common.rdap_conformance.as_ref(),
375 Self::AutnumSearchResults(s) => s.common.rdap_conformance.as_ref(),
376 Self::Rpki1Roa(r) => r.common.rdap_conformance.as_ref(),
377 Self::Rpki1Aspa(r) => r.common.rdap_conformance.as_ref(),
378 Self::Rpki1X509ResourceCert(r) => r.common.rdap_conformance.as_ref(),
379 Self::Rpki1RoaSearchResults(s) => s.common.rdap_conformance.as_ref(),
380 Self::Rpki1AspaSearchResults(s) => s.common.rdap_conformance.as_ref(),
381 Self::Rpki1X509ResourceCertSearchResults(s) => s.common.rdap_conformance.as_ref(),
382 Self::ErrorResponse(e) => e.common.rdap_conformance.as_ref(),
383 Self::Help(h) => h.common.rdap_conformance.as_ref(),
384 }
385 }
386
387 pub fn has_extension_id(&self, extension_id: ExtensionId) -> bool {
388 self.get_conformance()
389 .is_some_and(|conformance| conformance.contains(&extension_id.to_extension()))
390 }
391
392 pub fn has_extension(&self, extension: &str) -> bool {
393 self.get_conformance()
394 .is_some_and(|conformance| conformance.contains(&Extension::from(extension)))
395 }
396
397 pub fn is_redirect(&self) -> bool {
398 match self {
399 Self::ErrorResponse(e) => e.is_redirect(),
400 _ => false,
401 }
402 }
403 }
404
405 impl GetSelfLink for RdapResponse {
406 fn self_link(&self) -> Option<&Link> {
407 self.get_links()
408 .and_then(|links| links.iter().find(|link| link.is_relation("self")))
409 }
410 }
411
412 /// A trait for converting structs into an appropriate [RdapResponse] variant.
413 pub trait ToResponse {
414 /// Consumes the object and returns an [RdapResponse].
415 fn to_response(self) -> RdapResponse;
416 }
417
418 /// Trait for getting a link with a `rel` of "self".
419 pub trait GetSelfLink {
420 /// Get's the first self link.
421 /// See [crate::response::ObjectCommon::self_link()].
422 fn self_link(&self) -> Option<&Link>;
423 }
424
425 /// Train for setting a link with a `rel` of "self".
426 pub trait SelfLink: GetSelfLink {
427 /// See [crate::response::ObjectCommon::self_link()].
428 fn with_self_link(self, link: Link) -> Self;
429 }
430
431 pub fn get_related_links(rdap_response: &RdapResponse) -> Vec<&str> {
432 let related = &["related".to_string()];
433 get_relationship_links(related, rdap_response)
434 }
435
436 /// Gets the `href` of a link with `rel` of relationships.
437 ///
438 /// This function will get the `href` from an RDAP object's links where the `rel`
439 /// is a combination of the given relationships and the `type` is an RDAP media type.
440 /// If no link with an RDAP media type is found, it will attempt to find a link that
441 /// is formatted as a known RDAP URL.
442 pub fn get_relationship_links<'b>(
443 relationships: &[String],
444 rdap_response: &'b RdapResponse,
445 ) -> Vec<&'b str> {
446 let Some(links) = rdap_response.get_links() else {
447 return vec![];
448 };
449
450 let mut urls: Vec<_> = links
451 .iter()
452 .filter_map(|l| match (&l.href, &l.rel, &l.media_type) {
453 (Some(href), Some(rel), Some(media_type))
454 if is_relationship(rel, relationships)
455 && media_type.eq_ignore_ascii_case(RDAP_MEDIA_TYPE) =>
456 {
457 Some(href.as_str())
458 }
459 _ => None,
460 })
461 .collect();
462
463 // if none are found with correct media type, look for something that looks like an RDAP link
464 if urls.is_empty() {
465 urls = links
466 .iter()
467 .filter(|l| {
468 if let Some(href) = l.href() {
469 if let Some(rel) = l.rel() {
470 is_relationship(rel, relationships) && has_rdap_path(href)
471 } else {
472 false
473 }
474 } else {
475 false
476 }
477 })
478 .map(|l| l.href.as_ref().unwrap().as_str())
479 .collect::<Vec<&str>>();
480 }
481 urls
482 }
483
484 fn is_relationship(rel: &str, relationships: &[String]) -> bool {
485 let mut splits: usize = 0;
486 let num_found = rel
487 .split_whitespace()
488 .filter(|r| {
489 splits += 1;
490 relationships.iter().any(|s| r.eq_ignore_ascii_case(s))
491 })
492 .count();
493 splits == num_found && num_found == relationships.len()
494 }
495
496 /// Returns true if the URL contains an RDAP path as defined by RFC 9082.
497 pub fn has_rdap_path(url: &str) -> bool {
498 if url.contains("/domain/")
499 || url.contains("/ip/")
500 || url.contains("/autnum/")
501 || url.contains("/nameserver/")
502 || url.contains("/entity/")
503 {
504 return true;
505 }
506 false
507 }
508
509 /// Makes a root object class suitable for being embedded in another object class.
510 pub trait ToChild {
511 /// Removes notices and rdapConformance so this object can be a child
512 /// of another object.
513 fn to_child(self) -> Self;
514 }
515
516 /// Returns `Some(Vec<T>)` if the vector is not empty; otherwise, `None`.
517 pub fn to_opt_vec<T>(vec: Vec<T>) -> Option<Vec<T>> {
518 (!vec.is_empty()).then_some(vec)
519 }
520
521 /// Returns `Vec<T>` if `is_some()` else an empty vector.
522 pub fn opt_to_vec<T>(opt: Option<Vec<T>>) -> Vec<T> {
523 opt.unwrap_or_default()
524 }
525
526 /// Retrieve the RDAP extensions making up the content of a response.
527 pub trait ContentExtensions {
528 /// Returns a [HashSet] of [ExtensionId].
529 ///
530 /// The returned value should contain all the extension IDs used
531 /// in the instance of the object.
532 fn content_extensions(&self) -> HashSet<ExtensionId>;
533 }
534
535 impl ContentExtensions for RdapResponse {
536 fn content_extensions(&self) -> HashSet<ExtensionId> {
537 match &self {
538 Self::Entity(e) => e.content_extensions(),
539 Self::Domain(d) => d.content_extensions(),
540 Self::Nameserver(n) => n.content_extensions(),
541 Self::Autnum(a) => a.content_extensions(),
542 Self::Network(n) => n.content_extensions(),
543 Self::DomainSearchResults(r) => r.content_extensions(),
544 Self::EntitySearchResults(r) => r.content_extensions(),
545 Self::NameserverSearchResults(r) => r.content_extensions(),
546 Self::IpSearchResults(r) => r.content_extensions(),
547 Self::AutnumSearchResults(r) => r.content_extensions(),
548 Self::Rpki1Roa(r) => r.content_extensions(),
549 Self::Rpki1Aspa(r) => r.content_extensions(),
550 Self::Rpki1X509ResourceCert(r) => r.content_extensions(),
551 Self::Rpki1RoaSearchResults(r) => r.content_extensions(),
552 Self::Rpki1AspaSearchResults(r) => r.content_extensions(),
553 Self::Rpki1X509ResourceCertSearchResults(r) => r.content_extensions(),
554 Self::ErrorResponse(e) => e.content_extensions(),
555 Self::Help(h) => h.content_extensions(),
556 }
557 }
558 }
559
560 /// Normalizes the extensions in an [RdapResponse].
561 pub fn normalize_extensions(rdap: RdapResponse) -> RdapResponse {
562 normalize_extensions_with(rdap, [])
563 }
564
565 /// Normalizes the extensions in an [RdapResponse] with additional extensions.
566 pub fn normalize_extensions_with(
567 rdap: RdapResponse,
568 extra_extensions: impl IntoIterator<Item = ExtensionId>,
569 ) -> RdapResponse {
570 let mut extensions: HashSet<ExtensionId> = rdap.content_extensions();
571 extensions.extend(extra_extensions);
572 let rdap_conformance = extensions
573 .iter()
574 .map(|e| e.to_extension())
575 .collect::<Vec<Extension>>();
576
577 match rdap {
578 RdapResponse::Entity(e) => Entity {
579 common: Common {
580 rdap_conformance: Some(rdap_conformance),
581 ..e.common
582 },
583 ..*e
584 }
585 .to_response(),
586 RdapResponse::Domain(d) => Domain {
587 common: Common {
588 rdap_conformance: Some(rdap_conformance),
589 ..d.common
590 },
591 ..*d
592 }
593 .to_response(),
594 RdapResponse::Nameserver(n) => Nameserver {
595 common: Common {
596 rdap_conformance: Some(rdap_conformance),
597 ..n.common
598 },
599 ..*n
600 }
601 .to_response(),
602 RdapResponse::Autnum(a) => Autnum {
603 common: Common {
604 rdap_conformance: Some(rdap_conformance),
605 ..a.common
606 },
607 ..*a
608 }
609 .to_response(),
610 RdapResponse::Network(n) => Network {
611 common: Common {
612 rdap_conformance: Some(rdap_conformance),
613 ..n.common
614 },
615 ..*n
616 }
617 .to_response(),
618 RdapResponse::DomainSearchResults(r) => DomainSearchResults {
619 common: Common {
620 rdap_conformance: Some(rdap_conformance),
621 ..r.common
622 },
623 ..*r
624 }
625 .to_response(),
626 RdapResponse::EntitySearchResults(r) => EntitySearchResults {
627 common: Common {
628 rdap_conformance: Some(rdap_conformance),
629 ..r.common
630 },
631 ..*r
632 }
633 .to_response(),
634 RdapResponse::NameserverSearchResults(r) => NameserverSearchResults {
635 common: Common {
636 rdap_conformance: Some(rdap_conformance),
637 ..r.common
638 },
639 ..*r
640 }
641 .to_response(),
642 RdapResponse::IpSearchResults(r) => IpSearchResults {
643 common: Common {
644 rdap_conformance: Some(rdap_conformance),
645 ..r.common
646 },
647 ..*r
648 }
649 .to_response(),
650 RdapResponse::AutnumSearchResults(r) => AutnumSearchResults {
651 common: Common {
652 rdap_conformance: Some(rdap_conformance),
653 ..r.common
654 },
655 ..*r
656 }
657 .to_response(),
658 RdapResponse::Rpki1Roa(r) => Rpk1Roa {
659 common: Common {
660 rdap_conformance: Some(rdap_conformance),
661 ..r.common
662 },
663 ..*r
664 }
665 .to_response(),
666 RdapResponse::Rpki1Aspa(r) => Rpk1Aspa {
667 common: Common {
668 rdap_conformance: Some(rdap_conformance),
669 ..r.common
670 },
671 ..*r
672 }
673 .to_response(),
674 RdapResponse::Rpki1X509ResourceCert(r) => Rpk1X509ResourceCert {
675 common: Common {
676 rdap_conformance: Some(rdap_conformance),
677 ..r.common
678 },
679 ..*r
680 }
681 .to_response(),
682 RdapResponse::Rpki1RoaSearchResults(r) => Rpk1RoaSearchResults {
683 common: Common {
684 rdap_conformance: Some(rdap_conformance),
685 ..r.common
686 },
687 ..*r
688 }
689 .to_response(),
690 RdapResponse::Rpki1AspaSearchResults(r) => Rpk1AspaSearchResults {
691 common: Common {
692 rdap_conformance: Some(rdap_conformance),
693 ..r.common
694 },
695 ..*r
696 }
697 .to_response(),
698 RdapResponse::Rpki1X509ResourceCertSearchResults(r) => Rpk1X509ResourceCertSearchResults {
699 common: Common {
700 rdap_conformance: Some(rdap_conformance),
701 ..r.common
702 },
703 ..*r
704 }
705 .to_response(),
706 RdapResponse::ErrorResponse(e) => Rfc9083Error {
707 common: Common {
708 rdap_conformance: Some(rdap_conformance),
709 ..e.common
710 },
711 ..*e
712 }
713 .to_response(),
714 RdapResponse::Help(h) => Help {
715 common: Common {
716 rdap_conformance: Some(rdap_conformance),
717 ..h.common
718 },
719 }
720 .to_response(),
721 }
722 }
723
724 #[cfg(test)]
725 mod tests {
726 use serde_json::Value;
727
728 use crate::{
729 media_types::RDAP_MEDIA_TYPE,
730 prelude::{ExtensionId, get_relationship_links},
731 };
732
733 use super::{Domain, Link, RdapResponse, ToResponse, get_related_links};
734
735 #[test]
736 fn test_redaction_response_gets_object() {
737 // GIVEN
738 let expected: Value =
739 serde_json::from_str(include_str!("test_files/lookup_with_redaction.json")).unwrap();
740
741 // WHEN
742 let actual = RdapResponse::try_from(expected).unwrap();
743
744 // THEN
745 assert!(matches!(actual, RdapResponse::Domain(_)));
746 }
747
748 #[test]
749 fn test_redaction_response_has_extension() {
750 // GIVEN
751 let expected: Value =
752 serde_json::from_str(include_str!("test_files/lookup_with_redaction.json")).unwrap();
753
754 // WHEN
755 let actual = RdapResponse::try_from(expected).unwrap();
756
757 // THEN
758 assert!(actual.has_extension_id(ExtensionId::Redacted));
759 }
760
761 #[test]
762 fn test_redaction_response_domain_search() {
763 // GIVEN
764 let expected: Value =
765 serde_json::from_str(include_str!("test_files/domain_search_with_redaction.json"))
766 .unwrap();
767
768 // WHEN
769 let actual = RdapResponse::try_from(expected).unwrap();
770
771 // THEN
772 assert!(matches!(actual, RdapResponse::DomainSearchResults(_)));
773 }
774
775 #[test]
776 fn test_response_is_domain() {
777 // GIVEN
778 let expected: Value =
779 serde_json::from_str(include_str!("test_files/domain_afnic_fr.json")).unwrap();
780
781 // WHEN
782 let actual = RdapResponse::try_from(expected).unwrap();
783
784 // THEN
785 assert!(matches!(actual, RdapResponse::Domain(_)));
786 }
787
788 #[test]
789 fn test_response_is_entity() {
790 // GIVEN
791 let expected: Value =
792 serde_json::from_str(include_str!("test_files/entity_arin_hostmaster.json")).unwrap();
793
794 // WHEN
795 let actual = RdapResponse::try_from(expected).unwrap();
796
797 // THEN
798 assert!(matches!(actual, RdapResponse::Entity(_)));
799 }
800
801 #[test]
802 fn test_response_is_nameserver() {
803 // GIVEN
804 let expected: Value =
805 serde_json::from_str(include_str!("test_files/nameserver_ns1_nic_fr.json")).unwrap();
806
807 // WHEN
808 let actual = RdapResponse::try_from(expected).unwrap();
809
810 // THEN
811 assert!(matches!(actual, RdapResponse::Nameserver(_)));
812 }
813
814 #[test]
815 fn test_response_is_autnum() {
816 // GIVEN
817 let expected: Value =
818 serde_json::from_str(include_str!("test_files/autnum_16509.json")).unwrap();
819
820 // WHEN
821 let actual = RdapResponse::try_from(expected).unwrap();
822
823 // THEN
824 assert!(matches!(actual, RdapResponse::Autnum(_)));
825 }
826
827 #[test]
828 fn test_response_is_network() {
829 // GIVEN
830 let expected: Value =
831 serde_json::from_str(include_str!("test_files/network_192_198_0_0.json")).unwrap();
832
833 // WHEN
834 let actual = RdapResponse::try_from(expected).unwrap();
835
836 // THEN
837 assert!(matches!(actual, RdapResponse::Network(_)));
838 }
839
840 #[test]
841 fn test_response_is_domain_search_results() {
842 // GIVEN
843 let expected: Value =
844 serde_json::from_str(include_str!("test_files/domains_ldhname_ns1_arin_net.json"))
845 .unwrap();
846
847 // WHEN
848 let actual = RdapResponse::try_from(expected).unwrap();
849
850 // THEN
851 assert!(matches!(actual, RdapResponse::DomainSearchResults(_)));
852 }
853
854 #[test]
855 fn test_response_is_entity_search_results() {
856 // GIVEN
857 let expected: Value =
858 serde_json::from_str(include_str!("test_files/entities_fn_arin.json")).unwrap();
859
860 // WHEN
861 let actual = RdapResponse::try_from(expected).unwrap();
862
863 // THEN
864 assert!(matches!(actual, RdapResponse::EntitySearchResults(_)));
865 }
866
867 #[test]
868 fn test_response_is_ip_search_results() {
869 // GIVEN
870 let expected = r#"
871 {
872 "rdapConformance": [
873 "rdap_level_0"
874 ],
875 "ipSearchResults": [
876 {
877 "objectClassName": "ip network",
878 "handle": "NET-10-0-0-0",
879 "startAddress": "10.0.0.0",
880 "endAddress": "10.0.0.255",
881 "ipVersion": "v4"
882 }
883 ]
884 }
885 "#;
886
887 // WHEN
888 let actual =
889 RdapResponse::try_from(serde_json::from_str::<Value>(expected).unwrap()).unwrap();
890
891 // THEN
892 assert!(matches!(actual, RdapResponse::IpSearchResults(_)));
893 }
894
895 #[test]
896 fn test_response_is_autnum_search_results() {
897 // GIVEN
898 let expected = r#"
899 {
900 "rdapConformance": [
901 "rdap_level_0"
902 ],
903 "autnumSearchResults": [
904 {
905 "objectClassName": "autnum",
906 "handle": "AS65000",
907 "startAutnum": 65000,
908 "endAutnum": 65000,
909 "name": "TEST-AS",
910 "status": "active"
911 }
912 ]
913 }
914 "#;
915
916 // WHEN
917 let actual =
918 RdapResponse::try_from(serde_json::from_str::<Value>(expected).unwrap()).unwrap();
919
920 // THEN
921 assert!(matches!(actual, RdapResponse::AutnumSearchResults(_)));
922 }
923
924 #[test]
925 fn test_response_is_help() {
926 // GIVEN
927 let expected: Value =
928 serde_json::from_str(include_str!("test_files/help_nic_fr.json")).unwrap();
929
930 // WHEN
931 let actual = RdapResponse::try_from(expected).unwrap();
932
933 // THEN
934 assert!(matches!(actual, RdapResponse::Help(_)));
935 }
936
937 #[test]
938 fn test_response_is_error() {
939 // GIVEN
940 let expected: Value =
941 serde_json::from_str(include_str!("test_files/error_ripe_net.json")).unwrap();
942
943 // WHEN
944 let actual = RdapResponse::try_from(expected).unwrap();
945
946 // THEN
947 assert!(matches!(actual, RdapResponse::ErrorResponse(_)));
948 }
949
950 #[test]
951 fn test_string_is_entity_search_results() {
952 // GIVEN
953 let entity: Value =
954 serde_json::from_str(include_str!("test_files/entities_fn_arin.json")).unwrap();
955 let value = RdapResponse::try_from(entity).unwrap();
956
957 // WHEN
958 let actual = value.to_string();
959
960 // THEN
961 assert_eq!(actual, "EntitySearchResults");
962 }
963
964 #[test]
965 fn test_get_related_for_non_rel_link() {
966 // GIVEN
967 let rdap = Domain::builder()
968 .ldh_name("example.com")
969 .link(
970 Link::builder()
971 .rel("not-related")
972 .href("http://example.com")
973 .value("http://example.com")
974 .build(),
975 )
976 .build()
977 .to_response();
978
979 // WHEN
980 let links = get_related_links(&rdap);
981
982 // THEN
983 assert!(links.is_empty());
984 }
985
986 #[test]
987 fn test_get_related_for_rel_with_rdap_type_link() {
988 // GIVEN
989 let link = Link::builder()
990 .rel("related")
991 .href("http://example.com")
992 .value("http://example.com")
993 .media_type(RDAP_MEDIA_TYPE)
994 .build();
995 let rdap = Domain::builder()
996 .ldh_name("example.com")
997 .link(link.clone())
998 .build()
999 .to_response();
1000
1001 // WHEN
1002 let links = get_related_links(&rdap);
1003
1004 // THEN
1005 assert!(!links.is_empty());
1006 assert_eq!(links.first().expect("empty links"), &link.href().unwrap());
1007 }
1008
1009 #[test]
1010 fn test_get_related_for_rel_link() {
1011 // GIVEN
1012 let link = Link::builder()
1013 .rel("related")
1014 .href("http://example.com")
1015 .value("http://example.com")
1016 .build();
1017 let rdap = Domain::builder()
1018 .ldh_name("example.com")
1019 .link(link.clone())
1020 .build()
1021 .to_response();
1022
1023 // WHEN
1024 let links = get_related_links(&rdap);
1025
1026 // THEN
1027 assert!(links.is_empty());
1028 }
1029
1030 #[test]
1031 fn test_get_related_for_rel_link_that_look_like_rdap() {
1032 // GIVEN
1033 let link = Link::builder()
1034 .rel("related")
1035 .href("http://example.com/domain/foo")
1036 .value("http://example.com")
1037 .build();
1038 let rdap = Domain::builder()
1039 .ldh_name("example.com")
1040 .link(link.clone())
1041 .build()
1042 .to_response();
1043
1044 // WHEN
1045 let links = get_related_links(&rdap);
1046
1047 // THEN
1048 assert!(!links.is_empty());
1049 assert_eq!(links.first().expect("empty links"), &link.href().unwrap());
1050 }
1051
1052 #[test]
1053 fn test_get_rdap_up_and_rdap_active_link() {
1054 // GIVEN
1055 let link = Link::builder()
1056 .rel("rdap-up rdap-active")
1057 .href("http://example.com")
1058 .value("http://example.com")
1059 .media_type(RDAP_MEDIA_TYPE)
1060 .build();
1061 let rdap = Domain::builder()
1062 .ldh_name("example.com")
1063 .link(link.clone())
1064 .build()
1065 .to_response();
1066
1067 // WHEN
1068 let links =
1069 get_relationship_links(&["rdap-up".to_string(), "rdap-active".to_string()], &rdap);
1070
1071 // THEN
1072 assert!(!links.is_empty());
1073 assert_eq!(links.first().expect("empty links"), &link.href().unwrap());
1074 }
1075
1076 #[test]
1077 fn test_get_rdap_active_and_rdap_up_link() {
1078 // GIVEN
1079 let link = Link::builder()
1080 .rel("rdap-up rdap-active")
1081 .href("http://example.com")
1082 .value("http://example.com")
1083 .media_type(RDAP_MEDIA_TYPE)
1084 .build();
1085 let rdap = Domain::builder()
1086 .ldh_name("example.com")
1087 .link(link.clone())
1088 .build()
1089 .to_response();
1090
1091 // WHEN
1092 let links =
1093 get_relationship_links(&["rdap-active".to_string(), "rdap-up".to_string()], &rdap);
1094
1095 // THEN
1096 assert!(!links.is_empty());
1097 assert_eq!(links.first().expect("empty links"), &link.href().unwrap());
1098 }
1099
1100 #[test]
1101 fn test_get_only_one_relationship_link() {
1102 // GIVEN
1103 let link = Link::builder()
1104 .rel("rdap-up rdap-active")
1105 .href("http://example.com")
1106 .value("http://example.com")
1107 .media_type(RDAP_MEDIA_TYPE)
1108 .build();
1109 let rdap = Domain::builder()
1110 .ldh_name("example.com")
1111 .link(link.clone())
1112 .build()
1113 .to_response();
1114
1115 // WHEN
1116 let links = get_relationship_links(&["rdap-up".to_string()], &rdap);
1117
1118 // THEN
1119 assert!(links.is_empty());
1120 }
1121
1122 #[test]
1123 fn test_get_too_many_relationship_link() {
1124 // GIVEN
1125 let link = Link::builder()
1126 .rel("rdap-up")
1127 .href("http://example.com")
1128 .value("http://example.com")
1129 .media_type(RDAP_MEDIA_TYPE)
1130 .build();
1131 let rdap = Domain::builder()
1132 .ldh_name("example.com")
1133 .link(link.clone())
1134 .build()
1135 .to_response();
1136
1137 // WHEN
1138 let links =
1139 get_relationship_links(&["rdap-active".to_string(), "rdap-up".to_string()], &rdap);
1140
1141 // THEN
1142 assert!(links.is_empty());
1143 }
1144 }