summaryrefslogtreecommitdiffstats
path: root/src/review/approve.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/review/approve.rs')
-rw-r--r--src/review/approve.rs267
1 files changed, 267 insertions, 0 deletions
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)
+}