seer-core 0.57.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
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
//! Markdown output (`--format markdown`). One inherent `format_*` method per
//! report type, split into per-concern submodules; bullets go through the
//! private `Bullets` writer and `code_list`, and DNS record tables through
//! `record_table`, which escape every value so domain data can't inject
//! markdown: `MdSafe` for text, `MdCode` inside a code span and `MdCodeCell`
//! inside a code span in a table cell.

use std::fmt::{self, Write as _};

use chrono::{DateTime, Utc};

use super::OutputFormatter;

// Shared with the per-concern submodules below (each does `use super::*`).
pub(super) use super::contact::{self, Contact, FlatContacts};
pub(super) use super::grouping::render_grouped;
pub(super) use super::{
    days_until, dnssec_depth, expiry_phrase, format_duration, propagation_detail,
    propagation_difference, DNSSEC_NOTE, GEO_NOTE,
};
pub(super) use crate::caa::{CaaPolicy, IssuerCaaMatch};
pub(super) use crate::dns::{DnsRecord, FollowIteration, FollowResult, PropagationResult};
pub(super) use crate::lookup::LookupResult;
pub(super) use crate::rdap::RdapResponse;
pub(super) use crate::status::StatusResponse;
pub(super) use crate::whois::WhoisResponse;

mod audit;
mod delegation;
mod diff;
mod dig;
mod dns;
mod domain_info;
mod lookup;
mod propagation;
mod rdap;
mod security;
mod status;
mod whois;

/// `## title` and the blank line after it.
pub(super) fn heading(title: String) -> Vec<String> {
    vec![title, String::new()]
}

/// Appends a table header row and its delimiter row.
pub(super) fn table_header(out: &mut Vec<String>, columns: &[&str]) {
    out.push(format!("| {} |", columns.join(" | ")));
    out.push(format!("|{}", " --- |".repeat(columns.len())));
}

/// Where escaped text lands, which decides what must be escaped.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Context {
    /// Running text: every Markdown metacharacter that could change
    /// structure is backslash-escaped.
    Text,
    /// Inside a code span outside a table. Backslash escapes are not
    /// processed there (`\<` would print both characters), so only what can
    /// end the span or the line matters.
    Code,
    /// Inside a code span in a GFM table cell. The table splits its row on
    /// `|` before the span is parsed, so a pipe still needs `\|` here.
    CodeCell,
}

/// Writes attacker-controlled WHOIS/RDAP/DNS/SSL text into Markdown for
/// `context`. Whatever the context, ANSI escape sequences, control
/// characters and invisible bidi/zero-width format characters
/// (`is_invisible_format`) are dropped, newlines/CR/tabs and the Unicode
/// line separators collapse to spaces (so the text cannot break out of a
/// table row or start a heading), and backticks become apostrophes (so it
/// cannot close a code span or open one).
///
/// In [`Context::Text`], `\` `[` `]` `<` `>` `|` are backslash-escaped, so a
/// value can't render as a live link, image, autolink or raw HTML (e.g. a
/// registrar of `![x](https://attacker.example/p.png)`), can't add table
/// columns, and can't smuggle in a backslash that would cancel the next
/// escape (`\[Verify\](…)` would otherwise become `\\[Verify\\](…)`, a live
/// link). `(`/`)` are left alone: without a `]` before them they carry no
/// link syntax. In [`Context::CodeCell`] a `|` is written `\|`, and a
/// backslash right before a pipe is doubled too, so the table's own
/// escape pairing still sees an escaped pipe.
fn write_escaped(f: &mut fmt::Formatter<'_>, text: &str, context: Context) -> fmt::Result {
    let mut iter = text.chars().peekable();
    while let Some(c) = iter.next() {
        match c {
            '\x1b' => consume_escape(&mut iter),
            '\n' | '\r' | '\t' | '\u{2028}' | '\u{2029}' => f.write_str(" ")?,
            '`' => f.write_str("'")?,
            '\\' | '[' | ']' | '<' | '>' | '|' if context == Context::Text => {
                f.write_char('\\')?;
                f.write_char(c)?;
            }
            '|' if context == Context::CodeCell => f.write_str("\\|")?,
            '\\' if context == Context::CodeCell && iter.peek() == Some(&'|') => {
                f.write_str("\\\\")?;
            }
            c if c.is_control() || super::is_invisible_format(c) => {}
            c => f.write_char(c)?,
        }
    }
    Ok(())
}

/// `Display` adapter for remote text in running Markdown ([`Context::Text`]).
pub(super) struct MdSafe<'a>(pub &'a str);

impl fmt::Display for MdSafe<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_escaped(f, self.0, Context::Text)
    }
}

/// `Display` adapter for remote text inside a `` `code span` `` outside a
/// table ([`Context::Code`]); the caller writes the backticks.
pub(super) struct MdCode<'a>(pub &'a str);

impl fmt::Display for MdCode<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_escaped(f, self.0, Context::Code)
    }
}

/// `Display` adapter for remote text inside a `` `code span` `` in a table
/// cell ([`Context::CodeCell`]); the caller writes the backticks.
pub(super) struct MdCodeCell<'a>(pub &'a str);

impl fmt::Display for MdCodeCell<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_escaped(f, self.0, Context::CodeCell)
    }
}

/// Maximum chars consumed while scanning for an ANSI escape terminator. A
/// well-formed CSI/OSC/DCS sequence is far shorter; the cap stops a malformed
/// sequence from eating an unbounded run of legitimate text.
const ANSI_SCAN_CAP: usize = 64;

/// Consumes the remainder of an ANSI escape sequence after the leading ESC has
/// already been read, given a peekable char iterator positioned at the
/// introducer.
///
/// Critically, the introducer is only consumed when it is *actually* one — a
/// lone/truncated ESC (e.g. `ESC` then `X` or `|`) drops only the ESC and
/// leaves the following character for normal escaping, instead of swallowing
/// it. Scans also bail on a newline/CR so a terminator-less sequence can't eat
/// across a line.
fn consume_escape(iter: &mut std::iter::Peekable<std::str::Chars<'_>>) {
    match iter.peek() {
        // CSI: `ESC [` … final byte in `@`-`~` (0x40-0x7E).
        Some('[') => {
            iter.next(); // consume '['
            for _ in 0..ANSI_SCAN_CAP {
                match iter.peek() {
                    // Bail before consuming a newline/CR — it's layout, not
                    // part of the (malformed, unterminated) sequence.
                    Some('\n') | Some('\r') | None => break,
                    Some(&ch) => {
                        iter.next();
                        if matches!(ch as u32, 0x40..=0x7E) {
                            break;
                        }
                    }
                }
            }
        }
        // String-type sequences: OSC (`ESC ]`) and DCS (`ESC P`). Both run
        // until BEL (0x07) or ST (`ESC \\`).
        Some(']') | Some('P') => {
            iter.next(); // consume introducer
            for _ in 0..ANSI_SCAN_CAP {
                match iter.peek() {
                    Some('\n') | Some('\r') | None => break,
                    Some('\x07') => {
                        iter.next();
                        break;
                    }
                    Some('\x1b') => {
                        // Possible ST: consume ESC, then `\\` if present.
                        iter.next();
                        if iter.peek() == Some(&'\\') {
                            iter.next();
                        }
                        break;
                    }
                    Some(_) => {
                        iter.next();
                    }
                }
            }
        }
        // Charset-designation escapes: `ESC ( <id>` / `ESC ) <id>` and the
        // 96-char variants `ESC * <id>` / `ESC + <id>`. Consume the introducer
        // plus exactly the one designator char (never a newline).
        Some('(') | Some(')') | Some('*') | Some('+') => {
            iter.next(); // consume introducer
            if !matches!(iter.peek(), Some('\n') | Some('\r') | None) {
                iter.next();
            }
        }
        // Not a recognized introducer (lone/truncated ESC). Drop only the ESC;
        // leave the next char to be escaped normally by the main loop.
        _ => {}
    }
}

/// Markdown output formatter that produces clean, readable Markdown.
#[derive(Default)]
pub struct MarkdownFormatter;

impl MarkdownFormatter {
    pub fn new() -> Self {
        Self
    }

    /// Renders the CAA policy as a `### CAA Policy` section shared between
    /// SSL and status reports.
    fn render_caa_section(&self, caa: &CaaPolicy) -> Vec<String> {
        let mut out = vec![String::new(), "### CAA Policy".to_string(), String::new()];
        caa_body(&mut out, caa);
        out.extend([String::new(), format!("> **Note:** {}", caa.note)]);
        out
    }
}

/// The body of a CAA section: where the policy was found, its records as a
/// table, and how the certificate's issuer compares to it.
fn caa_body(out: &mut Vec<String>, caa: &CaaPolicy) {
    if !caa.has_policy {
        out.push("*No CAA records (any CA may issue)*".to_string());
    } else {
        Bullets(out).code_opt("Found at", &caa.effective_domain);
        out.push(String::new());
        out.push("| Flags | Tag | Value |".to_string());
        out.push("| --- | --- | --- |".to_string());
        for r in &caa.records {
            out.push(format!(
                "| {} | `{}` | `{}` |",
                r.flags,
                MdCodeCell(&r.tag),
                MdCodeCell(&r.value)
            ));
        }
    }

    if let Some(m) = caa.issuer_match {
        let rendered = match m {
            IssuerCaaMatch::NoPolicy => "no policy — any CA permitted",
            IssuerCaaMatch::Permitted => "issuer permitted by current CAA policy",
            IssuerCaaMatch::Mismatch => "issuer not in current CAA policy (informational)",
            IssuerCaaMatch::Indeterminate => "CAA present but no issue/issuewild tags",
        };
        out.push(String::new());
        Bullets(out).raw("Issuer vs CAA", rendered);
    }
}

/// `` `a`, `b` ``: each item in its own [`MdCode`] code span, joined by a
/// plain `, ` (the separator's backticks must never pass through the
/// escaper, which would turn them into apostrophes).
fn code_list<S: AsRef<str>>(items: &[S]) -> String {
    items
        .iter()
        .map(|item| format!("`{}`", MdCode(item.as_ref())))
        .collect::<Vec<_>>()
        .join(", ")
}

/// [`code_list`] for a table cell: each span escaped with [`MdCodeCell`].
fn code_cells<S: AsRef<str>>(items: &[S]) -> String {
    items
        .iter()
        .map(|item| format!("`{}`", MdCodeCell(item.as_ref())))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Appends a `| Name | TTL | Type | Data |` table, one row per record, with
/// the owner name and the data (remote text) in [`MdCodeCell`] code spans.
fn record_table<'r>(out: &mut Vec<String>, records: impl IntoIterator<Item = &'r DnsRecord>) {
    out.push("| Name | TTL | Type | Data |".to_string());
    out.push("| --- | --- | --- | --- |".to_string());
    for record in records {
        out.push(format!(
            "| `{}` | {} | {} | `{}` |",
            MdCodeCell(&record.name),
            record.ttl,
            record.record_type,
            MdCodeCell(&record.data.to_string())
        ));
    }
}

/// `` `YYYY-MM-DD` (expires in N days) `` — see [`expiry_phrase`].
fn expiry(date: DateTime<Utc>, days_until: i64) -> String {
    format!(
        "`{}` ({})",
        date.format("%Y-%m-%d"),
        expiry_phrase(days_until)
    )
}

/// Appends `- **Label**: value` bullets. Remote values go through [`MdSafe`]
/// (or [`MdCode`] in a code span) here, so no bullet can skip the
/// Markdown-injection guard.
struct Bullets<'a>(&'a mut Vec<String>);

impl Bullets<'_> {
    /// Appends a pre-built line as-is.
    fn push(&mut self, line: String) {
        self.0.push(line);
    }

    /// `- **label**: value` for a value the caller already rendered safely.
    fn raw(&mut self, label: &str, value: impl fmt::Display) {
        self.0.push(format!("- **{label}**: {value}"));
    }

    /// `- **label**: value` for remote text.
    fn text(&mut self, label: &str, value: &str) {
        self.raw(label, MdSafe(value));
    }

    /// [`Self::text`], skipped when the field is absent.
    fn opt(&mut self, label: &str, value: &Option<String>) {
        if let Some(value) = value {
            self.text(label, value);
        }
    }

    /// `` - **label**: `value` `` for remote text shown as a code span.
    fn code(&mut self, label: &str, value: &str) {
        self.0.push(format!("- **{label}**: `{}`", MdCode(value)));
    }

    /// [`Self::code`], skipped when the field is absent.
    fn code_opt(&mut self, label: &str, value: &Option<String>) {
        if let Some(value) = value {
            self.code(label, value);
        }
    }

    /// `` - **label**: `a`, `b` `` (see [`code_list`]); nothing when empty.
    fn code_list(&mut self, label: &str, items: &[String]) {
        if !items.is_empty() {
            self.raw(label, code_list(items));
        }
    }

    /// `` - **label**: `YYYY-MM-DD` ``, skipped when absent.
    fn date(&mut self, label: &str, date: Option<DateTime<Utc>>) {
        if let Some(date) = date {
            self.0
                .push(format!("- **{label}**: `{}`", date.format("%Y-%m-%d")));
        }
    }

    /// `` - **Expires**: `YYYY-MM-DD` (expires in N days) `` (see
    /// [`expiry`]), skipped when absent.
    fn expires(&mut self, date: Option<DateTime<Utc>>) {
        if let Some(date) = date {
            self.raw("Expires", expiry(date, days_until(date)));
        }
    }

    /// One `### <role> Contact` subsection with a bullet per populated
    /// field (the email as a code span); nothing for an empty contact.
    ///
    /// Push these only *after* every domain-level bullet: a `###` heading
    /// scopes everything below it, so a Created/Expires/Nameservers bullet
    /// emitted after a contact section renders as part of that contact.
    fn contact(&mut self, role: &str, c: Contact<'_>) {
        if c.is_empty() {
            return;
        }
        self.0
            .extend([String::new(), format!("### {role} Contact"), String::new()]);
        for (label, field) in c.fields() {
            match label {
                "Email" => self.code_opt(label, field),
                _ => self.opt(label, field),
            }
        }
    }

    /// [`Self::contact`] for each of [`contact::ROLES`].
    fn contacts(&mut self, contacts: [Contact<'_>; 3]) {
        for (role, c) in contact::ROLES.into_iter().zip(contacts) {
            self.contact(role, c);
        }
    }
}

with_report_methods!(impl_forwarding!(MarkdownFormatter;));

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

    // --- MdSafe sanitization tests -----------------------------------------

    fn md(s: &str) -> String {
        format!("{}", MdSafe(s))
    }

    #[test]
    fn test_mdsafe_strips_ansi_escape() {
        assert_eq!(md("\x1b[31mfoo\x1b[0m"), "foo");
    }

    #[test]
    fn test_mdsafe_collapses_newlines_cr_tab() {
        assert_eq!(md("a\nb"), "a b");
        assert_eq!(md("a\rb"), "a b");
        assert_eq!(md("a\tb"), "a b");
        // CRLF becomes two spaces (each replaced individually); that's fine —
        // the goal is to prevent breaking the line, not perfect whitespace.
        assert_eq!(md("a\r\nb"), "a  b");
    }

    #[test]
    fn test_mdsafe_neutralizes_backticks() {
        assert_eq!(md("`bad`"), "'bad'");
        assert_eq!(md("a `b` c"), "a 'b' c");
    }

    #[test]
    fn test_mdsafe_escapes_table_pipe() {
        // A bare `|` from attacker-controlled data (DNS TXT, cert subject,
        // WHOIS contact) breaks out of a Markdown table cell / fabricates
        // columns. GFM's cell escape is backslash-pipe, a literal `|` both
        // inside and outside tables.
        assert_eq!(md("a|b"), "a\\|b");
        assert_eq!(md("x | y | z"), "x \\| y \\| z");
    }

    #[test]
    fn test_mdsafe_drops_other_control_chars() {
        // NUL and DEL must vanish entirely.
        assert_eq!(md("a\0b\x7fc"), "abc");
    }

    #[test]
    fn test_mdsafe_preserves_unicode() {
        assert_eq!(md("café — résumé"), "café — résumé");
    }

    #[test]
    fn test_mdsafe_lone_esc_does_not_swallow_following_text() {
        // A bare ESC not followed by a real ANSI introducer must drop only the
        // ESC, not the following characters. `X` is not a CSI/OSC introducer, so
        // "hello" must survive — and the `|` is still escaped for table safety.
        assert_eq!(md("\x1bXhello|world"), "Xhello\\|world");
    }

    #[test]
    fn test_mdsafe_truncated_escape_does_not_swallow_newline_or_text() {
        // ESC + introducer `[` with no terminator before a newline: the scan
        // must bail at the newline (re-emitting it as a space) rather than
        // consuming "Ignore" while hunting for a terminator that never comes.
        assert_eq!(md("\x1b[\nIgnore"), " Ignore");
    }

    #[test]
    fn test_mdsafe_still_strips_wellformed_ansi() {
        // Regression: a complete CSI color sequence is still fully removed.
        assert_eq!(md("\x1b[31mfoo\x1b[0m"), "foo");
        // OSC terminated by BEL is still removed.
        assert_eq!(md("\x1b]0;title\x07rest"), "rest");
    }

    #[test]
    fn test_mdsafe_esc_then_pipe_still_escapes_pipe() {
        // After dropping a lone ESC, a following structural `|` must still be
        // escaped — the ANSI handling must not bypass the table-cell defense.
        assert_eq!(md("\x1b|col"), "\\|col");
    }

    #[test]
    fn test_mdsafe_neutralizes_links_images_and_html() {
        // Attacker-controlled WHOIS/RDAP text must not render as a live image
        // (tracking pixel), link (phishing), autolink, or raw HTML wherever
        // the markdown is rendered.
        assert_eq!(
            md("![x](https://attacker.example/p.png)"),
            "!\\[x\\](https://attacker.example/p.png)"
        );
        assert_eq!(
            md("[Verify](https://phish.example)"),
            "\\[Verify\\](https://phish.example)"
        );
        assert_eq!(
            md("<img src=https://attacker.example/p.png>"),
            "\\<img src=https://attacker.example/p.png\\>"
        );
        assert_eq!(md("<https://phish.example>"), "\\<https://phish.example\\>");
        // Parentheses alone carry no link syntax and stay unescaped.
        assert_eq!(md("Example (Holdings) LLC"), "Example (Holdings) LLC");
    }

    #[test]
    fn test_mdsafe_escapes_backslash_so_it_cannot_cancel_an_escape() {
        // A value that pre-escapes its own brackets used to come out as
        // `\\[Verify\\](…)`: each `\\` renders one backslash and the brackets
        // are live again, i.e. a clickable phishing link.
        assert_eq!(
            md("\\[Verify\\](https://phish.example)"),
            "\\\\\\[Verify\\\\\\](https://phish.example)"
        );
        // Same for a pre-escaped pipe (would add a table column) and `<`.
        assert_eq!(md("a\\|b"), "a\\\\\\|b");
        assert_eq!(md("\\<img>"), "\\\\\\<img\\>");
        assert_eq!(md("C:\\path"), "C:\\\\path");
    }

    fn code(s: &str) -> String {
        format!("{}", MdCode(s))
    }

    /// The one line `write` appends through a [`Bullets`] writer.
    fn bullet(write: impl FnOnce(&mut Bullets<'_>)) -> String {
        let mut out = Vec::new();
        write(&mut Bullets(&mut out));
        assert_eq!(out.len(), 1, "{out:?}");
        out.remove(0)
    }

    fn cell(s: &str) -> String {
        format!("{}", MdCodeCell(s))
    }

    #[test]
    fn code_spans_are_not_backslash_escaped() {
        // Backslash escapes are not processed inside a code span, so the
        // text-context escaping printed `CN=\<x\>` for a subject `CN=<x>`.
        assert_eq!(code("CN=<x>"), "CN=<x>");
        assert_eq!(code("[a](b) \\ c|d"), "[a](b) \\ c|d");
        // What could close the span or the line is still neutralized.
        assert_eq!(code("a`b\nc\x1b[31m"), "a'b c");
    }

    #[test]
    fn table_cell_code_spans_escape_pipes() {
        // GFM splits a row on `|` before parsing the span, so a pipe inside
        // a code span in a cell still needs `\|` …
        assert_eq!(cell("a|b"), "a\\|b");
        assert_eq!(cell("CN=<x>"), "CN=<x>");
        // … and a backslash before it is doubled, or the table would pair
        // `\\` and split on the now-bare pipe.
        assert_eq!(cell("a\\|b"), "a\\\\\\|b");
        assert_eq!(cell("a\\b"), "a\\b");
        assert_eq!(
            bullet(|b| b.code("Subject", "CN=<x>")),
            "- **Subject**: `CN=<x>`"
        );
    }

    #[test]
    fn invisible_bidi_and_zero_width_chars_are_dropped() {
        // A right-to-left override can make `moc.evil` read as `live.com`.
        let trojan = "a\u{202E}b\u{2066}c\u{200B}d\u{FEFF}e\u{061C}f\u{200F}g";
        assert_eq!(md(trojan), "abcdefg");
        assert_eq!(code(trojan), "abcdefg");
        assert_eq!(cell(trojan), "abcdefg");
    }

    #[test]
    fn contact_iterates_every_field_with_the_email_as_code() {
        let (name, email, address) = (
            Some("Jane".to_string()),
            Some("jane@example.com".to_string()),
            Some("1 Main St".to_string()),
        );
        let contact = Contact {
            name: &name,
            email: &email,
            address: &address,
            ..Contact::EMPTY
        };
        let mut out = Vec::new();
        Bullets(&mut out).contact("Admin", contact);
        assert_eq!(
            out,
            [
                "",
                "### Admin Contact",
                "",
                "- **Name**: Jane",
                "- **Email**: `jane@example.com`",
                "- **Address**: 1 Main St",
            ]
        );
    }

    #[test]
    fn expires_bullet_says_expired_days_ago() {
        let past = Utc::now() - chrono::Duration::days(3) - chrono::Duration::hours(1);
        let line = bullet(|b| b.expires(Some(past)));
        assert!(line.ends_with("(expired 3 days ago)"), "got: {line}");
        let soon = Utc::now() + chrono::Duration::days(10) + chrono::Duration::hours(1);
        let line = bullet(|b| b.expires(Some(soon)));
        assert!(line.ends_with("(expires in 10 days)"), "got: {line}");
    }

    #[test]
    fn domain_info_renders_registrar_detail_and_lifecycle_fields() {
        // Mirror of the human-formatter regression: the PR #101
        // registrar-detail + derived-lifecycle fields must be visible in
        // `--format markdown`, not just JSON/YAML (2026-07-11 review).
        let whois = WhoisResponse::parse(
            "example.com",
            "whois.test",
            "Registrar: Example Registrar\n\
             Creation Date: 2020-01-01T00:00:00Z\n\
             Registry Expiry Date: 2099-01-01T00:00:00Z\n\
             Domain Status: clientTransferProhibited\n",
        );
        let mut info =
            crate::domain_info::DomainInfo::from_sources("example.com", None, Some(&whois));
        info.registrar_abuse_email = Some("abuse@registrar.test".to_string());
        info.registrar_abuse_phone = Some("+1.5555550100".to_string());
        info.registrar_iana_id = Some("9999".to_string());
        info.registrar_url = Some("https://registrar.test".to_string());

        let out = MarkdownFormatter::new().format_domain_info(&info);
        for needle in [
            "Registrar Detail",
            "abuse@registrar.test",
            "+1.5555550100",
            "9999",
            "https://registrar.test",
            "Days Until Expiry",
            "Domain Age",
            "Expiry Status",
            "clientTransferProhibited",
        ] {
            assert!(out.contains(needle), "missing {needle:?} in:\n{out}");
        }
    }
}