seer-core 0.48.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
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;

use crate::error::{Result, SeerError};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RecordType {
    A,
    AAAA,
    CNAME,
    MX,
    NS,
    TXT,
    SOA,
    PTR,
    SRV,
    CAA,
    NAPTR,
    DNSKEY,
    DS,
    TLSA,
    SSHFP,
    ANY,
}

impl RecordType {
    /// Every queryable record type, in the canonical order the CLI help,
    /// REPL tab-completion, and the MCP tool schema all present.
    ///
    /// Single source of truth: those surfaces used to hand-mirror this list
    /// and two of the three had drifted (NAPTR/TLSA/SSHFP were missing from
    /// the REPL completer and the MCP schema, so the types were queryable but
    /// undiscoverable). Render from this — never re-type the list.
    pub const ALL: &'static [RecordType] = &[
        RecordType::A,
        RecordType::AAAA,
        RecordType::CNAME,
        RecordType::MX,
        RecordType::NS,
        RecordType::TXT,
        RecordType::SOA,
        RecordType::PTR,
        RecordType::SRV,
        RecordType::CAA,
        RecordType::NAPTR,
        RecordType::DNSKEY,
        RecordType::DS,
        RecordType::TLSA,
        RecordType::SSHFP,
        RecordType::ANY,
    ];

    /// The same list as `&'static str` names, for surfaces that need string
    /// slices directly (completion candidates, help text, JSON schemas).
    pub const ALL_NAMES: &'static [&'static str] = &[
        "A", "AAAA", "CNAME", "MX", "NS", "TXT", "SOA", "PTR", "SRV", "CAA", "NAPTR", "DNSKEY",
        "DS", "TLSA", "SSHFP", "ANY",
    ];

    /// The canonical uppercase name. Exhaustive match, so adding a variant
    /// fails to compile here first — the prompt to also extend [`Self::ALL`].
    pub const fn as_str(&self) -> &'static str {
        match self {
            RecordType::A => "A",
            RecordType::AAAA => "AAAA",
            RecordType::CNAME => "CNAME",
            RecordType::MX => "MX",
            RecordType::NS => "NS",
            RecordType::TXT => "TXT",
            RecordType::SOA => "SOA",
            RecordType::PTR => "PTR",
            RecordType::SRV => "SRV",
            RecordType::CAA => "CAA",
            RecordType::NAPTR => "NAPTR",
            RecordType::DNSKEY => "DNSKEY",
            RecordType::DS => "DS",
            RecordType::TLSA => "TLSA",
            RecordType::SSHFP => "SSHFP",
            RecordType::ANY => "ANY",
        }
    }
}

impl fmt::Display for RecordType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for RecordType {
    type Err = SeerError;

    fn from_str(s: &str) -> Result<Self> {
        match s.to_uppercase().as_str() {
            "A" => Ok(RecordType::A),
            "AAAA" => Ok(RecordType::AAAA),
            "CNAME" => Ok(RecordType::CNAME),
            "MX" => Ok(RecordType::MX),
            "NS" => Ok(RecordType::NS),
            "TXT" => Ok(RecordType::TXT),
            "SOA" => Ok(RecordType::SOA),
            "PTR" => Ok(RecordType::PTR),
            "SRV" => Ok(RecordType::SRV),
            "CAA" => Ok(RecordType::CAA),
            "NAPTR" => Ok(RecordType::NAPTR),
            "DNSKEY" => Ok(RecordType::DNSKEY),
            "DS" => Ok(RecordType::DS),
            "TLSA" => Ok(RecordType::TLSA),
            "SSHFP" => Ok(RecordType::SSHFP),
            "ANY" | "*" => Ok(RecordType::ANY),
            _ => Err(SeerError::InvalidRecordType(s.to_string())),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DnsRecord {
    pub name: String,
    pub record_type: RecordType,
    pub ttl: u32,
    pub data: RecordData,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "record_type", content = "value", rename_all = "UPPERCASE")]
#[allow(clippy::upper_case_acronyms)]
pub enum RecordData {
    A {
        address: String,
    },
    AAAA {
        address: String,
    },
    CNAME {
        target: String,
    },
    MX {
        preference: u16,
        exchange: String,
    },
    NS {
        nameserver: String,
    },
    TXT {
        text: String,
    },
    SOA {
        mname: String,
        rname: String,
        serial: u32,
        refresh: u32,
        retry: u32,
        expire: u32,
        minimum: u32,
    },
    PTR {
        target: String,
    },
    SRV {
        priority: u16,
        weight: u16,
        port: u16,
        target: String,
    },
    CAA {
        flags: u8,
        tag: String,
        value: String,
    },
    DNSKEY {
        flags: u16,
        protocol: u8,
        algorithm: u8,
        public_key: String,
    },
    DS {
        key_tag: u16,
        algorithm: u8,
        digest_type: u8,
        digest: String,
    },
    TLSA {
        cert_usage: u8,
        selector: u8,
        matching: u8,
        /// Hex-encoded certificate association data (uppercase).
        cert_data: String,
    },
    SSHFP {
        algorithm: u8,
        fingerprint_type: u8,
        /// Hex-encoded fingerprint (uppercase).
        fingerprint: String,
    },
    NAPTR {
        order: u16,
        preference: u16,
        flags: String,
        services: String,
        regexp: String,
        replacement: String,
    },
    Unknown {
        raw: String,
    },
}

impl fmt::Display for RecordData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RecordData::A { address } => write!(f, "{}", address),
            RecordData::AAAA { address } => write!(f, "{}", address),
            RecordData::CNAME { target } => write!(f, "{}", target),
            RecordData::MX {
                preference,
                exchange,
            } => write!(f, "{} {}", preference, exchange),
            RecordData::NS { nameserver } => write!(f, "{}", nameserver),
            RecordData::TXT { text } => write!(f, "\"{}\"", text),
            RecordData::SOA {
                mname,
                rname,
                serial,
                refresh,
                retry,
                expire,
                minimum,
            } => write!(
                f,
                "{} {} {} {} {} {} {}",
                mname, rname, serial, refresh, retry, expire, minimum
            ),
            RecordData::PTR { target } => write!(f, "{}", target),
            RecordData::SRV {
                priority,
                weight,
                port,
                target,
            } => write!(f, "{} {} {} {}", priority, weight, port, target),
            RecordData::CAA { flags, tag, value } => write!(f, "{} {} \"{}\"", flags, tag, value),
            RecordData::DNSKEY {
                flags,
                protocol,
                algorithm,
                public_key,
            } => write!(f, "{} {} {} {}", flags, protocol, algorithm, public_key),
            RecordData::DS {
                key_tag,
                algorithm,
                digest_type,
                digest,
            } => write!(f, "{} {} {} {}", key_tag, algorithm, digest_type, digest),
            RecordData::TLSA {
                cert_usage,
                selector,
                matching,
                cert_data,
            } => write!(f, "{} {} {} {}", cert_usage, selector, matching, cert_data),
            RecordData::SSHFP {
                algorithm,
                fingerprint_type,
                fingerprint,
            } => write!(f, "{} {} {}", algorithm, fingerprint_type, fingerprint),
            RecordData::NAPTR {
                order,
                preference,
                flags,
                services,
                regexp,
                replacement,
            } => write!(
                f,
                "{} {} \"{}\" \"{}\" \"{}\" {}",
                order, preference, flags, services, regexp, replacement
            ),
            RecordData::Unknown { raw } => write!(f, "{}", raw),
        }
    }
}

impl RecordData {
    /// The record's value as an equality key for cross-server / cross-time
    /// comparison (compare, follow, propagation).
    ///
    /// Domain-name fields are ASCII-lowercased — DNS names compare
    /// case-insensitively (RFC 4343), and resolvers applying 0x20 query-name
    /// randomization return `NS1.EXAMPLE.COM.` and `ns1.example.com.` for the
    /// same record. Everything else is kept verbatim because it is
    /// case-SENSITIVE data: TXT strings, base64 DNSKEY key material, CAA
    /// values, NAPTR regexps. Folding those (as compare/follow used to) hid
    /// real changes; folding nothing (as propagation used to) reported
    /// spurious NS/CNAME inconsistencies. This is the one shared rule.
    ///
    /// The key is rendered through `Display` so its shape always matches the
    /// displayed value.
    pub(crate) fn comparison_key(&self) -> String {
        let mut folded = self.clone();
        match &mut folded {
            RecordData::CNAME { target }
            | RecordData::PTR { target }
            | RecordData::SRV { target, .. } => target.make_ascii_lowercase(),
            RecordData::NS { nameserver } => nameserver.make_ascii_lowercase(),
            RecordData::MX { exchange, .. } => exchange.make_ascii_lowercase(),
            RecordData::SOA { mname, rname, .. } => {
                mname.make_ascii_lowercase();
                rname.make_ascii_lowercase();
            }
            RecordData::NAPTR { replacement, .. } => replacement.make_ascii_lowercase(),
            // RFC 8659 §4.1: property tags match case-insensitively; the
            // value is left alone.
            RecordData::CAA { tag, .. } => tag.make_ascii_lowercase(),
            RecordData::A { .. }
            | RecordData::AAAA { .. }
            | RecordData::TXT { .. }
            | RecordData::DNSKEY { .. }
            | RecordData::DS { .. }
            | RecordData::TLSA { .. }
            | RecordData::SSHFP { .. }
            | RecordData::Unknown { .. } => {}
        }
        folded.to_string()
    }
}

impl DnsRecord {
    pub fn format_short(&self) -> String {
        format!("{}", self.data)
    }

    pub fn format_full(&self) -> String {
        format!(
            "{}\t{}\tIN\t{}\t{}",
            self.name, self.ttl, self.record_type, self.data
        )
    }
}

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

    #[test]
    fn test_record_type_from_str() {
        assert_eq!("A".parse::<RecordType>().unwrap(), RecordType::A);
        assert_eq!("aaaa".parse::<RecordType>().unwrap(), RecordType::AAAA);
        assert_eq!("MX".parse::<RecordType>().unwrap(), RecordType::MX);
        assert_eq!("*".parse::<RecordType>().unwrap(), RecordType::ANY);
        assert!("INVALID".parse::<RecordType>().is_err());
    }

    #[test]
    fn test_record_type_display() {
        assert_eq!(RecordType::A.to_string(), "A");
        assert_eq!(RecordType::AAAA.to_string(), "AAAA");
        assert_eq!(RecordType::MX.to_string(), "MX");
        assert_eq!(RecordType::SOA.to_string(), "SOA");
    }

    #[test]
    fn test_dns_record_format_short() {
        let record = DnsRecord {
            name: "example.com".to_string(),
            record_type: RecordType::A,
            ttl: 300,
            data: RecordData::A {
                address: "1.2.3.4".to_string(),
            },
        };
        assert_eq!(record.format_short(), "1.2.3.4");
    }

    #[test]
    fn test_dns_record_format_full() {
        let record = DnsRecord {
            name: "example.com".to_string(),
            record_type: RecordType::A,
            ttl: 300,
            data: RecordData::A {
                address: "1.2.3.4".to_string(),
            },
        };
        assert_eq!(record.format_full(), "example.com\t300\tIN\tA\t1.2.3.4");
    }

    #[test]
    fn test_record_data_display() {
        let mx = RecordData::MX {
            preference: 10,
            exchange: "mail.example.com".to_string(),
        };
        assert_eq!(format!("{}", mx), "10 mail.example.com");

        let txt = RecordData::TXT {
            text: "v=spf1 include:example.com".to_string(),
        };
        assert_eq!(format!("{}", txt), "\"v=spf1 include:example.com\"");

        let srv = RecordData::SRV {
            priority: 10,
            weight: 5,
            port: 443,
            target: "server.example.com".to_string(),
        };
        assert_eq!(format!("{}", srv), "10 5 443 server.example.com");
    }

    #[test]
    fn test_record_serialization_roundtrip() {
        let record = DnsRecord {
            name: "example.com".to_string(),
            record_type: RecordType::A,
            ttl: 300,
            data: RecordData::A {
                address: "1.2.3.4".to_string(),
            },
        };
        let json = serde_json::to_string(&record).unwrap();
        assert!(json.contains("\"A\""));
        assert!(json.contains("1.2.3.4"));
    }

    #[test]
    fn test_soa_display() {
        let soa = RecordData::SOA {
            mname: "ns1.example.com".to_string(),
            rname: "admin.example.com".to_string(),
            serial: 2024010101,
            refresh: 3600,
            retry: 900,
            expire: 604800,
            minimum: 86400,
        };
        let display = format!("{}", soa);
        assert!(display.contains("ns1.example.com"));
        assert!(display.contains("2024010101"));
    }

    #[test]
    fn test_naptr_display() {
        // dig-style: order preference "flags" "services" "regexp" replacement
        let naptr = RecordData::NAPTR {
            order: 100,
            preference: 50,
            flags: "s".to_string(),
            services: "http+N2L+N2C+N2R".to_string(),
            regexp: String::new(),
            replacement: "www.example.com.".to_string(),
        };
        assert_eq!(
            format!("{}", naptr),
            "100 50 \"s\" \"http+N2L+N2C+N2R\" \"\" www.example.com."
        );
    }

    #[test]
    fn comparison_key_folds_only_domain_name_fields() {
        let ns = |n: &str| RecordData::NS {
            nameserver: n.to_string(),
        };
        assert_eq!(
            ns("NS1.Example.COM.").comparison_key(),
            ns("ns1.example.com.").comparison_key()
        );
        let mx = RecordData::MX {
            preference: 10,
            exchange: "MX.Example.com.".to_string(),
        };
        assert_eq!(mx.comparison_key(), "10 mx.example.com.");
        let cname = RecordData::CNAME {
            target: "Edge.CDN.test.".to_string(),
        };
        assert_eq!(cname.comparison_key(), "edge.cdn.test.");

        // Case-sensitive payloads are compared verbatim: a TXT token or a
        // base64 key that changes only in case IS a different value.
        let txt = |t: &str| RecordData::TXT {
            text: t.to_string(),
        };
        assert_ne!(
            txt("verify=AbC").comparison_key(),
            txt("verify=abc").comparison_key()
        );
        let key = |k: &str| RecordData::DNSKEY {
            flags: 257,
            protocol: 3,
            algorithm: 13,
            public_key: k.to_string(),
        };
        assert_ne!(
            key("mdsswUyr3DPW").comparison_key(),
            key("MDSSWUYR3DPW").comparison_key()
        );
    }

    /// Drift guard for the three surfaces that render `RecordType::ALL`
    /// (CLI help, REPL completion, MCP tool schema). Adding a variant breaks
    /// `as_str`'s exhaustive match at compile time; this pins the count so the
    /// author must also extend `ALL`/`ALL_NAMES` rather than only `as_str`.
    #[test]
    fn all_is_complete() {
        assert_eq!(
            RecordType::ALL.len(),
            16,
            "new RecordType variant — add it to ALL and ALL_NAMES too"
        );
        assert_eq!(RecordType::ALL.len(), RecordType::ALL_NAMES.len());
    }

    /// `ALL`, `ALL_NAMES`, `as_str`, and `FromStr` must agree entry-for-entry:
    /// a name a surface advertises has to be one `from_str` actually accepts.
    #[test]
    fn all_names_match_and_round_trip() {
        for (rt, name) in RecordType::ALL.iter().zip(RecordType::ALL_NAMES) {
            assert_eq!(&rt.as_str(), name, "ALL/ALL_NAMES out of order");
            assert_eq!(
                name.parse::<RecordType>().expect("advertised name parses"),
                *rt
            );
        }
    }
}