More scoping by user ID at DB level.

This commit is contained in:
2026-10-12 11:20:41 +02:00
parent 793f71e32e
commit b40d686ef9
18 changed files with 235 additions and 188 deletions
+2 -2
View File
@@ -6,7 +6,6 @@ use super::{
};
pub struct Query {
pub account_id: Uuid,
pub limit: Option<i64>,
pub offset: Option<i64>,
}
@@ -14,6 +13,7 @@ pub struct Query {
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
account_id: Uuid,
query: Query,
) -> Result<Vec<AccountMemberRow>, DatabaseError>
where
@@ -31,7 +31,7 @@ where
OFFSET $4
"#,
user_id,
query.account_id,
account_id,
query.limit,
query.offset,
)
+37 -13
View File
@@ -6,12 +6,16 @@ use super::{
};
pub struct Query {
pub app_id: Uuid,
pub limit: Option<i64>,
pub offset: Option<i64>,
}
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<UserAppSecretRow>, DatabaseError>
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
app_id: Uuid,
query: Query,
) -> Result<Vec<UserAppSecretRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
@@ -20,12 +24,14 @@ where
r#"
SELECT id, app_id, secret_hash, expires_at, created_at
FROM user_app_secrets
WHERE app_id = $1
WHERE app_id IN (SELECT id FROM user_apps WHERE user_id = $1)
AND app_id = $2
ORDER BY created_at DESC, id DESC
LIMIT $2
OFFSET $3
LIMIT $3
OFFSET $4
"#,
query.app_id,
user_id,
app_id,
query.limit,
query.offset,
)
@@ -36,6 +42,7 @@ where
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
app_id: Uuid,
id: Uuid,
) -> Result<Option<UserAppSecretRow>, DatabaseError>
@@ -47,8 +54,11 @@ where
r#"
SELECT id, app_id, secret_hash, expires_at, created_at
FROM user_app_secrets
WHERE app_id = $1 AND id = $2
WHERE app_id IN (SELECT id FROM user_apps WHERE user_id = $1)
AND app_id = $2
AND id = $3
"#,
user_id,
app_id,
id,
)
@@ -59,15 +69,19 @@ where
pub async fn upsert<'e, E>(
executor: E,
user_id: Uuid,
secret: UserAppSecretRow,
) -> Result<Upsert<UserAppSecretRow>, DatabaseError>
) -> Result<Option<Upsert<UserAppSecretRow>>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query!(
r#"
INSERT INTO user_app_secrets (id, app_id, secret_hash, expires_at)
VALUES ($1, $2, $3, $4)
SELECT $2, $3, $4, $5
FROM user_apps
WHERE user_id = $1 AND id = $3
FOR KEY SHARE
ON CONFLICT (id, app_id) DO UPDATE SET
secret_hash = EXCLUDED.secret_hash,
expires_at = EXCLUDED.expires_at
@@ -83,15 +97,21 @@ where
new_row.expires_at AS "expires_at!",
new_row.created_at AS "created_at!"
"#,
user_id,
secret.id,
secret.app_id,
secret.secret_hash,
secret.expires_at,
)
.fetch_one(executor)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
// Nothing is written when the app does not exist or is not owned by the user.
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.
@@ -103,7 +123,7 @@ where
created_at: row.old_created_at,
});
Ok(Upsert {
Ok(Some(Upsert {
previous,
current: UserAppSecretRow {
id: row.id,
@@ -112,7 +132,7 @@ where
expires_at: row.expires_at,
created_at: row.created_at,
},
})
}))
}
pub async fn verify<'e, E>(
@@ -141,6 +161,7 @@ where
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
app_id: Uuid,
id: Uuid,
) -> Result<Option<UserAppSecretRow>, DatabaseError>
@@ -151,9 +172,12 @@ where
UserAppSecretRow,
r#"
DELETE FROM user_app_secrets
WHERE app_id = $1 AND id = $2
WHERE app_id IN (SELECT id FROM user_apps WHERE user_id = $1)
AND app_id = $2
AND id = $3
RETURNING id, app_id, secret_hash, expires_at, created_at
"#,
user_id,
app_id,
id,
)
+46 -26
View File
@@ -6,12 +6,15 @@ use super::{
};
pub struct Query {
pub user_id: Uuid,
pub limit: Option<i64>,
pub offset: Option<i64>,
}
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<UserAppRow>, DatabaseError>
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
query: Query,
) -> Result<Vec<UserAppRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
@@ -25,7 +28,7 @@ where
LIMIT $2
OFFSET $3
"#,
query.user_id,
user_id,
query.limit,
query.offset,
)
@@ -34,7 +37,29 @@ where
.map_err(DatabaseError::from)
}
pub async fn get_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserAppRow>, DatabaseError>
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<UserAppRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
UserAppRow,
"SELECT id, user_id FROM user_apps WHERE user_id = $1 AND id = $2",
user_id,
id,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)
}
pub async fn get_by_id_unscoped<'e, E>(
executor: E,
id: Uuid,
) -> Result<Option<UserAppRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
@@ -48,26 +73,10 @@ where
.map_err(DatabaseError::from)
}
pub async fn find_owner_by_id<'e, E>(
executor: E,
app_id: Uuid,
) -> Result<Option<Uuid>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_scalar!(
"SELECT user_id FROM user_apps WHERE id = $1 FOR KEY SHARE",
app_id,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)
}
pub async fn upsert<'e, E>(
executor: E,
app: UserAppRow,
) -> Result<Upsert<UserAppRow>, DatabaseError>
) -> Result<Option<Upsert<UserAppRow>>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
@@ -77,6 +86,7 @@ where
VALUES ($1, $2)
ON CONFLICT (id) DO UPDATE SET
user_id = user_apps.user_id
WHERE user_apps.user_id = EXCLUDED.user_id
RETURNING WITH (OLD AS old_row, NEW AS new_row)
old_row.id AS "old_id?",
COALESCE(old_row.user_id, new_row.user_id) AS "old_user_id!",
@@ -86,10 +96,15 @@ where
app.id,
app.user_id,
)
.fetch_one(executor)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
// Nothing is written when the app ID already exists for another user.
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.
@@ -98,22 +113,27 @@ where
user_id: row.old_user_id,
});
Ok(Upsert {
Ok(Some(Upsert {
previous,
current: UserAppRow {
id: row.id,
user_id: row.user_id,
},
})
}))
}
pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserAppRow>, DatabaseError>
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<UserAppRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
UserAppRow,
"DELETE FROM user_apps WHERE id = $1 RETURNING id, user_id",
"DELETE FROM user_apps WHERE user_id = $1 AND id = $2 RETURNING id, user_id",
user_id,
id,
)
.fetch_optional(executor)
+5 -4
View File
@@ -10,7 +10,6 @@ use crate::{
};
pub struct Query {
pub account_id: Uuid,
pub limit: Option<u64>,
pub offset: Option<u64>,
}
@@ -18,13 +17,13 @@ pub struct Query {
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
account_id: Uuid,
query: Query,
) -> Result<Vec<AccountMember>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let query = db::Query {
account_id: query.account_id,
limit: query
.limit
.map(|limit| i64::try_from(limit).map_err(|_| QueryConversionError::Limit(limit)))
@@ -35,7 +34,7 @@ where
.transpose()?,
};
let members = db::list(executor, user_id, query)
let members = db::list(executor, user_id, account_id, query)
.await?
.into_iter()
.map(decode)
@@ -79,7 +78,9 @@ where
Ok(member)
}
/// Adds the first member of a newly created account, without checking account access.
/// 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: AccountMember,
+17 -10
View File
@@ -10,17 +10,20 @@ use crate::{
};
pub struct Query {
pub app_id: Uuid,
pub limit: Option<u64>,
pub offset: Option<u64>,
}
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<UserAppSecret>, RepositoryError>
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
app_id: Uuid,
query: Query,
) -> Result<Vec<UserAppSecret>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let query = db::Query {
app_id: query.app_id,
limit: query
.limit
.map(|limit| i64::try_from(limit).map_err(|_| QueryConversionError::Limit(limit)))
@@ -31,7 +34,7 @@ where
.transpose()?,
};
let secrets = db::list(executor, query)
let secrets = db::list(executor, user_id, app_id, query)
.await?
.into_iter()
.map(decode)
@@ -42,13 +45,14 @@ where
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
app_id: Uuid,
id: Uuid,
) -> Result<Option<UserAppSecret>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let secret = db::get_by_id(executor, app_id, id)
let secret = db::get_by_id(executor, user_id, app_id, id)
.await?
.map(decode)
.transpose()?;
@@ -58,16 +62,18 @@ where
pub async fn upsert<'e, E>(
executor: E,
user_id: Uuid,
secret: UserAppSecret,
) -> Result<Upsert<UserAppSecret>, RepositoryError>
) -> Result<Option<Upsert<UserAppSecret>>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let secret = db::upsert(executor, encode(secret))
let secret = db::upsert(executor, user_id, encode(secret))
.await
.map_err(classify_upsert_error)?
.try_map(decode)?
.into();
.map(|upserted| upserted.try_map(decode))
.transpose()?
.map(Into::into);
Ok(secret)
}
@@ -101,13 +107,14 @@ where
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
app_id: Uuid,
id: Uuid,
) -> Result<Option<UserAppSecret>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let secret = db::delete_by_id(executor, app_id, id)
let secret = db::delete_by_id(executor, user_id, app_id, id)
.await?
.map(decode)
.transpose()?;
+36 -16
View File
@@ -8,17 +8,19 @@ use crate::{
};
pub struct Query {
pub user_id: Uuid,
pub limit: Option<u64>,
pub offset: Option<u64>,
}
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<UserApp>, RepositoryError>
pub async fn list<'e, E>(
executor: E,
user_id: Uuid,
query: Query,
) -> Result<Vec<UserApp>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let query = db::Query {
user_id: query.user_id,
limit: query
.limit
.map(|limit| i64::try_from(limit).map_err(|_| QueryConversionError::Limit(limit)))
@@ -29,7 +31,7 @@ where
.transpose()?,
};
let apps = db::list(executor, query)
let apps = db::list(executor, user_id, query)
.await?
.into_iter()
.map(decode)
@@ -38,36 +40,50 @@ where
Ok(apps)
}
pub async fn get_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserApp>, RepositoryError>
pub async fn get_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<UserApp>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let app = db::get_by_id(executor, id).await?.map(decode).transpose()?;
let app = db::get_by_id(executor, user_id, id)
.await?
.map(decode)
.transpose()?;
Ok(app)
}
pub async fn find_owner_by_id<'e, E>(
pub async fn get_by_id_unscoped<'e, E>(
executor: E,
app_id: Uuid,
) -> Result<Option<Uuid>, RepositoryError>
id: Uuid,
) -> Result<Option<UserApp>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let owner = db::find_owner_by_id(executor, app_id).await?;
let app = db::get_by_id_unscoped(executor, id)
.await?
.map(decode)
.transpose()?;
Ok(owner)
Ok(app)
}
pub async fn upsert<'e, E>(executor: E, app: UserApp) -> Result<Upsert<UserApp>, RepositoryError>
pub async fn upsert<'e, E>(
executor: E,
app: UserApp,
) -> Result<Option<Upsert<UserApp>>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let app = db::upsert(executor, encode(app))
.await
.map_err(classify_upsert_error)?
.try_map(decode)?
.into();
.map(|upserted| upserted.try_map(decode))
.transpose()?
.map(Into::into);
Ok(app)
}
@@ -86,11 +102,15 @@ fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
}
}
pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserApp>, RepositoryError>
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<UserApp>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let app = db::delete_by_id(executor, id)
let app = db::delete_by_id(executor, user_id, id)
.await?
.map(decode)
.transpose()?;
+11 -17
View File
@@ -37,20 +37,22 @@ async fn list_account_members(
Path(account_id): Path<Uuid>,
Query(query): Query<QueryParams>,
) -> Result<Json<Vec<AccountMemberResponse>>, AppError> {
let user_id = auth.user_id();
let query = repository::account_members::Query {
account_id,
limit: Some(query.limit.unwrap_or(20)),
offset: query.offset,
};
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
ensure_account_access(&mut tx, auth.user_id(), account_id).await?;
let members = repository::account_members::list(&mut *tx, auth.user_id(), query)
repository::accounts::get_by_id(&pool, user_id, account_id)
.await?
.map(|_| ())
.ok_or(AppError::NotFound)?;
let members = repository::account_members::list(&pool, user_id, account_id, query)
.await?
.into_iter()
.map(AccountMemberResponse::from)
.collect();
tx.commit().await.map_err(RepositoryError::from)?;
Ok(Json(members))
}
@@ -103,14 +105,16 @@ async fn delete_account_member(
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)
.await?
.ok_or(AppError::NotFound)?;
let members = repository::account_members::list(
&mut *tx,
user_id,
account_id,
repository::account_members::Query {
account_id,
limit: Some(2),
offset: None,
},
@@ -123,20 +127,10 @@ async fn delete_account_member(
}
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)
}
async fn ensure_account_access(
connection: &mut sqlx::PgConnection,
user_id: Uuid,
account_id: Uuid,
) -> Result<(), AppError> {
repository::accounts::get_by_id(&mut *connection, user_id, account_id)
.await?
.map(|_| ())
.ok_or(AppError::NotFound)
}
+1 -1
View File
@@ -46,7 +46,7 @@ async fn issue_token(
return Err(AppError::InvalidClientCredentials);
}
let user_app = repository::user_apps::get_by_id(&mut *tx, client_id)
let user_app = repository::user_apps::get_by_id_unscoped(&mut *tx, client_id)
.await?
.ok_or(AppError::InvalidClientCredentials)?;
+14 -33
View File
@@ -12,7 +12,7 @@ use super::{
use crate::{
crypto::{generate_secret, hash_secret},
error::AppError,
repository::{self, RepositoryError},
repository,
};
pub fn create_router() -> axum::Router<PgPool> {
@@ -44,20 +44,20 @@ async fn list_user_app_secrets(
return Err(AppError::NotFound);
}
repository::user_apps::get_by_id(&pool, user_id, app_id)
.await?
.ok_or(AppError::NotFound)?;
let query = repository::user_app_secrets::Query {
app_id,
limit: Some(query.limit.unwrap_or(20)),
offset: query.offset,
};
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
ensure_app_ownership(&mut tx, user_id, app_id).await?;
let secrets = repository::user_app_secrets::list(&mut *tx, query)
let secrets = repository::user_app_secrets::list(&pool, user_id, app_id, query)
.await?
.into_iter()
.map(UserAppSecretResponse::from)
.collect();
tx.commit().await.map_err(RepositoryError::from)?;
Ok(Json(secrets))
}
@@ -73,12 +73,9 @@ async fn get_user_app_secret(
return Err(AppError::NotFound);
}
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
ensure_app_ownership(&mut tx, user_id, app_id).await?;
let secret = repository::user_app_secrets::get_by_id(&mut *tx, app_id, secret_id)
let secret = repository::user_app_secrets::get_by_id(&pool, user_id, app_id, secret_id)
.await?
.ok_or(AppError::NotFound)?;
tx.commit().await.map_err(RepositoryError::from)?;
Ok(Json(secret.into()))
}
@@ -100,22 +97,20 @@ async fn upsert_user_app_secret(
let hashed_secret = hash_secret(&generated_secret);
let secret = request.into_domain(secret_id, app_id, hashed_secret, now)?;
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
ensure_app_ownership(&mut tx, user_id, app_id).await?;
let upserted = repository::user_app_secrets::upsert(&mut *tx, secret).await?;
tx.commit().await.map_err(RepositoryError::from)?;
let upserted = repository::user_app_secrets::upsert(&pool, user_id, secret)
.await?
.ok_or(AppError::NotFound)?;
let status = if upserted.previous.is_some() {
StatusCode::OK
} else {
StatusCode::CREATED
};
let secret = upserted.current;
Ok((
status,
Json(CreatedUserAppSecretResponse {
credential: secret.into(),
credential: upserted.current.into(),
secret: generated_secret,
}),
))
@@ -132,23 +127,9 @@ async fn delete_user_app_secret(
return Err(AppError::NotFound);
}
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
ensure_app_ownership(&mut tx, user_id, app_id).await?;
let deleted = repository::user_app_secrets::delete_by_id(&mut *tx, app_id, secret_id).await?;
tx.commit().await.map_err(RepositoryError::from)?;
deleted.ok_or(AppError::NotFound)?;
repository::user_app_secrets::delete_by_id(&pool, user_id, app_id, secret_id)
.await?
.ok_or(AppError::NotFound)?;
Ok(StatusCode::NO_CONTENT)
}
async fn ensure_app_ownership(
connection: &mut sqlx::PgConnection,
user_id: Uuid,
app_id: Uuid,
) -> Result<(), AppError> {
match repository::user_apps::find_owner_by_id(&mut *connection, app_id).await? {
Some(owner) if owner == user_id => Ok(()),
Some(_) | None => Err(AppError::NotFound),
}
}
+8 -26
View File
@@ -7,10 +7,7 @@ use super::{
dtos::user_app::{UserAppRequest, UserAppResponse},
extractors::{Auth, Json, Path, Query},
};
use crate::{
error::AppError,
repository::{self, RepositoryError},
};
use crate::{error::AppError, repository};
pub fn create_router() -> axum::Router<PgPool> {
axum::Router::new()
@@ -42,12 +39,11 @@ async fn list_user_apps(
}
let query = repository::user_apps::Query {
user_id,
limit: Some(query.limit.unwrap_or(20)),
offset: query.offset,
};
let apps = repository::user_apps::list(&pool, query)
let apps = repository::user_apps::list(&pool, user_id, query)
.await?
.into_iter()
.map(UserAppResponse::from)
@@ -67,9 +63,8 @@ async fn get_user_app(
return Err(AppError::NotFound);
}
let app = repository::user_apps::get_by_id(&pool, app_id)
let app = repository::user_apps::get_by_id(&pool, user_id, app_id)
.await?
.filter(|app| app.user_id == user_id)
.ok_or(AppError::NotFound)?;
Ok(Json(app.into()))
@@ -88,17 +83,9 @@ async fn upsert_user_app(
}
let app = request.into_domain(user_id, app_id);
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
let upserted = repository::user_apps::upsert(&mut *tx, app).await?;
if upserted
.previous
.as_ref()
.is_some_and(|previous| previous.user_id != user_id)
{
return Err(AppError::AppIdAlreadyExists);
}
tx.commit().await.map_err(RepositoryError::from)?;
let upserted = repository::user_apps::upsert(&pool, app)
.await?
.ok_or(AppError::AppIdAlreadyExists)?;
let status = if upserted.previous.is_some() {
StatusCode::OK
@@ -120,14 +107,9 @@ async fn delete_user_app(
return Err(AppError::NotFound);
}
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
if repository::user_apps::delete_by_id(&mut *tx, app_id)
repository::user_apps::delete_by_id(&pool, user_id, app_id)
.await?
.is_none_or(|user_app| user_app.user_id != user_id)
{
return Err(AppError::NotFound);
}
tx.commit().await.map_err(RepositoryError::from)?;
.ok_or(AppError::NotFound)?;
Ok(StatusCode::NO_CONTENT)
}