iroh/address_lookup/
pkarr.rs

1//! An address lookup service which publishes and resolves endpoint information using a [pkarr] relay.
2//!
3//! Public-Key Addressable Resource Records, [pkarr], is a system which allows publishing
4//! [DNS Resource Records] owned by a particular [`SecretKey`] under a name derived from its
5//! corresponding [`PublicKey`], also known as the [`EndpointId`].  Additionally this pkarr
6//! Resource Record is signed using the same [`SecretKey`], ensuring authenticity of the
7//! record.
8//!
9//! Pkarr normally stores these records on the [Mainline DHT], but also provides two bridges
10//! that do not require clients to directly interact with the DHT:
11//!
12//! - Resolvers are servers which expose the pkarr Resource Record under a domain name,
13//!   e.g. `o3dks..6uyy.dns.iroh.link`.  This allows looking up the pkarr Resource Records
14//!   using normal DNS clients.  These resolvers would normally perform lookups on the
15//!   Mainline DHT augmented with a local cache to improve performance.
16//!
17//! - Relays are servers which allow both publishing and looking up of the pkarr Resource
18//!   Records using HTTP PUT and GET requests.  They will usually perform the publishing to
19//!   the Mainline DHT on behalf on the client as well as cache lookups performed on the DHT
20//!   to improve performance.
21//!
22//! [`PkarrPublisher`] filters published addresses: only relay addresses are published by default.
23//! To change this behavior, use [`PkarrPublisherBuilder::addr_filter`] and set it to e.g. [`AddrFilter::unfiltered`].
24//! This can be useful to enable publishing IP addresses if the iroh endpoint is reachable via public
25//! IP addresses.
26//!
27//! For address lookup in iroh the pkarr Resource Records contain the addressing information,
28//! providing endpoints which retrieve the pkarr Resource Record with enough detail
29//! to contact the iroh endpoint.
30//!
31//! There are several Address Lookup's built on top of pkarr, which can be composed
32//! to the application's needs:
33//!
34//! - [`PkarrPublisher`], which publishes to a pkarr relay server using HTTP.
35//!
36//! - [`PkarrResolver`], which resolves from a pkarr relay server using HTTP.
37//!
38//! - [`address_lookup::DnsAddressLookup`], which resolves from a DNS server.
39//!
40//! Mainline-DHT-based pkarr publishing/lookup lives in the
41//! [`iroh-mainline-address-lookup`] crate.
42//!
43//! [`iroh-mainline-address-lookup`]: https://docs.rs/iroh-mainline-address-lookup
44//! [pkarr]: https://pkarr.org
45//! [DNS Resource Records]: https://en.wikipedia.org/wiki/Domain_Name_System#Resource_records
46//! [Mainline DHT]: https://en.wikipedia.org/wiki/Mainline_DHT
47//! [`SecretKey`]: crate::SecretKey
48//! [`PublicKey`]: crate::PublicKey
49//! [`EndpointId`]: crate::EndpointId
50//! [`address_lookup::DnsAddressLookup`]: crate::address_lookup::DnsAddressLookup
51//! [`N0` preset]: crate::endpoint::presets::N0
52//! [`AddrFilter`]: crate::address_lookup::AddrFilter
53//! [`AddrFilter::relay_only`]: crate::address_lookup::AddrFilter::relay_only
54//! [`AddrFilter::unfiltered`]: crate::address_lookup::AddrFilter::unfiltered
55//! [`PkarrPublisherBuilder::addr_filter`]: PkarrPublisherBuilder::addr_filter
56
57use std::sync::Arc;
58
59use iroh_base::{EndpointId, RelayUrl, SecretKey};
60use iroh_dns::{
61    EncodingError,
62    endpoint_info::{AddrFilter, EndpointInfo},
63    pkarr::{SignedPacket, SignedPacketVerifyError},
64};
65use n0_error::{AnyError, anyerr, e, stack_error};
66use n0_future::{
67    boxed::BoxStream,
68    task::{self, AbortOnDropHandle},
69    time::{self, Duration, Instant},
70};
71use n0_watcher::{Disconnected, Watchable, Watcher as _};
72use tracing::{Instrument, debug, info_span, trace, warn};
73use url::Url;
74
75#[cfg(not(wasm_browser))]
76use crate::dns::DnsResolver;
77use crate::{
78    Endpoint,
79    address_lookup::{
80        AddressLookup, AddressLookupBuilder, AddressLookupBuilderError, EndpointData,
81        Error as AddressLookupError, Item as AddressLookupItem,
82    },
83    endpoint::force_staging_infra,
84    util::reqwest_client_builder,
85};
86
87#[allow(missing_docs)]
88#[stack_error(derive, add_meta)]
89#[non_exhaustive]
90pub enum PkarrError {
91    #[error("Invalid public key")]
92    PublicKey {
93        #[error(std_err)]
94        source: iroh_base::KeyParsingError,
95    },
96    #[error("Packet failed to verify")]
97    Verify {
98        #[error(std_err)]
99        source: SignedPacketVerifyError,
100    },
101    #[error("Invalid relay URL")]
102    InvalidRelayUrl { url: RelayUrl },
103    #[error("Error sending http request")]
104    HttpSend { source: AnyError },
105    #[error("Error resolving http request")]
106    HttpRequest { status: http::StatusCode },
107    #[error("Http payload error")]
108    HttpPayload { source: AnyError },
109    #[error("EncodingError")]
110    Encoding { source: EncodingError },
111}
112
113impl From<PkarrError> for AddressLookupError {
114    fn from(err: PkarrError) -> Self {
115        AddressLookupError::from_err_any("pkarr", err)
116    }
117}
118
119/// The production pkarr relay run by [number 0].
120///
121/// This server is both a pkarr relay server as well as a DNS resolver, see the [module
122/// documentation].  However it does not interact with the Mainline DHT, so is a more
123/// central service.  It is a reliable service to use for address lookup.
124///
125/// [number 0]: https://n0.computer
126/// [module documentation]: crate::address_lookup::pkarr
127pub const N0_DNS_PKARR_RELAY_PROD: &str = "https://dns.iroh.link/pkarr";
128/// The testing pkarr relay run by [number 0].
129///
130/// This server operates similarly to [`N0_DNS_PKARR_RELAY_PROD`] but is not as reliable.
131/// It is meant for more experimental use and testing purposes.
132///
133/// [number 0]: https://n0.computer
134pub const N0_DNS_PKARR_RELAY_STAGING: &str = "https://staging-dns.iroh.link/pkarr";
135
136/// Default TTL for the records in the pkarr signed packet.
137///
138/// The Time To Live (TTL) tells DNS caches how long to store a record. It is ignored by the
139/// `iroh-dns-server`, e.g. as running on [`N0_DNS_PKARR_RELAY_PROD`], as the home server
140/// keeps the records for the domain. When using the pkarr relay no DNS is involved and the
141/// setting is ignored.
142// TODO(flub): huh?
143pub const DEFAULT_PKARR_TTL: u32 = 30;
144
145/// Interval in which to republish the endpoint info even if unchanged: 5 minutes.
146pub const DEFAULT_REPUBLISH_INTERVAL: Duration = Duration::from_secs(60 * 5);
147
148/// Builder for [`PkarrPublisher`].
149///
150/// See [`PkarrPublisher::builder`].
151#[derive(Debug)]
152pub struct PkarrPublisherBuilder {
153    pkarr_relay: Url,
154    ttl: u32,
155    republish_interval: Duration,
156    filter: AddrFilter,
157    #[cfg(not(wasm_browser))]
158    dns_resolver: Option<DnsResolver>,
159    /// Taken from the endpoint in `into_address_lookup`.
160    #[cfg(not(wasm_browser))]
161    proxy_url: Option<Url>,
162}
163
164impl PkarrPublisherBuilder {
165    /// See [`PkarrPublisher::builder`].
166    fn new(pkarr_relay: Url) -> Self {
167        Self {
168            pkarr_relay,
169            ttl: DEFAULT_PKARR_TTL,
170            republish_interval: DEFAULT_REPUBLISH_INTERVAL,
171            filter: AddrFilter::relay_only(),
172            #[cfg(not(wasm_browser))]
173            dns_resolver: None,
174            #[cfg(not(wasm_browser))]
175            proxy_url: None,
176        }
177    }
178
179    /// See [`PkarrPublisher::n0_dns`].
180    fn n0_dns() -> Self {
181        let pkarr_relay = match force_staging_infra() {
182            true => N0_DNS_PKARR_RELAY_STAGING,
183            false => N0_DNS_PKARR_RELAY_PROD,
184        };
185
186        let pkarr_relay: Url = pkarr_relay.parse().expect("url is valid");
187        Self::new(pkarr_relay)
188    }
189
190    /// Sets the TTL (time-to-live) for published packets.
191    ///
192    /// Default is [`DEFAULT_PKARR_TTL`].
193    pub fn ttl(mut self, ttl: u32) -> Self {
194        self.ttl = ttl;
195        self
196    }
197
198    /// Sets the interval after which packets are republished even if our endpoint info did not change.
199    ///
200    /// Default is [`DEFAULT_REPUBLISH_INTERVAL`].
201    pub fn republish_interval(mut self, republish_interval: Duration) -> Self {
202        self.republish_interval = republish_interval;
203        self
204    }
205
206    /// Sets the DNS resolver to use for resolving the pkarr relay URL.
207    #[cfg(not(wasm_browser))]
208    pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self {
209        self.dns_resolver = Some(dns_resolver);
210        self
211    }
212
213    /// Sets the address filter to control which addresses are published to the pkarr server.
214    ///
215    /// By default [`AddrFilter::relay_only`] is used. This avoids leaking IP addresses to the
216    /// public pkarr server.
217    ///
218    /// However, enabling IP address publishing can be useful, e.g. when iroh runs on a machine
219    /// connected to the internet via public IP addresses without a firewall.
220    /// In such cases, publishing them can make dialing such endpoints via DNS or Pkarr lookup
221    /// faster, potentially skipping a relay connection altogether.
222    pub fn addr_filter(mut self, filter: AddrFilter) -> Self {
223        self.filter = filter;
224        self
225    }
226
227    /// Builds the [`PkarrPublisher`] with the passed secret key for signing packets.
228    ///
229    /// This publisher will be able to publish [pkarr](https://pkarr.org) records for [`SecretKey`].
230    pub fn build(self, secret_key: SecretKey, tls_config: rustls::ClientConfig) -> PkarrPublisher {
231        #[cfg(wasm_browser)]
232        let pkarr_client = PkarrRelayClient::new(self.pkarr_relay);
233
234        #[cfg(not(wasm_browser))]
235        let pkarr_client = PkarrRelayClient::with_proxy(
236            self.pkarr_relay,
237            tls_config,
238            self.dns_resolver.unwrap_or_default(),
239            self.proxy_url,
240        );
241
242        PkarrPublisher::new(
243            secret_key,
244            pkarr_client,
245            self.ttl,
246            self.republish_interval,
247            self.filter,
248        )
249    }
250}
251
252impl AddressLookupBuilder for PkarrPublisherBuilder {
253    fn into_address_lookup(
254        mut self,
255        endpoint: &Endpoint,
256    ) -> Result<impl AddressLookup, AddressLookupBuilderError> {
257        #[cfg(not(wasm_browser))]
258        if self.dns_resolver.is_none() {
259            self.dns_resolver = Some(endpoint.dns_resolver()?.clone());
260        }
261        #[cfg(not(wasm_browser))]
262        {
263            self.proxy_url = endpoint.proxy_url().cloned();
264        }
265        let tls_config = endpoint.tls_config().clone();
266        Ok(self.build(endpoint.secret_key().clone(), tls_config))
267    }
268}
269
270/// Publisher of address lookup information to a [pkarr] relay.
271///
272/// This publisher uses HTTP to publish address lookup information to a pkarr relay
273/// server, see the [module docs] for details.
274///
275/// This implements the [`AddressLookup`] trait to be used as an address lookup service.  Note
276/// that it only publishes address lookup information, for the corresponding resolver use
277/// the [`PkarrResolver`] together with [`AddressLookupServices`].
278///
279/// By default this publisher only publishes the [`RelayUrl`], to avoid leaking IP addresses to
280/// the public pkarr server.  Which addresses are published is controlled by the [`AddrFilter`]
281/// set via [`PkarrPublisherBuilder::addr_filter`].
282///
283/// [pkarr]: https://pkarr.org
284/// [module docs]: crate::address_lookup::pkarr
285/// [`RelayUrl`]: crate::RelayUrl
286/// [`AddressLookupServices`]: super::AddressLookupServices
287#[derive(derive_more::Debug, Clone)]
288pub struct PkarrPublisher {
289    endpoint_id: EndpointId,
290    watchable: Watchable<Option<EndpointInfo>>,
291    addr_filter: AddrFilter,
292    _drop_guard: Arc<AbortOnDropHandle<()>>,
293}
294
295impl PkarrPublisher {
296    /// Returns a [`PkarrPublisherBuilder`] that publishes endpoint info to a [pkarr] relay at `pkarr_relay`.
297    ///
298    /// If no further options are set, the pkarr publisher will use [`DEFAULT_PKARR_TTL`] as the
299    /// time-to-live value for the published packets, and it will republish Address Lookup information
300    /// every [`DEFAULT_REPUBLISH_INTERVAL`], even if the information is unchanged.
301    ///
302    /// [`PkarrPublisherBuilder`] implements [`AddressLookupBuilder`], so it can be passed to [`address_lookup`].
303    /// It will then use the endpoint's secret key to sign published packets.
304    ///
305    /// [`address_lookup`]:  crate::endpoint::Builder::address_lookup
306    /// [pkarr]: https://pkarr.org
307    pub fn builder(pkarr_relay: Url) -> PkarrPublisherBuilder {
308        PkarrPublisherBuilder::new(pkarr_relay)
309    }
310
311    /// Creates a new [`PkarrPublisher`] with a custom TTL and republish intervals.
312    ///
313    /// This allows creating the publisher with custom time-to-live values of the
314    /// [`SignedPacket`]s as well as a custom republish interval.
315    fn new(
316        secret_key: SecretKey,
317        pkarr_client: PkarrRelayClient,
318        ttl: u32,
319        republish_interval: Duration,
320        addr_filter: AddrFilter,
321    ) -> Self {
322        debug!(
323            "creating pkarr publisher that publishes to {}",
324            pkarr_client.pkarr_relay_url
325        );
326        let endpoint_id = secret_key.public();
327
328        let watchable = Watchable::default();
329        let service = PublisherService {
330            ttl,
331            watcher: watchable.watch(),
332            secret_key,
333            pkarr_client,
334            republish_interval,
335        };
336        let join_handle = task::spawn(service.run().instrument(info_span!("pkarr_publish")));
337        Self {
338            watchable,
339            endpoint_id,
340            addr_filter,
341            _drop_guard: Arc::new(AbortOnDropHandle::new(join_handle)),
342        }
343    }
344
345    /// Creates a pkarr publisher which uses the [number 0] pkarr relay server.
346    ///
347    /// This uses the pkarr relay server operated by [number 0], at
348    /// [`N0_DNS_PKARR_RELAY_PROD`].
349    ///
350    /// When running with the environment variable
351    /// `IROH_FORCE_STAGING_RELAYS` set to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`]
352    /// server is used instead.
353    ///
354    /// [number 0]: https://n0.computer
355    pub fn n0_dns() -> PkarrPublisherBuilder {
356        PkarrPublisherBuilder::n0_dns()
357    }
358
359    /// Publishes the addressing information about this endpoint to a pkarr relay.
360    ///
361    /// This is a nonblocking function, the actual update is performed in the background.
362    pub fn update_endpoint_data(&self, data: &EndpointData) {
363        let data = data.apply_filter(&self.addr_filter).into_owned();
364        let info = EndpointInfo::from_parts(self.endpoint_id, data);
365        self.watchable.set(Some(info)).ok();
366    }
367}
368
369impl AddressLookup for PkarrPublisher {
370    fn publish(&self, data: &EndpointData) {
371        self.update_endpoint_data(data);
372    }
373}
374
375/// Publish endpoint info to a pkarr relay.
376#[derive(derive_more::Debug, Clone)]
377struct PublisherService {
378    #[debug("SecretKey")]
379    secret_key: SecretKey,
380    #[debug("PkarrClient")]
381    pkarr_client: PkarrRelayClient,
382    watcher: n0_watcher::Direct<Option<EndpointInfo>>,
383    ttl: u32,
384    republish_interval: Duration,
385}
386
387impl PublisherService {
388    async fn run(mut self) {
389        let mut failed_attempts = 0;
390        let republish = time::sleep(Duration::MAX);
391        tokio::pin!(republish);
392        loop {
393            if !self.watcher.is_connected() {
394                break;
395            }
396            if let Some(info) = self.watcher.get() {
397                match self.publish_current(info).await {
398                    Err(err) => {
399                        failed_attempts += 1;
400                        // Retry after increasing timeout
401                        let retry_after = Duration::from_secs(failed_attempts);
402                        republish.as_mut().reset(Instant::now() + retry_after);
403                        warn!(
404                            err = %format!("{err:#}"),
405                            url = %self.pkarr_client.pkarr_relay_url ,
406                            ?retry_after,
407                            %failed_attempts,
408                            "Failed to publish to pkarr",
409                        );
410                    }
411                    Ok(()) => {
412                        failed_attempts = 0;
413                        // Republish after fixed interval
414                        republish
415                            .as_mut()
416                            .reset(Instant::now() + self.republish_interval);
417                    }
418                }
419            }
420            // Wait until either the retry/republish timeout is reached, or the endpoint info changed.
421            tokio::select! {
422                res = self.watcher.updated() => match res {
423                    Ok(_) => debug!("Publish endpoint info to pkarr (info changed)"),
424                    Err(Disconnected { .. }) => break,
425                },
426                _ = &mut republish => debug!("Publish endpoint info to pkarr (interval elapsed)"),
427            }
428        }
429    }
430
431    async fn publish_current(&self, info: EndpointInfo) -> Result<(), PkarrError> {
432        debug!(
433            data = ?info.data,
434            pkarr_relay = %self.pkarr_client.pkarr_relay_url,
435            "Publishing endpoint info to pkarr"
436        );
437        let signed_packet = info
438            .to_pkarr_signed_packet(&self.secret_key, self.ttl)
439            .map_err(|err| e!(PkarrError::Encoding, err))?;
440        self.pkarr_client.publish(&signed_packet).await?;
441        trace!(
442            data = ?info.data,
443            pkarr_relay = %self.pkarr_client.pkarr_relay_url,
444            "Published endpoint info to pkarr"
445        );
446        Ok(())
447    }
448}
449
450/// Builder for [`PkarrResolver`].
451///
452/// See [`PkarrResolver::builder`].
453#[derive(Debug)]
454pub struct PkarrResolverBuilder {
455    pkarr_relay: Url,
456    #[cfg(not(wasm_browser))]
457    dns_resolver: Option<DnsResolver>,
458    /// Taken from the endpoint in `into_address_lookup`.
459    #[cfg(not(wasm_browser))]
460    proxy_url: Option<Url>,
461}
462
463impl PkarrResolverBuilder {
464    /// Sets the DNS resolver to use for resolving the pkarr relay URL.
465    #[cfg(not(wasm_browser))]
466    pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self {
467        self.dns_resolver = Some(dns_resolver);
468        self
469    }
470
471    /// Creates a [`PkarrResolver`] from this builder.
472    pub fn build(self, tls_config: rustls::ClientConfig) -> PkarrResolver {
473        #[cfg(wasm_browser)]
474        let pkarr_client = PkarrRelayClient::new(self.pkarr_relay);
475
476        #[cfg(not(wasm_browser))]
477        let pkarr_client = PkarrRelayClient::with_proxy(
478            self.pkarr_relay,
479            tls_config,
480            self.dns_resolver.unwrap_or_default(),
481            self.proxy_url,
482        );
483
484        PkarrResolver { pkarr_client }
485    }
486}
487
488impl AddressLookupBuilder for PkarrResolverBuilder {
489    fn into_address_lookup(
490        mut self,
491        endpoint: &Endpoint,
492    ) -> Result<impl AddressLookup, AddressLookupBuilderError> {
493        #[cfg(not(wasm_browser))]
494        if self.dns_resolver.is_none() {
495            self.dns_resolver = Some(endpoint.dns_resolver()?.clone());
496        }
497        #[cfg(not(wasm_browser))]
498        {
499            self.proxy_url = endpoint.proxy_url().cloned();
500        }
501        let tls_config = endpoint.tls_config().clone();
502        Ok(self.build(tls_config))
503    }
504}
505
506/// Resolver of address lookup information from a [pkarr] relay.
507///
508/// The resolver uses HTTP to query address lookup information from a pkarr relay server,
509/// see the [module docs] for details.
510///
511/// This implements the [`AddressLookup`] trait to be used as an address lookup service.  Note
512/// that it only resolves address lookup information, for the corresponding publisher use
513/// the [`PkarrPublisher`] together with [`AddressLookupServices`].
514///
515/// [pkarr]: https://pkarr.org
516/// [module docs]: crate::address_lookup::pkarr
517/// [`AddressLookupServices`]: super::AddressLookupServices
518#[derive(derive_more::Debug, Clone)]
519pub struct PkarrResolver {
520    pkarr_client: PkarrRelayClient,
521}
522
523impl PkarrResolver {
524    /// Creates a new resolver builder using the pkarr relay server at the URL.
525    ///
526    /// The builder implements [`AddressLookupBuilder`].
527    pub fn builder(pkarr_relay: Url) -> PkarrResolverBuilder {
528        PkarrResolverBuilder {
529            pkarr_relay,
530            #[cfg(not(wasm_browser))]
531            dns_resolver: None,
532            #[cfg(not(wasm_browser))]
533            proxy_url: None,
534        }
535    }
536
537    /// Creates a pkarr resolver builder which uses the [number 0] pkarr relay server.
538    ///
539    /// This uses the pkarr relay server operated by [number 0] at
540    /// [`N0_DNS_PKARR_RELAY_PROD`].
541    ///
542    /// When running with the environment variable `IROH_FORCE_STAGING_RELAYS`
543    /// set to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`]
544    /// server is used instead.
545    ///
546    /// [number 0]: https://n0.computer
547    pub fn n0_dns() -> PkarrResolverBuilder {
548        let pkarr_relay = match force_staging_infra() {
549            true => N0_DNS_PKARR_RELAY_STAGING,
550            false => N0_DNS_PKARR_RELAY_PROD,
551        };
552
553        let pkarr_relay: Url = pkarr_relay.parse().expect("url is valid");
554        Self::builder(pkarr_relay)
555    }
556}
557
558impl AddressLookup for PkarrResolver {
559    fn resolve(
560        &self,
561        endpoint_id: EndpointId,
562    ) -> Option<BoxStream<Result<AddressLookupItem, AddressLookupError>>> {
563        let pkarr_client = self.pkarr_client.clone();
564        let fut = async move {
565            let signed_packet = pkarr_client.resolve(endpoint_id).await?;
566            let info = EndpointInfo::from_pkarr_signed_packet(&signed_packet)
567                .map_err(|err| AddressLookupError::from_err_any("pkarr", err))?;
568            let item = AddressLookupItem::new(info, "pkarr", None);
569            Ok(item)
570        };
571        let stream = n0_future::stream::once_future(fut);
572        Some(Box::pin(stream))
573    }
574}
575
576/// A [pkarr](https://pkarr.org) client to publish [`SignedPacket`]s to a pkarr relay.
577///
578/// [pkarr]: https://pkarr.org
579#[derive(Debug, Clone)]
580pub struct PkarrRelayClient {
581    http_client: reqwest::Client,
582    pkarr_relay_url: Url,
583}
584
585/// A builder for the [`PkarrRelayClient`]
586#[derive(Debug, Clone)]
587pub struct PkarrRelayClientBuilder {
588    pkarr_relay_url: Url,
589    #[cfg(not(wasm_browser))]
590    dns_resolver: DnsResolver,
591    #[cfg(not(wasm_browser))]
592    tls_config: rustls::ClientConfig,
593}
594
595impl PkarrRelayClientBuilder {
596    /// Build a [`PkarrRelayClient`].
597    pub fn build(self) -> PkarrRelayClient {
598        #[cfg(not(wasm_browser))]
599        let builder = reqwest_client_builder(self.tls_config, self.dns_resolver);
600
601        #[cfg(wasm_browser)]
602        let builder = reqwest_client_builder();
603
604        let http_client = builder.build().expect("failed to create reqwest client");
605        PkarrRelayClient {
606            http_client,
607            pkarr_relay_url: self.pkarr_relay_url,
608        }
609    }
610}
611
612impl PkarrRelayClient {
613    /// Creates a [`PkarrRelayClient`].
614    #[cfg(not(wasm_browser))]
615    pub fn new(
616        pkarr_relay_url: Url,
617        tls_config: rustls::ClientConfig,
618        dns_resolver: DnsResolver,
619    ) -> Self {
620        Self::with_proxy(pkarr_relay_url, tls_config, dns_resolver, None)
621    }
622
623    /// Creates a [`PkarrRelayClient`] that sends its requests through `proxy_url`, if set.
624    #[cfg(not(wasm_browser))]
625    pub(crate) fn with_proxy(
626        pkarr_relay_url: Url,
627        tls_config: rustls::ClientConfig,
628        dns_resolver: DnsResolver,
629        proxy_url: Option<Url>,
630    ) -> Self {
631        let mut builder = reqwest_client_builder(tls_config, dns_resolver);
632        if let Some(proxy_url) = proxy_url {
633            match reqwest::Proxy::all(proxy_url.clone()) {
634                Ok(proxy) => builder = builder.proxy(proxy),
635                // reqwest only rejects unsupported schemes. The relay client
636                // and net_report fail on such a proxy too, at connect time.
637                Err(err) => warn!(%proxy_url, "ignoring invalid proxy url for pkarr: {err:#}"),
638            }
639        }
640        let http_client = builder.build().expect("failed to create reqwest client");
641        Self {
642            http_client,
643            pkarr_relay_url,
644        }
645    }
646
647    /// Creates a [`PkarrRelayClient`].
648    #[cfg(wasm_browser)]
649    pub fn new(pkarr_relay_url: Url) -> Self {
650        let http_client = reqwest_client_builder()
651            .build()
652            .expect("failed to create reqwest client");
653        Self {
654            http_client,
655            pkarr_relay_url,
656        }
657    }
658
659    /// Resolves a [`SignedPacket`] for the given [`EndpointId`].
660    pub async fn resolve(
661        &self,
662        endpoint_id: EndpointId,
663    ) -> Result<SignedPacket, AddressLookupError> {
664        let mut url = self.pkarr_relay_url.clone();
665        url.path_segments_mut()
666            .map_err(|_| {
667                e!(PkarrError::InvalidRelayUrl {
668                    url: self.pkarr_relay_url.clone().into()
669                })
670            })?
671            .push(&endpoint_id.to_z32());
672
673        let response = self
674            .http_client
675            .get(url)
676            .send()
677            .await
678            .map_err(|err| e!(PkarrError::HttpSend, anyerr!(err)))?;
679
680        if !response.status().is_success() {
681            return Err(e!(PkarrError::HttpRequest {
682                status: response.status()
683            })
684            .into());
685        }
686
687        let payload = response
688            .bytes()
689            .await
690            .map_err(|err| e!(PkarrError::HttpPayload, anyerr!(err)))?;
691        let packet = SignedPacket::from_relay_payload(&endpoint_id, &payload)
692            .map_err(|err| e!(PkarrError::Verify, err))?;
693        Ok(packet)
694    }
695
696    /// Publishes a [`SignedPacket`].
697    pub async fn publish(&self, signed_packet: &SignedPacket) -> Result<(), PkarrError> {
698        let mut url = self.pkarr_relay_url.clone();
699        url.path_segments_mut()
700            .map_err(|_| {
701                e!(PkarrError::InvalidRelayUrl {
702                    url: self.pkarr_relay_url.clone().into()
703                })
704            })?
705            .push(&signed_packet.public_key().to_z32());
706
707        let response = self
708            .http_client
709            .put(url)
710            .body(signed_packet.to_relay_payload())
711            .send()
712            .await
713            .map_err(|err| e!(PkarrError::HttpSend, anyerr!(err)))?;
714
715        if !response.status().is_success() {
716            return Err(e!(PkarrError::HttpRequest {
717                status: response.status()
718            }));
719        }
720
721        Ok(())
722    }
723}
724
725#[cfg(all(test, not(wasm_browser)))]
726mod tests {
727    use std::net::Ipv4Addr;
728
729    use n0_error::{Result, StdResultExt};
730    use n0_future::{StreamExt, task, time};
731    use tokio::{io::AsyncReadExt, sync::oneshot};
732
733    use super::*;
734    use crate::endpoint::presets;
735
736    /// Spawns a fake HTTP proxy which captures the request line of the first connection
737    /// it receives and then hangs up.
738    async fn capturing_proxy() -> Result<(Url, oneshot::Receiver<String>)> {
739        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
740            .await
741            .anyerr()?;
742        let url: Url = format!("http://{}", listener.local_addr().anyerr()?)
743            .parse()
744            .anyerr()?;
745        let (tx, rx) = oneshot::channel();
746        task::spawn(async move {
747            let Ok((mut stream, _)) = listener.accept().await else {
748                return;
749            };
750            let mut line = Vec::new();
751            let mut byte = [0u8; 1];
752            while let Ok(1) = stream.read(&mut byte).await {
753                if byte[0] == b'\n' {
754                    break;
755                }
756                line.push(byte[0]);
757            }
758            tx.send(String::from_utf8_lossy(&line).trim().to_string())
759                .ok();
760        });
761        Ok((url, rx))
762    }
763
764    /// The pkarr resolver sends its requests through the endpoint's proxy.
765    #[tokio::test]
766    async fn resolver_uses_endpoint_proxy() -> Result {
767        let (proxy_url, request_line) = capturing_proxy().await?;
768        let endpoint = Endpoint::builder(presets::Minimal)
769            .proxy_url(proxy_url)
770            .address_lookup(PkarrResolver::builder(
771                "https://pkarr.test/pkarr".parse().anyerr()?,
772            ))
773            .bind()
774            .await?;
775
776        // The fake proxy never completes the tunnel, so the lookup fails. What
777        // matters is that it was attempted through the proxy.
778        let id = SecretKey::generate().public();
779        let mut lookup = endpoint.address_lookup()?.resolve(id);
780        let _ = time::timeout(Duration::from_secs(10), lookup.next()).await;
781
782        let request_line = time::timeout(Duration::from_secs(10), request_line)
783            .await
784            .expect("proxy did not receive a request, the lookup bypassed it")
785            .anyerr()?;
786        assert!(
787            request_line.starts_with("CONNECT pkarr.test:443 "),
788            "proxy received: {request_line}"
789        );
790        endpoint.close().await;
791        Ok(())
792    }
793}