Skip to main content

hickory_resolver/
cache.rs

1//! A cache for DNS responses.
2
3use std::{
4    collections::HashMap,
5    ops::RangeInclusive,
6    sync::Arc,
7    time::{Duration, Instant},
8};
9
10use moka::{Expiry, sync::Cache};
11#[cfg(feature = "serde")]
12use serde::Deserialize;
13
14use crate::{
15    config,
16    net::{DnsError, NetError, NoRecords},
17    proto::{
18        op::{Message, Query},
19        rr::RecordType,
20    },
21};
22#[cfg(feature = "__dnssec")]
23use crate::{net::dnssec::BOGUS_CACHE_TTL, proto::dnssec::DnssecSummary};
24
25/// A cache for DNS responses.
26#[derive(Clone, Debug)]
27pub struct ResponseCache {
28    cache: Cache<Query, Entry>,
29    ttl_config: Arc<TtlConfig>,
30}
31
32impl ResponseCache {
33    /// Construct a new response cache.
34    ///
35    /// # Arguments
36    ///
37    /// * `capacity` - size in number of cached responses
38    /// * `ttl_config` - minimum and maximum TTLs for cached records
39    pub fn new(capacity: u64, ttl_config: TtlConfig) -> Self {
40        Self {
41            cache: Cache::builder()
42                .max_capacity(capacity)
43                .expire_after(EntryExpiry)
44                .build(),
45            ttl_config: Arc::new(ttl_config),
46        }
47    }
48
49    /// Insert a response into the cache.
50    pub fn insert(&self, query: Query, result: Result<Message, NetError>, now: Instant) {
51        self.upsert_clamped_ttl(query, result, now, false)
52    }
53
54    /// Inserts a message into the cache, but may clamp the TTL of the entry to that of the existing
55    /// entry, if any.
56    ///
57    /// If `clamp_valid_until` is true, the cache expiration time of any existing entry will not be
58    /// extended when the entry's contents are replaced. This is used in a mitigation for ghost
59    /// domain attacks, where queries for an apex NS RRset keep a cache entry warm, without ever
60    /// checking the referral in the parent zone. This can be eliminated once authoritative
61    /// responses and referral responses are cached separately.
62    pub(super) fn upsert_clamped_ttl(
63        &self,
64        query: Query,
65        result: Result<Message, NetError>,
66        now: Instant,
67        clamp_valid_until: bool,
68    ) {
69        let (ttl, result) = match result {
70            Ok(mut message) => {
71                let ttl = self.clamp_positive_ttls(query.query_type(), &mut message);
72                message.edns = None;
73                (ttl, Ok(message))
74            }
75            Err(NetError::Dns(DnsError::NoRecordsFound(no_records))) => {
76                let (negative_min_ttl, negative_max_ttl) = self
77                    .ttl_config
78                    .negative_response_ttl_bounds(query.query_type())
79                    .into_inner();
80                let ttl = if let Some(ttl) = no_records.negative_ttl {
81                    Duration::from_secs(u64::from(ttl)).clamp(negative_min_ttl, negative_max_ttl)
82                } else {
83                    negative_min_ttl
84                };
85                (
86                    ttl,
87                    Err(NetError::Dns(DnsError::NoRecordsFound(no_records))),
88                )
89            }
90            Err(_) => return,
91        };
92        let valid_until = now + ttl;
93        if clamp_valid_until {
94            self.cache.entry(query).and_upsert_with(|entry_opt| Entry {
95                result: Arc::new(result),
96                original_time: now,
97                valid_until: entry_opt.map_or(valid_until, |entry| {
98                    entry.value().valid_until.min(valid_until)
99                }),
100            });
101        } else {
102            self.cache.insert(
103                query,
104                Entry {
105                    result: Arc::new(result),
106                    original_time: now,
107                    valid_until,
108                },
109            );
110        }
111    }
112
113    /// Try to retrieve a cached response with the given query.
114    pub fn get(&self, query: &Query, now: Instant) -> Option<Result<Message, NetError>> {
115        let entry = self.cache.get(query)?;
116        if !entry.is_current(now) {
117            return None;
118        }
119        Some(entry.updated_ttl(now))
120    }
121
122    /// Clamp all record TTLs to `[positive_min_ttl, positive_max_ttl]` and return
123    /// the cache duration derived from the minimum TTL of records matching
124    /// `query_type` across all sections.
125    ///
126    /// Each record is clamped according to the TTL bounds configured for its own
127    /// record type, so that per-type overrides are respected even for authority
128    /// and additional section records.
129    pub(crate) fn clamp_positive_ttls(
130        &self,
131        query_type: RecordType,
132        message: &mut Message,
133    ) -> Duration {
134        #[cfg(feature = "__dnssec")]
135        let bogus = matches!(
136            DnssecSummary::from_records(message.all_sections()),
137            DnssecSummary::Bogus,
138        );
139
140        for record in message
141            .answers
142            .iter_mut()
143            .chain(message.authorities.iter_mut())
144            .chain(message.additionals.iter_mut())
145        {
146            let (min_secs, max_secs) = self
147                .ttl_config
148                .positive_ttl_bounds_secs(record.record_type());
149            record.ttl = record.ttl.clamp(min_secs, max_secs);
150        }
151
152        let (positive_min_ttl, positive_max_ttl) = self
153            .ttl_config
154            .positive_response_ttl_bounds(query_type)
155            .into_inner();
156
157        let min_ttl = if query_type == RecordType::NS {
158            // Derive cache duration from the minimum TTL of the NS records. Check both the answer
159            // section and the authority section, to handle both apex NS RRsets and referral
160            // responses.
161            message
162                .answers
163                .iter()
164                .chain(message.authorities.iter())
165                .filter(|r| r.record_type() == RecordType::NS)
166                .map(|r| Duration::from_secs(r.ttl.into()))
167                .min()
168        } else {
169            // Derive cache duration from the minimum TTL of records whose type matches the query
170            // (or CNAME records, see RFC2181 sections 5.4.1 and 10.1.1), from the answers section
171            // only. This avoids letting unrelated authority/additional records skew the cache
172            // lifetime.
173            message
174                .answers
175                .iter()
176                .filter(|r| r.record_type() == query_type || r.record_type() == RecordType::CNAME)
177                .map(|r| Duration::from_secs(r.ttl.into()))
178                .min()
179        };
180
181        let ttl = min_ttl
182            .unwrap_or(positive_min_ttl)
183            .clamp(positive_min_ttl, positive_max_ttl);
184
185        // Cap the cache lifetime independently of operator-configured min/max
186        // bounds for bogus DNSSEC responses.
187        // RFC 4035 §4.7 requires implementations to assign a small TTL
188        // since the wire TTL is attacker-influenced
189        #[cfg(feature = "__dnssec")]
190        let ttl = if bogus { ttl.min(BOGUS_CACHE_TTL) } else { ttl };
191
192        ttl
193    }
194
195    pub(crate) fn clear(&self) {
196        self.cache.invalidate_all();
197    }
198
199    pub(crate) fn clear_query(&self, query: &Query) {
200        self.cache.invalidate(query);
201    }
202
203    /// Returns the approximate number of entries in the cache.
204    #[cfg(feature = "metrics")]
205    pub(crate) fn entry_count(&self) -> u64 {
206        #[cfg(test)]
207        {
208            // For tests, ensure pending tasks are processed before getting the count.
209            // This allows unit tests of the respective cache size metrics to be
210            // written without flakyness. In a production context, we're happier
211            // to defer background work and to return an approximate count.
212            self.cache.run_pending_tasks();
213        }
214
215        self.cache.entry_count()
216    }
217}
218
219/// An entry in the response cache.
220///
221/// This contains the response itself (or an error), the time it was received, and the time at which
222/// it expires.
223#[derive(Debug, Clone)]
224struct Entry {
225    result: Arc<Result<Message, NetError>>,
226    original_time: Instant,
227    valid_until: Instant,
228}
229
230impl Entry {
231    /// Return the `Result` stored in this entry, with modified TTLs, subtracting the elapsed time
232    /// since the response was received.
233    fn updated_ttl(&self, now: Instant) -> Result<Message, NetError> {
234        let elapsed = u32::try_from(now.saturating_duration_since(self.original_time).as_secs())
235            .unwrap_or(u32::MAX);
236        match &*self.result {
237            Ok(response) => {
238                let mut response = response.clone();
239                for records in [
240                    &mut response.answers,
241                    &mut response.authorities,
242                    &mut response.additionals,
243                ] {
244                    for record in records {
245                        record.decrement_ttl(elapsed);
246                    }
247                }
248                Ok(response)
249            }
250            Err(e) => {
251                let mut e = e.clone();
252
253                // The NoRecords error may contain up to four fields with TTL values present: negative_ttl, soa, authorities, and ns.
254                // For completeness, we update each field, if present.
255                if let NetError::Dns(DnsError::NoRecordsFound(NoRecords {
256                    negative_ttl,
257                    soa,
258                    authorities,
259                    ns,
260                    ..
261                })) = &mut e
262                {
263                    if let Some(ttl) = negative_ttl {
264                        *ttl = ttl.saturating_sub(elapsed);
265                    }
266
267                    if let Some(soa) = soa {
268                        soa.decrement_ttl(elapsed);
269                    }
270
271                    if let Some(recs) = authorities.take() {
272                        authorities.replace(Arc::from(
273                            recs.iter()
274                                .cloned()
275                                .map(|mut rec| {
276                                    rec.decrement_ttl(elapsed);
277                                    rec
278                                })
279                                .collect::<Vec<_>>(),
280                        ));
281                    }
282
283                    if let Some(ns_recs) = ns.take() {
284                        ns.replace(Arc::from(
285                            ns_recs
286                                .iter()
287                                .cloned()
288                                .map(|mut ns| {
289                                    ns.ns.decrement_ttl(elapsed);
290                                    ns.glue = Arc::from(
291                                        ns.glue
292                                            .iter()
293                                            .cloned()
294                                            .map(|mut glue| {
295                                                glue.decrement_ttl(elapsed);
296                                                glue
297                                            })
298                                            .collect::<Vec<_>>(),
299                                    );
300
301                                    ns
302                                })
303                                .collect::<Vec<_>>(),
304                        ));
305                    }
306                }
307                Err(e)
308            }
309        }
310    }
311
312    /// Returns whether this cache entry is still valid.
313    fn is_current(&self, now: Instant) -> bool {
314        now <= self.valid_until
315    }
316
317    /// Returns the remaining time that this cache entry is valid for.
318    fn ttl(&self, now: Instant) -> Duration {
319        self.valid_until.saturating_duration_since(now)
320    }
321}
322
323struct EntryExpiry;
324
325impl Expiry<Query, Entry> for EntryExpiry {
326    fn expire_after_create(
327        &self,
328        _key: &Query,
329        value: &Entry,
330        created_at: Instant,
331    ) -> Option<Duration> {
332        Some(value.ttl(created_at))
333    }
334
335    fn expire_after_update(
336        &self,
337        _key: &Query,
338        value: &Entry,
339        updated_at: Instant,
340        _duration_until_expiry: Option<Duration>,
341    ) -> Option<Duration> {
342        Some(value.ttl(updated_at))
343    }
344}
345
346/// The time-to-live (TTL) configuration used by the cache.
347///
348/// Minimum and maximum TTLs can be set for both positive responses and negative responses. Separate
349/// limits may be set depending on the query type. If a minimum value is not provided, it will
350/// default to 0 seconds. If a maximum value is not provided, it will default to one day.
351///
352/// Note that TTLs in DNS are represented as a number of seconds stored in a 32-bit unsigned
353/// integer. We use `Duration` here, instead of `u32`, which can express larger values than the DNS
354/// standard. Generally, a `Duration` greater than `u32::MAX_VALUE` shouldn't cause any issue, as
355/// this will never be used in serialization, but note that this would be outside the standard
356/// range.
357#[derive(Clone, Debug, Default, PartialEq, Eq)]
358#[cfg_attr(feature = "serde", derive(Deserialize))]
359#[cfg_attr(
360    feature = "serde",
361    serde(from = "ttl_config_deserialize::TtlConfigMap")
362)]
363pub struct TtlConfig {
364    /// TTL limits applied to all queries.
365    default: TtlBounds,
366
367    /// TTL limits applied to queries with specific query types.
368    by_query_type: HashMap<RecordType, TtlBounds>,
369}
370
371impl TtlConfig {
372    /// Construct the LRU's TTL configuration based on the ResolverOpts configuration.
373    pub fn from_opts(opts: &config::ResolverOpts) -> Self {
374        Self::from(TtlBounds {
375            positive_min_ttl: opts.positive_min_ttl,
376            negative_min_ttl: opts.negative_min_ttl,
377            positive_max_ttl: opts.positive_max_ttl,
378            negative_max_ttl: opts.negative_max_ttl,
379        })
380    }
381
382    /// Override the minimum and maximum TTL values for a specific query type.
383    ///
384    /// If a minimum value is not provided, it will default to 0 seconds. If a maximum value is not
385    /// provided, it will default to one day.
386    pub fn with_query_type_ttl_bounds(
387        &mut self,
388        query_type: RecordType,
389        bounds: TtlBounds,
390    ) -> &mut Self {
391        self.by_query_type.insert(query_type, bounds);
392        self
393    }
394
395    /// Returns the positive-response TTL bounds as `(min_secs, max_secs)` clamped to `u32`.
396    ///
397    /// This is a convenience wrapper around [`positive_response_ttl_bounds`](Self::positive_response_ttl_bounds)
398    /// for use when clamping individual record TTLs.
399    fn positive_ttl_bounds_secs(&self, record_type: RecordType) -> (u32, u32) {
400        let (min, max) = self.positive_response_ttl_bounds(record_type).into_inner();
401        (
402            u32::try_from(min.as_secs()).unwrap_or(MAX_TTL),
403            u32::try_from(max.as_secs()).unwrap_or(MAX_TTL),
404        )
405    }
406
407    /// Retrieves the minimum and maximum TTL values for positive responses.
408    pub fn positive_response_ttl_bounds(&self, query_type: RecordType) -> RangeInclusive<Duration> {
409        let bounds = self.by_query_type.get(&query_type).unwrap_or(&self.default);
410        let min = bounds
411            .positive_min_ttl
412            .unwrap_or_else(|| Duration::from_secs(0));
413        let max = bounds
414            .positive_max_ttl
415            .unwrap_or_else(|| Duration::from_secs(u64::from(MAX_TTL)));
416        min..=max
417    }
418
419    /// Retrieves the minimum and maximum TTL values for negative responses.
420    pub fn negative_response_ttl_bounds(&self, query_type: RecordType) -> RangeInclusive<Duration> {
421        let bounds = self.by_query_type.get(&query_type).unwrap_or(&self.default);
422        let min = bounds
423            .negative_min_ttl
424            .unwrap_or_else(|| Duration::from_secs(0));
425        let max = bounds
426            .negative_max_ttl
427            .unwrap_or_else(|| Duration::from_secs(u64::from(MAX_TTL)));
428        min..=max
429    }
430}
431
432impl From<TtlBounds> for TtlConfig {
433    fn from(default: TtlBounds) -> Self {
434        Self {
435            default,
436            by_query_type: HashMap::default(),
437        }
438    }
439}
440
441/// Minimum and maximum TTL values for positive and negative responses.
442#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
443#[cfg_attr(feature = "serde", derive(Deserialize))]
444#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
445pub struct TtlBounds {
446    /// An optional minimum TTL value for positive responses.
447    ///
448    /// Positive responses with TTLs under `positive_min_ttl` will use
449    /// `positive_min_ttl` instead.
450    #[cfg_attr(
451        feature = "serde",
452        serde(default, deserialize_with = "config::duration_opt::deserialize")
453    )]
454    positive_min_ttl: Option<Duration>,
455
456    /// An optional minimum TTL value for negative (`NXDOMAIN`) responses.
457    ///
458    /// `NXDOMAIN` responses with TTLs under `negative_min_ttl` will use
459    /// `negative_min_ttl` instead.
460    #[cfg_attr(
461        feature = "serde",
462        serde(default, deserialize_with = "config::duration_opt::deserialize")
463    )]
464    negative_min_ttl: Option<Duration>,
465
466    /// An optional maximum TTL value for positive responses.
467    ///
468    /// Positive responses with TTLs over `positive_max_ttl` will use
469    /// `positive_max_ttl` instead.
470    #[cfg_attr(
471        feature = "serde",
472        serde(default, deserialize_with = "config::duration_opt::deserialize")
473    )]
474    positive_max_ttl: Option<Duration>,
475
476    /// An optional maximum TTL value for negative (`NXDOMAIN`) responses.
477    ///
478    /// `NXDOMAIN` responses with TTLs over `negative_max_ttl` will use
479    /// `negative_max_ttl` instead.
480    #[cfg_attr(
481        feature = "serde",
482        serde(default, deserialize_with = "config::duration_opt::deserialize")
483    )]
484    negative_max_ttl: Option<Duration>,
485}
486
487#[cfg(feature = "serde")]
488mod ttl_config_deserialize {
489    use std::collections::HashMap;
490
491    use serde::Deserialize;
492
493    use super::{TtlBounds, TtlConfig};
494    use crate::proto::rr::RecordType;
495
496    #[derive(Deserialize)]
497    pub(super) struct TtlConfigMap(HashMap<TtlConfigField, TtlBounds>);
498
499    impl From<TtlConfigMap> for TtlConfig {
500        fn from(value: TtlConfigMap) -> Self {
501            let mut default = TtlBounds::default();
502            let mut by_query_type = HashMap::new();
503            for (field, bounds) in value.0.into_iter() {
504                match field {
505                    TtlConfigField::RecordType(record_type) => {
506                        by_query_type.insert(record_type, bounds);
507                    }
508                    TtlConfigField::Default => default = bounds,
509                }
510            }
511            Self {
512                default,
513                by_query_type,
514            }
515        }
516    }
517
518    #[derive(PartialEq, Eq, Hash, Deserialize)]
519    enum TtlConfigField {
520        #[serde(rename = "default")]
521        Default,
522        #[serde(untagged)]
523        RecordType(RecordType),
524    }
525}
526
527/// Maximum TTL. This is set to one day (in seconds).
528///
529/// [RFC 2181, section 8](https://tools.ietf.org/html/rfc2181#section-8) says
530/// that the maximum TTL value is 2147483647, but implementations may place an
531/// upper bound on received TTLs.
532pub const MAX_TTL: u32 = 86400_u32;
533
534#[cfg(test)]
535mod tests {
536    use std::{
537        str::FromStr,
538        time::{Duration, Instant},
539    };
540
541    use hickory_proto::rr::rdata::CNAME;
542    #[cfg(feature = "serde")]
543    use serde::Deserialize;
544
545    use super::*;
546    use crate::{
547        net::{ForwardNSData, NetError},
548        proto::{
549            op::{DnsResponse, Message, OpCode, Query, ResponseCode},
550            rr::{
551                Name, RData, Record, RecordType,
552                rdata::{A, AAAA, NS, SOA, TXT},
553            },
554        },
555    };
556    #[cfg(feature = "__dnssec")]
557    use hickory_proto::dnssec::Proof;
558    use test_support::subscribe;
559
560    #[test]
561    fn test_is_current() {
562        let now = Instant::now();
563        let not_the_future = now + Duration::from_secs(4);
564        let future = now + Duration::from_secs(5);
565        let past_the_future = now + Duration::from_secs(6);
566
567        let entry = Entry {
568            result: Err(NetError::Message("test error")).into(),
569            original_time: now,
570            valid_until: future,
571        };
572
573        assert!(entry.is_current(now));
574        assert!(entry.is_current(not_the_future));
575        assert!(entry.is_current(future));
576        assert!(!entry.is_current(past_the_future));
577    }
578
579    #[test]
580    fn test_positive_min_ttl() {
581        let now = Instant::now();
582
583        let name = Name::from_str("www.example.com.").unwrap();
584        let query = Query::query(name.clone(), RecordType::A);
585        // Record should have TTL of 1 second.
586        let mut message = Message::response(0, OpCode::Query);
587        message.add_answer(Record::from_rdata(
588            name.clone(),
589            1,
590            RData::A(A::new(127, 0, 0, 1)),
591        ));
592
593        // Configure the cache with a minimum TTL of 2 seconds.
594        let ttls = TtlConfig::from(TtlBounds {
595            positive_min_ttl: Some(Duration::from_secs(2)),
596            ..TtlBounds::default()
597        });
598        let cache = ResponseCache::new(1, ttls);
599
600        cache.insert(query.clone(), Ok(message), now);
601        let valid_until = cache.cache.get(&query).unwrap().valid_until;
602        // The returned lookup should use the cache's minimum TTL, since the
603        // query's TTL was below the minimum.
604        assert_eq!(valid_until, now + Duration::from_secs(2));
605
606        // Record should have TTL of 3 seconds.
607        let mut message = Message::response(0, OpCode::Query);
608        message.add_answer(Record::from_rdata(
609            name.clone(),
610            3,
611            RData::A(A::new(127, 0, 0, 1)),
612        ));
613
614        cache.insert(query.clone(), Ok(message), now);
615        let valid_until = cache.cache.get(&query).unwrap().valid_until;
616        // The returned lookup should use the record's TTL, since it's
617        // greater than the cache's minimum.
618        assert_eq!(valid_until, now + Duration::from_secs(3));
619    }
620
621    #[test]
622    fn test_positive_min_ttl_clamps_record_ttls() {
623        // Regression test: records with TTLs below positive_min_ttl must have their
624        // TTLs raised in the cached message. Otherwise `updated_ttl()` subtracts
625        // elapsed time from the original (low) TTL, which saturates to 0 long before
626        // the cache entry expires.
627        let now = Instant::now();
628
629        let name = Name::from_str("www.example.com.").unwrap();
630        let query = Query::query(name.clone(), RecordType::A);
631
632        // Upstream record has TTL=60, but positive_min_ttl is 3600.
633        let mut message = Message::response(0, OpCode::Query);
634        message.add_answer(Record::from_rdata(
635            name.clone(),
636            60,
637            RData::A(A::new(93, 184, 216, 34)),
638        ));
639
640        let ttls = TtlConfig::from(TtlBounds {
641            positive_min_ttl: Some(Duration::from_secs(3600)),
642            ..TtlBounds::default()
643        });
644        let cache = ResponseCache::new(1, ttls);
645
646        cache.insert(query.clone(), Ok(message), now);
647
648        // The cache stores the record with the clamped TTL (3600). At t=0 that is
649        // what clients receive.
650        let result = cache.get(&query, now).unwrap().unwrap();
651        assert_eq!(result.answers.first().unwrap().ttl, 3600);
652
653        // At t=61 the returned TTL counts down from the cached 3600, not the
654        // upstream 60.
655        let result = cache
656            .get(&query, now + Duration::from_secs(61))
657            .unwrap()
658            .unwrap();
659        assert_eq!(result.answers.first().unwrap().ttl, 3539);
660
661        // At t=3599: still valid, TTL=1.
662        let result = cache
663            .get(&query, now + Duration::from_secs(3599))
664            .unwrap()
665            .unwrap();
666        assert_eq!(result.answers.first().unwrap().ttl, 1);
667
668        // At t=3601: cache miss — a new upstream lookup will be issued.
669        assert!(cache.get(&query, now + Duration::from_secs(3601)).is_none());
670    }
671
672    #[test]
673    fn test_positive_max_ttl_clamps_record_ttls() {
674        // Regression test: records with TTLs above positive_max_ttl must have their
675        // TTLs lowered in the cached message. Otherwise clients see the original high
676        // TTL while the cache entry expires at positive_max_ttl, causing the TTL to
677        // appear to "reset" after every max_ttl interval.
678        let now = Instant::now();
679
680        let name = Name::from_str("www.example.com.").unwrap();
681        let query = Query::query(name.clone(), RecordType::A);
682
683        // Upstream record has TTL=3600, but positive_max_ttl is 120.
684        let mut message = Message::response(0, OpCode::Query);
685        message.add_answer(Record::from_rdata(
686            name.clone(),
687            3600,
688            RData::A(A::new(93, 184, 216, 34)),
689        ));
690
691        let ttls = TtlConfig::from(TtlBounds {
692            positive_max_ttl: Some(Duration::from_secs(120)),
693            ..TtlBounds::default()
694        });
695        let cache = ResponseCache::new(1, ttls);
696
697        cache.insert(query.clone(), Ok(message), now);
698
699        // The cache stores the record with the clamped TTL (120), not the
700        // upstream 3600.
701        let result = cache.get(&query, now).unwrap().unwrap();
702        assert_eq!(result.answers.first().unwrap().ttl, 120);
703
704        // At t=60 the returned TTL counts down from the cached 120.
705        let result = cache
706            .get(&query, now + Duration::from_secs(60))
707            .unwrap()
708            .unwrap();
709        assert_eq!(result.answers.first().unwrap().ttl, 60);
710
711        // At t=121: cache miss.
712        assert!(cache.get(&query, now + Duration::from_secs(121)).is_none());
713    }
714
715    #[cfg(feature = "__dnssec")]
716    #[test]
717    fn test_bogus_record_clamps_cache_ttl() {
718        // RFC 4035 §4.7:
719        //   Since RRsets that fail to validate do not have trustworthy TTLs,
720        //   the implementation MUST assign a TTL.  This TTL SHOULD be small,
721        //   in order to mitigate the effect of caching the results of an
722        //   attack.
723        //
724        // We test against both the default TtlConfig and a config with a long
725        // positive_min_ttl: the latter exercises the case where an operator's
726        // floor for legitimate responses must not re-inflate the lifetime of
727        // an attacker-influenced Bogus verdict.
728        let configs = [
729            TtlConfig::default(),
730            TtlConfig::from(TtlBounds {
731                positive_min_ttl: Some(Duration::from_secs(3600)),
732                ..TtlBounds::default()
733            }),
734        ];
735
736        for ttls in configs {
737            let now = Instant::now();
738            let name = Name::from_str("bogus.example.com.").unwrap();
739            let query = Query::query(name.clone(), RecordType::A);
740
741            let mut message = Message::response(0, OpCode::Query);
742            let mut record = Record::from_rdata(name.clone(), 3600, RData::A(A::new(10, 0, 0, 1)));
743            record.proof = Proof::Bogus;
744            message.add_answer(record);
745
746            let cache = ResponseCache::new(1, ttls);
747            cache.insert(query.clone(), Ok(message), now);
748
749            let valid_until = cache.cache.get(&query).unwrap().valid_until;
750            assert!(
751                // RFC 4035 §3.2:
752                //   resolution failures MUST NOT be cached for longer than 5 minutes.
753                valid_until <= now + Duration::from_secs(60 * 5),
754                "Bogus answer cached for {:?}, must be <= 5m",
755                valid_until.duration_since(now),
756            );
757        }
758    }
759
760    #[test]
761    fn test_authority_ttl_does_not_shorten_answer_cache() {
762        // Regression test: authority section records (NS, SOA) with short TTLs must
763        // not reduce the cache lifetime of positive answers when answer records
764        // are present.
765        let now = Instant::now();
766
767        let name = Name::from_str("api.example.com.").unwrap();
768        let query = Query::query(name.clone(), RecordType::AAAA);
769
770        let mut message = Message::response(0, OpCode::Query);
771        // Answer: AAAA record with TTL=120
772        message.add_answer(Record::from_rdata(
773            name.clone(),
774            120,
775            RData::AAAA(AAAA::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 1)),
776        ));
777        // Authority: NS record with TTL=30 (much shorter)
778        message.add_authority(Record::from_rdata(
779            Name::from_str("example.com.").unwrap(),
780            30,
781            RData::NS(NS(Name::from_str("ns1.example.com.").unwrap())),
782        ));
783
784        let ttls = TtlConfig::from(TtlBounds {
785            positive_min_ttl: Some(Duration::from_secs(3600)),
786            positive_max_ttl: Some(Duration::from_secs(28800)),
787            ..TtlBounds::default()
788        });
789        let cache = ResponseCache::new(1, ttls);
790
791        cache.insert(query.clone(), Ok(message), now);
792
793        // Cache should be valid for 3600s (answer TTL=120 raised to min_ttl=3600),
794        // NOT 30s from the authority NS record.
795        let valid_until = cache.cache.get(&query).unwrap().valid_until;
796        assert_eq!(valid_until, now + Duration::from_secs(3600));
797
798        // At t=130 (past the original authority TTL of 30): still a cache hit.
799        let result = cache
800            .get(&query, now + Duration::from_secs(130))
801            .unwrap()
802            .unwrap();
803        // AAAA answer TTL counts down from 3600.
804        assert_eq!(result.answers.first().unwrap().ttl, 3470);
805
806        // At t=3601: cache miss.
807        assert!(cache.get(&query, now + Duration::from_secs(3601)).is_none());
808    }
809
810    #[test]
811    fn test_negative_min_ttl() {
812        let now = Instant::now();
813
814        let name = Name::from_str("www.example.com.").unwrap();
815        let query = Query::query(name.clone(), RecordType::A);
816
817        // Configure the cache with a minimum TTL of 2 seconds.
818        let ttls = TtlConfig::from(TtlBounds {
819            negative_min_ttl: Some(Duration::from_secs(2)),
820            ..TtlBounds::default()
821        });
822        let cache = ResponseCache::new(1, ttls);
823
824        // Negative response should have TTL of 1 second.
825        let mut no_records = NoRecords::new(query.clone(), ResponseCode::NoError);
826        no_records.negative_ttl = Some(1);
827        cache.insert(query.clone(), Err(no_records.into()), now);
828        let valid_until = cache.cache.get(&query).unwrap().valid_until;
829        // The error's `valid_until` field should have been limited to 2 seconds.
830        assert_eq!(valid_until, now + Duration::from_secs(2));
831
832        // Negative response should have TTL of 3 seconds.
833        let mut no_records = NoRecords::new(query.clone(), ResponseCode::NoError);
834        no_records.negative_ttl = Some(3);
835        cache.insert(query.clone(), Err(no_records.into()), now);
836        let valid_until = cache.cache.get(&query).unwrap().valid_until;
837        // The error's `valid_until` field should not have been limited, as it was over the minimum
838        // TTL.
839        assert_eq!(valid_until, now + Duration::from_secs(3));
840    }
841
842    #[test]
843    fn test_positive_max_ttl() {
844        let now = Instant::now();
845
846        let name = Name::from_str("www.example.com.").unwrap();
847        let query = Query::query(name.clone(), RecordType::A);
848        // Record should have TTL of 62 seconds.
849        let mut message = Message::response(0, OpCode::Query);
850        message.add_answer(Record::from_rdata(
851            name.clone(),
852            62,
853            RData::A(A::new(127, 0, 0, 1)),
854        ));
855
856        // Configure the cache with a maximum TTL of 60 seconds.
857        let ttls = TtlConfig::from(TtlBounds {
858            positive_max_ttl: Some(Duration::from_secs(60)),
859            ..Default::default()
860        });
861        let cache = ResponseCache::new(1, ttls);
862
863        cache.insert(query.clone(), Ok(message), now);
864        let valid_until = cache.cache.get(&query).unwrap().valid_until;
865        // The returned lookup should use the cache's minimum TTL, since the
866        // query's TTL was above the maximum.
867        assert_eq!(valid_until, now + Duration::from_secs(60));
868
869        // Record should have TTL of 59 seconds.
870        let mut message = Message::response(0, OpCode::Query);
871        message.add_answer(Record::from_rdata(
872            name.clone(),
873            59,
874            RData::A(A::new(127, 0, 0, 1)),
875        ));
876
877        cache.insert(query.clone(), Ok(message), now);
878        let valid_until = cache.cache.get(&query).unwrap().valid_until;
879        // The returned lookup should use the record's TTL, since it's
880        // below than the cache's maximum.
881        assert_eq!(valid_until, now + Duration::from_secs(59));
882    }
883
884    #[test]
885    fn test_negative_max_ttl() {
886        let now = Instant::now();
887
888        let name = Name::from_str("www.example.com.").unwrap();
889        let query = Query::query(name.clone(), RecordType::A);
890
891        // Configure the cache with a maximum TTL of 60 seconds.
892        let ttls = TtlConfig::from(TtlBounds {
893            negative_max_ttl: Some(Duration::from_secs(60)),
894            ..TtlBounds::default()
895        });
896        let cache = ResponseCache::new(1, ttls);
897
898        // Negative response should have TTL of 62 seconds.
899        let mut no_records = NoRecords::new(query.clone(), ResponseCode::NoError);
900        no_records.negative_ttl = Some(62);
901        cache.insert(query.clone(), Err(no_records.into()), now);
902        let valid_until = cache.cache.get(&query).unwrap().valid_until;
903        // The error's `valid_until` field should have been limited to 60 seconds.
904        assert_eq!(valid_until, now + Duration::from_secs(60));
905
906        // Negative response should have TTL of 59 seconds.
907        let mut no_records = NoRecords::new(query.clone(), ResponseCode::NoError);
908        no_records.negative_ttl = Some(59);
909        cache.insert(query.clone(), Err(no_records.into()), now);
910        let valid_until = cache.cache.get(&query).unwrap().valid_until;
911        // The error's `valid_until` field should not have been limited, as it was under the maximum
912        // TTL.
913        assert_eq!(valid_until, now + Duration::from_secs(59));
914    }
915
916    #[test]
917    fn test_insert() {
918        let now = Instant::now();
919
920        let name = Name::from_str("www.example.com.").unwrap();
921        let query = Query::query(name.clone(), RecordType::A);
922        let mut message = Message::response(0, OpCode::Query);
923        message.add_answer(Record::from_rdata(
924            name.clone(),
925            1,
926            RData::A(A::new(127, 0, 0, 1)),
927        ));
928        let cache = ResponseCache::new(1, TtlConfig::default());
929        cache.insert(query.clone(), Ok(message.clone()), now);
930
931        let result = cache.get(&query, now).unwrap();
932        let cache_message = result.unwrap();
933        assert_eq!(cache_message.answers, message.answers);
934    }
935
936    #[test]
937    fn test_insert_negative() {
938        subscribe();
939        let now = Instant::now();
940
941        let query = Query::query(
942            Name::from_str("www.example.com.").unwrap(),
943            RecordType::AAAA,
944        );
945
946        let mut norecs = NoRecords::new(query.clone(), ResponseCode::NXDomain);
947        norecs.negative_ttl = Some(10);
948        let error = NetError::from(norecs);
949        let cache = ResponseCache::new(1, TtlConfig::default());
950
951        cache.insert(query.clone(), Err(error), now);
952
953        let cache_err = cache.get(&query, now).unwrap().unwrap_err();
954        let NetError::Dns(DnsError::NoRecordsFound(_no_records)) = &cache_err else {
955            panic!("expected NoRecordsFound");
956        };
957
958        // Cache should be expired
959        assert!(cache.get(&query, now + Duration::from_secs(11)).is_none());
960    }
961
962    #[test]
963    fn test_update_ttl() {
964        let now = Instant::now();
965
966        let name = Name::from_str("www.example.com.").unwrap();
967        let query = Query::query(name.clone(), RecordType::A);
968        let mut message = Message::response(0, OpCode::Query);
969        message.add_answer(Record::from_rdata(
970            name.clone(),
971            10,
972            RData::A(A::new(127, 0, 0, 1)),
973        ));
974        let cache = ResponseCache::new(1, TtlConfig::default());
975        cache.insert(query.clone(), Ok(message), now);
976
977        let result = cache.get(&query, now + Duration::from_secs(2)).unwrap();
978        let cache_message = result.unwrap();
979        let record = cache_message.answers.first().unwrap();
980        assert_eq!(record.ttl, 8);
981    }
982
983    #[test]
984    fn test_update_ttl_negative() -> Result<(), NetError> {
985        subscribe();
986        let now = Instant::now();
987        let name = Name::from_str("www.example.com.")?;
988        let ns_name = Name::from_str("ns1.example.com")?;
989        let zone_name = name.base_name();
990        let query = Query::query(name.clone(), RecordType::AAAA);
991
992        let mut norecs = NoRecords::new(query.clone(), ResponseCode::NXDomain);
993        norecs.negative_ttl = Some(10);
994        norecs.soa = Some(Box::new(Record::from_rdata(
995            zone_name.clone(),
996            10,
997            SOA::new(name.base_name(), name.clone(), 1, 1, 1, 1, 1),
998        )));
999        norecs.authorities = Some(Arc::new([Record::from_rdata(
1000            zone_name.clone(),
1001            10,
1002            RData::NS(NS(ns_name.clone())),
1003        )]));
1004        norecs.ns = Some(Arc::new([ForwardNSData {
1005            ns: Record::from_rdata(zone_name.clone(), 10, RData::NS(NS(ns_name.clone()))),
1006            glue: Arc::new([Record::from_rdata(
1007                ns_name.clone(),
1008                10,
1009                RData::A(A([192, 0, 2, 1].into())),
1010            )]),
1011        }]));
1012
1013        let error = NetError::from(norecs);
1014
1015        let cache = ResponseCache::new(1, TtlConfig::default());
1016        cache.insert(query.clone(), Err(error), now);
1017
1018        let cache_err = cache.get(&query, now).unwrap().unwrap_err();
1019        let NetError::Dns(DnsError::NoRecordsFound(no_records)) = &cache_err else {
1020            panic!("expected NoRecordsFound");
1021        };
1022
1023        let Some(soa) = no_records.soa.clone() else {
1024            panic!("no SOA in NoRecordsFound");
1025        };
1026        assert_eq!(soa.ttl, 10);
1027
1028        let cache_err = cache
1029            .get(&query, now + Duration::from_secs(2))
1030            .unwrap()
1031            .unwrap_err();
1032        let NetError::Dns(DnsError::NoRecordsFound(NoRecords {
1033            negative_ttl: Some(negative_ttl),
1034            soa: Some(soa),
1035            authorities: Some(authorities),
1036            ns: Some(ns),
1037            ..
1038        })) = &cache_err
1039        else {
1040            panic!("expected NoRecordsFound with negative_ttl, soa, authorities, and ns");
1041        };
1042
1043        assert_eq!(*negative_ttl, 8);
1044        assert_eq!(soa.ttl, 8);
1045        assert_eq!(authorities[0].ttl, 8);
1046        assert_eq!(ns[0].ns.ttl, 8);
1047
1048        // Cache should be expired
1049        assert!(cache.get(&query, now + Duration::from_secs(11)).is_none());
1050        Ok(())
1051    }
1052
1053    #[test]
1054    fn test_insert_ttl() {
1055        let now = Instant::now();
1056
1057        let name = Name::from_str("www.example.com.").unwrap();
1058        let query = Query::query(name.clone(), RecordType::A);
1059
1060        // TTL of entry should be 1.
1061        let mut message = Message::response(0, OpCode::Query);
1062        message.add_answer(Record::from_rdata(
1063            name.clone(),
1064            1,
1065            RData::A(A::new(127, 0, 0, 1)),
1066        ));
1067        message.add_answer(Record::from_rdata(name, 2, RData::A(A::new(127, 0, 0, 2))));
1068
1069        let cache = ResponseCache::new(1, TtlConfig::default());
1070        cache.insert(query.clone(), Ok(message), now);
1071
1072        // Entry is still valid.
1073        cache
1074            .get(&query, now + Duration::from_secs(1))
1075            .unwrap()
1076            .unwrap();
1077
1078        // Entry is expired.
1079        let option = cache.get(&query, now + Duration::from_secs(2));
1080        assert!(option.is_none());
1081    }
1082
1083    #[test]
1084    fn test_ttl_different_query_types() {
1085        let now = Instant::now();
1086        let name = Name::from_str("www.example.com.").unwrap();
1087
1088        // Store records with a TTL of 1 second.
1089        let query_a = Query::query(name.clone(), RecordType::A);
1090        let rdata_a = RData::A(A::new(127, 0, 0, 1));
1091        let mut message_a = Message::response(0, OpCode::Query);
1092        message_a.add_answer(Record::from_rdata(name.clone(), 1, rdata_a.clone()));
1093
1094        let query_txt = Query::query(name.clone(), RecordType::TXT);
1095        let rdata_txt = RData::TXT(TXT::try_from("data".to_owned()).unwrap());
1096        let mut message_txt = Message::response(0, OpCode::Query);
1097        message_txt.add_answer(Record::from_rdata(name.clone(), 1, rdata_txt.clone()));
1098
1099        // Set separate positive_min_ttl limits for TXT queries and all others.
1100        let mut ttl_config = TtlConfig::from(TtlBounds {
1101            positive_min_ttl: Some(Duration::from_secs(2)),
1102            ..TtlBounds::default()
1103        });
1104        ttl_config.with_query_type_ttl_bounds(
1105            RecordType::TXT,
1106            TtlBounds {
1107                positive_min_ttl: Some(Duration::from_secs(5)),
1108                ..TtlBounds::default()
1109            },
1110        );
1111        let cache = ResponseCache::new(2, ttl_config);
1112
1113        cache.insert(query_a.clone(), Ok(message_a), now);
1114        // This should use the cache's default minimum TTL, since the record's TTL was below the
1115        // minimum.
1116        assert_eq!(
1117            cache.cache.get(&query_a).unwrap().valid_until,
1118            now + Duration::from_secs(2)
1119        );
1120
1121        cache.insert(query_txt.clone(), Ok(message_txt), now);
1122        // This should use the minimum for TTL records, since the record's TTL was below the
1123        // minimum.
1124        assert_eq!(
1125            cache.cache.get(&query_txt).unwrap().valid_until,
1126            now + Duration::from_secs(5)
1127        );
1128
1129        // store records with a TTL of 7 seconds.
1130        let mut message_a = Message::response(0, OpCode::Query);
1131        message_a.add_answer(Record::from_rdata(name.clone(), 7, rdata_a));
1132
1133        let mut message_txt = Message::response(0, OpCode::Query);
1134        message_txt.add_answer(Record::from_rdata(name.clone(), 7, rdata_txt));
1135
1136        cache.insert(query_a.clone(), Ok(message_a), now);
1137        // This should use the record's TTL, since it's greater than the default minimum TTL.
1138        assert_eq!(
1139            cache.cache.get(&query_a).unwrap().valid_until,
1140            now + Duration::from_secs(7)
1141        );
1142
1143        cache.insert(query_txt.clone(), Ok(message_txt), now);
1144        // This should use the record's TTL, since it's greater than the minimum TTL for TXT records.
1145        assert_eq!(
1146            cache.cache.get(&query_txt).unwrap().valid_until,
1147            now + Duration::from_secs(7)
1148        );
1149    }
1150
1151    #[test]
1152    fn cname_alias_bounds_cache_lifetime() {
1153        let now = Instant::now();
1154        let cname = Name::from_ascii("cname-record.com.").unwrap();
1155        let a = Name::from_ascii("a-record.com.").unwrap();
1156
1157        let query = Query::query(cname.clone(), RecordType::A);
1158
1159        let mut message = Message::response(0, OpCode::Query);
1160        message.add_query(query.clone());
1161
1162        // Short-TTL CNAME alias
1163        message.add_answer(Record::from_rdata(cname, 5, RData::CNAME(CNAME(a.clone()))));
1164
1165        // Terminal A record with 24hr TTL.
1166        message.add_answer(Record::from_rdata(
1167            a,
1168            86_400,
1169            RData::A(A::new(51, 34, 100, 105)),
1170        ));
1171
1172        let cache = ResponseCache::new(1, TtlConfig::default());
1173        cache.insert(query.clone(), Ok::<Message, NetError>(message), now);
1174
1175        // Immediately after insert the response is a cache hit.
1176        assert!(
1177            cache.get(&query, now).is_some(),
1178            "freshly inserted response should be a cache hit"
1179        );
1180
1181        // At t=6s — just past the 5s CNAME TTL — the entry MUST be a cache miss so a
1182        // re-resolution occurs.
1183        assert!(
1184            cache.get(&query, now + Duration::from_secs(6)).is_none(),
1185            "response served past the 5s CNAME TTL"
1186        );
1187    }
1188
1189    // Authority section records (e.g. NS for a delegated zone) must not
1190    // shorten the cache TTL derived from answer records.
1191    #[test]
1192    fn authority_record_cannot_reduce_cache_ttl() {
1193        let now = Instant::now();
1194
1195        let name = Name::from_str("www.example.com.").unwrap();
1196        let query = Query::query(name.clone(), RecordType::A);
1197
1198        let mut message = Message::response(0, OpCode::Query);
1199        // Answer with TTL=300
1200        message.add_answer(Record::from_rdata(
1201            name.clone(),
1202            300,
1203            RData::A(A::new(93, 184, 216, 34)),
1204        ));
1205        // Authority NS with TTL=10 — must not pull cache TTL down to 10
1206        message.add_authority(Record::from_rdata(
1207            Name::from_str("example.com.").unwrap(),
1208            10,
1209            RData::NS(NS(Name::from_str("ns1.example.com.").unwrap())),
1210        ));
1211
1212        let cache = ResponseCache::new(1, TtlConfig::default());
1213        cache.insert(query.clone(), Ok(message), now);
1214
1215        let valid_until = cache.cache.get(&query).unwrap().valid_until;
1216        assert_eq!(valid_until, now + Duration::from_secs(300));
1217
1218        // Still cached well past the authority TTL of 10s
1219        assert!(cache.get(&query, now + Duration::from_secs(60)).is_some());
1220    }
1221
1222    // Additional section records (e.g. glue A/AAAA) must not shorten
1223    // the cache TTL derived from answer records.
1224    #[test]
1225    fn additional_record_cannot_reduce_cache_ttl() {
1226        let now = Instant::now();
1227
1228        let name = Name::from_str("www.example.com.").unwrap();
1229        let query = Query::query(name.clone(), RecordType::A);
1230
1231        let mut message = Message::response(0, OpCode::Query);
1232        // Answer with TTL=300
1233        message.add_answer(Record::from_rdata(
1234            name.clone(),
1235            300,
1236            RData::A(A::new(93, 184, 216, 34)),
1237        ));
1238        // Additional glue record with TTL=5 — must not pull cache TTL down
1239        message.add_additional(Record::from_rdata(
1240            Name::from_str("ns1.example.com.").unwrap(),
1241            5,
1242            RData::A(A::new(198, 51, 100, 1)),
1243        ));
1244
1245        let cache = ResponseCache::new(1, TtlConfig::default());
1246        cache.insert(query.clone(), Ok(message), now);
1247
1248        let valid_until = cache.cache.get(&query).unwrap().valid_until;
1249        assert_eq!(valid_until, now + Duration::from_secs(300));
1250
1251        // Still cached well past the additional record TTL of 5s
1252        assert!(cache.get(&query, now + Duration::from_secs(60)).is_some());
1253    }
1254
1255    // Both authority and additional records present with very low TTLs
1256    // must not affect the answer-derived cache TTL.
1257    #[test]
1258    fn authority_and_additional_combined_cannot_reduce_cache_ttl() {
1259        let now = Instant::now();
1260
1261        let name = Name::from_str("www.example.com.").unwrap();
1262        let query = Query::query(name.clone(), RecordType::A);
1263
1264        let mut message = Message::response(0, OpCode::Query);
1265        // Answer with TTL=600
1266        message.add_answer(Record::from_rdata(
1267            name.clone(),
1268            600,
1269            RData::A(A::new(93, 184, 216, 34)),
1270        ));
1271        // Authority SOA with TTL=1
1272        message.add_authority(Record::from_rdata(
1273            Name::from_str("example.com.").unwrap(),
1274            1,
1275            RData::SOA(SOA::new(
1276                Name::from_str("example.com.").unwrap(),
1277                Name::from_str("admin.example.com.").unwrap(),
1278                2024010100,
1279                3600,
1280                900,
1281                604800,
1282                60,
1283            )),
1284        ));
1285        // Authority NS with TTL=2
1286        message.add_authority(Record::from_rdata(
1287            Name::from_str("example.com.").unwrap(),
1288            2,
1289            RData::NS(NS(Name::from_str("ns1.example.com.").unwrap())),
1290        ));
1291        // Additional glue with TTL=3
1292        message.add_additional(Record::from_rdata(
1293            Name::from_str("ns1.example.com.").unwrap(),
1294            3,
1295            RData::A(A::new(198, 51, 100, 1)),
1296        ));
1297        // Additional glue with TTL=4
1298        message.add_additional(Record::from_rdata(
1299            Name::from_str("ns1.example.com.").unwrap(),
1300            4,
1301            RData::AAAA(AAAA::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 53)),
1302        ));
1303
1304        let cache = ResponseCache::new(1, TtlConfig::default());
1305        cache.insert(query.clone(), Ok(message), now);
1306
1307        // Cache TTL must be 600 from the answer, not 1/2/3/4 from authority/additional
1308        let valid_until = cache.cache.get(&query).unwrap().valid_until;
1309        assert_eq!(valid_until, now + Duration::from_secs(600));
1310    }
1311
1312    #[test]
1313    fn referral_response_cache_ttl() {
1314        let now = Instant::now();
1315
1316        let name = Name::from_str("example.com.").unwrap();
1317        let query = Query::query(name.clone(), RecordType::NS);
1318
1319        let mut message = Message::response(0, OpCode::Query);
1320        message.add_query(query.clone());
1321        // Referral NS record with TTL=300
1322        message.add_authority(Record::from_rdata(
1323            name,
1324            300,
1325            RData::NS(NS(Name::from_str("ns1.example.com.").unwrap())),
1326        ));
1327        message.metadata.authoritative = false;
1328
1329        // Confirm that this response goes down the positive response code path.
1330        // This test may need to be updated or deleted when referral response handling is changed.
1331        let response = DnsResponse::from_message(message.clone()).unwrap();
1332        let result = DnsError::from_response(response);
1333        assert!(
1334            result.is_ok(),
1335            "expected referral response to be returned in Ok: {result:?}"
1336        );
1337
1338        let cache = ResponseCache::new(1, TtlConfig::default());
1339        cache.insert(query.clone(), Ok(message), now);
1340
1341        let valid_until = cache.cache.get(&query).unwrap().valid_until;
1342        assert_eq!(valid_until, now + Duration::from_secs(300));
1343    }
1344
1345    #[cfg(feature = "serde")]
1346    #[test]
1347    fn ttl_config_deserialize_errors() {
1348        // Duplicate of "default"
1349        let input = r#"[default]
1350positive_max_ttl = 3600
1351[default]
1352positive_max_ttl = 3599"#;
1353        let error = toml::from_str::<TtlConfig>(input).unwrap_err();
1354        assert!(
1355            error.message().contains("duplicate key"),
1356            "wrong error message: {error}"
1357        );
1358
1359        // Duplicate of a record type
1360        let input = r#"[default]
1361positive_max_ttl = 86400
1362[OPENPGPKEY]
1363positive_max_ttl = 3600
1364[OPENPGPKEY]
1365negative_min_ttl = 60"#;
1366        let error = toml::from_str::<TtlConfig>(input).unwrap_err();
1367        assert!(
1368            error.message().contains("duplicate key"),
1369            "wrong error message: {error}"
1370        );
1371
1372        // Neither "default" nor a record type
1373        let input = r#"[not_a_record_type]
1374positive_max_ttl = 3600"#;
1375        let error = toml::from_str::<TtlConfig>(input).unwrap_err();
1376        assert!(
1377            error.message().contains("data did not match any variant"),
1378            "wrong error message: {error}"
1379        );
1380
1381        // Array instead of table
1382        #[derive(Debug, Deserialize)]
1383        struct Wrapper {
1384            #[allow(unused)]
1385            cache_policy: TtlConfig,
1386        }
1387        let input = r#"cache_policy = []"#;
1388        let error = toml::from_str::<Wrapper>(input).unwrap_err();
1389        assert!(
1390            error.message().contains("invalid type: sequence"),
1391            "wrong error message: {error}"
1392        );
1393
1394        // String instead of table
1395        let input = r#"cache_policy = "yes""#;
1396        let error = toml::from_str::<Wrapper>(input).unwrap_err();
1397        assert!(
1398            error.message().contains("invalid type: string"),
1399            "wrong error message: {error}"
1400        );
1401    }
1402}