1use 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
31pub trait CrawlSigner: Send + Sync + std::fmt::Debug {
36 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
52#[serde(rename_all = "snake_case")]
53pub enum FetchProfile {
54 Crawler,
56 Browser,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum EgressScope {
64 Public,
67 Only(BTreeSet<String>),
70}
71
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(rename_all = "camelCase")]
75pub struct ConnectionRecord {
76 pub url: String,
78 pub origin: String,
80 pub allowed: bool,
82 pub loopback: bool,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub reason: Option<String>,
87 pub at: DateTime<Utc>,
89}
90
91#[derive(Debug, Clone)]
93pub struct FetchOptions {
94 pub profile: FetchProfile,
96 pub headers: HeaderMap,
98 pub follow: u8,
100}
101
102impl FetchOptions {
103 pub fn crawler() -> Self {
105 Self { profile: FetchProfile::Crawler, headers: HeaderMap::new(), follow: 0 }
106 }
107
108 pub fn browser() -> Self {
110 Self { profile: FetchProfile::Browser, headers: HeaderMap::new(), follow: 0 }
111 }
112
113 #[must_use]
115 pub fn following(mut self, hops: u8) -> Self {
116 self.follow = hops;
117 self
118 }
119
120 #[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#[derive(Debug, Clone)]
130pub struct Fetched {
131 pub url: Url,
133 pub hops: Vec<(Url, u16)>,
135 pub status: u16,
137 pub headers: HeaderMap,
139 pub body: Bytes,
141 pub truncated: bool,
143 pub location: Option<Url>,
145 pub peer_certificate: Option<Vec<u8>>,
147}
148
149impl Fetched {
150 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 pub fn is_html(&self) -> bool {
160 self.content_type().is_some_and(|t| t == "text/html" || t == "application/xhtml+xml")
161 }
162
163 pub fn text(&self) -> String {
165 String::from_utf8_lossy(&self.body).into_owned()
166 }
167
168 pub fn is_redirect(&self) -> bool {
170 matches!(self.status, 301 | 302 | 303 | 307 | 308)
171 }
172
173 pub fn header(&self, name: &str) -> Option<&str> {
175 self.headers.get(name).and_then(|v| v.to_str().ok())
176 }
177}
178
179pub fn origin_of(url: &Url) -> String {
181 url.origin().ascii_serialization()
182}
183
184pub 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
188pub 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 #[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 #[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 #[must_use]
218 pub fn signer(mut self, signer: Arc<dyn CrawlSigner>) -> Self {
219 self.signer = Some(signer);
220 self
221 }
222
223 #[must_use]
225 pub fn egress(mut self, egress: EgressScope) -> Self {
226 self.egress = egress;
227 self
228 }
229
230 #[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 #[must_use]
239 pub fn min_interval(mut self, interval: Duration) -> Self {
240 self.min_interval = interval;
241 self
242 }
243
244 #[must_use]
246 pub fn timeout(mut self, timeout: Duration) -> Self {
247 self.timeout = timeout;
248 self
249 }
250
251 #[must_use]
253 pub fn max_body(mut self, bytes: usize) -> Self {
254 self.max_body = bytes;
255 self
256 }
257
258 #[must_use]
260 pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
261 self.clock = clock;
262 self
263 }
264
265 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
305pub 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 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 pub fn robots_token(&self) -> &str {
364 &self.robots_token
365 }
366
367 pub fn is_signed(&self) -> bool {
369 self.signer.is_some()
370 }
371
372 pub fn connections(&self) -> Vec<ConnectionRecord> {
374 self.state.lock().map(|s| s.records.clone()).unwrap_or_default()
375 }
376
377 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 pub fn outbound_connections(&self) -> Vec<ConnectionRecord> {
386 self.connections().into_iter().filter(|r| r.allowed && !r.loopback).collect()
387 }
388
389 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 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(¤t)?;
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(¤t).await?;
438 let mut fetched = self.send(¤t, 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 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(¤t, 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 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 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}