1use 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#[derive(Clone, Debug)]
27pub struct ResponseCache {
28 cache: Cache<Query, Entry>,
29 ttl_config: Arc<TtlConfig>,
30}
31
32impl ResponseCache {
33 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 pub fn insert(&self, query: Query, result: Result<Message, NetError>, now: Instant) {
51 self.upsert_clamped_ttl(query, result, now, false)
52 }
53
54 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 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 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 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 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 #[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 #[cfg(feature = "metrics")]
205 pub(crate) fn entry_count(&self) -> u64 {
206 #[cfg(test)]
207 {
208 self.cache.run_pending_tasks();
213 }
214
215 self.cache.entry_count()
216 }
217}
218
219#[derive(Debug, Clone)]
224struct Entry {
225 result: Arc<Result<Message, NetError>>,
226 original_time: Instant,
227 valid_until: Instant,
228}
229
230impl Entry {
231 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 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 fn is_current(&self, now: Instant) -> bool {
314 now <= self.valid_until
315 }
316
317 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#[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 default: TtlBounds,
366
367 by_query_type: HashMap<RecordType, TtlBounds>,
369}
370
371impl TtlConfig {
372 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 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 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 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 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#[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 #[cfg_attr(
451 feature = "serde",
452 serde(default, deserialize_with = "config::duration_opt::deserialize")
453 )]
454 positive_min_ttl: Option<Duration>,
455
456 #[cfg_attr(
461 feature = "serde",
462 serde(default, deserialize_with = "config::duration_opt::deserialize")
463 )]
464 negative_min_ttl: Option<Duration>,
465
466 #[cfg_attr(
471 feature = "serde",
472 serde(default, deserialize_with = "config::duration_opt::deserialize")
473 )]
474 positive_max_ttl: Option<Duration>,
475
476 #[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
527pub 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 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 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 assert_eq!(valid_until, now + Duration::from_secs(2));
605
606 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 assert_eq!(valid_until, now + Duration::from_secs(3));
619 }
620
621 #[test]
622 fn test_positive_min_ttl_clamps_record_ttls() {
623 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 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 let result = cache.get(&query, now).unwrap().unwrap();
651 assert_eq!(result.answers.first().unwrap().ttl, 3600);
652
653 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 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 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 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 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 let result = cache.get(&query, now).unwrap().unwrap();
702 assert_eq!(result.answers.first().unwrap().ttl, 120);
703
704 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 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 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 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 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 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 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 let valid_until = cache.cache.get(&query).unwrap().valid_until;
796 assert_eq!(valid_until, now + Duration::from_secs(3600));
797
798 let result = cache
800 .get(&query, now + Duration::from_secs(130))
801 .unwrap()
802 .unwrap();
803 assert_eq!(result.answers.first().unwrap().ttl, 3470);
805
806 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 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 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 assert_eq!(valid_until, now + Duration::from_secs(2));
831
832 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 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 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 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 assert_eq!(valid_until, now + Duration::from_secs(60));
868
869 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 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 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 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 assert_eq!(valid_until, now + Duration::from_secs(60));
905
906 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 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 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 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 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 cache
1074 .get(&query, now + Duration::from_secs(1))
1075 .unwrap()
1076 .unwrap();
1077
1078 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 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 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 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 assert_eq!(
1125 cache.cache.get(&query_txt).unwrap().valid_until,
1126 now + Duration::from_secs(5)
1127 );
1128
1129 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 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 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 message.add_answer(Record::from_rdata(cname, 5, RData::CNAME(CNAME(a.clone()))));
1164
1165 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 assert!(
1177 cache.get(&query, now).is_some(),
1178 "freshly inserted response should be a cache hit"
1179 );
1180
1181 assert!(
1184 cache.get(&query, now + Duration::from_secs(6)).is_none(),
1185 "response served past the 5s CNAME TTL"
1186 );
1187 }
1188
1189 #[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 message.add_answer(Record::from_rdata(
1201 name.clone(),
1202 300,
1203 RData::A(A::new(93, 184, 216, 34)),
1204 ));
1205 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 assert!(cache.get(&query, now + Duration::from_secs(60)).is_some());
1220 }
1221
1222 #[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 message.add_answer(Record::from_rdata(
1234 name.clone(),
1235 300,
1236 RData::A(A::new(93, 184, 216, 34)),
1237 ));
1238 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 assert!(cache.get(&query, now + Duration::from_secs(60)).is_some());
1253 }
1254
1255 #[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 message.add_answer(Record::from_rdata(
1267 name.clone(),
1268 600,
1269 RData::A(A::new(93, 184, 216, 34)),
1270 ));
1271 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 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 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 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 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 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 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 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 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 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 #[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 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}