Add WASM/JS support for doing full lookups using DoH
[dnssec-prover] / src / query.rs
1 //! This module exposes utilities for building DNSSEC proofs by directly querying a recursive
2 //! resolver.
3
4 use core::{cmp, ops};
5 use alloc::vec;
6 use alloc::vec::Vec;
7
8 #[cfg(feature = "std")]
9 use std::net::{SocketAddr, TcpStream};
10 #[cfg(feature = "std")]
11 use std::io::{Read, Write, Error, ErrorKind};
12
13 #[cfg(feature = "tokio")]
14 use tokio_crate::net::TcpStream as TokioTcpStream;
15 #[cfg(feature = "tokio")]
16 use tokio_crate::io::{AsyncReadExt, AsyncWriteExt};
17
18 use crate::rr::*;
19 use crate::ser::*;
20
21 // In testing use a rather small buffer to ensure we hit the allocation paths sometimes. In
22 // production, we should generally never actually need to go to heap as DNS messages are rarely
23 // larger than a KiB or two.
24 #[cfg(any(test, fuzzing))]
25 const STACK_BUF_LIMIT: u16 = 32;
26 #[cfg(not(any(test, fuzzing)))]
27 const STACK_BUF_LIMIT: u16 = 2048;
28
29 /// A buffer for storing queries and responses.
30 #[derive(Clone, PartialEq, Eq)]
31 pub struct QueryBuf {
32         buf: [u8; STACK_BUF_LIMIT as usize],
33         heap_buf: Vec<u8>,
34         len: u16,
35 }
36 impl QueryBuf {
37         /// Generates a new buffer of the given length, consisting of all zeros.
38         pub fn new_zeroed(len: u16) -> Self {
39                 let heap_buf = if len > STACK_BUF_LIMIT { vec![0; len as usize] } else { Vec::new() };
40                 Self {
41                         buf: [0; STACK_BUF_LIMIT as usize],
42                         heap_buf,
43                         len
44                 }
45         }
46         /// Extends the size of this buffer by appending the given slice.
47         ///
48         /// If the total length of this buffer exceeds [`u16::MAX`] after appending, the buffer's state
49         /// is undefined, however pushing data beyond [`u16::MAX`] will not panic.
50         pub fn extend_from_slice(&mut self, sl: &[u8]) {
51                 let new_len = self.len.saturating_add(sl.len() as u16);
52                 let was_heap = self.len > STACK_BUF_LIMIT;
53                 let is_heap = new_len > STACK_BUF_LIMIT;
54                 if was_heap != is_heap {
55                         self.heap_buf = vec![0; new_len as usize];
56                         self.heap_buf[..self.len as usize].copy_from_slice(&self.buf[..self.len as usize]);
57                 }
58                 let target = if is_heap {
59                         self.heap_buf.resize(new_len as usize, 0);
60                         &mut self.heap_buf[self.len as usize..]
61                 } else {
62                         &mut self.buf[self.len as usize..new_len as usize]
63                 };
64                 target.copy_from_slice(sl);
65                 self.len = new_len;
66         }
67         /// Converts this query into its bytes on the heap
68         pub fn into_vec(self) -> Vec<u8> {
69                 if self.len > STACK_BUF_LIMIT {
70                         self.heap_buf
71                 } else {
72                         self.buf[..self.len as usize].to_vec()
73                 }
74         }
75 }
76 impl ops::Deref for QueryBuf {
77         type Target = [u8];
78         fn deref(&self) -> &[u8] {
79                 if self.len > STACK_BUF_LIMIT {
80                         &self.heap_buf
81                 } else {
82                         &self.buf[..self.len as usize]
83                 }
84         }
85 }
86 impl ops::DerefMut for QueryBuf {
87         fn deref_mut(&mut self) -> &mut [u8] {
88                 if self.len > STACK_BUF_LIMIT {
89                         &mut self.heap_buf
90                 } else {
91                         &mut self.buf[..self.len as usize]
92                 }
93         }
94 }
95
96 // We don't care about transaction IDs as we're only going to accept signed data.
97 // Further, if we're querying over DoH, the RFC says we SHOULD use a transaction ID of 0 here.
98 const TXID: u16 = 0;
99
100 fn build_query(domain: &Name, ty: u16) -> QueryBuf {
101         let mut query = QueryBuf::new_zeroed(0);
102         query.extend_from_slice(&TXID.to_be_bytes());
103         query.extend_from_slice(&[0x01, 0x20]); // Flags: Recursive, Authenticated Data
104         query.extend_from_slice(&[0, 1, 0, 0, 0, 0, 0, 1]); // One question, One additional
105         write_name(&mut query, domain);
106         query.extend_from_slice(&ty.to_be_bytes());
107         query.extend_from_slice(&1u16.to_be_bytes()); // INternet class
108         query.extend_from_slice(&[0, 0, 0x29]); // . OPT
109         query.extend_from_slice(&0u16.to_be_bytes()); // 0 UDP payload size
110         query.extend_from_slice(&[0, 0]); // EDNS version 0
111         query.extend_from_slice(&0x8000u16.to_be_bytes()); // Accept DNSSEC RRs
112         query.extend_from_slice(&0u16.to_be_bytes()); // No additional data
113         query
114 }
115
116 #[cfg(fuzzing)]
117 /// Read some input and parse it as if it came from a server, for fuzzing.
118 pub fn fuzz_response(response: &[u8]) {
119         let (mut proof, mut names) = (Vec::new(), Vec::new());
120         let _ = handle_response(response, &mut proof, &mut names);
121 }
122
123 fn handle_response(resp: &[u8], proof: &mut Vec<u8>, rrsig_key_names: &mut Vec<Name>) -> Result<u32, ()> {
124         let mut read: &[u8] = resp;
125         if read_u16(&mut read)? != TXID { return Err(()); }
126         // 2 byte transaction ID
127         let flags = read_u16(&mut read)?;
128         if flags & 0b1000_0000_0000_0000 == 0 {
129                 return Err(());
130         }
131         if flags & 0b0111_1010_0000_0111 != 0 {
132                 return Err(());
133         }
134         if flags & 0b10_0000 == 0 {
135                 return Err(());
136         }
137         let questions = read_u16(&mut read)?;
138         if questions != 1 { return Err(()); }
139         let answers = read_u16(&mut read)?;
140         if answers == 0 { return Err(()); }
141         let _authorities = read_u16(&mut read)?;
142         let _additional = read_u16(&mut read)?;
143
144         for _ in 0..questions {
145                 read_wire_packet_name(&mut read, resp)?;
146                 read_u16(&mut read)?; // type
147                 read_u16(&mut read)?; // class
148         }
149
150         // Only read the answers (skip authorities and additional) as that's all we care about.
151         let mut min_ttl = u32::MAX;
152         for _ in 0..answers {
153                 let (rr, ttl) = parse_wire_packet_rr(&mut read, &resp)?;
154                 write_rr(&rr, ttl, proof);
155                 min_ttl = cmp::min(min_ttl, ttl);
156                 if let RR::RRSig(rrsig) = rr { rrsig_key_names.push(rrsig.key_name); }
157         }
158         Ok(min_ttl)
159 }
160
161 #[cfg(fuzzing)]
162 /// Read a stream of responses and handle them it as if they came from a server, for fuzzing.
163 pub fn fuzz_proof_builder(mut response_stream: &[u8]) {
164         let (mut builder, _) = ProofBuilder::new(&"example.com.".try_into().unwrap(), Txt::TYPE);
165         while builder.awaiting_responses() {
166                 let len = if let Ok(len) = read_u16(&mut response_stream) { len } else { return };
167                 let mut buf = QueryBuf::new_zeroed(len);
168                 if response_stream.len() < len as usize { return; }
169                 buf.copy_from_slice(&response_stream[..len as usize]);
170                 response_stream = &response_stream[len as usize..];
171                 let _ = builder.process_response(&buf);
172         }
173         let _ = builder.finish_proof();
174 }
175
176 const MAX_REQUESTS: usize = 10;
177 /// A simple state machine which will generate a series of queries and process the responses until
178 /// it has built a DNSSEC proof.
179 ///
180 /// A [`ProofBuilder`] driver starts with [`ProofBuilder::new`], fetching the state machine and
181 /// initial query. As long as [`ProofBuilder::awaiting_responses`] returns true, responses should
182 /// be read from the resolver. For each query response read from the DNS resolver,
183 /// [`ProofBuilder::process_response`] should be called, and each fresh query returned should be
184 /// sent to the resolver. Once [`ProofBuilder::awaiting_responses`] returns false,
185 /// [`ProofBuilder::finish_proof`] should be called to fetch the resulting proof.
186 pub struct ProofBuilder {
187         proof: Vec<u8>,
188         min_ttl: u32,
189         dnskeys_requested: Vec<Name>,
190         pending_queries: usize,
191         queries_made: usize,
192 }
193
194 impl ProofBuilder {
195         /// Constructs a new [`ProofBuilder`] and an initial query to send to the recursive resolver to
196         /// begin the proof building process.
197         ///
198         /// Given a correctly-functioning resolver the proof will ultimately be able to prove the
199         /// contents of any records with the given `ty`pe at the given `name` (as long as the given
200         /// `ty`pe is supported by this library).
201         ///
202         /// You can find constants for supported standard types in the [`crate::rr`] module.
203         pub fn new(name: &Name, ty: u16) -> (ProofBuilder, QueryBuf) {
204                 let initial_query = build_query(name, ty);
205                 (ProofBuilder {
206                         proof: Vec::new(),
207                         min_ttl: u32::MAX,
208                         dnskeys_requested: Vec::with_capacity(MAX_REQUESTS),
209                         pending_queries: 1,
210                         queries_made: 1,
211                 }, initial_query)
212         }
213
214         /// Returns true as long as further responses are expected from the resolver.
215         ///
216         /// As long as this returns true, responses should be read from the resolver and passed to
217         /// [`Self::process_response`]. Once this returns false, [`Self::finish_proof`] should be used
218         /// to (possibly) get the final proof.
219         pub fn awaiting_responses(&self) -> bool {
220                 self.pending_queries > 0 && self.queries_made <= MAX_REQUESTS
221         }
222
223         /// Processes a query response from the recursive resolver, returning a list of new queries to
224         /// send to the resolver.
225         pub fn process_response(&mut self, resp: &QueryBuf) -> Result<Vec<QueryBuf>, ()> {
226                 if self.pending_queries == 0 { return Err(()); }
227
228                 let mut rrsig_key_names = Vec::new();
229                 let min_ttl = handle_response(&resp, &mut self.proof, &mut rrsig_key_names)?;
230                 self.min_ttl = cmp::min(self.min_ttl, min_ttl);
231                 self.pending_queries -= 1;
232
233                 rrsig_key_names.sort_unstable();
234                 rrsig_key_names.dedup();
235
236                 let mut new_queries = Vec::with_capacity(2);
237                 for key_name in rrsig_key_names.drain(..) {
238                         if !self.dnskeys_requested.contains(&key_name) {
239                                 new_queries.push(build_query(&key_name, DnsKey::TYPE));
240                                 self.pending_queries += 1;
241                                 self.queries_made += 1;
242                                 self.dnskeys_requested.push(key_name.clone());
243
244                                 if key_name.as_str() != "." {
245                                         new_queries.push(build_query(&key_name, DS::TYPE));
246                                         self.pending_queries += 1;
247                                         self.queries_made += 1;
248                                 }
249                         }
250                 }
251                 if self.queries_made <= MAX_REQUESTS {
252                         Ok(new_queries)
253                 } else {
254                         Ok(Vec::new())
255                 }
256         }
257
258         /// Finalizes the proof, if one is available, and returns it as well as the TTL that should be
259         /// used to cache the proof (i.e. the lowest TTL of all records which were used to build the
260         /// proof).
261         pub fn finish_proof(self) -> Result<(Vec<u8>, u32), ()> {
262                 if self.pending_queries > 0 || self.queries_made > MAX_REQUESTS {
263                         Err(())
264                 } else {
265                         Ok((self.proof, self.min_ttl))
266                 }
267         }
268 }
269
270 #[cfg(feature = "std")]
271 fn send_query(stream: &mut TcpStream, query: &[u8]) -> Result<(), Error> {
272         stream.write_all(&(query.len() as u16).to_be_bytes())?;
273         stream.write_all(&query)?;
274         Ok(())
275 }
276
277 #[cfg(feature = "tokio")]
278 async fn send_query_async(stream: &mut TokioTcpStream, query: &[u8]) -> Result<(), Error> {
279         stream.write_all(&(query.len() as u16).to_be_bytes()).await?;
280         stream.write_all(&query).await?;
281         Ok(())
282 }
283
284 #[cfg(feature = "std")]
285 fn read_response(stream: &mut TcpStream) -> Result<QueryBuf, Error> {
286         let mut len_bytes = [0; 2];
287         stream.read_exact(&mut len_bytes)?;
288         let mut buf = QueryBuf::new_zeroed(u16::from_be_bytes(len_bytes));
289         stream.read_exact(&mut buf)?;
290         Ok(buf)
291 }
292
293 #[cfg(feature = "tokio")]
294 async fn read_response_async(stream: &mut TokioTcpStream) -> Result<QueryBuf, Error> {
295         let mut len_bytes = [0; 2];
296         stream.read_exact(&mut len_bytes).await?;
297         let mut buf = QueryBuf::new_zeroed(u16::from_be_bytes(len_bytes));
298         stream.read_exact(&mut buf).await?;
299         Ok(buf)
300 }
301
302 #[cfg(feature = "std")]
303 macro_rules! build_proof_impl {
304         ($stream: ident, $send_query: ident, $read_response: ident, $domain: expr, $ty: expr $(, $async_ok: tt)?) => { {
305                 // We require the initial query to have already gone out, and assume our resolver will
306                 // return any CNAMEs all the way to the final record in the response. From there, we just
307                 // have to take any RRSIGs in the response and walk them up to the root. We do so
308                 // iteratively, sending DNSKEY and DS lookups after every response, deduplicating requests
309                 // using `dnskeys_requested`.
310                 let (mut builder, initial_query) = ProofBuilder::new($domain, $ty);
311                 $send_query(&mut $stream, &initial_query)
312                         $(.await?; $async_ok)??; // Either await?; Ok(())?, or just ?
313                 while builder.awaiting_responses() {
314                         let response = $read_response(&mut $stream)
315                                 $(.await?; $async_ok)??; // Either await?; Ok(())?, or just ?
316                         let new_queries = builder.process_response(&response)
317                                 .map_err(|()| Error::new(ErrorKind::Other, "Bad response"))?;
318                         for query in new_queries {
319                                 $send_query(&mut $stream, &query)
320                                         $(.await?; $async_ok)??; // Either await?; Ok(())?, or just ?
321                         }
322                 }
323
324                 builder.finish_proof()
325                         .map_err(|()| Error::new(ErrorKind::Other, "Too many requests required"))
326         } }
327 }
328
329 #[cfg(feature = "std")]
330 fn build_proof(resolver: SocketAddr, domain: &Name, ty: u16) -> Result<(Vec<u8>, u32), Error> {
331         let mut stream = TcpStream::connect(resolver)?;
332         build_proof_impl!(stream, send_query, read_response, domain, ty)
333 }
334
335 #[cfg(feature = "tokio")]
336 async fn build_proof_async(resolver: SocketAddr, domain: &Name, ty: u16) -> Result<(Vec<u8>, u32), Error> {
337         let mut stream = TokioTcpStream::connect(resolver).await?;
338         build_proof_impl!(stream, send_query_async, read_response_async, domain, ty, { Ok::<(), Error>(()) })
339 }
340
341 /// Builds a DNSSEC proof for an A record by querying a recursive resolver, returning the proof as
342 /// well as the TTL for the proof provided by the recursive resolver.
343 ///
344 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
345 /// module to validate the records contained.
346 #[cfg(feature = "std")]
347 pub fn build_a_proof(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
348         build_proof(resolver, domain, A::TYPE)
349 }
350
351 /// Builds a DNSSEC proof for an AAAA record by querying a recursive resolver, returning the proof
352 /// as well as the TTL for the proof provided by the recursive resolver.
353 ///
354 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
355 /// module to validate the records contained.
356 #[cfg(feature = "std")]
357 pub fn build_aaaa_proof(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
358         build_proof(resolver, domain, AAAA::TYPE)
359 }
360
361 /// Builds a DNSSEC proof for an TXT record by querying a recursive resolver, returning the proof
362 /// as well as the TTL for the proof provided by the recursive resolver.
363 ///
364 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
365 /// module to validate the records contained.
366 #[cfg(feature = "std")]
367 pub fn build_txt_proof(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
368         build_proof(resolver, domain, Txt::TYPE)
369 }
370
371 /// Builds a DNSSEC proof for an TLSA record by querying a recursive resolver, returning the proof
372 /// as well as the TTL for the proof provided by the recursive resolver.
373 ///
374 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
375 /// module to validate the records contained.
376 #[cfg(feature = "std")]
377 pub fn build_tlsa_proof(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
378         build_proof(resolver, domain, TLSA::TYPE)
379 }
380
381
382 /// Builds a DNSSEC proof for an A record by querying a recursive resolver, returning the proof as
383 /// well as the TTL for the proof provided by the recursive resolver.
384 ///
385 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
386 /// module to validate the records contained.
387 #[cfg(feature = "tokio")]
388 pub async fn build_a_proof_async(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
389         build_proof_async(resolver, domain, A::TYPE).await
390 }
391
392 /// Builds a DNSSEC proof for an AAAA record by querying a recursive resolver, returning the proof
393 /// as well as the TTL for the proof provided by the recursive resolver.
394 ///
395 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
396 /// module to validate the records contained.
397 #[cfg(feature = "tokio")]
398 pub async fn build_aaaa_proof_async(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
399         build_proof_async(resolver, domain, AAAA::TYPE).await
400 }
401
402 /// Builds a DNSSEC proof for an TXT record by querying a recursive resolver, returning the proof
403 /// as well as the TTL for the proof provided by the recursive resolver.
404 ///
405 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
406 /// module to validate the records contained.
407 #[cfg(feature = "tokio")]
408 pub async fn build_txt_proof_async(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
409         build_proof_async(resolver, domain, Txt::TYPE).await
410 }
411
412 /// Builds a DNSSEC proof for an TLSA record by querying a recursive resolver, returning the proof
413 /// as well as the TTL for the proof provided by the recursive resolver.
414 ///
415 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
416 /// module to validate the records contained.
417 #[cfg(feature = "tokio")]
418 pub async fn build_tlsa_proof_async(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
419         build_proof_async(resolver, domain, TLSA::TYPE).await
420 }
421
422 #[cfg(all(feature = "validation", feature = "std", test))]
423 mod tests {
424         use super::*;
425         use crate::validation::*;
426
427         use rand::seq::SliceRandom;
428
429         use std::net::ToSocketAddrs;
430         use std::time::SystemTime;
431
432         #[test]
433         fn test_cloudflare_txt_query() {
434                 let sockaddr = "8.8.8.8:53".to_socket_addrs().unwrap().next().unwrap();
435                 let query_name = "cloudflare.com.".try_into().unwrap();
436                 let (proof, _) = build_txt_proof(sockaddr, &query_name).unwrap();
437
438                 let mut rrs = parse_rr_stream(&proof).unwrap();
439                 rrs.shuffle(&mut rand::rngs::OsRng);
440                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
441                 assert!(verified_rrs.verified_rrs.len() > 1);
442
443                 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
444                 assert!(verified_rrs.valid_from < now);
445                 assert!(verified_rrs.expires > now);
446         }
447
448         #[test]
449         fn test_sha1_query() {
450                 let sockaddr = "8.8.8.8:53".to_socket_addrs().unwrap().next().unwrap();
451                 let query_name = "benthecarman.com.".try_into().unwrap();
452                 let (proof, _) = build_a_proof(sockaddr, &query_name).unwrap();
453
454                 let mut rrs = parse_rr_stream(&proof).unwrap();
455                 rrs.shuffle(&mut rand::rngs::OsRng);
456                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
457                 assert!(verified_rrs.verified_rrs.len() >= 1);
458
459                 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
460                 assert!(verified_rrs.valid_from < now);
461                 assert!(verified_rrs.expires > now);
462         }
463
464         #[test]
465         fn test_txt_query() {
466                 let sockaddr = "8.8.8.8:53".to_socket_addrs().unwrap().next().unwrap();
467                 let query_name = "matt.user._bitcoin-payment.mattcorallo.com.".try_into().unwrap();
468                 let (proof, _) = build_txt_proof(sockaddr, &query_name).unwrap();
469
470                 let mut rrs = parse_rr_stream(&proof).unwrap();
471                 rrs.shuffle(&mut rand::rngs::OsRng);
472                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
473                 assert_eq!(verified_rrs.verified_rrs.len(), 1);
474
475                 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
476                 assert!(verified_rrs.valid_from < now);
477                 assert!(verified_rrs.expires > now);
478         }
479
480         #[test]
481         fn test_cname_query() {
482                 for resolver in ["1.1.1.1:53", "8.8.8.8:53", "9.9.9.9:53"] {
483                         let sockaddr = resolver.to_socket_addrs().unwrap().next().unwrap();
484                         let query_name = "cname_test.matcorallo.com.".try_into().unwrap();
485                         let (proof, _) = build_txt_proof(sockaddr, &query_name).unwrap();
486
487                         let mut rrs = parse_rr_stream(&proof).unwrap();
488                         rrs.shuffle(&mut rand::rngs::OsRng);
489                         let verified_rrs = verify_rr_stream(&rrs).unwrap();
490                         assert_eq!(verified_rrs.verified_rrs.len(), 2);
491
492                         let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
493                         assert!(verified_rrs.valid_from < now);
494                         assert!(verified_rrs.expires > now);
495
496                         let resolved_rrs = verified_rrs.resolve_name(&query_name);
497                         assert_eq!(resolved_rrs.len(), 1);
498                         if let RR::Txt(txt) = &resolved_rrs[0] {
499                                 assert_eq!(txt.name.as_str(), "txt_test.matcorallo.com.");
500                                 assert_eq!(txt.data, b"dnssec_prover_test");
501                         } else { panic!(); }
502                 }
503         }
504
505         #[cfg(feature = "tokio")]
506         use tokio_crate as tokio;
507
508         #[cfg(feature = "tokio")]
509         #[tokio::test]
510         async fn test_txt_query_async() {
511                 let sockaddr = "8.8.8.8:53".to_socket_addrs().unwrap().next().unwrap();
512                 let query_name = "matt.user._bitcoin-payment.mattcorallo.com.".try_into().unwrap();
513                 let (proof, _) = build_txt_proof_async(sockaddr, &query_name).await.unwrap();
514
515                 let mut rrs = parse_rr_stream(&proof).unwrap();
516                 rrs.shuffle(&mut rand::rngs::OsRng);
517                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
518                 assert_eq!(verified_rrs.verified_rrs.len(), 1);
519
520                 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
521                 assert!(verified_rrs.valid_from < now);
522                 assert!(verified_rrs.expires > now);
523         }
524
525         #[cfg(feature = "tokio")]
526         #[tokio::test]
527         async fn test_cross_domain_cname_query_async() {
528                 for resolver in ["1.1.1.1:53", "8.8.8.8:53", "9.9.9.9:53"] {
529                         let sockaddr = resolver.to_socket_addrs().unwrap().next().unwrap();
530                         let query_name = "wildcard.x_domain_cname_wild.matcorallo.com.".try_into().unwrap();
531                         let (proof, _) = build_txt_proof_async(sockaddr, &query_name).await.unwrap();
532
533                         let mut rrs = parse_rr_stream(&proof).unwrap();
534                         rrs.shuffle(&mut rand::rngs::OsRng);
535                         let verified_rrs = verify_rr_stream(&rrs).unwrap();
536                         assert_eq!(verified_rrs.verified_rrs.len(), 2);
537
538                         let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
539                         assert!(verified_rrs.valid_from < now);
540                         assert!(verified_rrs.expires > now);
541
542                         let resolved_rrs = verified_rrs.resolve_name(&query_name);
543                         assert_eq!(resolved_rrs.len(), 1);
544                         if let RR::Txt(txt) = &resolved_rrs[0] {
545                                 assert_eq!(txt.name.as_str(), "matt.user._bitcoin-payment.mattcorallo.com.");
546                                 assert!(txt.data.starts_with(b"bitcoin:"));
547                         } else { panic!(); }
548                 }
549         }
550 }