Skip to main content

adk_awp/verify/
fetch.rs

1//! Passive fetching for the verifier and the conformance kit: `GET` only (spec 3.5 §7.7,
2//! A-I9; AWP 2.0 §15.1).
3
4use std::sync::Arc;
5
6use async_trait::async_trait;
7use axum::Router;
8use axum::body::Body;
9use axum::http::{HeaderMap, HeaderValue, Request, header};
10use bytes::Bytes;
11use tower::util::ServiceExt;
12
13/// The largest response the verifier reads.
14pub const MAX_RESPONSE_BYTES: usize = 16 * 1024 * 1024;
15
16/// A fetched response.
17#[derive(Debug, Clone)]
18pub struct Fetched {
19    /// The HTTP status.
20    pub status: u16,
21    /// The response headers.
22    pub headers: HeaderMap,
23    /// The body.
24    pub body: Bytes,
25}
26
27impl Fetched {
28    /// The `Content-Type` without parameters, lowercased.
29    pub fn media_type(&self) -> Option<String> {
30        self.headers
31            .get(header::CONTENT_TYPE)
32            .and_then(|value| value.to_str().ok())
33            .map(|value| value.split(';').next().unwrap_or_default().trim().to_ascii_lowercase())
34    }
35
36    /// The value of header `name`, if it is text.
37    pub fn header(&self, name: &str) -> Option<&str> {
38        self.headers.get(name).and_then(|value| value.to_str().ok())
39    }
40}
41
42/// Why a fetch failed.
43#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
44#[error("GET {url} failed: {reason}")]
45pub struct FetchError {
46    /// The URL.
47    pub url: String,
48    /// Why.
49    pub reason: String,
50}
51
52/// Sends `GET` requests; the verifier and the conformance kit never send anything else (A-I9).
53#[async_trait]
54pub trait Fetcher: Send + Sync {
55    /// Fetches `url` with `GET`, adding `headers`.
56    ///
57    /// # Errors
58    ///
59    /// [`FetchError`] when the request cannot be made; an HTTP error status is a response.
60    async fn get(&self, url: &str, headers: &HeaderMap) -> Result<Fetched, FetchError>;
61}
62
63/// Signs outgoing requests, such as with Web Bot Auth (spec 3.5 §7.3 "Outbound").
64#[async_trait]
65pub trait RequestSigner: Send + Sync {
66    /// Adds signature headers for a `GET` of `url` to `headers`.
67    ///
68    /// # Errors
69    ///
70    /// A message when the request cannot be signed.
71    async fn sign(&self, url: &str, headers: &mut HeaderMap) -> Result<(), String>;
72}
73
74/// Fetches over HTTPS with `reqwest`, following no redirects, optionally signing each
75/// request.
76#[derive(Clone)]
77pub struct HttpFetcher {
78    client: reqwest::Client,
79    signer: Option<Arc<dyn RequestSigner>>,
80}
81
82impl std::fmt::Debug for HttpFetcher {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        f.debug_struct("HttpFetcher").field("signed", &self.signer.is_some()).finish()
85    }
86}
87
88impl HttpFetcher {
89    /// Creates a fetcher with a 30-second timeout that follows no redirects.
90    ///
91    /// # Errors
92    ///
93    /// [`FetchError`] when the client cannot be built.
94    pub fn new() -> Result<Self, FetchError> {
95        let client = reqwest::Client::builder()
96            .redirect(reqwest::redirect::Policy::none())
97            .timeout(std::time::Duration::from_secs(30))
98            .user_agent(concat!("adk-awp-verify/", env!("CARGO_PKG_VERSION")))
99            .build()
100            .map_err(|error| FetchError { url: String::new(), reason: error.to_string() })?;
101        Ok(Self { client, signer: None })
102    }
103
104    /// Signs every request with `signer`.
105    pub fn with_signer(mut self, signer: Arc<dyn RequestSigner>) -> Self {
106        self.signer = Some(signer);
107        self
108    }
109}
110
111#[async_trait]
112impl Fetcher for HttpFetcher {
113    async fn get(&self, url: &str, headers: &HeaderMap) -> Result<Fetched, FetchError> {
114        let failed = |reason: String| FetchError { url: url.to_owned(), reason };
115        let mut headers = headers.clone();
116        if let Some(signer) = &self.signer {
117            signer.sign(url, &mut headers).await.map_err(failed)?;
118        }
119        let response = self
120            .client
121            .get(url)
122            .headers(headers)
123            .send()
124            .await
125            .map_err(|error| failed(error.to_string()))?;
126        let status = response.status().as_u16();
127        let mut response_headers = HeaderMap::new();
128        for (name, value) in response.headers() {
129            response_headers.append(name.clone(), value.clone());
130        }
131        let body = response.bytes().await.map_err(|error| failed(error.to_string()))?;
132        if body.len() > MAX_RESPONSE_BYTES {
133            return Err(failed("the response is too large".to_owned()));
134        }
135        Ok(Fetched { status, headers: response_headers, body })
136    }
137}
138
139/// Fetches from an in-process Axum router, for tests and conformance runs against a router:
140/// the URL's path and query go to the router, its host to the `Host` header.
141#[derive(Clone)]
142pub struct RouterFetcher {
143    router: Router,
144}
145
146impl std::fmt::Debug for RouterFetcher {
147    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148        f.debug_struct("RouterFetcher").finish_non_exhaustive()
149    }
150}
151
152impl RouterFetcher {
153    /// Fetches from `router`.
154    pub fn new(router: Router) -> Self {
155        Self { router }
156    }
157}
158
159#[async_trait]
160impl Fetcher for RouterFetcher {
161    async fn get(&self, url: &str, headers: &HeaderMap) -> Result<Fetched, FetchError> {
162        let failed = |reason: &str| FetchError { url: url.to_owned(), reason: reason.to_owned() };
163        let rest = url.strip_prefix("https://").ok_or_else(|| failed("only https URLs"))?;
164        let (host, path) = rest
165            .split_once('/')
166            .map_or((rest, "/".to_owned()), |(host, path)| (host, format!("/{path}")));
167        let mut request = Request::get(path).body(Body::empty()).map_err(|_| failed("bad URL"))?;
168        *request.headers_mut() = headers.clone();
169        let host = HeaderValue::from_str(host).map_err(|_| failed("bad host"))?;
170        request.headers_mut().insert(header::HOST, host);
171        let response =
172            self.router.clone().oneshot(request).await.map_err(|_| failed("router failed"))?;
173        let status = response.status().as_u16();
174        let headers = response.headers().clone();
175        let body = axum::body::to_bytes(response.into_body(), MAX_RESPONSE_BYTES)
176            .await
177            .map_err(|_| failed("the response is too large"))?;
178        Ok(Fetched { status, headers, body })
179    }
180}