Skip to main content

adk_site/migrate/
http.rs

1//! The one HTTP client of the migration stages (spec 3.5 §7.3 "Outbound", §7.8 "Sources").
2//!
3//! | Rule | How |
4//! |------|-----|
5//! | Signed | Every crawler request is signed through a [`CrawlSigner`]: the site's Web Bot Auth key ([`HttpSignatureSigner`]); each redirect hop is a new request, signed again |
6//! | Robots-respecting | `robots.txt` is read before any other request to an origin, and a disallowed URL is never requested |
7//! | Rate-limited | One request at a time per origin, at least [`HttpClientBuilder::min_interval`] apart, longer when `Crawl-delay` says so |
8//! | Egress-checked | [`EgressScope::Public`] refuses non-public addresses (also after DNS); [`EgressScope::Only`] allows the listed origins and nothing else |
9//! | Recorded | Every request, sent or refused, is a [`ConnectionRecord`] |
10//!
11//! An origin map sends requests for a public origin to another address with the public `Host`
12//! header: the private vantage point of a freeze or the loopback port of an isolated replay.
13
14use std::collections::{BTreeSet, HashMap};
15use std::net::IpAddr;
16use std::sync::{Arc, Mutex};
17use std::time::Duration;
18
19use adk_auth::web_bot_auth::HttpSignatureSigner;
20use adk_core::egress::{EgressPolicy, EgressResolver, is_non_public};
21use adk_core::{Clock, SystemClock};
22use bytes::{Bytes, BytesMut};
23use chrono::{DateTime, Utc};
24use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
25use serde::{Deserialize, Serialize};
26use url::Url;
27
28use super::error::{MigrateError, Result};
29use super::robots::RobotsTxt;
30
31/// Signs outgoing crawler requests (spec 3.5 §7.3 "Outbound").
32///
33/// [`HttpSignatureSigner`] implements it with the site's Web Bot Auth key; the site publishes
34/// the matching key directory so the sites it reads can verify it.
35pub trait CrawlSigner: Send + Sync + std::fmt::Debug {
36    /// Adds the signature fields to `request`.
37    ///
38    /// # Errors
39    ///
40    /// Returns why the request could not be signed.
41    fn sign(&self, request: &mut reqwest::Request) -> std::result::Result<(), String>;
42}
43
44impl CrawlSigner for HttpSignatureSigner {
45    fn sign(&self, request: &mut reqwest::Request) -> std::result::Result<(), String> {
46        self.sign_reqwest(request).map_err(|e| e.to_string())
47    }
48}
49
50/// Who a request presents itself as.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
52#[serde(rename_all = "snake_case")]
53pub enum FetchProfile {
54    /// The site's crawler: its own user agent, signed.
55    Crawler,
56    /// A browser user agent, unsigned: the second half of a cloaking check, run only on a
57    /// proven domain (A-I9).
58    Browser,
59}
60
61/// Which addresses requests may reach.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum EgressScope {
64    /// Public addresses over `http` and `https`; loopback, private, link-local and other
65    /// non-public addresses are refused, also when a name resolves to one.
66    Public,
67    /// Only these origins (`scheme://host:port`, after the origin map); everything else is
68    /// refused before a connection is made.
69    Only(BTreeSet<String>),
70}
71
72/// One request the client sent or refused.
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(rename_all = "camelCase")]
75pub struct ConnectionRecord {
76    /// The URL connected to, after the origin map.
77    pub url: String,
78    /// Its origin.
79    pub origin: String,
80    /// Whether the request was sent.
81    pub allowed: bool,
82    /// Whether the host is a loopback address or `localhost`.
83    pub loopback: bool,
84    /// Why it was refused.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub reason: Option<String>,
87    /// When.
88    pub at: DateTime<Utc>,
89}
90
91/// How to make one request.
92#[derive(Debug, Clone)]
93pub struct FetchOptions {
94    /// Who the request presents itself as.
95    pub profile: FetchProfile,
96    /// Extra headers, such as `Authorization` for drafts.
97    pub headers: HeaderMap,
98    /// Redirects to follow; 0 returns the redirect itself.
99    pub follow: u8,
100}
101
102impl FetchOptions {
103    /// A signed crawler request that does not follow redirects.
104    pub fn crawler() -> Self {
105        Self { profile: FetchProfile::Crawler, headers: HeaderMap::new(), follow: 0 }
106    }
107
108    /// An unsigned browser request that does not follow redirects.
109    pub fn browser() -> Self {
110        Self { profile: FetchProfile::Browser, headers: HeaderMap::new(), follow: 0 }
111    }
112
113    /// Follows up to `hops` redirects, each a new, signed and checked request.
114    #[must_use]
115    pub fn following(mut self, hops: u8) -> Self {
116        self.follow = hops;
117        self
118    }
119
120    /// Adds a header.
121    #[must_use]
122    pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
123        self.headers.insert(name, value);
124        self
125    }
126}
127
128/// A response.
129#[derive(Debug, Clone)]
130pub struct Fetched {
131    /// The public URL of the last hop.
132    pub url: Url,
133    /// Every hop's public URL and status, the last one included.
134    pub hops: Vec<(Url, u16)>,
135    /// The last hop's status.
136    pub status: u16,
137    /// Its headers.
138    pub headers: HeaderMap,
139    /// Its body, up to the client's limit.
140    pub body: Bytes,
141    /// Whether the body was cut at the limit.
142    pub truncated: bool,
143    /// A redirect's target, resolved and mapped back to the public origin.
144    pub location: Option<Url>,
145    /// The server's TLS certificate (DER), on `https`.
146    pub peer_certificate: Option<Vec<u8>>,
147}
148
149impl Fetched {
150    /// The media type without parameters, lower case.
151    pub fn content_type(&self) -> Option<String> {
152        self.headers
153            .get(reqwest::header::CONTENT_TYPE)
154            .and_then(|v| v.to_str().ok())
155            .map(|v| v.split(';').next().unwrap_or_default().trim().to_ascii_lowercase())
156    }
157
158    /// Whether the body is HTML.
159    pub fn is_html(&self) -> bool {
160        self.content_type().is_some_and(|t| t == "text/html" || t == "application/xhtml+xml")
161    }
162
163    /// The body as text, invalid UTF-8 replaced.
164    pub fn text(&self) -> String {
165        String::from_utf8_lossy(&self.body).into_owned()
166    }
167
168    /// Whether the status is a redirect.
169    pub fn is_redirect(&self) -> bool {
170        matches!(self.status, 301 | 302 | 303 | 307 | 308)
171    }
172
173    /// A header's value as text.
174    pub fn header(&self, name: &str) -> Option<&str> {
175        self.headers.get(name).and_then(|v| v.to_str().ok())
176    }
177}
178
179/// `scheme://host[:port]` of a URL, the port shown only when it is not the scheme's default.
180pub fn origin_of(url: &Url) -> String {
181    url.origin().ascii_serialization()
182}
183
184/// A Chrome user agent for the browser half of a cloaking check.
185pub const BROWSER_USER_AGENT: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) \
186     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
187
188/// Builds an [`HttpClient`].
189pub struct HttpClientBuilder {
190    robots_token: String,
191    user_agent: String,
192    signer: Option<Arc<dyn CrawlSigner>>,
193    egress: EgressScope,
194    origin_map: Vec<(String, Url)>,
195    min_interval: Duration,
196    timeout: Duration,
197    max_body: usize,
198    clock: Arc<dyn Clock>,
199}
200
201impl HttpClientBuilder {
202    /// Identifies the crawler as `robots_token` in `robots.txt` matching and in its user agent.
203    #[must_use]
204    pub fn robots_token(mut self, token: impl Into<String>) -> Self {
205        self.robots_token = token.into();
206        self
207    }
208
209    /// Sets the crawler's full user agent.
210    #[must_use]
211    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
212        self.user_agent = user_agent.into();
213        self
214    }
215
216    /// Signs crawler requests with `signer`.
217    #[must_use]
218    pub fn signer(mut self, signer: Arc<dyn CrawlSigner>) -> Self {
219        self.signer = Some(signer);
220        self
221    }
222
223    /// Sets which addresses requests may reach.
224    #[must_use]
225    pub fn egress(mut self, egress: EgressScope) -> Self {
226        self.egress = egress;
227        self
228    }
229
230    /// Sends requests for `public` (an origin) to `fetch` with `public`'s `Host` header.
231    #[must_use]
232    pub fn map_origin(mut self, public: &Url, fetch: Url) -> Self {
233        self.origin_map.push((origin_of(public), fetch));
234        self
235    }
236
237    /// The minimum time between two requests to one origin (default one second).
238    #[must_use]
239    pub fn min_interval(mut self, interval: Duration) -> Self {
240        self.min_interval = interval;
241        self
242    }
243
244    /// The timeout of one request (default 30 seconds).
245    #[must_use]
246    pub fn timeout(mut self, timeout: Duration) -> Self {
247        self.timeout = timeout;
248        self
249    }
250
251    /// The largest body read (default 20 MiB).
252    #[must_use]
253    pub fn max_body(mut self, bytes: usize) -> Self {
254        self.max_body = bytes;
255        self
256    }
257
258    /// Stamps connection records with `clock`.
259    #[must_use]
260    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
261        self.clock = clock;
262        self
263    }
264
265    /// Builds the client.
266    ///
267    /// # Errors
268    ///
269    /// [`MigrateError::Http`] when the TLS stack cannot be set up.
270    pub fn build(self) -> Result<HttpClient> {
271        let mut builder = reqwest::Client::builder()
272            .redirect(reqwest::redirect::Policy::none())
273            .no_proxy()
274            .tls_info(true)
275            .timeout(self.timeout)
276            .connect_timeout(self.timeout.min(Duration::from_secs(10)));
277        if self.egress == EgressScope::Public {
278            builder =
279                builder.dns_resolver(Arc::new(EgressResolver::new(EgressPolicy::public_only())));
280        }
281        let client = builder.build().map_err(|e| MigrateError::http("client", e))?;
282        Ok(HttpClient {
283            client,
284            robots_token: self.robots_token,
285            user_agent: self.user_agent,
286            signer: self.signer,
287            egress: self.egress,
288            origin_map: self.origin_map,
289            min_interval: self.min_interval,
290            max_body: self.max_body,
291            clock: self.clock,
292            state: Mutex::new(ClientState::default()),
293            robots: tokio::sync::Mutex::new(HashMap::new()),
294        })
295    }
296}
297
298#[derive(Default)]
299struct ClientState {
300    next_slot: HashMap<String, tokio::time::Instant>,
301    delays: HashMap<String, Duration>,
302    records: Vec<ConnectionRecord>,
303}
304
305/// The signed, robots-respecting, rate-limited, egress-checked client every migration
306/// request goes through (spec 3.5 §7.3, §7.8).
307///
308/// # Example
309///
310/// ```rust
311/// use std::collections::BTreeSet;
312/// use adk_site::migrate::http::{EgressScope, HttpClient};
313///
314/// let client = HttpClient::builder()
315///     .egress(EgressScope::Only(BTreeSet::from(["http://127.0.0.1:8080".to_string()])))
316///     .build()
317///     .unwrap();
318/// assert!(client.connections().is_empty());
319/// ```
320pub struct HttpClient {
321    client: reqwest::Client,
322    robots_token: String,
323    user_agent: String,
324    signer: Option<Arc<dyn CrawlSigner>>,
325    egress: EgressScope,
326    origin_map: Vec<(String, Url)>,
327    min_interval: Duration,
328    max_body: usize,
329    clock: Arc<dyn Clock>,
330    state: Mutex<ClientState>,
331    robots: tokio::sync::Mutex<HashMap<String, Arc<RobotsTxt>>>,
332}
333
334impl std::fmt::Debug for HttpClient {
335    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
336        f.debug_struct("HttpClient")
337            .field("robots_token", &self.robots_token)
338            .field("signed", &self.signer.is_some())
339            .field("egress", &self.egress)
340            .field("min_interval", &self.min_interval)
341            .finish_non_exhaustive()
342    }
343}
344
345impl HttpClient {
346    /// A builder: public egress, one request per second per origin, unsigned until
347    /// [`HttpClientBuilder::signer`] is set.
348    pub fn builder() -> HttpClientBuilder {
349        HttpClientBuilder {
350            robots_token: "adk-site".into(),
351            user_agent: format!("adk-site/{} (AWP site migration)", env!("CARGO_PKG_VERSION")),
352            signer: None,
353            egress: EgressScope::Public,
354            origin_map: Vec::new(),
355            min_interval: Duration::from_secs(1),
356            timeout: Duration::from_secs(30),
357            max_body: 20 * 1024 * 1024,
358            clock: Arc::new(SystemClock),
359        }
360    }
361
362    /// The product token the crawler matches `robots.txt` groups with.
363    pub fn robots_token(&self) -> &str {
364        &self.robots_token
365    }
366
367    /// Whether crawler requests are signed.
368    pub fn is_signed(&self) -> bool {
369        self.signer.is_some()
370    }
371
372    /// Every request sent or refused, in order.
373    pub fn connections(&self) -> Vec<ConnectionRecord> {
374        self.state.lock().map(|s| s.records.clone()).unwrap_or_default()
375    }
376
377    /// Every request sent or refused since the last call, in order, leaving none kept: a
378    /// long-running caller, such as the Guardian's probe every five minutes (spec 3.5 §7.20),
379    /// reads them per run so they do not accumulate.
380    pub fn take_connections(&self) -> Vec<ConnectionRecord> {
381        self.state.lock().map(|mut s| std::mem::take(&mut s.records)).unwrap_or_default()
382    }
383
384    /// The requests sent to anything other than a loopback address.
385    pub fn outbound_connections(&self) -> Vec<ConnectionRecord> {
386        self.connections().into_iter().filter(|r| r.allowed && !r.loopback).collect()
387    }
388
389    /// The `robots.txt` that applies to `url`'s origin, read once per origin.
390    ///
391    /// A missing file (4xx) allows everything; an unreadable one (5xx, no answer) disallows
392    /// everything (RFC 9309 §2.3.1).
393    pub async fn robots_for(&self, url: &Url) -> Arc<RobotsTxt> {
394        let origin = origin_of(url);
395        let mut cache = self.robots.lock().await;
396        if let Some(robots) = cache.get(&origin) {
397            return Arc::clone(robots);
398        }
399        let robots = match url.join("/robots.txt") {
400            Ok(robots_url) => {
401                match self.send_following(&robots_url, &FetchOptions::crawler(), 5).await {
402                    Ok(fetched) if (200..300).contains(&fetched.status) => {
403                        RobotsTxt::parse(&fetched.text())
404                    }
405                    Ok(fetched) if (400..500).contains(&fetched.status) => RobotsTxt::allow_all(),
406                    _ => RobotsTxt::disallow_all(),
407                }
408            }
409            Err(_) => RobotsTxt::disallow_all(),
410        };
411        let robots = Arc::new(robots);
412        if let Some(delay) = robots.crawl_delay(&self.robots_token)
413            && let Some(fetch) = self.fetch_url(url).ok().map(|(u, _)| origin_of(&u))
414            && let Ok(mut state) = self.state.lock()
415        {
416            state.delays.insert(fetch, delay);
417        }
418        cache.insert(origin, Arc::clone(&robots));
419        robots
420    }
421
422    /// Requests `url` as `options` say, after `robots.txt` allows it.
423    ///
424    /// # Errors
425    ///
426    /// [`MigrateError::RobotsDisallowed`], [`MigrateError::Egress`] before any connection;
427    /// [`MigrateError::Http`] when no answer arrives. Any HTTP status is an answer.
428    pub async fn fetch(&self, url: &Url, options: &FetchOptions) -> Result<Fetched> {
429        let mut current = url.clone();
430        let mut hops = Vec::new();
431        loop {
432            let (target, _) = self.fetch_url(&current)?;
433            if let Err(reason) = self.check_egress(&target) {
434                self.record(&target, false, Some(reason.clone()));
435                return Err(MigrateError::Egress { url: current.to_string(), reason });
436            }
437            self.check_robots(&current).await?;
438            let mut fetched = self.send(&current, options).await?;
439            hops.push((current.clone(), fetched.status));
440            match fetched.location.clone() {
441                Some(next)
442                    if fetched.is_redirect() && hops.len() <= usize::from(options.follow) =>
443                {
444                    current = next;
445                }
446                _ => {
447                    fetched.hops = hops;
448                    return Ok(fetched);
449                }
450            }
451        }
452    }
453
454    async fn check_robots(&self, url: &Url) -> Result<()> {
455        let robots = self.robots_for(url).await;
456        let path = match url.query() {
457            Some(query) => format!("{}?{query}", url.path()),
458            None => url.path().to_string(),
459        };
460        if robots.allows(&self.robots_token, &path) {
461            Ok(())
462        } else {
463            Err(MigrateError::RobotsDisallowed { url: url.to_string() })
464        }
465    }
466
467    /// Follows redirects without consulting `robots.txt`: for `robots.txt` itself.
468    async fn send_following(&self, url: &Url, options: &FetchOptions, hops: u8) -> Result<Fetched> {
469        let mut current = url.clone();
470        for _ in 0..=hops {
471            let fetched = self.send(&current, options).await?;
472            match fetched.location.clone() {
473                Some(next) if fetched.is_redirect() => current = next,
474                _ => return Ok(fetched),
475            }
476        }
477        Err(MigrateError::http(url, "too many redirects"))
478    }
479
480    /// The URL to connect to and the `Host` header to send, after the origin map.
481    fn fetch_url(&self, url: &Url) -> Result<(Url, Option<String>)> {
482        let origin = origin_of(url);
483        let Some((_, target)) = self.origin_map.iter().find(|(public, _)| *public == origin) else {
484            return Ok((url.clone(), None));
485        };
486        let mut mapped = target.clone();
487        mapped.set_path(url.path());
488        mapped.set_query(url.query());
489        let host = match (url.host_str(), url.port()) {
490            (Some(host), Some(port)) => Some(format!("{host}:{port}")),
491            (Some(host), None) => Some(host.to_string()),
492            _ => None,
493        };
494        Ok((mapped, host))
495    }
496
497    /// Maps a URL on a fetch origin back to its public origin.
498    fn public_url(&self, url: Url) -> Url {
499        let origin = origin_of(&url);
500        for (public, target) in &self.origin_map {
501            if origin_of(target) == origin
502                && let Ok(base) = Url::parse(public)
503                && let Ok(mapped) = base.join(&url[url::Position::BeforePath..])
504            {
505                return mapped;
506            }
507        }
508        url
509    }
510
511    fn record(&self, url: &Url, allowed: bool, reason: Option<String>) {
512        let loopback = match url.host() {
513            Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
514            Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
515            Some(url::Host::Domain(name)) => {
516                let name = name.trim_end_matches('.').to_ascii_lowercase();
517                name == "localhost" || name.ends_with(".localhost")
518            }
519            None => false,
520        };
521        let record = ConnectionRecord {
522            url: url.to_string(),
523            origin: origin_of(url),
524            allowed,
525            loopback,
526            reason,
527            at: self.clock.now(),
528        };
529        if let Ok(mut state) = self.state.lock() {
530            state.records.push(record);
531        }
532    }
533
534    fn check_egress(&self, url: &Url) -> std::result::Result<(), String> {
535        match url.scheme() {
536            "http" | "https" => {}
537            other => return Err(format!("scheme '{other}' is not http or https")),
538        }
539        match &self.egress {
540            EgressScope::Only(origins) => {
541                let origin = origin_of(url);
542                if origins.contains(&origin) {
543                    Ok(())
544                } else {
545                    Err(format!("origin '{origin}' is not one this client may reach"))
546                }
547            }
548            EgressScope::Public => match url.host() {
549                Some(url::Host::Ipv4(ip)) if is_non_public(IpAddr::V4(ip)) => {
550                    Err(format!("{ip} is not a public address"))
551                }
552                Some(url::Host::Ipv6(ip)) if is_non_public(IpAddr::V6(ip)) => {
553                    Err(format!("{ip} is not a public address"))
554                }
555                Some(url::Host::Domain(name))
556                    if name.eq_ignore_ascii_case("localhost")
557                        || name.to_ascii_lowercase().ends_with(".localhost") =>
558                {
559                    Err("localhost is not a public address".into())
560                }
561                Some(_) => Ok(()),
562                None => Err("the URL has no host".into()),
563            },
564        }
565    }
566
567    async fn wait_turn(&self, origin: &str) {
568        let wait_until = {
569            let Ok(mut state) = self.state.lock() else { return };
570            let delay =
571                state.delays.get(origin).copied().unwrap_or_default().max(self.min_interval);
572            let now = tokio::time::Instant::now();
573            let slot = state.next_slot.get(origin).copied().unwrap_or(now).max(now);
574            state.next_slot.insert(origin.to_string(), slot + delay);
575            slot
576        };
577        tokio::time::sleep_until(wait_until).await;
578    }
579
580    async fn send(&self, url: &Url, options: &FetchOptions) -> Result<Fetched> {
581        let (target, host) = self.fetch_url(url)?;
582        if let Err(reason) = self.check_egress(&target) {
583            tracing::warn!(url = %target, reason = %reason, "migration request refused");
584            self.record(&target, false, Some(reason.clone()));
585            return Err(MigrateError::Egress { url: url.to_string(), reason });
586        }
587        self.record(&target, true, None);
588        self.wait_turn(&origin_of(&target)).await;
589        let user_agent = match options.profile {
590            FetchProfile::Crawler => self.user_agent.as_str(),
591            FetchProfile::Browser => BROWSER_USER_AGENT,
592        };
593        let mut request = self
594            .client
595            .get(target.clone())
596            .header(reqwest::header::USER_AGENT, user_agent)
597            .headers(options.headers.clone())
598            .build()
599            .map_err(|e| MigrateError::http(url, e))?;
600        if let Some(host) = host
601            && let Ok(value) = HeaderValue::from_str(&host)
602        {
603            request.headers_mut().insert(reqwest::header::HOST, value);
604        }
605        if options.profile == FetchProfile::Crawler
606            && let Some(signer) = &self.signer
607        {
608            signer
609                .sign(&mut request)
610                .map_err(|e| MigrateError::http(url, format!("signing failed: {e}")))?;
611        }
612        let mut response =
613            self.client.execute(request).await.map_err(|e| MigrateError::http(url, e))?;
614        let status = response.status().as_u16();
615        let headers = response.headers().clone();
616        let peer_certificate = response
617            .extensions()
618            .get::<reqwest::tls::TlsInfo>()
619            .and_then(|info| info.peer_certificate())
620            .map(<[u8]>::to_vec);
621        let mut body = BytesMut::new();
622        let mut truncated = false;
623        while let Some(chunk) = response.chunk().await.map_err(|e| MigrateError::http(url, e))? {
624            if body.len() + chunk.len() > self.max_body {
625                body.extend_from_slice(&chunk[..self.max_body - body.len()]);
626                truncated = true;
627                break;
628            }
629            body.extend_from_slice(&chunk);
630        }
631        let location = headers
632            .get(reqwest::header::LOCATION)
633            .and_then(|v| v.to_str().ok())
634            .and_then(|v| target.join(v).ok())
635            .map(|u| self.public_url(u));
636        tracing::debug!(url = %url, status, bytes = body.len(), "migration request");
637        Ok(Fetched {
638            url: url.clone(),
639            hops: Vec::new(),
640            status,
641            headers,
642            body: body.freeze(),
643            truncated,
644            location,
645            peer_certificate,
646        })
647    }
648}