Skip to main content

adk_site/
release.rs

1//! Releases: the build output hashed into a manifest, refused when it holds server code,
2//! appended to the site log (spec 3.5 §7.7, §7.8.2 step 5, §7.8.3 "Releases at scale",
3//! A-I1, A-I4; AWP 2.0 §14.1–§14.4).
4//!
5//! [`ReleaseBuilder::stage`] hashes every file of a build into an awp-types
6//! [`ReleaseManifest`] (a snapshot, or a delta against the previous release) and refuses the
7//! whole release when any file is server code. [`ReleaseBuilder::release`] then appends the
8//! manifest digest to the [`SiteLog`] and attaches the tiles and checkpoint a host publishes
9//! last. A preview release is staged and never logged.
10
11use std::collections::{BTreeMap, BTreeSet};
12use std::path::{Path, PathBuf};
13use std::sync::Arc;
14
15use adk_auth::signed_audit::canonicalize;
16use adk_core::{Clock, SystemClock};
17use awp_types::{
18    Digest, FileEntry, GeneratorRef, LogEntry, Redirect, ReleaseManifest, ReleaseSource,
19};
20use bytes::Bytes;
21use chrono::{DateTime, Utc};
22use sha2::{Digest as _, Sha256};
23
24use crate::error::{Result, SiteError};
25use crate::log::{LOG_PREFIX, LogPublication, SiteLog};
26use crate::scan::scan_file;
27
28/// Where release manifests are published, relative to the site root.
29pub const RELEASES_PREFIX: &str = ".well-known/awp/releases";
30
31/// The manifest path of release `seq`, relative to the site root.
32pub fn manifest_path(seq: u64) -> String {
33    format!("{RELEASES_PREFIX}/{seq}.json")
34}
35
36/// Whether a path (with or without a leading `/`) is under the releases or log prefix,
37/// which the log authenticates and no manifest lists (AWP 2.0 §14.2).
38pub fn is_log_path(path: &str) -> bool {
39    let path = path.trim_start_matches('/');
40    path.starts_with(&format!("{RELEASES_PREFIX}/")) || path.starts_with(&format!("{LOG_PREFIX}/"))
41}
42
43/// The media type a file is published with, from its name.
44pub fn content_type(path: &str) -> &'static str {
45    let name = path.rsplit('/').next().unwrap_or(path);
46    if name.ends_with(".awp.json") || path.trim_start_matches('/') == ".well-known/awp.json" {
47        return "application/awp+json";
48    }
49    if name == "_redirects" || name == "security.txt" {
50        return "text/plain; charset=utf-8";
51    }
52    match name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).as_deref() {
53        Some("html" | "htm") => "text/html; charset=utf-8",
54        Some("md") => "text/markdown; charset=utf-8",
55        Some("txt") => "text/plain; charset=utf-8",
56        Some("css") => "text/css; charset=utf-8",
57        Some("js" | "mjs") => "text/javascript; charset=utf-8",
58        Some("json") => "application/json",
59        Some("xml") if name == "feed.xml" => "application/atom+xml",
60        Some("xml") => "application/xml",
61        Some("svg") => "image/svg+xml",
62        Some("png") => "image/png",
63        Some("jpg" | "jpeg") => "image/jpeg",
64        Some("gif") => "image/gif",
65        Some("webp") => "image/webp",
66        Some("avif") => "image/avif",
67        Some("ico") => "image/x-icon",
68        Some("pdf") => "application/pdf",
69        Some("mp4") => "video/mp4",
70        Some("webm") => "video/webm",
71        Some("mp3") => "audio/mpeg",
72        Some("ogg") => "audio/ogg",
73        Some("woff2") => "font/woff2",
74        Some("woff") => "font/woff",
75        _ => "application/octet-stream",
76    }
77}
78
79/// The digest of a manifest: SHA-256 of its JCS form (AWP 2.0 §14.1).
80///
81/// # Errors
82///
83/// [`SiteError::Serde`] when the manifest holds a number JCS cannot carry.
84pub fn manifest_digest(manifest: &ReleaseManifest) -> Result<(Digest, Bytes)> {
85    let value =
86        serde_json::to_value(manifest).map_err(|e| SiteError::serde("release manifest", e))?;
87    let canonical = canonicalize(&value).map_err(|e| SiteError::serde("release manifest", e))?;
88    let digest = Digest::from_sha256_bytes(Sha256::digest(canonical.as_bytes()).into());
89    Ok((digest, Bytes::from(canonical.into_bytes())))
90}
91
92/// A file's digest.
93pub fn file_digest(bytes: &[u8]) -> Digest {
94    Digest::from_sha256_bytes(Sha256::digest(bytes).into())
95}
96
97/// The release a new one follows.
98#[derive(Debug, Clone)]
99pub struct PreviousRelease {
100    /// Its manifest.
101    pub manifest: ReleaseManifest,
102    /// Its manifest digest.
103    pub digest: Digest,
104    /// Its full file set (resolved through its delta chain).
105    pub files: BTreeMap<String, FileEntry>,
106    /// The latest snapshot at or before it: its number and build time.
107    pub last_snapshot: (u64, DateTime<Utc>),
108}
109
110impl PreviousRelease {
111    /// The previous release from a staged one.
112    pub fn from_staged(staged: &StagedRelease) -> Self {
113        let last_snapshot = match &staged.previous_snapshot {
114            Some(snapshot) if !staged.manifest.is_snapshot() => *snapshot,
115            _ => (staged.manifest.seq, staged.manifest.created_at),
116        };
117        Self {
118            manifest: staged.manifest.clone(),
119            digest: staged.digest.clone(),
120            files: staged.files.clone(),
121            last_snapshot,
122        }
123    }
124}
125
126/// What a release is made of besides its files.
127#[derive(Debug, Clone)]
128pub struct ReleaseOptions {
129    /// What produced it.
130    pub source: ReleaseSource,
131    /// The generator that built it.
132    pub generator: GeneratorRef,
133    /// The charter version in effect.
134    pub charter_version: u32,
135    /// Every redirect.
136    pub redirects: Vec<Redirect>,
137    /// Build only the files the generator wrote again; others keep the previous entries.
138    pub written: Option<BTreeSet<String>>,
139    /// Ask for a snapshot even when a delta would do.
140    pub force_snapshot: bool,
141}
142
143/// A release ready for a host: its manifest and where its files are.
144#[derive(Debug, Clone)]
145pub struct StagedRelease {
146    /// The manifest.
147    pub manifest: ReleaseManifest,
148    /// The manifest's digest.
149    pub digest: Digest,
150    /// The manifest's JCS bytes, published at [`manifest_path`].
151    pub manifest_bytes: Bytes,
152    /// The directory holding the release's files, at their paths without the leading `/`.
153    pub root: PathBuf,
154    /// The full file set.
155    pub files: BTreeMap<String, FileEntry>,
156    /// Paths added or changed since the previous release: what a host uploads.
157    pub changed: BTreeSet<String>,
158    /// Paths the previous release had and this one does not.
159    pub removed: BTreeSet<String>,
160    /// The log's tiles and checkpoint, for a logged (production) release.
161    pub log: Option<LogPublication>,
162    /// The last snapshot before this release, when this one is a delta.
163    pub previous_snapshot: Option<(u64, DateTime<Utc>)>,
164}
165
166impl StagedRelease {
167    /// The local path of a release file (`/a/b.html` or `a/b.html`).
168    pub fn local_path(&self, path: &str) -> PathBuf {
169        self.root.join(path.trim_start_matches('/'))
170    }
171
172    /// Reads a release file's bytes and checks them against the manifest.
173    ///
174    /// # Errors
175    ///
176    /// [`SiteError::Io`] when the file cannot be read; [`SiteError::DigestMismatch`] when it
177    /// changed after staging.
178    pub fn read(&self, path: &str) -> Result<Vec<u8>> {
179        let local = self.local_path(path);
180        let bytes = std::fs::read(&local).map_err(|e| SiteError::io(&local, e))?;
181        if let Some(entry) = self.files.get(path) {
182            let actual = file_digest(&bytes);
183            if actual != entry.sha256 {
184                return Err(SiteError::DigestMismatch {
185                    path: path.to_string(),
186                    expected: entry.sha256.to_string(),
187                    actual: actual.to_string(),
188                });
189            }
190        }
191        Ok(bytes)
192    }
193}
194
195/// A delta release: its manifest names a `base` and lists only changes (spec 3.5 §7.8.3).
196#[derive(Debug, Clone)]
197pub struct StagedDelta(StagedRelease);
198
199impl StagedDelta {
200    /// Wraps a staged delta release.
201    ///
202    /// # Errors
203    ///
204    /// [`SiteError::Sequence`] when the release is a snapshot.
205    pub fn new(release: StagedRelease) -> Result<Self> {
206        if release.manifest.is_snapshot() {
207            return Err(SiteError::Sequence(format!(
208                "release {} is a snapshot, not a delta",
209                release.manifest.seq
210            )));
211        }
212        Ok(Self(release))
213    }
214
215    /// The release.
216    pub fn release(&self) -> &StagedRelease {
217        &self.0
218    }
219}
220
221/// Hashes builds into signed, logged releases (spec 3.5 §7.7).
222///
223/// # Example
224///
225/// ```rust,no_run
226/// use adk_site::release::{ReleaseBuilder, ReleaseOptions};
227/// use awp_types::ReleaseSource;
228///
229/// # async fn demo(out: &std::path::Path, log: &adk_site::log::SiteLog) -> adk_site::Result<()> {
230/// let builder = ReleaseBuilder::new();
231/// let options = ReleaseOptions {
232///     source: ReleaseSource::Onboarding,
233///     generator: adk_site::generator::BuiltinGenerator::reference(),
234///     charter_version: 1,
235///     redirects: Vec::new(),
236///     written: None,
237///     force_snapshot: false,
238/// };
239/// let staged = builder.release(out, None, options, log).await?;
240/// assert_eq!(staged.manifest.seq, 1);
241/// # Ok(())
242/// # }
243/// ```
244#[derive(Debug, Clone)]
245pub struct ReleaseBuilder {
246    clock: Arc<dyn Clock>,
247    snapshot_every: u64,
248    snapshot_interval: chrono::Duration,
249}
250
251impl Default for ReleaseBuilder {
252    fn default() -> Self {
253        Self::new()
254    }
255}
256
257impl ReleaseBuilder {
258    /// A builder that writes a snapshot every 100 releases and at least daily.
259    pub fn new() -> Self {
260        Self {
261            clock: Arc::new(SystemClock),
262            snapshot_every: 100,
263            snapshot_interval: chrono::Duration::days(1),
264        }
265    }
266
267    /// Stamps manifests with `clock`.
268    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
269        self.clock = clock;
270        self
271    }
272
273    /// Writes a snapshot every `releases` releases (at least 1).
274    pub fn snapshot_every(mut self, releases: u64) -> Self {
275        self.snapshot_every = releases.max(1);
276        self
277    }
278
279    /// Stages a release of the build in `out` without logging it: a preview, or the first
280    /// half of [`release`](Self::release).
281    ///
282    /// # Errors
283    ///
284    /// [`SiteError::ServerCode`] when any file is server code (A-I1), whatever the options;
285    /// [`SiteError::InvalidContent`] for a redirect with an unknown status or log paths in
286    /// the build; I/O errors.
287    pub async fn stage(
288        &self,
289        out: &Path,
290        previous: Option<&PreviousRelease>,
291        options: ReleaseOptions,
292    ) -> Result<StagedRelease> {
293        for redirect in &options.redirects {
294            if !matches!(redirect.status, 301 | 302 | 307 | 308 | 410) {
295                return Err(SiteError::InvalidContent {
296                    path: redirect.from.clone(),
297                    message: format!(
298                        "redirect status {} is not 301, 302, 307, 308 or 410",
299                        redirect.status
300                    ),
301                });
302            }
303        }
304        let out_owned = out.to_path_buf();
305        let reuse: Option<BTreeMap<String, FileEntry>> = match (&options.written, previous) {
306            (Some(_), Some(previous)) => Some(previous.files.clone()),
307            _ => None,
308        };
309        let written = options.written.clone();
310        let files = tokio::task::spawn_blocking(move || {
311            hash_tree(&out_owned, reuse.as_ref(), written.as_ref())
312        })
313        .await
314        .map_err(|e| SiteError::Pipeline(format!("hashing task failed: {e}")))??;
315        let seq = previous.map_or(1, |p| p.manifest.seq + 1);
316        let now = self.clock.now();
317        let snapshot = match previous {
318            None => true,
319            Some(previous) => {
320                options.force_snapshot
321                    || seq - previous.last_snapshot.0 >= self.snapshot_every
322                    || now - previous.last_snapshot.1 >= self.snapshot_interval
323            }
324        };
325        let empty = BTreeMap::new();
326        let before = previous.map_or(&empty, |p| &p.files);
327        let changed: BTreeSet<String> = files
328            .iter()
329            .filter(|(path, entry)| before.get(*path) != Some(entry))
330            .map(|(path, _)| path.clone())
331            .collect();
332        let removed: BTreeSet<String> =
333            before.keys().filter(|p| !files.contains_key(*p)).cloned().collect();
334        let manifest = ReleaseManifest {
335            seq,
336            previous: previous.map(|p| p.digest.clone()),
337            base: (!snapshot).then(|| seq - 1),
338            created_at: now,
339            files: if snapshot {
340                files.clone()
341            } else {
342                changed.iter().map(|p| (p.clone(), files[p].clone())).collect()
343            },
344            removed: if snapshot { BTreeSet::new() } else { removed.clone() },
345            redirects: options.redirects,
346            source: options.source,
347            generator: options.generator,
348            charter_version: options.charter_version,
349        };
350        let (digest, manifest_bytes) = manifest_digest(&manifest)?;
351        tracing::info!(
352            site.release.seq = seq,
353            site.release.files = files.len(),
354            site.release.changed = changed.len(),
355            snapshot,
356            "release staged"
357        );
358        Ok(StagedRelease {
359            manifest,
360            digest,
361            manifest_bytes,
362            root: out.to_path_buf(),
363            files,
364            changed,
365            removed,
366            log: None,
367            previous_snapshot: (!snapshot).then(|| previous.map(|p| p.last_snapshot)).flatten(),
368        })
369    }
370
371    /// Stages a release and appends its manifest digest to `log`, attaching the tiles and
372    /// signed checkpoint a host publishes after the files (spec 3.5 §7.7).
373    ///
374    /// # Errors
375    ///
376    /// As [`stage`](Self::stage); [`SiteError::Sequence`] when the log is not at the
377    /// previous release; log and signing errors.
378    pub async fn release(
379        &self,
380        out: &Path,
381        previous: Option<&PreviousRelease>,
382        options: ReleaseOptions,
383        log: &SiteLog,
384    ) -> Result<StagedRelease> {
385        let mut staged = self.stage(out, previous, options).await?;
386        let before = log.size().await;
387        log.append(&LogEntry { seq: staged.manifest.seq, manifest: staged.digest.clone() }).await?;
388        staged.log = Some(log.publication(before).await?);
389        tracing::info!(site.release.seq = staged.manifest.seq, site.release.digest = %staged.digest, "release logged");
390        Ok(staged)
391    }
392}
393
394/// Hashes every file under `out`, scanning each for server code; entries for files not in
395/// `written` are taken from `reuse` when present.
396fn hash_tree(
397    out: &Path,
398    reuse: Option<&BTreeMap<String, FileEntry>>,
399    written: Option<&BTreeSet<String>>,
400) -> Result<BTreeMap<String, FileEntry>> {
401    let mut files = BTreeMap::new();
402    let mut findings = Vec::new();
403    for relative in crate::generator::list_files(out)? {
404        let key = format!("/{relative}");
405        if is_log_path(&key) {
406            return Err(SiteError::InvalidContent {
407                path: relative,
408                message: "the build output holds a release or log path; those are written by the release builder".into(),
409            });
410        }
411        if let (Some(reuse), Some(written)) = (reuse, written)
412            && !written.contains(&relative)
413            && let Some(entry) = reuse.get(&key)
414        {
415            files.insert(key, entry.clone());
416            continue;
417        }
418        let path = out.join(&relative);
419        let bytes = std::fs::read(&path).map_err(|e| SiteError::io(&path, e))?;
420        findings.extend(scan_file(&relative, &bytes));
421        files.insert(
422            key,
423            FileEntry {
424                sha256: file_digest(&bytes),
425                size: bytes.len() as u64,
426                content_type: content_type(&relative).into(),
427            },
428        );
429    }
430    if !findings.is_empty() {
431        tracing::warn!(
432            site.release.refused = findings.len(),
433            "release refused: server code (A-I1)"
434        );
435        return Err(SiteError::ServerCode { findings });
436    }
437    Ok(files)
438}
439
440/// Resolves a release's full file set from its manifest and its base's full set
441/// (AWP 2.0 §14.4).
442pub fn full_file_set(
443    manifest: &ReleaseManifest,
444    base: &BTreeMap<String, FileEntry>,
445) -> BTreeMap<String, FileEntry> {
446    manifest.apply_to(base)
447}