Skip to main content

hickory_resolver/
caching_client.rs

1// Copyright 2015-2023 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! Caching related functionality for the Resolver.
9
10use std::{
11    borrow::Cow,
12    future::Future,
13    time::{Duration, Instant},
14};
15
16use once_cell::sync::Lazy;
17
18#[cfg(feature = "__dnssec")]
19use crate::proto::dnssec::{DnssecSummary, Proof};
20use crate::{
21    cache::{MAX_TTL, ResponseCache, TtlConfig},
22    lookup::Lookup,
23    net::{
24        DnsError, NetError, NoRecords,
25        xfer::{DnsHandle, FirstAnswer},
26    },
27    proto::{
28        op::{DnsRequestOptions, DnsResponse, Message, OpCode, Query, ResponseCode},
29        rr::{
30            DNSClass, Name, RData, Record, RecordRef, RecordType,
31            domain::usage::{
32                DEFAULT, IN_ADDR_ARPA_127, INVALID, IP6_ARPA_1, LOCAL,
33                LOCALHOST as LOCALHOST_usage, ONION, ResolverUsage,
34            },
35            rdata::{A, AAAA, CNAME, PTR},
36        },
37    },
38};
39
40static LOCALHOST: Lazy<RData> =
41    Lazy::new(|| RData::PTR(PTR(Name::from_ascii("localhost.").unwrap())));
42static LOCALHOST_V4: Lazy<RData> = Lazy::new(|| RData::A(A::new(127, 0, 0, 1)));
43static LOCALHOST_V6: Lazy<RData> = Lazy::new(|| RData::AAAA(AAAA::new(0, 0, 0, 0, 0, 0, 0, 1)));
44
45/// Counts the depth of CNAME query resolutions.
46#[derive(Default, Clone, Copy)]
47struct DepthTracker {
48    query_depth: u8,
49}
50
51impl DepthTracker {
52    fn nest(self) -> Self {
53        Self {
54            query_depth: self.query_depth + 1,
55        }
56    }
57
58    fn is_exhausted(self) -> bool {
59        self.query_depth + 1 >= Self::MAX_QUERY_DEPTH
60    }
61
62    const MAX_QUERY_DEPTH: u8 = 8; // arbitrarily chosen number...
63}
64
65#[derive(Clone, Debug)]
66#[doc(hidden)]
67pub struct CachingClient<C>
68where
69    C: DnsHandle,
70{
71    cache: ResponseCache,
72    client: C,
73    preserve_intermediates: bool,
74    #[cfg(feature = "metrics")]
75    cache_metrics: crate::metrics::CacheMetrics,
76}
77
78impl<C> CachingClient<C>
79where
80    C: DnsHandle + Send + 'static,
81{
82    #[doc(hidden)]
83    pub fn new(max_size: u64, client: C, preserve_intermediates: bool) -> Self {
84        Self::with_cache(
85            ResponseCache::new(max_size, TtlConfig::default()),
86            client,
87            preserve_intermediates,
88        )
89    }
90
91    pub(crate) fn with_cache(
92        cache: ResponseCache,
93        client: C,
94        preserve_intermediates: bool,
95    ) -> Self {
96        Self {
97            cache,
98            client,
99            preserve_intermediates,
100            #[cfg(feature = "metrics")]
101            cache_metrics: crate::metrics::CacheMetrics::default(),
102        }
103    }
104
105    /// Perform a lookup against this caching client, looking first in the cache for a result
106    pub fn lookup(
107        &self,
108        query: Query,
109        options: DnsRequestOptions,
110    ) -> impl Future<Output = Result<Lookup, NetError>> {
111        Self::inner_lookup(
112            query,
113            options,
114            self.clone(),
115            vec![],
116            DepthTracker::default(),
117        )
118    }
119
120    async fn inner_lookup(
121        query: Query,
122        options: DnsRequestOptions,
123        mut client: Self,
124        preserved_records: Vec<Record>,
125        depth: DepthTracker,
126    ) -> Result<Lookup, NetError> {
127        // see https://tools.ietf.org/html/rfc6761
128        //
129        // ```text
130        // Name resolution APIs and libraries SHOULD recognize localhost
131        // names as special and SHOULD always return the IP loopback address
132        // for address queries and negative responses for all other query
133        // types.  Name resolution APIs SHOULD NOT send queries for
134        // localhost names to their configured caching DNS server(s).
135        // ```
136        // special use rules only apply to the IN Class
137        if query.query_class() == DNSClass::IN {
138            let usage = match query.name() {
139                n if LOCALHOST_usage.zone_of(n) => &*LOCALHOST_usage,
140                n if IN_ADDR_ARPA_127.zone_of(n) => &*LOCALHOST_usage,
141                n if IP6_ARPA_1.zone_of(n) => &*LOCALHOST_usage,
142                n if INVALID.zone_of(n) => &*INVALID,
143                n if LOCAL.zone_of(n) => &*LOCAL,
144                n if ONION.zone_of(n) => &*ONION,
145                _ => &*DEFAULT,
146            };
147
148            match usage.resolver() {
149                ResolverUsage::Loopback => match query.query_type() {
150                    // TODO: look in hosts for these ips/names first...
151                    RecordType::A => return Ok(Lookup::from_rdata(query, LOCALHOST_V4.clone())),
152                    RecordType::AAAA => return Ok(Lookup::from_rdata(query, LOCALHOST_V6.clone())),
153                    RecordType::PTR => return Ok(Lookup::from_rdata(query, LOCALHOST.clone())),
154                    // Are there any other types we can use?
155                    _ => return Err(NoRecords::new(query, ResponseCode::NoError).into()),
156                },
157                // TODO: this requires additional config, as Kubernetes and other systems misuse the .local. zone.
158                // when mdns is not enabled we will return errors on LinkLocal ("*.local.") names
159                ResolverUsage::LinkLocal => (),
160                ResolverUsage::NxDomain => {
161                    return Err(NoRecords::new(query, ResponseCode::NXDomain).into());
162                }
163                ResolverUsage::Normal => (),
164            }
165        }
166
167        let is_dnssec = client.client.is_verifying_dnssec();
168
169        #[cfg(feature = "metrics")]
170        let request_start = Instant::now();
171
172        if let Some(cached_lookup) = client.lookup_from_cache(&query) {
173            #[cfg(feature = "metrics")]
174            {
175                client.cache_metrics.cache_hit.increment(1);
176                client
177                    .cache_metrics
178                    .cache_hit_duration
179                    .record(request_start.elapsed());
180                client
181                    .cache_metrics
182                    .cache_size
183                    .set(client.cache.entry_count() as f64);
184            }
185            return cached_lookup;
186        };
187
188        #[cfg(feature = "metrics")]
189        client.cache_metrics.cache_miss.increment(1);
190
191        let response_message = client
192            .client
193            .lookup(query.clone(), options)
194            .first_answer()
195            .await;
196
197        // TODO: technically this might be duplicating work, as name_server already performs this evaluation.
198        //  we may want to create a new type, if evaluated... but this is most generic to support any impl in LookupState...
199        let response_message = if let Ok(response) = response_message {
200            DnsError::from_response(response).map_err(NetError::from)
201        } else {
202            response_message
203        };
204
205        // TODO: This doesn't yet take into account the CD flag. There is not yet a way to pass it
206        // from the ForwarderZoneHandler, through the Resolver public API, to here.
207        #[cfg(feature = "__dnssec")]
208        if is_dnssec {
209            let summary_opt = match &response_message {
210                Ok(response) => Some(DnssecSummary::from_records(response.answers.iter())),
211                Err(NetError::Dns(DnsError::Nsec {
212                    response, proof, ..
213                })) => Some(if *proof == Proof::Bogus {
214                    DnssecSummary::Bogus
215                } else {
216                    DnssecSummary::from_records(response.authorities.iter())
217                }),
218                _ => None,
219            };
220            if let Some(DnssecSummary::Bogus) = summary_opt {
221                #[cfg(feature = "metrics")]
222                client
223                    .cache_metrics
224                    .cache_miss_duration
225                    .record(request_start.elapsed());
226                return Err(NetError::Dns(DnsError::DnssecBogus));
227            }
228        }
229
230        // TODO: take all records and cache them?
231        //  if it's DNSSEC they must be signed, otherwise?
232        let records = match response_message {
233            Ok(response_message) => {
234                // allow the handle_noerror function to deal with any error codes
235                let records = match Self::handle_noerror(
236                    &mut client,
237                    options,
238                    &query,
239                    response_message,
240                    preserved_records,
241                    depth,
242                ) {
243                    Ok(records) => records,
244                    Err(err) => {
245                        #[cfg(feature = "metrics")]
246                        client
247                            .cache_metrics
248                            .cache_miss_duration
249                            .record(request_start.elapsed());
250                        return Err(err);
251                    }
252                };
253
254                Ok(records)
255            }
256            // this is the only cacheable form
257            Err(NetError::Dns(DnsError::NoRecordsFound(mut no_records))) => {
258                if is_dnssec {
259                    no_records.negative_ttl = None;
260                }
261                Err(no_records.into())
262            }
263            Err(err) => {
264                #[cfg(feature = "metrics")]
265                client
266                    .cache_metrics
267                    .cache_miss_duration
268                    .record(request_start.elapsed());
269                return Err(err);
270            }
271        };
272
273        // after the request, evaluate if we have additional queries to perform
274        let result = match records {
275            Ok(Records::CnameChain { next: future, .. }) => match future.await {
276                Ok(lookup) => client.cname(lookup, query),
277                Err(e) => client.cache(query, Err(e)),
278            },
279            Ok(Records::Exists { message }) => client.cache(query, Ok(message)),
280            Err(e) => client.cache(query, Err(e)),
281        };
282
283        #[cfg(feature = "metrics")]
284        client
285            .cache_metrics
286            .cache_miss_duration
287            .record(request_start.elapsed());
288
289        result
290    }
291
292    /// Check if this query is already cached
293    fn lookup_from_cache(&self, query: &Query) -> Option<Result<Lookup, NetError>> {
294        let now = Instant::now();
295        let message_res = self.cache.get(query, now)?;
296        let message = match message_res {
297            Ok(message) => message,
298            Err(err) => return Some(Err(err)),
299        };
300
301        let valid_until = now
302            + Duration::from_secs(
303                message
304                    .answers
305                    .iter()
306                    .map(|r| r.ttl)
307                    .min()
308                    .unwrap_or(MAX_TTL)
309                    .into(),
310            );
311
312        Some(Ok(Lookup::new(message, valid_until)))
313    }
314
315    /// Handle the case where there is no error returned
316    fn handle_noerror(
317        client: &mut Self,
318        options: DnsRequestOptions,
319        query: &Query,
320        response: DnsResponse,
321        mut preserved_records: Vec<Record>,
322        depth: DepthTracker,
323    ) -> Result<Records<impl Future<Output = Result<Lookup, NetError>>>, NetError> {
324        // TODO: there should be a ResolverOpts config to disable the
325        // name validation in this function to more closely match the
326        // behaviour of glibc if that's what the user expects.
327
328        // initial ttl is what CNAMES use for min usage
329        const INITIAL_TTL: u32 = MAX_TTL;
330
331        // need to capture these before the subsequent and destructive record processing
332        let soa = response.soa().as_ref().map(RecordRef::to_owned);
333        let negative_ttl = response.negative_ttl();
334        let response_code = response.response_code;
335
336        // seek out CNAMES, this is only performed if the query is not a CNAME or ANY
337        let (search_name, was_cname, preserved_records) = {
338            // this will only search for CNAMEs if the request was not meant to be for one of the triggers for recursion
339            let (search_name, cname_ttl, was_cname) =
340                if query.query_type().is_any() || query.query_type().is_cname() {
341                    (Cow::Borrowed(query.name()), INITIAL_TTL, false)
342                } else {
343                    // Folds any cnames from the answers section, into the final cname in the answers section
344                    //   this works by folding the last CNAME found into the final folded result.
345                    //   it assumes that the CNAMEs are in chained order in the DnsResponse Message...
346                    //
347                    // TODO: should this include the additionals?
348                    response.answers.iter().fold(
349                        (Cow::Borrowed(query.name()), INITIAL_TTL, false),
350                        |(search_name, cname_ttl, was_cname), r| {
351                            if let RData::CNAME(CNAME(cname)) = &r.data {
352                                // take the minimum TTL of the cname_ttl and the next record in the chain
353                                let ttl = cname_ttl.min(r.ttl);
354                                debug_assert_eq!(r.record_type(), RecordType::CNAME);
355                                if search_name.as_ref() == &r.name {
356                                    return (Cow::Owned(cname.clone()), ttl, true);
357                                }
358                            }
359
360                            (search_name, cname_ttl, was_cname)
361                        },
362                    )
363                };
364
365            // take all answers. // TODO: following CNAMES?
366            let mut message = response.into_message();
367
368            // set of names that still require resolution
369            // TODO: this needs to be enhanced for SRV
370            let mut found_name = false;
371            let mut found_cname_target = false;
372            // Scan through all sections to determine what we found.
373            // We need this first pass to decide our strategy: return complete message vs filter
374            for r in message.all_sections() {
375                // restrict to the RData type requested
376                if query.query_class() != r.dns_class {
377                    continue;
378                }
379
380                // standard evaluation, it's an any type, or it's the requested type and the
381                // search_name matches
382                let type_matches =
383                    query.query_type().is_any() || query.query_type() == r.record_type();
384                let name_matches = search_name.as_ref() == &r.name || query.name() == &r.name;
385                if type_matches && name_matches {
386                    found_name = true;
387                    // Track if we found the CNAME target (not just the original name)
388                    if was_cname && search_name.as_ref() == &r.name {
389                        found_cname_target = true;
390                    }
391                }
392            }
393
394            // After following all the CNAMES to the last one, try and lookup the final name
395            if found_name && (!was_cname || preserved_records.is_empty()) {
396                // Decide strategy: do we need to filter, or return the message as-is?
397                // - If we have accumulated records from previous CNAME hops → must filter and merge
398                // - If we found the CNAME target in this response → filter out intermediate CNAMEs
399                //   (unless preserve_intermediates)
400                // - Otherwise → return complete message to preserve all sections exactly as DNS server
401                //   sent them
402                let needs_filtering = !preserved_records.is_empty()
403                    || (found_cname_target && !client.preserve_intermediates);
404
405                if needs_filtering {
406                    // Filter records that belong in ANSWER section only
407                    // Don't include records from ADDITIONAL/AUTHORITY here - they're preserved as-is below
408                    preserved_records.extend(message.all_sections().filter_map(|r| {
409                        // because this resolved potentially recursively, we want the min TTL from the chain
410                        let ttl = cname_ttl.min(r.ttl);
411                        let mut r = r.clone();
412                        r.ttl = ttl;
413
414                        // restrict to the RData type requested
415                        if query.query_class() != r.dns_class {
416                            return None;
417                        }
418
419                        // standard evaluation, it's an any type, or it's the requested type
420                        // and the search_name matches
421                        let query_type = query.query_type();
422                        let record_type = r.record_type();
423                        let type_matches = query_type.is_any() || query_type == record_type;
424                        let name_matches =
425                            search_name.as_ref() == &r.name || query.name() == &r.name;
426                        if type_matches && name_matches {
427                            return Some(r);
428                        }
429
430                        // CNAME evaluation, the record is from the CNAME lookup chain.
431                        if client.preserve_intermediates && record_type == RecordType::CNAME {
432                            return Some(r);
433                        }
434
435                        // Note: NS glue and SRV target IPs are NOT included here
436                        // They belong in ADDITIONAL section and are preserved below via insert_additionals
437                        None
438                    }));
439
440                    // Replace ANSWER section with filtered records, preserve AUTHORITY and ADDITIONAL sections
441                    message.answers = preserved_records;
442                }
443
444                // Strip DNSSEC records if DO bit is not set.
445                message = message.maybe_strip_dnssec_records(options.edns_set_dnssec_ok);
446
447                return Ok(Records::Exists { message });
448            }
449
450            // We didn't find the answer - need to continue following CNAME chain
451            // Only accumulate ANSWER-section records (CNAMEs) for next hop
452            // AUTHORITY and ADDITIONAL records stay with their original message and are not carried forward
453            preserved_records.extend(message.take_all_sections().filter_map(|mut r| {
454                // because this resolved potentially recursively, we want the min TTL from the chain
455                r.ttl = cname_ttl.min(r.ttl);
456
457                // restrict to the RData type requested
458                if query.query_class() != r.dns_class {
459                    return None;
460                }
461
462                // CNAME evaluation, the record is from the CNAME lookup chain.
463                if client.preserve_intermediates && r.record_type() == RecordType::CNAME {
464                    return Some(r);
465                }
466
467                // Note: NS glue and SRV target IPs are NOT accumulated across hops
468                // They belong in ADDITIONAL section of their original response, not in ANSWER
469                None
470            }));
471
472            (search_name.into_owned(), was_cname, preserved_records)
473        };
474
475        // TODO: for SRV records we *could* do an implicit lookup, but, this requires knowing the type of IP desired
476        //    for now, we'll make the API require the user to perform a follow up to the lookups.
477        // It was a CNAME, but not included in the request...
478        if was_cname && !depth.is_exhausted() {
479            let next_query = Query::query(search_name, query.query_type());
480            Ok(Records::CnameChain {
481                next: Box::pin(Self::inner_lookup(
482                    next_query,
483                    options,
484                    client.clone(),
485                    #[cfg(test)]
486                    preserved_records.clone(),
487                    #[cfg(not(test))]
488                    preserved_records,
489                    depth.nest(),
490                )),
491                #[cfg(test)]
492                preserved_records,
493            })
494        } else {
495            // TODO: review See https://tools.ietf.org/html/rfc2308 for NoData section
496            // Note on DNSSEC, in secure_client_handle, if verify_nsec fails then the request fails.
497            //   this will mean that no unverified negative caches will make it to this point and be stored
498            let mut new = NoRecords::new(query.clone(), response_code);
499            new.soa = soa.map(Box::new);
500            new.negative_ttl = negative_ttl;
501            Err(new.into())
502        }
503    }
504
505    #[allow(clippy::unnecessary_wraps)]
506    fn cname(&self, lookup: Lookup, query: Query) -> Result<Lookup, NetError> {
507        let mut message = Message::response(0, OpCode::Query);
508        message.add_query(query.clone());
509        message.add_answers(lookup.answers().iter().cloned());
510        message.add_authorities(lookup.authorities().iter().cloned());
511        message.add_additionals(lookup.additionals().iter().cloned());
512        self.cache.insert(query, Ok(message), Instant::now());
513        Ok(lookup)
514    }
515
516    fn cache(&self, query: Query, result: Result<Message, NetError>) -> Result<Lookup, NetError> {
517        let now = Instant::now();
518        let result = match result {
519            Ok(mut message) => {
520                // Clamp record TTLs before building the Lookup so that the first
521                // response to the client reflects positive_min/max_ttl, not the
522                // raw upstream TTL.
523                let ttl = self
524                    .cache
525                    .clamp_positive_ttls(query.query_type(), &mut message);
526                let valid_until = now + ttl;
527                let lookup = Lookup::new(message.clone(), valid_until);
528                self.cache.insert(query, Ok(message), now);
529                Ok(lookup)
530            }
531            Err(err) => {
532                self.cache.insert(query, Err(err.clone()), now);
533                Err(err)
534            }
535        };
536        #[cfg(feature = "metrics")]
537        self.cache_metrics
538            .cache_size
539            .set(self.cache.entry_count() as f64);
540        result
541    }
542
543    /// Flushes/Removes all entries from the cache
544    pub fn clear_cache(&self) {
545        self.cache.clear();
546    }
547
548    /// Flushes/Removes the entry from the cache that is associated with this query
549    pub fn clear_cache_query(&self, query: &Query) {
550        self.cache.clear_query(query);
551    }
552}
553
554enum Records<F> {
555    /// The records exist, stored as a complete DNS Message
556    Exists { message: Message },
557    /// Future lookup for recursive cname records
558    CnameChain {
559        next: F,
560        #[cfg(test)]
561        preserved_records: Vec<Record>,
562    },
563}
564
565// see also the lookup_tests.rs in integration-tests crate
566#[cfg(test)]
567mod tests {
568    use std::net::{Ipv4Addr, Ipv6Addr};
569    use std::str::FromStr;
570    use std::time::{Duration, Instant};
571
572    use futures_executor::block_on;
573    use test_support::subscribe;
574
575    use super::*;
576    use crate::cache::TtlConfig;
577    use crate::lookup_ip::tests::{empty, error, mock, v4_message};
578    use crate::proto::op::{Message, Query};
579    use crate::proto::rr::rdata::{NS, SRV};
580    use crate::proto::rr::{Name, Record};
581
582    #[test]
583    fn test_empty_cache() {
584        subscribe();
585        let cache = ResponseCache::new(1, TtlConfig::default());
586        let client = mock(vec![empty()]);
587        let client = CachingClient::with_cache(cache, client, false);
588
589        let error = block_on(CachingClient::inner_lookup(
590            Query::new(),
591            DnsRequestOptions::default(),
592            client,
593            vec![],
594            DepthTracker::default(),
595        ))
596        .unwrap_err();
597
598        let NetError::Dns(DnsError::NoRecordsFound(no_records)) = error else {
599            panic!("wrong error received")
600        };
601
602        assert_eq!(no_records.query, Box::new(Query::new()));
603        assert_eq!(no_records.negative_ttl, None);
604    }
605
606    #[test]
607    fn test_from_cache() {
608        subscribe();
609        let cache = ResponseCache::new(1, TtlConfig::default());
610        let query = Query::new();
611        let mut message = Message::response(0, OpCode::Query);
612        message.add_query(query.clone());
613        message.add_answer(Record::from_rdata(
614            query.name().clone(),
615            u32::MAX,
616            RData::A(A::new(127, 0, 0, 1)),
617        ));
618        cache.insert(query.clone(), Ok(message), Instant::now());
619
620        let client = mock(vec![empty()]);
621        let client = CachingClient::with_cache(cache, client, false);
622
623        let ips = block_on(CachingClient::inner_lookup(
624            Query::new(),
625            DnsRequestOptions::default(),
626            client,
627            vec![],
628            DepthTracker::default(),
629        ))
630        .unwrap();
631
632        assert_eq!(
633            ips.answers(),
634            &[Record::from_rdata(
635                query.name().clone(),
636                u32::MAX,
637                RData::A(A::new(127, 0, 0, 1))
638            )]
639        );
640    }
641
642    #[test]
643    fn test_no_cache_insert() {
644        subscribe();
645        let cache = ResponseCache::new(1, TtlConfig::default());
646        // first should come from client...
647        let client = mock(vec![v4_message()]);
648        let client = CachingClient::with_cache(cache.clone(), client, false);
649
650        let ips = block_on(CachingClient::inner_lookup(
651            Query::query(Name::root(), RecordType::A),
652            DnsRequestOptions::default(),
653            client,
654            vec![],
655            DepthTracker::default(),
656        ))
657        .unwrap();
658
659        assert_eq!(
660            ips.answers(),
661            &[Record::from_rdata(
662                Name::root(),
663                86400,
664                RData::A(A::new(127, 0, 0, 1))
665            )]
666        );
667
668        // next should come from cache...
669        let client = mock(vec![empty()]);
670        let client = CachingClient::with_cache(cache, client, false);
671
672        let ips = block_on(CachingClient::inner_lookup(
673            Query::query(Name::root(), RecordType::A),
674            DnsRequestOptions::default(),
675            client,
676            vec![],
677            DepthTracker::default(),
678        ))
679        .unwrap();
680
681        assert_eq!(
682            ips.answers(),
683            &[Record::from_rdata(
684                Name::root(),
685                86400,
686                RData::A(A::new(127, 0, 0, 1))
687            )]
688        );
689    }
690
691    #[allow(clippy::unnecessary_wraps)]
692    pub(crate) fn cname_message() -> Result<DnsResponse, NetError> {
693        let mut message = Message::query();
694        message.add_query(Query::query(
695            Name::from_str("www.example.com.").unwrap(),
696            RecordType::A,
697        ));
698        message.insert_answers(vec![Record::from_rdata(
699            Name::from_str("www.example.com.").unwrap(),
700            86400,
701            RData::CNAME(CNAME(Name::from_str("actual.example.com.").unwrap())),
702        )]);
703        Ok(DnsResponse::from_message(message.into_response()).unwrap())
704    }
705
706    #[allow(clippy::unnecessary_wraps)]
707    pub(crate) fn srv_message() -> Result<DnsResponse, NetError> {
708        let mut message = Message::query();
709        message.add_query(Query::query(
710            Name::from_str("_443._tcp.www.example.com.").unwrap(),
711            RecordType::SRV,
712        ));
713        message.insert_answers(vec![Record::from_rdata(
714            Name::from_str("_443._tcp.www.example.com.").unwrap(),
715            86400,
716            RData::SRV(SRV::new(
717                1,
718                2,
719                443,
720                Name::from_str("www.example.com.").unwrap(),
721            )),
722        )]);
723        Ok(DnsResponse::from_message(message.into_response()).unwrap())
724    }
725
726    #[allow(clippy::unnecessary_wraps)]
727    pub(crate) fn ns_message() -> Result<DnsResponse, NetError> {
728        let mut message = Message::query();
729        message.add_query(Query::query(
730            Name::from_str("www.example.com.").unwrap(),
731            RecordType::NS,
732        ));
733        message.insert_answers(vec![Record::from_rdata(
734            Name::from_str("www.example.com.").unwrap(),
735            86400,
736            RData::NS(NS(Name::from_str("www.example.com.").unwrap())),
737        )]);
738        Ok(DnsResponse::from_message(message.into_response()).unwrap())
739    }
740
741    fn no_recursion_on_query_test(query_type: RecordType) {
742        let cache = ResponseCache::new(1, TtlConfig::default());
743
744        // the cname should succeed, we shouldn't query again after that, which would cause an error...
745        let client = mock(vec![error(), cname_message()]);
746        let client = CachingClient::with_cache(cache, client, false);
747
748        let ips = block_on(CachingClient::inner_lookup(
749            Query::query(Name::from_str("www.example.com.").unwrap(), query_type),
750            DnsRequestOptions::default(),
751            client,
752            vec![],
753            DepthTracker::default(),
754        ))
755        .expect("lookup failed");
756
757        assert_eq!(
758            ips.answers(),
759            &[Record::from_rdata(
760                Name::from_str("www.example.com.").unwrap(),
761                86400,
762                RData::CNAME(CNAME(Name::from_str("actual.example.com.").unwrap()))
763            )]
764        );
765    }
766
767    #[test]
768    fn test_no_recursion_on_cname_query() {
769        subscribe();
770        no_recursion_on_query_test(RecordType::CNAME);
771    }
772
773    #[test]
774    fn test_no_recursion_on_all_query() {
775        subscribe();
776        no_recursion_on_query_test(RecordType::ANY);
777    }
778
779    #[test]
780    fn test_non_recursive_srv_query() {
781        subscribe();
782
783        let cache = ResponseCache::new(1, TtlConfig::default());
784
785        // the cname should succeed, we shouldn't query again after that, which would cause an error...
786        let client = mock(vec![error(), srv_message()]);
787        let client = CachingClient::with_cache(cache, client, false);
788
789        let ips = block_on(CachingClient::inner_lookup(
790            Query::query(
791                Name::from_str("_443._tcp.www.example.com.").unwrap(),
792                RecordType::SRV,
793            ),
794            DnsRequestOptions::default(),
795            client,
796            vec![],
797            DepthTracker::default(),
798        ))
799        .expect("lookup failed");
800
801        assert_eq!(
802            ips.answers(),
803            &[Record::from_rdata(
804                Name::from_str("_443._tcp.www.example.com.").unwrap(),
805                86400,
806                RData::SRV(SRV::new(
807                    1,
808                    2,
809                    443,
810                    Name::from_str("www.example.com.").unwrap(),
811                ))
812            )]
813        );
814    }
815
816    #[test]
817    fn test_single_srv_query_response() {
818        subscribe();
819
820        let cache = ResponseCache::new(1, TtlConfig::default());
821
822        let mut message = srv_message().unwrap().into_message();
823        message.add_answer(Record::from_rdata(
824            Name::from_str("www.example.com.").unwrap(),
825            86400,
826            RData::CNAME(CNAME(Name::from_str("actual.example.com.").unwrap())),
827        ));
828        message.insert_additionals(vec![
829            Record::from_rdata(
830                Name::from_str("actual.example.com.").unwrap(),
831                86400,
832                RData::A(A::new(127, 0, 0, 1)),
833            ),
834            Record::from_rdata(
835                Name::from_str("actual.example.com.").unwrap(),
836                86400,
837                RData::AAAA(AAAA::new(0, 0, 0, 0, 0, 0, 0, 1)),
838            ),
839        ]);
840
841        let client = mock(vec![
842            error(),
843            Ok(DnsResponse::from_message(message).unwrap()),
844        ]);
845        let client = CachingClient::with_cache(cache, client, false);
846
847        let ips = block_on(CachingClient::inner_lookup(
848            Query::query(
849                Name::from_str("_443._tcp.www.example.com.").unwrap(),
850                RecordType::SRV,
851            ),
852            DnsRequestOptions::default(),
853            client,
854            vec![],
855            DepthTracker::default(),
856        ))
857        .expect("lookup failed");
858
859        // Answers section should have SRV + CNAME
860        let answers = ips
861            .answers()
862            .iter()
863            .map(|r| r.data.clone())
864            .collect::<Vec<_>>();
865        assert!(answers.contains(&RData::SRV(SRV::new(
866            1,
867            2,
868            443,
869            Name::from_str("www.example.com.").unwrap(),
870        ))));
871        assert!(answers.contains(&RData::CNAME(CNAME(
872            Name::from_str("actual.example.com.").unwrap()
873        ))));
874
875        // Additionals section should have A + AAAA records
876        let additionals = ips
877            .additionals()
878            .iter()
879            .map(|r| r.data.clone())
880            .collect::<Vec<_>>();
881        assert!(additionals.contains(&RData::A(A::new(127, 0, 0, 1))));
882        assert!(additionals.contains(&RData::AAAA(AAAA::new(0, 0, 0, 0, 0, 0, 0, 1))));
883    }
884
885    #[test]
886    fn test_srv_behind_cname_in_one_response() {
887        subscribe();
888
889        // SRV query for a name that is a CNAME to the owner of the SRV record, as in
890        // `_xmpp-client._tcp.cname.badxmpp.eu.` (see #4139).
891        let mut message = Message::response(0, OpCode::Query);
892        message.add_query(Query::query(
893            Name::from_str("_xmpp-client._tcp.example.com.").unwrap(),
894            RecordType::SRV,
895        ));
896        message.insert_answers(vec![
897            Record::from_rdata(
898                Name::from_str("_xmpp-client._tcp.example.com.").unwrap(),
899                3600,
900                RData::CNAME(CNAME(Name::from_str("c2s.example.com.").unwrap())),
901            ),
902            Record::from_rdata(
903                Name::from_str("c2s.example.com.").unwrap(),
904                3600,
905                RData::SRV(SRV::new(
906                    0,
907                    0,
908                    5222,
909                    Name::from_str("example.com.").unwrap(),
910                )),
911            ),
912        ]);
913
914        let lookup = srv_behind_cname_lookup(vec![message], false).expect("lookup failed");
915        let answers = lookup
916            .answers()
917            .iter()
918            .map(|r| r.data.clone())
919            .collect::<Vec<_>>();
920        assert_eq!(
921            answers,
922            vec![RData::SRV(SRV::new(
923                0,
924                0,
925                5222,
926                Name::from_str("example.com.").unwrap()
927            ))]
928        );
929    }
930
931    #[test]
932    fn test_srv_behind_cname_in_one_response_with_preserve_intermediates() {
933        subscribe();
934
935        let mut message = Message::response(0, OpCode::Query);
936        message.add_query(Query::query(
937            Name::from_str("_xmpp-client._tcp.example.com.").unwrap(),
938            RecordType::SRV,
939        ));
940        message.insert_answers(vec![
941            Record::from_rdata(
942                Name::from_str("_xmpp-client._tcp.example.com.").unwrap(),
943                3600,
944                RData::CNAME(CNAME(Name::from_str("c2s.example.com.").unwrap())),
945            ),
946            Record::from_rdata(
947                Name::from_str("c2s.example.com.").unwrap(),
948                3600,
949                RData::SRV(SRV::new(
950                    0,
951                    0,
952                    5222,
953                    Name::from_str("example.com.").unwrap(),
954                )),
955            ),
956        ]);
957
958        let lookup = srv_behind_cname_lookup(vec![message], true).expect("lookup failed");
959        let answers = lookup
960            .answers()
961            .iter()
962            .map(|r| r.data.clone())
963            .collect::<Vec<_>>();
964        assert_eq!(
965            answers,
966            vec![
967                RData::CNAME(CNAME(Name::from_str("c2s.example.com.").unwrap())),
968                RData::SRV(SRV::new(
969                    0,
970                    0,
971                    5222,
972                    Name::from_str("example.com.").unwrap()
973                ))
974            ]
975        );
976    }
977
978    #[test]
979    fn test_srv_behind_cname_in_second_hop_with_preserve_intermediates() {
980        subscribe();
981
982        let mut message1 = Message::response(0, OpCode::Query);
983        message1.add_query(Query::query(
984            Name::from_str("_xmpp-client._tcp.example.com.").unwrap(),
985            RecordType::SRV,
986        ));
987        message1.insert_answers(vec![Record::from_rdata(
988            Name::from_str("_xmpp-client._tcp.example.com.").unwrap(),
989            3600,
990            RData::CNAME(CNAME(Name::from_str("c2s.example.com.").unwrap())),
991        )]);
992
993        let mut message2 = Message::response(0, OpCode::Query);
994        message2.add_query(Query::query(
995            Name::from_str("c2s.example.com.").unwrap(),
996            RecordType::SRV,
997        ));
998        message2.insert_answers(vec![Record::from_rdata(
999            Name::from_str("c2s.example.com.").unwrap(),
1000            3600,
1001            RData::SRV(SRV::new(
1002                0,
1003                0,
1004                5222,
1005                Name::from_str("example.com.").unwrap(),
1006            )),
1007        )]);
1008
1009        let lookup =
1010            srv_behind_cname_lookup(vec![message1, message2], true).expect("lookup failed");
1011        let answers = lookup
1012            .answers()
1013            .iter()
1014            .map(|r| r.data.clone())
1015            .collect::<Vec<_>>();
1016        assert_eq!(
1017            answers,
1018            vec![
1019                RData::CNAME(CNAME(Name::from_str("c2s.example.com.").unwrap())),
1020                RData::SRV(SRV::new(
1021                    0,
1022                    0,
1023                    5222,
1024                    Name::from_str("example.com.").unwrap()
1025                ))
1026            ]
1027        );
1028    }
1029
1030    #[test]
1031    fn test_srv_behind_cname_chain_takes_min_ttl() {
1032        subscribe();
1033
1034        // Two CNAMEs, the first with the lower TTL, then the SRV record.
1035        let mut message = Message::response(0, OpCode::Query);
1036        message.add_query(Query::query(
1037            Name::from_str("_xmpp-client._tcp.example.com.").unwrap(),
1038            RecordType::SRV,
1039        ));
1040        message.insert_answers(vec![
1041            Record::from_rdata(
1042                Name::from_str("_xmpp-client._tcp.example.com.").unwrap(),
1043                300,
1044                RData::CNAME(CNAME(Name::from_str("alias.example.com.").unwrap())),
1045            ),
1046            Record::from_rdata(
1047                Name::from_str("alias.example.com.").unwrap(),
1048                600,
1049                RData::CNAME(CNAME(Name::from_str("c2s.example.com.").unwrap())),
1050            ),
1051            Record::from_rdata(
1052                Name::from_str("c2s.example.com.").unwrap(),
1053                3600,
1054                RData::SRV(SRV::new(
1055                    0,
1056                    0,
1057                    5222,
1058                    Name::from_str("example.com.").unwrap(),
1059                )),
1060            ),
1061        ]);
1062
1063        let lookup = srv_behind_cname_lookup(vec![message], false).expect("lookup failed");
1064        let answers = lookup
1065            .answers()
1066            .iter()
1067            .map(|r| (r.data.clone(), r.ttl))
1068            .collect::<Vec<_>>();
1069        assert_eq!(
1070            answers,
1071            vec![(
1072                RData::SRV(SRV::new(
1073                    0,
1074                    0,
1075                    5222,
1076                    Name::from_str("example.com.").unwrap()
1077                )),
1078                300
1079            )]
1080        );
1081    }
1082
1083    #[test]
1084    fn test_srv_behind_cname_ignores_unrelated_cname() {
1085        subscribe();
1086
1087        // A CNAME that is not part of the chain must not change the search name.
1088        let mut message = Message::response(0, OpCode::Query);
1089        message.add_query(Query::query(
1090            Name::from_str("_xmpp-client._tcp.example.com.").unwrap(),
1091            RecordType::SRV,
1092        ));
1093        message.insert_answers(vec![
1094            Record::from_rdata(
1095                Name::from_str("_xmpp-client._tcp.example.com.").unwrap(),
1096                3600,
1097                RData::CNAME(CNAME(Name::from_str("c2s.example.com.").unwrap())),
1098            ),
1099            Record::from_rdata(
1100                Name::from_str("other.example.com.").unwrap(),
1101                3600,
1102                RData::CNAME(CNAME(Name::from_str("elsewhere.example.net.").unwrap())),
1103            ),
1104            Record::from_rdata(
1105                Name::from_str("c2s.example.com.").unwrap(),
1106                3600,
1107                RData::SRV(SRV::new(
1108                    0,
1109                    0,
1110                    5222,
1111                    Name::from_str("example.com.").unwrap(),
1112                )),
1113            ),
1114        ]);
1115
1116        let lookup = srv_behind_cname_lookup(vec![message], false).expect("lookup failed");
1117        let answers = lookup
1118            .answers()
1119            .iter()
1120            .map(|r| r.data.clone())
1121            .collect::<Vec<_>>();
1122        assert_eq!(
1123            answers,
1124            vec![RData::SRV(SRV::new(
1125                0,
1126                0,
1127                5222,
1128                Name::from_str("example.com.").unwrap()
1129            ))]
1130        );
1131    }
1132
1133    fn srv_behind_cname_lookup(
1134        responses: Vec<Message>,
1135        preserve_intermediates: bool,
1136    ) -> Result<Lookup, NetError> {
1137        let cache = ResponseCache::new(1, TtlConfig::default());
1138
1139        // Any further query, e.g. for SRV at the SRV target, gets an error.
1140        let mut messages = vec![error()];
1141        messages.extend(
1142            responses
1143                .into_iter()
1144                .rev()
1145                .map(|message| Ok(DnsResponse::from_message(message).unwrap())),
1146        );
1147        let client = CachingClient::with_cache(cache, mock(messages), preserve_intermediates);
1148
1149        block_on(CachingClient::inner_lookup(
1150            Query::query(
1151                Name::from_str("_xmpp-client._tcp.example.com.").unwrap(),
1152                RecordType::SRV,
1153            ),
1154            DnsRequestOptions::default(),
1155            client,
1156            vec![],
1157            DepthTracker::default(),
1158        ))
1159    }
1160
1161    // TODO: if we ever enable recursive lookups for SRV, here are the tests...
1162    // #[test]
1163    // fn test_recursive_srv_query() {
1164    //     let cache = Arc::new(Mutex::new(DnsLru::new(1)));
1165
1166    //     let mut message = Message::new();
1167    //     message.add_answer(Record::from_rdata(
1168    //         Name::from_str("www.example.com.").unwrap(),
1169    //         86400,
1170    //         RecordType::CNAME,
1171    //         RData::CNAME(Name::from_str("actual.example.com.").unwrap()),
1172    //     ));
1173    //     message.insert_additionals(vec![
1174    //         Record::from_rdata(
1175    //             Name::from_str("actual.example.com.").unwrap(),
1176    //             86400,
1177    //             RecordType::A,
1178    //             RData::A(Ipv4Addr::LOCALHOST),
1179    //         ),
1180    //     ]);
1181
1182    //     let mut client = mock(vec![error(), Ok(DnsResponse::from_message(message).unwrap()), srv_message()]);
1183
1184    //     let ips = QueryState::lookup(
1185    //         Query::query(
1186    //             Name::from_str("_443._tcp.www.example.com.").unwrap(),
1187    //             RecordType::SRV,
1188    //         ),
1189    //         Default::default(),
1190    //         &mut client,
1191    //         cache.clone(),
1192    //     ).wait()
1193    //         .expect("lookup failed");
1194
1195    //     assert_eq!(
1196    //         ips.iter().cloned().collect::<Vec<_>>(),
1197    //         vec![
1198    //             RData::SRV(SRV::new(
1199    //                 1,
1200    //                 2,
1201    //                 443,
1202    //                 Name::from_str("www.example.com.").unwrap(),
1203    //             )),
1204    //             RData::A(Ipv4Addr::LOCALHOST),
1205    //             //RData::AAAA(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)),
1206    //         ]
1207    //     );
1208    // }
1209
1210    #[test]
1211    fn test_single_ns_query_response() {
1212        subscribe();
1213
1214        let cache = ResponseCache::new(1, TtlConfig::default());
1215
1216        let mut message = ns_message().unwrap().into_message();
1217        message.add_answer(Record::from_rdata(
1218            Name::from_str("www.example.com.").unwrap(),
1219            86400,
1220            RData::CNAME(CNAME(Name::from_str("actual.example.com.").unwrap())),
1221        ));
1222        message.insert_additionals(vec![
1223            Record::from_rdata(
1224                Name::from_str("actual.example.com.").unwrap(),
1225                86400,
1226                RData::A(A::new(127, 0, 0, 1)),
1227            ),
1228            Record::from_rdata(
1229                Name::from_str("actual.example.com.").unwrap(),
1230                86400,
1231                RData::AAAA(AAAA::new(0, 0, 0, 0, 0, 0, 0, 1)),
1232            ),
1233        ]);
1234
1235        let client = mock(vec![
1236            error(),
1237            Ok(DnsResponse::from_message(message).unwrap()),
1238        ]);
1239        let client = CachingClient::with_cache(cache, client, false);
1240
1241        let ips = block_on(CachingClient::inner_lookup(
1242            Query::query(Name::from_str("www.example.com.").unwrap(), RecordType::NS),
1243            DnsRequestOptions::default(),
1244            client,
1245            vec![],
1246            DepthTracker::default(),
1247        ))
1248        .expect("lookup failed");
1249
1250        // Answers section should have NS + CNAME
1251        let answers = ips
1252            .answers()
1253            .iter()
1254            .map(|r| r.data.clone())
1255            .collect::<Vec<_>>();
1256        assert!(answers.contains(&RData::NS(NS(Name::from_str("www.example.com.").unwrap()))));
1257        assert!(answers.contains(&RData::CNAME(CNAME(
1258            Name::from_str("actual.example.com.").unwrap()
1259        ))));
1260
1261        // Additionals section should have A + AAAA records
1262        let additionals = ips
1263            .additionals()
1264            .iter()
1265            .map(|r| r.data.clone())
1266            .collect::<Vec<_>>();
1267        assert!(additionals.contains(&RData::A(A::new(127, 0, 0, 1))));
1268        assert!(additionals.contains(&RData::AAAA(AAAA::new(0, 0, 0, 0, 0, 0, 0, 1))));
1269    }
1270
1271    /// Purpose: Verify glue records stay in ADDITIONAL section
1272    ///
1273    /// This test ensures that when querying for NS records, the glue A records for those
1274    /// nameservers stay in the ADDITIONAL section and do NOT leak into the ANSWER section.
1275    #[test]
1276    fn test_ns_query_glue_in_additional_section() {
1277        subscribe();
1278
1279        let cache = ResponseCache::new(1, TtlConfig::default());
1280
1281        // Create NS query response for example.com with glue in ADDITIONAL section
1282        let mut message = Message::response(0, OpCode::Query);
1283        message.add_query(Query::query(
1284            Name::from_str("example.com.").unwrap(),
1285            RecordType::NS,
1286        ));
1287
1288        // ANSWER section: NS records
1289        message.insert_answers(vec![
1290            Record::from_rdata(
1291                Name::from_str("example.com.").unwrap(),
1292                3600,
1293                RData::NS(NS(Name::from_str("ns1.example.com.").unwrap())),
1294            ),
1295            Record::from_rdata(
1296                Name::from_str("example.com.").unwrap(),
1297                3600,
1298                RData::NS(NS(Name::from_str("ns2.example.com.").unwrap())),
1299            ),
1300        ]);
1301
1302        // ADDITIONAL section: Glue A records for the nameservers
1303        message.insert_additionals(vec![
1304            Record::from_rdata(
1305                Name::from_str("ns1.example.com.").unwrap(),
1306                3600,
1307                RData::A(A::new(192, 0, 2, 1)),
1308            ),
1309            Record::from_rdata(
1310                Name::from_str("ns2.example.com.").unwrap(),
1311                3600,
1312                RData::A(A::new(192, 0, 2, 2)),
1313            ),
1314        ]);
1315
1316        let client = mock(vec![
1317            error(),
1318            Ok(DnsResponse::from_message(message).unwrap()),
1319        ]);
1320        let client = CachingClient::with_cache(cache, client, false);
1321
1322        let lookup = block_on(CachingClient::inner_lookup(
1323            Query::query(Name::from_str("example.com.").unwrap(), RecordType::NS),
1324            DnsRequestOptions::default(),
1325            client,
1326            vec![],
1327            DepthTracker::default(),
1328        ))
1329        .expect("lookup failed");
1330
1331        // Verify: NS records in ANSWER section only
1332        let answers = lookup.answers().iter().collect::<Vec<_>>();
1333        assert_eq!(
1334            answers.len(),
1335            2,
1336            "Should have exactly 2 NS records in ANSWER"
1337        );
1338
1339        // Verify all answer records are NS type
1340        for answer in &answers {
1341            assert_eq!(
1342                answer.record_type(),
1343                RecordType::NS,
1344                "All ANSWER section records should be NS type"
1345            );
1346        }
1347
1348        // Verify: Glue A records in ADDITIONAL section only
1349        let additionals = lookup.additionals().iter().collect::<Vec<_>>();
1350        assert_eq!(
1351            additionals.len(),
1352            2,
1353            "Should have exactly 2 glue A records in ADDITIONAL"
1354        );
1355
1356        // Verify all additional records are A type
1357        for additional in &additionals {
1358            assert_eq!(
1359                additional.record_type(),
1360                RecordType::A,
1361                "All ADDITIONAL section records should be A type (glue records)"
1362            );
1363        }
1364
1365        // Verify glue records do NOT appear in ANSWER section
1366        for answer in &answers {
1367            assert_ne!(
1368                answer.record_type(),
1369                RecordType::A,
1370                "A records (glue) should NEVER appear in ANSWER for NS query - this was the original bug!"
1371            );
1372        }
1373
1374        // Verify AUTHORITY section is empty
1375        assert_eq!(
1376            lookup.authorities().len(),
1377            0,
1378            "AUTHORITY section should be empty"
1379        );
1380    }
1381
1382    /// Purpose: Verify sections preserved when CNAME and target in same response
1383    ///
1384    /// This test verifies that when a CNAME and its target appear in the same DNS response,
1385    /// the AUTHORITY and ADDITIONAL sections are preserved correctly, and filtering only
1386    /// affects the ANSWER section when preserve_intermediates=false.
1387    #[test]
1388    fn test_single_hop_cname_preserves_sections() {
1389        subscribe();
1390
1391        let cache = ResponseCache::new(1, TtlConfig::default());
1392
1393        // Create a response with CNAME + A in ANSWER, plus AUTHORITY and ADDITIONAL sections
1394        let mut message = Message::response(0, OpCode::Query);
1395        message.add_query(Query::query(
1396            Name::from_str("www.example.com.").unwrap(),
1397            RecordType::A,
1398        ));
1399
1400        // ANSWER section: CNAME + A record
1401        message.insert_answers(vec![
1402            Record::from_rdata(
1403                Name::from_str("www.example.com.").unwrap(),
1404                300,
1405                RData::CNAME(CNAME(Name::from_str("v4.example.com.").unwrap())),
1406            ),
1407            Record::from_rdata(
1408                Name::from_str("v4.example.com.").unwrap(),
1409                300,
1410                RData::A(A::new(192, 0, 2, 1)),
1411            ),
1412        ]);
1413
1414        // AUTHORITY section: NS record
1415        message.insert_authorities(vec![Record::from_rdata(
1416            Name::from_str("example.com.").unwrap(),
1417            3600,
1418            RData::NS(NS(Name::from_str("ns1.example.com.").unwrap())),
1419        )]);
1420
1421        // ADDITIONAL section: Glue for NS
1422        message.insert_additionals(vec![Record::from_rdata(
1423            Name::from_str("ns1.example.com.").unwrap(),
1424            3600,
1425            RData::A(A::new(192, 0, 2, 10)),
1426        )]);
1427
1428        let client = mock(vec![
1429            error(),
1430            Ok(DnsResponse::from_message(message).unwrap()),
1431        ]);
1432        let client = CachingClient::with_cache(cache, client, false); // preserve_intermediates=false
1433
1434        let lookup = block_on(CachingClient::inner_lookup(
1435            Query::query(Name::from_str("www.example.com.").unwrap(), RecordType::A),
1436            DnsRequestOptions::default(),
1437            client,
1438            vec![],
1439            DepthTracker::default(),
1440        ))
1441        .expect("lookup failed");
1442
1443        // Verify ANSWER: Only A record (CNAME filtered out because target was found)
1444        let answers = lookup.answers().iter().collect::<Vec<_>>();
1445        assert_eq!(
1446            answers.len(),
1447            1,
1448            "ANSWER should have 1 record (CNAME filtered)"
1449        );
1450        assert_eq!(
1451            answers[0].record_type(),
1452            RecordType::A,
1453            "ANSWER should contain only the A record"
1454        );
1455        match answers[0].data {
1456            RData::A(a) => assert_eq!(a, A::new(192, 0, 2, 1), "A record should have correct IP"),
1457            _ => panic!("wrong rdata type"),
1458        }
1459
1460        // Verify AUTHORITY: NS record preserved
1461        let authorities = lookup.authorities().iter().collect::<Vec<_>>();
1462        assert_eq!(
1463            authorities.len(),
1464            1,
1465            "AUTHORITY section should be preserved"
1466        );
1467        assert_eq!(
1468            authorities[0].record_type(),
1469            RecordType::NS,
1470            "AUTHORITY should contain NS record"
1471        );
1472
1473        // Verify ADDITIONAL: Glue preserved
1474        let additionals = lookup.additionals().iter().collect::<Vec<_>>();
1475        assert_eq!(
1476            additionals.len(),
1477            1,
1478            "ADDITIONAL section should be preserved"
1479        );
1480        assert_eq!(
1481            additionals[0].record_type(),
1482            RecordType::A,
1483            "ADDITIONAL should contain glue A record"
1484        );
1485        match additionals[0].data {
1486            RData::A(a) => assert_eq!(
1487                a,
1488                A::new(192, 0, 2, 10),
1489                "Glue record should have correct IP"
1490            ),
1491            _ => panic!("wrong rdata type"),
1492        }
1493    }
1494
1495    /// test_single_hop_cname_with_preserve_intermediates
1496    ///
1497    /// Purpose: Verify CNAME is kept when preserve_intermediates=true
1498    ///
1499    /// Same setup as Test 2.1 but with preserve_intermediates=true, so the CNAME
1500    /// should be kept in the ANSWER section along with the A record.
1501    #[test]
1502    fn test_single_hop_cname_with_preserve_intermediates() {
1503        subscribe();
1504
1505        let cache = ResponseCache::new(1, TtlConfig::default());
1506
1507        // Same response as Test 2.1
1508        let mut message = Message::response(0, OpCode::Query);
1509        message.add_query(Query::query(
1510            Name::from_str("www.example.com.").unwrap(),
1511            RecordType::A,
1512        ));
1513
1514        message.insert_answers(vec![
1515            Record::from_rdata(
1516                Name::from_str("www.example.com.").unwrap(),
1517                300,
1518                RData::CNAME(CNAME(Name::from_str("v4.example.com.").unwrap())),
1519            ),
1520            Record::from_rdata(
1521                Name::from_str("v4.example.com.").unwrap(),
1522                300,
1523                RData::A(A::new(192, 0, 2, 1)),
1524            ),
1525        ]);
1526
1527        message.insert_authorities(vec![Record::from_rdata(
1528            Name::from_str("example.com.").unwrap(),
1529            3600,
1530            RData::NS(NS(Name::from_str("ns1.example.com.").unwrap())),
1531        )]);
1532
1533        message.insert_additionals(vec![Record::from_rdata(
1534            Name::from_str("ns1.example.com.").unwrap(),
1535            3600,
1536            RData::A(A::new(192, 0, 2, 10)),
1537        )]);
1538
1539        let client = mock(vec![
1540            error(),
1541            Ok(DnsResponse::from_message(message).unwrap()),
1542        ]);
1543        let client = CachingClient::with_cache(cache, client, true); // preserve_intermediates=true
1544
1545        let lookup = block_on(CachingClient::inner_lookup(
1546            Query::query(Name::from_str("www.example.com.").unwrap(), RecordType::A),
1547            DnsRequestOptions::default(),
1548            client,
1549            vec![],
1550            DepthTracker::default(),
1551        ))
1552        .expect("lookup failed");
1553
1554        // Verify ANSWER: Both CNAME and A record
1555        let answers = lookup.answers().iter().collect::<Vec<_>>();
1556        assert_eq!(answers.len(), 2, "ANSWER should have 2 records (CNAME + A)");
1557
1558        // Check for CNAME record
1559        let cname_records = answers
1560            .iter()
1561            .filter(|r| r.record_type() == RecordType::CNAME)
1562            .collect::<Vec<_>>();
1563        assert_eq!(cname_records.len(), 1, "Should have 1 CNAME record");
1564
1565        // Check for A record
1566        let a_records = answers
1567            .iter()
1568            .filter(|r| r.record_type() == RecordType::A)
1569            .collect::<Vec<_>>();
1570        assert_eq!(a_records.len(), 1, "Should have 1 A record");
1571
1572        // Verify AUTHORITY: NS records preserved (1 record)
1573        assert_eq!(
1574            lookup.authorities().len(),
1575            1,
1576            "AUTHORITY section should be preserved"
1577        );
1578
1579        // Verify ADDITIONAL: Glue preserved (1 record)
1580        assert_eq!(
1581            lookup.additionals().len(),
1582            1,
1583            "ADDITIONAL section should be preserved"
1584        );
1585    }
1586
1587    /// Purpose: Verify only final response sections are preserved in multi-hop CNAME chains
1588    ///
1589    /// This test verifies that in a multi-hop CNAME chain, only the AUTHORITY and ADDITIONAL
1590    /// sections from the FINAL response are preserved, not merged from intermediate responses.
1591    #[test]
1592    fn test_multi_hop_cname_preserves_final_sections() {
1593        subscribe();
1594
1595        let cache = ResponseCache::new(1, TtlConfig::default());
1596
1597        // Response 1 (first hop): CNAME only
1598        let mut message1 = Message::response(0, OpCode::Query);
1599        message1.add_query(Query::query(
1600            Name::from_str("www.example.com.").unwrap(),
1601            RecordType::A,
1602        ));
1603
1604        message1.insert_answers(vec![Record::from_rdata(
1605            Name::from_str("www.example.com.").unwrap(),
1606            300,
1607            RData::CNAME(CNAME(Name::from_str("v4.example.com.").unwrap())),
1608        )]);
1609
1610        // AUTHORITY from first response (should NOT be in final result)
1611        message1.insert_authorities(vec![Record::from_rdata(
1612            Name::from_str("www-zone.example.com.").unwrap(),
1613            3600,
1614            RData::NS(NS(Name::from_str("ns-www.example.com.").unwrap())),
1615        )]);
1616
1617        // ADDITIONAL from first response (should NOT be in final result)
1618        message1.insert_additionals(vec![Record::from_rdata(
1619            Name::from_str("ns-www.example.com.").unwrap(),
1620            3600,
1621            RData::A(A::new(192, 0, 2, 20)),
1622        )]);
1623
1624        // Response 2 (second hop): Final A record
1625        let mut message2 = Message::response(0, OpCode::Query);
1626        message2.add_query(Query::query(
1627            Name::from_str("v4.example.com.").unwrap(),
1628            RecordType::A,
1629        ));
1630
1631        message2.insert_answers(vec![Record::from_rdata(
1632            Name::from_str("v4.example.com.").unwrap(),
1633            300,
1634            RData::A(A::new(192, 0, 2, 1)),
1635        )]);
1636
1637        // AUTHORITY from second response (SHOULD be in final result)
1638        message2.insert_authorities(vec![Record::from_rdata(
1639            Name::from_str("v4-zone.example.com.").unwrap(),
1640            3600,
1641            RData::NS(NS(Name::from_str("ns-v4.example.com.").unwrap())),
1642        )]);
1643
1644        // ADDITIONAL from second response (SHOULD be in final result)
1645        message2.insert_additionals(vec![Record::from_rdata(
1646            Name::from_str("ns-v4.example.com.").unwrap(),
1647            3600,
1648            RData::A(A::new(192, 0, 2, 30)),
1649        )]);
1650
1651        let mut client = CachingClient::with_cache(cache, mock(vec![]), false); // preserve_intermediates=false
1652
1653        // First hop: Process CNAME response
1654        let result1 = CachingClient::handle_noerror(
1655            &mut client,
1656            DnsRequestOptions::default(),
1657            &Query::query(Name::from_str("www.example.com.").unwrap(), RecordType::A),
1658            DnsResponse::from_message(message1).unwrap(),
1659            vec![],
1660            DepthTracker::default(),
1661        );
1662
1663        // Should return Records::CnameChain with empty preserved_records (preserve_intermediates=false)
1664        let preserved_records = match result1 {
1665            Ok(Records::CnameChain {
1666                preserved_records, ..
1667            }) => {
1668                // Verify preserved_records is empty when preserve_intermediates=false
1669                assert_eq!(
1670                    preserved_records.len(),
1671                    0,
1672                    "With preserve_intermediates=false, preserved_records should be empty"
1673                );
1674                preserved_records
1675            }
1676            Ok(Records::Exists { .. }) => {
1677                panic!("Expected Records::CnameChain from first hop, got Records::Exists")
1678            }
1679            Err(e) => panic!(
1680                "Expected Records::CnameChain from first hop, got error: {}",
1681                e
1682            ),
1683        };
1684
1685        // Second hop: Process final A record response
1686        let result2 = CachingClient::handle_noerror(
1687            &mut client,
1688            DnsRequestOptions::default(),
1689            &Query::query(Name::from_str("v4.example.com.").unwrap(), RecordType::A),
1690            DnsResponse::from_message(message2).unwrap(),
1691            preserved_records,
1692            DepthTracker::default().nest(),
1693        );
1694
1695        // Should return Records::Exists
1696        let lookup_message = match result2 {
1697            Ok(Records::Exists { message, .. }) => message,
1698            Ok(Records::CnameChain { .. }) => {
1699                panic!("Expected Records::Exists from second hop, got Records::CnameChain")
1700            }
1701            Err(e) => panic!("Expected Records::Exists from second hop, got error: {}", e),
1702        };
1703
1704        // Create a Lookup from the final message
1705        let lookup = Lookup::new(lookup_message, Instant::now() + Duration::from_secs(300));
1706
1707        // Verify ANSWER: Only final A record (CNAME from Response 1 filtered)
1708        let answers = lookup.answers().iter().collect::<Vec<_>>();
1709        assert_eq!(
1710            answers.len(),
1711            1,
1712            "ANSWER should have only the final A record"
1713        );
1714        assert_eq!(answers[0].record_type(), RecordType::A);
1715        match answers[0].data {
1716            RData::A(a) => assert_eq!(a, A::new(192, 0, 2, 1), "Should have IP from Response 2"),
1717            _ => panic!("wrong rdata type"),
1718        }
1719        match answers[0].data {
1720            RData::A(a) => assert_eq!(a, A::new(192, 0, 2, 1), "Should have IP from Response 2"),
1721            _ => panic!("wrong rdata type"),
1722        }
1723
1724        // Verify AUTHORITY: From Response 2 only (not merged with Response 1)
1725        let authorities = lookup.authorities().iter().collect::<Vec<_>>();
1726        assert_eq!(
1727            authorities.len(),
1728            1,
1729            "AUTHORITY should have 1 record from final response only"
1730        );
1731
1732        // Check it's the NS from Response 2, not Response 1
1733        match &authorities[0].data {
1734            RData::NS(ns_name) => assert_eq!(
1735                ns_name.0,
1736                Name::from_str("ns-v4.example.com.").unwrap(),
1737                "AUTHORITY should be from Response 2 (ns-v4), NOT Response 1 (ns-www)"
1738            ),
1739            _ => panic!("wrong rdata type"),
1740        }
1741
1742        // Verify ADDITIONAL: From Response 2 only
1743        let additionals = lookup.additionals().iter().collect::<Vec<_>>();
1744        assert_eq!(
1745            additionals.len(),
1746            1,
1747            "ADDITIONAL should have 1 record from final response only"
1748        );
1749
1750        // Check it's the IP from Response 2, not Response 1
1751        match additionals[0].data {
1752            RData::A(a) => assert_eq!(
1753                a,
1754                A::new(192, 0, 2, 30),
1755                "ADDITIONAL should have IP 192.0.2.30 from Response 2, NOT 192.0.2.20 from Response 1"
1756            ),
1757            _ => panic!("wrong rdata type"),
1758        }
1759    }
1760
1761    /// test_multi_hop_cname_with_preserve_accumulates_cnames
1762    ///
1763    /// Purpose: Verify CNAMEs from multiple hops are accumulated when
1764    /// preserve_intermediates=true
1765    ///
1766    /// Same setup as test_multi_hop_cname_preserves_final_sections
1767    /// but with preserve_intermediates=true, so the CNAME from the
1768    /// first hop should be included in the final ANSWER section.
1769    ///
1770    /// Uses handle_noerror directly to test the two-hop CNAME chain
1771    /// with CNAME preservation.
1772    #[test]
1773    fn test_multi_hop_cname_with_preserve_accumulates_cnames() {
1774        subscribe();
1775
1776        let cache = ResponseCache::new(1, TtlConfig::default());
1777
1778        // Response 1 (first hop): CNAME only
1779        let mut message1 = Message::response(0, OpCode::Query);
1780        message1.add_query(Query::query(
1781            Name::from_str("www.example.com.").unwrap(),
1782            RecordType::A,
1783        ));
1784
1785        message1.insert_answers(vec![Record::from_rdata(
1786            Name::from_str("www.example.com.").unwrap(),
1787            300,
1788            RData::CNAME(CNAME(Name::from_str("v4.example.com.").unwrap())),
1789        )]);
1790
1791        message1.insert_authorities(vec![Record::from_rdata(
1792            Name::from_str("www-zone.example.com.").unwrap(),
1793            3600,
1794            RData::NS(NS(Name::from_str("ns-www.example.com.").unwrap())),
1795        )]);
1796
1797        message1.insert_additionals(vec![Record::from_rdata(
1798            Name::from_str("ns-www.example.com.").unwrap(),
1799            3600,
1800            RData::A(A::new(192, 0, 2, 20)),
1801        )]);
1802
1803        // Response 2 (second hop): Final A record
1804        let mut message2 = Message::response(0, OpCode::Query);
1805        message2.add_query(Query::query(
1806            Name::from_str("v4.example.com.").unwrap(),
1807            RecordType::A,
1808        ));
1809
1810        message2.insert_answers(vec![Record::from_rdata(
1811            Name::from_str("v4.example.com.").unwrap(),
1812            300,
1813            RData::A(A::new(192, 0, 2, 1)),
1814        )]);
1815
1816        message2.insert_authorities(vec![Record::from_rdata(
1817            Name::from_str("v4-zone.example.com.").unwrap(),
1818            3600,
1819            RData::NS(NS(Name::from_str("ns-v4.example.com.").unwrap())),
1820        )]);
1821
1822        message2.insert_additionals(vec![Record::from_rdata(
1823            Name::from_str("ns-v4.example.com.").unwrap(),
1824            3600,
1825            RData::A(A::new(192, 0, 2, 30)),
1826        )]);
1827
1828        let client = mock(vec![]);
1829        let mut client = CachingClient::with_cache(cache, client, true); // preserve_intermediates=true
1830
1831        // First hop: Process CNAME response
1832        let result1 = CachingClient::handle_noerror(
1833            &mut client,
1834            DnsRequestOptions::default(),
1835            &Query::query(Name::from_str("www.example.com.").unwrap(), RecordType::A),
1836            DnsResponse::from_message(message1.clone()).unwrap(),
1837            vec![],
1838            DepthTracker::default(),
1839        );
1840
1841        // With preserve_intermediates=true, verify CNAME is preserved
1842        let preserved_records = match result1 {
1843            Ok(Records::CnameChain {
1844                preserved_records, ..
1845            }) => {
1846                // Verify preserved_records contains the CNAME when preserve_intermediates=true
1847                assert_eq!(
1848                    preserved_records.len(),
1849                    1,
1850                    "With preserve_intermediates=true, preserved_records should contain the CNAME"
1851                );
1852                assert_eq!(
1853                    preserved_records[0].record_type(),
1854                    RecordType::CNAME,
1855                    "Preserved record should be a CNAME"
1856                );
1857                preserved_records
1858            }
1859            _ => panic!("Expected CnameChain from first hop"),
1860        };
1861
1862        // Second hop: Process final A record with preserved CNAME
1863        let result2 = CachingClient::handle_noerror(
1864            &mut client,
1865            DnsRequestOptions::default(),
1866            &Query::query(Name::from_str("v4.example.com.").unwrap(), RecordType::A),
1867            DnsResponse::from_message(message2).unwrap(),
1868            preserved_records,
1869            DepthTracker::default().nest(),
1870        );
1871
1872        let lookup_message = match result2 {
1873            Ok(Records::Exists { message, .. }) => message,
1874            Ok(Records::CnameChain { .. }) => {
1875                panic!("Expected Records::Exists from second hop, got Records::CnameChain")
1876            }
1877            Err(e) => panic!("Expected Records::Exists from second hop, got error: {}", e),
1878        };
1879
1880        // Create a Lookup from the final message
1881        let lookup = Lookup::new(lookup_message, Instant::now() + Duration::from_secs(300));
1882
1883        // Verify ANSWER: CNAME from Response 1 + A from Response 2
1884        let answers = lookup.answers().iter().collect::<Vec<_>>();
1885        assert_eq!(
1886            answers.len(),
1887            2,
1888            "ANSWER should have CNAME + A (both preserved)"
1889        );
1890
1891        // Check for CNAME record (from Response 1)
1892        let cname_records = answers
1893            .iter()
1894            .filter(|r| r.record_type() == RecordType::CNAME)
1895            .collect::<Vec<_>>();
1896        assert_eq!(
1897            cname_records.len(),
1898            1,
1899            "Should have 1 CNAME from Response 1"
1900        );
1901
1902        match &cname_records[0].data {
1903            RData::CNAME(cname_target) => assert_eq!(
1904                cname_target.0,
1905                Name::from_str("v4.example.com.").unwrap(),
1906                "CNAME should point to v4.example.com"
1907            ),
1908            _ => panic!("wrong rdata type"),
1909        }
1910
1911        // Check for A record (from Response 2)
1912        let a_records = answers
1913            .iter()
1914            .filter(|r| r.record_type() == RecordType::A)
1915            .collect::<Vec<_>>();
1916        assert_eq!(a_records.len(), 1, "Should have 1 A record");
1917        match a_records[0].data {
1918            RData::A(a) => assert_eq!(
1919                a,
1920                A::new(192, 0, 2, 1),
1921                "A record should have IP from Response 2"
1922            ),
1923            _ => panic!("wrong rdata type"),
1924        };
1925
1926        // Verify AUTHORITY: From Response 2 only (1 record)
1927        assert_eq!(
1928            lookup.authorities().len(),
1929            1,
1930            "AUTHORITY should be from final response only"
1931        );
1932
1933        // Verify ADDITIONAL: From Response 2 only (1 record)
1934        assert_eq!(
1935            lookup.additionals().len(),
1936            1,
1937            "ADDITIONAL should be from final response only"
1938        );
1939    }
1940
1941    fn cname_ttl_test(first: u32, second: u32) {
1942        let lru = ResponseCache::new(1, TtlConfig::default());
1943        // expecting no queries to be performed
1944        let mut client = CachingClient::with_cache(lru, mock(vec![error()]), false);
1945
1946        let mut message = Message::query();
1947        message.insert_answers(vec![Record::from_rdata(
1948            Name::from_str("ttl.example.com.").unwrap(),
1949            first,
1950            RData::CNAME(CNAME(Name::from_str("actual.example.com.").unwrap())),
1951        )]);
1952        message.insert_additionals(vec![Record::from_rdata(
1953            Name::from_str("actual.example.com.").unwrap(),
1954            second,
1955            RData::A(A::new(127, 0, 0, 1)),
1956        )]);
1957
1958        let records = CachingClient::handle_noerror(
1959            &mut client,
1960            DnsRequestOptions::default(),
1961            &Query::query(Name::from_str("ttl.example.com.").unwrap(), RecordType::A),
1962            DnsResponse::from_message(message.into_response()).unwrap(),
1963            vec![],
1964            DepthTracker::default(),
1965        );
1966
1967        if let Ok(Records::Exists { message }) = records {
1968            assert!(!message.answers.is_empty());
1969        } else {
1970            panic!("expected Records::Exists");
1971        }
1972    }
1973
1974    #[test]
1975    fn test_cname_ttl() {
1976        subscribe();
1977        cname_ttl_test(1, 2);
1978        cname_ttl_test(2, 1);
1979    }
1980
1981    #[test]
1982    fn test_early_return_localhost() {
1983        subscribe();
1984        let cache = ResponseCache::new(0, TtlConfig::default());
1985        let client = mock(vec![empty()]);
1986        let client = CachingClient::with_cache(cache, client, false);
1987
1988        {
1989            let query = Query::query(Name::from_ascii("localhost.").unwrap(), RecordType::A);
1990            let lookup = block_on(client.lookup(query.clone(), DnsRequestOptions::default()))
1991                .expect("should have returned localhost");
1992            assert_eq!(lookup.query(), &query);
1993            assert_eq!(
1994                lookup.answers(),
1995                &[Record::from_rdata(
1996                    query.name().clone(),
1997                    MAX_TTL,
1998                    LOCALHOST_V4.clone()
1999                )]
2000            );
2001        }
2002
2003        {
2004            let query = Query::query(Name::from_ascii("localhost.").unwrap(), RecordType::AAAA);
2005            let lookup = block_on(client.lookup(query.clone(), DnsRequestOptions::default()))
2006                .expect("should have returned localhost");
2007            assert_eq!(lookup.query(), &query);
2008            assert_eq!(
2009                lookup.answers(),
2010                &[Record::from_rdata(
2011                    query.name().clone(),
2012                    MAX_TTL,
2013                    LOCALHOST_V6.clone()
2014                )]
2015            );
2016        }
2017
2018        {
2019            let query = Query::query(Name::from(Ipv4Addr::LOCALHOST), RecordType::PTR);
2020            let lookup = block_on(client.lookup(query.clone(), DnsRequestOptions::default()))
2021                .expect("should have returned localhost");
2022            assert_eq!(lookup.query(), &query);
2023            assert_eq!(
2024                lookup.answers(),
2025                &[Record::from_rdata(
2026                    query.name().clone(),
2027                    MAX_TTL,
2028                    LOCALHOST.clone()
2029                )]
2030            );
2031        }
2032
2033        {
2034            let query = Query::query(
2035                Name::from(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)),
2036                RecordType::PTR,
2037            );
2038            let lookup = block_on(client.lookup(query.clone(), DnsRequestOptions::default()))
2039                .expect("should have returned localhost");
2040            assert_eq!(lookup.query(), &query);
2041            assert_eq!(
2042                lookup.answers(),
2043                &[Record::from_rdata(
2044                    query.name().clone(),
2045                    MAX_TTL,
2046                    LOCALHOST.clone()
2047                )]
2048            );
2049        }
2050
2051        assert!(
2052            block_on(client.lookup(
2053                Query::query(Name::from_ascii("localhost.").unwrap(), RecordType::MX),
2054                DnsRequestOptions::default()
2055            ))
2056            .is_err()
2057        );
2058
2059        assert!(
2060            block_on(client.lookup(
2061                Query::query(Name::from(Ipv4Addr::LOCALHOST), RecordType::MX),
2062                DnsRequestOptions::default()
2063            ))
2064            .is_err()
2065        );
2066
2067        assert!(
2068            block_on(client.lookup(
2069                Query::query(
2070                    Name::from(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)),
2071                    RecordType::MX
2072                ),
2073                DnsRequestOptions::default()
2074            ))
2075            .is_err()
2076        );
2077    }
2078
2079    #[test]
2080    fn test_early_return_invalid() {
2081        subscribe();
2082        let cache = ResponseCache::new(0, TtlConfig::default());
2083        let client = mock(vec![empty()]);
2084        let client = CachingClient::with_cache(cache, client, false);
2085
2086        assert!(
2087            block_on(client.lookup(
2088                Query::query(
2089                    Name::from_ascii("horrible.invalid.").unwrap(),
2090                    RecordType::A,
2091                ),
2092                DnsRequestOptions::default()
2093            ))
2094            .is_err()
2095        );
2096    }
2097
2098    #[test]
2099    fn test_no_error_on_dot_local_no_mdns() {
2100        subscribe();
2101
2102        let cache = ResponseCache::new(1, TtlConfig::default());
2103
2104        let mut message = srv_message().unwrap().into_message();
2105        message.add_query(Query::query(
2106            Name::from_ascii("www.example.local.").unwrap(),
2107            RecordType::A,
2108        ));
2109        message.add_answer(Record::from_rdata(
2110            Name::from_str("www.example.local.").unwrap(),
2111            86400,
2112            RData::A(A::new(127, 0, 0, 1)),
2113        ));
2114
2115        let client = mock(vec![
2116            error(),
2117            Ok(DnsResponse::from_message(message).unwrap()),
2118        ]);
2119        let client = CachingClient::with_cache(cache, client, false);
2120
2121        assert!(
2122            block_on(client.lookup(
2123                Query::query(
2124                    Name::from_ascii("www.example.local.").unwrap(),
2125                    RecordType::A,
2126                ),
2127                DnsRequestOptions::default()
2128            ))
2129            .is_ok()
2130        );
2131    }
2132}