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
//! [`RdapParser`]: turning an RDAP object into the same record a WHOIS text gives.

use crate::domain::DomainName;
use crate::error::{Error, Result};
use crate::parser::{parse_datetime, Contact, RecordParser, WhoisRecord};
use crate::rdap::{JCard, RdapEntity, RdapResponse};
use crate::transport::{RawResponse, ResponseKind};

/// Reads an RDAP domain object into a [`WhoisRecord`].
///
/// The point of mapping RDAP onto the same record type as WHOIS text is that a
/// caller should not have to care which protocol answered. Whether a registry
/// runs RDAP, port 43, or both, `record.expires` means the same thing.
///
/// ```
/// use monovm_whois::parser::RdapParser;
///
/// let record = RdapParser::new().parse_json(r#"{
///     "objectClassName": "domain",
///     "ldhName": "example.com",
///     "status": ["client transfer prohibited"],
///     "events": [{"eventAction": "expiration", "eventDate": "2027-08-13T04:00:00Z"}],
///     "nameservers": [{"ldhName": "A.IANA-SERVERS.NET"}],
///     "entities": [{
///         "roles": ["registrar"],
///         "publicIds": [{"type": "IANA Registrar ID", "identifier": "376"}],
///         "vcardArray": ["vcard", [["fn", {}, "text", "Example Registrar, LLC"]]]
///     }]
/// }"#).unwrap();
///
/// assert_eq!(record.registrar.as_deref(), Some("Example Registrar, LLC"));
/// assert_eq!(record.registrar_iana_id.as_deref(), Some("376"));
/// assert_eq!(record.name_servers, ["a.iana-servers.net"]);
/// assert!(record.is_transfer_locked());
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct RdapParser {
    _private: (),
}

impl RdapParser {
    /// A parser.
    pub fn new() -> Self {
        RdapParser { _private: () }
    }

    /// Parse a response body.
    ///
    /// # Errors
    ///
    /// [`Error::Rdap`] when the body is not JSON. An error object parses fine and
    /// yields an empty record, since "this domain does not exist" is a valid answer
    /// with no registration in it.
    pub fn parse_json(&self, json: &str) -> Result<WhoisRecord> {
        let response = RdapResponse::parse(json).map_err(|source| Error::Rdap {
            url: "<in-memory>".to_string(),
            source,
        })?;
        Ok(self.map(&response))
    }

    /// Map an already-parsed response.
    pub fn map(&self, response: &RdapResponse) -> WhoisRecord {
        let mut record = WhoisRecord::new();

        if response.is_error() {
            return record;
        }

        // Prefer the Unicode name for display purposes but store the ASCII form,
        // exactly as the key/value parser does, so the two agree.
        record.domain = response
            .ldh_name
            .as_deref()
            .or(response.unicode_name.as_deref())
            .and_then(|name| DomainName::parse(name).ok());
        record.registry_id = response.handle.clone();

        record.statuses = response
            .status
            .iter()
            .map(|status| status.to_lowercase())
            .collect();
        record.statuses.dedup();

        record.name_servers = response.nameserver_names();
        record.name_servers.sort();
        record.name_servers.dedup();

        record.dnssec = response.is_signed();

        record.created = response.event_date("registration").and_then(parse_datetime);
        record.expires = response.event_date("expiration").and_then(parse_datetime);
        record.updated = response
            .event_date("last changed")
            .or_else(|| response.event_date("last update of RDAP database"))
            .and_then(parse_datetime);

        if let Some(registrar) = response.entity_with_role("registrar") {
            record.registrar = registrar.display_name();
            record.registrar_iana_id = registrar
                .public_id("IANA Registrar ID")
                .map(str::to_string)
                .or_else(|| registrar.handle.clone());

            let card = registrar.card();
            record.registrar_url = card
                .get("url")
                .map(str::to_string)
                .or_else(|| card.get("fburl").map(str::to_string));

            // Registrars nest their abuse contact rather than putting it on
            // themselves, which is why this searches recursively.
            if let Some(abuse) = registrar.find_role("abuse") {
                let abuse_card = abuse.card();
                record.abuse_contact_email = abuse_card.email().map(str::to_string);
                record.abuse_contact_phone = abuse_card.phone().map(strip_tel_uri);
            }
        }

        for (role, slot) in [
            ("registrant", &mut record.registrant),
            ("administrative", &mut record.admin),
            ("technical", &mut record.tech),
            ("billing", &mut record.billing),
        ] {
            if let Some(entity) = response.entity_with_role(role) {
                let contact = contact_from(entity);
                if !contact.is_empty() {
                    *slot = Some(contact);
                }
            }
        }

        record
    }
}

impl RecordParser for RdapParser {
    fn name(&self) -> &'static str {
        "rdap"
    }

    fn can_parse(&self, response: &RawResponse) -> bool {
        response.kind() == ResponseKind::RdapJson
    }

    fn parse(&self, response: &RawResponse) -> Result<WhoisRecord> {
        let parsed = RdapResponse::parse(response.text()).map_err(|source| Error::Rdap {
            url: response.endpoint().address(),
            source,
        })?;
        Ok(self.map(&parsed))
    }
}

/// Build a contact from an entity's jCard.
fn contact_from(entity: &RdapEntity) -> Contact {
    let card = entity.card();

    Contact {
        handle: entity.handle.clone(),
        name: card.formatted_name().map(str::to_string),
        organization: card.organization().map(str::to_string),
        street: street_lines(&card),
        city: card.address_part(3),
        state: card.address_part(4),
        postal_code: card.address_part(5),
        country: card.address_part(6).map(|code| code.to_uppercase()),
        phone: card.phone().map(strip_tel_uri),
        fax: fax_number(&card),
        email: card.email().map(str::to_string),
    }
}

/// The street components of an address: the extended address and the street
/// itself, in RFC 6350 positions 1 and 2.
fn street_lines(card: &JCard) -> Vec<String> {
    [card.address_part(1), card.address_part(2)]
        .into_iter()
        .flatten()
        .collect()
}

/// A `tel` property whose type marks it as a fax number.
///
/// jCard puts the distinction in the parameters object, which [`JCard`] flattens
/// away, so the best available signal is a second `tel` value.
fn fax_number(card: &JCard) -> Option<String> {
    let numbers = card.get_all("tel");
    numbers.get(1).map(|number| strip_tel_uri(number))
}

/// `tel:+1.5555555555` is a URI; a record should carry the number.
fn strip_tel_uri(value: &str) -> String {
    value
        .strip_prefix("tel:")
        .unwrap_or(value)
        .trim()
        .to_string()
}

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

    const FULL: &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": [
            {"ldhName": "B.IANA-SERVERS.NET"},
            {"ldhName": "A.IANA-SERVERS.NET."}
        ],
        "secureDNS": {"delegationSigned": false},
        "entities": [
            {
                "handle": "376",
                "roles": ["registrar"],
                "publicIds": [{"type": "IANA Registrar ID", "identifier": "376"}],
                "vcardArray": ["vcard", [
                    ["fn", {}, "text", "Example Registrar, LLC"],
                    ["url", {}, "uri", "https://www.example-registrar.com"]
                ]],
                "entities": [{
                    "roles": ["abuse"],
                    "vcardArray": ["vcard", [
                        ["email", {}, "text", "abuse@example-registrar.com"],
                        ["tel", {}, "uri", "tel:+1.5555555555"]
                    ]]
                }]
            },
            {
                "handle": "EX123",
                "roles": ["registrant"],
                "vcardArray": ["vcard", [
                    ["fn", {}, "text", "Ada Lovelace"],
                    ["org", {}, "text", "Example Ltd"],
                    ["adr", {}, "text", ["", "Flat 1", "1 Example Street", "London", "Greater London", "EC1A 1AA", "gb"]],
                    ["email", {}, "text", "ada@example.com"],
                    ["tel", {}, "uri", "tel:+44.2000000000"],
                    ["tel", {}, "uri", "tel:+44.2000000001"]
                ]]
            },
            {
                "roles": ["administrative"],
                "vcardArray": ["vcard", [["fn", {}, "text", "REDACTED FOR PRIVACY"]]]
            }
        ]
    }"#;

    fn parse(json: &str) -> WhoisRecord {
        RdapParser::new().parse_json(json).unwrap()
    }

    #[test]
    fn maps_a_full_domain_object() {
        let record = parse(FULL);

        assert_eq!(record.domain.as_ref().unwrap().as_ascii(), "example.com");
        assert_eq!(
            record.registry_id.as_deref(),
            Some("2336799_DOMAIN_COM-VRSN")
        );
        assert_eq!(record.dnssec, Some(false));
        assert_eq!(
            record.statuses,
            ["client delete prohibited", "client transfer prohibited"],
            "statuses must be lower-cased"
        );
        assert!(record.is_transfer_locked());
    }

    #[test]
    fn maps_events_onto_the_record_dates() {
        let record = parse(FULL);

        assert_eq!(
            record.created.unwrap().format("%Y-%m-%d").to_string(),
            "1995-08-14"
        );
        assert_eq!(
            record.expires.unwrap().format("%Y-%m-%d").to_string(),
            "2027-08-13"
        );
        assert_eq!(
            record.updated.unwrap().format("%Y-%m-%d").to_string(),
            "2026-08-14"
        );
    }

    #[test]
    fn name_servers_are_normalised_and_sorted() {
        let record = parse(FULL);
        assert_eq!(
            record.name_servers,
            ["a.iana-servers.net", "b.iana-servers.net"]
        );
    }

    #[test]
    fn maps_the_registrar_and_its_nested_abuse_contact() {
        let record = parse(FULL);

        assert_eq!(record.registrar.as_deref(), Some("Example Registrar, LLC"));
        assert_eq!(record.registrar_iana_id.as_deref(), Some("376"));
        assert_eq!(
            record.registrar_url.as_deref(),
            Some("https://www.example-registrar.com")
        );
        assert_eq!(
            record.abuse_contact_email.as_deref(),
            Some("abuse@example-registrar.com")
        );
        assert_eq!(
            record.abuse_contact_phone.as_deref(),
            Some("+1.5555555555"),
            "the tel: URI scheme should be stripped"
        );
    }

    #[test]
    fn maps_a_registrant_from_its_jcard() {
        let record = parse(FULL);
        let registrant = record.registrant.as_ref().unwrap();

        assert_eq!(registrant.handle.as_deref(), Some("EX123"));
        assert_eq!(registrant.name.as_deref(), Some("Ada Lovelace"));
        assert_eq!(registrant.organization.as_deref(), Some("Example Ltd"));
        assert_eq!(registrant.street, ["Flat 1", "1 Example Street"]);
        assert_eq!(registrant.city.as_deref(), Some("London"));
        assert_eq!(registrant.state.as_deref(), Some("Greater London"));
        assert_eq!(registrant.postal_code.as_deref(), Some("EC1A 1AA"));
        assert_eq!(registrant.country.as_deref(), Some("GB"));
        assert_eq!(registrant.email.as_deref(), Some("ada@example.com"));
        assert_eq!(registrant.phone.as_deref(), Some("+44.2000000000"));
        assert_eq!(registrant.fax.as_deref(), Some("+44.2000000001"));
    }

    #[test]
    fn redacted_contacts_are_still_mapped_and_flagged() {
        let record = parse(FULL);
        let admin = record.admin.as_ref().unwrap();

        assert!(admin.is_redacted());
        assert_eq!(admin.name.as_deref(), Some("REDACTED FOR PRIVACY"));
    }

    #[test]
    fn an_error_object_maps_to_an_empty_record() {
        let record = parse(r#"{"errorCode":404,"title":"Not Found"}"#);
        assert!(record.is_empty(), "{record:?}");
    }

    #[test]
    fn a_minimal_domain_object_maps_what_it_has() {
        let record = parse(r#"{"objectClassName":"domain","ldhName":"example.com"}"#);

        assert_eq!(record.domain.as_ref().unwrap().as_ascii(), "example.com");
        assert!(record.registrar.is_none());
        assert!(record.statuses.is_empty());
        assert!(!record.is_empty());
    }

    #[test]
    fn a_registrar_without_a_public_id_falls_back_to_its_handle() {
        let record = parse(
            r#"{"objectClassName":"domain","ldhName":"a.com","entities":[
                {"handle":"9999","roles":["registrar"],
                 "vcardArray":["vcard",[["fn",{},"text","Some Registrar"]]]}
            ]}"#,
        );
        assert_eq!(record.registrar_iana_id.as_deref(), Some("9999"));
    }

    #[test]
    fn an_entity_with_an_empty_card_is_not_recorded_as_a_contact() {
        let record = parse(
            r#"{"objectClassName":"domain","ldhName":"a.com","entities":[
                {"roles":["registrant"]}
            ]}"#,
        );
        assert!(record.registrant.is_none());
    }

    #[test]
    fn an_idn_domain_is_stored_in_ascii_form() {
        let record = parse(r#"{"objectClassName":"domain","ldhName":"xn--mnchen-3ya.de"}"#);
        assert_eq!(
            record.domain.as_ref().unwrap().as_ascii(),
            "xn--mnchen-3ya.de"
        );
        assert_eq!(record.domain.as_ref().unwrap().as_unicode(), "münchen.de");
    }

    #[test]
    fn a_unicode_only_name_still_maps() {
        let record = parse(r#"{"objectClassName":"domain","unicodeName":"münchen.de"}"#);
        assert_eq!(
            record.domain.as_ref().unwrap().as_ascii(),
            "xn--mnchen-3ya.de"
        );
    }

    #[test]
    fn non_json_is_an_error_not_an_empty_record() {
        let error = RdapParser::new()
            .parse_json("<html>Gateway Timeout</html>")
            .unwrap_err();
        assert!(matches!(error, Error::Rdap { .. }), "got {error:?}");
    }
}