From 2b37fd6ebc0fdf9a9082d7eb06d05ee99e46fd63 Mon Sep 17 00:00:00 2001 From: Rogier Reerink Date: Mon, 12 Oct 2026 18:05:10 +0200 Subject: [PATCH] Perform last member removal check on the database. --- ...adac86afc0498ca2e27562557f505cd96b2bf.json | 41 ------------------ .../20260918000001_create_account_members.sql | 27 +++++++++++- server/src/database.rs | 26 +++++++++++- server/src/database/accounts.rs | 28 ------------- server/src/database/error_codes.rs | 1 + server/src/error.rs | 3 -- server/src/repository.rs | 3 ++ server/src/repository/account_members.rs | 42 ++++++++++++++++++- server/src/repository/accounts.rs | 16 ------- server/src/routes/account_members.rs | 30 +------------ server/src/routes/errors.rs | 8 ++-- 11 files changed, 102 insertions(+), 123 deletions(-) delete mode 100644 server/.sqlx/query-a4f47fa48d44b0239289b75d1f5adac86afc0498ca2e27562557f505cd96b2bf.json diff --git a/server/.sqlx/query-a4f47fa48d44b0239289b75d1f5adac86afc0498ca2e27562557f505cd96b2bf.json b/server/.sqlx/query-a4f47fa48d44b0239289b75d1f5adac86afc0498ca2e27562557f505cd96b2bf.json deleted file mode 100644 index 61a4e1a..0000000 --- a/server/.sqlx/query-a4f47fa48d44b0239289b75d1f5adac86afc0498ca2e27562557f505cd96b2bf.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n\t\tSELECT id, name\n\t\tFROM accounts\n\t\tWHERE id IN (SELECT id FROM accessible_accounts($1))\n AND id = $2\n\t\tFOR NO KEY UPDATE\n\t\t", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id", - "type_info": "Uuid", - "origin": { - "Table": { - "table": "accounts", - "name": "id" - } - } - }, - { - "ordinal": 1, - "name": "name", - "type_info": "Text", - "origin": { - "Table": { - "table": "accounts", - "name": "name" - } - } - } - ], - "parameters": { - "Left": [ - "Uuid", - "Uuid" - ] - }, - "nullable": [ - false, - false - ] - }, - "hash": "a4f47fa48d44b0239289b75d1f5adac86afc0498ca2e27562557f505cd96b2bf" -} diff --git a/server/migrations/20260918000001_create_account_members.sql b/server/migrations/20260918000001_create_account_members.sql index e237f9f..2503f16 100644 --- a/server/migrations/20260918000001_create_account_members.sql +++ b/server/migrations/20260918000001_create_account_members.sql @@ -4,4 +4,29 @@ CREATE TABLE account_members ( user_id UUID NOT NULL CONSTRAINT fk_account_members_user REFERENCES users (id), PRIMARY KEY (id, account_id), CONSTRAINT uq_account_members_account_user UNIQUE (account_id, user_id) -); \ No newline at end of file +); + +CREATE FUNCTION ensure_account_has_member () RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + -- Serialises concurrent removals for the same account. Without the lock, two transactions + -- removing different members of a two-member account would each still see the other's row. + -- No row is found when the account itself is being deleted (cascade), which is allowed. + PERFORM 1 FROM accounts WHERE id = OLD.account_id FOR NO KEY UPDATE; + + IF FOUND AND NOT EXISTS ( + SELECT 1 FROM account_members WHERE account_id = OLD.account_id + ) THEN + RAISE EXCEPTION 'account must have at least one member' + USING ERRCODE = 'check_violation', + CONSTRAINT = 'ck_account_members_last_member'; + END IF; + + RETURN NULL; +END +$$; + +CREATE CONSTRAINT TRIGGER ck_account_members_last_member +AFTER DELETE OR UPDATE OF account_id ON account_members +DEFERRABLE INITIALLY IMMEDIATE +FOR EACH ROW +EXECUTE FUNCTION ensure_account_has_member (); diff --git a/server/src/database.rs b/server/src/database.rs index 1827b06..5855ae0 100644 --- a/server/src/database.rs +++ b/server/src/database.rs @@ -9,10 +9,17 @@ pub mod user_app_secrets; pub mod user_apps; pub mod users; -use error_codes::{PG_FOREIGN_KEY_VIOLATION, PG_UNIQUE_VIOLATION}; +use error_codes::{PG_CHECK_VIOLATION, PG_FOREIGN_KEY_VIOLATION, PG_UNIQUE_VIOLATION}; #[derive(Debug, thiserror::Error)] pub enum DatabaseError { + #[error("check violation ({constraint}): {source}")] + CheckViolation { + constraint: Constraint, + #[source] + source: sqlx::Error, + }, + #[error("foreign key violation ({constraint}): {source}")] ForeignKeyViolation { constraint: Constraint, @@ -34,6 +41,19 @@ pub enum DatabaseError { impl From for DatabaseError { fn from(err: sqlx::Error) -> Self { match err { + sqlx::Error::Database(db_err) + if db_err.code().as_deref() == Some(PG_CHECK_VIOLATION) => + { + let constraint = db_err + .constraint() + .map(Constraint::from) + .unwrap_or(Constraint::Unnamed); + + DatabaseError::CheckViolation { + constraint, + source: sqlx::Error::Database(db_err), + } + } sqlx::Error::Database(db_err) if db_err.code().as_deref() == Some(PG_FOREIGN_KEY_VIOLATION) => { @@ -76,6 +96,9 @@ pub enum Constraint { #[error("account member user constraint")] AccountMemberUser, + #[error("account member last member constraint")] + AccountMemberLastMember, + #[error("user app user constraint")] UserAppUser, @@ -101,6 +124,7 @@ impl From<&str> for Constraint { "fk_account_members_account" => Constraint::AccountMemberAccount, "uq_account_members_account_user" => Constraint::AccountMemberAccountUser, "fk_account_members_user" => Constraint::AccountMemberUser, + "ck_account_members_last_member" => Constraint::AccountMemberLastMember, "fk_user_apps_user" => Constraint::UserAppUser, "fk_user_app_secrets_app" => Constraint::UserAppSecretApp, "fk_transactions_account" => Constraint::TransactionAccount, diff --git a/server/src/database/accounts.rs b/server/src/database/accounts.rs index fc68d44..366aa38 100644 --- a/server/src/database/accounts.rs +++ b/server/src/database/accounts.rs @@ -62,34 +62,6 @@ where .map_err(DatabaseError::from) } -/// Like [`get_by_id`], but also locks the account row until the end of the transaction, so the -/// executor must be a transaction. Callers locking the same account are serialized, while -/// inserting members into the account is not blocked. -pub async fn get_by_id_locking<'e, E>( - executor: E, - user_id: Uuid, - id: Uuid, -) -> Result, DatabaseError> -where - E: sqlx::Executor<'e, Database = sqlx::Postgres>, -{ - sqlx::query_as!( - AccountRow, - r#" - SELECT id, name - FROM accounts - WHERE id IN (SELECT id FROM accessible_accounts($1)) - AND id = $2 - FOR NO KEY UPDATE - "#, - user_id, - id, - ) - .fetch_optional(executor) - .await - .map_err(DatabaseError::from) -} - pub async fn get_by_ids<'e, E>( executor: E, user_id: Uuid, diff --git a/server/src/database/error_codes.rs b/server/src/database/error_codes.rs index c66ddaf..fd8b8a8 100644 --- a/server/src/database/error_codes.rs +++ b/server/src/database/error_codes.rs @@ -1,2 +1,3 @@ +pub const PG_CHECK_VIOLATION: &str = "23514"; pub const PG_FOREIGN_KEY_VIOLATION: &str = "23503"; pub const PG_UNIQUE_VIOLATION: &str = "23505"; diff --git a/server/src/error.rs b/server/src/error.rs index 1874bdf..cc5a525 100644 --- a/server/src/error.rs +++ b/server/src/error.rs @@ -20,9 +20,6 @@ pub enum AppError { #[error("transaction id already exists")] TransactionIdAlreadyExists, - #[error("cannot remove the last member of an account")] - LastAccountMemberRemoval, - #[error("invalid client credentials")] InvalidClientCredentials, diff --git a/server/src/repository.rs b/server/src/repository.rs index 4d4027b..e178efb 100644 --- a/server/src/repository.rs +++ b/server/src/repository.rs @@ -102,6 +102,9 @@ pub enum ReferenceViolationKind { #[error("still referenced")] StillReferenced, + + #[error("last remaining")] + LastRemaining, } #[derive(Debug, thiserror::Error)] diff --git a/server/src/repository/account_members.rs b/server/src/repository/account_members.rs index d3523e1..b7b644e 100644 --- a/server/src/repository/account_members.rs +++ b/server/src/repository/account_members.rs @@ -134,13 +134,28 @@ where E: sqlx::Executor<'e, Database = sqlx::Postgres>, { let member = db::delete_by_id(executor, user_id, account_id, id) - .await? + .await + .map_err(classify_delete_error)? .map(decode) .transpose()?; Ok(member) } +fn classify_delete_error(error: DatabaseError) -> RepositoryError { + match &error { + DatabaseError::CheckViolation { + constraint: Constraint::AccountMemberLastMember, + .. + } => RepositoryError::ReferenceViolation { + relation: ReferenceRelation::AccountMember, + kind: ReferenceViolationKind::LastRemaining, + source: error, + }, + _ => RepositoryError::Database(error), + } +} + fn decode(row: AccountMemberRow) -> Result { Ok(AccountMember { id: row.id, @@ -232,6 +247,31 @@ mod tests { assert!(matches!(error, RepositoryError::Database(_))); } + #[test] + fn classifies_account_member_delete_last_member_check_violation() { + let error = classify_delete_error(DatabaseError::CheckViolation { + constraint: Constraint::AccountMemberLastMember, + source: sqlx::Error::Protocol("test database cause".to_owned()), + }); + assert!(matches!( + error, + RepositoryError::ReferenceViolation { + relation: ReferenceRelation::AccountMember, + kind: ReferenceViolationKind::LastRemaining, + .. + } + )); + } + + #[test] + fn keeps_unknown_delete_check_violations_generic() { + let error = classify_delete_error(DatabaseError::CheckViolation { + constraint: Constraint::Unnamed, + source: sqlx::Error::Protocol("test database cause".to_owned()), + }); + assert!(matches!(error, RepositoryError::Database(_))); + } + #[test] fn decodes_valid_rows() { let row = row(); diff --git a/server/src/repository/accounts.rs b/server/src/repository/accounts.rs index 3763f72..ee0de6d 100644 --- a/server/src/repository/accounts.rs +++ b/server/src/repository/accounts.rs @@ -62,22 +62,6 @@ where Ok(account) } -pub async fn get_by_id_locking<'e, E>( - executor: E, - user_id: Uuid, - id: Uuid, -) -> Result, RepositoryError> -where - E: sqlx::Executor<'e, Database = sqlx::Postgres>, -{ - let account = db::get_by_id_locking(executor, user_id, id) - .await? - .map(decode) - .transpose()?; - - Ok(account) -} - pub async fn get_by_ids<'e, E>( executor: E, user_id: Uuid, diff --git a/server/src/routes/account_members.rs b/server/src/routes/account_members.rs index e0cb266..83742da 100644 --- a/server/src/routes/account_members.rs +++ b/server/src/routes/account_members.rs @@ -9,11 +9,7 @@ use super::{ dtos::account_member::{AccountMemberRequest, AccountMemberResponse}, extractors::{Auth, Json, Path, Query}, }; -use crate::{ - domain, - error::AppError, - repository::{self, RepositoryError}, -}; +use crate::{domain, error::AppError, repository}; pub fn create_router() -> axum::Router { axum::Router::new() @@ -124,32 +120,10 @@ async fn delete_account_member( ) -> Result { let user_id = auth.user_id(); - let mut tx = pool.begin().await.map_err(RepositoryError::from)?; - - repository::accounts::get_by_id_locking(&mut *tx, user_id, account_id) + repository::account_members::delete_by_id(&pool, user_id, account_id, member_id) .await? .ok_or(AppError::NotFound)?; - let members_query = repository::account_members::Query { - limit: Some(2), - offset: None, - }; - - let members = - repository::account_members::list(&mut *tx, user_id, account_id, members_query).await?; - if let [only] = members.as_slice() - && only.id == member_id - { - return Err(AppError::LastAccountMemberRemoval); - } - - let deleted = - repository::account_members::delete_by_id(&mut *tx, user_id, account_id, member_id).await?; - - tx.commit().await.map_err(RepositoryError::from)?; - - deleted.ok_or(AppError::NotFound)?; - Ok(StatusCode::NO_CONTENT) } diff --git a/server/src/routes/errors.rs b/server/src/routes/errors.rs index 3918b81..778ac8c 100644 --- a/server/src/routes/errors.rs +++ b/server/src/routes/errors.rs @@ -44,10 +44,6 @@ impl ClientError for AppError { Self::TransactionIdAlreadyExists => { (StatusCode::CONFLICT, "Transaction ID already exists".into()) } - Self::LastAccountMemberRemoval => ( - StatusCode::CONFLICT, - "Cannot remove the last member of an account".into(), - ), Self::InvalidClientCredentials => ( StatusCode::UNAUTHORIZED, "Invalid client credentials".into(), @@ -157,6 +153,10 @@ impl ClientError for RepositoryError { StatusCode::CONFLICT, "Still referenced by one or more transactions".into(), ), + (Kind::LastRemaining, Relation::AccountMember) => ( + StatusCode::CONFLICT, + "Cannot remove the last member of an account".into(), + ), _ => internal_error(), } }