From f586d11f6a1711145ba4804787217a1bab58751d Mon Sep 17 00:00:00 2001 From: aur-build Date: Tue, 17 Nov 2026 21:19:35 +0000 Subject: feat: AUR mirror watcher, recipe parsing, candidate creation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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). --- src/review/candidates.rs | 293 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 293 insertions(+) create mode 100644 src/review/candidates.rs (limited to 'src/review/candidates.rs') 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 { + 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, 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 = 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 = 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, + kind: &str, + nc: &NewCandidate, +) -> Result { + 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> { + 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> { + 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 { + 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> { + 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> { + match pb.current_accepted_release_id { + Some(id) => db::release_by_id(db, id), + None => Ok(None), + } +} -- cgit v1.2.3