Skip to main content

adk_website/deploy/
project.rs

1//! A served site's project on disk (spec 3.5 §7.8, §7.17): the layout `adk-rust site` uses,
2//! so the CLI and a running site share one content repository, log, host and journal.
3//!
4//! | Path | Holds |
5//! |---|---|
6//! | `site.toml`, `content/`, `theme/`, `public-terms.json`, `capabilities.json` | The content repository |
7//! | `well-known/`, `static/` | Files released under `/.well-known/` (the root-signed contract and `keys.json`) and at their own paths |
8//! | `feeds.json`, `calendar.json`, `payments.json` | The owner's feeds with their bounds, bookable slots, and payment links |
9//! | `caldav.json` | The owner's CalDAV calendar of open slots, in place of `calendar.json` ([`CalDavConfig`]) |
10//! | `approvals.json` | The owner's amount thresholds: orders, bookings and payments above them wait for the owner (spec 3.5 §7.4) |
11//! | `data/site-log.db`, `data/host/`, `data/history/`, `data/work/` | The site log, the `DirectoryHost`, every saved version, builds |
12//! | `data/keys/` | Delegated keys as private JWK files: `release.jwk` signs the log, `edge.jwk` the card and receipts, `web-bot-auth.jwk` crawls; `subject.key` keys consent sessions |
13//! | `data/kernel.db`, `data/edge.db` | The kernel's durable stores and the edge's |
14//! | `data/updates/` | The update engine's journal: `batches.jsonl` and `feeds.json`, read by `site batches` and `site feeds` |
15//! | `data/experiments/` | Experiment records |
16//!
17//! The root key never lives here: the owner keeps it and delegates the keys above with
18//! `adk-rust awp keys delegate` (A-I5).
19
20use std::collections::BTreeMap;
21use std::path::{Component, Path, PathBuf};
22
23use adk_core::{AdkError, Result};
24use adk_site::feed::FeedMapping;
25use adk_site::host::SiteHost;
26use adk_site::release::{PreviousRelease, manifest_digest, manifest_path};
27use awp_types::{FeedBounds, ReleaseManifest};
28use base64::Engine as _;
29use base64::engine::general_purpose::URL_SAFE_NO_PAD;
30use bytes::Bytes;
31use serde::{Deserialize, Serialize};
32use zeroize::Zeroizing;
33
34use crate::edge::handlers::Slot;
35
36fn io(path: &Path, error: impl std::fmt::Display) -> AdkError {
37    AdkError::config(format!("{}: {error}", path.display()))
38}
39
40/// The paths of a site project.
41///
42/// # Example
43///
44/// ```rust
45/// use adk_website::deploy::project::ProjectPaths;
46///
47/// let paths = ProjectPaths::new("/srv/bakery");
48/// assert!(paths.journal().ends_with("data/updates"));
49/// assert!(paths.key_file("release").ends_with("data/keys/release.jwk"));
50/// ```
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct ProjectPaths {
53    root: PathBuf,
54}
55
56impl ProjectPaths {
57    /// The project at `root`.
58    pub fn new(root: impl Into<PathBuf>) -> Self {
59        Self { root: root.into() }
60    }
61
62    /// The project's root: the content repository.
63    pub fn root(&self) -> &Path {
64        &self.root
65    }
66
67    /// `data/`.
68    pub fn data(&self) -> PathBuf {
69        self.root.join("data")
70    }
71
72    /// The private key file `data/keys/{name}.jwk`.
73    pub fn key_file(&self, name: &str) -> PathBuf {
74        self.data().join("keys").join(format!("{name}.jwk"))
75    }
76
77    /// The `DirectoryHost`'s directory.
78    pub fn host_dir(&self) -> PathBuf {
79        self.data().join("host")
80    }
81
82    /// Builds.
83    pub fn work(&self) -> PathBuf {
84        self.data().join("work")
85    }
86
87    /// Every saved version of every item.
88    pub fn history(&self) -> PathBuf {
89        self.data().join("history")
90    }
91
92    /// The update engine's journal.
93    pub fn journal(&self) -> PathBuf {
94        self.data().join("updates")
95    }
96
97    /// Experiment records.
98    pub fn experiments(&self) -> PathBuf {
99        self.data().join("experiments")
100    }
101
102    /// The SQLite database `data/{name}.db`.
103    pub fn database(&self, name: &str) -> String {
104        format!("sqlite://{}?mode=rwc", self.data().join(format!("{name}.db")).display())
105    }
106
107    /// The kernel database the site runs on (spec 3.5 §7.22, A-I22): the agency's
108    /// `data/kernel.db` when an `agency.toml` beside the project lists it, as
109    /// `serve_agency` serves it, else the project's own.
110    ///
111    /// # Example
112    ///
113    /// ```rust
114    /// use adk_website::deploy::ProjectPaths;
115    ///
116    /// let dir = tempfile::tempdir().unwrap();
117    /// std::fs::write(dir.path().join("agency.toml"), "[[site]]\ndomain = \"bakery.example\"\ndir = \"bakery\"\n").unwrap();
118    /// let site = ProjectPaths::new(dir.path().join("bakery"));
119    /// assert_eq!(site.kernel_database(), ProjectPaths::new(dir.path()).database("kernel"));
120    /// let alone = ProjectPaths::new(dir.path().join("notes"));
121    /// assert_eq!(alone.kernel_database(), alone.database("kernel"));
122    /// ```
123    pub fn kernel_database(&self) -> String {
124        let listed = self.root.parent().and_then(|agency| {
125            let text = std::fs::read_to_string(agency.join("agency.toml")).ok()?;
126            let file: super::serve::AgencyFile = toml::from_str(&text).ok()?;
127            let name = self.root.file_name()?;
128            file.sites
129                .iter()
130                .any(|site| site.dir.as_os_str() == name || agency.join(&site.dir) == self.root)
131                .then(|| ProjectPaths::new(agency))
132        });
133        listed.map_or_else(|| self.database("kernel"), |agency| agency.database("kernel"))
134    }
135
136    /// Files released under `/.well-known/`.
137    pub fn well_known(&self) -> PathBuf {
138        self.root.join("well-known")
139    }
140
141    /// Files released at their own paths.
142    pub fn static_dir(&self) -> PathBuf {
143        self.root.join("static")
144    }
145}
146
147/// An Ed25519 key from a private JWK file `{"kty":"OKP","crv":"Ed25519","kid","x","d"}`,
148/// the format `adk-rust awp keys` writes.
149pub struct KeyFile {
150    /// The key id.
151    pub kid: String,
152    seed: Zeroizing<[u8; 32]>,
153}
154
155impl std::fmt::Debug for KeyFile {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        f.debug_struct("KeyFile").field("kid", &self.kid).finish_non_exhaustive()
158    }
159}
160
161impl KeyFile {
162    /// The key at `path`, made with `kid` on first use, readable by its owner only.
163    ///
164    /// # Errors
165    ///
166    /// A file that is not an Ed25519 private JWK, or the file system's error.
167    pub fn load_or_create(path: &Path, kid: &str) -> Result<Self> {
168        if path.exists() {
169            return Self::read(path);
170        }
171        let mut seed = Zeroizing::new([0u8; 32]);
172        getrandom::fill(seed.as_mut()).map_err(|e| io(path, e))?;
173        let key = Self { kid: kid.to_string(), seed };
174        key.write_new(path)?;
175        Ok(key)
176    }
177
178    /// Reads the key at `path`.
179    ///
180    /// # Errors
181    ///
182    /// A file that is not an Ed25519 private JWK carrying `kid` and `d`.
183    pub fn read(path: &Path) -> Result<Self> {
184        #[derive(Deserialize)]
185        struct Jwk {
186            kty: String,
187            crv: String,
188            kid: Option<String>,
189            d: Option<String>,
190        }
191        let text = Zeroizing::new(std::fs::read_to_string(path).map_err(|e| io(path, e))?);
192        let jwk: Jwk = serde_json::from_str(&text)
193            .map_err(|_| io(path, "not a JSON Web Key; a key file is an Ed25519 private JWK"))?;
194        if jwk.kty != "OKP" || jwk.crv != "Ed25519" {
195            return Err(io(path, "not an Ed25519 key (kty OKP, crv Ed25519)"));
196        }
197        let d = Zeroizing::new(jwk.d.unwrap_or_default());
198        let bytes = Zeroizing::new(
199            URL_SAFE_NO_PAD.decode(d.as_bytes()).map_err(|_| io(path, "`d` is not base64url"))?,
200        );
201        let seed: [u8; 32] = bytes
202            .as_slice()
203            .try_into()
204            .map_err(|_| io(path, "`d` is not a 32-byte Ed25519 seed"))?;
205        let kid = jwk.kid.filter(|kid| !kid.is_empty()).ok_or_else(|| io(path, "no `kid`"))?;
206        Ok(Self { kid, seed: Zeroizing::new(seed) })
207    }
208
209    /// The key's seed.
210    pub fn seed(&self) -> [u8; 32] {
211        *self.seed
212    }
213
214    fn write_new(&self, path: &Path) -> Result<()> {
215        use std::io::Write as _;
216        let key = adk_auth::web_bot_auth::Ed25519SigningKey::from_seed(*self.seed)
217            .map_err(|e| io(path, e))?;
218        let text = Zeroizing::new(format!(
219            "{{\"kty\":\"OKP\",\"crv\":\"Ed25519\",\"kid\":{},\"x\":\"{}\",\"d\":\"{}\"}}\n",
220            serde_json::Value::String(self.kid.clone()),
221            URL_SAFE_NO_PAD.encode(key.public_key()),
222            Zeroizing::new(URL_SAFE_NO_PAD.encode(self.seed.as_ref())).as_str()
223        ));
224        if let Some(parent) = path.parent() {
225            std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
226        }
227        let mut options = std::fs::OpenOptions::new();
228        options.write(true).create_new(true);
229        #[cfg(unix)]
230        std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
231        let mut file = options.open(path).map_err(|e| io(path, e))?;
232        file.write_all(text.as_bytes()).map_err(|e| io(path, e))
233    }
234}
235
236/// The files released beside the generated ones (spec 3.5 §7.2): `well-known/` under
237/// `/.well-known/` (the public terms excepted, which the generator writes) and `static/` at
238/// their own paths.
239///
240/// # Errors
241///
242/// An unreadable file.
243pub fn documents(paths: &ProjectPaths) -> Result<BTreeMap<String, Bytes>> {
244    let mut documents = BTreeMap::new();
245    collect(&paths.well_known(), ".well-known", &mut documents)?;
246    collect(&paths.static_dir(), "", &mut documents)?;
247    documents.remove(awp_types::v2::contract::CHARTER_PATH.trim_start_matches('/'));
248    Ok(documents)
249}
250
251fn collect(dir: &Path, prefix: &str, documents: &mut BTreeMap<String, Bytes>) -> Result<()> {
252    if !dir.is_dir() {
253        return Ok(());
254    }
255    let mut stack = vec![dir.to_path_buf()];
256    while let Some(current) = stack.pop() {
257        for entry in std::fs::read_dir(&current).map_err(|e| io(&current, e))? {
258            let path = entry.map_err(|e| io(&current, e))?.path();
259            if path.is_dir() {
260                stack.push(path);
261                continue;
262            }
263            let relative = path.strip_prefix(dir).unwrap_or(&path);
264            if !relative.components().all(|c| matches!(c, Component::Normal(_))) {
265                continue;
266            }
267            let relative = relative.to_string_lossy().replace('\\', "/");
268            let key = if prefix.is_empty() { relative } else { format!("{prefix}/{relative}") };
269            let bytes = std::fs::read(&path).map_err(|e| io(&path, e))?;
270            documents.insert(key, Bytes::from(bytes));
271        }
272    }
273    Ok(())
274}
275
276/// The release `host` serves for a log of `size` entries, so a restarted site continues
277/// after it.
278///
279/// # Errors
280///
281/// A logged release whose manifest the host does not serve.
282pub async fn previous_release(host: &dyn SiteHost, size: u64) -> Result<Option<PreviousRelease>> {
283    if size == 0 {
284        return Ok(None);
285    }
286    let fetch = |seq: u64| async move {
287        let bytes = host
288            .fetch(&manifest_path(seq))
289            .await
290            .map_err(|e| AdkError::config(e.to_string()))?
291            .ok_or_else(|| {
292                AdkError::config(format!(
293                    "the site log holds release {seq} but the host does not serve its manifest"
294                ))
295            })?;
296        serde_json::from_slice::<ReleaseManifest>(&bytes)
297            .map_err(|e| AdkError::config(format!("release {seq}'s manifest: {e}")))
298    };
299    let latest = fetch(size).await?;
300    let mut chain = vec![latest.clone()];
301    while let Some(base) = chain.last().and_then(|manifest| manifest.base) {
302        if chain.len() > 10_000 {
303            return Err(AdkError::config("the delta chain does not end in a snapshot"));
304        }
305        chain.push(fetch(base).await?);
306    }
307    let mut files = BTreeMap::new();
308    for manifest in chain.iter().rev() {
309        files = manifest.apply_to(&files);
310    }
311    let snapshot = chain.last().map_or((latest.seq, latest.created_at), |m| (m.seq, m.created_at));
312    let (digest, _) = manifest_digest(&latest).map_err(|e| AdkError::config(e.to_string()))?;
313    Ok(Some(PreviousRelease { manifest: latest, digest, files, last_snapshot: snapshot }))
314}
315
316pub(crate) fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<Option<T>> {
317    match std::fs::read(path) {
318        Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| io(path, e)),
319        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
320        Err(error) => Err(io(path, error)),
321    }
322}
323
324/// One feed the owner configured in `feeds.json` (A-I24, A-I27).
325#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
326pub struct ConfiguredFeed {
327    /// The mapping.
328    pub mapping: FeedMapping,
329    /// Its bounds.
330    pub bounds: FeedBounds,
331}
332
333/// The feeds in `feeds.json`; none without the file.
334///
335/// # Errors
336///
337/// A file that is not a list of `{mapping, bounds}`.
338pub fn feeds(paths: &ProjectPaths) -> Result<Vec<ConfiguredFeed>> {
339    Ok(read_json(&paths.root().join("feeds.json"))?.unwrap_or_default())
340}
341
342/// The bookable slots in `calendar.json`; `None` without the file.
343///
344/// # Errors
345///
346/// A file that is not a list of slots.
347pub fn slots(paths: &ProjectPaths) -> Result<Option<Vec<Slot>>> {
348    read_json(&paths.root().join("calendar.json"))
349}
350
351/// The owner's CalDAV calendar in `caldav.json` (spec 3.5 §7.5 "Commerce"): where the open
352/// slots are, where bookings go, and how to sign in. Secrets are references, `env:VAR` or
353/// `file:PATH` (relative to the project), never the secret itself (A-I19).
354///
355/// ```json
356/// {
357///   "slots": "https://dav.example.com/calendars/juniper/open-slots/",
358///   "bookings": "https://dav.example.com/calendars/juniper/personal/",
359///   "username": "juniper",
360///   "password": "env:JUNIPER_CALDAV_PASSWORD",
361///   "price": 1500,
362///   "timeZone": "Africa/Nairobi"
363/// }
364/// ```
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366#[serde(rename_all = "camelCase", deny_unknown_fields)]
367pub struct CalDavConfig {
368    /// The collection of open slots.
369    pub slots: String,
370    /// The collection bookings are written to; the slots' collection when not set.
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    pub bookings: Option<String>,
373    /// The account, for HTTP Basic with `password`.
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub username: Option<String>,
376    /// The app password, as `env:VAR` or `file:PATH`.
377    #[serde(default, skip_serializing_if = "Option::is_none")]
378    pub password: Option<String>,
379    /// An OAuth bearer token in place of a password, as `env:VAR` or `file:PATH`.
380    #[serde(default, skip_serializing_if = "Option::is_none")]
381    pub token: Option<String>,
382    /// The price of a slot with none of its own, in minor units of the site's currency.
383    #[serde(default, skip_serializing_if = "Option::is_none")]
384    pub price: Option<u64>,
385    /// The IANA zone times without one are read in; UTC when not set.
386    #[serde(default, skip_serializing_if = "Option::is_none")]
387    pub time_zone: Option<String>,
388}
389
390/// A secret from `env:VAR` or `file:PATH`, a relative path read from the project root;
391/// `file` names the configuration file for the error.
392pub(crate) fn secret_in(
393    paths: &ProjectPaths,
394    file: &str,
395    source: &str,
396) -> Result<adk_core::CredentialSecret> {
397    let text = if let Some(var) = source.strip_prefix("env:") {
398        std::env::var(var)
399            .map_err(|_| AdkError::config(format!("{file}: the environment holds no `{var}`")))?
400    } else if let Some(path) = source.strip_prefix("file:") {
401        let path = paths.root().join(path);
402        std::fs::read_to_string(&path).map_err(|e| io(&path, e))?
403    } else {
404        return Err(AdkError::config(format!(
405            "{file}: write each secret as `env:VAR` or `file:PATH`, never in the file itself"
406        )));
407    };
408    Ok(adk_core::CredentialSecret::new(text.trim()))
409}
410
411fn secret_reference(paths: &ProjectPaths, source: &str) -> Result<adk_core::CredentialSecret> {
412    secret_in(paths, "caldav.json", source)
413}
414
415/// The owner's CalDAV calendar from `caldav.json`; `None` without the file.
416///
417/// # Errors
418///
419/// A file that is not a [`CalDavConfig`], a secret written in it or not found, an unknown
420/// time zone, or an address that is not `https` (`http` on loopback only).
421pub fn caldav(paths: &ProjectPaths) -> Result<Option<crate::edge::caldav::CalDavCalendar>> {
422    use crate::edge::caldav::{CalDavAuth, CalDavCalendar};
423
424    let Some(config) = read_json::<CalDavConfig>(&paths.root().join("caldav.json"))? else {
425        return Ok(None);
426    };
427    let auth = match (&config.username, &config.password, &config.token) {
428        (Some(username), Some(password), None) => CalDavAuth::Basic {
429            username: username.clone(),
430            password: secret_reference(paths, password)?,
431        },
432        (None, None, Some(token)) => CalDavAuth::Bearer(secret_reference(paths, token)?),
433        (None, None, None) => CalDavAuth::None,
434        _ => {
435            return Err(AdkError::config(
436                "caldav.json: sign in with `username` and `password`, or with `token`",
437            ));
438        }
439    };
440    let mut calendar = CalDavCalendar::new(&config.slots, auth)?;
441    if let Some(bookings) = &config.bookings {
442        calendar = calendar.with_bookings(bookings)?;
443    }
444    if let Some(price) = config.price {
445        calendar = calendar.with_price(price);
446    }
447    if let Some(zone) = &config.time_zone {
448        let zone = zone.parse::<chrono_tz::Tz>().map_err(|_| {
449            AdkError::config(format!("caldav.json: `{zone}` is not an IANA time zone"))
450        })?;
451        calendar = calendar.with_time_zone(zone);
452    }
453    Ok(Some(calendar))
454}
455
456/// One way to pay the owner, from `payments.json`: a rail's name, what the buyer is told,
457/// and the owner's own payment page.
458#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
459#[serde(rename_all = "camelCase")]
460pub struct PaymentLink {
461    /// The rail, as `pay_order`'s `rail` names it, such as `mpesa` or `card`.
462    pub rail: String,
463    /// What the buyer is told, such as "Pay till 123456 with the order id as reference".
464    pub instructions: String,
465    /// The owner's payment page, when the rail has one.
466    #[serde(default, skip_serializing_if = "Option::is_none")]
467    pub url: Option<String>,
468}
469
470/// The payment links in `payments.json`; `None` without the file.
471///
472/// # Errors
473///
474/// A file that is not a list of payment links.
475pub fn payment_links(paths: &ProjectPaths) -> Result<Option<Vec<PaymentLink>>> {
476    read_json(&paths.root().join("payments.json"))
477}
478
479/// The owner's amount thresholds in `approvals.json`, such as
480/// `{"place_order": 20000, "book": 15000}` in minor units of the site's currency: calls above
481/// them answer `202` and wait for the owner (spec 3.5 §7.4, S9). None without the file.
482///
483/// # Errors
484///
485/// A file that is not a map of capability names to amounts, or a threshold on a capability
486/// whose calls carry no amount.
487pub fn approval_thresholds(paths: &ProjectPaths) -> Result<crate::packs::ApprovalThresholds> {
488    let thresholds: crate::packs::ApprovalThresholds =
489        read_json(&paths.root().join("approvals.json"))?.unwrap_or_default();
490    thresholds.validate()?;
491    Ok(thresholds)
492}