Skip to main content

adk_harness/website/
verify.rs

1//! `awp verify` as the back office runs it: published documents fetched with `GET` only,
2//! signed with the site's key (spec 3.5 §7.3 "Outbound", §7.7, A-I9).
3//!
4//! | Verifier | Checks | Use |
5//! |---|---|---|
6//! | `adk_awp::verify::Verifier` | The whole AWP 2.0 §15 procedure: contract, keys, DNS root, delegations, card, log, releases, pages, public terms | A site that publishes its contract |
7//! | [`ReleaseLogVerifier`] | The release log's checkpoint and inclusion, and sampled pages | A site whose contract is not published yet: onboarding, a migration's first releases |
8
9use std::sync::Arc;
10use std::time::Duration;
11
12use adk_auth::signed_audit::NoteVerifier;
13use adk_core::Result;
14use adk_site::log::{
15    CHECKPOINT_PATH, LOG_PREFIX, TileFetch, TileProofs, verify_checkpoint, verify_release_inclusion,
16};
17use adk_site::release::{file_digest, manifest_path};
18use async_trait::async_trait;
19use awp_types::ReleaseManifest;
20use bytes::Bytes;
21use serde::{Deserialize, Serialize};
22
23use crate::web::RequestSigner;
24
25/// One check of a verification (spec 3.5 §7.7).
26#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(rename_all = "camelCase")]
28pub struct VerifyCheck {
29    /// What was checked: `checkpoint`, `inclusion`, `pages`.
30    pub name: String,
31    /// Whether it passed.
32    pub passed: bool,
33    /// What was found.
34    pub detail: String,
35}
36
37/// What `awp verify` found (spec 3.5 §7.7).
38#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "camelCase")]
40pub struct VerifyReport {
41    /// The origin verified.
42    pub origin: String,
43    /// The release the log's checkpoint names, when it verified.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub release: Option<u64>,
46    /// Every check, in order.
47    pub checks: Vec<VerifyCheck>,
48}
49
50impl VerifyReport {
51    /// Whether every check passed.
52    pub fn passed(&self) -> bool {
53        !self.checks.is_empty() && self.checks.iter().all(|check| check.passed)
54    }
55}
56
57/// Verifies a served site from what it publishes (spec 3.5 §7.7): the contract, cards,
58/// checkpoint, release inclusion and sampled pages: `adk-awp`'s `Verifier`, the library
59/// behind `adk-rust awp verify`, or [`ReleaseLogVerifier`] before the site publishes a
60/// contract.
61#[async_trait]
62pub trait SiteVerifier: Send + Sync {
63    /// Verifies the site at `origin` with `GET` requests for published documents only
64    /// (A-I9).
65    ///
66    /// # Errors
67    ///
68    /// Returns an error when the verification could not run; a site that fails a check is
69    /// an `Ok` report that did not pass.
70    async fn verify(&self, origin: &str) -> Result<VerifyReport>;
71}
72
73/// The release log and page checks of `awp verify` for a site that publishes no contract yet
74/// (spec 3.5 §7.7, §7.18 stage 7): the checkpoint's
75/// signature by a trusted release key and its origin, the current release's inclusion in
76/// the log, and the digests of up to `samples` pages against the release manifest. Every
77/// request is a `GET`, signed when a signer is set (spec 3.5 §7.3 "Outbound").
78///
79/// # Example
80///
81/// ```rust,ignore
82/// let verifier = ReleaseLogVerifier::new("bakery.example", vec![release_key]).with_signer(signer);
83/// let report = verifier.verify("https://bakery.example").await?;
84/// assert!(report.passed());
85/// ```
86#[derive(Clone)]
87pub struct ReleaseLogVerifier {
88    domain: String,
89    keys: Vec<NoteVerifier>,
90    samples: usize,
91    signer: Option<Arc<dyn RequestSigner>>,
92    timeout: Duration,
93}
94
95impl std::fmt::Debug for ReleaseLogVerifier {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        f.debug_struct("ReleaseLogVerifier")
98            .field("domain", &self.domain)
99            .field("samples", &self.samples)
100            .finish_non_exhaustive()
101    }
102}
103
104impl ReleaseLogVerifier {
105    /// A verifier of `domain`'s log, trusting `keys` (its release keys), sampling 20 pages.
106    pub fn new(domain: impl Into<String>, keys: Vec<NoteVerifier>) -> Self {
107        Self {
108            domain: domain.into(),
109            keys,
110            samples: 20,
111            signer: None,
112            timeout: Duration::from_secs(20),
113        }
114    }
115
116    /// Samples `n` pages.
117    #[must_use]
118    pub fn with_samples(mut self, n: usize) -> Self {
119        self.samples = n;
120        self
121    }
122
123    /// Signs every request with `signer`.
124    #[must_use]
125    pub fn with_signer(mut self, signer: Arc<dyn RequestSigner>) -> Self {
126        self.signer = Some(signer);
127        self
128    }
129}
130
131/// `GET`s published documents of one origin, signed when a signer is set.
132pub(crate) struct OriginReader {
133    origin: String,
134    client: reqwest::Client,
135    signer: Option<Arc<dyn RequestSigner>>,
136}
137
138impl OriginReader {
139    pub(crate) fn new(
140        origin: &str,
141        signer: Option<Arc<dyn RequestSigner>>,
142        timeout: Duration,
143    ) -> Result<Self> {
144        let client = reqwest::Client::builder()
145            .redirect(reqwest::redirect::Policy::none())
146            .no_proxy()
147            .timeout(timeout)
148            .build()
149            .map_err(|e| adk_core::AdkError::tool(format!("http client: {e}")))?;
150        Ok(Self { origin: origin.trim_end_matches('/').to_string(), client, signer })
151    }
152
153    /// The body at `path`, `None` on 404.
154    pub(crate) async fn get(&self, path: &str) -> Result<Option<Bytes>> {
155        let url = format!("{}/{}", self.origin, path.trim_start_matches('/'));
156        let mut request = self
157            .client
158            .get(&url)
159            .build()
160            .map_err(|e| adk_core::AdkError::tool(format!("request {url}: {e}")))?;
161        if let Some(signer) = &self.signer {
162            signer.sign(&mut request).map_err(|reason| {
163                adk_core::AdkError::tool(format!("the request could not be signed: {reason}"))
164            })?;
165        }
166        let response = self
167            .client
168            .execute(request)
169            .await
170            .map_err(|e| adk_core::AdkError::tool(format!("GET {url}: {}", e.without_url())))?;
171        match response.status().as_u16() {
172            404 | 410 => Ok(None),
173            200..=299 => Ok(Some(response.bytes().await.map_err(|e| {
174                adk_core::AdkError::tool(format!("GET {url}: {}", e.without_url()))
175            })?)),
176            status => Err(adk_core::AdkError::tool(format!("GET {url} answered {status}"))),
177        }
178    }
179}
180
181struct HttpTiles<'a>(&'a OriginReader);
182
183#[async_trait]
184impl TileFetch for HttpTiles<'_> {
185    async fn fetch_tile(&self, path: &str) -> adk_site::Result<Option<Bytes>> {
186        self.0
187            .get(&format!("{LOG_PREFIX}/{path}"))
188            .await
189            .map_err(|e| adk_site::SiteError::Log(e.to_string()))
190    }
191}
192
193fn check(name: &str, passed: bool, detail: impl Into<String>) -> VerifyCheck {
194    VerifyCheck { name: name.to_string(), passed, detail: detail.into() }
195}
196
197#[async_trait]
198impl SiteVerifier for ReleaseLogVerifier {
199    async fn verify(&self, origin: &str) -> Result<VerifyReport> {
200        let reader = OriginReader::new(origin, self.signer.clone(), self.timeout)?;
201        let mut report =
202            VerifyReport { origin: origin.to_string(), release: None, checks: Vec::new() };
203        let Some(note) = reader.get(CHECKPOINT_PATH).await? else {
204            report.checks.push(check("checkpoint", false, "the site publishes no log checkpoint"));
205            return Ok(report);
206        };
207        let checkpoint =
208            match verify_checkpoint(&String::from_utf8_lossy(&note), &self.domain, &self.keys) {
209                Ok(checkpoint) => checkpoint,
210                Err(error) => {
211                    report.checks.push(check("checkpoint", false, error.to_string()));
212                    return Ok(report);
213                }
214            };
215        let seq = checkpoint.size;
216        report.release = Some(seq);
217        report.checks.push(check(
218            "checkpoint",
219            true,
220            format!("signed checkpoint of release {seq}"),
221        ));
222        let Some(manifest_bytes) = reader.get(&manifest_path(seq)).await? else {
223            report.checks.push(check(
224                "inclusion",
225                false,
226                format!("release {seq}'s manifest is not served"),
227            ));
228            return Ok(report);
229        };
230        let tiles = HttpTiles(&reader);
231        let proofs = TileProofs::new(&tiles, seq);
232        let included = async {
233            let entry = proofs.entry(seq - 1).await?;
234            let proof = proofs.inclusion_proof(seq - 1).await?;
235            verify_release_inclusion(
236                &checkpoint,
237                &entry,
238                &proof,
239                seq,
240                &file_digest(&manifest_bytes),
241            )
242        }
243        .await;
244        report.checks.push(match included {
245            Ok(()) => check("inclusion", true, format!("release {seq} is in the log")),
246            Err(error) => check("inclusion", false, error.to_string()),
247        });
248        let manifest: ReleaseManifest = match serde_json::from_slice(&manifest_bytes) {
249            Ok(manifest) => manifest,
250            Err(error) => {
251                report.checks.push(check(
252                    "pages",
253                    false,
254                    format!("the manifest does not parse: {error}"),
255                ));
256                return Ok(report);
257            }
258        };
259        // A delta lists only its changes; the pages it lists are still the release's.
260        let mut mismatched = Vec::new();
261        let mut sampled = 0;
262        for (path, entry) in
263            manifest.files.iter().filter(|(p, _)| p.ends_with(".html")).take(self.samples)
264        {
265            sampled += 1;
266            match reader.get(path).await? {
267                Some(bytes) if file_digest(&bytes) == entry.sha256 => {}
268                _ => mismatched.push(path.clone()),
269            }
270        }
271        report.checks.push(if mismatched.is_empty() {
272            check("pages", true, format!("{sampled} sampled pages match release {seq}"))
273        } else {
274            check(
275                "pages",
276                false,
277                format!("pages differ from release {seq}: {}", mismatched.join(", ")),
278            )
279        });
280        Ok(report)
281    }
282}
283
284/// The whole `awp verify` (AWP 2.0 §15) as the back office's verifier. `origin` names the
285/// domain, with or without its scheme.
286#[async_trait]
287impl SiteVerifier for adk_awp::verify::Verifier {
288    async fn verify(&self, origin: &str) -> Result<VerifyReport> {
289        let domain = origin
290            .trim_start_matches("https://")
291            .trim_start_matches("http://")
292            .trim_end_matches('/');
293        let report = adk_awp::verify::Verifier::verify(self, domain).await;
294        let mut checks = vec![match &report.failure {
295            None => check("awp", true, format!("{} sampled files match", report.sampled.len())),
296            Some(failure) => check(failure.name, false, failure.detail.clone()),
297        }];
298        if !report.posture.server_code.is_empty() {
299            checks.push(check("server_code", false, report.posture.server_code.join(", ")));
300        }
301        Ok(VerifyReport { origin: origin.to_string(), release: report.release_seq, checks })
302    }
303}