iroh/
test_utils.rs

1//! Internal utilities to support testing.
2use std::{net::Ipv4Addr, sync::Arc};
3
4use iroh_base::RelayUrl;
5use iroh_relay::{
6    RelayConfig, RelayMap, RelayQuicConfig,
7    server::{
8        AllowAll, CertConfig, DynAccessControl, QuicConfig, RelayConfig as RelayServerConfig,
9        Server, ServerConfig, SpawnError, TlsConfig,
10    },
11};
12use tokio::sync::oneshot;
13
14pub use self::{dns_and_pkarr_servers::DnsPkarrServer, qlog::QlogFileGroup};
15
16mod qlog;
17#[cfg(feature = "unstable-custom-transports")]
18pub mod test_transport;
19
20/// A drop guard to clean up test infrastructure.
21///
22/// After dropping the test infrastructure will asynchronously shutdown and release its
23/// resources.
24// Nightly sees the sender as dead code currently, but we only rely on Drop of the
25// sender.
26#[derive(Debug)]
27#[allow(dead_code)]
28pub struct CleanupDropGuard(pub(crate) oneshot::Sender<()>);
29
30/// Runs a relay server with QUIC enabled suitable for tests.
31///
32/// The returned `Url` is the url of the relay server in the returned [`RelayMap`].
33/// When dropped, the returned [`Server`] does will stop running.
34pub async fn run_relay_server() -> Result<(RelayMap, RelayUrl, Server), SpawnError> {
35    run_relay_server_with(true).await
36}
37
38/// Runs a relay server.
39///
40/// If `quic` is set to `true`, it will make the appropriate [`QuicConfig`] from the generated tls certificates and run the quic server at a random free port.
41///
42///
43/// The return value is similar to [`run_relay_server`].
44pub async fn run_relay_server_with(quic: bool) -> Result<(RelayMap, RelayUrl, Server), SpawnError> {
45    run_relay_server_with_access(quic, Arc::new(AllowAll)).await
46}
47
48/// Runs a relay server with a custom access control.
49///
50/// See [`run_relay_server_with`] for details on `quic`.
51pub async fn run_relay_server_with_access(
52    quic: bool,
53    access: Arc<dyn DynAccessControl>,
54) -> Result<(RelayMap, RelayUrl, Server), SpawnError> {
55    let (_certs, server_config) = iroh_relay::server::testing::self_signed_tls_certs_and_config();
56
57    let tls = TlsConfig::new(
58        (Ipv4Addr::LOCALHOST, 0),
59        CertConfig::Manual { server_config },
60    );
61
62    let mut relay = RelayServerConfig::new((Ipv4Addr::LOCALHOST, 0));
63    relay.tls = Some(tls);
64    relay.key_cache_capacity = Some(1024);
65    relay.access = access;
66
67    let mut config = ServerConfig::default();
68    config.relay = Some(relay);
69    config.quic = quic.then(|| QuicConfig::new((Ipv4Addr::LOCALHOST, 0)));
70
71    let server = Server::spawn(config).await?;
72    let url: RelayUrl = format!("https://{}", server.https_addr().expect("configured"))
73        .parse()
74        .expect("invalid relay url");
75
76    let quic = server
77        .quic_addr()
78        .map(|addr| RelayQuicConfig::new(addr.port()));
79    let n: RelayMap = RelayConfig::new(url.clone(), quic).into();
80    Ok((n, url, server))
81}
82
83mod dns_and_pkarr_servers {
84    use std::{net::SocketAddr, time::Duration};
85
86    use iroh_base::EndpointId;
87    use url::Url;
88
89    use super::CleanupDropGuard;
90    use crate::{
91        address_lookup::{
92            DnsAddressLookup, DnsAddressLookupBuilder, PkarrPublisher, PkarrPublisherBuilder,
93        },
94        dns::DnsResolver,
95        endpoint::presets::Preset,
96        test_utils::{
97            dns_server::run_dns_server, pkarr_dns_state::State, pkarr_relay::run_pkarr_relay,
98        },
99    };
100
101    /// Handle and drop guard for test DNS and Pkarr servers.
102    ///
103    /// Once the struct is dropped the servers will shut down.
104    #[derive(Debug)]
105    pub struct DnsPkarrServer {
106        /// The endpoint origin domain.
107        endpoint_origin: String,
108        /// The shared state of the DNS and Pkarr servers.
109        state: State,
110        /// The socket address of the DNS server.
111        nameserver: SocketAddr,
112        /// The HTTP URL of the Pkarr server.
113        pkarr_url: Url,
114        _dns_drop_guard: CleanupDropGuard,
115        _pkarr_drop_guard: CleanupDropGuard,
116    }
117
118    impl DnsPkarrServer {
119        /// Run DNS and Pkarr servers on localhost.
120        pub async fn run() -> std::io::Result<Self> {
121            Self::run_with_origin("dns.iroh.test".to_string()).await
122        }
123
124        /// Run DNS and Pkarr servers on localhost with the specified `endpoint_origin` domain.
125        pub async fn run_with_origin(endpoint_origin: String) -> std::io::Result<Self> {
126            let state = State::new(endpoint_origin.clone());
127            let (nameserver, dns_drop_guard) = run_dns_server(state.clone()).await?;
128            let (pkarr_url, pkarr_drop_guard) = run_pkarr_relay(state.clone()).await?;
129            Ok(Self {
130                endpoint_origin,
131                nameserver,
132                pkarr_url,
133                state,
134                _dns_drop_guard: dns_drop_guard,
135                _pkarr_drop_guard: pkarr_drop_guard,
136            })
137        }
138
139        /// Returns a [`Preset`] to apply the DNS address lookup and Pkarr Publisher to an endpoint.
140        pub fn preset(&self) -> impl Preset {
141            struct DnsPkarrPreset {
142                dns_address_lookup: DnsAddressLookupBuilder,
143                pkarr_address_publisher: PkarrPublisherBuilder,
144                dns_resolver: DnsResolver,
145            }
146
147            let preset = DnsPkarrPreset {
148                dns_address_lookup: DnsAddressLookup::builder(self.endpoint_origin.clone()),
149                pkarr_address_publisher: PkarrPublisher::builder(self.pkarr_url.clone()),
150                dns_resolver: self.dns_resolver(),
151            };
152            impl Preset for DnsPkarrPreset {
153                fn apply(self, builder: crate::endpoint::Builder) -> crate::endpoint::Builder {
154                    builder
155                        .addr_filter(crate::address_lookup::AddrFilter::relay_only())
156                        .address_lookup(self.dns_address_lookup)
157                        .address_lookup(self.pkarr_address_publisher)
158                        .dns_resolver(self.dns_resolver)
159                }
160            }
161            preset
162        }
163
164        /// Create a [`DnsResolver`] configured to use the test DNS server.
165        pub fn dns_resolver(&self) -> DnsResolver {
166            DnsResolver::with_nameserver(self.nameserver)
167        }
168
169        /// Returns the PKARR server HTTP URL.
170        pub fn pkarr_url(&self) -> &Url {
171            &self.pkarr_url
172        }
173
174        /// Wait until a Pkarr announce for an endpoint is published to the server.
175        ///
176        /// If `timeout` elapses an error is returned.
177        pub async fn on_endpoint(
178            &self,
179            endpoint_id: &EndpointId,
180            timeout: Duration,
181        ) -> std::io::Result<()> {
182            self.state.on_endpoint(endpoint_id, timeout).await
183        }
184    }
185}
186
187pub(crate) mod dns_server {
188    use std::{
189        future::Future,
190        net::{Ipv4Addr, SocketAddr},
191    };
192
193    use n0_future::future::Boxed as BoxFuture;
194    use simple_dns::{Packet, PacketFlag};
195    use tokio::{net::UdpSocket, sync::oneshot};
196    use tracing::{debug, error, warn};
197
198    use super::CleanupDropGuard;
199
200    /// Trait used by [`run_dns_server`] for answering DNS queries.
201    pub(crate) trait QueryHandler: Send + Sync + 'static {
202        fn resolve(
203            &self,
204            query: &Packet<'_>,
205            reply: &mut Packet<'static>,
206        ) -> impl Future<Output = std::io::Result<()>> + Send;
207    }
208
209    pub(crate) type QueryHandlerFunction = Box<
210        dyn Fn(&Packet<'_>, &mut Packet<'static>) -> BoxFuture<std::io::Result<()>>
211            + Send
212            + Sync
213            + 'static,
214    >;
215
216    impl QueryHandler for QueryHandlerFunction {
217        fn resolve(
218            &self,
219            query: &Packet<'_>,
220            reply: &mut Packet<'static>,
221        ) -> impl Future<Output = std::io::Result<()>> + Send {
222            (self)(query, reply)
223        }
224    }
225
226    /// Run a DNS server.
227    ///
228    /// Must pass a [`QueryHandler`] that answers queries.
229    pub(crate) async fn run_dns_server(
230        resolver: impl QueryHandler,
231    ) -> std::io::Result<(SocketAddr, CleanupDropGuard)> {
232        let bind_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 0));
233        let socket = UdpSocket::bind(bind_addr).await?;
234        let bound_addr = socket.local_addr()?;
235        let s = TestDnsServer { socket, resolver };
236        let (tx, mut rx) = oneshot::channel();
237        tokio::task::spawn(async move {
238            tokio::select! {
239                _ = &mut rx => {
240                    debug!("shutting down dns server");
241                }
242                res = s.run() => {
243                    if let Err(e) = res {
244                        error!("error running dns server {e:?}");
245                    }
246                }
247            }
248        });
249        Ok((bound_addr, CleanupDropGuard(tx)))
250    }
251
252    struct TestDnsServer<R> {
253        resolver: R,
254        socket: UdpSocket,
255    }
256
257    impl<R: QueryHandler> TestDnsServer<R> {
258        async fn run(self) -> std::io::Result<()> {
259            let mut buf = [0; 1450];
260            loop {
261                let res = self.socket.recv_from(&mut buf).await;
262                let (len, from) = res?;
263                if let Err(err) = self.handle_datagram(from, &buf[..len]).await {
264                    warn!(?err, %from, "failed to handle incoming datagram");
265                }
266            }
267        }
268
269        async fn handle_datagram(
270            &self,
271            from: SocketAddr,
272            buf: &[u8],
273        ) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
274            let packet = Packet::parse(buf).map_err(std::io::Error::other)?;
275            debug!(questions = ?packet.questions, %from, "received query");
276            let mut reply = Packet::new_reply(packet.id());
277            reply.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE);
278            // Echo the question section, as a real resolver does. The client
279            // validates that the response question matches its query.
280            reply.questions = packet
281                .questions
282                .iter()
283                .map(|q| q.clone().into_owned())
284                .collect();
285            self.resolver.resolve(&packet, &mut reply).await?;
286            debug!(?reply, %from, "send reply");
287            let buf = reply.build_bytes_vec().map_err(std::io::Error::other)?;
288            let len = self.socket.send_to(&buf, from).await?;
289            assert_eq!(len, buf.len(), "failed to send complete packet");
290            Ok(())
291        }
292    }
293}
294
295pub(crate) mod pkarr_relay {
296    use std::{
297        future::IntoFuture,
298        net::{Ipv4Addr, SocketAddr},
299    };
300
301    use axum::{
302        Router,
303        extract::{Path, State},
304        response::IntoResponse,
305        routing::put,
306    };
307    use bytes::Bytes;
308    use iroh_base::EndpointId;
309    use tokio::sync::oneshot;
310    use tracing::{debug, error, warn};
311    use url::Url;
312
313    use super::CleanupDropGuard;
314    use crate::test_utils::pkarr_dns_state::State as AppState;
315
316    pub(crate) async fn run_pkarr_relay(
317        state: AppState,
318    ) -> std::io::Result<(Url, CleanupDropGuard)> {
319        let bind_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 0));
320        let app = Router::new()
321            .route("/pkarr/{key}", put(pkarr_put))
322            .with_state(state);
323        let listener = tokio::net::TcpListener::bind(bind_addr).await?;
324        let bound_addr = listener.local_addr()?;
325        let url: Url = format!("http://{bound_addr}/pkarr")
326            .parse()
327            .expect("valid url");
328
329        let (tx, mut rx) = oneshot::channel();
330        tokio::spawn(async move {
331            let serve = axum::serve(listener, app);
332            tokio::select! {
333                _ = &mut rx => {
334                    debug!("shutting down pkarr server");
335                }
336                res = serve.into_future() => {
337                    if let Err(e) = res {
338                        error!("pkarr server error: {e:?}");
339                    }
340                }
341            }
342        });
343        Ok((url, CleanupDropGuard(tx)))
344    }
345
346    async fn pkarr_put(
347        State(state): State<AppState>,
348        Path(key): Path<String>,
349        body: Bytes,
350    ) -> Result<impl IntoResponse, AppError> {
351        let key = EndpointId::from_z32(&key).map_err(std::io::Error::other)?;
352        let signed_packet = iroh_dns::pkarr::SignedPacket::from_relay_payload(&key, &body)
353            .map_err(std::io::Error::other)?;
354        let _updated = state.upsert(signed_packet)?;
355        Ok(http::StatusCode::NO_CONTENT)
356    }
357
358    #[derive(Debug)]
359    struct AppError(std::io::Error);
360    impl<T: Into<std::io::Error>> From<T> for AppError {
361        fn from(value: T) -> Self {
362            Self(value.into())
363        }
364    }
365    impl IntoResponse for AppError {
366        fn into_response(self) -> axum::response::Response {
367            warn!(err = ?self, "request failed");
368            (http::StatusCode::INTERNAL_SERVER_ERROR, self.0.to_string()).into_response()
369        }
370    }
371}
372
373pub(crate) mod pkarr_dns_state {
374    use std::{
375        collections::{HashMap, hash_map},
376        future::Future,
377        sync::{Arc, Mutex},
378        time::Duration,
379    };
380
381    use iroh_base::EndpointId;
382    use iroh_dns::{IROH_TXT_NAME, endpoint_info::EndpointInfo, pkarr::SignedPacket};
383    use simple_dns::{
384        CLASS, Name, Packet, ResourceRecord,
385        rdata::{RData, TXT},
386    };
387    use tracing::debug;
388
389    use crate::test_utils::dns_server::QueryHandler;
390
391    #[derive(Debug, Clone)]
392    pub(crate) struct State {
393        packets: Arc<Mutex<HashMap<EndpointId, SignedPacket>>>,
394        origin: String,
395        notify: Arc<tokio::sync::Notify>,
396    }
397
398    impl State {
399        pub(crate) fn new(origin: String) -> Self {
400            Self {
401                packets: Default::default(),
402                origin,
403                notify: Arc::new(tokio::sync::Notify::new()),
404            }
405        }
406
407        pub(crate) fn on_update(&self) -> tokio::sync::futures::Notified<'_> {
408            self.notify.notified()
409        }
410
411        pub(crate) async fn on_endpoint(
412            &self,
413            endpoint: &EndpointId,
414            timeout: Duration,
415        ) -> std::io::Result<()> {
416            let timeout = tokio::time::sleep(timeout);
417            tokio::pin!(timeout);
418            while self.get(endpoint, |p| {
419                let endpoint_info = p
420                    .as_ref()
421                    .and_then(|p| EndpointInfo::from_pkarr_signed_packet(p).ok());
422                debug!("got info {:#?}", endpoint_info);
423                // Wait until we have endpoint info with actual addressing data,
424                // not just an empty initial publish.
425                endpoint_info
426                    .as_ref()
427                    .is_none_or(|info| info.data.addrs().next().is_none())
428            }) {
429                tokio::select! {
430                    _ = &mut timeout => return Err(std::io::Error::other("timeout")),
431                    _ = self.on_update() => {}
432                }
433            }
434            Ok(())
435        }
436
437        pub(crate) fn upsert(&self, signed_packet: SignedPacket) -> std::io::Result<bool> {
438            let endpoint_id = signed_packet.public_key();
439            let mut map = self.packets.lock().expect("poisoned");
440            let updated = match map.entry(endpoint_id) {
441                hash_map::Entry::Vacant(e) => {
442                    e.insert(signed_packet);
443                    true
444                }
445                hash_map::Entry::Occupied(mut e) => {
446                    if signed_packet.more_recent_than(e.get()) {
447                        e.insert(signed_packet);
448                        true
449                    } else {
450                        false
451                    }
452                }
453            };
454            if updated {
455                self.notify.notify_waiters();
456            }
457            Ok(updated)
458        }
459
460        /// Returns a mutex guard, do not hold over await points
461        pub(crate) fn get<F, T>(&self, endpoint_id: &EndpointId, cb: F) -> T
462        where
463            F: FnOnce(Option<&mut SignedPacket>) -> T,
464        {
465            let mut map = self.packets.lock().expect("poisoned");
466            let packet = map.get_mut(endpoint_id);
467            cb(packet)
468        }
469
470        pub(crate) fn resolve_dns(
471            &self,
472            query: &Packet<'_>,
473            reply: &mut Packet<'static>,
474            ttl: u32,
475        ) -> std::io::Result<()> {
476            for question in &query.questions {
477                let domain_name = question.qname.to_string();
478                let Some(endpoint_id) = endpoint_id_from_domain_name(&domain_name) else {
479                    continue;
480                };
481
482                self.get(&endpoint_id, |packet| {
483                    if let Some(packet) = packet {
484                        let endpoint_info = EndpointInfo::from_pkarr_signed_packet(packet)
485                            .map_err(std::io::Error::other)?;
486                        for record in
487                            endpoint_info_to_dns_records(&endpoint_info, &self.origin, ttl)
488                        {
489                            reply.answers.push(record);
490                        }
491                    }
492                    Ok::<_, std::io::Error>(())
493                })?;
494            }
495            Ok(())
496        }
497    }
498
499    impl QueryHandler for State {
500        fn resolve(
501            &self,
502            query: &Packet<'_>,
503            reply: &mut Packet<'static>,
504        ) -> impl Future<Output = std::io::Result<()>> + Send {
505            const TTL: u32 = 30;
506            let res = self.resolve_dns(query, reply, TTL);
507            std::future::ready(res)
508        }
509    }
510
511    /// Parses a [`EndpointId`] from a DNS domain name.
512    ///
513    /// Splits the domain name into labels on each dot. Expects the first label to be
514    /// [`IROH_TXT_NAME`] and the second label to be a z32 encoded [`EndpointId`]. Ignores
515    /// subsequent labels.
516    ///
517    /// Returns a [`EndpointId`] if parsed successfully, otherwise `None`.
518    fn endpoint_id_from_domain_name(name: &str) -> Option<EndpointId> {
519        let mut labels = name.split(".");
520        let label = labels.next()?;
521        if label != IROH_TXT_NAME {
522            return None;
523        }
524        let label = labels.next()?;
525        let endpoint_id = EndpointId::from_z32(label).ok()?;
526        Some(endpoint_id)
527    }
528
529    /// Converts an [`EndpointInfo`] into simple-dns [`ResourceRecord`]s.
530    fn endpoint_info_to_dns_records(
531        endpoint_info: &EndpointInfo,
532        origin: &str,
533        ttl: u32,
534    ) -> Vec<ResourceRecord<'static>> {
535        let txt_strings = endpoint_info.to_txt_strings();
536        to_dns_records(txt_strings, endpoint_info.endpoint_id, origin, ttl)
537    }
538
539    /// Converts TXT strings to simple-dns [`ResourceRecord`]s.
540    fn to_dns_records(
541        txt_strings: Vec<String>,
542        endpoint_id: EndpointId,
543        origin: &str,
544        ttl: u32,
545    ) -> Vec<ResourceRecord<'static>> {
546        let name = format!("{IROH_TXT_NAME}.{}.{origin}", endpoint_id.to_z32());
547        let name = Name::new(&name).expect("invalid name").into_owned();
548        txt_strings
549            .into_iter()
550            .map(move |s| {
551                let txt = TXT::new()
552                    .with_string(&s)
553                    .expect("invalid TXT string")
554                    .into_owned();
555                let rdata = RData::TXT(txt);
556                ResourceRecord::new(name.clone(), CLASS::IN, ttl, rdata)
557            })
558            .collect()
559    }
560
561    #[cfg(test)]
562    mod tests {
563        use iroh_base::EndpointId;
564        use n0_error::Result;
565
566        #[test]
567        fn test_endpoint_id_from_domain_name() -> Result {
568            let name = "_iroh.dgjpkxyn3zyrk3zfads5duwdgbqpkwbjxfj4yt7rezidr3fijccy.dns.iroh.link.";
569            let endpoint_id = super::endpoint_id_from_domain_name(name);
570            let expected: EndpointId =
571                "1992d53c02cdc04566e5c0edb1ce83305cd550297953a047a445ea3264b54b18".parse()?;
572            assert_eq!(endpoint_id, Some(expected));
573            Ok(())
574        }
575    }
576}