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
//! [`WhoisRecord`]: a registration, as data rather than as prose.

use std::collections::BTreeMap;
use std::fmt;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::domain::DomainName;

/// A parsed registration record.
///
/// Most WHOIS libraries hand back the server's text and leave the caller to
/// find the expiry date in it. That works until it does not: every registry lays
/// its record out differently, and code that greps for `Expiry Date:` breaks the
/// first time it meets a registry that writes `paid-till`.
///
/// Every field is optional, because every field genuinely is. Thin registries
/// publish almost nothing, GDPR redaction removed most contact data from the rest,
/// and a field this crate could not parse is better reported as absent than as
/// wrong. The unrecognised remainder is kept in [`extra`](WhoisRecord::extra) so
/// nothing is silently lost.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct WhoisRecord {
    /// The domain the record is about, as the registry spelled it.
    pub domain: Option<DomainName>,
    /// Registry's internal identifier for the registration.
    pub registry_id: Option<String>,

    /// Sponsoring registrar's name.
    pub registrar: Option<String>,
    /// The registrar's IANA identifier.
    pub registrar_iana_id: Option<String>,
    /// The registrar's own WHOIS server, when the registry names one.
    pub registrar_whois_server: Option<String>,
    /// The registrar's website.
    pub registrar_url: Option<String>,
    /// Where to report abuse.
    pub abuse_contact_email: Option<String>,
    /// Abuse contact telephone number.
    pub abuse_contact_phone: Option<String>,

    /// When the domain was first registered.
    pub created: Option<DateTime<Utc>>,
    /// When the record last changed.
    pub updated: Option<DateTime<Utc>>,
    /// When the registration lapses.
    pub expires: Option<DateTime<Utc>>,

    /// EPP and registry-specific status values, lower-cased.
    pub statuses: Vec<String>,
    /// Authoritative name servers, lower-cased, without trailing dots.
    pub name_servers: Vec<String>,
    /// Whether DNSSEC is signed, when the registry says.
    pub dnssec: Option<bool>,

    /// The registrant, if the registry publishes one.
    pub registrant: Option<Contact>,
    /// The administrative contact.
    pub admin: Option<Contact>,
    /// The technical contact.
    pub tech: Option<Contact>,
    /// The billing contact.
    pub billing: Option<Contact>,

    /// Fields that were parsed as key/value pairs but not recognised.
    ///
    /// Keys are lower-cased and stripped of padding; values keep their original
    /// text. A registry-specific field a caller cares about lives here.
    pub extra: BTreeMap<String, Vec<String>>,
}

impl WhoisRecord {
    /// An empty record.
    pub fn new() -> Self {
        WhoisRecord::default()
    }

    /// Whether nothing at all was parsed.
    ///
    /// True for a "no match" response, and for a record whose format the parser did
    /// not recognise — so it is a signal to look at the raw text, not proof that a
    /// domain is free.
    pub fn is_empty(&self) -> bool {
        self.domain.is_none()
            && self.registrar.is_none()
            && self.created.is_none()
            && self.expires.is_none()
            && self.statuses.is_empty()
            && self.name_servers.is_empty()
            && self.registrant.is_none()
            && self.extra.is_empty()
    }

    /// How many days until the registration lapses, negative once it has.
    ///
    /// `None` when the registry published no expiry date, which is common: most
    /// ccTLDs do not.
    pub fn days_until_expiry(&self) -> Option<i64> {
        self.expires
            .map(|expires| (expires - Utc::now()).num_days())
    }

    /// Whether the expiry date is in the past.
    pub fn is_expired(&self) -> bool {
        self.days_until_expiry().is_some_and(|days| days < 0)
    }

    /// Whether any status value forbids a transfer.
    ///
    /// The question a registrar's transfer flow actually needs to ask, and one that
    /// requires knowing both the EPP spelling and the registry dialects.
    pub fn is_transfer_locked(&self) -> bool {
        self.statuses.iter().any(|status| {
            let status = status.replace([' ', '-', '_'], "");
            status.contains("transferprohibited") || status.contains("locked")
        })
    }

    /// Whether any status value marks the domain as being deleted.
    pub fn is_pending_delete(&self) -> bool {
        self.statuses.iter().any(|status| {
            let status = status.replace([' ', '-', '_'], "");
            status.contains("pendingdelete") || status.contains("redemptionperiod")
        })
    }

    /// The value of an unrecognised field, if it was present.
    pub fn extra_field(&self, key: &str) -> Option<&str> {
        self.extra
            .get(&key.to_lowercase())
            .and_then(|values| values.first())
            .map(String::as_str)
    }
}

impl fmt::Display for WhoisRecord {
    /// A compact, stable summary. Not the registry's format, and not meant to be
    /// parsed back.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut lines: Vec<String> = Vec::new();

        if let Some(domain) = &self.domain {
            lines.push(format!("domain: {}", domain.as_ascii()));
        }
        if let Some(registrar) = &self.registrar {
            lines.push(format!("registrar: {registrar}"));
        }
        for (label, value) in [
            ("created", self.created),
            ("updated", self.updated),
            ("expires", self.expires),
        ] {
            if let Some(when) = value {
                lines.push(format!("{label}: {}", when.format("%Y-%m-%d")));
            }
        }
        if !self.statuses.is_empty() {
            lines.push(format!("status: {}", self.statuses.join(", ")));
        }
        if !self.name_servers.is_empty() {
            lines.push(format!("nameservers: {}", self.name_servers.join(", ")));
        }

        f.write_str(&lines.join("\n"))
    }
}

/// A contact on a registration.
///
/// Mostly redacted in practice. Kept as a struct rather than a string so that the
/// fields a registry does publish are usable without re-parsing.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Contact {
    /// Registry or registrar handle for the contact.
    pub handle: Option<String>,
    /// Personal or role name.
    pub name: Option<String>,
    /// Organisation.
    pub organization: Option<String>,
    /// Street address lines.
    pub street: Vec<String>,
    /// City.
    pub city: Option<String>,
    /// State or province.
    pub state: Option<String>,
    /// Postal code.
    pub postal_code: Option<String>,
    /// Two-letter country code, upper-cased.
    pub country: Option<String>,
    /// Telephone number.
    pub phone: Option<String>,
    /// Fax number.
    pub fax: Option<String>,
    /// Email address, or the redaction notice the registry substituted.
    pub email: Option<String>,
}

impl Contact {
    /// Whether no field was populated.
    pub fn is_empty(&self) -> bool {
        self.handle.is_none()
            && self.name.is_none()
            && self.organization.is_none()
            && self.street.is_empty()
            && self.city.is_none()
            && self.state.is_none()
            && self.postal_code.is_none()
            && self.country.is_none()
            && self.phone.is_none()
            && self.fax.is_none()
            && self.email.is_none()
    }

    /// Whether the contact data looks redacted rather than absent.
    ///
    /// Since GDPR most registries substitute a notice — "REDACTED FOR PRIVACY",
    /// "Data Protected", a proxy address — and telling that apart from a registry
    /// that never published contacts is worth doing.
    pub fn is_redacted(&self) -> bool {
        const MARKERS: [&str; 8] = [
            "redacted",
            "not disclosed",
            "data protected",
            "privacy",
            "gdpr",
            "withheld",
            "statutory masking",
            "non-public data",
        ];

        [
            self.name.as_deref(),
            self.organization.as_deref(),
            self.email.as_deref(),
        ]
        .into_iter()
        .flatten()
        .any(|value| {
            let value = value.to_lowercase();
            MARKERS.iter().any(|marker| value.contains(marker))
        })
    }

    /// The most useful single line for display.
    pub fn display_name(&self) -> Option<&str> {
        self.name
            .as_deref()
            .or(self.organization.as_deref())
            .or(self.handle.as_deref())
    }
}

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

    fn at(year: i32, month: u32, day: u32) -> DateTime<Utc> {
        Utc.with_ymd_and_hms(year, month, day, 0, 0, 0).unwrap()
    }

    #[test]
    fn a_new_record_is_empty() {
        assert!(WhoisRecord::new().is_empty());
    }

    #[test]
    fn one_populated_field_makes_it_non_empty() {
        let record = WhoisRecord {
            registrar: Some("Example LLC".into()),
            ..WhoisRecord::default()
        };
        assert!(!record.is_empty());
    }

    #[test]
    fn expiry_is_measured_in_days_either_side_of_now() {
        let future = WhoisRecord {
            expires: Some(Utc::now() + chrono::Duration::days(30)),
            ..WhoisRecord::default()
        };
        assert!(!future.is_expired());
        assert!((29..=30).contains(&future.days_until_expiry().unwrap()));

        let past = WhoisRecord {
            expires: Some(Utc::now() - chrono::Duration::days(5)),
            ..WhoisRecord::default()
        };
        assert!(past.is_expired());
        assert!(past.days_until_expiry().unwrap() < 0);

        assert!(!WhoisRecord::new().is_expired());
        assert!(WhoisRecord::new().days_until_expiry().is_none());
    }

    #[test]
    fn transfer_locks_are_recognised_in_every_spelling() {
        for status in [
            "clientTransferProhibited",
            "client transfer prohibited",
            "CLIENT-TRANSFER-PROHIBITED",
            "serverTransferProhibited",
            "REGISTRAR-LOCKED",
        ] {
            let record = WhoisRecord {
                statuses: vec![status.to_lowercase()],
                ..WhoisRecord::default()
            };
            assert!(record.is_transfer_locked(), "missed {status:?}");
        }

        let ok = WhoisRecord {
            statuses: vec!["ok".into()],
            ..WhoisRecord::default()
        };
        assert!(!ok.is_transfer_locked());
    }

    #[test]
    fn deletion_states_are_recognised() {
        for status in ["pendingDelete", "redemptionPeriod", "pending delete"] {
            let record = WhoisRecord {
                statuses: vec![status.to_lowercase()],
                ..WhoisRecord::default()
            };
            assert!(record.is_pending_delete(), "missed {status:?}");
        }
    }

    #[test]
    fn unrecognised_fields_are_reachable() {
        let mut extra = BTreeMap::new();
        extra.insert("eligibility type".to_string(), vec!["Company".to_string()]);
        let record = WhoisRecord {
            extra,
            ..WhoisRecord::default()
        };

        assert_eq!(record.extra_field("Eligibility Type"), Some("Company"));
        assert_eq!(record.extra_field("absent"), None);
        assert!(!record.is_empty());
    }

    #[test]
    fn redaction_is_told_apart_from_absence() {
        let redacted = Contact {
            name: Some("REDACTED FOR PRIVACY".into()),
            ..Contact::default()
        };
        assert!(redacted.is_redacted());
        assert!(!redacted.is_empty());

        let real = Contact {
            name: Some("Ada Lovelace".into()),
            ..Contact::default()
        };
        assert!(!real.is_redacted());

        // Nothing published at all is not the same as redaction.
        assert!(!Contact::default().is_redacted());
        assert!(Contact::default().is_empty());
    }

    #[test]
    fn display_name_falls_back_through_the_useful_fields() {
        let organization = Contact {
            organization: Some("Example Ltd".into()),
            ..Contact::default()
        };
        assert_eq!(organization.display_name(), Some("Example Ltd"));

        let handle = Contact {
            handle: Some("EX123".into()),
            ..Contact::default()
        };
        assert_eq!(handle.display_name(), Some("EX123"));
        assert_eq!(Contact::default().display_name(), None);
    }

    #[test]
    fn display_is_compact_and_skips_absent_fields() {
        let record = WhoisRecord {
            domain: Some(DomainName::parse("example.com").unwrap()),
            registrar: Some("Example LLC".into()),
            expires: Some(at(2027, 3, 14)),
            statuses: vec!["ok".into()],
            ..WhoisRecord::default()
        };

        let rendered = record.to_string();
        assert!(rendered.contains("domain: example.com"), "{rendered}");
        assert!(rendered.contains("expires: 2027-03-14"), "{rendered}");
        assert!(!rendered.contains("created"), "{rendered}");
        assert!(!rendered.contains("nameservers"), "{rendered}");
    }

    #[test]
    fn round_trips_through_json() {
        let record = WhoisRecord {
            domain: Some(DomainName::parse("example.com").unwrap()),
            created: Some(at(2001, 1, 1)),
            statuses: vec!["ok".into()],
            name_servers: vec!["ns1.example.com".into()],
            dnssec: Some(false),
            ..WhoisRecord::default()
        };

        let json = serde_json::to_string(&record).unwrap();
        assert_eq!(serde_json::from_str::<WhoisRecord>(&json).unwrap(), record);
    }
}