Check account membership on DB level.

This commit is contained in:
2026-10-11 14:03:39 +02:00
parent 3faea141dd
commit 793f71e32e
12 changed files with 261 additions and 44 deletions
+61 -12
View File
@@ -11,7 +11,11 @@ pub struct Query {
pub offset: Option<i64>,
}
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<AccountMemberRow>, DatabaseError>
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
query: Query,
) -> Result<Vec<AccountMemberRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
@@ -20,11 +24,13 @@ where
r#"
SELECT id, account_id, user_id
FROM account_members
WHERE account_id = $1
WHERE account_id IN (SELECT id FROM accessible_accounts($1))
AND account_id = $2
ORDER BY id
LIMIT $2
OFFSET $3
LIMIT $3
OFFSET $4
"#,
user_id,
query.account_id,
query.limit,
query.offset,
@@ -36,6 +42,7 @@ where
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
account_id: Uuid,
id: Uuid,
) -> Result<Option<AccountMemberRow>, DatabaseError>
@@ -47,8 +54,11 @@ where
r#"
SELECT id, account_id, user_id
FROM account_members
WHERE account_id = $1 AND id = $2
WHERE account_id IN (SELECT id FROM accessible_accounts($1))
AND account_id = $2
AND id = $3
"#,
user_id,
account_id,
id,
)
@@ -57,17 +67,46 @@ where
.map_err(DatabaseError::from)
}
pub async fn upsert<'e, E>(
/// Inserts a member without checking account access. Only meant for adding the first member of a
/// newly created account, where no member exists yet to grant access. Use [upsert] for regular
/// member insertion or updating existing members.
pub async fn insert_initial<'e, E>(
executor: E,
member: AccountMemberRow,
) -> Result<Upsert<AccountMemberRow>, DatabaseError>
) -> Result<AccountMemberRow, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
AccountMemberRow,
r#"
INSERT INTO account_members (id, account_id, user_id)
VALUES ($1, $2, $3)
RETURNING id, account_id, user_id
"#,
member.id,
member.account_id,
member.user_id,
)
.fetch_one(executor)
.await
.map_err(DatabaseError::from)
}
pub async fn upsert<'e, E>(
executor: E,
user_id: Uuid,
member: AccountMemberRow,
) -> Result<Option<Upsert<AccountMemberRow>>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query!(
r#"
INSERT INTO account_members (id, account_id, user_id)
VALUES ($1, $2, $3)
SELECT $2, $3, $4
FROM accessible_accounts($1) AS accounts
WHERE accounts.id = $3
ON CONFLICT (id, account_id) DO UPDATE SET
user_id = EXCLUDED.user_id
RETURNING WITH (OLD AS old_row, NEW AS new_row)
@@ -78,14 +117,20 @@ where
new_row.account_id AS "account_id!",
new_row.user_id AS "user_id!"
"#,
user_id,
member.id,
member.account_id,
member.user_id,
)
.fetch_one(executor)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
// Nothing is written when the account is not accessible.
let Some(row) = row else {
return Ok(None);
};
// `old_id` indicates whether there was a previous row before the upsert, other old fields are
// coalesced with the new row's values in case there was no previous row. This enables static
// typing on the previous row instead of having to check nullability for each old field in code.
@@ -95,18 +140,19 @@ where
user_id: row.old_user_id,
});
Ok(Upsert {
Ok(Some(Upsert {
previous,
current: AccountMemberRow {
id: row.id,
account_id: row.account_id,
user_id: row.user_id,
},
})
}))
}
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
account_id: Uuid,
id: Uuid,
) -> Result<Option<AccountMemberRow>, DatabaseError>
@@ -117,9 +163,12 @@ where
AccountMemberRow,
r#"
DELETE FROM account_members
WHERE account_id = $1 AND id = $2
WHERE account_id IN (SELECT id FROM accessible_accounts($1))
AND account_id = $2
AND id = $3
RETURNING id, account_id, user_id
"#,
user_id,
account_id,
id,
)
+28
View File
@@ -62,6 +62,34 @@ 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<Option<AccountRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
AccountRow,
r#"
SELECT id, name
FROM accounts
WHERE id = $2
AND id IN (SELECT id FROM accessible_accounts($1))
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,
+31 -8
View File
@@ -15,7 +15,11 @@ pub struct Query {
pub offset: Option<u64>,
}
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<AccountMember>, RepositoryError>
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
query: Query,
) -> Result<Vec<AccountMember>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
@@ -31,7 +35,7 @@ where
.transpose()?,
};
let members = db::list(executor, query)
let members = db::list(executor, user_id, query)
.await?
.into_iter()
.map(decode)
@@ -42,13 +46,14 @@ where
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
account_id: Uuid,
id: Uuid,
) -> Result<Option<AccountMember>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let member = db::get_by_id(executor, account_id, id)
let member = db::get_by_id(executor, user_id, account_id, id)
.await?
.map(decode)
.transpose()?;
@@ -58,20 +63,37 @@ where
pub async fn upsert<'e, E>(
executor: E,
user_id: Uuid,
member: AccountMember,
) -> Result<Upsert<AccountMember>, RepositoryError>
) -> Result<Option<Upsert<AccountMember>>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let member = db::upsert(executor, encode(member))
let member = db::upsert(executor, user_id, encode(member))
.await
.map_err(classify_upsert_error)?
.try_map(decode)?
.into();
.map(|upserted| upserted.try_map(decode))
.transpose()?
.map(Into::into);
Ok(member)
}
/// Adds the first member of a newly created account, without checking account access.
pub async fn insert_initial<'e, E>(
executor: E,
member: AccountMember,
) -> Result<AccountMember, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = db::insert_initial(executor, encode(member))
.await
.map_err(classify_upsert_error)?;
Ok(decode(row)?)
}
fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
match &error {
DatabaseError::ForeignKeyViolation {
@@ -103,13 +125,14 @@ fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
account_id: Uuid,
id: Uuid,
) -> Result<Option<AccountMember>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let member = db::delete_by_id(executor, account_id, id)
let member = db::delete_by_id(executor, user_id, account_id, id)
.await?
.map(decode)
.transpose()?;
+16
View File
@@ -62,6 +62,22 @@ where
Ok(account)
}
pub async fn get_by_id_locking<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<Account>, 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,
+17 -15
View File
@@ -44,8 +44,8 @@ async fn list_account_members(
};
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
ensure_account_ownership(&mut tx, auth.user_id(), account_id).await?;
let members = repository::account_members::list(&mut *tx, query)
ensure_account_access(&mut tx, auth.user_id(), account_id).await?;
let members = repository::account_members::list(&mut *tx, auth.user_id(), query)
.await?
.into_iter()
.map(AccountMemberResponse::from)
@@ -62,12 +62,10 @@ async fn get_account_member(
State(pool): State<PgPool>,
Path((account_id, member_id)): Path<(Uuid, Uuid)>,
) -> Result<Json<AccountMemberResponse>, AppError> {
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
ensure_account_ownership(&mut tx, auth.user_id(), account_id).await?;
let member = repository::account_members::get_by_id(&mut *tx, account_id, member_id)
.await?
.ok_or(AppError::NotFound)?;
tx.commit().await.map_err(RepositoryError::from)?;
let member =
repository::account_members::get_by_id(&pool, auth.user_id(), account_id, member_id)
.await?
.ok_or(AppError::NotFound)?;
Ok(Json(member.into()))
}
@@ -82,10 +80,9 @@ async fn upsert_account_member(
) -> Result<(StatusCode, Json<AccountMemberResponse>), AppError> {
let member = member.into_domain(member_id, account_id)?;
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
ensure_account_ownership(&mut tx, auth.user_id(), account_id).await?;
let upserted = repository::account_members::upsert(&mut *tx, member).await?;
tx.commit().await.map_err(RepositoryError::from)?;
let upserted = repository::account_members::upsert(&pool, auth.user_id(), member)
.await?
.ok_or(AppError::NotFound)?;
let status = if upserted.previous.is_some() {
StatusCode::OK
@@ -103,10 +100,15 @@ async fn delete_account_member(
State(pool): State<PgPool>,
Path((account_id, member_id)): Path<(Uuid, Uuid)>,
) -> Result<StatusCode, AppError> {
let user_id = auth.user_id();
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
ensure_account_ownership(&mut tx, auth.user_id(), account_id).await?;
repository::accounts::get_by_id_locking(&mut *tx, user_id, account_id)
.await?
.ok_or(AppError::NotFound)?;
let members = repository::account_members::list(
&mut *tx,
user_id,
repository::account_members::Query {
account_id,
limit: Some(2),
@@ -120,7 +122,7 @@ async fn delete_account_member(
return Err(AppError::LastAccountMemberRemoval);
}
let deleted =
repository::account_members::delete_by_id(&mut *tx, account_id, member_id).await?;
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)?;
@@ -128,7 +130,7 @@ async fn delete_account_member(
Ok(StatusCode::NO_CONTENT)
}
async fn ensure_account_ownership(
async fn ensure_account_access(
connection: &mut sqlx::PgConnection,
user_id: Uuid,
account_id: Uuid,
+1 -1
View File
@@ -89,7 +89,7 @@ async fn upsert_account(
account_id: id,
user_id,
};
repository::account_members::upsert(&mut *tx, member).await?;
repository::account_members::insert_initial(&mut *tx, member).await?;
}
tx.commit()