1use std::collections::HashMap;
2use std::net::{IpAddr, SocketAddr};
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use futures::StreamExt;
7use once_cell::sync::Lazy;
8use reqwest::Client;
9use serde::Deserialize;
10use tokio::sync::{Notify, RwLock};
11use tracing::{debug, info, instrument, warn};
12
13use super::bootstrap::{
14 ipv4_matches_prefix, ipv6_matches_prefix, parse_asn_range, validate_bootstrap_url,
15};
16use super::types::RdapResponse;
17use crate::error::{Result, SeerError};
18use crate::retry::{NetworkRetryClassifier, RetryClassifier, RetryExecutor, RetryPolicy};
19use crate::validation::{describe_reserved_ip, normalize_domain};
20
21const IANA_BOOTSTRAP_DNS: &str = "https://data.iana.org/rdap/dns.json";
22const IANA_BOOTSTRAP_IPV4: &str = "https://data.iana.org/rdap/ipv4.json";
23const IANA_BOOTSTRAP_IPV6: &str = "https://data.iana.org/rdap/ipv6.json";
24const IANA_BOOTSTRAP_ASN: &str = "https://data.iana.org/rdap/asn.json";
25
26const DEFAULT_TIMEOUT: Duration = Duration::from_secs(15);
31
32const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
35
36const BOOTSTRAP_TTL: Duration = Duration::from_secs(24 * 60 * 60);
38
39const BOOTSTRAP_REFRESH_MIN_INTERVAL: Duration = Duration::from_secs(60);
43
44static RDAP_HTTP_CLIENT: Lazy<Option<Client>> = Lazy::new(|| {
53 Client::builder()
54 .timeout(DEFAULT_TIMEOUT)
55 .connect_timeout(CONNECT_TIMEOUT)
56 .user_agent("Seer/1.0 (RDAP Client)")
57 .pool_max_idle_per_host(10)
58 .redirect(reqwest::redirect::Policy::none())
62 .build()
63 .ok()
64});
65
66fn rdap_http_client() -> Result<&'static Client> {
70 RDAP_HTTP_CLIENT
71 .as_ref()
72 .ok_or_else(|| SeerError::HttpError("failed to initialize HTTP client".into()))
73}
74
75static BOOTSTRAP_CACHE: Lazy<RwLock<Option<CachedBootstrap>>> = Lazy::new(|| RwLock::new(None));
77
78static BOOTSTRAP_LAST_ATTEMPT: Lazy<RwLock<Option<Instant>>> = Lazy::new(|| RwLock::new(None));
82
83static BOOTSTRAP_LOAD_NOTIFY: Lazy<Notify> = Lazy::new(Notify::new);
91
92struct CachedBootstrap {
94 data: BootstrapData,
95 loaded_at: Instant,
96}
97
98impl CachedBootstrap {
99 fn new(data: BootstrapData) -> Self {
100 Self {
101 data,
102 loaded_at: Instant::now(),
103 }
104 }
105
106 fn is_expired(&self) -> bool {
107 self.loaded_at.elapsed() > BOOTSTRAP_TTL
108 }
109
110 fn age(&self) -> Duration {
111 self.loaded_at.elapsed()
112 }
113}
114
115struct BootstrapData {
120 dns: HashMap<String, Arc<Vec<url::Url>>>,
121 ipv4: Vec<(IpRange, Arc<Vec<url::Url>>)>,
122 ipv6: Vec<(IpRange, Arc<Vec<url::Url>>)>,
123 asn: Vec<(AsnRange, Arc<Vec<url::Url>>)>,
124}
125
126#[derive(Clone)]
127struct IpRange {
128 prefix: String,
129}
130
131#[derive(Clone)]
132struct AsnRange {
133 start: u32,
134 end: u32,
135}
136
137#[derive(Deserialize)]
138struct BootstrapResponse {
139 services: Vec<Vec<serde_json::Value>>,
140}
141
142async fn wait_for_in_flight_load(
152 notified: std::pin::Pin<&mut tokio::sync::futures::Notified<'_>>,
153) -> Result<()> {
154 let _ = tokio::time::timeout(DEFAULT_TIMEOUT, notified).await;
157 let cache = BOOTSTRAP_CACHE.read().await;
158 if cache.is_some() {
159 Ok(())
160 } else {
161 Err(SeerError::RdapBootstrapError(
162 "bootstrap refresh throttled and no cache available".to_string(),
163 ))
164 }
165}
166
167#[derive(Debug, Clone)]
168pub struct RdapClient {
169 retry_policy: RetryPolicy,
170 timeout: Duration,
172 allow_reserved: bool,
176}
177
178impl Default for RdapClient {
179 fn default() -> Self {
180 Self::new()
181 }
182}
183
184impl RdapClient {
185 pub fn new() -> Self {
187 Self {
188 retry_policy: RetryPolicy::new()
195 .with_max_attempts(3)
196 .with_initial_delay(Duration::from_millis(500))
197 .with_max_delay(Duration::from_secs(5)),
198 timeout: DEFAULT_TIMEOUT,
199 allow_reserved: false,
200 }
201 }
202
203 pub fn with_timeout(mut self, timeout: Duration) -> Self {
205 self.timeout = timeout;
206 self
207 }
208
209 #[cfg(test)]
211 pub(crate) fn allowing_reserved_for_tests(mut self) -> Self {
212 self.allow_reserved = true;
213 self
214 }
215
216 pub fn with_retry_policy(mut self, policy: RetryPolicy) -> Self {
220 self.retry_policy = policy;
221 self
222 }
223
224 pub fn without_retries(mut self) -> Self {
226 self.retry_policy = RetryPolicy::no_retry();
227 self
228 }
229
230 async fn ensure_bootstrap(&self) -> Result<()> {
245 {
247 let cache = BOOTSTRAP_CACHE.read().await;
248 if let Some(cached) = cache.as_ref() {
249 if !cached.is_expired() {
250 return Ok(());
251 }
252 }
253 }
254
255 let notified = BOOTSTRAP_LOAD_NOTIFY.notified();
261 tokio::pin!(notified);
262
263 {
267 let last = BOOTSTRAP_LAST_ATTEMPT.read().await;
268 if let Some(ts) = *last {
269 if ts.elapsed() < BOOTSTRAP_REFRESH_MIN_INTERVAL {
270 let cache = BOOTSTRAP_CACHE.read().await;
272 if cache.is_some() {
273 return Ok(());
275 }
276 drop(cache);
279 drop(last);
280 return wait_for_in_flight_load(notified).await;
281 }
282 }
283 }
284
285 {
288 let mut last = BOOTSTRAP_LAST_ATTEMPT.write().await;
289 if let Some(ts) = *last {
291 if ts.elapsed() < BOOTSTRAP_REFRESH_MIN_INTERVAL {
292 drop(last);
293 let cache = BOOTSTRAP_CACHE.read().await;
294 if cache.is_some() {
295 return Ok(());
296 }
297 drop(cache);
298 return wait_for_in_flight_load(notified).await;
299 }
300 }
301 *last = Some(Instant::now());
302 }
303
304 debug!("Loading/refreshing RDAP bootstrap data");
308 let load_result = load_bootstrap_data_with_retry(&self.retry_policy).await;
309
310 let outcome = match load_result {
311 Ok(data) => {
312 let mut cache = BOOTSTRAP_CACHE.write().await;
313 let should_store = cache.as_ref().map(|c| c.is_expired()).unwrap_or(true);
316 if should_store {
317 *cache = Some(CachedBootstrap::new(data));
318 }
319 Ok(())
320 }
321 Err(e) => {
322 let cache = BOOTSTRAP_CACHE.read().await;
324 if let Some(cached) = cache.as_ref() {
325 debug!(
326 error = %e,
327 age_hours = cached.age().as_secs() / 3600,
328 "Bootstrap refresh failed, using stale data"
329 );
330 Ok(())
331 } else {
332 Err(e)
334 }
335 }
336 };
337
338 BOOTSTRAP_LOAD_NOTIFY.notify_waiters();
340 outcome
341 }
342
343 fn get_rdap_urls_for_domain(cache: &BootstrapData, domain: &str) -> Option<Arc<Vec<url::Url>>> {
345 let tld = domain.rsplit('.').next()?;
346 cache.dns.get(&tld.to_lowercase()).cloned()
347 }
348
349 fn get_rdap_urls_for_ip(cache: &BootstrapData, ip: &IpAddr) -> Option<Arc<Vec<url::Url>>> {
351 match ip {
352 IpAddr::V4(addr) => {
353 for (range, urls) in &cache.ipv4 {
354 if ipv4_matches_prefix(&range.prefix, addr) {
355 return Some(Arc::clone(urls));
356 }
357 }
358 }
359 IpAddr::V6(addr) => {
360 for (range, urls) in &cache.ipv6 {
361 if ipv6_matches_prefix(&range.prefix, addr) {
362 return Some(Arc::clone(urls));
363 }
364 }
365 }
366 }
367
368 None
369 }
370
371 fn get_rdap_urls_for_asn(cache: &BootstrapData, asn: u32) -> Option<Arc<Vec<url::Url>>> {
373 for (range, urls) in &cache.asn {
374 if asn >= range.start && asn <= range.end {
375 return Some(Arc::clone(urls));
376 }
377 }
378
379 None
380 }
381
382 #[instrument(skip(self), fields(domain = %domain))]
386 pub async fn lookup_domain(&self, domain: &str) -> Result<RdapResponse> {
387 self.ensure_bootstrap().await?;
388
389 let domain = normalize_domain(domain)?;
390
391 let urls = {
393 let cache_guard = BOOTSTRAP_CACHE.read().await;
394 let cache = cache_guard.as_ref().ok_or_else(|| {
395 SeerError::RdapBootstrapError("bootstrap data not loaded".to_string())
396 })?;
397
398 let bases = Self::get_rdap_urls_for_domain(&cache.data, &domain).ok_or_else(|| {
399 SeerError::RdapBootstrapError(format!("no RDAP server for {}", domain))
400 })?;
401
402 build_rdap_urls(&bases, &format!("domain/{}", domain))
403 }; self.query_rdap_urls(&urls).await
406 }
407
408 #[instrument(skip(self), fields(ip = %ip))]
412 pub async fn lookup_ip(&self, ip: &str) -> Result<RdapResponse> {
413 self.ensure_bootstrap().await?;
414
415 let ip_addr: IpAddr = ip
416 .parse()
417 .map_err(|_| SeerError::InvalidIpAddress(ip.to_string()))?;
418
419 let urls = {
420 let cache_guard = BOOTSTRAP_CACHE.read().await;
421 let cache = cache_guard.as_ref().ok_or_else(|| {
422 SeerError::RdapBootstrapError("bootstrap data not loaded".to_string())
423 })?;
424
425 let bases = Self::get_rdap_urls_for_ip(&cache.data, &ip_addr).ok_or_else(|| {
426 SeerError::RdapBootstrapError(format!("no RDAP server for {}", ip))
427 })?;
428
429 build_rdap_urls(&bases, &format!("ip/{}", ip))
430 };
431
432 self.query_rdap_urls(&urls).await
433 }
434
435 #[instrument(skip(self), fields(asn = %asn))]
439 pub async fn lookup_asn(&self, asn: u32) -> Result<RdapResponse> {
440 self.ensure_bootstrap().await?;
441
442 let urls = {
443 let cache_guard = BOOTSTRAP_CACHE.read().await;
444 let cache = cache_guard.as_ref().ok_or_else(|| {
445 SeerError::RdapBootstrapError("bootstrap data not loaded".to_string())
446 })?;
447
448 let bases = Self::get_rdap_urls_for_asn(&cache.data, asn).ok_or_else(|| {
449 SeerError::RdapBootstrapError(format!("no RDAP server for AS{}", asn))
450 })?;
451
452 build_rdap_urls(&bases, &format!("autnum/{}", asn))
453 };
454
455 self.query_rdap_urls(&urls).await
456 }
457
458 #[instrument(skip(self), fields(tld = %tld))]
464 pub async fn get_rdap_base_url_for_tld(&self, tld: &str) -> Option<String> {
465 if self.ensure_bootstrap().await.is_err() {
466 return None;
467 }
468
469 let cache_guard = BOOTSTRAP_CACHE.read().await;
470 let cache = cache_guard.as_ref()?;
471 let lower = tld.to_lowercase();
475 let key = crate::validation::domain_to_ascii(&lower).unwrap_or(lower);
476 cache
477 .data
478 .dns
479 .get(&key)
480 .and_then(|urls| urls.first())
481 .map(|u| u.to_string())
482 }
483
484 async fn query_rdap_urls(&self, urls: &[url::Url]) -> Result<RdapResponse> {
488 if urls.is_empty() {
489 return Err(SeerError::RdapError(
490 "no candidate RDAP URLs available".to_string(),
491 ));
492 }
493
494 let mut last_error: Option<SeerError> = None;
495 for (idx, url) in urls.iter().enumerate() {
496 let url_str = url.as_str().to_string();
497 debug!(url = %url_str, candidate = idx + 1, total = urls.len(), "Querying RDAP");
498 match self.query_rdap_with_retry(&url_str).await {
499 Ok(resp) => return Ok(resp),
500 Err(e) => {
501 if urls.len() > 1 {
502 debug!(
503 url = %url_str,
504 error = %e,
505 candidate = idx + 1,
506 total = urls.len(),
507 "RDAP candidate failed, trying next",
508 );
509 }
510 last_error = Some(e);
511 }
512 }
513 }
514
515 Err(wrap_all_candidates_failed(last_error, urls.len()))
517 }
518
519 async fn query_rdap_with_retry(&self, url: &str) -> Result<RdapResponse> {
524 let classifier = NetworkRetryClassifier::new();
525 let mut attempt = 0;
526 loop {
527 match query_rdap_attempt(url, self.timeout, self.allow_reserved).await {
528 Ok(resp) => return Ok(resp),
529 Err((err, retry_after)) => {
530 let attempts_remaining =
531 self.retry_policy.max_attempts.saturating_sub(attempt + 1);
532 if !classifier.is_retryable(&err) || attempts_remaining == 0 {
533 return Err(if attempt > 0 {
534 SeerError::RetryExhausted {
535 attempts: attempt + 1,
536 last_error: Box::new(err),
537 }
538 } else {
539 err
540 });
541 }
542 let backoff = self.retry_policy.delay_for_attempt(attempt);
543 let delay = effective_retry_delay(backoff, retry_after);
544 debug!(
545 url = %url,
546 attempt = attempt + 1,
547 max_attempts = self.retry_policy.max_attempts,
548 delay_ms = delay.as_millis(),
549 error = %err,
550 "Retrying RDAP after transient error"
551 );
552 tokio::time::sleep(delay).await;
553 attempt += 1;
554 }
555 }
556 }
557 }
558}
559
560const MAX_RDAP_RESPONSE_SIZE: usize = 10 * 1024 * 1024;
562
563const MAX_RETRY_AFTER: Duration = Duration::from_secs(5);
568
569async fn validate_url_not_reserved(url: &str) -> Result<Vec<SocketAddr>> {
576 let parsed = url::Url::parse(url)
577 .map_err(|e| SeerError::RdapError(format!("invalid URL '{}': {}", url, e)))?;
578 if parsed.scheme() != "https" {
584 return Err(SeerError::RdapError(format!(
585 "RDAP URL '{}' is not https — request blocked (downgrade/SSRF protection)",
586 url
587 )));
588 }
589 let host = parsed
590 .host_str()
591 .ok_or_else(|| SeerError::RdapError(format!("URL '{}' has no host", url)))?;
592 let port = parsed.port_or_known_default().unwrap_or(443);
593
594 if let Ok(ip) = host.parse::<IpAddr>() {
596 if let Some(reason) = describe_reserved_ip(&ip) {
597 return Err(SeerError::RdapError(format!(
598 "RDAP URL resolves to reserved IP {}: {} — request blocked (SSRF protection)",
599 ip, reason
600 )));
601 }
602 return Ok(vec![SocketAddr::new(ip, port)]);
603 }
604
605 let addr = format!("{}:{}", host, port);
606
607 let socket_addrs: Vec<SocketAddr> = tokio::net::lookup_host(&addr)
608 .await
609 .map_err(|e| SeerError::RdapError(format!("failed to resolve host '{}': {}", host, e)))?
610 .collect();
611
612 if socket_addrs.is_empty() {
613 return Err(SeerError::RdapError(format!(
614 "host '{}' resolved to no addresses",
615 host
616 )));
617 }
618
619 for socket_addr in &socket_addrs {
620 if let Some(reason) = describe_reserved_ip(&socket_addr.ip()) {
621 return Err(SeerError::RdapError(format!(
622 "RDAP URL resolves to reserved IP {}: {} — request blocked (SSRF protection)",
623 socket_addr.ip(),
624 reason
625 )));
626 }
627 }
628
629 Ok(socket_addrs)
630}
631
632fn parse_retry_after(value: &str) -> Option<Duration> {
637 value.trim().parse::<u64>().ok().map(Duration::from_secs)
638}
639
640fn effective_retry_delay(backoff: Duration, retry_after: Option<Duration>) -> Duration {
644 match retry_after {
645 Some(hint) => hint.min(MAX_RETRY_AFTER),
646 None => backoff,
647 }
648}
649
650async fn send_rdap_request(
657 url: &str,
658 timeout: Duration,
659 allow_reserved: bool,
660) -> Result<reqwest::Response> {
661 let connect_timeout = CONNECT_TIMEOUT.min(timeout);
664 if allow_reserved {
665 let client = Client::builder()
666 .timeout(timeout)
667 .connect_timeout(connect_timeout)
668 .user_agent("Seer/1.0 (RDAP Client)")
669 .redirect(reqwest::redirect::Policy::none())
670 .build()
671 .map_err(|e| SeerError::RdapError(format!("failed to build HTTP client: {}", e)))?;
672 return client
673 .get(url)
674 .header("Accept", "application/rdap+json")
675 .send()
676 .await
677 .map_err(Into::into);
678 }
679
680 let resolved = validate_url_not_reserved(url).await?;
683
684 let parsed = url::Url::parse(url)
685 .map_err(|e| SeerError::RdapError(format!("invalid URL '{}': {}", url, e)))?;
686 let host = parsed
687 .host_str()
688 .ok_or_else(|| SeerError::RdapError(format!("URL '{}' has no host", url)))?;
689
690 let client = Client::builder()
694 .timeout(timeout)
695 .connect_timeout(connect_timeout)
696 .user_agent("Seer/1.0 (RDAP Client)")
697 .resolve_to_addrs(host, &resolved)
698 .redirect(reqwest::redirect::Policy::none())
707 .build()
708 .map_err(|e| SeerError::RdapError(format!("failed to build HTTP client: {}", e)))?;
709
710 client
711 .get(url)
712 .header("Accept", "application/rdap+json")
713 .send()
714 .await
715 .map_err(Into::into)
716}
717
718async fn read_and_parse_rdap_body(response: reqwest::Response, url: &str) -> Result<RdapResponse> {
721 let mut body = Vec::new();
726 let mut stream = response.bytes_stream();
727 let streamed = tokio::time::timeout(DEFAULT_TIMEOUT, async {
728 while let Some(chunk) = stream.next().await {
729 let chunk = chunk
730 .map_err(|e| SeerError::RdapError(format!("failed to read response: {}", e)))?;
731 body.extend_from_slice(&chunk);
732 if body.len() > MAX_RDAP_RESPONSE_SIZE {
733 return Err(SeerError::RdapError(format!(
734 "RDAP response exceeds {} byte limit",
735 MAX_RDAP_RESPONSE_SIZE
736 )));
737 }
738 }
739 Ok::<(), SeerError>(())
740 })
741 .await;
742
743 match streamed {
744 Ok(Ok(())) => {}
745 Ok(Err(e)) => return Err(e),
746 Err(_) => {
747 return Err(SeerError::Timeout(format!(
748 "timed out reading RDAP response body from {} after {:?}",
749 url, DEFAULT_TIMEOUT
750 )));
751 }
752 }
753
754 let rdap: RdapResponse = serde_json::from_slice(&body)?;
755 rdap.validate()?;
761 Ok(rdap)
762}
763
764async fn query_rdap_attempt(
770 url: &str,
771 timeout: Duration,
772 allow_reserved: bool,
773) -> std::result::Result<RdapResponse, (SeerError, Option<Duration>)> {
774 let response = send_rdap_request(url, timeout, allow_reserved)
775 .await
776 .map_err(|e| (e, None))?;
777
778 if !response.status().is_success() {
779 let status = response.status();
780 let retry_after = if status.as_u16() == 429 {
783 response
784 .headers()
785 .get(reqwest::header::RETRY_AFTER)
786 .and_then(|v| v.to_str().ok())
787 .and_then(parse_retry_after)
788 } else {
789 None
790 };
791 return Err((
792 SeerError::RdapError(format!("query failed with status {}", status)),
793 retry_after,
794 ));
795 }
796
797 read_and_parse_rdap_body(response, url)
798 .await
799 .map_err(|e| (e, None))
800}
801
802async fn load_bootstrap_data_with_retry(policy: &RetryPolicy) -> Result<BootstrapData> {
804 let executor = RetryExecutor::new(policy.clone());
805 executor.execute(load_bootstrap_data).await
806}
807
808async fn load_bootstrap_data() -> Result<BootstrapData> {
810 debug!("Loading RDAP bootstrap data from IANA");
811
812 let http = rdap_http_client()?;
817
818 let dns_future = http.get(IANA_BOOTSTRAP_DNS).send();
819 let ipv4_future = http.get(IANA_BOOTSTRAP_IPV4).send();
820 let ipv6_future = http.get(IANA_BOOTSTRAP_IPV6).send();
821 let asn_future = http.get(IANA_BOOTSTRAP_ASN).send();
822
823 let (dns_resp, ipv4_resp, ipv6_resp, asn_resp) =
826 tokio::join!(dns_future, ipv4_future, ipv6_future, asn_future);
827
828 const MAX_BOOTSTRAP_SIZE: usize = 10 * 1024 * 1024; async fn read_bootstrap(resp: reqwest::Response) -> Result<BootstrapResponse> {
832 let mut body = Vec::new();
838 let mut stream = resp.bytes_stream();
839 let streamed = tokio::time::timeout(DEFAULT_TIMEOUT, async {
840 while let Some(chunk) = stream.next().await {
841 let chunk = chunk.map_err(|e| {
842 SeerError::RdapBootstrapError(format!("failed to read body: {}", e))
843 })?;
844 body.extend_from_slice(&chunk);
845 if body.len() > MAX_BOOTSTRAP_SIZE {
846 return Err(SeerError::RdapBootstrapError(format!(
847 "bootstrap response too large (exceeds {} bytes)",
848 MAX_BOOTSTRAP_SIZE
849 )));
850 }
851 }
852 Ok::<(), SeerError>(())
853 })
854 .await;
855
856 match streamed {
857 Ok(Ok(())) => {}
858 Ok(Err(e)) => return Err(e),
859 Err(_) => {
860 return Err(SeerError::Timeout(format!(
861 "RDAP bootstrap body read timed out after {:?}",
862 DEFAULT_TIMEOUT
863 )));
864 }
865 }
866
867 serde_json::from_slice(&body).map_err(Into::into)
868 }
869
870 let dns_data = match dns_resp {
872 Ok(resp) => match read_bootstrap(resp).await {
873 Ok(data) => Some(data),
874 Err(e) => {
875 warn!(error = %e, "Failed to parse DNS bootstrap response");
876 None
877 }
878 },
879 Err(e) => {
880 warn!(error = %e, "Failed to fetch DNS bootstrap from IANA");
881 None
882 }
883 };
884 let ipv4_data = match ipv4_resp {
885 Ok(resp) => match read_bootstrap(resp).await {
886 Ok(data) => Some(data),
887 Err(e) => {
888 warn!(error = %e, "Failed to parse IPv4 bootstrap response");
889 None
890 }
891 },
892 Err(e) => {
893 warn!(error = %e, "Failed to fetch IPv4 bootstrap from IANA");
894 None
895 }
896 };
897 let ipv6_data = match ipv6_resp {
898 Ok(resp) => match read_bootstrap(resp).await {
899 Ok(data) => Some(data),
900 Err(e) => {
901 warn!(error = %e, "Failed to parse IPv6 bootstrap response");
902 None
903 }
904 },
905 Err(e) => {
906 warn!(error = %e, "Failed to fetch IPv6 bootstrap from IANA");
907 None
908 }
909 };
910 let asn_data = match asn_resp {
911 Ok(resp) => match read_bootstrap(resp).await {
912 Ok(data) => Some(data),
913 Err(e) => {
914 warn!(error = %e, "Failed to parse ASN bootstrap response");
915 None
916 }
917 },
918 Err(e) => {
919 warn!(error = %e, "Failed to fetch ASN bootstrap from IANA");
920 None
921 }
922 };
923
924 if dns_data.is_none() && ipv4_data.is_none() && ipv6_data.is_none() && asn_data.is_none() {
926 return Err(SeerError::RdapBootstrapError(
927 "all IANA bootstrap registries failed".to_string(),
928 ));
929 }
930
931 let mut dns = HashMap::new();
932 let mut ipv4 = Vec::new();
933 let mut ipv6 = Vec::new();
934 let mut asn = Vec::new();
935
936 fn collect_valid_urls(urls: &[serde_json::Value]) -> Option<Arc<Vec<url::Url>>> {
940 let mut out = Vec::new();
941 for u in urls {
942 if let Some(s) = u.as_str() {
943 match validate_bootstrap_url(s) {
944 Ok(parsed) => out.push(parsed),
945 Err(e) => {
946 debug!(url = s, error = %e, "Skipping invalid bootstrap URL");
947 }
948 }
949 }
950 }
951 if out.is_empty() {
952 None
953 } else {
954 Some(Arc::new(out))
955 }
956 }
957
958 if let Some(dns_data) = dns_data {
960 for service in dns_data.services {
961 if service.len() >= 2 {
962 if let (Some(tlds), Some(urls)) = (service[0].as_array(), service[1].as_array()) {
963 if let Some(urls_arc) = collect_valid_urls(urls) {
964 for tld in tlds {
965 if let Some(tld_str) = tld.as_str() {
966 dns.insert(tld_str.to_lowercase(), Arc::clone(&urls_arc));
967 }
968 }
969 }
970 }
971 }
972 }
973 }
974
975 if let Some(ipv4_data) = ipv4_data {
977 for service in ipv4_data.services {
978 if service.len() >= 2 {
979 if let (Some(prefixes), Some(urls)) = (service[0].as_array(), service[1].as_array())
980 {
981 if let Some(urls_arc) = collect_valid_urls(urls) {
982 for prefix in prefixes {
983 if let Some(prefix_str) = prefix.as_str() {
984 ipv4.push((
985 IpRange {
986 prefix: prefix_str.to_string(),
987 },
988 Arc::clone(&urls_arc),
989 ));
990 }
991 }
992 }
993 }
994 }
995 }
996 }
997
998 if let Some(ipv6_data) = ipv6_data {
1000 for service in ipv6_data.services {
1001 if service.len() >= 2 {
1002 if let (Some(prefixes), Some(urls)) = (service[0].as_array(), service[1].as_array())
1003 {
1004 if let Some(urls_arc) = collect_valid_urls(urls) {
1005 for prefix in prefixes {
1006 if let Some(prefix_str) = prefix.as_str() {
1007 ipv6.push((
1008 IpRange {
1009 prefix: prefix_str.to_string(),
1010 },
1011 Arc::clone(&urls_arc),
1012 ));
1013 }
1014 }
1015 }
1016 }
1017 }
1018 }
1019 }
1020
1021 if let Some(asn_data) = asn_data {
1023 for service in asn_data.services {
1024 if service.len() >= 2 {
1025 if let (Some(ranges), Some(urls)) = (service[0].as_array(), service[1].as_array()) {
1026 if let Some(urls_arc) = collect_valid_urls(urls) {
1027 for range in ranges {
1028 if let Some(range_str) = range.as_str() {
1029 if let Some((start, end)) = parse_asn_range(range_str) {
1030 asn.push((AsnRange { start, end }, Arc::clone(&urls_arc)));
1031 }
1032 }
1033 }
1034 }
1035 }
1036 }
1037 }
1038 }
1039
1040 info!(
1041 dns_entries = dns.len(),
1042 ipv4_ranges = ipv4.len(),
1043 ipv6_ranges = ipv6.len(),
1044 asn_ranges = asn.len(),
1045 "RDAP bootstrap loaded"
1046 );
1047
1048 Ok(BootstrapData {
1049 dns,
1050 ipv4,
1051 ipv6,
1052 asn,
1053 })
1054}
1055
1056fn wrap_all_candidates_failed(last_error: Option<SeerError>, candidate_count: usize) -> SeerError {
1065 let last = last_error.unwrap_or_else(|| SeerError::RdapError("no candidates".to_string()));
1066
1067 if candidate_count <= 1 {
1068 return last;
1069 }
1070
1071 match last {
1072 SeerError::Timeout(msg) => SeerError::Timeout(format!(
1073 "all {} RDAP candidate URLs timed out; last error: {}",
1074 candidate_count, msg
1075 )),
1076 other => SeerError::RdapError(format!(
1077 "all {} RDAP candidate URLs failed; last error: {}",
1078 candidate_count, other
1079 )),
1080 }
1081}
1082
1083fn build_rdap_urls(bases: &[url::Url], path: &str) -> Vec<url::Url> {
1085 bases
1086 .iter()
1087 .filter_map(|base| {
1088 let base_str = base.as_str();
1091 let normalized = if base_str.ends_with('/') {
1092 base_str.to_string()
1093 } else {
1094 format!("{}/", base_str)
1095 };
1096 url::Url::parse(&normalized).and_then(|u| u.join(path)).ok()
1097 })
1098 .collect()
1099}
1100
1101#[cfg(test)]
1102mod tests {
1103 use super::*;
1104
1105 #[test]
1106 fn test_default_client_has_retry_policy() {
1107 let client = RdapClient::new();
1108 assert_eq!(client.retry_policy.max_attempts, 3);
1112 }
1113
1114 #[test]
1117 fn parse_retry_after_parses_delta_seconds() {
1118 assert_eq!(parse_retry_after("5"), Some(Duration::from_secs(5)));
1119 assert_eq!(parse_retry_after(" 10 "), Some(Duration::from_secs(10)));
1120 assert_eq!(parse_retry_after("0"), Some(Duration::from_secs(0)));
1121 }
1122
1123 #[test]
1124 fn parse_retry_after_rejects_http_date_and_junk() {
1125 assert_eq!(parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT"), None);
1128 assert_eq!(parse_retry_after("soon"), None);
1129 assert_eq!(parse_retry_after(""), None);
1130 }
1131
1132 #[test]
1133 fn effective_retry_delay_prefers_capped_retry_after() {
1134 assert_eq!(
1136 effective_retry_delay(Duration::from_millis(100), Some(Duration::from_secs(5))),
1137 Duration::from_secs(5)
1138 );
1139 assert_eq!(
1141 effective_retry_delay(Duration::from_millis(100), Some(Duration::from_secs(600))),
1142 MAX_RETRY_AFTER
1143 );
1144 }
1145
1146 #[test]
1147 fn effective_retry_delay_falls_back_to_backoff() {
1148 assert_eq!(
1149 effective_retry_delay(Duration::from_millis(250), None),
1150 Duration::from_millis(250)
1151 );
1152 }
1153
1154 #[test]
1155 fn test_client_without_retries() {
1156 let client = RdapClient::new().without_retries();
1157 assert_eq!(client.retry_policy.max_attempts, 1);
1158 }
1159
1160 #[test]
1161 fn test_client_custom_retry_policy() {
1162 let policy = RetryPolicy::new().with_max_attempts(5);
1163 let client = RdapClient::new().with_retry_policy(policy);
1164 assert_eq!(client.retry_policy.max_attempts, 5);
1165 }
1166
1167 #[test]
1168 fn test_cached_bootstrap_expiration() {
1169 let data = BootstrapData {
1170 dns: HashMap::new(),
1171 ipv4: Vec::new(),
1172 ipv6: Vec::new(),
1173 asn: Vec::new(),
1174 };
1175 let cached = CachedBootstrap::new(data);
1176 assert!(!cached.is_expired());
1178 }
1179
1180 #[test]
1181 fn test_rdap_http_client_is_configured() {
1182 let client = rdap_http_client();
1185 assert!(client.is_ok(), "RDAP HTTP client builder must succeed");
1186 }
1187
1188 #[test]
1189 fn test_parse_bootstrap_empty_services() {
1190 let data = BootstrapData {
1192 dns: HashMap::new(),
1193 ipv4: Vec::new(),
1194 ipv6: Vec::new(),
1195 asn: Vec::new(),
1196 };
1197 assert!(RdapClient::get_rdap_urls_for_domain(&data, "example.com").is_none());
1199 assert!(RdapClient::get_rdap_urls_for_asn(&data, 12345).is_none());
1200 }
1201
1202 #[tokio::test]
1205 async fn test_validate_url_not_reserved_rejects_loopback_literal() {
1206 let err = validate_url_not_reserved("https://127.0.0.1/domain/example.com")
1207 .await
1208 .unwrap_err();
1209 assert!(
1210 matches!(err, SeerError::RdapError(ref s) if s.contains("reserved IP")),
1211 "expected reserved-IP error, got: {:?}",
1212 err
1213 );
1214 }
1215
1216 #[tokio::test]
1217 async fn test_validate_url_not_reserved_rejects_private_ipv4_literal() {
1218 let err = validate_url_not_reserved("https://10.0.0.1/")
1219 .await
1220 .unwrap_err();
1221 assert!(
1222 matches!(err, SeerError::RdapError(ref s) if s.contains("reserved IP")),
1223 "expected reserved-IP error, got: {:?}",
1224 err
1225 );
1226 }
1227
1228 #[tokio::test]
1229 async fn test_validate_url_not_reserved_rejects_non_https_scheme() {
1230 let err = validate_url_not_reserved("http://93.184.216.34/domain/example.com")
1234 .await
1235 .unwrap_err();
1236 assert!(
1237 matches!(err, SeerError::RdapError(ref s) if s.contains("not https")),
1238 "expected non-https rejection, got: {:?}",
1239 err
1240 );
1241 }
1242
1243 #[tokio::test]
1244 async fn test_validate_url_not_reserved_rejects_ipv6_loopback_literal() {
1245 let err = validate_url_not_reserved("https://[::1]/")
1246 .await
1247 .unwrap_err();
1248 assert!(
1249 matches!(err, SeerError::RdapError(ref s) if s.contains("reserved IP")),
1250 "expected reserved-IP error, got: {:?}",
1251 err
1252 );
1253 }
1254
1255 #[tokio::test]
1256 async fn test_validate_url_not_reserved_returns_resolved_addrs_for_public_literal() {
1257 let addrs = validate_url_not_reserved("https://8.8.8.8/").await.unwrap();
1260 assert_eq!(addrs.len(), 1);
1261 assert!(addrs[0].ip().is_ipv4());
1262 assert_eq!(addrs[0].port(), 443);
1263 }
1264
1265 #[test]
1268 fn test_build_rdap_urls_preserves_order_and_appends_path() {
1269 let bases = vec![
1270 url::Url::parse("https://rdap.a.example/").unwrap(),
1271 url::Url::parse("https://rdap.b.example").unwrap(), ];
1273 let built = build_rdap_urls(&bases, "domain/example.com");
1274 assert_eq!(built.len(), 2);
1275 assert_eq!(
1276 built[0].as_str(),
1277 "https://rdap.a.example/domain/example.com"
1278 );
1279 assert_eq!(
1280 built[1].as_str(),
1281 "https://rdap.b.example/domain/example.com"
1282 );
1283 }
1284
1285 #[test]
1286 fn test_build_rdap_urls_empty_input_returns_empty() {
1287 let built = build_rdap_urls(&[], "domain/example.com");
1288 assert!(built.is_empty());
1289 }
1290
1291 #[test]
1294 fn test_wrap_all_candidates_failed_preserves_timeout_variant() {
1295 let last = SeerError::Timeout("body read timed out".to_string());
1298 let wrapped = wrap_all_candidates_failed(Some(last), 3);
1299 match wrapped {
1300 SeerError::Timeout(msg) => {
1301 assert!(
1302 msg.contains("all 3 RDAP candidate URLs timed out"),
1303 "expected wrapped timeout message, got: {}",
1304 msg
1305 );
1306 assert!(
1307 msg.contains("body read timed out"),
1308 "expected original message preserved, got: {}",
1309 msg
1310 );
1311 }
1312 other => panic!(
1313 "expected SeerError::Timeout after wrapping a Timeout, got: {:?}",
1314 other
1315 ),
1316 }
1317 }
1318
1319 #[test]
1320 fn test_wrap_all_candidates_failed_wraps_non_timeout_as_rdap_error() {
1321 let last = SeerError::RdapError("500 internal error".to_string());
1322 let wrapped = wrap_all_candidates_failed(Some(last), 2);
1323 assert!(
1324 matches!(wrapped, SeerError::RdapError(ref s) if s.contains("all 2 RDAP candidate URLs failed")),
1325 "expected wrapped RdapError, got: {:?}",
1326 wrapped
1327 );
1328 }
1329
1330 #[test]
1331 fn test_wrap_all_candidates_failed_single_candidate_returns_unchanged() {
1332 let last = SeerError::Timeout("single timeout".to_string());
1335 let wrapped = wrap_all_candidates_failed(Some(last), 1);
1336 assert!(
1337 matches!(wrapped, SeerError::Timeout(ref s) if s == "single timeout"),
1338 "expected unchanged Timeout, got: {:?}",
1339 wrapped
1340 );
1341 }
1342
1343 #[test]
1344 fn test_wrap_all_candidates_failed_no_last_error_returns_placeholder() {
1345 let wrapped = wrap_all_candidates_failed(None, 0);
1346 assert!(matches!(wrapped, SeerError::RdapError(_)));
1347 }
1348
1349 static BOOTSTRAP_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
1368
1369 #[tokio::test]
1370 async fn test_bootstrap_load_notify_wakes_waiter_when_cache_populated() {
1371 let _guard = BOOTSTRAP_TEST_LOCK.lock().await;
1372
1373 {
1375 let mut cache = BOOTSTRAP_CACHE.write().await;
1376 *cache = None;
1377 }
1378
1379 let notified = BOOTSTRAP_LOAD_NOTIFY.notified();
1382 tokio::pin!(notified);
1383
1384 {
1386 let mut cache = BOOTSTRAP_CACHE.write().await;
1387 *cache = Some(CachedBootstrap::new(BootstrapData {
1388 dns: HashMap::new(),
1389 ipv4: Vec::new(),
1390 ipv6: Vec::new(),
1391 asn: Vec::new(),
1392 }));
1393 }
1394 BOOTSTRAP_LOAD_NOTIFY.notify_waiters();
1395
1396 let result = wait_for_in_flight_load(notified).await;
1397 assert!(
1398 result.is_ok(),
1399 "expected waiter to see populated cache, got: {:?}",
1400 result
1401 );
1402
1403 {
1405 let mut cache = BOOTSTRAP_CACHE.write().await;
1406 *cache = None;
1407 }
1408 }
1409
1410 #[tokio::test]
1411 async fn test_bootstrap_load_notify_empty_cache_after_wake_returns_error() {
1412 let _guard = BOOTSTRAP_TEST_LOCK.lock().await;
1413
1414 {
1416 let mut cache = BOOTSTRAP_CACHE.write().await;
1417 *cache = None;
1418 }
1419
1420 let notified = BOOTSTRAP_LOAD_NOTIFY.notified();
1421 tokio::pin!(notified);
1422
1423 BOOTSTRAP_LOAD_NOTIFY.notify_waiters();
1425
1426 let result = wait_for_in_flight_load(notified).await;
1427 assert!(
1428 matches!(
1429 result,
1430 Err(SeerError::RdapBootstrapError(ref s))
1431 if s.contains("throttled and no cache available")
1432 ),
1433 "expected throttled error when cache still empty after notify, got: {:?}",
1434 result
1435 );
1436 }
1437
1438 use wiremock::matchers::method;
1448 use wiremock::{Mock, MockServer, ResponseTemplate};
1449
1450 #[tokio::test]
1451 async fn mock_rdap_404_is_nonretryable_typed_error() {
1452 let server = MockServer::start().await;
1453 Mock::given(method("GET"))
1454 .respond_with(ResponseTemplate::new(404))
1455 .mount(&server)
1456 .await;
1457
1458 let client = RdapClient::new()
1459 .without_retries()
1460 .allowing_reserved_for_tests();
1461 let err = client
1462 .query_rdap_with_retry(&format!("{}/domain/example.com", server.uri()))
1463 .await
1464 .unwrap_err();
1465 assert!(
1466 matches!(err, SeerError::RdapError(ref m) if m.contains("404")),
1467 "got: {err:?}"
1468 );
1469 }
1470
1471 #[tokio::test]
1472 async fn mock_rdap_429_honors_retry_after_and_succeeds() {
1473 let server = MockServer::start().await;
1474 Mock::given(method("GET"))
1477 .respond_with(ResponseTemplate::new(429).insert_header("Retry-After", "0"))
1478 .up_to_n_times(1)
1479 .mount(&server)
1480 .await;
1481 Mock::given(method("GET"))
1482 .respond_with(ResponseTemplate::new(200).set_body_raw(
1483 r#"{"objectClassName":"domain","handle":"MOCK-1"}"#,
1484 "application/rdap+json",
1485 ))
1486 .mount(&server)
1487 .await;
1488
1489 let client = RdapClient::new().allowing_reserved_for_tests();
1490 let resp = client
1491 .query_rdap_with_retry(&format!("{}/domain/example.com", server.uri()))
1492 .await
1493 .unwrap();
1494 assert_eq!(resp.handle.as_deref(), Some("MOCK-1"));
1495 }
1496
1497 #[tokio::test]
1498 async fn mock_rdap_malformed_body_is_parse_error_not_panic() {
1499 let server = MockServer::start().await;
1500 Mock::given(method("GET"))
1501 .respond_with(ResponseTemplate::new(200).set_body_raw("not json", "text/plain"))
1502 .mount(&server)
1503 .await;
1504
1505 let client = RdapClient::new()
1506 .without_retries()
1507 .allowing_reserved_for_tests();
1508 let err = client
1509 .query_rdap_with_retry(&format!("{}/domain/example.com", server.uri()))
1510 .await
1511 .unwrap_err();
1512 assert!(matches!(err, SeerError::JsonError(_)), "got: {err:?}");
1513 }
1514
1515 #[tokio::test]
1516 async fn mock_rdap_candidate_fallback_uses_second_url() {
1517 let bad = MockServer::start().await;
1518 Mock::given(method("GET"))
1519 .respond_with(ResponseTemplate::new(500))
1520 .mount(&bad)
1521 .await;
1522 let good = MockServer::start().await;
1523 Mock::given(method("GET"))
1524 .respond_with(ResponseTemplate::new(200).set_body_raw(
1525 r#"{"objectClassName":"domain","handle":"MOCK-2"}"#,
1526 "application/rdap+json",
1527 ))
1528 .mount(&good)
1529 .await;
1530
1531 let client = RdapClient::new()
1532 .without_retries()
1533 .allowing_reserved_for_tests();
1534 let urls = vec![
1535 url::Url::parse(&format!("{}/domain/example.com", bad.uri())).unwrap(),
1536 url::Url::parse(&format!("{}/domain/example.com", good.uri())).unwrap(),
1537 ];
1538 let resp = client.query_rdap_urls(&urls).await.unwrap();
1539 assert_eq!(resp.handle.as_deref(), Some("MOCK-2"));
1540 }
1541}