Skip to main content

adk_website/
contract.rs

1//! The site's signed AWP documents (spec 3.5 §7.2, §7.3, §7.7, D-11, A-I5): the contract at
2//! `/.well-known/awp.json`, the key set with the root's delegations, and the public charter
3//! terms, built with `adk-awp`'s `StaticBundle` and released with every release so `awp
4//! verify` can walk the chain from the DNS-anchored root to every served page.
5//!
6//! | Key | Scope | Signs |
7//! |---|---|---|
8//! | Root | — | The contract and the delegations; outside every agent (A-I5) |
9//! | Release | `release` | The site log's checkpoints (`adk-site`'s release signer, same seed) |
10//! | Edge | `card`, `receipt` | The A2A Agent Card, the status, consent receipts and stream entries |
11//!
12//! Signing is the owner's step at a terminal, as `adk-rust awp keys rotate` and `delegate`
13//! do it: a served site never holds the root and never signs its own contract or
14//! delegations; it publishes the `well-known/` files the owner wrote (D-11, A-I5).
15
16use std::collections::BTreeMap;
17use std::sync::Arc;
18
19use adk_awp::signing::anchor::{root_record, root_record_name};
20use adk_awp::signing::bundle::StaticBundle;
21use adk_awp::signing::jws::{DocumentSigner, Ed25519DocumentSigner};
22use adk_awp::signing::keys::delegate;
23use adk_core::{AdkError, Result};
24use adk_site::content::SiteProject;
25use awp_types::v2::contract::{CHARTER_PATH, CHECKPOINT_PATH, release_manifest_path};
26use awp_types::{
27    ContactLinks, ContractRelease, ContractStatus, IdentityMethod, IdentityPolicy, KeyScope,
28    KeySet, LanguageTag, Profile, PublicTerms, RootKey, SiteContract, SiteState, SurfaceLinks,
29};
30use chrono::{DateTime, Duration, Utc};
31
32fn signing(error: impl std::fmt::Display) -> AdkError {
33    AdkError::config(format!("signing the site's documents failed: {error}"))
34}
35
36/// The site's keys (spec 3.5 D-11): the root that signs the contract and delegations, the
37/// release key the site log's checkpoints are signed with, and the edge's key.
38#[derive(Clone)]
39pub struct SiteKeys {
40    /// The root key; it never enters an agent's context (A-I5).
41    pub root: Arc<Ed25519DocumentSigner>,
42    /// The release key, as `adk-awp` sees it; `adk-site`'s release signer holds the same seed.
43    pub release: Arc<Ed25519DocumentSigner>,
44    /// The edge's key, delegated `card` and `receipt`.
45    pub edge: Arc<Ed25519DocumentSigner>,
46}
47
48impl std::fmt::Debug for SiteKeys {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        f.debug_struct("SiteKeys")
51            .field("root", &self.root.kid())
52            .field("release", &self.release.kid())
53            .field("edge", &self.edge.kid())
54            .finish()
55    }
56}
57
58impl SiteKeys {
59    /// Keys from seeds; the release seed is the one `adk-site`'s `Ed25519ReleaseSigner`
60    /// signs the site log with.
61    ///
62    /// # Errors
63    ///
64    /// A seed that does not make a key.
65    pub fn from_seeds(
66        domain: &str,
67        root: [u8; 32],
68        release: [u8; 32],
69        edge: [u8; 32],
70    ) -> Result<Self> {
71        Ok(Self {
72            root: Arc::new(
73                Ed25519DocumentSigner::from_seed(format!("{domain}-root"), root)
74                    .map_err(signing)?,
75            ),
76            release: Arc::new(
77                Ed25519DocumentSigner::from_seed(format!("{domain}-release"), release)
78                    .map_err(signing)?,
79            ),
80            edge: Arc::new(
81                Ed25519DocumentSigner::from_seed(format!("{domain}-edge"), edge)
82                    .map_err(signing)?,
83            ),
84        })
85    }
86
87    /// The `_awp-root.{domain}` TXT record that anchors the root (spec 3.5 §7.7): its name
88    /// and value.
89    pub fn root_record(&self, domain: &str) -> (String, String) {
90        (root_record_name(domain), root_record(self.root.kid(), &self.root.public_key()))
91    }
92
93    /// The key set: the root and its delegations, valid from `from` for `days` (spec 3.5
94    /// §7.3).
95    ///
96    /// # Errors
97    ///
98    /// The root's signing error.
99    pub async fn key_set(&self, from: DateTime<Utc>, days: i64) -> Result<KeySet> {
100        let until = from + Duration::days(days);
101        let release = delegate(
102            self.root.as_ref(),
103            self.release.kid(),
104            self.release.public_key(),
105            vec![KeyScope::Release],
106            from,
107            until,
108        )
109        .await
110        .map_err(signing)?;
111        let edge = delegate(
112            self.root.as_ref(),
113            self.edge.kid(),
114            self.edge.public_key(),
115            vec![KeyScope::Card, KeyScope::Receipt],
116            from,
117            until,
118        )
119        .await
120        .map_err(signing)?;
121        Ok(KeySet {
122            root: RootKey {
123                kid: self.root.kid().to_string(),
124                public_key: self.root.public_key(),
125                endorsement: None,
126            },
127            delegations: vec![release, edge],
128            retired_roots: vec![],
129            revocations: vec![],
130        })
131    }
132}
133
134/// What the contract says about the site.
135#[derive(Debug, Clone, PartialEq)]
136pub struct ContractInputs {
137    /// The site's id.
138    pub id: uuid::Uuid,
139    /// Its name.
140    pub name: String,
141    /// Its domain.
142    pub domain: String,
143    /// Its languages.
144    pub languages: Vec<LanguageTag>,
145    /// The edge's origin, such as `https://agent.example.com`; `None` for a static site.
146    pub edge: Option<String>,
147    /// The release the contract ships in.
148    pub release_seq: u64,
149    /// The charter's public terms.
150    pub terms: PublicTerms,
151}
152
153/// The signed documents of a release, by path (spec 3.5 §7.2): the contract, the key set and
154/// the public charter terms. [`add_to_project`] puts them in the project every release is
155/// built from.
156///
157/// # Errors
158///
159/// The root's signing error.
160pub async fn site_documents(
161    keys: &SiteKeys,
162    inputs: &ContractInputs,
163    valid_from: DateTime<Utc>,
164) -> Result<(BTreeMap<String, Vec<u8>>, SiteContract)> {
165    let origin = format!("https://{}", inputs.domain);
166    let key_set = keys.key_set(valid_from, 90).await?;
167    let mut contract = SiteContract::new(awp_types::SiteRef {
168        id: inputs.id,
169        name: inputs.name.clone(),
170        domain: inputs.domain.clone(),
171        languages: inputs.languages.clone(),
172    });
173    contract.profile =
174        Some(if inputs.edge.is_some() { Profile::StaticEdge } else { Profile::Static });
175    contract.surfaces = Some(SurfaceLinks {
176        a2a_card: inputs.edge.as_ref().map(|edge| format!("{edge}/.well-known/agent-card.json")),
177        mcp_server_card: inputs
178            .edge
179            .as_ref()
180            .map(|edge| format!("{edge}/.well-known/mcp/server-card.json")),
181        manifest: inputs.edge.as_ref().map(|edge| format!("{edge}/awp/v2/manifest")),
182        llms_txt: Some(format!("{origin}/llms.txt")),
183        machine_views: true,
184    });
185    if let Some(edge) = &inputs.edge {
186        contract.identity = Some(IdentityPolicy {
187            accepts: vec![IdentityMethod::WebBotAuth],
188            trust_rules: Some(format!("{edge}/awp/v2/trust")),
189        });
190        contract.status = Some(ContractStatus {
191            url: format!("{edge}/awp/v2/status"),
192            last_known: Some(SiteState::Operational),
193        });
194    }
195    contract.release = Some(ContractRelease {
196        seq: inputs.release_seq,
197        manifest: format!("{origin}{}", release_manifest_path(inputs.release_seq)),
198        checkpoint: format!("{origin}{CHECKPOINT_PATH}"),
199    });
200    contract.contact = Some(ContactLinks {
201        security: Some(format!("{origin}/.well-known/security.txt")),
202        ..inputs.terms.contact.clone()
203    });
204    let bundle = StaticBundle::build(contract, &key_set, &inputs.terms, keys.root.as_ref())
205        .await
206        .map_err(signing)?;
207    Ok((bundle.files().clone(), bundle.contract().clone()))
208}
209
210/// Puts the signed `documents` into `project` (spec 3.5 §7.2, AWP 2.0 §14.2): the contract and
211/// the key set as release documents, and `terms` as the project's public terms, which the
212/// generator renders at the charter path whose digest the contract carries.
213///
214/// # Example
215///
216/// ```rust
217/// use adk_site::content::{SiteConfig, SiteProject};
218/// use adk_website::contract::{ContractInputs, SiteKeys, add_to_project, site_documents};
219/// use awp_types::PublicTerms;
220///
221/// # #[tokio::main(flavor = "current_thread")]
222/// # async fn main() {
223/// let keys = SiteKeys::from_seeds("notes.example", [1; 32], [2; 32], [3; 32]).unwrap();
224/// let inputs = ContractInputs {
225///     id: uuid::Uuid::nil(),
226///     name: "Notes".into(),
227///     domain: "notes.example".into(),
228///     languages: vec!["en".parse().unwrap()],
229///     edge: None,
230///     release_seq: 1,
231///     terms: PublicTerms::default(),
232/// };
233/// let (documents, contract) = site_documents(&keys, &inputs, chrono::Utc::now()).await.unwrap();
234/// assert!(contract.proof.is_some(), "the root signs the contract");
235/// let config = SiteConfig::new("Notes", "notes.example", vec!["en".parse().unwrap()]);
236/// let mut project = SiteProject::new(config, Vec::new(), chrono::Utc::now());
237/// add_to_project(&mut project, documents, inputs.terms);
238/// assert!(project.documents.contains_key(".well-known/awp.json"));
239/// assert!(project.public_terms.is_some());
240/// # }
241/// ```
242pub fn add_to_project(
243    project: &mut SiteProject,
244    documents: BTreeMap<String, Vec<u8>>,
245    terms: PublicTerms,
246) {
247    for (path, bytes) in documents {
248        if path != CHARTER_PATH {
249            project.documents.insert(path.trim_start_matches('/').to_string(), bytes.into());
250        }
251    }
252    project.public_terms = Some(terms);
253}