blastdns 1.9.1

Async DNS lookup library for bulk/parallel DNS resolution
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
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
use std::collections::{HashMap, HashSet};
use std::str::FromStr;

use hickory_proto::op::{Header, Message, MessageType, OpCode, Query, ResponseCode};
use hickory_proto::rr::{Name, RData, Record, RecordType};
use hickory_proto::serialize::txt::RDataParser;
use hickory_proto::xfer::DnsResponse;
use regex::Regex;

use crate::error::BlastDNSError;
use crate::resolver::DnsResolver;
use crate::utils::format_ptr_query;

/// Mock DNS client for testing purposes.
#[derive(Clone, Debug)]
pub struct MockBlastDNSClient {
    mock_data: HashMap<String, HashMap<RecordType, Vec<String>>>,
    regex_patterns: Vec<(Regex, HashMap<RecordType, Vec<String>>)>,
    nxdomain_hosts: HashSet<String>,
    nxdomain_patterns: Vec<Regex>,
}

impl MockBlastDNSClient {
    /// Create a new mock client.
    pub fn new() -> Self {
        Self {
            mock_data: HashMap::new(),
            regex_patterns: Vec::new(),
            nxdomain_hosts: HashSet::new(),
            nxdomain_patterns: Vec::new(),
        }
    }

    /// Configure mock DNS responses.
    /// Takes responses (hostname -> record type -> answers) and a list of NXDOMAIN hosts.
    ///
    /// Hostnames prefixed with "regex:" will be treated as regex patterns.
    /// Examples:
    /// - "example.com" - exact match
    /// - "regex:.*\.example\.com" - matches any subdomain of example.com
    /// - "regex:test-\d+" - matches test-1, test-2, etc.
    pub fn mock_dns(
        &mut self,
        responses: HashMap<String, HashMap<String, Vec<String>>>,
        nxdomains: Vec<String>,
    ) {
        self.clear();

        for (host, records) in responses {
            if let Some(pattern) = host.strip_prefix("regex:") {
                // Regex pattern
                if let Ok(regex) = Regex::new(pattern) {
                    let mut record_map = HashMap::new();
                    for (record_type_str, answers) in records {
                        if let Ok(record_type) = RecordType::from_str(&record_type_str) {
                            record_map.insert(record_type, answers);
                        }
                    }
                    self.regex_patterns.push((regex, record_map));
                }
            } else {
                // Exact match
                for (record_type_str, answers) in records {
                    if let Ok(record_type) = RecordType::from_str(&record_type_str) {
                        self.mock_data
                            .entry(host.clone())
                            .or_default()
                            .insert(record_type, answers);
                    }
                }
            }
        }

        for host in nxdomains {
            if let Some(pattern) = host.strip_prefix("regex:") {
                // Regex pattern for NXDOMAIN
                if let Ok(regex) = Regex::new(pattern) {
                    self.nxdomain_patterns.push(regex);
                }
            } else {
                // Exact match for NXDOMAIN
                self.nxdomain_hosts.insert(host);
            }
        }
    }

    fn clear(&mut self) {
        self.mock_data.clear();
        self.regex_patterns.clear();
        self.nxdomain_hosts.clear();
        self.nxdomain_patterns.clear();
    }

    /// Resolve a hostname (mocked), returning full DNS response.
    /// Note: PTR formatting is handled by the trait implementation.
    async fn resolve_full_impl(
        &self,
        host: String,
        record_type: RecordType,
    ) -> Result<DnsResponse, BlastDNSError> {
        // Check if this host should return NXDOMAIN (exact match)
        if self.nxdomain_hosts.contains(&host) {
            return self.fabricate_nxdomain_response(&host, record_type);
        }

        // Check if this host matches any NXDOMAIN regex pattern
        for pattern in &self.nxdomain_patterns {
            if pattern.is_match(&host) {
                return self.fabricate_nxdomain_response(&host, record_type);
            }
        }

        // Check if we have exact match mock data for this host
        if let Some(host_data) = self.mock_data.get(&host)
            && let Some(answers_data) = host_data.get(&record_type)
        {
            return self.fabricate_response(&host, record_type, answers_data);
        }

        // Check if host matches any regex pattern
        for (pattern, record_map) in &self.regex_patterns {
            if pattern.is_match(&host)
                && let Some(answers_data) = record_map.get(&record_type)
            {
                return self.fabricate_response(&host, record_type, answers_data);
            }
        }

        // No mock data, return empty response
        self.fabricate_response(&host, record_type, &[])
    }

    fn fabricate_nxdomain_response(
        &self,
        host: &str,
        record_type: RecordType,
    ) -> Result<DnsResponse, BlastDNSError> {
        self.fabricate_response_with_code(host, record_type, &[], ResponseCode::NXDomain)
    }

    fn fabricate_response(
        &self,
        host: &str,
        record_type: RecordType,
        answers_data: &[String],
    ) -> Result<DnsResponse, BlastDNSError> {
        self.fabricate_response_with_code(host, record_type, answers_data, ResponseCode::NoError)
    }

    fn fabricate_response_with_code(
        &self,
        host: &str,
        record_type: RecordType,
        answers_data: &[String],
        response_code: ResponseCode,
    ) -> Result<DnsResponse, BlastDNSError> {
        // Ensure host has trailing dot (FQDN format)
        let fqdn = if host.ends_with('.') {
            host.to_string()
        } else {
            format!("{host}.")
        };

        let name = Name::from_str(&fqdn)
            .map_err(|e| BlastDNSError::Configuration(format!("invalid name: {e}")))?;

        // Create answer records
        let mut answers = Vec::new();
        for rdata_str in answers_data {
            if let Some(rdata) = self.parse_rdata(record_type, rdata_str)? {
                let record = Record::from_rdata(name.clone(), 300, rdata);
                answers.push(record);
            }
        }

        // Fabricate header
        let mut header = Header::new();
        header.set_id(12345);
        header.set_message_type(MessageType::Response);
        header.set_op_code(OpCode::Query);
        header.set_authoritative(false);
        header.set_truncated(false);
        header.set_recursion_desired(true);
        header.set_recursion_available(true);
        header.set_authentic_data(false);
        header.set_checking_disabled(false);
        header.set_response_code(response_code);

        // Fabricate query
        let query = Query::query(name, record_type);

        // Build message
        let mut message = Message::new();
        message.set_header(header);
        message.add_query(query);
        for answer in answers {
            message.add_answer(answer);
        }

        DnsResponse::from_message(message)
            .map_err(|e| BlastDNSError::Configuration(format!("failed to create response: {e}")))
    }

    fn parse_rdata(
        &self,
        record_type: RecordType,
        rdata_str: &str,
    ) -> Result<Option<RData>, BlastDNSError> {
        // Mock inputs are zone-file format, no exceptions. Hand off to hickory's
        // zone-format parser, which handles A, AAAA, CNAME, NS, PTR, MX, SOA,
        // SRV, TXT, CAA, NAPTR, SVCB, HTTPS, TLSA, and the rest in one call.
        RData::try_from_str(record_type, rdata_str)
            .map(Some)
            .map_err(|e| {
                BlastDNSError::Configuration(format!(
                    "invalid mock {record_type} record `{rdata_str}`: {e}"
                ))
            })
    }
}

impl Default for MockBlastDNSClient {
    fn default() -> Self {
        Self::new()
    }
}

// Implement the DnsResolver trait
impl DnsResolver for MockBlastDNSClient {
    fn resolve_full(
        &self,
        mut host: String,
        record_type: RecordType,
    ) -> impl std::future::Future<Output = Result<DnsResponse, BlastDNSError>> + Send {
        // Auto-format PTR queries if an IP address is provided
        if record_type == RecordType::PTR {
            host = format_ptr_query(&host);
        }

        self.resolve_full_impl(host, record_type)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use hickory_client::proto::rr::RecordType;

    fn create_test_mock_client() -> MockBlastDNSClient {
        let mut client = MockBlastDNSClient::new();

        let responses = HashMap::from([
            (
                "example.com".to_string(),
                HashMap::from([
                    ("A".to_string(), vec!["93.184.216.34".to_string()]),
                    (
                        "AAAA".to_string(),
                        vec!["2606:2800:220:1:248:1893:25c8:1946".to_string()],
                    ),
                    (
                        "MX".to_string(),
                        vec![
                            "10 aspmx.l.google.com.".to_string(),
                            "20 alt1.aspmx.l.google.com.".to_string(),
                        ],
                    ),
                ]),
            ),
            (
                "cname.example.com".to_string(),
                HashMap::from([("CNAME".to_string(), vec!["example.com.".to_string()])]),
            ),
        ]);

        let nxdomains = vec!["notfound.example.com".to_string()];

        client.mock_dns(responses, nxdomains);
        client
    }

    #[tokio::test]
    async fn test_resolve_a_record() {
        let client = create_test_mock_client();
        let result = client
            .resolve("example.com".to_string(), RecordType::A)
            .await;

        assert!(result.is_ok());
        let answers = result.unwrap();
        assert_eq!(answers.len(), 1);
        assert_eq!(answers[0], "93.184.216.34");
    }

    #[tokio::test]
    async fn test_resolve_mx_records() {
        let client = create_test_mock_client();
        let result = client
            .resolve("example.com".to_string(), RecordType::MX)
            .await;

        assert!(result.is_ok());
        let answers = result.unwrap();
        assert_eq!(answers.len(), 2);
        assert!(answers.contains(&"10 aspmx.l.google.com.".to_string()));
        assert!(answers.contains(&"20 alt1.aspmx.l.google.com.".to_string()));
    }

    #[tokio::test]
    async fn test_resolve_nxdomain() {
        let client = create_test_mock_client();
        let result = client
            .resolve("notfound.example.com".to_string(), RecordType::A)
            .await;

        assert!(result.is_ok());
        let answers = result.unwrap();
        assert_eq!(answers.len(), 0, "NXDOMAIN should return empty list");
    }

    #[tokio::test]
    async fn test_resolve_unknown_host() {
        let client = create_test_mock_client();
        let result = client
            .resolve("unknown.example.com".to_string(), RecordType::A)
            .await;

        assert!(result.is_ok());
        let answers = result.unwrap();
        assert_eq!(answers.len(), 0, "Unknown host should return empty list");
    }

    #[tokio::test]
    async fn test_resolve_full_with_answers() {
        let client = create_test_mock_client();
        let result = client
            .resolve_full("example.com".to_string(), RecordType::A)
            .await;

        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.answers().len(), 1);
        assert_eq!(response.answers()[0].data().to_string(), "93.184.216.34");
    }

    #[tokio::test]
    async fn test_resolve_full_nxdomain() {
        let client = create_test_mock_client();
        let result = client
            .resolve_full("notfound.example.com".to_string(), RecordType::A)
            .await;

        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(
            response.answers().len(),
            0,
            "NXDOMAIN should return empty response"
        );
    }

    #[tokio::test]
    async fn test_resolve_multi() {
        let client = create_test_mock_client();
        let record_types = vec![RecordType::A, RecordType::AAAA, RecordType::MX];
        let result = client
            .resolve_multi("example.com".to_string(), record_types)
            .await;

        assert!(result.is_ok());
        let results = result.unwrap();
        assert_eq!(results.len(), 3);
        assert!(results.contains_key(&RecordType::A));
        assert!(results.contains_key(&RecordType::AAAA));
        assert!(results.contains_key(&RecordType::MX));
        assert_eq!(results[&RecordType::MX].len(), 2);
    }

    #[tokio::test]
    async fn test_resolve_multi_partial_mocking() {
        let client = create_test_mock_client();
        let record_types = vec![RecordType::A, RecordType::TXT];
        let result = client
            .resolve_multi("example.com".to_string(), record_types)
            .await;

        assert!(result.is_ok());
        let results = result.unwrap();
        // Only A should be in results (TXT has no mock data)
        assert_eq!(results.len(), 1);
        assert!(results.contains_key(&RecordType::A));
        assert!(!results.contains_key(&RecordType::TXT));
    }

    #[tokio::test]
    async fn test_resolve_multi_nxdomain() {
        let client = create_test_mock_client();
        let record_types = vec![RecordType::A, RecordType::AAAA];
        let result = client
            .resolve_multi("notfound.example.com".to_string(), record_types)
            .await;

        assert!(result.is_ok());
        let results = result.unwrap();
        assert_eq!(results.len(), 0, "NXDOMAIN should return empty results");
    }

    #[tokio::test]
    async fn test_resolve_multi_full() {
        let client = create_test_mock_client();
        let record_types = vec![RecordType::A, RecordType::AAAA, RecordType::MX];
        let result = client
            .resolve_multi_full("example.com".to_string(), record_types)
            .await;

        assert!(result.is_ok());
        let results = result.unwrap();
        assert_eq!(results.len(), 3);

        // All should be successful
        for result in results.values() {
            assert!(result.is_ok());
        }

        // Check MX has multiple answers
        let mx_result = &results[&RecordType::MX];
        assert!(mx_result.is_ok());
        let mx_response = mx_result.as_ref().unwrap();
        assert_eq!(mx_response.answers().len(), 2);
    }

    #[tokio::test]
    async fn test_resolve_multi_full_with_nxdomain() {
        let client = create_test_mock_client();
        let record_types = vec![RecordType::A];
        let result = client
            .resolve_multi_full("notfound.example.com".to_string(), record_types)
            .await;

        assert!(result.is_ok());
        let results = result.unwrap();
        assert_eq!(results.len(), 1);

        let a_result = &results[&RecordType::A];
        assert!(
            a_result.is_ok(),
            "NXDOMAIN should return Ok with empty response"
        );
        let response = a_result.as_ref().unwrap();
        assert_eq!(response.answers().len(), 0);
    }

    #[tokio::test]
    async fn test_ptr_auto_format_ipv4() {
        let mut client = MockBlastDNSClient::new();

        let responses = HashMap::from([(
            "8.8.8.8.in-addr.arpa".to_string(),
            HashMap::from([("PTR".to_string(), vec!["dns.google.".to_string()])]),
        )]);
        client.mock_dns(responses, vec![]);

        // Query with raw IP - should be auto-formatted
        let result = client.resolve("8.8.8.8".to_string(), RecordType::PTR).await;
        assert!(result.is_ok());
        let answers = result.unwrap();
        assert_eq!(answers.len(), 1);
        assert_eq!(answers[0], "dns.google.");

        // Query with already-formatted string should also work
        let result2 = client
            .resolve("8.8.8.8.in-addr.arpa".to_string(), RecordType::PTR)
            .await;
        assert!(result2.is_ok());
        assert_eq!(result2.unwrap(), answers);
    }

    #[tokio::test]
    async fn test_ptr_auto_format_ipv6() {
        let mut client = MockBlastDNSClient::new();

        let responses = HashMap::from([(
            "8.8.8.8.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.6.8.4.0.6.8.4.1.0.0.2.ip6.arpa".to_string(),
            HashMap::from([("PTR".to_string(), vec!["dns.google.".to_string()])]),
        )]);
        client.mock_dns(responses, vec![]);

        // Query with IPv6 address - should be auto-formatted
        let result = client
            .resolve("2001:4860:4860::8888".to_string(), RecordType::PTR)
            .await;
        assert!(result.is_ok());
        let answers = result.unwrap();
        assert_eq!(answers.len(), 1);
        assert_eq!(answers[0], "dns.google.");
    }

    #[test]
    fn test_mock_dns() {
        let mut client = MockBlastDNSClient::new();

        let responses = HashMap::from([(
            "test.com".to_string(),
            HashMap::from([
                (
                    "A".to_string(),
                    vec!["1.2.3.4".to_string(), "5.6.7.8".to_string()],
                ),
                ("AAAA".to_string(), vec!["2001:db8::1".to_string()]),
            ]),
        )]);

        let nxdomains = vec!["bad.com".to_string(), "notfound.com".to_string()];

        client.mock_dns(responses, nxdomains);

        // Verify the data was loaded
        assert!(client.mock_data.contains_key("test.com"));
        assert_eq!(client.nxdomain_hosts.len(), 2);
        assert!(client.nxdomain_hosts.contains("bad.com"));
        assert!(client.nxdomain_hosts.contains("notfound.com"));
    }

    #[tokio::test]
    async fn test_cname_record() {
        let client = create_test_mock_client();
        let result = client
            .resolve("cname.example.com".to_string(), RecordType::CNAME)
            .await;

        assert!(result.is_ok());
        let answers = result.unwrap();
        assert_eq!(answers.len(), 1);
        assert_eq!(answers[0], "example.com.");
    }

    #[tokio::test]
    async fn test_empty_response_structure() {
        let client = create_test_mock_client();
        let result = client
            .resolve_full("unknown.example.com".to_string(), RecordType::A)
            .await;

        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.answers().len(), 0);
        assert_eq!(response.response_code().to_string(), "No Error");
        assert_eq!(response.queries().len(), 1);
    }

    #[tokio::test]
    async fn test_regex_wildcard_subdomain() {
        let mut client = MockBlastDNSClient::new();

        let responses = HashMap::from([(
            "regex:.*\\.example\\.com".to_string(),
            HashMap::from([("A".to_string(), vec!["192.168.1.1".to_string()])]),
        )]);

        client.mock_dns(responses, vec![]);

        // Should match any subdomain
        let result = client
            .resolve("api.example.com".to_string(), RecordType::A)
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec!["192.168.1.1"]);

        let result = client
            .resolve("cdn.example.com".to_string(), RecordType::A)
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec!["192.168.1.1"]);

        let result = client
            .resolve("sub.domain.example.com".to_string(), RecordType::A)
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec!["192.168.1.1"]);

        // Should not match the base domain
        let result = client
            .resolve("example.com".to_string(), RecordType::A)
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 0);
    }

    #[tokio::test]
    async fn test_regex_numeric_pattern() {
        let mut client = MockBlastDNSClient::new();

        let responses = HashMap::from([(
            "regex:^server-\\d+\\.test\\.com$".to_string(),
            HashMap::from([("A".to_string(), vec!["10.0.0.1".to_string()])]),
        )]);

        client.mock_dns(responses, vec![]);

        // Should match numbered servers
        let result = client
            .resolve("server-1.test.com".to_string(), RecordType::A)
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec!["10.0.0.1"]);

        let result = client
            .resolve("server-42.test.com".to_string(), RecordType::A)
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec!["10.0.0.1"]);

        // Should not match non-numeric
        let result = client
            .resolve("server-abc.test.com".to_string(), RecordType::A)
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 0);
    }

    #[tokio::test]
    async fn test_regex_nxdomain_pattern() {
        let mut client = MockBlastDNSClient::new();

        let responses = HashMap::from([(
            "good.example.com".to_string(),
            HashMap::from([("A".to_string(), vec!["1.2.3.4".to_string()])]),
        )]);

        let nxdomains = vec!["regex:^bad-.*\\.example\\.com$".to_string()];

        client.mock_dns(responses, nxdomains);

        // Should return NXDOMAIN for matching pattern
        let result = client
            .resolve("bad-host.example.com".to_string(), RecordType::A)
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 0);

        let result = client
            .resolve("bad-server.example.com".to_string(), RecordType::A)
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 0);

        // Should return normal result for non-matching
        let result = client
            .resolve("good.example.com".to_string(), RecordType::A)
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec!["1.2.3.4"]);
    }

    #[tokio::test]
    async fn test_regex_exact_match_priority() {
        let mut client = MockBlastDNSClient::new();

        let responses = HashMap::from([
            (
                "specific.example.com".to_string(),
                HashMap::from([("A".to_string(), vec!["10.0.0.1".to_string()])]),
            ),
            (
                "regex:.*\\.example\\.com".to_string(),
                HashMap::from([("A".to_string(), vec!["192.168.1.1".to_string()])]),
            ),
        ]);

        client.mock_dns(responses, vec![]);

        // Exact match should take priority
        let result = client
            .resolve("specific.example.com".to_string(), RecordType::A)
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec!["10.0.0.1"]);

        // Regex should match others
        let result = client
            .resolve("other.example.com".to_string(), RecordType::A)
            .await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec!["192.168.1.1"]);
    }
}