Skip to main content

adk_website/deploy/
checks.rs

1//! What a served site adds around the runtime (spec 3.5 §7.2, §7.5, D-11, A-I5): the gate
2//! check that refuses to publish until the owner has delegated the release key, payments
3//! through the owner's own payment links, and audit records in the logs.
4//!
5//! | Part | Does |
6//! |---|---|
7//! | [`ReleaseDelegation`] | Fails every build whose `/.well-known/awp/keys.json` does not delegate the release key the site log signs with; the finding names `adk-rust awp keys rotate` and `adk-rust awp keys delegate` |
8//! | [`preview_verification`] | The full tier runs `awp verify` against the preview of the next release (spec 3.5 §7.8.1), over the host's site log, with the edge's documents read from the served router |
9//! | [`PaymentLinks`] | `pay_order`, `donate`, `subscribe` and `buy_ticket` answer with the owner's payment instructions from `payments.json`; the money never passes through the site |
10//! | [`LogRecorder`] | Writes audit records to the logs, for the edge's meter |
11//! | [`metered_trail`] | The edge's meter over a durable recorder, such as the served site's `data/audit.jsonl` |
12
13use std::sync::Arc;
14
15use adk_awp::v2::capability::{CapabilityCall, CapabilityError};
16use adk_core::audit_log::{AuditRecordDraft, AuditRecorder};
17use async_trait::async_trait;
18use awp_types::ErrorCode;
19use serde_json::{Value, json};
20
21use super::project::PaymentLink;
22use crate::edge::handlers::PaymentDesk;
23
24/// Refuses to publish until the owner's root has delegated the release key (spec 3.5 §7.2,
25/// D-11, A-I5); it lives in `adk-site`'s gate and reports as `GateCheck::Signing`.
26pub use adk_site::gate::ReleaseDelegation;
27
28/// `awp verify` against the preview, for a served site's launch gate (spec 3.5 §7.8.1
29/// "Machine views"): the full tier stages the build as the release after the ones `host`
30/// logs and verifies it as an agent would once it is live, reporting as
31/// `GateCheck::AwpVerify`. What the release does not hold, such as the Agent Card the edge
32/// serves, is read from `edge`. The DNS root anchor is checked against the `_awp-root`
33/// record the project's key set names — the record the owner publishes when the domain
34/// points at the site; the Guardian's probes and `adk-rust awp verify` read the published
35/// one.
36///
37/// # Example
38///
39/// ```rust,no_run
40/// use std::sync::Arc;
41///
42/// use adk_site::gate::LaunchGate;
43/// use adk_website::deploy::checks::preview_verification;
44/// use adk_website::edge::adapters::DeferredFetcher;
45///
46/// # fn demo(project: &adk_site::content::SiteProject, host: Arc<dyn adk_site::host::SiteHost>) {
47/// let edge = Arc::new(DeferredFetcher::default());
48/// let gate = LaunchGate::new().with_extension(Arc::new(preview_verification(project, host, edge)));
49/// # let _ = gate;
50/// # }
51/// ```
52pub fn preview_verification(
53    project: &adk_site::content::SiteProject,
54    host: Arc<dyn adk_site::host::SiteHost>,
55    edge: Arc<crate::edge::adapters::DeferredFetcher>,
56) -> adk_site::gate::PreviewVerification {
57    use adk_awp::signing::anchor::{FixedTxtResolver, root_record, root_record_name};
58
59    let domain = project.config.domain.clone();
60    let keys = project
61        .documents
62        .get(".well-known/awp/keys.json")
63        .and_then(|bytes| serde_json::from_slice::<awp_types::KeySet>(bytes).ok());
64    let resolver = match keys {
65        Some(keys) => FixedTxtResolver::default()
66            .with(&root_record_name(&domain), &root_record(&keys.root.kid, &keys.root.public_key)),
67        None => FixedTxtResolver::default(),
68    };
69    adk_site::gate::PreviewVerification::new(domain, host, Arc::new(resolver)).with_fetcher(edge)
70}
71
72/// Payments through the owner's own payment links (spec 3.5 §7.5 "Commerce", §7.14): the
73/// buyer is told how to pay with the order as the reference; nothing is charged here.
74pub struct PaymentLinks {
75    links: Vec<PaymentLink>,
76}
77
78impl PaymentLinks {
79    /// The desk over `links`, from `payments.json`.
80    pub fn new(links: Vec<PaymentLink>) -> Self {
81        Self { links }
82    }
83}
84
85#[async_trait]
86impl PaymentDesk for PaymentLinks {
87    async fn take(&self, call: &CapabilityCall) -> Result<Value, CapabilityError> {
88        let wanted = call.input["rail"].as_str();
89        let link = match wanted {
90            Some(rail) => self.links.iter().find(|link| link.rail == rail),
91            None => self.links.first(),
92        }
93        .ok_or_else(|| CapabilityError::Refused {
94            code: ErrorCode::PaymentPolicyRejected,
95            message: format!(
96                "the site does not take payment by {}; it accepts {}",
97                wanted.unwrap_or("that rail"),
98                self.links.iter().map(|link| link.rail.as_str()).collect::<Vec<_>>().join(", ")
99            ),
100        })?;
101        let reference = call.input["orderId"].as_str().map_or_else(
102            || format!("{}-{}", call.capability, call.idempotency_key),
103            str::to_string,
104        );
105        Ok(json!({
106            "status": "awaiting_payment",
107            "reference": reference,
108            "rail": link.rail,
109            "instructions": link.instructions,
110            "url": link.url,
111        }))
112    }
113}
114
115/// Writes audit records to the logs.
116#[derive(Debug, Default, Clone)]
117pub struct LogRecorder;
118
119#[async_trait]
120impl AuditRecorder for LogRecorder {
121    fn digest(&self, value: &Value) -> String {
122        adk_core::json_digest(value)
123    }
124
125    async fn record(&self, draft: AuditRecordDraft) -> adk_core::Result<()> {
126        tracing::info!(audit.action = %draft.action, "audit record");
127        Ok(())
128    }
129}
130
131/// The edge's meter over `recorder`, counting into `counts`: a served site's edge keeps its
132/// records in `data/audit.jsonl` through `adk_core::audit_log::FileAuditRecorder` (spec 3.5
133/// §7.9, §9.3).
134///
135/// # Example
136///
137/// ```rust,ignore
138/// let recorder = Arc::new(FileAuditRecorder::open("data/audit.jsonl")?);
139/// let trail = metered_trail(recorder, counts);
140/// ```
141pub fn metered_trail(
142    recorder: Arc<dyn AuditRecorder>,
143    counts: Arc<dyn adk_server::awp::BeaconStore>,
144) -> adk_core::audit_log::AuditTrail {
145    adk_core::audit_log::AuditTrail::new(Arc::new(crate::measurement::EdgeMeter::new(
146        recorder, counts,
147    )))
148}
149
150/// The edge's meter over [`LogRecorder`], counting into `counts`.
151pub fn metered_audit(
152    counts: Arc<dyn adk_server::awp::BeaconStore>,
153) -> adk_core::audit_log::AuditTrail {
154    adk_core::audit_log::AuditTrail::new(Arc::new(crate::measurement::EdgeMeter::new(
155        Arc::new(LogRecorder),
156        counts,
157    )))
158}