monovm-whois-rust 1.0.0

Domain WHOIS and RDAP lookups with availability detection, structured record parsing, referral chasing, caching and rate limiting.
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
//! The RDAP response objects of RFC 9083, and the jCard of RFC 7095.

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// An RDAP response to a domain query.
///
/// Models both shapes a server can return: a domain object, or the error object
/// RFC 9083 §6 defines. They share a type because they arrive from the same
/// request and a caller has to handle whichever came back — a 404 error object is
/// the *answer* to "is this domain registered", not a failure.
///
/// Unknown members are ignored rather than rejected. RDAP is designed to be
/// extended, registries do extend it, and a parser that refuses an unrecognised
/// member is a parser that breaks on the next extension.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct RdapResponse {
    /// `"domain"` for a domain object.
    pub object_class_name: Option<String>,
    /// Registry's identifier for the registration.
    pub handle: Option<String>,
    /// The domain in punycode.
    pub ldh_name: Option<String>,
    /// The domain in its Unicode form, when internationalised.
    pub unicode_name: Option<String>,
    /// EPP status values.
    pub status: Vec<String>,
    /// Lifecycle events: registration, expiration, last changed.
    pub events: Vec<RdapEvent>,
    /// Delegated name servers.
    pub nameservers: Vec<RdapNameserver>,
    /// DNSSEC delegation state.
    ///
    /// Spelled out rather than left to `rename_all`: RFC 9083 names this member
    /// `secureDNS`, and camel-casing `secure_dns` would produce `secureDns`, which no
    /// server sends.
    #[serde(rename = "secureDNS")]
    pub secure_dns: Option<SecureDns>,
    /// Registrar, registrant and contact entities.
    pub entities: Vec<RdapEntity>,
    /// Which RDAP extensions the server implements.
    pub rdap_conformance: Vec<String>,
    /// Legal notices attached to the response.
    pub notices: Vec<RdapNotice>,

    /// HTTP status repeated in the body, on an error object.
    pub error_code: Option<u16>,
    /// Short error description, on an error object.
    pub title: Option<String>,
    /// Longer error description, on an error object.
    pub description: Vec<String>,
}

impl RdapResponse {
    /// Parse a response body.
    pub fn parse(json: &str) -> serde_json::Result<Self> {
        serde_json::from_str(json)
    }

    /// Whether this is the error object RFC 9083 §6 defines.
    pub fn is_error(&self) -> bool {
        self.error_code.is_some()
    }

    /// Whether this is a domain object describing a registration.
    pub fn is_domain(&self) -> bool {
        !self.is_error()
            && (self
                .object_class_name
                .as_deref()
                .is_some_and(|class| class.eq_ignore_ascii_case("domain"))
                || self.ldh_name.is_some())
    }

    /// The date of one lifecycle event, if the server published it.
    ///
    /// ```
    /// use monovm_whois::rdap::RdapResponse;
    ///
    /// let response = RdapResponse::parse(r#"{
    ///     "objectClassName": "domain",
    ///     "ldhName": "example.com",
    ///     "events": [{"eventAction": "registration", "eventDate": "1995-08-14T04:00:00Z"}]
    /// }"#).unwrap();
    ///
    /// assert_eq!(response.event_date("registration"), Some("1995-08-14T04:00:00Z"));
    /// assert_eq!(response.event_date("expiration"), None);
    /// ```
    pub fn event_date(&self, action: &str) -> Option<&str> {
        self.events
            .iter()
            .find(|event| {
                event
                    .event_action
                    .as_deref()
                    .is_some_and(|value| value.eq_ignore_ascii_case(action))
            })
            .and_then(|event| event.event_date.as_deref())
    }

    /// The first entity holding a role, case-insensitively.
    pub fn entity_with_role(&self, role: &str) -> Option<&RdapEntity> {
        self.entities.iter().find(|entity| entity.has_role(role))
    }

    /// Name-server host names in punycode, lower-cased.
    pub fn nameserver_names(&self) -> Vec<String> {
        self.nameservers
            .iter()
            .filter_map(|server| server.ldh_name.as_deref())
            .map(|name| name.trim_end_matches('.').to_lowercase())
            .collect()
    }

    /// Whether the delegation is signed, when the server says.
    pub fn is_signed(&self) -> Option<bool> {
        self.secure_dns
            .as_ref()
            .and_then(|dns| dns.delegation_signed)
    }
}

/// One lifecycle event.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct RdapEvent {
    /// What happened: `registration`, `expiration`, `last changed`, `transfer`.
    pub event_action: Option<String>,
    /// When, as an RFC 3339 timestamp.
    pub event_date: Option<String>,
    /// Who did it.
    pub event_actor: Option<String>,
}

/// A delegated name server.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct RdapNameserver {
    /// `"nameserver"`.
    pub object_class_name: Option<String>,
    /// The host name in punycode.
    pub ldh_name: Option<String>,
    /// The host name in Unicode.
    pub unicode_name: Option<String>,
    /// Glue addresses, keyed `v4` and `v6`.
    pub ip_addresses: Option<IpAddresses>,
}

/// Glue records for a name server.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct IpAddresses {
    /// IPv4 glue.
    pub v4: Vec<String>,
    /// IPv6 glue.
    pub v6: Vec<String>,
}

/// DNSSEC delegation state.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct SecureDns {
    /// Whether the parent zone holds a DS record.
    pub delegation_signed: Option<bool>,
    /// Whether the zone itself is signed.
    pub zone_signed: Option<bool>,
    /// DS records published in the parent.
    pub ds_data: Vec<Value>,
    /// DNSKEY records.
    pub key_data: Vec<Value>,
}

/// A registrar, registrant or contact.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct RdapEntity {
    /// `"entity"`.
    pub object_class_name: Option<String>,
    /// Registry or registrar handle.
    pub handle: Option<String>,
    /// Roles held: `registrar`, `registrant`, `administrative`, `technical`.
    pub roles: Vec<String>,
    /// Contact details as a jCard, RFC 7095.
    pub vcard_array: Option<Value>,
    /// Public identifiers, such as the registrar's IANA number.
    pub public_ids: Vec<PublicId>,
    /// Nested entities: a registrar's abuse contact lives here.
    pub entities: Vec<RdapEntity>,
    /// Status values.
    pub status: Vec<String>,
    /// Lifecycle events for the entity.
    pub events: Vec<RdapEvent>,
}

impl RdapEntity {
    /// Whether the entity holds a role, case-insensitively.
    pub fn has_role(&self, role: &str) -> bool {
        self.roles
            .iter()
            .any(|held| held.eq_ignore_ascii_case(role))
    }

    /// The contact details, parsed.
    pub fn card(&self) -> JCard {
        JCard::from_value(self.vcard_array.as_ref())
    }

    /// A public identifier by type, e.g. `"IANA Registrar ID"`.
    pub fn public_id(&self, kind: &str) -> Option<&str> {
        self.public_ids
            .iter()
            .find(|id| {
                id.id_type
                    .as_deref()
                    .is_some_and(|value| value.eq_ignore_ascii_case(kind))
            })
            .and_then(|id| id.identifier.as_deref())
    }

    /// The best available display name: the jCard's formatted name, its
    /// organisation, or the handle.
    pub fn display_name(&self) -> Option<String> {
        let card = self.card();
        card.formatted_name()
            .or_else(|| card.organization())
            .map(str::to_string)
            .or_else(|| self.handle.clone())
    }

    /// Every nested entity holding a role, at any depth.
    ///
    /// Registrars nest their abuse contact one level down, and some registries nest
    /// deeper than that.
    pub fn find_role(&self, role: &str) -> Option<&RdapEntity> {
        if self.has_role(role) {
            return Some(self);
        }
        self.entities
            .iter()
            .find_map(|nested| nested.find_role(role))
    }
}

/// A public identifier attached to an entity.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PublicId {
    /// What kind of identifier, e.g. `IANA Registrar ID`.
    #[serde(rename = "type", default)]
    pub id_type: Option<String>,
    /// The value.
    #[serde(default)]
    pub identifier: Option<String>,
}

/// A legal notice.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct RdapNotice {
    /// Heading.
    pub title: Option<String>,
    /// Body, one entry per paragraph.
    pub description: Vec<String>,
    /// Related links.
    pub links: Vec<Value>,
}

/// One jCard property: name, parameters, type and value.
#[derive(Debug, Clone, PartialEq)]
pub struct JCardProperty {
    /// Lower-cased property name, e.g. `fn`, `org`, `adr`.
    pub name: String,
    /// The value as text, with structured values flattened.
    pub value: String,
    /// Components of a structured value such as `adr`, in order.
    pub components: Vec<String>,
}

/// Contact details in the jCard form RDAP uses, RFC 7095.
///
/// jCard is vCard expressed as nested JSON arrays:
///
/// ```json
/// ["vcard", [
///   ["version", {}, "text", "4.0"],
///   ["fn", {}, "text", "Ada Lovelace"],
///   ["adr", {}, "text", ["", "", "1 Example Street", "London", "", "EC1A 1AA", "GB"]]
/// ]]
/// ```
///
/// Positional arrays with an object in the middle do not map onto a Rust struct,
/// so this type does the walking and exposes the handful of properties a
/// registration record needs.
///
/// ```
/// use monovm_whois::rdap::JCard;
///
/// let card = JCard::parse(r#"["vcard",[
///     ["version",{},"text","4.0"],
///     ["fn",{},"text","Ada Lovelace"],
///     ["email",{},"text","ada@example.com"]
/// ]]"#).unwrap();
///
/// assert_eq!(card.formatted_name(), Some("Ada Lovelace"));
/// assert_eq!(card.email(), Some("ada@example.com"));
/// assert_eq!(card.organization(), None);
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
pub struct JCard {
    properties: Vec<JCardProperty>,
}

impl JCard {
    /// Parse a jCard from its JSON text.
    pub fn parse(json: &str) -> serde_json::Result<Self> {
        let value: Value = serde_json::from_str(json)?;
        Ok(JCard::from_value(Some(&value)))
    }

    /// Read a jCard out of an already-parsed value.
    ///
    /// Anything that is not a jCard yields an empty card. RDAP servers put
    /// surprising things in this member, and a malformed contact block should cost
    /// the contact details rather than the whole lookup.
    pub fn from_value(value: Option<&Value>) -> Self {
        let mut properties = Vec::new();

        // ["vcard", [ [name, params, type, value], ... ]]
        let entries = value
            .and_then(Value::as_array)
            .and_then(|outer| outer.get(1))
            .and_then(Value::as_array);

        for entry in entries.into_iter().flatten() {
            let Some(parts) = entry.as_array() else {
                continue;
            };
            let Some(name) = parts.first().and_then(Value::as_str) else {
                continue;
            };
            let Some(raw_value) = parts.get(3) else {
                continue;
            };

            let (value, components) = flatten_value(raw_value);
            properties.push(JCardProperty {
                name: name.to_lowercase(),
                value,
                components,
            });
        }

        JCard { properties }
    }

    /// Every property, in order.
    pub fn properties(&self) -> &[JCardProperty] {
        &self.properties
    }

    /// Whether the card holds nothing.
    pub fn is_empty(&self) -> bool {
        self.properties.is_empty()
    }

    /// The first value of a property.
    pub fn get(&self, name: &str) -> Option<&str> {
        self.properties
            .iter()
            .find(|property| property.name == name)
            .map(|property| property.value.as_str())
            .filter(|value| !value.is_empty())
    }

    /// Every value of a property.
    pub fn get_all(&self, name: &str) -> Vec<&str> {
        self.properties
            .iter()
            .filter(|property| property.name == name)
            .map(|property| property.value.as_str())
            .filter(|value| !value.is_empty())
            .collect()
    }

    /// The `fn` property: the contact's formatted name.
    pub fn formatted_name(&self) -> Option<&str> {
        self.get("fn")
    }

    /// The `org` property.
    pub fn organization(&self) -> Option<&str> {
        self.get("org")
    }

    /// The `email` property.
    pub fn email(&self) -> Option<&str> {
        self.get("email")
    }

    /// The `tel` property, preferring a voice number over a fax number.
    pub fn phone(&self) -> Option<&str> {
        self.get("tel")
    }

    /// The components of the `adr` property, in RFC 6350 order:
    /// post office box, extended address, street, locality, region, postal code,
    /// country.
    pub fn address_components(&self) -> Vec<String> {
        self.properties
            .iter()
            .find(|property| property.name == "adr")
            .map(|property| property.components.clone())
            .unwrap_or_default()
    }

    /// One `adr` component by position, empty strings treated as absent.
    pub fn address_part(&self, index: usize) -> Option<String> {
        self.address_components()
            .get(index)
            .map(|part| part.trim().to_string())
            .filter(|part| !part.is_empty())
    }
}

/// Flatten a jCard value into text plus, for structured values, its components.
fn flatten_value(value: &Value) -> (String, Vec<String>) {
    match value {
        Value::String(text) => (text.clone(), Vec::new()),
        Value::Number(number) => (number.to_string(), Vec::new()),
        Value::Bool(flag) => (flag.to_string(), Vec::new()),
        Value::Array(items) => {
            let components: Vec<String> = items
                .iter()
                .map(|item| match item {
                    Value::String(text) => text.clone(),
                    // A component may itself be an array of alternatives.
                    Value::Array(nested) => nested
                        .iter()
                        .filter_map(Value::as_str)
                        .collect::<Vec<_>>()
                        .join(" "),
                    other => other.as_str().unwrap_or_default().to_string(),
                })
                .collect();

            let joined = components
                .iter()
                .filter(|part| !part.trim().is_empty())
                .cloned()
                .collect::<Vec<_>>()
                .join(", ");

            (joined, components)
        }
        _ => (String::new(), Vec::new()),
    }
}

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

    const VERISIGN_STYLE: &str = r#"{
        "objectClassName": "domain",
        "handle": "2336799_DOMAIN_COM-VRSN",
        "ldhName": "EXAMPLE.COM",
        "status": ["client delete prohibited", "client transfer prohibited"],
        "events": [
            {"eventAction": "registration", "eventDate": "1995-08-14T04:00:00Z"},
            {"eventAction": "expiration", "eventDate": "2027-08-13T04:00:00Z"},
            {"eventAction": "last changed", "eventDate": "2026-08-14T07:01:44Z"}
        ],
        "nameservers": [
            {"objectClassName": "nameserver", "ldhName": "A.IANA-SERVERS.NET"},
            {"objectClassName": "nameserver", "ldhName": "B.IANA-SERVERS.NET."}
        ],
        "secureDNS": {"delegationSigned": true},
        "entities": [{
            "objectClassName": "entity",
            "handle": "376",
            "roles": ["registrar"],
            "publicIds": [{"type": "IANA Registrar ID", "identifier": "376"}],
            "vcardArray": ["vcard", [
                ["version", {}, "text", "4.0"],
                ["fn", {}, "text", "Example Registrar, LLC"]
            ]],
            "entities": [{
                "objectClassName": "entity",
                "roles": ["abuse"],
                "vcardArray": ["vcard", [
                    ["version", {}, "text", "4.0"],
                    ["email", {}, "text", "abuse@example-registrar.com"],
                    ["tel", {}, "text", "+1.5555555555"]
                ]]
            }]
        }],
        "rdapConformance": ["rdap_level_0", "icann_rdap_response_profile_0"]
    }"#;

    #[test]
    fn reads_a_registry_domain_object() {
        let response = RdapResponse::parse(VERISIGN_STYLE).unwrap();

        assert!(response.is_domain());
        assert!(!response.is_error());
        assert_eq!(response.ldh_name.as_deref(), Some("EXAMPLE.COM"));
        assert_eq!(response.handle.as_deref(), Some("2336799_DOMAIN_COM-VRSN"));
        assert_eq!(response.status.len(), 2);
        assert_eq!(response.is_signed(), Some(true));
        assert_eq!(
            response.nameserver_names(),
            ["a.iana-servers.net", "b.iana-servers.net"],
            "trailing dots and case must be normalised"
        );
    }

    #[test]
    fn finds_events_by_action_case_insensitively() {
        let response = RdapResponse::parse(VERISIGN_STYLE).unwrap();

        assert_eq!(
            response.event_date("registration"),
            Some("1995-08-14T04:00:00Z")
        );
        assert_eq!(
            response.event_date("EXPIRATION"),
            Some("2027-08-13T04:00:00Z")
        );
        assert_eq!(
            response.event_date("last changed"),
            Some("2026-08-14T07:01:44Z")
        );
        assert_eq!(response.event_date("transfer"), None);
    }

    #[test]
    fn finds_the_registrar_and_its_identifiers() {
        let response = RdapResponse::parse(VERISIGN_STYLE).unwrap();
        let registrar = response.entity_with_role("registrar").unwrap();

        assert_eq!(
            registrar.display_name().as_deref(),
            Some("Example Registrar, LLC")
        );
        assert_eq!(registrar.public_id("IANA Registrar ID"), Some("376"));
        assert_eq!(registrar.public_id("nonexistent"), None);
        assert!(registrar.has_role("REGISTRAR"));
    }

    #[test]
    fn finds_a_nested_abuse_contact() {
        let response = RdapResponse::parse(VERISIGN_STYLE).unwrap();
        let registrar = response.entity_with_role("registrar").unwrap();

        let abuse = registrar.find_role("abuse").unwrap();
        assert_eq!(abuse.card().email(), Some("abuse@example-registrar.com"));
        assert_eq!(abuse.card().phone(), Some("+1.5555555555"));
    }

    #[test]
    fn reads_the_error_object() {
        let response = RdapResponse::parse(
            r#"{"errorCode":404,"title":"Not Found","description":["The domain does not exist"]}"#,
        )
        .unwrap();

        assert!(response.is_error());
        assert!(!response.is_domain());
        assert_eq!(response.error_code, Some(404));
        assert_eq!(response.title.as_deref(), Some("Not Found"));
        assert_eq!(response.description, ["The domain does not exist"]);
    }

    #[test]
    fn unknown_members_are_ignored_not_rejected() {
        let response = RdapResponse::parse(
            r#"{"objectClassName":"domain","ldhName":"a.com","somethingNew":{"x":1}}"#,
        )
        .unwrap();
        assert!(response.is_domain());
    }

    #[test]
    fn an_empty_object_is_neither_a_domain_nor_an_error() {
        let response = RdapResponse::parse("{}").unwrap();
        assert!(!response.is_domain());
        assert!(!response.is_error());
    }

    #[test]
    fn a_domain_object_without_object_class_name_still_counts() {
        // Several registries omit it, though the RFC asks for it.
        let response = RdapResponse::parse(r#"{"ldhName":"example.com"}"#).unwrap();
        assert!(response.is_domain());
    }

    #[test]
    fn jcard_reads_the_flat_properties() {
        let card = JCard::parse(
            r#"["vcard",[
                ["version",{},"text","4.0"],
                ["fn",{},"text","Ada Lovelace"],
                ["org",{},"text","Example Ltd"],
                ["email",{},"text","ada@example.com"],
                ["tel",{"type":["voice"]},"uri","tel:+44.2000000000"]
            ]]"#,
        )
        .unwrap();

        assert_eq!(card.formatted_name(), Some("Ada Lovelace"));
        assert_eq!(card.organization(), Some("Example Ltd"));
        assert_eq!(card.email(), Some("ada@example.com"));
        assert_eq!(card.phone(), Some("tel:+44.2000000000"));
        assert!(!card.is_empty());
    }

    #[test]
    fn jcard_reads_a_structured_address() {
        let card = JCard::parse(
            r#"["vcard",[
                ["version",{},"text","4.0"],
                ["adr",{},"text",["","","1 Example Street","London","Greater London","EC1A 1AA","GB"]]
            ]]"#,
        )
        .unwrap();

        let parts = card.address_components();
        assert_eq!(parts.len(), 7);
        assert_eq!(card.address_part(2).as_deref(), Some("1 Example Street"));
        assert_eq!(card.address_part(3).as_deref(), Some("London"));
        assert_eq!(card.address_part(5).as_deref(), Some("EC1A 1AA"));
        assert_eq!(card.address_part(6).as_deref(), Some("GB"));
        // Empty components read as absent rather than as an empty string.
        assert_eq!(card.address_part(0), None);
        assert_eq!(card.address_part(99), None);
    }

    #[test]
    fn jcard_flattens_a_structured_value_for_display() {
        let card = JCard::parse(
            r#"["vcard",[["adr",{},"text",["","","1 Example Street","London","","EC1A 1AA","GB"]]]]"#,
        )
        .unwrap();
        assert_eq!(
            card.get("adr"),
            Some("1 Example Street, London, EC1A 1AA, GB")
        );
    }

    #[test]
    fn jcard_handles_multi_valued_components() {
        let card = JCard::parse(
            r#"["vcard",[["adr",{},"text",["","",["Flat 1","1 Example Street"],"London","","","GB"]]]]"#,
        )
        .unwrap();
        assert_eq!(
            card.address_part(2).as_deref(),
            Some("Flat 1 1 Example Street")
        );
    }

    #[test]
    fn jcard_returns_every_value_of_a_repeated_property() {
        let card = JCard::parse(
            r#"["vcard",[
                ["email",{},"text","one@example.com"],
                ["email",{},"text","two@example.com"]
            ]]"#,
        )
        .unwrap();

        assert_eq!(
            card.get_all("email"),
            ["one@example.com", "two@example.com"]
        );
        assert_eq!(card.email(), Some("one@example.com"));
    }

    #[test]
    fn a_malformed_jcard_costs_only_the_contact_details() {
        for json in [
            "null",
            "{}",
            "[]",
            r#"["vcard"]"#,
            r#"["vcard", "not an array"]"#,
            r#"["vcard", [["fn"]]]"#,
            r#"["vcard", [null, 42]]"#,
        ] {
            let card = JCard::parse(json).unwrap();
            assert!(card.is_empty(), "for {json}");
            assert_eq!(card.formatted_name(), None);
            assert!(card.address_components().is_empty());
        }
    }

    #[test]
    fn an_entity_with_no_vcard_falls_back_to_its_handle() {
        let entity = RdapEntity {
            handle: Some("EX123".into()),
            roles: vec!["registrant".into()],
            ..RdapEntity::default()
        };

        assert_eq!(entity.display_name().as_deref(), Some("EX123"));
        assert!(entity.card().is_empty());
    }

    #[test]
    fn round_trips_through_json() {
        let response = RdapResponse::parse(VERISIGN_STYLE).unwrap();
        let json = serde_json::to_string(&response).unwrap();
        assert_eq!(RdapResponse::parse(&json).unwrap(), response);
    }
}