Debian Codegraph @

src/response/nameserver.rs

raw
1 //! RDAP Nameserver object class.
2 use std::collections::HashSet;
3
4 use crate::prelude::{ContentExtensions, ttl::Ttl0Data};
5
6 use {
7 crate::prelude::{Common, Extension, ObjectCommon},
8 std::{net::IpAddr, str::FromStr},
9 };
10
11 use serde::{Deserialize, Serialize};
12
13 use super::{
14 CommonFields, Entity, Event, GetSelfLink, Notice, ObjectCommonFields, Port43,
15 RdapResponseError, Remark, SelfLink, ToChild, ToResponse, VectorStringish, to_opt_vec,
16 to_opt_vectorstringish, types::Link,
17 };
18
19 /// Represents an IP address set for nameservers.
20 #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
21 pub struct IpAddresses {
22 #[serde(skip_serializing_if = "Option::is_none")]
23 pub v6: Option<VectorStringish>,
24
25 #[serde(skip_serializing_if = "Option::is_none")]
26 pub v4: Option<VectorStringish>,
27 }
28
29 #[buildstructor::buildstructor]
30 impl IpAddresses {
31 /// Builds nameserver IP address.
32 #[builder(visibility = "pub")]
33 fn new(addresses: Vec<String>) -> Result<Self, RdapResponseError> {
34 let mut v4: Vec<String> = Vec::new();
35 let mut v6: Vec<String> = Vec::new();
36 for addr in addresses {
37 let ip = IpAddr::from_str(&addr)?;
38 match ip {
39 IpAddr::V4(_) => v4.push(addr),
40 IpAddr::V6(_) => v6.push(addr),
41 }
42 }
43 Ok(Self {
44 v4: to_opt_vectorstringish(v4),
45 v6: to_opt_vectorstringish(v6),
46 })
47 }
48
49 #[allow(dead_code)]
50 #[builder(entry = "illegal", visibility = "pub(crate)")]
51 fn new_illegal(v6: Option<Vec<String>>, v4: Option<Vec<String>>) -> Self {
52 Self {
53 v4: v4.map(VectorStringish::from),
54 v6: v6.map(VectorStringish::from),
55 }
56 }
57
58 /// Get the IPv6 addresses.
59 pub fn v6s(&self) -> &[String] {
60 self.v6
61 .as_ref()
62 .map(|v| v.vec().as_ref())
63 .unwrap_or_default()
64 }
65
66 /// Get the IPv4 addresses.
67 pub fn v4s(&self) -> &[String] {
68 self.v4
69 .as_ref()
70 .map(|v| v.vec().as_ref())
71 .unwrap_or_default()
72 }
73 }
74
75 /// Represents an RDAP [nameserver](https://rdap.rcode3.com/protocol/object_classes.html#nameserver) response.
76 ///
77 /// Using the builder is recommended to construct this structure as it
78 /// will fill-in many of the mandatory fields.
79 /// The following is an example.
80 ///
81 /// ```rust
82 /// use icann_rdap_common::prelude::*;
83 ///
84 /// let ns = Nameserver::response_obj()
85 /// .ldh_name("ns1.example.com")
86 /// .handle("ns1_example_com-1")
87 /// .status("active")
88 /// .address("10.0.0.1")
89 /// .address("10.0.0.2")
90 /// .entity(Entity::builder().handle("FOO").build())
91 /// .build().unwrap();
92 /// let c = serde_json::to_string_pretty(&ns).unwrap();
93 /// eprintln!("{c}");
94 /// ```
95 ///
96 /// This will produce the following.
97 ///
98 /// ```norust
99 /// {
100 /// "rdapConformance": [
101 /// "rdap_level_0"
102 /// ],
103 /// "objectClassName": "nameserver",
104 /// "handle": "ns1_example_com-1",
105 /// "status": [
106 /// "active"
107 /// ],
108 /// "entities": [
109 /// {
110 /// "rdapConformance": [
111 /// "rdap_level_0"
112 /// ],
113 /// "objectClassName": "entity",
114 /// "handle": "FOO"
115 /// }
116 /// ],
117 /// "ldhName": "ns1.example.com",
118 /// "ipAddresses": {
119 /// "v4": [
120 /// "10.0.0.1",
121 /// "10.0.0.2"
122 /// ]
123 /// }
124 /// }
125 /// ```
126 ///
127 /// Access to the nameserver information should be done via the getter functions.
128 /// See [CommonFields] and [ObjectCommonFields] for common getter functions.
129 /// ```rust
130 /// # use icann_rdap_common::prelude::*;
131 /// # let nameserver = Nameserver::builder()
132 /// # .ldh_name("foo.example.com")
133 /// # .build().unwrap();
134 /// let handle = nameserver.handle();
135 /// let ldh_name = nameserver.ldh_name();
136 /// let unicode_name = nameserver.unicode_name();
137 /// let ip_addresses = nameserver.ip_addresses();
138 /// ```
139 #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
140 pub struct Nameserver {
141 #[serde(flatten)]
142 pub common: Common,
143
144 #[serde(flatten)]
145 pub object_common: ObjectCommon,
146
147 #[serde(rename = "ldhName")]
148 #[serde(skip_serializing_if = "Option::is_none")]
149 pub ldh_name: Option<String>,
150
151 #[serde(rename = "unicodeName")]
152 #[serde(skip_serializing_if = "Option::is_none")]
153 pub unicode_name: Option<String>,
154
155 #[serde(rename = "ipAddresses")]
156 #[serde(skip_serializing_if = "Option::is_none")]
157 pub ip_addresses: Option<IpAddresses>,
158
159 #[serde(skip_serializing_if = "Option::is_none")]
160 pub ttl0_data: Option<Ttl0Data>,
161 }
162
163 #[buildstructor::buildstructor]
164 impl Nameserver {
165 /// Builds a basic nameserver object for use with embedding into response objects.
166 ///
167 /// ```rust
168 /// use icann_rdap_common::prelude::*;
169 ///
170 /// let ns = Nameserver::builder()
171 /// .ldh_name("ns1.example.com") //required for this builder
172 /// .handle("ns1_example_com-1")
173 /// .status("active")
174 /// .address("10.0.0.1")
175 /// .address("10.0.0.2")
176 /// .entity(Entity::builder().handle("FOO").build())
177 /// .remark(Remark::builder().title("hidden nameserver").build())
178 /// .build().unwrap();
179 /// ```
180 #[builder(visibility = "pub")]
181 fn new<T: Into<String>>(
182 ldh_name: T,
183 addresses: Vec<String>,
184 handle: Option<String>,
185 remarks: Vec<Remark>,
186 links: Vec<Link>,
187 events: Vec<Event>,
188 statuses: Vec<String>,
189 port_43: Option<Port43>,
190 entities: Vec<Entity>,
191 ttl0_data: Option<Ttl0Data>,
192 redacted: Option<Vec<crate::response::redacted::Redacted>>,
193 ) -> Result<Self, RdapResponseError> {
194 let ip_addresses = if !addresses.is_empty() {
195 Some(IpAddresses::builder().addresses(addresses).build()?)
196 } else {
197 None
198 };
199 Ok(Self {
200 common: Common::builder().build(),
201 object_common: ObjectCommon::nameserver()
202 .and_handle(handle)
203 .and_remarks(to_opt_vec(remarks))
204 .and_links(to_opt_vec(links))
205 .and_events(to_opt_vec(events))
206 .status(statuses)
207 .and_port_43(port_43)
208 .and_entities(to_opt_vec(entities))
209 .and_redacted(redacted)
210 .build(),
211 ldh_name: Some(ldh_name.into()),
212 unicode_name: None,
213 ip_addresses,
214 ttl0_data,
215 })
216 }
217
218 /// Builds a nameserver object for a response.
219 ///
220 /// ```rust
221 /// use icann_rdap_common::prelude::*;
222 ///
223 /// let ns = Nameserver::response_obj()
224 /// .ldh_name("ns1.example.com") //required for this builder
225 /// .handle("ns1_example_com-1")
226 /// .status("active")
227 /// .address("10.0.0.1")
228 /// .address("10.0.0.2")
229 /// .entity(Entity::builder().handle("FOO").build())
230 /// .extension(ExtensionId::NroRdapProfile0.as_ref())
231 /// .notice(Notice::builder().title("test").build())
232 /// .build().unwrap();
233 /// ```
234 #[builder(entry = "response_obj", visibility = "pub")]
235 fn new_response_obj<T: Into<String>>(
236 ldh_name: T,
237 addresses: Vec<String>,
238 handle: Option<String>,
239 remarks: Vec<Remark>,
240 links: Vec<Link>,
241 events: Vec<Event>,
242 statuses: Vec<String>,
243 port_43: Option<Port43>,
244 entities: Vec<Entity>,
245 notices: Vec<Notice>,
246 extensions: Vec<Extension>,
247 ttl0_data: Option<Ttl0Data>,
248 redacted: Option<Vec<crate::response::redacted::Redacted>>,
249 ) -> Result<Self, RdapResponseError> {
250 let common = Common::level0()
251 .extensions(extensions)
252 .and_notices(to_opt_vec(notices))
253 .build();
254 let mut nameserver = Nameserver::builder()
255 .ldh_name(ldh_name)
256 .addresses(addresses)
257 .and_handle(handle)
258 .remarks(remarks)
259 .links(links)
260 .events(events)
261 .statuses(statuses)
262 .and_port_43(port_43)
263 .entities(entities)
264 .and_ttl0_data(ttl0_data)
265 .and_redacted(redacted)
266 .build()?;
267 nameserver.common = common;
268 Ok(nameserver)
269 }
270
271 #[builder(entry = "illegal", visibility = "pub(crate)")]
272 #[allow(dead_code)]
273 fn new_illegal(ldh_name: Option<String>, ip_addresses: Option<IpAddresses>) -> Self {
274 Self {
275 common: Common::level0().build(),
276 object_common: ObjectCommon::nameserver().build(),
277 ldh_name,
278 unicode_name: None,
279 ip_addresses,
280 ttl0_data: None,
281 }
282 }
283
284 /// Get the LDH name.
285 pub fn ldh_name(&self) -> Option<&str> {
286 self.ldh_name.as_deref()
287 }
288
289 /// Get the Unicode name.
290 pub fn unicode_name(&self) -> Option<&str> {
291 self.unicode_name.as_deref()
292 }
293
294 /// Get the IP addresses.
295 pub fn ip_addresses(&self) -> Option<&IpAddresses> {
296 self.ip_addresses.as_ref()
297 }
298
299 /// Getter for the ttl0 data.
300 pub fn ttl0_data(&self) -> Option<&Ttl0Data> {
301 self.ttl0_data.as_ref()
302 }
303 }
304
305 impl ToResponse for Nameserver {
306 fn to_response(self) -> super::RdapResponse {
307 super::RdapResponse::Nameserver(Box::new(self))
308 }
309 }
310
311 impl GetSelfLink for Nameserver {
312 fn self_link(&self) -> Option<&Link> {
313 self.object_common.self_link()
314 }
315 }
316
317 impl SelfLink for Nameserver {
318 fn with_self_link(mut self, link: Link) -> Self {
319 self.object_common = self.object_common.with_self_link(link);
320 self
321 }
322 }
323
324 impl ToChild for Nameserver {
325 fn to_child(mut self) -> Self {
326 self.common = Common {
327 rdap_conformance: None,
328 notices: None,
329 };
330 self
331 }
332 }
333
334 impl CommonFields for Nameserver {
335 fn common(&self) -> &Common {
336 &self.common
337 }
338 }
339
340 impl ObjectCommonFields for Nameserver {
341 fn object_common(&self) -> &ObjectCommon {
342 &self.object_common
343 }
344 }
345
346 impl ContentExtensions for Nameserver {
347 fn content_extensions(&self) -> std::collections::HashSet<super::ExtensionId> {
348 let mut exts = HashSet::new();
349 exts.extend(self.common().content_extensions());
350 exts.extend(self.object_common().content_extensions());
351 exts
352 }
353 }
354
355 #[cfg(test)]
356 #[allow(non_snake_case)]
357 mod tests {
358 use super::Nameserver;
359
360 #[test]
361 fn GIVEN_nameserver_WHEN_deserialize_THEN_success() {
362 // GIVEN
363 let expected = r#"
364 {
365 "objectClassName" : "nameserver",
366 "handle" : "XXXX",
367 "ldhName" : "ns1.xn--fo-5ja.example",
368 "unicodeName" : "ns.fóo.example",
369 "status" : [ "active" ],
370 "ipAddresses" :
371 {
372 "v4": [ "192.0.2.1", "192.0.2.2" ],
373 "v6": [ "2001:db8::123" ]
374 },
375 "remarks" :
376 [
377 {
378 "description" :
379 [
380 "She sells sea shells down by the sea shore.",
381 "Originally written by Terry Sullivan."
382 ]
383 }
384 ],
385 "links" :
386 [
387 {
388 "value" : "https://example.net/nameserver/ns1.xn--fo-5ja.example",
389 "rel" : "self",
390 "href" : "https://example.net/nameserver/ns1.xn--fo-5ja.example",
391 "type" : "application/rdap+json"
392 }
393 ],
394 "port43" : "whois.example.net",
395 "events" :
396 [
397 {
398 "eventAction" : "registration",
399 "eventDate" : "1990-12-31T23:59:59Z"
400 },
401 {
402 "eventAction" : "last changed",
403 "eventDate" : "1991-12-31T23:59:59Z",
404 "eventActor" : "[email protected]"
405 }
406 ]
407 }
408 "#;
409
410 // WHEN
411 let actual = serde_json::from_str::<Nameserver>(expected);
412
413 // THEN
414 let actual = actual.unwrap();
415 assert_eq!(actual.object_common.object_class_name, "nameserver");
416 assert!(actual.object_common.handle.is_some());
417 assert!(actual.ldh_name.is_some());
418 assert!(actual.unicode_name.is_some());
419 assert!(actual.ip_addresses.is_some());
420 assert!(actual.object_common.remarks.is_some());
421 assert!(actual.object_common.status.is_some());
422 assert!(actual.object_common.links.is_some());
423 assert!(actual.object_common.events.is_some());
424 }
425 }