Skip to main content

adk_awp/conformance/
mod.rs

1//! The AWP 2.0 conformance kit (feature `verify`; spec 3.5 §7.7 "Conformance kit"; AWP 2.0
2//! §16).
3//!
4//! [`run`] checks a site against its profile's requirements — `static` S1–S9, `static+edge`
5//! adds E1–E13, `dynamic` takes the edge rows — through any [`Fetcher`]: HTTPS for a deployed
6//! site, [`RouterFetcher`](crate::verify::fetch::RouterFetcher) for an in-process one. Passive
7//! checks send only `GET` requests for published documents. Active checks of edge routes —
8//! still `GET` only — run when [`ConformanceOptions::active_edge_checks`] is set, which the
9//! caller does only for deployments whose control the operator proved (A-I9). Requirements no
10//! passive or `GET` check can observe are reported as skipped.
11//!
12//! [`rules`] holds the document rules the types accept and conformance enforces; [`fixture`]
13//! a deterministic signed site; [`vectors`] the protocol's test vectors.
14
15pub mod fixture;
16pub mod rules;
17pub mod vectors;
18
19use std::sync::Arc;
20
21use awp_types::{
22    CapabilityManifestV2, ErrorCode, ErrorEnvelope, KeyScope, KeySet, Profile, SiteContract,
23    SiteStatus, TrustTier,
24};
25use axum::http::{HeaderMap, HeaderValue};
26use chrono::{DateTime, Utc};
27use serde_json::Value;
28
29use crate::signing::anchor::DnsTxtResolver;
30use crate::signing::jws::verify;
31use crate::signing::keys::{Dated, delegated_key, verify_key_set};
32use crate::verify::fetch::Fetcher;
33use crate::verify::pins::InMemoryPinStore;
34use crate::verify::{Verifier, VerifyOptions};
35
36use rules::{DocumentKind, check_document, release_rules};
37
38/// Options of a conformance run.
39#[derive(Debug, Clone, Default)]
40pub struct ConformanceOptions {
41    /// Run the `GET` checks of edge routes; only for a deployment whose control the operator
42    /// proved (A-I9).
43    pub active_edge_checks: bool,
44    /// Files sampled; `0` uses the verifier's default.
45    pub samples: usize,
46    /// The time live documents are checked at; `None` is now.
47    pub now: Option<DateTime<Utc>>,
48}
49
50/// The outcome of one requirement.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52#[non_exhaustive]
53pub enum CheckStatus {
54    /// Met.
55    Pass,
56    /// Not met.
57    Fail,
58    /// Not observable by this run.
59    Skipped,
60}
61
62/// One requirement's result (AWP 2.0 §16.1).
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct CheckResult {
65    /// The requirement's id, such as `S5` or `E3`.
66    pub id: &'static str,
67    /// The requirement.
68    pub requirement: &'static str,
69    /// The outcome.
70    pub status: CheckStatus,
71    /// Why, for a failure or a skip.
72    pub detail: String,
73}
74
75/// A conformance run's results.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct ConformanceReport {
78    /// The domain.
79    pub domain: String,
80    /// The contract's profile.
81    pub profile: Option<Profile>,
82    /// One result per requirement of the profile.
83    pub results: Vec<CheckResult>,
84}
85
86impl ConformanceReport {
87    /// Returns `true` when no requirement failed.
88    pub fn passed(&self) -> bool {
89        self.results.iter().all(|result| result.status != CheckStatus::Fail)
90    }
91
92    /// Returns the result of requirement `id`.
93    pub fn result(&self, id: &str) -> Option<&CheckResult> {
94        self.results.iter().find(|result| result.id == id)
95    }
96}
97
98const STATIC_REQUIREMENTS: &[(&str, &str)] = &[
99    ("S1", "Serves the contract as application/awp+json with profile, keys, release and proof"),
100    ("S2", "Serves the key set; the root signs the contract and the delegations"),
101    ("S3", "Publishes the _awp-root DNS record for the root key"),
102    ("S4", "Serves no file outside its latest release and no server-executable file"),
103    ("S5", "Publishes the release manifests, the site log as tiles and a signed checkpoint"),
104    ("S6", "Gives every HTML page both twins, linked with rel=\"alternate\""),
105    ("S7", "Publishes its public terms with a matching digest"),
106    ("S8", "Signs its A2A Agent Card with a card delegation"),
107    ("S9", "Uses snapshots and deltas as AWP 2.0 §14.4 defines"),
108];
109
110const EDGE_REQUIREMENTS: &[(&str, &str)] = &[
111    ("E1", "The contract names identity, status, the manifest and an A2A or MCP surface"),
112    ("E2", "Assigns tiers only from verified credentials"),
113    ("E3", "Lists only the capabilities visible to the caller's tier"),
114    ("E4", "Exposes every capability over each advertised binding through one governed path"),
115    ("E5", "Answers held calls with 202, Location and the held-call document"),
116    ("E6", "Executes a non_idempotent capability at most once per idempotency key"),
117    ("E7", "Refuses consent-bound calls without a live receipt; revocation, export, erasure"),
118    ("E8", "Serves a signed status"),
119    ("E9", "Delivers events as Standard Webhooks with retries, suspension and replay"),
120    ("E10", "Signs commerce receipts; honours open quotes"),
121    ("E11", "Answers failures with the error envelope"),
122    ("E12", "Negotiates versions with AWP-Version"),
123    ("E13", "Exposes no route that changes the site, its content, its policies or its keys"),
124];
125
126/// The requirement a verifier failure breaks, and the order in which the verifier reaches it.
127fn requirement_of(failure: &str) -> (&'static str, usize) {
128    match failure {
129        "contract.unavailable" | "contract.invalid" => ("S1", 0),
130        "keys.unavailable" | "keys.invalid" => ("S2", 1),
131        "root.unanchored" | "root.changed" => ("S3", 2),
132        "contract.signature" | "delegation.signature" => ("S2", 3),
133        "card.signature" => ("S8", 4),
134        "charter.digest" => ("S7", 5),
135        "release.executable" | "page.digest" => ("S4", 7),
136        _ => ("S5", 6),
137    }
138}
139
140fn first_reached(id: &str) -> usize {
141    match id {
142        "S1" => 0,
143        "S2" => 1,
144        "S3" => 2,
145        "S8" => 4,
146        "S7" => 5,
147        "S5" | "S9" => 6,
148        "S4" | "S6" => 7,
149        _ => 8,
150    }
151}
152
153fn result(
154    id: &'static str,
155    requirement: &'static str,
156    status: CheckStatus,
157    detail: impl Into<String>,
158) -> CheckResult {
159    CheckResult { id, requirement, status, detail: detail.into() }
160}
161
162/// Runs the conformance suite against `domain` (AWP 2.0 §16).
163///
164/// # Example
165///
166/// ```
167/// use std::sync::Arc;
168///
169/// use adk_awp::conformance::fixture::{FixtureSite, fixture_time};
170/// use adk_awp::conformance::{ConformanceOptions, run};
171/// use adk_awp::verify::fetch::RouterFetcher;
172/// use awp_types::Profile;
173///
174/// # #[tokio::main(flavor = "current_thread")]
175/// # async fn main() {
176/// let site = FixtureSite::build("example.com", Profile::Static).await.unwrap();
177/// let options = ConformanceOptions { now: Some(fixture_time()), ..Default::default() };
178/// let report = run(
179///     Arc::new(RouterFetcher::new(site.router())),
180///     Arc::new(site.resolver.clone()),
181///     "example.com",
182///     &options,
183/// )
184/// .await;
185/// assert!(report.passed(), "{report:#?}");
186/// # }
187/// ```
188pub async fn run(
189    fetcher: Arc<dyn Fetcher>,
190    resolver: Arc<dyn DnsTxtResolver>,
191    domain: &str,
192    options: &ConformanceOptions,
193) -> ConformanceReport {
194    let now = options.now.unwrap_or_else(Utc::now);
195    let mut verify_options = VerifyOptions { now: Some(now), ..Default::default() };
196    if options.samples > 0 {
197        verify_options.samples = options.samples;
198    }
199    let verifier =
200        Verifier::new(Arc::clone(&fetcher), resolver, Arc::new(InMemoryPinStore::default()))
201            .with_options(verify_options);
202    let verified = verifier.verify(domain).await;
203    let origin = format!("https://{}", verified.domain);
204
205    let contract_value =
206        fetch_json(fetcher.as_ref(), &format!("{origin}/.well-known/awp.json"), &HeaderMap::new())
207            .await;
208    let contract: Option<SiteContract> =
209        contract_value.as_ref().and_then(|value| serde_json::from_value(value.clone()).ok());
210    let profile = contract.as_ref().and_then(|contract| contract.profile);
211    let contract_violations = contract_value
212        .as_ref()
213        .map(|value| check_document(DocumentKind::SiteContract, value))
214        .unwrap_or_default();
215
216    let failed_at =
217        verified.failure.as_ref().map(|failure| (requirement_of(failure.name), failure));
218    let mut results = Vec::new();
219    for &(id, requirement) in STATIC_REQUIREMENTS {
220        if profile == Some(Profile::Dynamic) && matches!(id, "S4" | "S5" | "S8" | "S9") {
221            continue;
222        }
223        let verdict = match failed_at {
224            Some(((broken, _), failure)) if broken == id => {
225                result(id, requirement, CheckStatus::Fail, failure.to_string())
226            }
227            Some(((_, order), failure)) if first_reached(id) > order => result(
228                id,
229                requirement,
230                CheckStatus::Skipped,
231                format!("not reached: verification stopped at {}", failure.name),
232            ),
233            _ => result(id, requirement, CheckStatus::Pass, ""),
234        };
235        results.push(verdict);
236    }
237
238    // S1 member rules.
239    let s1: Vec<String> = contract_violations
240        .iter()
241        .filter(|v| {
242            matches!(
243                v.rule,
244                "contract.proof"
245                    | "contract.keys"
246                    | "contract.profile"
247                    | "contract.release"
248                    | "document.schema"
249            )
250        })
251        .map(|v| format!("{}: {}", v.rule, v.detail))
252        .collect();
253    downgrade(&mut results, "S1", &s1);
254
255    // S9 release rules on the latest manifest.
256    if let Some(seq) = verified.release_seq {
257        let url = format!("{origin}/.well-known/awp/releases/{seq}.json");
258        let s9: Vec<String> = match fetch_json(fetcher.as_ref(), &url, &HeaderMap::new()).await {
259            Some(value) => match serde_json::from_value(value) {
260                Ok(manifest) => release_rules(&manifest)
261                    .into_iter()
262                    .map(|v| format!("{}: {}", v.rule, v.detail))
263                    .collect(),
264                Err(error) => vec![format!("document.schema: {error}")],
265            },
266            None => vec![format!("{url} is unavailable")],
267        };
268        downgrade(&mut results, "S9", &s9);
269    }
270
271    // S6 machine views of the sampled HTML pages.
272    if contract.as_ref().and_then(|c| c.surfaces.as_ref()).is_some_and(|s| s.machine_views) {
273        let mut s6 = Vec::new();
274        for path in verified.sampled.iter().filter(|path| path.ends_with("/index.html")) {
275            let base = path.trim_end_matches("index.html");
276            for twin in ["index.awp.json", "index.md"] {
277                let url = format!("{origin}{base}{twin}");
278                match fetcher.get(&url, &HeaderMap::new()).await {
279                    Ok(fetched) if fetched.status == 200 => {}
280                    _ => s6.push(format!("{base}{twin} is missing")),
281                }
282            }
283            if let Ok(page) = fetcher.get(&format!("{origin}{path}"), &HeaderMap::new()).await {
284                let html = String::from_utf8_lossy(&page.body);
285                if !html.contains("type=\"application/awp+json\"")
286                    || !html.contains("type=\"text/markdown\"")
287                {
288                    s6.push(format!("{path} does not link its twins"));
289                }
290            }
291        }
292        downgrade(&mut results, "S6", &s6);
293    }
294
295    if matches!(profile, Some(Profile::StaticEdge | Profile::Dynamic)) {
296        let keys: Option<KeySet> = match contract.as_ref().and_then(|c| c.keys.clone()) {
297            Some(url) => fetch_json(fetcher.as_ref(), &url, &HeaderMap::new())
298                .await
299                .and_then(|value| serde_json::from_value(value).ok())
300                .filter(|keys| verify_key_set(keys).is_ok()),
301            None => None,
302        };
303        edge_checks(
304            &mut results,
305            fetcher.as_ref(),
306            contract.as_ref(),
307            keys.as_ref(),
308            &contract_violations,
309            options,
310            now,
311        )
312        .await;
313    }
314    ConformanceReport { domain: verified.domain, profile, results }
315}
316
317fn downgrade(results: &mut [CheckResult], id: &str, problems: &[String]) {
318    if problems.is_empty() {
319        return;
320    }
321    if let Some(result) =
322        results.iter_mut().find(|result| result.id == id && result.status != CheckStatus::Fail)
323    {
324        result.status = CheckStatus::Fail;
325        result.detail = problems.join("; ");
326    }
327}
328
329async fn fetch_json(fetcher: &dyn Fetcher, url: &str, headers: &HeaderMap) -> Option<Value> {
330    let fetched = fetcher.get(url, headers).await.ok()?;
331    (fetched.status == 200).then(|| serde_json::from_slice(&fetched.body).ok()).flatten()
332}
333
334async fn edge_checks(
335    results: &mut Vec<CheckResult>,
336    fetcher: &dyn Fetcher,
337    contract: Option<&SiteContract>,
338    keys: Option<&KeySet>,
339    contract_violations: &[rules::RuleViolation],
340    options: &ConformanceOptions,
341    now: DateTime<Utc>,
342) {
343    let e1: Vec<String> = contract_violations
344        .iter()
345        .filter(|v| {
346            matches!(
347                v.rule,
348                "contract.identity" | "contract.status" | "contract.manifest" | "contract.surfaces"
349            )
350        })
351        .map(|v| format!("{}: {}", v.rule, v.detail))
352        .collect();
353    for &(id, requirement) in EDGE_REQUIREMENTS {
354        let skipped = |why: &str| result(id, requirement, CheckStatus::Skipped, why);
355        let outcome = match id {
356            "E1" if e1.is_empty() => result(id, requirement, CheckStatus::Pass, ""),
357            "E1" => result(id, requirement, CheckStatus::Fail, e1.join("; ")),
358            _ if !options.active_edge_checks => skipped(
359                "active edge checks run only against a deployment whose control the operator proved (A-I9)",
360            ),
361            "E3" => check_manifest(fetcher, contract).await,
362            "E8" => check_status(fetcher, contract, keys, now).await,
363            "E11" => check_error_envelope(fetcher, contract).await,
364            "E12" => check_negotiation(fetcher, contract).await,
365            _ => skipped(
366                "needs capability calls, credentials or deliveries; a GET-only kit cannot observe it",
367            ),
368        };
369        let outcome = CheckResult { id, requirement, ..outcome };
370        results.push(outcome);
371    }
372}
373
374fn verdict(problem: Option<String>) -> CheckResult {
375    match problem {
376        None => result("", "", CheckStatus::Pass, ""),
377        Some(problem) => result("", "", CheckStatus::Fail, problem),
378    }
379}
380
381fn manifest_url(contract: Option<&SiteContract>) -> Option<String> {
382    contract.and_then(|c| c.surfaces.as_ref()).and_then(|s| s.manifest.clone())
383}
384
385async fn check_manifest(fetcher: &dyn Fetcher, contract: Option<&SiteContract>) -> CheckResult {
386    let Some(url) = manifest_url(contract) else {
387        return verdict(Some("no manifest URL".to_owned()));
388    };
389    let Some(value) = fetch_json(fetcher, &url, &HeaderMap::new()).await else {
390        return verdict(Some(format!("{url} is unavailable")));
391    };
392    let mut problems: Vec<String> = check_document(DocumentKind::CapabilityManifest, &value)
393        .into_iter()
394        .map(|v| v.detail)
395        .collect();
396    if let Ok(manifest) = serde_json::from_value::<CapabilityManifestV2>(value) {
397        if manifest.tier != Some(TrustTier::Public) {
398            problems.push("an unauthenticated caller is not listed as public".to_owned());
399        }
400        problems.extend(
401            manifest
402                .capabilities
403                .iter()
404                .filter(|c| c.min_trust > TrustTier::Public)
405                .map(|c| format!("`{}` needs {} but is listed to public", c.name, c.min_trust)),
406        );
407    }
408    verdict((!problems.is_empty()).then(|| problems.join("; ")))
409}
410
411async fn check_status(
412    fetcher: &dyn Fetcher,
413    contract: Option<&SiteContract>,
414    keys: Option<&KeySet>,
415    now: DateTime<Utc>,
416) -> CheckResult {
417    let Some(url) = contract.and_then(|c| c.status.as_ref()).map(|s| s.url.clone()) else {
418        return verdict(Some("no status URL".to_owned()));
419    };
420    let Some(value) = fetch_json(fetcher, &url, &HeaderMap::new()).await else {
421        return verdict(Some(format!("{url} is unavailable")));
422    };
423    let Ok(status) = serde_json::from_value::<SiteStatus>(value.clone()) else {
424        return verdict(Some("the status is not a signed status document".to_owned()));
425    };
426    let Some(keys) = keys else { return verdict(Some("the key set does not verify".to_owned())) };
427    let problem = match delegated_key(keys, &status.proof.kid, KeyScope::Receipt, Dated::Live(now))
428    {
429        Ok(key) => verify(&value, &status.proof, key).err().map(|error| error.to_string()),
430        Err(error) => Some(error.to_string()),
431    };
432    verdict(problem)
433}
434
435async fn check_error_envelope(
436    fetcher: &dyn Fetcher,
437    contract: Option<&SiteContract>,
438) -> CheckResult {
439    let Some(base) = manifest_url(contract)
440        .and_then(|url| url.strip_suffix("/awp/v2/manifest").map(str::to_owned))
441    else {
442        return verdict(Some("no edge origin".to_owned()));
443    };
444    let url = format!("{base}/awp/v2/calls/conformance-{}", uuid::Uuid::new_v4().simple());
445    let problem = match fetcher.get(&url, &HeaderMap::new()).await {
446        Ok(fetched) if fetched.status == 404 => {
447            match serde_json::from_slice::<ErrorEnvelope>(&fetched.body) {
448                Ok(envelope)
449                    if envelope.awp.major == 2
450                        && envelope.error.code == ErrorCode::ResourceNotFound =>
451                {
452                    None
453                }
454                Ok(envelope) => Some(format!("an unknown call answered {}", envelope.error.code)),
455                Err(error) => Some(format!("the 404 is not an error envelope: {error}")),
456            }
457        }
458        Ok(fetched) => Some(format!("an unknown call answered {}", fetched.status)),
459        Err(error) => Some(error.to_string()),
460    };
461    verdict(problem)
462}
463
464async fn check_negotiation(fetcher: &dyn Fetcher, contract: Option<&SiteContract>) -> CheckResult {
465    let Some(url) = manifest_url(contract) else {
466        return verdict(Some("no manifest URL".to_owned()));
467    };
468    let mut headers = HeaderMap::new();
469    headers.insert("AWP-Version", HeaderValue::from_static("9.0"));
470    let problem = match fetcher.get(&url, &headers).await {
471        Ok(fetched) if fetched.status == 406 => {
472            match serde_json::from_slice::<ErrorEnvelope>(&fetched.body) {
473                Ok(envelope) if envelope.error.code == ErrorCode::VersionNotSupported => {
474                    (fetched.header("awp-version").is_none())
475                        .then(|| "406 names no supported versions".to_owned())
476                }
477                _ => Some("406 is not a version_not_supported envelope".to_owned()),
478            }
479        }
480        Ok(fetched) => Some(format!("AWP-Version: 9.0 answered {}", fetched.status)),
481        Err(error) => Some(error.to_string()),
482    };
483    verdict(problem)
484}