summaryrefslogtreecommitdiffstats
path: root/src/watch/digests.rs
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-17 21:19:35 +0000
committeraur-build <aur-build@localhost>2026-11-17 21:19:35 +0000
commitf586d11f6a1711145ba4804787217a1bab58751d (patch)
tree3a8cd7d4a3d4097e315907c63e687bd243e8e686 /src/watch/digests.rs
parentfd3ecf91686b11feea078531baeddb60e6941116 (diff)
downloadaur-build-f586d11f6a1711145ba4804787217a1bab58751d.tar.gz
aur-build-f586d11f6a1711145ba4804787217a1bab58751d.zip
feat: AUR mirror watcher, recipe parsing, candidate creation
The detection path (§5.1, §5.1a, §5.3, §7.1): * git helpers, all subprocess git in one auditable place. Mirrors are cloned with --mirror and polled with git ls-remote, fetching only when the tip actually moved; --no-prune keeps history we may need forever. * .SRCINFO parsing (authoritative) with a PKGBUILD fallback, and source=() parsing that keeps VCS kind, #commit/#tag/#branch refs and the filename:: form. * recipe_hash over the whole snapshot tree, so a shipped patch is part of the recipe and cannot change silently. * source digest resolution: declared checksums are trusted-as-declared (makepkg enforces them, no bandwidth), local files are hashed from the mirror, and SKIP sources are downloaded and stream-hashed into the content-addressed source cache. Detection always re-fetches SKIP sources — answering from our own cache would defeat drift detection. * candidate creation with base = current_accepted_release, collapse in place while unviewed, supersede only once a human has looked, and a previously rejected identity is not re-raised. * non-publishable change handling (I11): unchanged version string means no review, but never silence — recipe drift and pin drift become notices, and a changed digest on a remote source with an unchanged version becomes a high-severity integrity_alert. Also vercmp + dep-string parsing with the ALPM test vectors, and the approval record with optimistic concurrency (§7.1a) that the CLI and web layers will both call. 16 detection tests against real file:// git fixtures, incl. I2 across three unattended detections and I11 for all three drift kinds. Part of P0 (DESIGN.md §17).
Diffstat (limited to 'src/watch/digests.rs')
-rw-r--r--src/watch/digests.rs193
1 files changed, 193 insertions, 0 deletions
diff --git a/src/watch/digests.rs b/src/watch/digests.rs
new file mode 100644
index 0000000..07551ca
--- /dev/null
+++ b/src/watch/digests.rs
@@ -0,0 +1,193 @@
+//! Source digest resolution (§5.3).
+//!
+//! `sha256sums=('SKIP')` is the hole in the integrity story. We resolve and
+//! record the digest of *every* source ourselves, at detection time, regardless
+//! of what the PKGBUILD declares — which turns a silent artifact swap into a
+//! reviewable (or at least alertable) event.
+//!
+//! Cost control: only `SKIP`-declared static sources cost bandwidth. Declared
+//! checksums are trusted-as-declared for identity because makepkg enforces them
+//! at build time; VCS digests come free from the pin we already resolved; local
+//! files are already in the mirror.
+
+use crate::config::Config;
+use crate::db::*;
+use crate::error::Result;
+use crate::time;
+use crate::watch::mirror::Tree;
+
+const SKIP: &str = "SKIP";
+
+fn declared_sums(recipe: &Recipe, index: usize) -> Option<String> {
+ recipe
+ .sha256sums
+ .get(index)
+ .or_else(|| recipe.b2sums.get(index))
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+}
+
+fn is_hex_digest(s: &str) -> bool {
+ (s.len() == 64 || s.len() == 128) && s.chars().all(|c| c.is_ascii_hexdigit())
+}
+
+/// Resolve the digest of every `source=()` entry.
+pub fn resolve_sources(
+ cfg: &Config,
+ db: &Db,
+ mirror: &std::path::Path,
+ commit: &str,
+ tree: &Tree,
+ recipe: &Recipe,
+ pins: &[UpstreamPin],
+) -> Result<Vec<SourceDigest>> {
+ let mut out = Vec::new();
+ for entry in &recipe.source_entries {
+ let declared = declared_sums(recipe, entry.index);
+ let skip_declared = match &declared {
+ Some(d) => d == SKIP || !is_hex_digest(d),
+ None => true,
+ };
+
+ if entry.is_vcs() {
+ // The resolved commit *is* the digest; captured during Stage B where
+ // we clone anyway (§5.2), so near-free.
+ let pin = pins.iter().find(|p| p.index == entry.index);
+ let digest = pin
+ .map(|p| p.commit.clone())
+ .or_else(|| entry.commit.clone())
+ .unwrap_or_default();
+ out.push(SourceDigest {
+ index: entry.index,
+ url: entry.url.clone(),
+ kind: entry.vcs.clone().unwrap_or_else(|| "vcs".into()),
+ digest,
+ size: 0,
+ skip_declared: true,
+ });
+ continue;
+ }
+
+ if entry.local {
+ let name = entry.filename.clone().unwrap_or_default();
+ let path = tree
+ .blobs
+ .iter()
+ .find(|(p, _)| p == &name || p.ends_with(&format!("/{name}")))
+ .map(|(p, _)| p.clone());
+ let (digest, size) = match path {
+ Some(p) => {
+ let bytes = crate::watch::mirror::read_file(mirror, commit, &p)?;
+ let d = crate::hash::hex(&bytes);
+ (d, bytes.len() as u64)
+ }
+ // A "local" file that is not in the tree is the recipe's bug;
+ // record the absence rather than inventing a digest.
+ None => (String::new(), 0),
+ };
+ out.push(SourceDigest {
+ index: entry.index,
+ url: entry.url.clone(),
+ kind: "local".into(),
+ digest,
+ size,
+ skip_declared,
+ });
+ continue;
+ }
+
+ // Static source.
+ if !skip_declared {
+ // Trusted-as-declared: makepkg verifies it at build time.
+ out.push(SourceDigest {
+ index: entry.index,
+ url: entry.url.clone(),
+ kind: "static".into(),
+ digest: declared.unwrap_or_default(),
+ size: 0,
+ skip_declared: false,
+ });
+ continue;
+ }
+
+ // The paid path: download and stream-hash into the cache, which the
+ // build then reuses so the bytes are paid for once.
+ let (digest, size) = download_and_cache(cfg, db, &entry.url)?;
+ out.push(SourceDigest {
+ index: entry.index,
+ url: entry.url.clone(),
+ kind: "static".into(),
+ digest,
+ size,
+ skip_declared: true,
+ });
+ }
+ Ok(out)
+}
+
+/// Download `url`, hashing as we go, and record it in `source_cache`.
+///
+/// This always goes to the network. That is deliberate: the whole point of §5.3
+/// is to notice that the bytes behind a `SKIP` source changed while the version
+/// did not, and answering from our own cache would make that impossible. The
+/// cache exists so the *build* can reuse the bytes it was reviewed against
+/// ([`cached_path`]), not so detection can skip looking.
+pub fn download_and_cache(cfg: &Config, db: &Db, url: &str) -> Result<(String, u64)> {
+ let tmp = cfg.source_cache_dir().join(format!("tmp-{}", crate::hash::short(url.as_bytes(), 16)));
+ let (digest, size) = crate::fetch::fetch_to(url, &tmp)?;
+ let dest = cfg.source_cache_path(&digest);
+ if !dest.exists() {
+ if let Some(parent) = dest.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ std::fs::rename(&tmp, &dest)?;
+ } else {
+ let _ = std::fs::remove_file(&tmp);
+ }
+ let at = time::now();
+ let dest_s = dest.display().to_string();
+ let u = url.to_string();
+ let digest_for_row = digest.clone();
+ db.writer.tx(move |tx| {
+ tx.execute(
+ "INSERT INTO source_cache (url, digest, size, fetched_at, path) VALUES (?1,?2,?3,?4,?5)
+ ON CONFLICT(url, digest) DO UPDATE SET fetched_at=excluded.fetched_at",
+ rusqlite::params![u, digest_for_row, size as i64, at, dest_s],
+ )?;
+ Ok(())
+ })?;
+ Ok((digest, size))
+}
+
+/// The cached file holding `digest`, if we still have it. The build uses this
+/// so the bytes it consumes are the bytes that were hashed at detection time.
+pub fn cached_path(db: &Db, url: &str, digest: &str) -> Option<std::path::PathBuf> {
+ let p: Option<String> = db
+ .read(|c| {
+ use rusqlite::OptionalExtension;
+ Ok(c.query_row(
+ "SELECT path FROM source_cache WHERE url=?1 AND digest=?2",
+ rusqlite::params![url, digest],
+ |r| r.get(0),
+ )
+ .optional()?)
+ })
+ .ok()
+ .flatten();
+ p.map(std::path::PathBuf::from).filter(|p| p.exists())
+}
+
+/// True when a `SKIP` on a non-VCS source means the recipe permanently refuses
+/// to verify its input — itself a risk signal (§5.3).
+pub fn skip_on_non_vcs(recipe: &Recipe) -> Vec<usize> {
+ recipe
+ .source_entries
+ .iter()
+ .filter(|e| !e.is_vcs())
+ .filter(|e| match declared_sums(recipe, e.index) {
+ Some(d) => d == SKIP || !is_hex_digest(&d),
+ None => true,
+ })
+ .map(|e| e.index)
+ .collect()
+}