diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/db/mod.rs | 6 | ||||
| -rw-r--r-- | src/db/model.rs | 3 | ||||
| -rw-r--r-- | src/fetch.rs | 65 | ||||
| -rw-r--r-- | src/git.rs | 238 | ||||
| -rw-r--r-- | src/lib.rs | 5 | ||||
| -rw-r--r-- | src/pkgver/mod.rs | 59 | ||||
| -rw-r--r-- | src/recipe.rs | 426 | ||||
| -rw-r--r-- | src/review/approve.rs | 267 | ||||
| -rw-r--r-- | src/review/candidates.rs | 293 | ||||
| -rw-r--r-- | src/review/diff.rs | 156 | ||||
| -rw-r--r-- | src/review/mod.rs | 8 | ||||
| -rw-r--r-- | src/watch/detect.rs | 288 | ||||
| -rw-r--r-- | src/watch/digests.rs | 193 | ||||
| -rw-r--r-- | src/watch/mirror.rs | 119 | ||||
| -rw-r--r-- | src/watch/mod.rs | 12 | ||||
| -rw-r--r-- | src/watch/scheduler.rs | 71 |
16 files changed, 2206 insertions, 3 deletions
diff --git a/src/db/mod.rs b/src/db/mod.rs index c11bf5a..a841fec 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -8,9 +8,9 @@ //! design entirely. Readers are thread-local, read-only connections; WAL lets //! them proceed concurrently with the writer. -mod migrations; -mod model; -mod queries; +pub mod migrations; +pub mod model; +pub mod queries; pub use migrations::MIGRATIONS; pub use model::*; diff --git a/src/db/model.rs b/src/db/model.rs index 599fc21..66674ab 100644 --- a/src/db/model.rs +++ b/src/db/model.rs @@ -197,6 +197,9 @@ pub struct Recipe { pub srcinfo: Option<String>, /// True if `--skippgpcheck` appears in the PKGBUILD. pub skipgpcheck: bool, + /// Parsed `source=()` entries. Derived from `source`, so not serialized. + #[serde(skip, default)] + pub source_entries: Vec<SourceEntry>, } impl Recipe { diff --git a/src/fetch.rs b/src/fetch.rs new file mode 100644 index 0000000..c1c4575 --- /dev/null +++ b/src/fetch.rs @@ -0,0 +1,65 @@ +//! Outbound HTTP. `ureq` is blocking, which is the whole point of this stack +//! (DESIGN.md §4: "`reqwest` pulls in tokio even in blocking mode — avoid"). +//! +//! `file://` is supported as a first-class scheme so the test corpus can serve +//! sources from disk with no network (§16a). + +use std::io::{Read, Write}; +use std::path::PathBuf; + +use crate::error::{Error, Result}; + +pub enum Body { + File(std::fs::File), + Http(Box<dyn Read + Send>), +} + +impl Read for Body { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { + match self { + Body::File(f) => f.read(buf), + Body::Http(r) => r.read(buf), + } + } +} + +/// Open a URL for streaming. Never buffers the whole body: sources are hashed +/// while they are written into the cache (§5.3). +pub fn open(url: &str) -> Result<(Body, Option<u64>)> { + if let Some(path) = url.strip_prefix("file://") { + let p = path.trim_start_matches('/'); + let p = PathBuf::from(format!("/{p}")); + let f = std::fs::File::open(&p).map_err(|e| Error::Http(format!("{url}: {e}")))?; + let len = f.metadata().map(|m| m.len()).ok(); + return Ok((Body::File(f), len)); + } + if url.starts_with("http://") || url.starts_with("https://") { + let resp = ureq::get(url) + .timeout(std::time::Duration::from_secs(300)) + .call() + .map_err(|e| Error::Http(format!("{url}: {e}")))?; + let len = resp + .header("content-length") + .and_then(|v| v.parse::<u64>().ok()); + return Ok((Body::Http(resp.into_reader()), len)); + } + Err(Error::invalid(format!("unsupported url scheme: {url}"))) +} + +/// Fetch `url` into `dest`, returning `(sha256, size)`. +pub fn fetch_to(url: &str, dest: &std::path::Path) -> Result<(String, u64)> { + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + let (body, _len) = open(url)?; + let mut tmp = dest.as_os_str().to_os_string(); + tmp.push(".part"); + let tmp = PathBuf::from(tmp); + let mut file = std::io::BufWriter::new(std::fs::File::create(&tmp)?); + let (digest, size) = crate::hash::digest_reader(std::io::BufReader::new(body), Some(&mut file)) + .map_err(|e| Error::Http(format!("{url}: {e}")))?; + file.flush()?; + // Rename into place: a half-written cache entry must never be visible. + std::fs::rename(&tmp, dest)?; + Ok((digest, size)) +} diff --git a/src/git.rs b/src/git.rs new file mode 100644 index 0000000..6c1f442 --- /dev/null +++ b/src/git.rs @@ -0,0 +1,238 @@ +//! Shelling out to `git` (DESIGN.md §4: "shell out to git ... avoids libgit2 +//! build pain"). +//! +//! Every git operation the system performs goes through here so the subprocess +//! surface is auditable in one place. + +use std::path::Path; +use std::process::{Command, Output}; + +use crate::error::{Error, Result}; + +/// Run git and capture output; non-zero status becomes `Error::Git`. +pub fn git(cwd: Option<&Path>, args: &[&str]) -> Result<String> { + let mut cmd = Command::new("git"); + if let Some(c) = cwd { + cmd.current_dir(c); + } + cmd.args(args); + // Never let a stray terminal prompt hang a watcher thread. + cmd.env("GIT_TERMINAL_PROMPT", "0"); + cmd.env("GIT_CONFIG_NOSYSTEM", "1"); + cmd.env("LC_ALL", "C"); + let out = cmd.output().map_err(|e| Error::git(format!("git {args:?}: {e}")))?; + ok(out, args) +} + +fn ok(out: Output, args: &[&str]) -> Result<String> { + if !out.status.success() { + return Err(Error::git(format!( + "git {args:?} exited {}: {}", + out.status, + String::from_utf8_lossy(&out.stderr).trim() + ))); + } + Ok(String::from_utf8_lossy(&out.stdout).to_string()) +} + +/// Run git, discarding output, returning success/failure without allocating. +pub fn git_ok(cwd: Option<&Path>, args: &[&str]) -> bool { + git(cwd, args).is_ok() +} + +/// `git ls-remote <url> HEAD` — the cheap poll (§5.1). Returns the remote HEAD +/// SHA, or `None` when the remote is gone (deletion / orphan handling). +pub fn ls_remote_head(url: &str) -> Result<Option<String>> { + match git(None, &["ls-remote", url, "HEAD"]) { + Ok(out) => { + let sha = out + .split_whitespace() + .next() + .filter(|s| s.len() >= 7) + .map(|s| s.to_string()); + Ok(sha) + } + Err(e) if is_missing_remote(&e) => Ok(None), + Err(e) => Err(e), + } +} + +/// `ls-remote --heads <url>`: every branch tip, as `(refname, sha)`. +pub fn ls_remote_heads(url: &str) -> Result<Vec<(String, String)>> { + let out = git(None, &["ls-remote", "--heads", url])?; + let mut v = Vec::new(); + for line in out.lines() { + let mut it = line.split_whitespace(); + if let (Some(sha), Some(name)) = (it.next(), it.next()) { + v.push((name.to_string(), sha.to_string())); + } + } + Ok(v) +} + +/// Ask a single remote ref for its SHA, e.g. `refs/tags/v1.2` or a full commit. +pub fn ls_remote_ref(url: &str, refname: &str) -> Result<Option<String>> { + match git(None, &["ls-remote", url, refname]) { + Ok(out) => Ok(out + .lines() + .next() + .and_then(|l| l.split_whitespace().next()) + .map(|s| s.to_string())), + Err(e) if is_missing_remote(&e) => Ok(None), + Err(e) => Err(e), + } +} + +fn is_missing_remote(e: &Error) -> bool { + let s = e.to_string(); + s.contains("not found") + || s.contains("does not appear to be a git repository") + || s.contains("Repository not found") + || s.contains("404") +} + +/// Clone an AUR mirror. `--mirror` so that `git fetch` actually moves our refs +/// (a plain clone would leave HEAD on the original commit), and **never** +/// `--filter=blob:none`: a partial clone can lazily drop blobs and we must be +/// able to materialize any historical commit forever (§5.1). +pub fn clone(url: &str, dest: &Path) -> Result<()> { + if dest.exists() { + return Ok(()); + } + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + git(None, &["clone", "--quiet", "--mirror", url, &dest.display().to_string()])?; + Ok(()) +} + +/// `git clone --bare` for the upstream VCS cache. +pub fn clone_bare(url: &str, dest: &Path) -> Result<()> { + if dest.exists() { + return Ok(()); + } + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + git( + None, + &["clone", "--quiet", "--bare", url, &dest.display().to_string()], + )?; + Ok(()) +} + +/// Fetch into an existing mirror. Returns the new HEAD. +pub fn fetch_head(mirror: &Path) -> Result<String> { + // `--no-prune` mirrors the "never GC a commit we may need" rule (§5.1a). + git(Some(mirror), &["fetch", "--quiet", "--no-prune", "origin"])?; + head(mirror) +} + +pub fn head(mirror: &Path) -> Result<String> { + Ok(git(Some(mirror), &["rev-parse", "HEAD"])?.trim().to_string()) +} + +/// True if `commit` exists in the local mirror. Guards against a force-pushed +/// AUR history making a pin vanish (§16 mirror divergence). +pub fn has_commit(mirror: &Path, commit: &str) -> bool { + git_ok(Some(mirror), &["cat-file", "-e", &format!("{commit}^{{commit}}")]) +} + +/// `git ls-tree -r <commit>`: every `(path, blob-sha)` in the tree. +pub fn ls_tree(mirror: &Path, commit: &str) -> Result<Vec<(String, String)>> { + let out = git(Some(mirror), &["ls-tree", "-r", commit])?; + let mut v = Vec::new(); + for line in out.lines() { + // "<mode> blob <sha>\t<path>" + if let Some(rest) = line.strip_prefix("100644 blob ").or_else(|| line.strip_prefix("100755 blob ")) { + if let Some((sha, path)) = rest.split_once('\t') { + v.push((path.to_string(), sha.to_string())); + } + } + } + Ok(v) +} + +pub fn read_blob(mirror: &Path, commit: &str, path: &str) -> Result<Vec<u8>> { + let spec = format!("{commit}:{path}"); + let out = Command::new("git") + .current_dir(mirror) + .env("GIT_TERMINAL_PROMPT", "0") + .env("GIT_CONFIG_NOSYSTEM", "1") + .args(["cat-file", "blob", &spec]) + .output() + .map_err(|e| Error::git(e.to_string()))?; + if !out.status.success() { + return Err(Error::not_found(format!("{spec} not in mirror"))); + } + Ok(out.stdout) +} + +/// Materialize a commit into `dest` using the local mirror only — no network +/// (§8.1 step 0). `git archive` + tar keeps it dependency-free. +pub fn materialize(mirror: &Path, commit: &str, dest: &Path) -> Result<()> { + std::fs::create_dir_all(dest)?; + let out = Command::new("git") + .current_dir(mirror) + .env("GIT_TERMINAL_PROMPT", "0") + .env("GIT_CONFIG_NOSYSTEM", "1") + .args(["archive", "--format=tar", commit]) + .output() + .map_err(|e| Error::git(e.to_string()))?; + if !out.status.success() { + return Err(Error::git(format!( + "git archive {commit}: {}", + String::from_utf8_lossy(&out.stderr).trim() + ))); + } + let mut ar = tar::Archive::new(std::io::Cursor::new(&out.stdout)); + ar.set_preserve_permissions(true); + ar.unpack(dest) + .map_err(|e| Error::git(format!("unpack {commit}: {e}")))?; + Ok(()) +} + +/// `git log --oneline range` — review context (§5.1) and the upstream delta +/// panel (§6). +pub fn log_oneline(mirror: &Path, range: &str) -> Result<Vec<String>> { + let out = git(Some(mirror), &["log", "--oneline", range])?; + Ok(out.lines().map(|l| l.to_string()).collect()) +} + +/// `git diff range -- <paths>`; empty `paths` means everything. +pub fn diff(mirror: &Path, range: &str, paths: &[&str]) -> Result<String> { + let mut args: Vec<&str> = vec!["diff", "--no-color", range, "--"]; + args.extend(paths); + git(Some(mirror), &args) +} + +/// `git rev-list --count range`. +pub fn count_commits(mirror: &Path, range: &str) -> Result<usize> { + let out = git(Some(mirror), &["rev-list", "--count", range])?; + Ok(out.trim().parse().unwrap_or(0)) +} + +/// Clone a VCS source the way a PKGBUILD would (depth/ref aware) into `dest`. +pub fn clone_source(url: &str, dest: &Path, depth: Option<usize>, branch: Option<&str>) -> Result<()> { + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + let mut args: Vec<String> = vec!["clone".into(), "--quiet".into()]; + if let Some(d) = depth { + args.push(format!("--depth={d}")); + } + if let Some(b) = branch { + args.push(format!("--branch={b}")); + } + args.push(url.to_string()); + args.push(dest.display().to_string()); + let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect(); + git(None, &refs)?; + Ok(()) +} + +/// Fetch into an existing clone and return HEAD. +pub fn fetch_and_head(repo: &Path) -> Result<String> { + git(Some(repo), &["fetch", "--quiet", "--no-prune", "origin"])?; + head(repo) +} @@ -8,8 +8,13 @@ pub mod config; pub mod db; pub mod error; +pub mod fetch; +pub mod git; pub mod hash; pub mod pkgver; +pub mod recipe; +pub mod review; pub mod time; +pub mod watch; pub use error::{Error, Result}; diff --git a/src/pkgver/mod.rs b/src/pkgver/mod.rs index a940dc0..75be308 100644 --- a/src/pkgver/mod.rs +++ b/src/pkgver/mod.rs @@ -271,3 +271,62 @@ pub fn parse_deps(list: &[String]) -> Vec<Dep> { pub fn dep_names(list: &[String]) -> Vec<String> { parse_deps(list).into_iter().map(|d| d.name).collect() } + +#[cfg(test)] +mod tests { + use super::*; + + fn ord(a: &str, b: &str) -> Ordering { + vercmp(a, b) + } + + #[test] + fn alpm_version_ordering() { + // The classic ALPM test vectors. + assert_eq!(ord("1.0-1", "1.0-1"), Ordering::Equal); + assert_eq!(ord("1.0-1", "1.0-2"), Ordering::Less); + assert_eq!(ord("1.1-1", "1.0-1"), Ordering::Greater); + assert_eq!(ord("1.10-1", "1.9-1"), Ordering::Greater, "numeric chunks compare numerically"); + assert_eq!(ord("1.0.a-1", "1.0.1-1"), Ordering::Greater, "alpha sorts after numeric"); + assert_eq!(ord("1.5-1", "1.5.0-1"), Ordering::Less, "a trailing numeric chunk is newer"); + assert_eq!(ord("1:1.0-1", "2.0-1"), Ordering::Greater, "epoch dominates"); + assert_eq!(ord("1.0-1", "1.0_2-1"), Ordering::Less, "non-alnum separators are ignored"); + assert_eq!(ord("1.0.0-1", "1.0-1"), Ordering::Greater, "a trailing numeric chunk is newer"); + assert_eq!(ord("01.0-1", "1.0-1"), Ordering::Equal, "leading zeros are not significant"); + } + + #[test] + fn full_version_formatting() { + assert_eq!(full_version("0", "1.0", "1"), "1.0-1"); + assert_eq!(full_version("", "1.0", "1"), "1.0-1"); + assert_eq!(full_version("2", "1.0", "3"), "2:1.0-3"); + assert_eq!(split_full_version("2:1.0-3").0, "2"); + assert_eq!(split_full_version("1.0-3"), ("0".into(), "1.0".into(), "3".into())); + } + + #[test] + fn pkgrel_reset_is_a_new_version() { + // §3: a pkgrel reset is a major signal. + assert_eq!(ord("1.0-7", "1.0-1"), Ordering::Greater); + assert!(is_downgrade("1.0-7", "1.0-1")); + } + + #[test] + fn dep_strings_parse() { + assert_eq!(Dep::parse("foo").unwrap(), Dep { name: "foo".into(), op: DepOp::Any, version: None }); + assert_eq!(Dep::parse("foo>=1.2").unwrap().op, DepOp::Ge); + assert_eq!(Dep::parse("foo<=1.2").unwrap().op, DepOp::Le); + assert_eq!(Dep::parse("foo=1.2-3").unwrap().version.as_deref(), Some("1.2-3")); + assert_eq!(Dep::parse("python-numpy").unwrap().name, "python-numpy"); + assert_eq!(Dep::parse("cmake: for building").unwrap().name, "cmake"); + assert!(Dep::parse("").is_none()); + } + + #[test] + fn version_constraints_are_checked() { + let d = Dep::parse("python>=3.11").unwrap(); + assert!(d.satisfied_by("3.12-1")); + assert!(!d.satisfied_by("3.10-1")); + assert!(Dep::parse("foo").unwrap().satisfied_by("anything")); + } +} diff --git a/src/recipe.rs b/src/recipe.rs new file mode 100644 index 0000000..a43059d --- /dev/null +++ b/src/recipe.rs @@ -0,0 +1,426 @@ +//! Recipe parsing: `.SRCINFO` (authoritative, present in every AUR repo) with a +//! `PKGBUILD` fallback, plus `source=()` parsing. +//! +//! The recipe is what a human reviews, so parsing failures are loud: a recipe we +//! cannot read must never silently produce a candidate with an empty source list. + +use std::collections::BTreeMap; + +use crate::db::model::{Recipe, SourceEntry}; +use crate::error::{Error, Result}; + +/// Parse `.SRCINFO`. Sections are `pkgbase = X` followed by `key = value` lines, +/// then one `pkgname = Y` section per emitted package. +pub fn parse_srcinfo(text: &str) -> Result<Recipe> { + let mut r = Recipe::default(); + let mut current: Option<String> = None; // Some(pkgname) when inside a pkgname section + let mut base_seen = false; + for line in text.lines() { + let line = line.trim_end(); + if line.is_empty() { + continue; + } + let indented = line.starts_with('\t') || line.starts_with(' '); + let (k, v) = match line.split_once('=') { + Some((k, v)) => (k.trim().to_string(), v.trim().to_string()), + None => continue, + }; + if !indented { + if k == "pkgbase" { + r.pkgbase = v; + base_seen = true; + current = None; + } else if k == "pkgname" { + current = Some(v.clone()); + r.pkgnames.push(v.clone()); + r.pkg_depends.push((v, Vec::new())); + } + continue; + } + if !base_seen { + return Err(Error::invalid(".SRCINFO has no pkgbase line")); + } + let in_pkg = current.is_some(); + push_field(&mut r, in_pkg, current.as_deref(), &k, &v); + } + if r.pkgnames.is_empty() { + r.pkgnames.push(r.pkgbase.clone()); + let deps = r.depends.clone(); + r.pkg_depends.push((r.pkgbase.clone(), deps)); + } + r.srcinfo = Some(text.to_string()); + r.source_entries = parse_source_entries(&r.source)?; + Ok(r) +} + +#[allow(clippy::too_many_arguments)] +fn push_field(r: &mut Recipe, in_pkg: bool, pkg: Option<&str>, k: &str, v: &str) { + // Fields that belong to the base only are ignored inside pkgname sections. + match k { + "pkgver" if !in_pkg => r.pkgver = v.into(), + "pkgrel" if !in_pkg => r.pkgrel = v.into(), + "epoch" if !in_pkg => r.epoch = v.into(), + "pkgdesc" => r.pkgdesc = v.into(), + "url" if !in_pkg => r.url = v.into(), + "arch" => r.arch.push(v.into()), + "license" => r.license.push(v.into()), + "groups" => r.groups.push(v.into()), + "depends" => { + r.depends.push(v.into()); + if let Some(p) = pkg { + if let Some((_, d)) = r.pkg_depends.iter_mut().find(|(n, _)| n == p) { + d.push(v.into()); + } + } + } + "makedepends" => r.makedepends.push(v.into()), + "checkdepends" => r.checkdepends.push(v.into()), + "optdepends" => r.optdepends.push(v.into()), + "provides" => r.provides.push(v.into()), + "conflicts" => r.conflicts.push(v.into()), + "source" => r.source.push(v.into()), + "sha256sums" => r.sha256sums.push(v.into()), + "b2sums" => r.b2sums.push(v.into()), + "validpgpkeys" => r.validpgpkeys.push(v.into()), + "options" => r.options.push(v.into()), + "backup" => r.backup.push(v.into()), + "install" => r.install = Some(v.into()), + _ => {} + } +} + +/// Minimal `PKGBUILD` variable reader: top-level `var=value` and `var=(...)` +/// assignments, including arrays spanning several lines and quoted elements. +/// +/// This is a fallback for recipes without `.SRCINFO`; it deliberately does not +/// try to evaluate bash. Anything it cannot read is reported, not guessed. +pub fn parse_pkgbuild(text: &str) -> Result<Recipe> { + let vars = pkgbuild_vars(text); + let mut r = Recipe::default(); + let get = |k: &str| vars.get(k).cloned().unwrap_or_default(); + r.pkgbase = get("pkgbase").into_iter().next().unwrap_or_default(); + if r.pkgbase.is_empty() { + // A PKGBUILD without pkgbase emits one package named pkgname[0]. + r.pkgbase = get("pkgname").into_iter().next().unwrap_or_default(); + } + if r.pkgbase.is_empty() { + return Err(Error::invalid("PKGBUILD declares no pkgbase or pkgname")); + } + r.pkgver = get("pkgver").into_iter().next().unwrap_or_default(); + r.pkgrel = get("pkgrel").into_iter().next().unwrap_or_default(); + r.epoch = get("epoch").into_iter().next().unwrap_or_default(); + if r.epoch.is_empty() { + r.epoch = "0".into(); + } + if r.pkgver.is_empty() { + return Err(Error::invalid("PKGBUILD declares no pkgver")); + } + if r.pkgrel.is_empty() { + r.pkgrel = "1".into(); + } + r.pkgdesc = get("pkgdesc").into_iter().next().unwrap_or_default(); + r.url = get("url").into_iter().next().unwrap_or_default(); + r.arch = get("arch"); + r.license = get("license"); + r.groups = get("groups"); + r.depends = get("depends"); + r.makedepends = get("makedepends"); + r.checkdepends = get("checkdepends"); + r.optdepends = get("optdepends"); + r.provides = get("provides"); + r.conflicts = get("conflicts"); + r.source = get("source"); + r.sha256sums = get("sha256sums"); + r.b2sums = get("b2sums"); + r.validpgpkeys = get("validpgpkeys"); + r.options = get("options"); + r.backup = get("backup"); + r.install = get("install").into_iter().next(); + let pkgnames = get("pkgname"); + r.pkgnames = if pkgnames.is_empty() { + vec![r.pkgbase.clone()] + } else { + pkgnames.clone() + }; + r.pkg_depends = r + .pkgnames + .iter() + .map(|n| (n.clone(), r.depends.clone())) + .collect(); + r.skipgpcheck = text.contains("--skippgpcheck"); + r.pkgbuild = text.to_string(); + r.source_entries = parse_source_entries(&r.source)?; + Ok(r) +} + +/// Extract top-level assignments from a PKGBUILD. +fn pkgbuild_vars(text: &str) -> BTreeMap<String, Vec<String>> { + let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new(); + let mut lines = text.lines().peekable(); + while let Some(line) = lines.next() { + let t = line.trim_start(); + if t.starts_with('#') || t.is_empty() { + continue; + } + // Stop at the first function definition: variables inside functions are + // not part of the recipe metadata we diff. + if t.contains("()") && t.contains('{') { + break; + } + let Some((name, rest)) = split_assign(t) else { continue }; + let rest = rest.trim(); + if let Some(inner) = rest.strip_prefix('(') { + // Array: may close on this line or later ones. + let mut buf = String::from(inner); + while !buf.contains(')') { + match lines.next() { + Some(l) => { + buf.push(' '); + buf.push_str(l.trim()); + } + None => break, + } + } + let inner = buf.split(')').next().unwrap_or(&buf).to_string(); + out.entry(name).or_default().extend(split_array_elements(&inner)); + } else { + let v = unquote(rest); + if !v.is_empty() { + out.entry(name).or_default().push(v); + } + } + } + out +} + +/// `name=value` where the line is an assignment (no spaces before `=`). +fn split_assign(t: &str) -> Option<(String, String)> { + let (name, rest) = t.split_once('=')?; + let name = name.trim(); + if name.is_empty() + || !name + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + { + return None; + } + // `foo[1]=x` and similar are not metadata. + if name.contains('[') { + return None; + } + Some((name.to_string(), rest.to_string())) +} + +fn unquote(s: &str) -> String { + let s = s.trim(); + let s = s.strip_prefix('"').unwrap_or(s); + let s = s.strip_suffix('"').unwrap_or(s); + let s = s.strip_prefix('\'').unwrap_or(s); + s.strip_suffix('\'').unwrap_or(s).to_string() +} + +/// Split `(a "b c" 'd e')` into elements. +fn split_array_elements(s: &str) -> Vec<String> { + let mut out = Vec::new(); + let mut cur = String::new(); + let mut quote: Option<char> = None; + let mut pushed = false; + for c in s.chars() { + match quote { + Some(q) => { + if c == q { + quote = None; + } else { + cur.push(c); + } + } + None => match c { + '\'' | '"' => quote = Some(c), + c if c.is_whitespace() => { + if !cur.is_empty() { + out.push(std::mem::take(&mut cur)); + } + pushed = true; + } + c => { + cur.push(c); + pushed = false; + } + }, + } + } + let _ = pushed; + if !cur.is_empty() { + out.push(cur); + } + out.into_iter().filter(|e| !e.is_empty()).collect() +} + +/// Parse `source=()` entries into structured form (§5.2 needs the VCS refs, +/// §5.3 needs the kind of each entry). +pub fn parse_source_entries(list: &[String]) -> Result<Vec<SourceEntry>> { + let mut out = Vec::new(); + for (index, raw) in list.iter().enumerate() { + let s = raw.trim(); + if s.is_empty() { + return Err(Error::invalid("empty source entry")); + } + // `filename::url` (filename first, per makepkg). + let (filename, url) = match s.split_once("::") { + Some((f, u)) => (Some(f.to_string()), u.to_string()), + None => (None, s.to_string()), + }; + let (url, frag) = match url.split_once('#') { + Some((u, f)) => (u.to_string(), Some(f.to_string())), + None => (url.clone(), None), + }; + let (vcs, clean) = match url.split_once('+') { + Some((scheme, rest)) if ["git", "svn", "hg", "bzr", "fossil"].contains(&scheme) => { + (Some(scheme.to_string()), rest.to_string()) + } + _ => (None, url.clone()), + }; + let mut commit = None; + let mut tag = None; + let mut branch = None; + if let Some(f) = frag { + for pair in f.split('&') { + let (k, v) = match pair.split_once('=') { + Some((k, v)) => (k, v), + None => continue, + }; + match k { + "commit" => commit = Some(v.to_string()), + "tag" => tag = Some(v.to_string()), + "branch" => branch = Some(v.to_string()), + _ => {} + } + } + } + let local = vcs.is_none() && !clean.contains("://"); + let filename = filename.or_else(|| { + if local { + clean.rsplit('/').next().map(|s| s.to_string()) + } else { + None + } + }); + out.push(SourceEntry { + index, + url: clean, + filename, + commit, + tag, + branch, + vcs, + local, + }); + } + Ok(out) +} + +/// Build a recipe from a materialized AUR tree. +/// +/// `.SRCINFO` wins when present — it is what `makepkg` itself reports and every +/// real AUR repo ships it. Otherwise we fall back to reading the `PKGBUILD`. +pub fn recipe_from_tree(files: &BTreeMap<String, String>) -> Result<Recipe> { + let pkgbuild_path = files + .keys() + .find(|k| k.ends_with("PKGBUILD")) + .cloned() + .ok_or_else(|| Error::invalid("snapshot tree contains no PKGBUILD"))?; + let pkgbuild = files.get(&pkgbuild_path).cloned().unwrap_or_default(); + let mut r = match files.iter().find(|(k, _)| k.ends_with(".SRCINFO")) { + Some((_, srcinfo)) => parse_srcinfo(srcinfo)?, + None => parse_pkgbuild(&pkgbuild)?, + }; + if r.pkgbuild.is_empty() { + r.pkgbuild = pkgbuild; + } + if r.pkgbase.is_empty() { + return Err(Error::invalid("recipe has no pkgbase")); + } + Ok(r) +} + +/// Text files we render diffs for (§6 "recipe diff" panel). +pub fn is_diffable(path: &str) -> bool { + let ext = path.rsplit('.').next().unwrap_or(""); + !matches!( + ext, + "png" | "jpg" | "gif" | "ico" | "pdf" | "gz" | "zst" | "xz" | "bz2" | "zip" | "deb" | "rpm" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pkgbuild_arrays_span_lines_and_quotes() { + let r = parse_pkgbuild( + r#"# comment +pkgbase=foo +pkgver=1.0 +pkgrel=2 +pkgdesc="a package" +arch=(x86_64) +depends=('glibc' openssl + zlib) +source=(git+https://example.invalid/foo.git + fix.patch::https://example.invalid/fix.patch) +sha256sums=('SKIP' 'abc') +build() { + local pkgver=not-this +} +"#, + ) + .unwrap(); + assert_eq!(r.pkgbase, "foo"); + assert_eq!(r.full_version(), "1.0-2"); + assert_eq!(r.depends, vec!["glibc", "openssl", "zlib"]); + assert_eq!(r.source.len(), 2); + assert_eq!(r.sha256sums, vec!["SKIP", "abc"]); + assert_eq!(r.pkgnames, vec!["foo"]); + } + + #[test] + fn source_entries_carry_kind_and_refs() { + let e = parse_source_entries(&[ + "git+https://github.com/foo/bar.git#commit=deadbeef".into(), + "git+https://github.com/foo/bar.git#branch=next".into(), + "hg+https://example.invalid/x".into(), + "name::https://example.invalid/file.tar.gz".into(), + "local.patch".into(), + ]) + .unwrap(); + assert_eq!(e[0].vcs.as_deref(), Some("git")); + assert_eq!(e[0].commit.as_deref(), Some("deadbeef")); + assert_eq!(e[0].url, "https://github.com/foo/bar.git"); + assert_eq!(e[1].branch.as_deref(), Some("next")); + assert_eq!(e[2].vcs.as_deref(), Some("hg")); + assert_eq!(e[3].filename.as_deref(), Some("name")); + assert!(!e[3].local); + assert!(e[4].local); + assert_eq!(e[4].filename.as_deref(), Some("local.patch")); + } + + #[test] + fn srcinfo_sections_describe_split_pkgbases() { + let r = parse_srcinfo( + "pkgbase = foo\n\tpkgver = 1.0\n\tpkgrel = 1\n\tmakedepends = cmake\n\tsource = x.tar\n\tsha256sums = SKIP\npkgname = foo\n\tdepends = glibc\npkgname = foo-lua\n\tdepends = lua\n", + ) + .unwrap(); + assert_eq!(r.pkgbase, "foo"); + assert_eq!(r.pkgnames, vec!["foo", "foo-lua"]); + assert_eq!(r.makedepends, vec!["cmake"]); + assert_eq!(r.pkg_depends[1].1, vec!["lua"]); + } + + #[test] + fn a_recipe_without_a_version_is_an_error_not_a_guess() { + assert!(parse_pkgbuild("pkgbase=foo\n").is_err()); + } +} diff --git a/src/review/approve.rs b/src/review/approve.rs new file mode 100644 index 0000000..b62adec --- /dev/null +++ b/src/review/approve.rs @@ -0,0 +1,267 @@ +//! Approval semantics (§7.1, §7.1a, §7.2, §7.4). +//! +//! Rule of the system: **we build exactly what was displayed, or nothing.** +//! The approve POST carries the `identity_hash` and `diff_digest` that were +//! rendered; if either has moved under the reviewer, the approval is refused +//! with a conflict (HTTP 409) and a re-render, never silently retargeted. + +use rusqlite::OptionalExtension; + +use crate::db::{self, *}; +use crate::error::{Error, Result}; +use crate::time; + +/// Why an approval was refused (§7.1a). Rendered as HTTP 409 with the current +/// diff, plus a CLI message. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Stale { + NotPending { state: String }, + Identity { expected: String, actual: String }, + Diff { expected: String, actual: String }, + Base { expected: Option<i64>, actual: Option<i64> }, +} + +impl std::fmt::Display for Stale { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Stale::NotPending { state } => write!(f, "review is no longer pending (state: {state})"), + Stale::Identity { expected, actual } => write!( + f, + "the candidate changed while you were looking: you were shown {expected}, it is now {actual}" + ), + Stale::Diff { expected, actual } => write!( + f, + "the diff changed while you were looking (shown {expected}, now {actual})" + ), + Stale::Base { .. } => write!( + f, + "a newer version was accepted since this review was opened" + ), + } + } +} + +#[derive(Debug, Clone)] +pub struct Approval { + pub id: i64, + pub candidate_id: i64, + pub base_release_id: Option<i64>, + pub decision: String, + pub diff_digest: String, + pub identity_hash: String, +} + +/// Approve a candidate. Returns the approval row on success, or the reason the +/// approval was refused. +pub fn approve( + db: &Db, + actor: &str, + candidate_id: i64, + identity_hash: &str, + diff_digest: &str, + note: Option<&str>, +) -> std::result::Result<Approval, Stale> { + let actor = actor.to_string(); + let ih = identity_hash.to_string(); + let dd = diff_digest.to_string(); + let note = note.map(|s| s.to_string()); + let at = time::now(); + + db.writer.tx(move |tx| -> Result<std::result::Result<Approval, Stale>> { + type CandidateState = (i64, String, String, Option<i64>, Option<i64>, String, String); + let row: Option<CandidateState> = tx + .query_row( + "SELECT c.id, c.state, c.identity_hash, c.base_release_id, p.current_accepted_release_id, + c.risk_level, b.name + FROM candidate c JOIN pkgbase p ON p.id = c.pkgbase_id + WHERE c.id = ?1", + rusqlite::params![candidate_id], + |r| { + Ok(( + r.get(0)?, + r.get(1)?, + r.get(2)?, + r.get(3)?, + r.get(4)?, + r.get(5)?, + r.get(6)?, + )) + }, + ) + .optional()?; + let (id, state, actual_identity, base, current_base, risk, _pkgbase) = + row.ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?; + + // 1. still open + if state != candidate_state::PENDING { + return Ok(Err(Stale::NotPending { state })); + } + // 2. same candidate bytes + if actual_identity != ih { + return Ok(Err(Stale::Identity { expected: ih.clone(), actual: actual_identity })); + } + // 3. same rendered diff + let stored_diff: String = tx.query_row( + "SELECT diff_digest FROM candidate WHERE id=?1", + rusqlite::params![id], + |r| r.get(0), + )?; + if stored_diff != dd { + return Ok(Err(Stale::Diff { expected: dd.clone(), actual: stored_diff })); + } + // 4. base is still the accepted release (I2, end to end) + if base != current_base { + return Ok(Err(Stale::Base { expected: base, actual: current_base })); + } + + tx.execute( + "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level, + diff_digest, identity_hash, note) + VALUES (?1,?2,?3,'approved',?4,?5,?6,?7)", + rusqlite::params![id, base, at, risk, dd, ih, note], + )?; + let approval_id = tx.last_insert_rowid(); + tx.execute( + "UPDATE candidate SET state='approved', resolved_at=?1 WHERE id=?2", + rusqlite::params![at, id], + )?; + let pkgbase_id: i64 = tx.query_row( + "SELECT pkgbase_id FROM candidate WHERE id=?1", + rusqlite::params![id], + |r| r.get(0), + )?; + tx.execute( + "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) + VALUES (?1,'human',?2,'approve','candidate',?3,?4)", + rusqlite::params![ + at, + actor, + id.to_string(), + serde_json::json!({"approval": approval_id, "identity": ih, "pkgbase_id": pkgbase_id}) + .to_string() + ], + )?; + Ok(Ok(Approval { + id: approval_id, + candidate_id: id, + base_release_id: base, + decision: "approved".into(), + diff_digest: dd, + identity_hash: ih, + })) + }) + .map_err(|e| Stale::NotPending { state: e.to_string() })? +} + +/// Reject a candidate. Rejection is remembered per identity so the watcher stops +/// nagging about the same version (§7.1), and can be re-opened later. +pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> { + let actor = actor.to_string(); + let note = note.to_string(); + let at = time::now(); + db.writer.tx(move |tx| { + let state: String = tx + .query_row("SELECT state FROM candidate WHERE id=?1", rusqlite::params![candidate_id], |r| r.get(0)) + .optional()? + .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?; + if state != candidate_state::PENDING { + return Err(Error::conflict(format!("candidate is {state}, not pending"))); + } + let identity: String = tx.query_row( + "SELECT identity_hash FROM candidate WHERE id=?1", + rusqlite::params![candidate_id], + |r| r.get(0), + )?; + tx.execute( + "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level, + diff_digest, identity_hash, note) + SELECT id, base_release_id, ?1, 'rejected', risk_level, diff_digest, ?2, ?3 + FROM candidate WHERE id=?4", + rusqlite::params![at, identity, note, candidate_id], + )?; + tx.execute( + "UPDATE candidate SET state='rejected', resolved_at=?1 WHERE id=?2", + rusqlite::params![at, candidate_id], + )?; + tx.execute( + "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) + VALUES (?1,'human',?2,'reject','candidate',?3,?4)", + rusqlite::params![at, actor, candidate_id.to_string(), serde_json::json!({"note": note}).to_string()], + )?; + Ok(()) + }) +} + +/// §7.4 bulk decision. High-risk items are refused unless confirmed individually. +pub fn bulk( + db: &Db, + actor: &str, + items: &[(i64, String, String)], // (candidate_id, identity_hash, diff_digest) + decision: &str, + confirm_high_risk: bool, +) -> Result<Vec<std::result::Result<Approval, Stale>>> { + let mut out = Vec::new(); + for (id, ih, dd) in items { + let risk: String = db.read(|c| { + Ok(c.query_row( + "SELECT risk_level FROM candidate WHERE id=?1", + rusqlite::params![id], + |r| r.get(0), + ) + .optional()?) + })? + .unwrap_or_default(); + if decision == "approve" && risk == "high" && !confirm_high_risk { + out.push(Err(Stale::NotPending { + state: "high-risk: needs individual confirmation".into(), + })); + continue; + } + out.push(match decision { + "approve" => approve(db, actor, *id, ih, dd, Some("bulk")), + "reject" => reject(db, actor, *id, "bulk") + .map(|_| Approval { id: 0, candidate_id: *id, base_release_id: None, decision: "rejected".into(), diff_digest: dd.clone(), identity_hash: ih.clone() }) + .map_err(|e| Stale::NotPending { state: e.to_string() }), + other => Err(Stale::NotPending { state: format!("unknown decision {other}") }), + }); + } + Ok(out) +} + +/// The approval behind a candidate, if any. +pub fn approval_for(db: &Db, candidate_id: i64) -> Result<Option<(i64, String)>> { + db.read(|c| { + Ok(c.query_row( + "SELECT id, decision FROM approval WHERE candidate_id=?1", + rusqlite::params![candidate_id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()?) + }) +} + +/// Withdraw a published release (§9 `repo-remove` path, decision 23: warns, +/// does not block). +pub fn withdraw(db: &Db, actor: &str, release_id: i64, reason: &str) -> Result<()> { + let actor = actor.to_string(); + let reason = reason.to_string(); + let at = time::now(); + db.writer.tx(move |tx| { + tx.execute("UPDATE release SET state='withdrawn' WHERE id=?1", rusqlite::params![release_id])?; + tx.execute( + "UPDATE package SET state='removed' WHERE release_id=?1", + rusqlite::params![release_id], + )?; + tx.execute( + "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) + VALUES (?1,'human',?2,'withdraw','release',?3,?4)", + rusqlite::params![at, actor, release_id.to_string(), serde_json::json!({"reason": reason}).to_string()], + )?; + Ok(()) + }) +} + +/// The pkgbase's accepted release pointer, exposed for callers that need it. +pub fn current_accepted(db: &Db, pkgbase: &str) -> Result<Option<ReleaseRow>> { + db::accepted_release(db, pkgbase) +} diff --git a/src/review/candidates.rs b/src/review/candidates.rs new file mode 100644 index 0000000..4dc6c4f --- /dev/null +++ b/src/review/candidates.rs @@ -0,0 +1,293 @@ +//! Candidate creation and the collapse-in-place rule (§7.1). +//! +//! One review object per pkgbase at a time. A newer detection **collapses into** +//! the open review rather than queueing beside it, and the review's `base` is +//! fixed at creation to the pkgbase's `current_accepted_release` — that is what +//! makes "diff against the last accepted version, never the last seen one" (I2) +//! true no matter how many detections arrive while nobody is looking. + +use rusqlite::OptionalExtension; + +use crate::db::{self, *}; +use crate::error::Result; +use crate::time; + +#[derive(Debug, Clone)] +pub struct NewCandidate { + pub snapshot_id: i64, + pub epoch: String, + pub pkgver: String, + pub pkgrel: String, + pub upstream_pins_json: String, + pub source_digests_json: String, + pub identity_hash: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Upsert { + /// A new review row was opened. + Created { id: i64, kind: String }, + /// The open review was updated in place; no new row, `base` untouched (I7). + Collapsed { id: i64, revision: i64 }, + /// A human had already seen the old diff, so it was frozen as `superseded` + /// and a fresh review opened (decision 8). + Superseded { old: i64, new: i64 }, + /// This exact identity was rejected before; do not nag (§7.1). + PreviouslyRejected, + /// Nothing changed relative to what is already recorded. + Unchanged, +} + +/// Insert-or-collapse a candidate for `pb`. +/// +/// `accepted` is the pkgbase's current accepted release, or `None` when this is +/// a first introduction (§7.1b). +pub fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc: &NewCandidate) -> Result<Upsert> { + let kind = if accepted.is_some() { candidate_kind::NEW_VERSION } else { candidate_kind::FIRST_INTRODUCTION }; + let base = accepted.map(|a| a.id); + let pkgbase_id = pb.id; + let nc = nc.clone(); + + db.writer.tx(move |tx| { + let existing: Option<(i64, String, Option<String>, i64)> = tx + .query_row( + "SELECT id, identity_hash, viewed_at, revision FROM candidate + WHERE pkgbase_id=?1 AND state='pending_review'", + rusqlite::params![pkgbase_id], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), + ) + .optional()?; + + if let Some((id, identity, viewed, revision)) = existing { + if identity == nc.identity_hash { + return Ok(Upsert::Unchanged); + } + if viewed.is_none() { + // Collapse in place: same base, no new row, revision bumped. + tx.execute( + "UPDATE candidate SET snapshot_id=?1, epoch=?2, pkgver=?3, pkgrel=?4, + upstream_pins_json=?5, source_digests_json=?6, identity_hash=?7, + revision=?8, detected_at=?9, diff_digest='' + WHERE id=?10", + rusqlite::params![ + nc.snapshot_id, nc.epoch, nc.pkgver, nc.pkgrel, + nc.upstream_pins_json, nc.source_digests_json, nc.identity_hash, + revision + 1, time::now(), id + ], + )?; + return Ok(Upsert::Collapsed { id, revision: revision + 1 }); + } + // A human saw the old diff: freeze it for the audit trail and open a + // fresh review against the same base. + tx.execute( + "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2", + rusqlite::params![time::now(), id], + )?; + let new_id = insert(tx, pkgbase_id, base, kind, &nc)?; + return Ok(Upsert::Superseded { old: id, new: new_id }); + } + + // No open review. A previously rejected identity must not be re-raised. + let rejected: Option<i64> = tx + .query_row( + "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2 AND state='rejected' + ORDER BY id DESC LIMIT 1", + rusqlite::params![pkgbase_id, nc.identity_hash], + |r| r.get(0), + ) + .optional()?; + if rejected.is_some() { + return Ok(Upsert::PreviouslyRejected); + } + // Same identity already approved/recorded: nothing to do. + let same: Option<i64> = tx + .query_row( + "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2 + ORDER BY id DESC LIMIT 1", + rusqlite::params![pkgbase_id, nc.identity_hash], + |r| r.get(0), + ) + .optional()?; + if same.is_some() { + return Ok(Upsert::Unchanged); + } + let id = insert(tx, pkgbase_id, base, kind, &nc)?; + Ok(Upsert::Created { id, kind: kind.to_string() }) + }) +} + +fn insert( + tx: &mut rusqlite::Transaction<'_>, + pkgbase_id: i64, + base: Option<i64>, + kind: &str, + nc: &NewCandidate, +) -> Result<i64> { + tx.execute( + "INSERT INTO candidate (pkgbase_id, base_release_id, kind, snapshot_id, epoch, pkgver, pkgrel, + upstream_pins_json, source_digests_json, identity_hash, state, detected_at) + VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'pending_review',?11)", + rusqlite::params![ + pkgbase_id, base, kind, nc.snapshot_id, nc.epoch, nc.pkgver, nc.pkgrel, + nc.upstream_pins_json, nc.source_digests_json, nc.identity_hash, time::now() + ], + )?; + Ok(tx.last_insert_rowid()) +} + +impl NewCandidate { + /// The `epoch:pkgver-pkgrel` this candidate would publish. + pub fn version(&self) -> String { + crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) + } +} + +/// Mark a candidate `viewed` the first time a human opens it. That timestamp is +/// what decides whether a later detection collapses or supersedes (§7.1). +pub fn mark_viewed(db: &Db, id: i64) -> Result<()> { + let at = time::now(); + db.writer.tx(move |tx| { + tx.execute( + "UPDATE candidate SET viewed_at=?1 WHERE id=?2 AND viewed_at IS NULL", + rusqlite::params![at, id], + )?; + Ok(()) + }) +} + +pub fn pending_candidates(db: &Db) -> Result<Vec<CandidateRow>> { + db.read(|c| { + let mut stmt = c.prepare( + "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, + c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, + c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, + c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name + FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id + WHERE c.state='pending_review' + ORDER BY (c.risk_level='high') DESC, c.detected_at", + )?; + let rows = stmt.query_map([], row_to_candidate)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +pub fn candidate_by_id(db: &Db, id: i64) -> Result<Option<CandidateRow>> { + db.read(|c| { + Ok(c.query_row( + "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, + c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, + c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, + c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name + FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?1", + rusqlite::params![id], + row_to_candidate, + ) + .optional()?) + }) +} + +fn row_to_candidate(r: &rusqlite::Row<'_>) -> rusqlite::Result<CandidateRow> { + Ok(CandidateRow { + id: r.get(0)?, + pkgbase_id: r.get(1)?, + base_release_id: r.get(2)?, + kind: r.get(3)?, + snapshot_id: r.get(4)?, + epoch: r.get(5)?, + pkgver: r.get(6)?, + pkgrel: r.get(7)?, + upstream_pins_json: r.get(8)?, + source_digests_json: r.get(9)?, + identity_hash: r.get(10)?, + diff_digest: r.get(11)?, + revision: r.get(12)?, + viewed_at: r.get(13)?, + risk_level: r.get(14)?, + risk_signals_json: r.get(15)?, + missing_deps_json: r.get(16)?, + state: r.get(17)?, + detected_at: r.get(18)?, + resolved_at: r.get(19)?, + pkgbase: r.get(20)?, + }) +} + +/// Open reviews for a pkgbase (usually zero or one, by I7). +pub fn open_reviews_for(db: &Db, pkgbase_id: i64) -> Result<Vec<CandidateRow>> { + db.read(|c| { + let mut stmt = c.prepare( + "SELECT c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, + c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, + c.diff_digest, c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, + c.missing_deps_json, c.state, c.detected_at, c.resolved_at, b.name + FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id + WHERE c.pkgbase_id=?1 AND c.state='pending_review'", + )?; + let rows = stmt.query_map(rusqlite::params![pkgbase_id], row_to_candidate)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +/// §7.1: a rejection can be re-opened. We retire the rejected row so it stops +/// suppressing the identity, and the next detection opens a fresh review. +pub fn reopen_rejected(db: &Db, id: i64) -> Result<()> { + let at = time::now(); + db.writer.tx(move |tx| { + let n = tx.execute( + "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2 AND state='rejected'", + rusqlite::params![at, id], + )?; + if n == 0 { + return Err(crate::error::Error::conflict("candidate is not rejected")); + } + Ok(()) + }) +} + +/// Record the risk assessment computed at review time. +pub fn set_risk(db: &Db, id: i64, level: &str, signals: &[String]) -> Result<()> { + let lvl = level.to_string(); + let sig = serde_json::to_string(signals)?; + db.writer.tx(move |tx| { + tx.execute( + "UPDATE candidate SET risk_level=?1, risk_signals_json=?2 WHERE id=?3", + rusqlite::params![lvl, sig, id], + )?; + Ok(()) + }) +} + +pub fn set_missing_deps(db: &Db, id: i64, missing: &[String]) -> Result<()> { + let m = serde_json::to_string(missing)?; + db.writer.tx(move |tx| { + tx.execute( + "UPDATE candidate SET missing_deps_json=?1 WHERE id=?2", + rusqlite::params![m, id], + )?; + Ok(()) + }) +} + +pub fn set_diff_digest(db: &Db, id: i64, digest: &str) -> Result<()> { + let d = digest.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE candidate SET diff_digest=?1 WHERE id=?2", rusqlite::params![d, id])?; + Ok(()) + }) +} + +/// Convenience used by the watcher: the accepted release of a pkgbase row. +pub fn accepted_for(db: &Db, pb: &Pkgbase) -> Result<Option<ReleaseRow>> { + match pb.current_accepted_release_id { + Some(id) => db::release_by_id(db, id), + None => Ok(None), + } +} diff --git a/src/review/diff.rs b/src/review/diff.rs new file mode 100644 index 0000000..cfce3fe --- /dev/null +++ b/src/review/diff.rs @@ -0,0 +1,156 @@ +//! Diff rendering (§6). +//! +//! A review is not one diff, it is a panel set, and **every** panel compares what +//! the accepted release recorded against what the candidate records now — never +//! "last seen". The rendered text is hashed into `diff_digest`, which is what +//! makes "we build exactly what was displayed, or nothing" (§7.1a) provable. + +use crate::config::Config; +use crate::db::{self, *}; +use crate::error::Result; +use crate::git; + +#[derive(Debug, Clone)] +pub struct Panel { + pub name: &'static str, + pub title: &'static str, + /// Unified-diff text, or a readable rendering for panels that are not diffs. + pub body: String, +} + +/// Everything a reviewer needs for one candidate. +pub fn panels(cfg: &Config, db: &Db, c: &CandidateRow, base: Option<&ReleaseRow>) -> Result<Vec<Panel>> { + let mut out = Vec::new(); + let snap = db::snapshot_by_id(db, c.snapshot_id)?; + let mirror = std::path::PathBuf::from( + db::get_pkgbase_by_id(db, c.pkgbase_id)? + .and_then(|p| p.mirror_path) + .unwrap_or_else(|| cfg.mirror_path(&c.pkgbase).display().to_string()), + ); + + out.push(version_delta(base, c)); + + if let Some(base) = base { + if let Some(s) = &snap { + let range = format!("{}..{}", base.aur_commit, s.aur_commit); + let body = git::diff(&mirror, &range, &[]).unwrap_or_else(|e| { + format!("(diff unavailable: {e})\n\n--- base {}\n+++ candidate {}", base.aur_commit, s.aur_commit) + }); + out.push(Panel { name: "recipe", title: "Recipe diff", body }); + } + out.push(digest_delta(base, c)); + out.push(pin_delta(base, c)); + } else { + // §7.1b first_introduction: no diff pane. The full recipe is rendered + // readably instead, by the template. + out.push(Panel { + name: "recipe_full", + title: "Full recipe", + body: snap + .map(|s| s.srcinfo_json.clone()) + .unwrap_or_else(|| "(no snapshot)".into()), + }); + } + Ok(out) +} + +fn version_delta(base: Option<&ReleaseRow>, c: &CandidateRow) -> Panel { + let mut body = String::new(); + match base { + Some(b) => { + let (bv, cv) = (b.version(), c.version()); + body.push_str(&format!("{bv} -> {cv}\n")); + let ord = crate::pkgver::vercmp(&bv, &cv); + if b.epoch != c.epoch { + body.push_str(&format!("epoch bump: {} -> {}\n", b.epoch, c.epoch)); + } + if b.pkgrel != c.pkgrel && b.pkgver == c.pkgver { + body.push_str(&format!("pkgrel change: {} -> {}\n", b.pkgrel, c.pkgrel)); + } + if crate::pkgver::is_downgrade(&bv, &cv) { + body.push_str("DOWNGRADE: AUR now offers a lower version than we serve\n"); + } + let _ = ord; + } + None => body.push_str(&format!("first introduction: {}\n", c.version())), + } + Panel { name: "version", title: "Version delta", body } +} + +fn digest_delta(base: &ReleaseRow, c: &CandidateRow) -> Panel { + let mut body = String::new(); + let old: Vec<SourceDigest> = base.digests(); + let new: Vec<SourceDigest> = c.digests(); + for n in &new { + match old.iter().find(|o| o.index == n.index) { + Some(o) if o.digest != n.digest => { + body.push_str(&format!( + "! [{}] {} {} -> {}\n", + n.index, n.url, short(&o.digest), short(&n.digest) + )); + } + Some(_) => body.push_str(&format!(" [{}] {} unchanged\n", n.index, n.url)), + None => body.push_str(&format!( + "+ [{}] {} NEW ({}{})\n", + n.index, + n.url, + n.kind, + if n.skip_declared { ", sha256sums=SKIP" } else { "" } + )), + } + } + for o in &old { + if !new.iter().any(|n| n.index == o.index) { + body.push_str(&format!("- [{}] {} REMOVED\n", o.index, o.url)); + } + } + Panel { name: "digests", title: "Source digest delta", body } +} + +fn pin_delta(base: &ReleaseRow, c: &CandidateRow) -> Panel { + let mut body = String::new(); + let old: Vec<UpstreamPin> = base.pins(); + let new: Vec<UpstreamPin> = c.pins(); + if old.is_empty() && new.is_empty() { + body.push_str("no VCS sources\n"); + } + for n in &new { + match old.iter().find(|o| o.index == n.index) { + Some(o) if o.commit != n.commit => { + body.push_str(&format!( + "! [{}] {} {} -> {} (branch {})\n", + n.index, n.url, short(&o.commit), short(&n.commit), n.branch.as_deref().unwrap_or("?") + )); + } + Some(_) => body.push_str(&format!(" [{}] {} unchanged\n", n.index, n.url)), + None => body.push_str(&format!("+ [{}] {} at {}\n", n.index, n.url, short(&n.commit))), + } + } + Panel { name: "upstream", title: "Upstream delta", body } +} + +fn short(s: &str) -> String { + if s.len() > 12 { s[..12].to_string() } else { s.to_string() } +} + +/// Flatten the rendered panels into one canonical string. +pub fn render_text(ps: &[Panel]) -> String { + let mut s = String::new(); + for p in ps { + s.push_str(&format!("### {}\n{}\n", p.title, p.body)); + } + s +} + +/// `diff_digest`: hash of the exact rendered diff the human was shown (§7.2). +pub fn diff_digest(ps: &[Panel]) -> String { + crate::hash::hex_str(&render_text(ps)) +} + +/// The recipe text a reviewer reads for a first introduction (§7.1b). +pub fn full_recipe_text(db: &Db, c: &CandidateRow) -> Result<String> { + let snap = db::snapshot_by_id(db, c.snapshot_id)?; + let snap = snap.ok_or_else(|| crate::error::Error::not_found("snapshot missing"))?; + let r: Recipe = serde_json::from_str(&snap.srcinfo_json).unwrap_or_default(); + Ok(r.pkgbuild) +} diff --git a/src/review/mod.rs b/src/review/mod.rs new file mode 100644 index 0000000..25abca8 --- /dev/null +++ b/src/review/mod.rs @@ -0,0 +1,8 @@ +//! Review lifecycle: candidate creation and collapse-in-place (§7.1), the +//! approval record (§7.2), diffing (§6) and risk scoring (§6). + +pub mod approve; +pub mod candidates; +pub mod diff; + +pub use candidates::{upsert_candidate, NewCandidate, Upsert}; diff --git a/src/watch/detect.rs b/src/watch/detect.rs new file mode 100644 index 0000000..e00a2f9 --- /dev/null +++ b/src/watch/detect.rs @@ -0,0 +1,288 @@ +//! Detection: the recipe watcher pass for one pkgbase (§5.1, §5.2, §5.3). +//! +//! The decision that matters is *what counts as a change*. A candidate exists +//! only if something **publishable** changed — if the version string is +//! unchanged, `pacman` cannot offer an upgrade, so there is nothing to approve. +//! Those events become `notice` rows instead, and are never silently dropped +//! (I11). + +use crate::config::Config; +use crate::db::{self, *}; +use crate::error::Result; +use crate::pkgver; +use crate::recipe::recipe_from_tree; +use crate::review::candidates::{upsert_candidate, NewCandidate, Upsert}; +use crate::time; +use crate::watch::digests::resolve_sources; +use crate::watch::mirror::{read_tree, sync_mirror, Sync}; + +#[derive(Debug, Clone)] +pub enum Outcome { + /// Nothing moved at all. + NoChange, + /// A new review was opened. + Candidate { id: i64, kind: String }, + /// The open review was updated in place (I7). + Collapsed { id: i64, revision: i64 }, + /// The seen-but-unresolved review was frozen and a new one opened. + Superseded { old: i64, new: i64 }, + /// Identical to something a human already rejected. + PreviouslyRejected, + /// Something changed but nothing is publishable (I11). + Notice { kind: String, detail: serde_json::Value }, + /// The package vanished from AUR. + Gone, + /// Detection could not complete; the watcher will back off. + Blocked(String), +} + +#[derive(Debug, Clone)] +pub struct CheckReport { + pub pkgbase: String, + pub head: String, + pub outcome: Outcome, +} + +/// One full detection pass for a subscribed pkgbase. +pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> { + let pb = get_pkgbase(db, name)? + .ok_or_else(|| crate::error::Error::not_found(format!("pkgbase {name}")))?; + let sync = sync_mirror(cfg, db, name, &pb.aur_url)?; + let head = match &sync { + Sync::Gone => { + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::DELETED, + "high", + serde_json::json!({"aur_url": pb.aur_url, "note": "repository no longer exists"}), + )?; + db::set_subscription_state(&db.writer, name, subscription_state::ORPHANED)?; + return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Gone }); + } + // The cheap poll saved us a fetch, but we still have to look: a source + // can change its bytes without the recipe moving at all, and that is the + // digest-drift case §5.3 calls the single most valuable detection. + Sync::Unchanged { head } => head.clone(), + Sync::Fetched { head, .. } | Sync::Cloned { head } => head.clone(), + }; + let r = analyse(cfg, db, &pb, &head); + schedule_next(db, name, &pb); + r +} + +fn schedule_next(db: &Db, name: &str, pb: &Pkgbase) { + let interval = db + .read(|c| { + use rusqlite::OptionalExtension; + Ok(c.query_row( + "SELECT poll_interval_secs FROM subscription WHERE pkgbase=?1", + rusqlite::params![name], + |r| r.get::<_, Option<i64>>(0), + ) + .optional()?) + }) + .ok() + .flatten() + .flatten() + .unwrap_or(crate::db::setting_i64(db, "poll_interval", 86400)); + let next = time::secs_ahead(interval); + let _ = db::note_check(&db.writer, name, &next, None); + let _ = pb; +} + +/// Everything after the mirror is up to date. +fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckReport> { + let mirror = cfg.mirror_path(&pb.name); + let report = |outcome: Outcome| CheckReport { pkgbase: pb.name.clone(), head: head.to_string(), outcome }; + + // §16 mirror divergence: if the accepted pin has vanished from our own + // mirror, hard-fail this pkgbase rather than silently re-pinning. + let accepted = crate::review::candidates::accepted_for(db, pb)?; + if let Some(a) = &accepted { + if !crate::git::has_commit(&mirror, &a.aur_commit) { + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::DELETED, + "high", + serde_json::json!({"mirror_divergence": a.aur_commit}), + )?; + return Ok(report(Outcome::Blocked(format!( + "accepted pin {} missing from local mirror", + a.aur_commit + )))); + } + } + + let tree = read_tree(&mirror, head)?; + let recipe = recipe_from_tree(&tree.files)?; + let recipe_hash = tree.recipe_hash(); + let digests = resolve_sources(cfg, db, &mirror, head, &tree, &recipe, &[])?; + let pins: Vec<UpstreamPin> = Vec::new(); // P1 fills this in for VCS sources + + let identity = Identity { + aur_commit: head.to_string(), + epoch: recipe.epoch.clone(), + pkgver: recipe.pkgver.clone(), + pkgrel: recipe.pkgrel.clone(), + upstream_pins: pins.clone(), + source_digests: digests.clone(), + }; + let identity_hash = identity.hash(); + let snap_id = db::put_snapshot( + &db.writer, + pb.id, + head, + &recipe_hash, + &serde_json::to_string(&recipe)?, + &tree.json_list(), + )?; + + let nc = NewCandidate { + snapshot_id: snap_id, + epoch: recipe.epoch.clone(), + pkgver: recipe.pkgver.clone(), + pkgrel: recipe.pkgrel.clone(), + upstream_pins_json: serde_json::to_string(&pins)?, + source_digests_json: serde_json::to_string(&digests)?, + identity_hash: identity_hash.clone(), + }; + + let Some(base) = accepted else { + // §7.1b: nothing to diff against — this is a first introduction. + return match upsert_candidate(db, pb, None, &nc)? { + Upsert::Created { id, kind } => Ok(report(Outcome::Candidate { id, kind })), + other => Ok(report(outcome_of(other))), + }; + }; + + // Same identity as what we already serve: nothing happened. + if base.aur_commit == head + && base.epoch == nc.epoch + && base.pkgver == nc.pkgver + && base.pkgrel == nc.pkgrel + && base.upstream_pins_json == nc.upstream_pins_json + && base.source_digests_json == nc.source_digests_json + { + return Ok(report(Outcome::NoChange)); + } + + let new_version = nc.version(); + let publishable = pkgver::vercmp(&base.version(), &new_version) != std::cmp::Ordering::Equal; + + if !publishable { + // §5.2 / §5.3: nothing pacman could offer as an upgrade. Record it + // loudly instead of inventing a pkgrel bump. + return Ok(report(non_publishable(db, pb, &base, &nc, &recipe)?)); + } + + if pkgver::is_downgrade(&base.version(), &new_version) { + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::DOWNGRADE, + "warning", + serde_json::json!({"served": base.version(), "aur": new_version}), + )?; + } + + let up = upsert_candidate(db, pb, Some(&base), &nc)?; + Ok(report(outcome_of(up))) +} + +fn outcome_of(up: Upsert) -> Outcome { + match up { + Upsert::Created { id, kind } => Outcome::Candidate { id, kind }, + Upsert::Collapsed { id, revision } => Outcome::Collapsed { id, revision }, + Upsert::Superseded { old, new } => Outcome::Superseded { old, new }, + Upsert::PreviouslyRejected => Outcome::PreviouslyRejected, + Upsert::Unchanged => Outcome::NoChange, + } +} + +/// The version string did not move, so there is no review to open — but the +/// change is recorded, because a silently drifting tarball is exactly the kind +/// of thing that must not be invisible (§5.3). +fn non_publishable( + db: &Db, + pb: &Pkgbase, + base: &ReleaseRow, + nc: &NewCandidate, + recipe: &Recipe, +) -> Result<Outcome> { + let old_digests: Vec<SourceDigest> = base.digests(); + let new_digests: Vec<SourceDigest> = serde_json::from_str(&nc.source_digests_json).unwrap_or_default(); + // A local source is part of the recipe: when its bytes move, that *is* the + // recipe drift, not an integrity event. The integrity alert is specifically + // "the bytes upstream serves no longer match what we built" (§5.3). + let changed_remote: Vec<&SourceDigest> = new_digests + .iter() + .filter(|n| n.kind != "local") + .filter(|n| match old_digests.iter().find(|o| o.index == n.index) { + Some(o) => o.digest != n.digest, + None => true, + }) + .collect(); + let digest_changed = !changed_remote.is_empty(); + let old_pins: Vec<UpstreamPin> = base.pins(); + let new_pins: Vec<UpstreamPin> = serde_json::from_str(&nc.upstream_pins_json).unwrap_or_default(); + let pins_changed = old_pins != new_pins; + + if digest_changed { + // The single most valuable detection in the system: the artifact in the + // index was built from bytes upstream no longer serves, and the version + // string is unchanged. An approval would be useless (approving it would + // not let us publish anything), so this is an alert, not a review. + let changed: Vec<serde_json::Value> = changed_remote + .iter() + .map(|n| { + serde_json::json!({"index": n.index, "url": n.url, + "old": old_digests.iter().find(|o| o.index == n.index) + .map(|o| o.digest.clone()).unwrap_or_default(), + "new": n.digest}) + }) + .collect(); + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::INTEGRITY_ALERT, + "high", + serde_json::json!({ + "version": nc.version(), + "changed": changed, + "message": "the artifact in your index was built from bytes upstream no longer serves; the version string is unchanged", + }), + )?; + return Ok(Outcome::Notice { kind: notice_kind::INTEGRITY_ALERT.into(), detail: serde_json::json!({"changed": changed}) }); + } + if pins_changed { + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::PIN_DRIFT, + "info", + serde_json::json!({ + "version": nc.version(), + "message": "upstream moved; pkgver unchanged, nothing publishable", + }), + )?; + return Ok(Outcome::Notice { kind: notice_kind::PIN_DRIFT.into(), detail: serde_json::json!({}) }); + } + // The recipe drifted under a static version: the maintainer probably forgot + // to bump pkgrel, and the user should know. + let _ = recipe; + db::put_notice_once( + &db.writer, + pb.id, + notice_kind::RECIPE_DRIFT, + "warning", + serde_json::json!({ + "version": nc.version(), + "accepted_aur_commit": base.aur_commit, + "aur_commit": "moved", + "message": "recipe changed but the version did not; the maintainer may have forgotten to bump pkgrel", + }), + )?; + Ok(Outcome::Notice { kind: notice_kind::RECIPE_DRIFT.into(), detail: serde_json::json!({}) }) +} 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() +} diff --git a/src/watch/mirror.rs b/src/watch/mirror.rs new file mode 100644 index 0000000..989b968 --- /dev/null +++ b/src/watch/mirror.rs @@ -0,0 +1,119 @@ +//! The local AUR git mirror (§5.1). +//! +//! Clone, don't scrape. The mirror is load-bearing rather than a cache: every +//! build materializes its recipe from it at the pinned commit and never asks +//! the network for a recipe (§5.1a), so losing it would mean losing the ability +//! to reproduce any historical release. + +use std::collections::BTreeMap; +use std::path::Path; + +use crate::config::Config; +use crate::db::{self, Db}; +use crate::error::{Error, Result}; +use crate::git; + +/// Result of a cheap poll. `Unchanged` means we did **not** fetch — the poll is +/// `git ls-remote`, one request per pkgbase (§5.1). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Sync { + /// Remote is gone (deleted from AUR). + Gone, + /// `ls-remote` matched the local tip; no fetch performed. + Unchanged { head: String }, + /// The tip moved; we fetched and now have `head`. + Fetched { head: String, previous: Option<String> }, + /// We had no local mirror yet. + Cloned { head: String }, +} + +/// Ensure a mirror exists and is polled. Updates `pkgbase.aur_head`. +pub fn sync_mirror(cfg: &Config, db: &Db, name: &str, url: &str) -> Result<Sync> { + let mirror = cfg.mirror_path(name); + let known_head = db::get_pkgbase(db, name)?.and_then(|p| p.aur_head.clone()); + + if !mirror.exists() { + git::clone(url, &mirror)?; + let head = git::head(&mirror)?; + record(db, name, &head, &mirror)?; + return Ok(Sync::Cloned { head }); + } + + let remote = match git::ls_remote_head(url)? { + Some(h) => h, + None => return Ok(Sync::Gone), + }; + let local = git::head(&mirror).ok(); + if let Some(l) = &local { + if *l == remote { + return Ok(Sync::Unchanged { head: remote }); + } + } + let head = git::fetch_head(&mirror)?; + record(db, name, &head, &mirror)?; + Ok(Sync::Fetched { head, previous: known_head }) +} + +fn record(db: &Db, name: &str, head: &str, mirror: &Path) -> Result<()> { + let pb = db::get_pkgbase(db, name)?.ok_or_else(|| Error::not_found(format!("pkgbase {name}")))?; + db::set_aur_head(&db.writer, pb.id, head, &mirror.display().to_string()) +} + +/// A materialized snapshot tree: blob ids for hashing, text bodies for parsing +/// and diffing. +#[derive(Debug, Clone)] +pub struct Tree { + /// `(path, git blob id)` for every file in the tree — the input to + /// `recipe_hash`. Covers PKGBUILD, .SRCINFO, *.install and shipped patches + /// (§3): a patch file is part of the recipe. + pub blobs: Vec<(String, String)>, + /// Text bodies, keyed by path. Binary files are omitted from this map but + /// still counted in `blobs`. + pub files: BTreeMap<String, String>, +} + +impl Tree { + pub fn recipe_hash(&self) -> String { + crate::hash::recipe_hash(&self.blobs) + } + pub fn get(&self, suffix: &str) -> Option<&String> { + self.files + .iter() + .find(|(k, _)| k.ends_with(suffix)) + .map(|(_, v)| v) + } + pub fn json_list(&self) -> String { + serde_json::to_string(&self.blobs).unwrap_or_else(|_| "[]".into()) + } +} + +/// Read a commit's tree out of the mirror without touching the network. +pub fn read_tree(mirror: &Path, commit: &str) -> Result<Tree> { + // §16 mirror divergence: if a pin we are asked to read has vanished, that is + // a hard failure, not a silent re-pin. + if !git::has_commit(mirror, commit) { + return Err(Error::fail_closed(format!( + "commit {commit} is missing from the local mirror; history was rewritten" + ))); + } + let blobs = git::ls_tree(mirror, commit)?; + let mut files = BTreeMap::new(); + for (path, _) in &blobs { + let bytes = git::read_blob(mirror, commit, path)?; + if bytes.len() > 4 * 1024 * 1024 || !looks_textual(&bytes) { + continue; + } + files.insert(path.clone(), String::from_utf8_lossy(&bytes).into_owned()); + } + Ok(Tree { blobs, files }) +} + +fn looks_textual(b: &[u8]) -> bool { + !b[..b.len().min(512)].contains(&0) +} + +/// Raw bytes of one file at a commit — used to hash sources shipped in the AUR +/// repo (§5.3 "local file shipped in the AUR repo"). +pub fn read_file(mirror: &Path, commit: &str, path: &str) -> Result<Vec<u8>> { + git::read_blob(mirror, commit, path) +} diff --git a/src/watch/mod.rs b/src/watch/mod.rs new file mode 100644 index 0000000..3f0d217 --- /dev/null +++ b/src/watch/mod.rs @@ -0,0 +1,12 @@ +//! Watchers: AUR recipe mirror (§5.1), upstream VCS probe (§5.2), source digest +//! resolution (§5.3), and the scheduler tick. + +pub mod detect; +pub mod digests; +pub mod mirror; +pub mod scheduler; + +pub use detect::{check_pkgbase, CheckReport, Outcome}; +pub use digests::{cached_path, download_and_cache, resolve_sources, skip_on_non_vcs}; +pub use mirror::{read_tree, sync_mirror, Tree}; +pub use scheduler::spawn_scheduler; diff --git a/src/watch/scheduler.rs b/src/watch/scheduler.rs new file mode 100644 index 0000000..ca42e32 --- /dev/null +++ b/src/watch/scheduler.rs @@ -0,0 +1,71 @@ +//! The scheduler tick (§4: "one tick thread + sweep over `next_check_at`"). +//! +//! Blocking is the right shape here: the tick sleeps between sweeps and each +//! sweep is a sequence of blocking git and HTTP calls. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::thread::JoinHandle; + +use crate::config::Config; +use crate::db::{self, Db}; +use crate::watch::detect::check_pkgbase; + +/// Spawn the watcher tick thread. +pub fn spawn_scheduler(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>) -> JoinHandle<()> { + std::thread::Builder::new() + .name("watcher".into()) + .spawn(move || { + while !stop.load(Ordering::SeqCst) { + let tick = crate::db::setting_i64(&db, "poll_tick", 30); + sweep(&cfg, &db); + // Sleep in small slices so shutdown is prompt. + let mut slept = 0; + while slept < tick && !stop.load(Ordering::SeqCst) { + std::thread::sleep(std::time::Duration::from_secs(1)); + slept += 1; + } + } + }) + .expect("spawn watcher") +} + +/// One sweep over everything that is due. +pub fn sweep(cfg: &Config, db: &Db) -> usize { + let now = crate::time::now(); + let due = match db::due_subscriptions(db, &now) { + Ok(d) => d, + Err(_) => return 0, + }; + let mut n = 0; + for sub in due { + // Mark it checked first so a slow or hanging source cannot make the + // scheduler re-enter it on the next tick. + let interval = sub + .poll_interval_secs + .unwrap_or(crate::db::setting_i64(db, "poll_interval", 86400)); + let _ = db::note_check(&db.writer, &sub.pkgbase, &crate::time::secs_ahead(interval), None); + match check_pkgbase(cfg, db, &sub.pkgbase) { + Ok(report) => { + if matches!(report.outcome, crate::watch::detect::Outcome::Blocked(_)) { + let _ = db::note_check( + &db.writer, + &sub.pkgbase, + &crate::time::secs_ahead(600), + Some(&format!("{:?}", report.outcome)), + ); + } + } + Err(e) => { + let _ = db::note_check( + &db.writer, + &sub.pkgbase, + &crate::time::secs_ahead(600), + Some(&e.to_string()), + ); + } + } + n += 1; + } + n +} |
