seer-core 0.50.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
//! Test-only mock DNS fixture shared by the crate's hermetic DNS tests
//! (`resolver.rs`, `transport.rs`, `follow.rs`, `compare.rs`, `dnssec.rs`,
//! `trace.rs`, `posture.rs`, …): a real UDP socket on 127.0.0.1 (optionally
//! with a TCP relay on the same port) serving
//! hickory-proto-encoded canned responses, so the full `resolve()` and
//! `query()` paths (normalization → nameserver vetting → hickory transport →
//! RData conversion) run without touching the network.
//!
//! Compiled only under `cfg(test)` — production builds never include this
//! module. The SSRF guards deliberately refuse loopback, so tests reach the
//! fixture through the `#[cfg(test)]`-only `allowing_private_hosts` /
//! `with_port` seams on [`DnsResolver`]; the production validation path is
//! never weakened.

use std::net::{IpAddr, Ipv4Addr};
use std::time::Duration;

use hickory_resolver::proto::dnssec::rdata::{DNSSECRData, CDNSKEY, CDS, DNSKEY};
use hickory_resolver::proto::dnssec::{Algorithm, DigestType, PublicKeyBuf};
use hickory_resolver::proto::op::{Edns, Message, OpCode, ResponseCode};
use hickory_resolver::proto::rr::rdata::svcb::{
    Alpn, EchConfigList, IpHint, Mandatory, SvcParamKey, SvcParamValue, Unknown, SVCB,
};
use hickory_resolver::proto::rr::rdata::{self as wire, sshfp, tlsa, CAA, HTTPS};
use hickory_resolver::proto::rr::{
    Name, RData as HickoryRData, Record, RecordType as HickoryRecordType,
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream, UdpSocket};

use super::resolver::{fqdn, DnsResolver};

/// How the mock server answers every query it receives.
#[derive(Clone, Copy)]
pub(crate) enum MockMode {
    /// Answer from the canned zone (see [`zone_answers`]).
    Zone,
    /// NXDOMAIN for every query.
    Nxdomain,
    /// NOERROR with an empty answer section (NODATA).
    NoData,
    /// Never respond, forcing the client's timeout path.
    Ignore,
}

fn name(s: &str) -> Name {
    Name::from_ascii(s).expect("valid test name")
}

/// `s` as a fully qualified name, with or without its trailing dot (`"."`
/// is the root).
pub(crate) fn fq_name(s: &str) -> Name {
    name(&fqdn(s))
}

/// A-record RDATA, e.g. `a_rdata([192, 0, 2, 7])`.
pub(crate) fn a_rdata(ip: impl Into<Ipv4Addr>) -> HickoryRData {
    HickoryRData::A(wire::A(ip.into()))
}

/// CNAME RDATA pointing at `target`.
pub(crate) fn cname_rdata(target: &str) -> HickoryRData {
    HickoryRData::CNAME(wire::CNAME(fq_name(target)))
}

/// Canned zone for [`MockMode::Zone`]. Query names are matched with the
/// trailing root dot stripped, since hickory sends fully-qualified names.
fn zone_answers(qname: &str, qtype: HickoryRecordType) -> Vec<HickoryRData> {
    match (qname.trim_end_matches('.'), qtype) {
        ("seer.test", HickoryRecordType::A) => vec![
            HickoryRData::A(wire::A(Ipv4Addr::new(192, 0, 2, 1))),
            HickoryRData::A(wire::A(Ipv4Addr::new(192, 0, 2, 2))),
        ],
        ("seer.test", HickoryRecordType::AAAA) => vec![HickoryRData::AAAA(wire::AAAA(
            "2001:db8::1".parse().expect("valid IPv6 literal"),
        ))],
        // Deliberately out of preference order to prove resolve() sorts.
        ("seer.test", HickoryRecordType::MX) => vec![
            HickoryRData::MX(wire::MX::new(30, name("c.mail.seer.test."))),
            HickoryRData::MX(wire::MX::new(10, name("a.mail.seer.test."))),
            HickoryRData::MX(wire::MX::new(20, name("b.mail.seer.test."))),
        ],
        ("seer.test", HickoryRecordType::NS) => {
            vec![HickoryRData::NS(wire::NS(name("ns1.seer.test.")))]
        }
        // Two character-strings, to prove segments are joined.
        ("seer.test", HickoryRecordType::TXT) => vec![HickoryRData::TXT(wire::TXT::new(vec![
            "v=spf1 ".to_string(),
            "-all".to_string(),
        ]))],
        ("seer.test", HickoryRecordType::SOA) => vec![HickoryRData::SOA(wire::SOA::new(
            name("ns1.seer.test."),
            name("hostmaster.seer.test."),
            2026070101,
            7200,
            3600,
            1209600,
            300,
        ))],
        // `CAA` has no struct-literal constructor (#[non_exhaustive]).
        ("seer.test", HickoryRecordType::CAA) => vec![
            HickoryRData::CAA(CAA::new_issue(false, Some(name("letsencrypt.org")), vec![])),
            HickoryRData::CAA(CAA::new_iodef(
                true,
                url::Url::parse("mailto:security@seer.test").expect("valid iodef URL"),
            )),
        ],
        ("_443._tcp.seer.test", HickoryRecordType::TLSA) => {
            vec![HickoryRData::TLSA(wire::TLSA::new(
                tlsa::CertUsage::from(3),
                tlsa::Selector::from(1),
                tlsa::Matching::from(1),
                vec![0xAB, 0xCD, 0x01],
            ))]
        }
        ("seer.test", HickoryRecordType::SSHFP) => vec![HickoryRData::SSHFP(wire::SSHFP::new(
            sshfp::Algorithm::from(4),
            sshfp::FingerprintType::from(2),
            vec![0xDE, 0xAD, 0xBE, 0xEF],
        ))],
        ("seer.test", HickoryRecordType::NAPTR) => vec![HickoryRData::NAPTR(wire::NAPTR::new(
            100,
            50,
            b"U".to_vec().into_boxed_slice(),
            b"E2U+sip".to_vec().into_boxed_slice(),
            b"!^.*$!sip:info@seer.test!".to_vec().into_boxed_slice(),
            Name::root(),
        ))],
        ("_sip._tcp.seer.test", HickoryRecordType::SRV) => vec![HickoryRData::SRV(wire::SRV::new(
            10,
            5,
            5060,
            name("sipserver.seer.test."),
        ))],
        ("1.2.0.192.in-addr.arpa", HickoryRecordType::PTR) => {
            vec![HickoryRData::PTR(wire::PTR(name("ptr.seer.test.")))]
        }
        // `www` carries its own record (the apex has no CNAME), so a query
        // that silently strips `www.` comes back empty.
        ("www.seer.test", HickoryRecordType::CNAME) => {
            vec![HickoryRData::CNAME(wire::CNAME(name("edge.cdn.test.")))]
        }
        // Reverse name of 2606:4700:4700::1111.
        (
            "1.1.1.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.7.4.0.0.7.4.6.0.6.2.ip6.arpa",
            HickoryRecordType::PTR,
        ) => vec![HickoryRData::PTR(wire::PTR(name("one.one.one.one.")))],
        // ServiceMode with every registered SvcParam kind plus a private-use
        // key, in the strictly increasing key order the wire requires.
        ("seer.test", HickoryRecordType::HTTPS) => {
            vec![HickoryRData::HTTPS(HTTPS(SVCB::new(
                1,
                Name::root(),
                vec![
                    (
                        SvcParamKey::Alpn,
                        SvcParamValue::Alpn(Alpn(vec!["h3".to_string(), "h2".to_string()])),
                    ),
                    (SvcParamKey::Port, SvcParamValue::Port(8443)),
                    (
                        SvcParamKey::Ipv4Hint,
                        SvcParamValue::Ipv4Hint(IpHint(vec![
                            wire::A::new(192, 0, 2, 1),
                            wire::A::new(192, 0, 2, 2),
                        ])),
                    ),
                    (
                        SvcParamKey::EchConfigList,
                        SvcParamValue::EchConfigList(EchConfigList(vec![0x00, 0x01, 0xFE])),
                    ),
                    (
                        SvcParamKey::Ipv6Hint,
                        SvcParamValue::Ipv6Hint(IpHint(vec![wire::AAAA::new(
                            0x2001, 0xdb8, 0, 0, 0, 0, 0, 1,
                        )])),
                    ),
                    (
                        SvcParamKey::Key(65333),
                        SvcParamValue::Unknown(Unknown(b"ex 1".to_vec())),
                    ),
                ],
            )))]
        }
        // AliasMode: priority 0, the alias target, no params.
        ("alias.seer.test", HickoryRecordType::HTTPS) => vec![HickoryRData::HTTPS(HTTPS(
            SVCB::new(0, name("pool.seer.test."), vec![]),
        ))],
        ("_8443._foo.seer.test", HickoryRecordType::SVCB) => {
            vec![HickoryRData::SVCB(SVCB::new(
                2,
                name("svc.seer.test."),
                vec![
                    (
                        SvcParamKey::Mandatory,
                        SvcParamValue::Mandatory(Mandatory(vec![
                            SvcParamKey::Alpn,
                            SvcParamKey::Port,
                        ])),
                    ),
                    (
                        SvcParamKey::Alpn,
                        SvcParamValue::Alpn(Alpn(vec!["foo".to_string()])),
                    ),
                    (SvcParamKey::NoDefaultAlpn, SvcParamValue::NoDefaultAlpn),
                    (SvcParamKey::Port, SvcParamValue::Port(8443)),
                ],
            ))]
        }
        ("seer.test", HickoryRecordType::DNSKEY) => {
            vec![HickoryRData::DNSSEC(DNSSECRData::DNSKEY(DNSKEY::new(
                true,
                true,
                false,
                PublicKeyBuf::new(vec![7u8; 32], Algorithm::ED25519),
            )))]
        }
        // An update request plus the RFC 8078 delete request (`0 0 0 00`).
        ("seer.test", HickoryRecordType::CDS) => vec![
            HickoryRData::DNSSEC(DNSSECRData::CDS(CDS::new(
                2371,
                Some(Algorithm::ED25519),
                DigestType::SHA256,
                vec![0xAB, 0xCD, 0xEF],
            ))),
            HickoryRData::DNSSEC(DNSSECRData::CDS(CDS::new(
                0,
                None,
                DigestType::from(0),
                vec![0x00],
            ))),
        ],
        // An update request plus the RFC 8078 delete request (`0 3 0 AA==`).
        ("seer.test", HickoryRecordType::CDNSKEY) => vec![
            HickoryRData::DNSSEC(DNSSECRData::CDNSKEY(CDNSKEY::with_flags(
                257,
                Some(Algorithm::ED25519),
                vec![7u8; 32],
            ))),
            HickoryRData::DNSSEC(DNSSECRData::CDNSKEY(CDNSKEY::with_flags(
                0,
                None,
                vec![0x00],
            ))),
        ],
        _ => vec![],
    }
}

/// Builds the response skeleton for `request`: echoes the ID and the question
/// section (hickory discards responses whose queries don't match the request
/// — anti-spoofing) and marks recursion available.
fn response_skeleton(request: &Message) -> Message {
    let mut response = Message::response(request.metadata.id, OpCode::Query);
    response.metadata.recursion_desired = request.metadata.recursion_desired;
    response.metadata.recursion_available = true;
    for query in &request.queries {
        response.add_query(query.clone());
    }
    response
}

/// Binds a UDP socket on an ephemeral loopback port and answers DNS
/// queries per `mode` until the test runtime shuts down. Returns the
/// bound port.
pub(crate) async fn spawn_mock_dns(mode: MockMode) -> u16 {
    spawn_mock_dns_fn(move |qname, qtype| match mode {
        MockMode::Zone => MockReply::Answer(zone_answers(qname, qtype)),
        MockMode::Nxdomain => MockReply::NxDomain,
        MockMode::NoData => MockReply::NoData,
        MockMode::Ignore => MockReply::NoReply,
    })
    .await
}

/// Binds a UDP socket on an ephemeral loopback port and answers the n-th
/// query received with the n-th answer set, clamping to the last set once
/// the sequence is exhausted (an empty sequence answers NODATA). Every
/// answer echoes the query name, so any domain works. Lets follow-loop
/// tests observe record sets that change between iterations. Returns the
/// bound port.
pub(crate) async fn spawn_mock_dns_sequence(answer_sets: Vec<Vec<HickoryRData>>) -> u16 {
    let mut served = 0usize;
    spawn_mock_dns_fn(move |_, _| {
        let idx = served.min(answer_sets.len().saturating_sub(1));
        served += 1;
        MockReply::Answer(answer_sets.get(idx).cloned().unwrap_or_default())
    })
    .await
}

/// A plausible SOA RRdata for `zone` (for scripted apex answers).
pub(crate) fn soa_rdata(zone: &str) -> HickoryRData {
    HickoryRData::SOA(wire::SOA::new(
        name(&format!("ns1.{zone}.")),
        name(&format!("hostmaster.{zone}.")),
        2026070101,
        7200,
        3600,
        1209600,
        300,
    ))
}

/// A record owned by `owner` (fully qualified, with or without its trailing
/// dot), for [`MockReply::Records`] answers that must not be owned by the
/// query name — a CNAME chain's hops, the records at its target.
pub(crate) fn record(owner: &str, ttl: u32, rdata: HickoryRData) -> Record {
    Record::from_rdata(fq_name(owner), ttl, rdata)
}

/// The SOA record of `zone`, owned by the zone apex (negative answers'
/// AUTHORITY section).
fn zone_soa(zone: &str) -> Record {
    Record::from_rdata(fq_name(zone), 300, soa_rdata(zone))
}

/// A scripted reply for [`spawn_mock_dns_fn`].
pub(crate) enum MockReply {
    /// NOERROR with these answers, each owned by the query name.
    Answer(Vec<HickoryRData>),
    /// NOERROR with these complete records in ANSWER, in this order, under
    /// their own owner names (see [`record`]) — e.g. a CNAME chain followed
    /// by the records at its target, as a recursive resolver relays it.
    Records(Vec<Record>),
    /// Like [`MockReply::Answer`], with the AA (authoritative) bit set.
    AuthoritativeAnswer(Vec<HickoryRData>),
    /// NOERROR with an empty answer section (NODATA).
    NoData,
    /// NODATA whose AUTHORITY section carries the SOA of the named zone — the
    /// shape a recursive resolver relays for a name inside that zone.
    NoDataWithSoa(&'static str),
    /// NXDOMAIN.
    NxDomain,
    /// NXDOMAIN whose AUTHORITY section carries the SOA of the named zone —
    /// the negative answer a recursive resolver relays (RFC 2308).
    NxDomainWithSoa(&'static str),
    /// Like [`MockReply::NxDomainWithSoa`], with the AA bit set: an
    /// authoritative server's own "no such name".
    AuthoritativeNxDomain(&'static str),
    /// An empty response with any other response code (NOTIMP, FORMERR,
    /// …); SERVFAIL and REFUSED have their own variants.
    Rcode(ResponseCode),
    /// SERVFAIL — e.g. a validating upstream rejecting a broken DNSSEC chain.
    ServFail,
    /// REFUSED.
    Refused,
    /// Send nothing, forcing the client's timeout path.
    NoReply,
    /// A referral to a child zone, as a parent-side server sends it:
    /// NOERROR, AA and RA clear, empty ANSWER, an NS record for `zone` (`"."` for
    /// the root) per listed server in AUTHORITY, and in ADDITIONAL an A/AAAA
    /// glue record for each address listed with a server (none: a glueless
    /// server).
    Delegation {
        zone: String,
        servers: Vec<(String, Vec<IpAddr>)>,
    },
    /// NOERROR with the TC (truncated) bit set and no records: the reply did
    /// not fit, so the client must retry over TCP.
    Truncated,
    /// A negative answer behind a CNAME chain, as a recursive resolver
    /// relays it (RFC 6604 §2): response code `code` (NXDOMAIN when the
    /// chain's last target does not exist, NOERROR when it has no records of
    /// the type), the `chain` records in ANSWER under their own owners (see
    /// [`record`]), and the SOA of `soa` — the target's zone — in AUTHORITY.
    Negative {
        code: ResponseCode,
        chain: Vec<Record>,
        soa: &'static str,
    },
}

/// Binds a UDP socket on an ephemeral loopback port and answers every query
/// with `handler(qname, qtype)`, where `qname` is the lowercased ASCII query
/// name without the trailing root dot. Lets a test script a whole multi-name
/// scenario (tree walks, redirects, per-name failures) that the fixed
/// [`MockMode::Zone`] table cannot express. Every spawner here ends in its
/// server loop ([`serve_udp`]). Returns the bound port.
pub(crate) async fn spawn_mock_dns_fn<F>(handler: F) -> u16
where
    F: FnMut(&str, HickoryRecordType) -> MockReply + Send + 'static,
{
    let socket = UdpSocket::bind("127.0.0.1:0").await.expect("bind mock DNS");
    serve_udp(socket, handler)
}

/// Like [`spawn_mock_dns_fn`], but the same port also takes DNS over TCP:
/// each TCP query is relayed to the UDP server loop and its reply sent back,
/// so one `handler` scripts both transports (in arrival order — e.g. a
/// [`MockReply::Truncated`] first reply, then the full answer the client
/// retries for over TCP). Returns the shared port.
pub(crate) async fn spawn_mock_dns_fn_with_tcp<F>(handler: F) -> u16
where
    F: FnMut(&str, HickoryRecordType) -> MockReply + Send + 'static,
{
    // TCP and UDP port spaces are separate, so the UDP socket's ephemeral
    // port is almost always free for TCP too; retry the pair if it is not.
    for _ in 0..16 {
        let socket = UdpSocket::bind("127.0.0.1:0").await.expect("bind mock DNS");
        let port = socket.local_addr().expect("mock DNS local addr").port();
        if let Ok(listener) = TcpListener::bind(("127.0.0.1", port)).await {
            let port = serve_udp(socket, handler);
            tokio::spawn(relay_tcp(listener, port));
            return port;
        }
    }
    panic!("no loopback port free for both UDP and TCP");
}

/// Accepts DNS-over-TCP connections and relays every length-prefixed query
/// to the UDP mock on `udp_port`, writing its reply back.
async fn relay_tcp(listener: TcpListener, udp_port: u16) {
    while let Ok((stream, _)) = listener.accept().await {
        tokio::spawn(relay_connection(stream, udp_port));
    }
}

/// Relays one TCP connection's queries until the client closes it (or a
/// query gets no UDP reply — the client's timeout then applies).
async fn relay_connection(mut stream: TcpStream, udp_port: u16) {
    let Ok(socket) = UdpSocket::bind("127.0.0.1:0").await else {
        return;
    };
    let mut buf = [0u8; 4096];
    loop {
        let Ok(len) = stream.read_u16().await else {
            return;
        };
        let mut query = vec![0u8; usize::from(len)];
        if stream.read_exact(&mut query).await.is_err()
            || socket
                .send_to(&query, ("127.0.0.1", udp_port))
                .await
                .is_err()
        {
            return;
        }
        let Ok(reply_len) = socket.recv(&mut buf).await else {
            return;
        };
        let Ok(prefix) = u16::try_from(reply_len) else {
            return;
        };
        if stream.write_u16(prefix).await.is_err()
            || stream.write_all(&buf[..reply_len]).await.is_err()
        {
            return;
        }
    }
}

/// The UDP server loop behind every spawner: answers each query on `socket`
/// with `handler(qname, qtype)` until the test runtime shuts down. Returns
/// the bound port.
fn serve_udp<F>(socket: UdpSocket, mut handler: F) -> u16
where
    F: FnMut(&str, HickoryRecordType) -> MockReply + Send + 'static,
{
    let port = socket.local_addr().expect("mock DNS local addr").port();
    tokio::spawn(async move {
        let mut buf = [0u8; 4096];
        loop {
            let Ok((len, src)) = socket.recv_from(&mut buf).await else {
                return;
            };
            let Ok(request) = Message::from_vec(&buf[..len]) else {
                continue;
            };
            let mut response = response_skeleton(&request);
            if let Some(query) = request.queries.first() {
                let qname = query.name.to_ascii().to_ascii_lowercase();
                let owned = |rdata| Record::from_rdata(query.name.clone(), 300, rdata);
                match handler(qname.trim_end_matches('.'), query.query_type) {
                    MockReply::Answer(answers) => {
                        response.add_answers(answers.into_iter().map(owned));
                    }
                    MockReply::Records(records) => {
                        response.add_answers(records);
                    }
                    MockReply::AuthoritativeAnswer(answers) => {
                        response.metadata.authoritative = true;
                        response.add_answers(answers.into_iter().map(owned));
                    }
                    MockReply::NoData => {}
                    MockReply::NoDataWithSoa(zone) => {
                        response.add_authority(zone_soa(zone));
                    }
                    MockReply::NxDomain => {
                        response.metadata.response_code = ResponseCode::NXDomain;
                    }
                    MockReply::NxDomainWithSoa(zone) => {
                        response.metadata.response_code = ResponseCode::NXDomain;
                        response.add_authority(zone_soa(zone));
                    }
                    MockReply::AuthoritativeNxDomain(zone) => {
                        response.metadata.authoritative = true;
                        response.metadata.response_code = ResponseCode::NXDomain;
                        response.add_authority(zone_soa(zone));
                    }
                    MockReply::Rcode(code) => {
                        response.metadata.response_code = code;
                        // A code above 15 is extended: its high bits travel
                        // in the OPT record (RFC 6891 §6.1.3).
                        if code.high() > 0 {
                            response.edns = Some(Edns::new());
                        }
                    }
                    MockReply::ServFail => {
                        response.metadata.response_code = ResponseCode::ServFail;
                    }
                    MockReply::Refused => {
                        response.metadata.response_code = ResponseCode::Refused;
                    }
                    MockReply::NoReply => continue,
                    MockReply::Delegation { zone, servers } => {
                        // A parent-side server answers from its own zone
                        // data and does not recurse.
                        response.metadata.recursion_available = false;
                        let zone = fq_name(&zone);
                        for (server, addrs) in servers {
                            let server = fq_name(&server);
                            response.add_authority(Record::from_rdata(
                                zone.clone(),
                                300,
                                HickoryRData::NS(wire::NS(server.clone())),
                            ));
                            response.add_additionals(addrs.into_iter().map(|ip| {
                                let glue = match ip {
                                    IpAddr::V4(v4) => HickoryRData::A(wire::A(v4)),
                                    IpAddr::V6(v6) => HickoryRData::AAAA(wire::AAAA(v6)),
                                };
                                Record::from_rdata(server.clone(), 300, glue)
                            }));
                        }
                    }
                    MockReply::Truncated => {
                        response.metadata.truncation = true;
                    }
                    MockReply::Negative { code, chain, soa } => {
                        response.metadata.response_code = code;
                        response.add_answers(chain);
                        response.add_authority(zone_soa(soa));
                    }
                }
            }
            let Ok(bytes) = response.to_vec() else {
                continue;
            };
            let _ = socket.send_to(&bytes, src).await;
        }
    });
    port
}

/// A resolver wired to the loopback fixture through the `#[cfg(test)]`-only
/// seams, with a short timeout to keep failing tests fast.
pub(crate) fn mock_dns_resolver(port: u16) -> DnsResolver {
    DnsResolver::new()
        .with_timeout(Duration::from_millis(500))
        .allowing_private_hosts()
        .with_port(port)
}

/// Like [`mock_dns_resolver`], but ALSO routes queries that name no
/// nameserver (`resolve(.., None)`) to the fixture, so code that always uses
/// the default upstream (posture, CAA) can be exercised end to end.
pub(crate) fn mock_dns_resolver_default(port: u16) -> DnsResolver {
    mock_dns_resolver(port).with_default_nameserver("127.0.0.1")
}