mirror of
https://github.com/thegeneralist01/archivr
synced 2026-12-04 18:56:44 +01:00
fix: serialize last-owner checks with the mutation
The last-owner guard checked the owner count outside the write, so two concurrent deletes of different owners could both pass and leave no active owner. The check and the delete now run in one BEGIN IMMEDIATE transaction, and the auth DB gets a busy timeout so the second writer waits. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
59f7ab9730
commit
6e5bd070ef
5 changed files with 109 additions and 18 deletions
|
|
@ -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<bool> {
|
||||
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<bool> {
|
||||
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)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -828,6 +828,9 @@ pub fn open_auth_db(auth_db_path: &Path) -> Result<Connection> {
|
|||
}
|
||||
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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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<T>(
|
||||
conn: &mut Connection,
|
||||
op: impl FnOnce(&Connection) -> Result<T, ApiError>,
|
||||
) -> Result<T, ApiError> {
|
||||
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<Result<bool, ApiError>> =
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<StatusCode, ApiError> {
|
||||
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)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue