diff --git a/crates/archivr-core/src/auth_users.rs b/crates/archivr-core/src/auth_users.rs index f13e5c8..241c96b 100644 --- a/crates/archivr-core/src/auth_users.rs +++ b/crates/archivr-core/src/auth_users.rs @@ -19,12 +19,19 @@ pub struct RoleDeletion { /// `user_roles` rows cascade. Returns false when the user does not exist. pub fn delete_user(conn: &mut Connection, user_id: i64) -> Result { let tx = conn.transaction()?; - tx.execute( + let deleted = delete_user_in(&tx, user_id)?; + tx.commit()?; + Ok(deleted) +} + +/// [`delete_user`] without its own transaction, for callers that already hold one +/// (e.g. a last-owner check that must run under the same write lock). +pub fn delete_user_in(conn: &Connection, user_id: i64) -> Result { + conn.execute( "UPDATE user_roles SET assigned_by_user_id = NULL WHERE assigned_by_user_id = ?1", [user_id], )?; - let deleted = tx.execute("DELETE FROM users WHERE id = ?1", [user_id])?; - tx.commit()?; + let deleted = conn.execute("DELETE FROM users WHERE id = ?1", [user_id])?; Ok(deleted > 0) } diff --git a/crates/archivr-core/src/database.rs b/crates/archivr-core/src/database.rs index 4d38841..3dd4707 100644 --- a/crates/archivr-core/src/database.rs +++ b/crates/archivr-core/src/database.rs @@ -828,6 +828,9 @@ pub fn open_auth_db(auth_db_path: &Path) -> Result { } let conn = Connection::open(auth_db_path) .with_context(|| format!("failed to open auth database at {}", auth_db_path.display()))?; + // Owner-guarded writes take BEGIN IMMEDIATE; wait for a concurrent writer + // instead of failing with SQLITE_BUSY. + conn.busy_timeout(std::time::Duration::from_secs(5))?; initialize_auth_schema(&conn)?; Ok(conn) } diff --git a/crates/archivr-server/src/admin_users.rs b/crates/archivr-server/src/admin_users.rs index c7efca1..780a09d 100644 --- a/crates/archivr-server/src/admin_users.rs +++ b/crates/archivr-server/src/admin_users.rs @@ -34,8 +34,11 @@ async fn admin_delete_user( .ok_or_else(|| ApiError::not_found("user not found"))?; guards::ensure_not_self(caller_id, target_id)?; guards::ensure_can_manage(caller_bits, database::compute_role_bits(&conn, target_id)?)?; - guards::ensure_not_last_owner(&conn, target_id)?; - if !auth_users::delete_user(&mut conn, target_id)? { + let deleted = guards::with_write_lock(&mut conn, |tx| { + guards::ensure_not_last_owner(tx, target_id)?; + Ok(auth_users::delete_user_in(tx, target_id)?) + })?; + if !deleted { return Err(ApiError::not_found("user not found")); } Ok(StatusCode::NO_CONTENT) diff --git a/crates/archivr-server/src/guards.rs b/crates/archivr-server/src/guards.rs index f2ded77..8a8cab0 100644 --- a/crates/archivr-server/src/guards.rs +++ b/crates/archivr-server/src/guards.rs @@ -2,7 +2,7 @@ //! //! Callers still do their own coarse role check (`require_role(ROLE_ADMIN)`); //! these guards add the target-aware rules on top. -use rusqlite::Connection; +use rusqlite::{Connection, TransactionBehavior}; use crate::auth::{ROLE_ADMIN, ROLE_OWNER}; use crate::routes::ApiError; @@ -47,6 +47,19 @@ pub fn ensure_not_last_owner(conn: &Connection, target_id: i64) -> Result<(), Ap Ok(()) } +/// Runs `op` inside a `BEGIN IMMEDIATE` transaction. The last-owner check and the +/// write it guards must share this lock: with a deferred transaction, two concurrent +/// deletes of two different owners can both pass the check before either writes. +pub fn with_write_lock( + conn: &mut Connection, + op: impl FnOnce(&Connection) -> Result, +) -> Result { + let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; + let out = op(&tx)?; + tx.commit()?; + Ok(out) +} + #[cfg(test)] mod tests { use super::*; @@ -123,4 +136,59 @@ mod tests { // A disabled owner is not an active owner: touching it is fine. assert!(ensure_not_last_owner(&conn, second).is_ok()); } + + #[test] + fn concurrent_last_owner_deletes_leave_one_active_owner() { + use archivr_core::auth_users; + // Each round races two deletes of two different owners on separate + // connections. The check and the delete share one BEGIN IMMEDIATE lock, + // so exactly one may succeed. + for _ in 0..30 { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("auth.db"); + let setup = database::open_auth_db(&path).unwrap(); + let first = database::create_owner(&setup, "first", "pw").unwrap(); + let second = add_owner(&setup, "second", first); + drop(setup); + + let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); + let handles: Vec<_> = [first, second] + .into_iter() + .map(|target| { + let path = path.clone(); + let barrier = barrier.clone(); + std::thread::spawn(move || { + let mut conn = database::open_auth_db(&path).unwrap(); + barrier.wait(); + with_write_lock(&mut conn, |tx| { + ensure_not_last_owner(tx, target)?; + Ok(auth_users::delete_user_in(tx, target)?) + }) + }) + }) + .collect(); + let results: Vec> = + handles.into_iter().map(|h| h.join().unwrap()).collect(); + + let oks = results.iter().filter(|r| matches!(r, Ok(true))).count(); + let conflicts = results + .iter() + .filter(|r| matches!(r, Err(e) if e.status == StatusCode::CONFLICT)) + .count(); + assert_eq!((oks, conflicts), (1, 1), "unexpected outcomes"); + + let check = database::open_auth_db(&path).unwrap(); + let active: i64 = check + .query_row( + "SELECT COUNT(*) FROM user_roles ur + JOIN roles r ON r.id = ur.role_id + JOIN users u ON u.id = ur.user_id + WHERE r.slug = 'owner' AND u.status = 'active'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(active, 1); + } + } } diff --git a/crates/archivr-server/src/routes.rs b/crates/archivr-server/src/routes.rs index 2af079c..d15ac2f 100644 --- a/crates/archivr-server/src/routes.rs +++ b/crates/archivr-server/src/routes.rs @@ -3183,17 +3183,20 @@ async fn admin_set_user_status( "status must be 'active' or 'disabled'", )); } - let conn = database::open_auth_db(&state.auth_db_path)?; + let mut conn = database::open_auth_db(&state.auth_db_path)?; let target_id = database::get_user_id_by_uid(&conn, &uid)? .ok_or_else(|| ApiError::not_found("user not found"))?; if body.status == "disabled" { crate::guards::ensure_not_self(caller_id, target_id)?; } crate::guards::ensure_can_manage(caller_bits, database::compute_role_bits(&conn, target_id)?)?; - if body.status == "disabled" { - crate::guards::ensure_not_last_owner(&conn, target_id)?; - } - if !database::set_user_status(&conn, &uid, &body.status)? { + let updated = crate::guards::with_write_lock(&mut conn, |tx| { + if body.status == "disabled" { + crate::guards::ensure_not_last_owner(tx, target_id)?; + } + Ok(database::set_user_status(tx, &uid, &body.status)?) + })?; + if !updated { return Err(ApiError::not_found("user not found")); } Ok(Json( @@ -3231,7 +3234,7 @@ async fn admin_remove_role( ) -> Result { auth_user.require_role(ROLE_ADMIN)?; let (_, caller_bits) = auth_user.require_auth()?; - let conn = database::open_auth_db(&state.auth_db_path)?; + let mut conn = database::open_auth_db(&state.auth_db_path)?; let target_id = database::get_user_id_by_uid(&conn, &uid)? .ok_or_else(|| ApiError::not_found("user not found"))?; crate::guards::ensure_can_manage(caller_bits, database::compute_role_bits(&conn, target_id)?)?; @@ -3242,15 +3245,22 @@ async fn admin_remove_role( "only an owner can remove the owner or admin role", )); } - // Removing a role the user does not hold is a no-op. - if archivr_core::auth_users::user_has_role(&conn, target_id, &role_slug)? { - if role_slug == "owner" { - crate::guards::ensure_not_last_owner(&conn, target_id)?; + if role_slug == "owner" { + // The has-role check, last-owner checks and the removal share one write lock. + // Removing a role the user does not hold is a no-op. + crate::guards::with_write_lock(&mut conn, |tx| { + if !archivr_core::auth_users::user_has_role(tx, target_id, "owner")? { + return Ok(()); + } + crate::guards::ensure_not_last_owner(tx, target_id)?; // `remove_role` also refuses to drop the sole owner row (even a disabled one). - if archivr_core::auth_users::count_role_holders(&conn, "owner")? <= 1 { + if archivr_core::auth_users::count_role_holders(tx, "owner")? <= 1 { return Err(ApiError::conflict("cannot remove the last owner")); } - } + Ok(database::remove_role(tx, target_id, "owner")?) + })?; + } else if archivr_core::auth_users::user_has_role(&conn, target_id, &role_slug)? { + // Removing a role the user does not hold is a no-op. database::remove_role(&conn, target_id, &role_slug)?; } Ok(StatusCode::NO_CONTENT)