nsproxy-hickory-server 0.25.4

Hickory DNS is a safe and secure DNS server with DNSSEC support. The DNSSEC support allows for live signing of all records, but it does not currently support records signed offline. The server supports dynamic DNS with SIG(0) or TSIG authenticated requests. Hickory DNS is based on the Tokio and Futures libraries, which means it should be easy to integrate into other software that also uses those libraries.
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
// Copyright 2015-2022 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// https://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! Blocklist resolver related types

#![cfg(feature = "blocklist")]

use std::{
    collections::HashMap,
    fs::File,
    io,
    io::{Error, Read},
    net::{Ipv4Addr, Ipv6Addr},
    path::Path,
    str::FromStr,
    time::{Duration, Instant},
};

use serde::Deserialize;
use tracing::{error, info, trace};

#[cfg(feature = "__dnssec")]
use crate::{authority::Nsec3QueryInfo, dnssec::NxProofKind};
use crate::{
    authority::{
        Authority, LookupControlFlow, LookupError, LookupObject, LookupOptions, MessageRequest,
        UpdateResult, ZoneType,
    },
    proto::{
        op::{Query, ResponseCode},
        rr::{
            LowerName, Name, RData, Record, RecordType,
            rdata::{A, AAAA, TXT},
        },
    },
    resolver::lookup::Lookup,
    server::RequestInfo,
};

// TODO:
//  * Add (optional) support for logging the client IP address.  This will require some Authority
//    trait changes to accomplish
//  * Add query-type specific results for non-address queries
//  * Add support for per-blocklist sinkhole IPs, block messages, actions
//  * Add support for an exclusion list: allow the user to configure a list of patterns that
//    will never be insert into the in-memory blocklist (such as their own domain)
//  * Add support for regex matching

/// A conditional authority that will resolve queries against one or more block lists and return a
/// forged response.  The typical use case will be to use this in a chained configuration before a
/// forwarding or recursive resolver in order to pre-emptively block queries for hosts that are on
/// a block list. Refer to tests/test-data/test_configs/chained_blocklist.toml for an example
/// of this configuration.
///
/// The blocklist authority also supports the consult interface, which allows an authority to review
/// a query/response that has been processed by another authority, and, optionally, overwrite that
/// response before returning it to the requestor.  There is an example of this configuration in
/// tests/test-data/test_configs/example_consulting_blocklist.toml.  The main intended use of this
/// feature is to allow log-only configurations, to allow administrators to see if blocklist domains
/// are being queried.  While this can be configured to overwrite responses, it is not recommended
/// to do so - it is both more efficient, and more secure, to allow the blocklist to drop queries
/// pre-emptively, as in the first example.
pub struct BlocklistAuthority {
    origin: LowerName,
    blocklist: HashMap<LowerName, bool>,
    wildcard_match: bool,
    min_wildcard_depth: u8,
    sinkhole_ipv4: Ipv4Addr,
    sinkhole_ipv6: Ipv6Addr,
    ttl: u32,
    block_message: Option<String>,
    consult_action: BlocklistConsultAction,
}

impl BlocklistAuthority {
    /// Read the Authority for the origin from the specified configuration
    pub async fn try_from_config(
        origin: Name,
        _zone_type: ZoneType,
        config: &BlocklistConfig,
        base_dir: Option<&Path>,
    ) -> Result<Self, String> {
        info!("loading blocklist config: {origin}");

        let mut authority = Self {
            origin: origin.into(),
            blocklist: HashMap::new(),
            wildcard_match: config.wildcard_match,
            min_wildcard_depth: config.min_wildcard_depth,
            sinkhole_ipv4: match config.sinkhole_ipv4 {
                Some(ip) => ip,
                None => Ipv4Addr::UNSPECIFIED,
            },
            sinkhole_ipv6: match config.sinkhole_ipv6 {
                Some(ip) => ip,
                None => Ipv6Addr::UNSPECIFIED,
            },
            ttl: config.ttl,
            block_message: config.block_message.clone(),
            consult_action: config.consult_action,
        };

        let base_dir = match base_dir {
            Some(dir) => dir.display(),
            None => {
                return Err(format!(
                    "invalid blocklist (zone directory) base path specified: '{base_dir:?}'"
                ));
            }
        };

        // Load block lists into the block table cache for this authority.
        for bl in &config.lists {
            info!("adding blocklist {bl}");

            match File::open(format!("{base_dir}/{bl}")) {
                Ok(handle) => {
                    if let Err(e) = authority.add(handle) {
                        return Err(format!(
                            "unable to add data from blocklist {base_dir}/{bl}: {e:?}"
                        ));
                    }
                }
                Err(e) => {
                    return Err(format!(
                        "unable to open blocklist file {base_dir}/{bl}: {e:?}"
                    ));
                }
            }
        }

        Ok(authority)
    }

    /// Add the contents of a block list to the in-memory cache. This function is normally called
    /// from try_from_config, but it can be invoked after the blocklist authority is created.
    ///
    /// # Arguments
    ///
    /// * `handle` - A source implementing `std::io::Read` that contains the blocklist entries
    ///   to insert into the in-memory cache.
    ///
    /// # Return value
    ///
    /// `Result<(), std::io::Error>`
    ///
    /// # Expected format of blocklist entries
    ///
    /// * One entry per line
    /// * Any character after a '\#' will be treated as a comment and stripped out.
    /// * Leading wildcard entries are supported when the user has wildcard_match set to true.
    ///   E.g., '\*.foo.com' will match any host in the foo.com domain.  Intermediate wildcard
    ///   matches, such as 'www.\*.com' are not supported. **Note: when wildcard matching is enabled,
    ///   min_wildcard_depth (default: 2) controls how many static name labels must be present for a
    ///   wildcard entry to be valid.  With the default value of 2, an entry for '\*.foo.com' would
    ///   be accepted, but an entry for '\*.com' would not.**
    /// * All entries are treated as being fully-qualified. If an entry does not contain a trailing
    ///   '.', one will be added before insertion into the cache.
    ///
    /// # Example
    /// ```
    /// use std::{fs::File, net::{Ipv4Addr, Ipv6Addr}, path::Path, str::FromStr, sync::Arc};
    /// use hickory_proto::rr::{LowerName, RecordType};
    /// use hickory_resolver::Name;
    /// use hickory_server::{authority::{AuthorityObject, LookupControlFlow, LookupOptions, ZoneType}, store::blocklist::*};
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let config = BlocklistConfig {
    ///         wildcard_match: true,
    ///         min_wildcard_depth: 2,
    ///         lists: vec!["default/blocklist.txt".to_string()],
    ///         sinkhole_ipv4: None,
    ///         sinkhole_ipv6: None,
    ///         block_message: None,
    ///         ttl: 86_400,
    ///         consult_action: BlocklistConsultAction::Disabled,
    ///     };
    ///
    ///     let mut blocklist = BlocklistAuthority::try_from_config(
    ///         Name::root(),
    ///         ZoneType::External,
    ///         &config,
    ///         Some(Path::new("../../tests/test-data/test_configs")),
    ///     ).await.unwrap();
    ///
    ///     let handle = File::open("../../tests/test-data/test_configs/default/blocklist2.txt").unwrap();
    ///     if let Err(e) = blocklist.add(handle) {
    ///         panic!("error adding blocklist: {e:?}");
    ///     }
    ///
    ///     let origin = blocklist.origin().clone();
    ///     let authority = Arc::new(blocklist) as Arc<dyn AuthorityObject>;
    ///
    ///     // In this example, malc0de.com only exists in the blocklist2.txt file we added to the
    ///     // authority after instantiating it.  The following simulates a lookup against the blocklist
    ///     // authority, and checks for the expected response for a blocklist match.
    ///     use LookupControlFlow::*;
    ///     let Break(Ok(_res)) = authority.lookup(
    ///                             &LowerName::from(Name::from_ascii("malc0de.com.").unwrap()),
    ///                             RecordType::A,
    ///                             LookupOptions::default(),
    ///                           ).await else {
    ///         panic!("blocklist authority did not return expected match");
    ///     };
    /// }
    /// ```
    pub fn add(&mut self, mut handle: impl Read) -> Result<(), Error> {
        let mut contents = String::new();

        if let Err(e) = handle.read_to_string(&mut contents) {
            error!("unable to read blocklist data: {e:?}");
            return Err(e);
        }

        for mut entry in contents.lines() {
            // Strip comments
            if let Some((item, _)) = entry.split_once('#') {
                entry = item.trim();
            }

            if entry.is_empty() {
                continue;
            }

            let mut str_entry = entry.to_string();
            if !entry.ends_with('.') {
                str_entry += ".";
            }

            let Ok(name) = LowerName::from_str(&str_entry[..]) else {
                error!(
                    "unable to derive LowerName for blocklist entry '{str_entry}'; skipping entry"
                );
                continue;
            };

            trace!("inserting blocklist entry {str_entry}");

            // The boolean value is not significant; only the key is used.
            self.blocklist.insert(name, true);
        }

        Ok(())
    }

    /// Build a wildcard match list for a given host
    fn wildcards(&self, host: &Name) -> Vec<LowerName> {
        host.iter()
            .enumerate()
            .filter_map(|(i, _x)| {
                if i > ((self.min_wildcard_depth - 1) as usize) {
                    Some(host.trim_to(i + 1).into_wildcard().into())
                } else {
                    None
                }
            })
            .collect()
    }

    /// Perform a blocklist lookup. Returns true on match, false on no match.  This is also where
    /// wildcard expansion is done, if wildcard support is enabled for the blocklist authority.
    fn is_blocked(&self, name: &LowerName) -> bool {
        let mut match_list = vec![name.to_owned()];

        if self.wildcard_match {
            match_list.append(&mut self.wildcards(name));
        }

        trace!("blocklist match list: {match_list:?}");

        if match_list
            .iter()
            .any(|entry| self.blocklist.contains_key(entry))
        {
            info!("block list matched query {name}");
            return true;
        }

        false
    }

    /// Generate a BlocklistLookup to return on a blocklist match.  This will return a lookup with
    /// either an A or AAAA record and, if the user has configured a block message, a TXT record
    /// with the contents of that message.
    fn blocklist_response(&self, name: Name, rtype: RecordType) -> BlocklistLookup {
        let mut records = vec![];

        match rtype {
            RecordType::AAAA => records.push(Record::from_rdata(
                name.clone(),
                self.ttl,
                RData::AAAA(AAAA(self.sinkhole_ipv6)),
            )),
            _ => records.push(Record::from_rdata(
                name.clone(),
                self.ttl,
                RData::A(A(self.sinkhole_ipv4)),
            )),
        }

        if let Some(block_message) = &self.block_message {
            records.push(Record::from_rdata(
                name.clone(),
                self.ttl,
                RData::TXT(TXT::new(vec![block_message.clone()])),
            ));
        }

        BlocklistLookup(Lookup::new_with_deadline(
            Query::query(name.clone(), rtype),
            records.into(),
            Instant::now() + Duration::from_secs(u64::from(self.ttl)),
        ))
    }
}

#[async_trait::async_trait]
impl Authority for BlocklistAuthority {
    type Lookup = BlocklistLookup;

    fn zone_type(&self) -> ZoneType {
        ZoneType::External
    }

    fn is_axfr_allowed(&self) -> bool {
        false
    }

    async fn update(&self, _update: &MessageRequest) -> UpdateResult<bool> {
        Err(ResponseCode::NotImp)
    }

    fn origin(&self) -> &LowerName {
        &self.origin
    }

    /// Perform a blocklist lookup.  This will return LookupControlFlow::Break(Ok) on a match, or
    /// LookupControlFlow::Skip on no match.
    async fn lookup(
        &self,
        name: &LowerName,
        rtype: RecordType,
        _lookup_options: LookupOptions,
    ) -> LookupControlFlow<Self::Lookup> {
        use LookupControlFlow::*;

        trace!("blocklist lookup: {name} {rtype}");

        if self.is_blocked(name) {
            return Break(Ok(self.blocklist_response(Name::from(name), rtype)));
        }

        trace!("query '{name}' is not in blocklist; returning Skip...");
        Skip
    }

    /// Optionally, perform a blocklist lookup after another authority has done a lookup for this
    /// query.
    async fn consult(
        &self,
        name: &LowerName,
        rtype: RecordType,
        lookup_options: LookupOptions,
        last_result: LookupControlFlow<Box<dyn LookupObject>>,
    ) -> LookupControlFlow<Box<dyn LookupObject>> {
        match self.consult_action {
            BlocklistConsultAction::Disabled => last_result,
            BlocklistConsultAction::Log => {
                self.is_blocked(name);
                last_result
            }
            BlocklistConsultAction::Enforce => {
                let lookup = self.lookup(name, rtype, lookup_options).await;

                if lookup.is_break() {
                    lookup.map_dyn()
                } else {
                    last_result
                }
            }
        }
    }

    async fn search(
        &self,
        request_info: RequestInfo<'_>,
        lookup_options: LookupOptions,
    ) -> LookupControlFlow<Self::Lookup> {
        self.lookup(
            request_info.query.name(),
            request_info.query.query_type(),
            lookup_options,
        )
        .await
    }

    async fn get_nsec_records(
        &self,
        _name: &LowerName,
        _lookup_options: LookupOptions,
    ) -> LookupControlFlow<Self::Lookup> {
        LookupControlFlow::Continue(Err(LookupError::from(io::Error::new(
            io::ErrorKind::Other,
            "Getting NSEC records is unimplemented for the blocklist",
        ))))
    }

    #[cfg(feature = "__dnssec")]
    async fn get_nsec3_records(
        &self,
        _info: Nsec3QueryInfo<'_>,
        _lookup_options: LookupOptions,
    ) -> LookupControlFlow<Self::Lookup> {
        LookupControlFlow::Continue(Err(LookupError::from(io::Error::new(
            io::ErrorKind::Other,
            "getting NSEC3 records is unimplemented for the forwarder",
        ))))
    }

    #[cfg(feature = "__dnssec")]
    fn nx_proof_kind(&self) -> Option<&NxProofKind> {
        None
    }
}

/// Consult action enum.  Controls how consult lookups are handled.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
pub enum BlocklistConsultAction {
    /// Do not log or block any request when the blocklist is called via consult
    #[default]
    Disabled,
    /// Log and block matching requests when the blocklist is called via consult
    Enforce,
    /// Log but do not block matching requests when the blocklist is called via consult
    Log,
}

/// Configuration for file based zones
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
#[serde(default, deny_unknown_fields)]
pub struct BlocklistConfig {
    /// Support wildcards?  Defaults to true. If set to true, block list entries containing
    /// asterisks will be expanded to match queries.
    pub wildcard_match: bool,

    /// Minimum wildcard depth.  Defaults to 2.  Any wildcard entries without at least this many
    /// static elements will not be expanded (e.g., *.com has a depth of 1; *.example.com has a
    /// depth of two.) This is meant as a safeguard against an errant block list entry, such as *
    /// or *.com that might block many more hosts than intended.
    pub min_wildcard_depth: u8,

    /// Block lists to load.  These should be specified as relative (to the server zone directory)
    /// paths in the config file.
    pub lists: Vec<String>,

    /// IPv4 sinkhole IP. This is the IP that is returned when a blocklist entry is matched for an
    /// A query. If unspecified, an implementation-provided default will be used.
    pub sinkhole_ipv4: Option<Ipv4Addr>,

    /// IPv6 sinkhole IP.  This is the IP that is returned when a blocklist entry is matched for a
    /// AAAA query. If unspecified, an implementation-provided default will be used.
    pub sinkhole_ipv6: Option<Ipv6Addr>,

    /// Block TTL. This is the length of time a block response should be stored in the requesting
    /// resolvers cache, in seconds.  Defaults to 86,400 seconds.
    pub ttl: u32,

    /// Block message to return to the user.  This is an optional message that, if configured, will
    /// be returned as a TXT record in the additionals section when a blocklist entry is matched for
    /// a query.
    pub block_message: Option<String>,

    /// The consult action controls how the blocklist handles queries where another authority has
    /// already provided an answer.  By default, it ignores any such queries ("Disabled",) however
    /// it can be configured to log blocklist matches for those queries ("Log",) or can be
    /// configured to overwrite the previous responses ("Enforce".)
    pub consult_action: BlocklistConsultAction,
}

impl Default for BlocklistConfig {
    fn default() -> Self {
        Self {
            wildcard_match: true,
            min_wildcard_depth: 2,
            lists: vec![],
            sinkhole_ipv4: None,
            sinkhole_ipv6: None,
            ttl: 86_400,
            block_message: None,
            consult_action: BlocklistConsultAction::default(),
        }
    }
}

/// A lookup object that is returned when a blocklist entry is matched.
pub struct BlocklistLookup(Lookup);

impl LookupObject for BlocklistLookup {
    fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = &'a Record> + Send + 'a> {
        Box::new(self.0.record_iter())
    }

    fn take_additionals(&mut self) -> Option<Box<dyn LookupObject>> {
        None
    }
}

#[cfg(test)]
mod test {
    use std::{
        net::{Ipv4Addr, Ipv6Addr},
        path::Path,
        str::FromStr,
        sync::Arc,
    };
    use tracing::error;

    use crate::{
        authority::{AuthorityObject, LookupOptions, ZoneType},
        proto::rr::domain::Name,
        proto::rr::{
            LowerName, RData, RecordType,
            rdata::{A, AAAA},
        },
        store::blocklist::BlocklistConsultAction,
    };
    use test_support::subscribe;

    enum TestResult {
        Break,
        Skip,
    }

    #[tokio::test]
    async fn test_blocklist_basic() {
        subscribe();
        let config = super::BlocklistConfig {
            wildcard_match: true,
            min_wildcard_depth: 2,
            lists: vec!["default/blocklist.txt".to_string()],
            sinkhole_ipv4: None,
            sinkhole_ipv6: None,
            block_message: None,
            ttl: 86_400,
            consult_action: BlocklistConsultAction::Disabled,
        };

        let blocklist = super::BlocklistAuthority::try_from_config(
            Name::root(),
            ZoneType::External,
            &config,
            Some(Path::new("../../tests/test-data/test_configs/")),
        );

        let authority = blocklist.await;

        // Test: verify the blocklist authority was successfully created.
        match authority {
            Ok(ref _authority) => {}
            Err(e) => {
                panic!("Unable to create blocklist authority: {e}");
            }
        }

        let ao = Arc::new(authority.unwrap()) as Arc<dyn AuthorityObject>;

        let v4 = A::new(0, 0, 0, 0);
        let v6 = AAAA::new(0, 0, 0, 0, 0, 0, 0, 0);

        use RecordType::{A as Rec_A, AAAA as Rec_AAAA};
        use TestResult::*;
        // Test: lookup a record that is in the blocklist and that should match without a wildcard.
        basic_test(&ao, "foo.com.", Rec_A, Break, Some(v4), None, None).await;

        // test: lookup a record that is not in the blocklist. This test should fail.
        basic_test(&ao, "test.com.", Rec_A, Skip, None, None, None).await;

        // Test: lookup a record that will match a wildcard that is in the blocklist.
        basic_test(&ao, "www.foo.com.", Rec_A, Break, Some(v4), None, None).await;

        // Test: lookup a record that will match a wildcard that is in the blocklist.
        basic_test(&ao, "www.com.foo.com.", Rec_A, Break, Some(v4), None, None).await;

        // Test: lookup a record that is in the blocklist and that should match without a wildcard.
        basic_test(&ao, "foo.com.", Rec_AAAA, Break, None, Some(v6), None).await;

        // test: lookup a record that is not in the blocklist. This test should fail.
        basic_test(&ao, "test.com.", Rec_AAAA, Skip, None, None, None).await;

        // Test: lookup a record that will match a wildcard that is in the blocklist.
        basic_test(&ao, "www.foo.com.", Rec_AAAA, Break, None, Some(v6), None).await;

        // Test: lookup a record that will match a wildcard that is in the blocklist.
        basic_test(&ao, "ab.cd.foo.com.", Rec_AAAA, Break, None, Some(v6), None).await;
    }

    #[tokio::test]
    async fn test_blocklist_wildcard_disabled() {
        subscribe();
        let config = super::BlocklistConfig {
            min_wildcard_depth: 2,
            wildcard_match: false,
            lists: vec!["default/blocklist.txt".to_string()],
            sinkhole_ipv4: Some(Ipv4Addr::new(192, 0, 2, 1)),
            sinkhole_ipv6: Some(Ipv6Addr::new(0, 0, 0, 0, 0xc0, 0, 2, 1)),
            block_message: Some(String::from("blocked")),
            ttl: 86_400,
            consult_action: BlocklistConsultAction::Disabled,
        };

        let blocklist = super::BlocklistAuthority::try_from_config(
            Name::root(),
            ZoneType::External,
            &config,
            Some(Path::new("../../tests/test-data/test_configs/")),
        );

        let authority = blocklist.await;

        // Test: verify the blocklist authority was successfully created.
        match authority {
            Ok(ref _authority) => {}
            Err(e) => {
                panic!("Unable to create blocklist authority: {e}");
            }
        }

        let ao = Arc::new(authority.unwrap()) as Arc<dyn AuthorityObject>;

        let v4 = A::new(192, 0, 2, 1);
        let v6 = AAAA::new(0, 0, 0, 0, 0xc0, 0, 2, 1);
        let msg = config.block_message;

        use RecordType::{A as Rec_A, AAAA as Rec_AAAA};
        use TestResult::*;

        // Test: lookup a record that is in the blocklist and that should match without a wildcard.
        basic_test(&ao, "foo.com.", Rec_A, Break, Some(v4), None, msg.clone()).await;

        // Test: lookup a record that is not in the blocklist, but would match a wildcard; this
        // should fail.
        basic_test(&ao, "www.foo.com.", Rec_A, Skip, None, None, msg.clone()).await;

        // Test: lookup a record that is in the blocklist and that should match without a wildcard.
        basic_test(&ao, "foo.com.", Rec_AAAA, Break, None, Some(v6), msg).await;
    }

    #[tokio::test]
    #[should_panic]
    async fn test_blocklist_wrong_block_message() {
        subscribe();
        let config = super::BlocklistConfig {
            min_wildcard_depth: 2,
            wildcard_match: false,
            lists: vec!["default/blocklist.txt".to_string()],
            sinkhole_ipv4: Some(Ipv4Addr::new(192, 0, 2, 1)),
            sinkhole_ipv6: Some(Ipv6Addr::new(0, 0, 0, 0, 0xc0, 0, 2, 1)),
            block_message: Some(String::from("blocked")),
            ttl: 86_400,
            consult_action: BlocklistConsultAction::Disabled,
        };

        let blocklist = super::BlocklistAuthority::try_from_config(
            Name::root(),
            ZoneType::External,
            &config,
            Some(Path::new("../../tests/test-data/test_configs/")),
        );

        let authority = blocklist.await;

        // Test: verify the blocklist authority was successfully created.
        match authority {
            Ok(ref _authority) => {}
            Err(e) => {
                error!("Unable to create blocklist authority: {e}");
                return;
            }
        }

        let ao = Arc::new(authority.unwrap()) as Arc<dyn AuthorityObject>;

        let sinkhole_v4 = A::new(192, 0, 2, 1);

        // Test: lookup a record that is in the blocklist, but specify an incorrect block message to
        // match.
        basic_test(
            &ao,
            "foo.com.",
            RecordType::A,
            TestResult::Break,
            Some(sinkhole_v4),
            None,
            Some(String::from("wrong message")),
        )
        .await;
    }

    #[allow(clippy::borrowed_box)]
    async fn basic_test(
        ao: &Arc<dyn AuthorityObject>,
        query: &'static str,
        q_type: RecordType,
        r_type: TestResult,
        ipv4: Option<A>,
        ipv6: Option<AAAA>,
        msg: Option<String>,
    ) {
        let res = ao
            .lookup(
                &LowerName::from_str(query).unwrap(),
                q_type,
                LookupOptions::default(),
            )
            .await;

        use super::LookupControlFlow::*;

        match r_type {
            TestResult::Break => match res {
                Break(Ok(l)) => {
                    if !l.iter().all(|x| match x.record_type() {
                        RecordType::TXT => {
                            if let Some(msg) = &msg {
                                x.data().to_string() == *msg
                            } else {
                                false
                            }
                        }
                        RecordType::AAAA => {
                            let Some(rec_ip) = ipv6 else {
                                panic!("expected to validate record IPv6, but None was passed");
                            };

                            x.name() == &Name::from_str(query).unwrap()
                                && x.data() == &RData::AAAA(rec_ip)
                        }
                        _ => {
                            let Some(rec_ip) = ipv4 else {
                                panic!("expected to validate record IPv4, but None was passed");
                            };

                            x.name() == &Name::from_str(query).unwrap()
                                && x.data() == &RData::A(rec_ip)
                        }
                    }) {
                        panic!("{query} lookup data is incorrect.");
                    }
                }
                _ => panic!("Unexpected result for {query}: {res}"),
            },
            TestResult::Skip => match res {
                Skip => {}
                _ => {
                    panic!("unexpected result for {query}; expected Skip, found {res}");
                }
            },
        }
    }
}