diff options
| author | aur-build <aur-build@localhost> | 2026-11-18 17:43:25 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-18 17:43:25 +0000 |
| commit | 7587284ae48fb59c59da33af928322e8a621f4b0 (patch) | |
| tree | 3426d4d3e2319374a387a636468ac247c9743480 /src | |
| parent | f3e4c1496d2ddcdae535132427fdb499181f1695 (diff) | |
| download | aur-build-7587284ae48fb59c59da33af928322e8a621f4b0.tar.gz aur-build-7587284ae48fb59c59da33af928322e8a621f4b0.zip | |
pipeline, db: the correctness minors — fsync, withdrawal, orphans, retry class
m-7. `fsync_file` and `fsync_dir` opened, ignored every error, and returned Ok,
in the module whose entire guarantee is "fsync, then rename". A filesystem that
refused the sync — full, read-only, a network mount that had dropped — still
produced a successful publish whose database might not be on disk. They
propagate now, with the path and the cause.
m-10. `withdraw_release_in` set `state='withdrawn'` unconditionally, so
withdrawing twice reported success the second time while changing nothing, and
withdrawing a release that had never been live did the same. The write is a
compare-and-swap on `state='published'`, and a refusal names the state that was
actually there ("release 1 is withdrawn, not published: nothing to withdraw").
m-16. Artifacts are copied into the served tree before the DB commit, and when
the commit refused they stayed: files no index names, sitting in the directory
consumers download from. `publish` now tracks which files it created (a file
that already existed belongs to the release still being served and is never
touched) and removes them if the publish does not land.
m-14. `is_transient` treated every `Error::Io` as retryable, which made ENOSPC
and EACCES — plain `Io` — into three identical failures and a silent build.
Only the kinds that mean "ask again in a moment" retry now. This turned a test
that had been asserting the bug: it simulated a transient failure by pointing
`makechrootpkg` at a nonexistent path, which is a missing binary, not a flaky
network. That test now asserts the opposite (one attempt, no retries), and a new
one produces a genuinely transient failure the way production does — a `SKIP`
source whose bytes go unreachable after detection, cache dropped, so the
`sources` step fails over the fetch path and retries to the cap.
m-13. `random_hex` read `/dev/urandom` into a zeroed buffer, ignored every
error, and hashed it anyway. Since C-1 the session id is the whole credential,
so a failed read is now a refusal: `new_session()` returns `Option`, and the two
call sites answer 500 rather than mint a token derivable from the clock and a
counter.
m-9. The row-error policy is decided and applied: a row that cannot be read
fails the query instead of vanishing from the result (six `filter_map(|r|
r.ok())` sites, including the reaper's and the claimer's), and `setting_i64`
documents its own policy — absent means default, nonsense means default *and a
complaint*, because a typo that silently does nothing is worse than a knob that
refuses to apply.
Diffstat (limited to 'src')
| -rw-r--r-- | src/db/builds.rs | 7 | ||||
| -rw-r--r-- | src/db/queries.rs | 63 | ||||
| -rw-r--r-- | src/error.rs | 51 | ||||
| -rw-r--r-- | src/http/auth.rs | 28 | ||||
| -rw-r--r-- | src/http/mod.rs | 7 | ||||
| -rw-r--r-- | src/http/routes.rs | 5 | ||||
| -rw-r--r-- | src/pipeline/publish.rs | 136 |
7 files changed, 216 insertions, 81 deletions
diff --git a/src/db/builds.rs b/src/db/builds.rs index c1d65db..4244034 100644 --- a/src/db/builds.rs +++ b/src/db/builds.rs @@ -175,7 +175,7 @@ pub fn reap_expired(db: &Db) -> Result<usize> { AND lease_expires_at IS NOT NULL AND lease_expires_at < ?1", )?; let rows = stmt.query_map(params![now], |r| r.get::<_, String>(0))?; - rows.filter_map(|r| r.ok()).collect() + rows.collect::<rusqlite::Result<Vec<String>>>()? }; for id in &ids { tx.execute( @@ -262,8 +262,7 @@ pub fn requeue_blocked(db: &Db) -> Result<usize> { let mut stmt = tx.prepare("SELECT id, blocked_on_json FROM build WHERE state='blocked_missing_dep'")?; let out = stmt .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))? - .filter_map(|x| x.ok()) - .collect(); + .collect::<rusqlite::Result<Vec<(String, String)>>>()?; out }; let mut n = 0; @@ -559,7 +558,7 @@ pub fn claim_batch(db: &Db, owner: &str, limit: usize, lease_secs: i64) -> Resul ORDER BY priority DESC, created_at LIMIT ?1", )?; let rows = stmt.query_map(params![limit as i64], |r| r.get::<_, String>(0))?; - rows.filter_map(|r| r.ok()).collect() + rows.collect::<rusqlite::Result<Vec<String>>>()? }; for id in &ids { tx.execute( diff --git a/src/db/queries.rs b/src/db/queries.rs index 23b95ec..66bab73 100644 --- a/src/db/queries.rs +++ b/src/db/queries.rs @@ -10,11 +10,16 @@ use crate::time; // ---------------------------------------------------------------- settings -- /// Every setting, for the settings page. +/// +/// Row-error policy, applied everywhere in `db` (m-9): a row that cannot be read +/// fails the query. `filter_map(|r| r.ok())` used to drop such rows silently, +/// which is fine for a page that merely looks incomplete and fatal for the +/// callers that decide what to reap, what to claim, and what is stale. pub fn all_settings(db: &Db) -> Result<Vec<(String, String)>> { db.read(|c| { let mut st = c.prepare("SELECT key, value FROM settings ORDER BY key")?; let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; - Ok(rows.filter_map(|r| r.ok()).collect()) + Ok(rows.collect::<::rusqlite::Result<Vec<_>>>()?) }) } @@ -26,12 +31,27 @@ pub fn setting(db: &Db, key: &str) -> Result<Option<String>> { }) } +/// An integer setting, or `default`. +/// +/// The policy, stated once (m-9): a *missing* setting is normal — the default is +/// the answer, and every knob in `settings` has one. A setting that is present +/// but unparseable, or a read that failed outright, is not normal, and silently +/// returning the default would hide an operator's typo behind a config that +/// looks applied. Both still fall back — these are tuning knobs, and refusing to +/// start over `stage_b_cooldown = 86400x` is worse than using the default — but +/// they fall back out loud. pub fn setting_i64(db: &Db, key: &str, default: i64) -> i64 { - setting(db, key) - .ok() - .flatten() - .and_then(|v| v.parse().ok()) - .unwrap_or(default) + match setting(db, key) { + Ok(None) => default, + Ok(Some(v)) => v.parse().unwrap_or_else(|_| { + eprintln!("settings: {key}={v:?} is not an integer; using default {default}"); + default + }), + Err(e) => { + eprintln!("settings: could not read {key} ({e}); using default {default}"); + default + } + } } pub fn set_setting(writer: &Writer, key: &str, value: &str) -> Result<()> { @@ -506,8 +526,33 @@ const RELEASE_COLS_R: &str = "r.id, r.pkgbase_id, r.candidate_id, r.approval_id, /// Withdraw a published release and remove the packages it served (§9 /// `repo-remove`, decision 23). Runs in the caller's transaction so the removal /// and the audit row that explains it are one fact. +/// Take a release out of the served index (§9, decision 23). +/// +/// Refuses a release that is not currently published (m-10): re-withdrawing used +/// to report success and rewrite nothing, so an operator who clicked twice — or +/// withdrew a release that had never been live — got a green result and no +/// explanation. The write is a compare-and-swap on `state='published'`, and the +/// refusal names the state that was actually there. pub fn withdraw_release_in(tx: &rusqlite::Transaction<'_>, release_id: i64) -> Result<()> { - tx.execute("UPDATE release SET state='withdrawn' WHERE id=?1", params![release_id])?; + let n = tx.execute( + "UPDATE release SET state='withdrawn' WHERE id=?1 AND state='published'", + params![release_id], + )?; + if n == 0 { + let state: Option<String> = tx + .query_row("SELECT state FROM release WHERE id=?1", params![release_id], |r| r.get(0)) + .optional()?; + return Err(match state.as_deref().map(ReleaseState::parse) { + None => Error::not_found(format!("no release {release_id}")), + Some(Some(s)) => Error::conflict(format!( + "release {release_id} is {s}, not published: nothing to withdraw" + )), + Some(None) => Error::invalid(format!( + "release {release_id} has a state outside the state machine: {:?}", + state.unwrap_or_default() + )), + }); + } tx.execute("UPDATE package SET state='removed' WHERE release_id=?1", params![release_id])?; Ok(()) } @@ -853,7 +898,7 @@ pub fn published_world_members(db: &Db) -> Result<Vec<(String, String)>> { WHERE r.state = 'published'", )?; let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; - Ok(rows.filter_map(|r| r.ok()).collect::<Vec<_>>()) + Ok(rows.collect::<::rusqlite::Result<Vec<_>>>()?) }) } @@ -877,7 +922,7 @@ pub fn served_vs_offered_pkgvers(db: &Db) -> Result<Vec<(String, String, String) r.get::<_, Option<String>>(2)?.unwrap_or_default(), )) })?; - Ok(rows.filter_map(|r| r.ok()).collect::<Vec<_>>()) + Ok(rows.collect::<::rusqlite::Result<Vec<_>>>()?) }) } diff --git a/src/error.rs b/src/error.rs index ac47fc8..cf6e567 100644 --- a/src/error.rs +++ b/src/error.rs @@ -68,11 +68,56 @@ impl Error { Error::Transient(s.to_string()) } - /// True when a retry could plausibly help (network, mirror 5xx). Deterministic - /// build failures must not auto-retry (§8.4). + /// True when a retry could plausibly help (§8.4): an unreachable upstream, a + /// mirror that 5xx'd, a connection that reset. + /// + /// `Error::Io` is *not* automatically transient (m-14). `ENOSPC` and + /// `EACCES` are `Io`, and treating them as retryable meant a full disk or a + /// misconfigured root turned into three identical failures, a shrug, and a + /// build that never got the operator's attention. Only the kinds that mean + /// "the same call might work in a moment" are retried. pub fn is_transient(&self) -> bool { - matches!(self, Error::Http(_) | Error::Io(_) | Error::Transient(_)) + match self { + Error::Http(_) | Error::Transient(_) => true, + Error::Io(e) => matches!( + e.kind(), + std::io::ErrorKind::WouldBlock + | std::io::ErrorKind::TimedOut + | std::io::ErrorKind::Interrupted + | std::io::ErrorKind::BrokenPipe + | std::io::ErrorKind::ConnectionReset + | std::io::ErrorKind::ConnectionRefused + | std::io::ErrorKind::ConnectionAborted + ), + _ => false, + } } } pub type Result<T> = std::result::Result<T, Error>; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_full_disk_is_not_a_retryable_failure() { + // m-14: `Error::Io` used to mean "retry", so ENOSPC and EACCES — both + // plain `Io` — turned into three identical failures and a build that + // never announced itself as broken. + let enospc = Error::Io(std::io::Error::from_raw_os_error(28)); + let eacces = Error::Io(std::io::Error::from_raw_os_error(13)); + assert!(!enospc.is_transient(), "a full disk does not clear itself between retries"); + assert!(!eacces.is_transient(), "a permissions problem does not clear itself either"); + } + + #[test] + fn what_a_moment_might_fix_is_retried() { + let refused = Error::Io(std::io::Error::from_raw_os_error(111)); + assert!(refused.is_transient()); + assert!(Error::transient("mirror returned 502").is_transient()); + assert!(Error::Http("connection reset".into()).is_transient()); + assert!(!Error::invalid("recipe has no pkgbase").is_transient()); + assert!(!Error::fail_closed("identity hash moved").is_transient()); + } +} diff --git a/src/http/auth.rs b/src/http/auth.rs index 3d05cab..8c56c1f 100644 --- a/src/http/auth.rs +++ b/src/http/auth.rs @@ -27,20 +27,26 @@ fn sessions() -> &'static Mutex<HashMap<String, bool>> { SESSIONS.get_or_init(|| Mutex::new(HashMap::new())) } -/// Random hex token from the system RNG (`/dev/urandom` through our hash). -fn random_hex() -> String { +/// Random hex token from the system RNG, or `None` when there is no usable one. +/// +/// The old version read `/dev/urandom` into a zeroed buffer, ignored every +/// error, and hashed the result anyway (§6 m-13): a failed read produced a +/// session id derived from a buffer of zeros plus the clock and a counter, +/// which is guessable by anyone who can guess roughly when the process started +/// — and nothing anywhere said the RNG had failed. A session id is the whole +/// credential now (C-1), so "no RNG" is a refusal, not a weaker token. +fn random_hex() -> Option<String> { + use std::io::Read; let mut buf = [0u8; 32]; - if let Ok(mut f) = std::fs::File::open("/dev/urandom") { - use std::io::Read; - let _ = f.read_exact(&mut buf); - } - // Mix in a counter and the clock so two calls in the same instant differ. + let mut f = std::fs::File::open("/dev/urandom").ok()?; + f.read_exact(&mut buf).ok()?; + // Mixed in regardless, so two calls in the same instant still differ. let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_nanos()) .unwrap_or(0); let salt = format!("{:?}", (buf, nanos, std::process::id(), counter())); - hash::hex(salt.as_bytes()) + Some(hash::hex(salt.as_bytes())) } fn counter() -> u64 { @@ -50,12 +56,12 @@ fn counter() -> u64 { /// Mint an anonymous session: enough for a CSRF token, not enough to see a /// single page when a password is set. -pub fn new_session() -> String { - let sid = random_hex(); +pub fn new_session() -> Option<String> { + let sid = random_hex()?; if let Ok(mut s) = sessions().lock() { s.insert(sid.clone(), false); } - sid + Some(sid) } pub fn is_valid_session(sid: &str) -> bool { diff --git a/src/http/mod.rs b/src/http/mod.rs index 07024d8..24da43f 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -238,7 +238,12 @@ fn dispatch(state: &State, req: &Req) -> Res { // through a sid that a successful login marked authenticated. let (sid, new_session) = match req.cookie("sid") { Some(s) if auth::is_valid_session(&s) => (s, false), - _ => (auth::new_session(), true), + _ => match auth::new_session() { + Some(s) => (s, true), + // No system RNG means no unguessable session id. Refuse rather than + // hand out a token someone else could compute. + None => return Res::text(500, "500: could not mint a session\n".into()), + }, }; let gated = routes::gate(state, req, &sid); if let Some(mut res) = gated { diff --git a/src/http/routes.rs b/src/http/routes.rs index 288f002..f475d3a 100644 --- a/src/http/routes.rs +++ b/src/http/routes.rs @@ -52,7 +52,10 @@ pub fn login(state: &State, req: &Req) -> Res { if let Some(old) = req.cookie("sid") { auth::drop_session(&old); } - let sid = auth::new_session(); + let sid = match auth::new_session() { + Some(sid) => sid, + None => return page_to_res(Login { page, error: "server: no entropy for a session".into() }, 500), + }; auth::authenticate(&sid); let mut res = Res::redirect("/"); // `serve` turns this into the `Set-Cookie: sid=…` header. diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs index d70ba8d..94fc46f 100644 --- a/src/pipeline/publish.rs +++ b/src/pipeline/publish.rs @@ -91,70 +91,95 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { // Artifacts are copied into the served tree under their real filenames. let mut staged: Vec<(PathBuf, PathBuf)> = Vec::new(); + // Files this publish created that were not there before. If the publish does + // not land, they are orphans: no index names them and no consumer will ever + // ask for them (§6 m-16). A file that already existed belongs to the release + // that is still live, so it is never on this list. + let mut fresh: Vec<PathBuf> = Vec::new(); for p in &collect.packages { let from = PathBuf::from(&p.path); let filename = format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch); let dest = arch_dir.join(&filename); + let sig_dest = arch_dir.join(format!("{filename}.sig")); + let existed = dest.exists(); std::fs::copy(&from, &dest)?; if let Some(sig) = &p.signature_path { let s = PathBuf::from(sig); if s.exists() { - std::fs::copy(&s, arch_dir.join(format!("{filename}.sig")))?; + std::fs::copy(&s, &sig_dest)?; + } + } + if !existed { + fresh.push(dest.clone()); + if sig_dest.exists() { + fresh.push(sig_dest.clone()); } } staged.push((dest, from)); } - // 1. render the new database to .tmp and fsync it. The old one is untouched. - let db_name = ctx.cfg.repo_db_name(); - let final_db = arch_dir.join(format!("{db_name}.tar.gz")); - let tmp_db = arch_dir.join(format!("{db_name}.tar.gz.tmp")); - let mut pkgs = index_artifacts(&ctx.db, &staged.iter().map(|(d, _)| d.clone()).collect::<Vec<_>>())?; - // Deduplicate: the same package name must appear once, newest wins. - pkgs = dedupe_by_name(pkgs); - run_repo_add(&ctx.cfg, &tmp_db, &pkgs)?; - fsync_file(&tmp_db)?; + let outcome = (|| -> Result<i64> { + // 1. render the new database to .tmp and fsync it. The old one is untouched. + let db_name = ctx.cfg.repo_db_name(); + let final_db = arch_dir.join(format!("{db_name}.tar.gz")); + let tmp_db = arch_dir.join(format!("{db_name}.tar.gz.tmp")); + let mut pkgs = index_artifacts(&ctx.db, &staged.iter().map(|(d, _)| d.clone()).collect::<Vec<_>>())?; + // Deduplicate: the same package name must appear once, newest wins. + pkgs = dedupe_by_name(pkgs); + run_repo_add(&ctx.cfg, &tmp_db, &pkgs)?; + fsync_file(&tmp_db)?; - // Fault injection so I4 can be tested for real: die between the tmp write - // and the rename, and the old index must still be what consumers get. - // Compiled out of a production build (§6 M-9). - #[cfg(feature = "test-support")] - if ctx.cfg.hooks.publish_fault.as_deref() == Some("before-rename") { - return Err(Error::other("injected fault: before-rename")); - } + // Fault injection so I4 can be tested for real: die between the tmp write + // and the rename, and the old index must still be what consumers get. + // Compiled out of a production build (§6 M-9). + #[cfg(feature = "test-support")] + if ctx.cfg.hooks.publish_fault.as_deref() == Some("before-rename") { + return Err(Error::other("injected fault: before-rename")); + } - // 2. commit the DB: release + package rows + the accepted pointer, in one - // transaction, with the pointer moved by compare-and-swap. - let release_id = commit_release(ctx, &collect)?; + // 2. commit the DB: release + package rows + the accepted pointer, in one + // transaction, with the pointer moved by compare-and-swap. + let release_id = commit_release(ctx, &collect)?; - // 3. atomic swap: rename over the real database, then sign and swap the sig. - std::fs::rename(&tmp_db, &final_db)?; - fsync_dir(&arch_dir)?; - sign(&ctx.cfg, &final_db)?; - let sig = arch_dir.join(format!("{db_name}.tar.gz.sig")); - let tmp_sig = arch_dir.join(format!("{db_name}.tar.gz.sig.tmp")); - if tmp_sig.exists() { - std::fs::rename(&tmp_sig, &sig)?; - } + // 3. atomic swap: rename over the real database, then sign and swap the sig. + std::fs::rename(&tmp_db, &final_db)?; + fsync_dir(&arch_dir)?; + sign(&ctx.cfg, &final_db)?; + let sig = arch_dir.join(format!("{db_name}.tar.gz.sig")); + let tmp_sig = arch_dir.join(format!("{db_name}.tar.gz.sig.tmp")); + if tmp_sig.exists() { + std::fs::rename(&tmp_sig, &sig)?; + } - // 4. a publish can unblock builds waiting on a dependency we just added. - let unblocked = builds::requeue_blocked(&ctx.db)?; - db::audit_system( - &ctx.db.writer, - "publish", - "repo", - &repo_row, - serde_json::json!({ - "release": release_id, - "packages": collect.packages.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>(), - "unblocked_builds": unblocked, - }), - )?; - #[cfg(feature = "test-support")] - if ctx.cfg.hooks.publish_fault.as_deref() == Some("after-rename") { - return Err(Error::other("injected fault: after-rename")); + // 4. a publish can unblock builds waiting on a dependency we just added. + let unblocked = builds::requeue_blocked(&ctx.db)?; + db::audit_system( + &ctx.db.writer, + "publish", + "repo", + &repo_row, + serde_json::json!({ + "release": release_id, + "packages": collect.packages.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>(), + "unblocked_builds": unblocked, + }), + )?; + #[cfg(feature = "test-support")] + if ctx.cfg.hooks.publish_fault.as_deref() == Some("after-rename") { + return Err(Error::other("injected fault: after-rename")); + } + Ok(release_id) + })(); + + if outcome.is_err() { + // The publish did not land, so nothing in the served tree may look like it + // did: the bytes this call copied in are removed again (m-16). Files that + // were already there belong to the release still being served and stay. + for p in &fresh { + let _ = std::fs::remove_file(p); + } } - Ok(release_id) + outcome } fn repo_for(db: &Db) -> Result<String> { @@ -301,17 +326,24 @@ fn sign(cfg: &Config, path: &Path) -> Result<()> { Ok(()) } +/// fsync, and *say so* when it fails (m-7). The whole point of writing to +/// `.tmp`, fsyncing, and renaming is the promise that a consumer never sees a +/// half-written database; swallowing the error made that a comment rather than +/// a guarantee — on a filesystem that refuses `fsync` (full, read-only, a +/// network mount that dropped), the rename still "succeeded". fn fsync_file(p: &Path) -> Result<()> { - if let Ok(f) = std::fs::File::open(p) { - let _ = f.sync_all(); - } + let f = std::fs::File::open(p) + .map_err(|e| Error::other(format!("open {} for fsync: {e}", p.display())))?; + f.sync_all() + .map_err(|e| Error::other(format!("fsync {}: {e}", p.display())))?; Ok(()) } fn fsync_dir(p: &Path) -> Result<()> { - if let Ok(d) = std::fs::File::open(p) { - let _ = d.sync_all(); - } + let d = std::fs::File::open(p) + .map_err(|e| Error::other(format!("open dir {} for fsync: {e}", p.display())))?; + d.sync_all() + .map_err(|e| Error::other(format!("fsync dir {}: {e}", p.display())))?; Ok(()) } |
