seer-core 0.54.0

Core library for Seer domain name utilities
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
use super::*;
use crate::output::{availability_label, lookup_source};

impl HumanFormatter {
    pub(super) fn format_lookup(&self, result: &LookupResult) -> String {
        let domain = result
            .domain_name()
            .unwrap_or_else(|| "Unknown".to_string());
        let header_suffix = match result {
            LookupResult::Rdap { .. } => "via RDAP".to_string(),
            LookupResult::Whois { .. } => "via WHOIS".to_string(),
            LookupResult::Available { data, .. } => {
                availability_label(data.verdict()).0.to_lowercase()
            }
        };

        let mut output = vec![self.header(&format!(
            "Lookup: {} ({})",
            sanitize_line(&domain),
            header_suffix
        ))];
        let mut rows = self.rows(&mut output, "  ");
        let source = lookup_source(result);
        let source = match result {
            LookupResult::Rdap { .. } => self.success(source),
            _ => self.warning(source),
        };
        rows.kv("Source", source);

        match result {
            LookupResult::Rdap {
                data,
                whois_fallback,
            } => {
                rows.opt("Registrar", &data.get_registrar());
                rows.opt("Registrant", &data.get_registrant());
                rows.opt("Organization", &data.get_registrant_organization());
                let infos = contact::rdap_contacts(data);
                let rdap_contacts = contact::rdap_detail_views(&infos);
                rows.contacts(rdap_contacts);
                rows.date("Created", data.creation_date());
                rows.expires(data.expiration_date());
                rows.list("Status", &data.status);
                rows.list("Nameservers", &data.nameserver_names());
                if data.is_dnssec_signed() {
                    rows.kv("DNSSEC", self.success("signed"));
                }

                if let Some(whois) = whois_fallback {
                    // Only what RDAP didn't already show.
                    let mut extra = Vec::new();
                    let mut fill = self.rows(&mut extra, "    ");
                    if data.get_registrant().is_none() {
                        fill.opt("Registrant", &whois.registrant);
                    }
                    if data.get_registrant_organization().is_none() {
                        fill.opt("Organization", &whois.organization);
                    }
                    let fallback = contact::ROLES
                        .into_iter()
                        .zip(rdap_contacts)
                        .zip(whois.contacts());
                    for ((role, rdap), whois_contact) in fallback {
                        if rdap.is_empty() {
                            fill.contact(role, whois_contact);
                        }
                    }
                    // RDAP doesn't typically expose an updated date.
                    fill.date("Updated", whois.updated_date);
                    if !data.is_dnssec_signed() {
                        fill.opt("DNSSEC", &whois.dnssec);
                    }
                    if !whois.whois_server.is_empty() {
                        fill.text("WHOIS Server", &whois.whois_server);
                    }

                    if !extra.is_empty() {
                        rows.push(format!("\n  {}", self.label("Additional WHOIS Data:")));
                        rows.extend(extra);
                    }
                }
            }
            LookupResult::Whois {
                data,
                rdap_error,
                dns_nameservers,
                ..
            } => {
                // Error strings can carry upstream server text (e.g. an
                // IANA-returned WHOIS server name), so sanitize like any
                // other remote-sourced value.
                if let Some(error) = rdap_error {
                    rows.kv("RDAP Error", self.error(&sanitize_line(error)));
                }
                rows.opt("Registrar", &data.registrar);
                rows.opt("Registrant", &data.registrant);
                rows.opt("Organization", &data.organization);
                rows.contacts(data.contacts());
                rows.date("Created", data.creation_date);
                rows.expires(data.expiration_date);
                rows.list("Status", &data.status);
                rows.list("Nameservers", &data.nameservers);
                if let Some(dns) = dns_nameservers {
                    if !dns.in_sync {
                        rows.list("Nameservers (DNS)", &dns.delegated);
                    }
                    rows.dns_delegation(dns);
                }
                rows.opt("DNSSEC", &data.dnssec);
            }
            LookupResult::Available {
                data,
                rdap_error,
                whois_error,
                whois_data,
            } => {
                let (verdict, emphasis) = availability_label(data.verdict());
                rows.kv("Verdict", self.emphasize(verdict, emphasis));
                rows.kv("Confidence", self.confidence(&data.confidence));
                rows.text("Method", &data.method);
                rows.opt("Details", &data.details);
                if !rdap_error.is_empty() {
                    rows.kv("RDAP Error", self.error(&sanitize_line(rdap_error)));
                }
                if !whois_error.is_empty() {
                    rows.kv("WHOIS Error", self.error(&sanitize_line(whois_error)));
                }

                if let Some(w) = whois_data {
                    let mut extra = Vec::new();
                    let mut fill = self.rows(&mut extra, "    ");
                    if !w.nameservers.is_empty() {
                        fill.text("Nameservers", &w.nameservers.join(", "));
                    }
                    if !w.status.is_empty() {
                        fill.text("Status", &w.status.join(", "));
                    }
                    fill.opt("DNSSEC", &w.dnssec);
                    if !w.whois_server.is_empty() {
                        fill.text("WHOIS Server", &w.whois_server);
                    }
                    if !extra.is_empty() {
                        rows.push(format!("\n  {}", self.label("Additional WHOIS Data:")));
                        rows.extend(extra);
                    }
                }
            }
        }

        output.join("\n")
    }

    pub(super) fn format_availability(
        &self,
        result: &crate::availability::AvailabilityResult,
    ) -> String {
        let status = if result.available {
            self.success("AVAILABLE")
        } else {
            self.error("TAKEN")
        };
        let mut output = vec![format!("{}: {}", sanitize_line(&result.domain), status)];
        let mut rows = self.rows(&mut output, "  ");
        rows.kv("Confidence", self.confidence(&result.confidence));
        rows.text("Method", &result.method);
        // `details` in `decide_fallback` can interpolate raw `rdap_err` /
        // `whois_err` strings from third-party servers, so it is sanitized
        // like every other remote value.
        rows.opt("Details", &result.details);

        output.join("\n")
    }

    /// Colors an availability confidence purely by certainty, independent of
    /// the registered/available answer.
    fn confidence(&self, confidence: &str) -> String {
        match confidence {
            "high" => self.success(confidence),
            "medium" => self.warning(confidence),
            _ => self.error(confidence),
        }
    }
}

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

    fn formatter() -> HumanFormatter {
        HumanFormatter::new().without_colors()
    }

    fn availability_lookup(available: bool, confidence: &str) -> LookupResult {
        LookupResult::Available {
            data: Box::new(crate::availability::AvailabilityResult {
                domain: "myroyalcanin.lv".to_string(),
                available,
                confidence: confidence.to_string(),
                method: "whois".to_string(),
                details: None,
            }),
            rdap_error: "bootstrap failed".to_string(),
            whois_error: String::new(),
            whois_data: None,
        }
    }

    #[test]
    fn format_lookup_registered_high_confidence_does_not_say_available() {
        // Regression: a `LookupResult::Available` with `available: false` was
        // previously rendered as "AVAILABLE" because the formatter branched on
        // `confidence` alone. See myroyalcanin.lv investigation.
        let f = formatter();
        let out = f.format_lookup(&availability_lookup(false, "high"));
        assert!(
            !out.contains("AVAILABLE"),
            "must not claim available:\n{}",
            out
        );
        assert!(
            out.contains("REGISTERED"),
            "must render REGISTERED:\n{}",
            out
        );
        assert!(
            out.contains("(registered)"),
            "header suffix must say registered:\n{}",
            out
        );
    }

    #[test]
    fn format_lookup_available_high_confidence_still_says_available() {
        let f = formatter();
        let out = f.format_lookup(&availability_lookup(true, "high"));
        assert!(
            out.contains("AVAILABLE"),
            "high-confidence available:\n{}",
            out
        );
        assert!(out.contains("(available)"), "header suffix:\n{}", out);
    }

    #[test]
    fn format_lookup_likely_registered_medium_confidence() {
        let f = formatter();
        let out = f.format_lookup(&availability_lookup(false, "medium"));
        assert!(out.contains("LIKELY REGISTERED"), "medium reg:\n{}", out);
        assert!(
            !out.contains("MAY BE AVAILABLE"),
            "must not say MAY BE AVAILABLE:\n{}",
            out
        );
    }

    #[test]
    fn format_lookup_sanitizes_protocol_error_strings() {
        // rdap_error / whois_error can carry upstream server text (e.g. an
        // IANA-returned WHOIS server name); they were printed raw while every
        // adjacent value went through sanitize_line.
        let evil = "connect to whois.evil\x1b]52;c;AAAA\x07\x1b[2J failed";
        let whois = WhoisResponse::parse("example.com", "whois.test", "Registrar: R\n");
        let whois_variant = LookupResult::Whois {
            data: whois,
            rdap_error: Some(evil.to_string()),
            rdap_fallback: None,
            dns_nameservers: None,
        };
        let available_variant = LookupResult::Available {
            data: Box::new(crate::availability::AvailabilityResult {
                domain: "example.com".to_string(),
                available: false,
                confidence: "low".to_string(),
                method: "none".to_string(),
                details: None,
            }),
            rdap_error: evil.to_string(),
            whois_error: evil.to_string(),
            whois_data: None,
        };
        for result in [whois_variant, available_variant] {
            let out = formatter().format_lookup(&result);
            assert!(!out.contains('\x1b'), "ESC reached terminal: {out:?}");
            assert!(!out.contains('\x07'), "BEL reached terminal: {out:?}");
            assert!(
                out.contains("connect to whois.evil failed"),
                "error text kept: {out:?}"
            );
        }
    }

    #[test]
    fn format_lookup_whois_fallback_keeps_organization_only_contacts() {
        // The WHOIS-fallback admin/tech gate ignored the organization field,
        // so a contact carrying only an organization (common once a registry
        // redacts the personal fields) vanished from `seer lookup` while
        // `seer whois` showed it.
        let mut whois = WhoisResponse::parse("example.com", "whois.test", "Registrar: R\n");
        whois.admin_organization = Some("Admin Org LLC".to_string());
        whois.tech_organization = Some("Tech Org LLC".to_string());
        let rdap: RdapResponse =
            serde_json::from_value(serde_json::json!({"ldhName": "example.com"})).unwrap();
        let result = LookupResult::Rdap {
            data: Box::new(rdap),
            whois_fallback: Some(whois),
        };
        let out = formatter().format_lookup(&result);
        for needle in [
            "Admin Contact",
            "Admin Org LLC",
            "Tech Contact",
            "Tech Org LLC",
        ] {
            assert!(out.contains(needle), "missing {needle:?}:\n{out}");
        }
    }

    /// RDAP whose registrant entity carries only a name and organization.
    fn rdap_registrant_identity_only() -> RdapResponse {
        serde_json::from_value(serde_json::json!({
            "ldhName": "example.com",
            "entities": [{
                "objectClassName": "entity",
                "roles": ["registrant"],
                "vcardArray": ["vcard", [
                    ["fn", {}, "text", "Jane Registrant"],
                    ["org", {}, "text", "Example LLC"]
                ]]
            }]
        }))
        .unwrap()
    }

    #[test]
    fn rdap_registrant_identity_only_opens_no_empty_contact_heading() {
        // has_info() counts name/organization, but the Registrant Contact
        // block renders only email/phone/address/country (name and org are
        // the top-level lines), so this printed a bare heading.
        let out = formatter().format_rdap(&rdap_registrant_identity_only());
        assert!(out.contains("Registrant: Jane Registrant"), "got:\n{out}");
        assert!(
            !out.contains("Registrant Contact"),
            "empty heading rendered:\n{out}"
        );
    }

    #[test]
    fn format_lookup_falls_back_to_whois_registrant_details() {
        // The same identity-only RDAP registrant also counted as "RDAP has
        // registrant details", suppressing the WHOIS fallback's email.
        let mut whois = WhoisResponse::parse("example.com", "whois.test", "Registrar: R\n");
        whois.registrant_email = Some("owner@example.com".to_string());
        let result = LookupResult::Rdap {
            data: Box::new(rdap_registrant_identity_only()),
            whois_fallback: Some(whois),
        };
        let out = formatter().format_lookup(&result);
        assert_eq!(out.matches("Registrant Contact").count(), 1, "got:\n{out}");
        assert!(out.contains("Email: owner@example.com"), "got:\n{out}");
    }

    #[test]
    fn format_lookup_rdap_admin_and_tech_show_postal_details() {
        // The lookup view rendered RDAP admin/tech contacts with the WHOIS
        // field set (name/org/email/phone) and dropped the address and
        // country that `seer rdap` and markdown lookup both show.
        let entities = ["administrative", "technical"].map(|role| {
            serde_json::json!({
                "objectClassName": "entity",
                "roles": [role],
                "vcardArray": ["vcard", [
                    ["fn", {}, "text", format!("{role} person")],
                    ["adr", {}, "text", ["", "", "1 Main St", "Springfield", "", "", "US"]]
                ]]
            })
        });
        let rdap: RdapResponse = serde_json::from_value(serde_json::json!({
            "ldhName": "example.com",
            "entities": entities,
        }))
        .unwrap();
        let result = LookupResult::Rdap {
            data: Box::new(rdap),
            whois_fallback: None,
        };
        let out = formatter().format_lookup(&result);
        assert_eq!(
            out.matches("Address: 1 Main St, Springfield, US").count(),
            2,
            "got:\n{out}"
        );
        assert_eq!(out.matches("Country: US").count(), 2, "got:\n{out}");
    }

    #[test]
    fn domain_info_verdict_registered_for_high_confidence_unavailable() {
        // Regression: DomainInfo::availability_verdict ignored data.available.
        let lookup = availability_lookup(false, "high");
        let info = crate::domain_info::DomainInfo::from_lookup_result(&lookup);
        assert_eq!(info.availability_verdict.as_deref(), Some("registered"));
    }
}