Added ownership and app existence validation to the user app secrets routes.
This commit is contained in:
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n INSERT INTO user_app_secrets (id, app_id, secret_hash, expires_at)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (id) DO UPDATE SET\n secret_hash = EXCLUDED.secret_hash,\n expires_at = EXCLUDED.expires_at\n WHERE user_app_secrets.app_id = EXCLUDED.app_id\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n new_row.id AS \"id!\",\n new_row.app_id AS \"app_id!\",\n new_row.secret_hash AS \"secret_hash!\",\n new_row.expires_at AS \"expires_at!\",\n new_row.created_at AS \"created_at!\"\n ",
|
||||
"query": "\n INSERT INTO user_app_secrets (id, app_id, secret_hash, expires_at)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (id, app_id) DO UPDATE SET\n secret_hash = EXCLUDED.secret_hash,\n expires_at = EXCLUDED.expires_at\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n new_row.id AS \"id!\",\n new_row.app_id AS \"app_id!\",\n new_row.secret_hash AS \"secret_hash!\",\n new_row.expires_at AS \"expires_at!\",\n new_row.created_at AS \"created_at!\"\n ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -87,5 +87,5 @@
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "b01b27f9cdf2ec1c9aa28be0e760d66d01c6083166bd6a6f53784ddcdc92f12c"
|
||||
"hash": "594090231079a7874dbe6d8b9696c92e30ca688f496cc02c79f265f870540153"
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT user_id FROM user_apps WHERE id = $1 FOR SHARE",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "user_id",
|
||||
"type_info": "Uuid",
|
||||
"origin": {
|
||||
"Table": {
|
||||
"table": "user_apps",
|
||||
"name": "user_id"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "f9a9d0e201e0f1c912d940fb6d0e4c27664bf4a0dbc2e71b2ade48df2e8dcd6e"
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
CREATE TABLE user_app_secrets (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
|
||||
id UUID DEFAULT gen_random_uuid (),
|
||||
app_id UUID NOT NULL CONSTRAINT fk_user_app_secrets_app REFERENCES user_apps (id) ON DELETE CASCADE,
|
||||
secret_hash BYTEA NOT NULL CHECK (
|
||||
octet_length(secret_hash) = 32
|
||||
),
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (id, app_id)
|
||||
);
|
||||
|
||||
CREATE INDEX ix_user_app_secrets_app_id ON user_app_secrets (app_id);
|
||||
@@ -68,10 +68,9 @@ where
|
||||
r#"
|
||||
INSERT INTO user_app_secrets (id, app_id, secret_hash, expires_at)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
ON CONFLICT (id, app_id) DO UPDATE SET
|
||||
secret_hash = EXCLUDED.secret_hash,
|
||||
expires_at = EXCLUDED.expires_at
|
||||
WHERE user_app_secrets.app_id = EXCLUDED.app_id
|
||||
RETURNING WITH (OLD AS old_row, NEW AS new_row)
|
||||
old_row.id AS "old_id?",
|
||||
new_row.id AS "id!",
|
||||
|
||||
@@ -57,6 +57,22 @@ 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 SHARE",
|
||||
app_id,
|
||||
)
|
||||
.fetch_optional(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)
|
||||
}
|
||||
|
||||
pub async fn upsert<'e, E>(
|
||||
executor: E,
|
||||
app: UserAppRow,
|
||||
|
||||
@@ -56,9 +56,22 @@ impl IntoResponse for AppError {
|
||||
tracing::warn!("user app ownership conflict");
|
||||
return error_response(StatusCode::CONFLICT, "User app belongs to another user");
|
||||
}
|
||||
Self::Repository(RepositoryError::NotFound {
|
||||
relation: ReferenceRelation::User,
|
||||
}) => {
|
||||
return error_response(StatusCode::NOT_FOUND, "User cannot be found");
|
||||
}
|
||||
Self::Repository(RepositoryError::NotFound {
|
||||
relation: ReferenceRelation::UserApp,
|
||||
}) => {
|
||||
return error_response(StatusCode::NOT_FOUND, "User app cannot be found");
|
||||
}
|
||||
Self::Repository(RepositoryError::OwnershipConflict { relation }) => {
|
||||
tracing::error!(%relation, "unhandled ownership conflict");
|
||||
}
|
||||
Self::Repository(RepositoryError::NotFound { relation }) => {
|
||||
tracing::error!(%relation, "unhandled not found");
|
||||
}
|
||||
Self::Repository(RepositoryError::ReferenceViolation {
|
||||
relation: ReferenceRelation::User,
|
||||
kind: ReferenceViolationKind::Missing,
|
||||
|
||||
@@ -24,6 +24,9 @@ pub enum RepositoryError {
|
||||
#[error("{relation} is owned by another user")]
|
||||
OwnershipConflict { relation: ReferenceRelation },
|
||||
|
||||
#[error("{relation} cannot be found")]
|
||||
NotFound { relation: ReferenceRelation },
|
||||
|
||||
#[error("reference violation ({kind}: {relation})")]
|
||||
ReferenceViolation {
|
||||
relation: ReferenceRelation,
|
||||
|
||||
@@ -138,6 +138,16 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
fn row() -> UserAppSecretRow {
|
||||
UserAppSecretRow {
|
||||
id: Uuid::new_v4(),
|
||||
app_id: Uuid::new_v4(),
|
||||
secret_hash: vec![0; 32],
|
||||
expires_at: Utc::now(),
|
||||
created_at: Utc::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn foreign_key_violation(constraint: Constraint) -> DatabaseError {
|
||||
DatabaseError::ForeignKeyViolation {
|
||||
constraint,
|
||||
@@ -164,16 +174,6 @@ mod tests {
|
||||
assert!(matches!(error, RepositoryError::Database(_)));
|
||||
}
|
||||
|
||||
fn row() -> UserAppSecretRow {
|
||||
UserAppSecretRow {
|
||||
id: Uuid::new_v4(),
|
||||
app_id: Uuid::new_v4(),
|
||||
secret_hash: vec![7; 32],
|
||||
expires_at: Utc::now(),
|
||||
created_at: Utc::now(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_through_rows() {
|
||||
let secret = decode(row()).unwrap();
|
||||
|
||||
@@ -58,6 +58,18 @@ where
|
||||
Ok(app)
|
||||
}
|
||||
|
||||
pub async fn find_owner_by_id<'e, E>(
|
||||
executor: E,
|
||||
app_id: Uuid,
|
||||
) -> Result<Option<Uuid>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let owner = db::find_owner_by_id(executor, app_id).await?;
|
||||
|
||||
Ok(owner)
|
||||
}
|
||||
|
||||
pub async fn upsert<'e, E>(executor: E, app: UserApp) -> Result<Upsert<UserApp>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use chrono::{DateTime, FixedOffset, Utc};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -6,13 +6,7 @@ use crate::domain;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct UserAppSecretRequest {
|
||||
pub expires_at: DateTime<FixedOffset>,
|
||||
}
|
||||
|
||||
impl UserAppSecretRequest {
|
||||
pub fn expires_at_utc(&self) -> DateTime<Utc> {
|
||||
self.expires_at.with_timezone(&Utc)
|
||||
}
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
@@ -50,10 +44,7 @@ mod tests {
|
||||
let request: UserAppSecretRequest =
|
||||
serde_json::from_str(r#"{"expires_at":"2030-01-01T12:00:00+02:00"}"#).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
request.expires_at_utc().to_rfc3339(),
|
||||
"2030-01-01T10:00:00+00:00"
|
||||
);
|
||||
assert_eq!(request.expires_at.to_rfc3339(), "2030-01-01T10:00:00+00:00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::{
|
||||
domain::UserAppSecret,
|
||||
error::AppError,
|
||||
repository::{
|
||||
self,
|
||||
self, ReferenceRelation, RepositoryError,
|
||||
dtos::{Delete, Upsert},
|
||||
},
|
||||
};
|
||||
@@ -49,11 +49,14 @@ async fn list_user_app_secrets(
|
||||
offset: query.offset,
|
||||
};
|
||||
|
||||
let secrets = repository::user_app_secrets::list(&pool, query)
|
||||
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)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(UserAppSecretResponse::from)
|
||||
.collect();
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
Ok(Json(secrets))
|
||||
}
|
||||
@@ -64,9 +67,12 @@ async fn get_user_app_secret(
|
||||
State(pool): State<PgPool>,
|
||||
Path((user_id, app_id, secret_id)): Path<(Uuid, Uuid, Uuid)>,
|
||||
) -> Result<Json<UserAppSecretResponse>, AppError> {
|
||||
let secret = repository::user_app_secrets::get_by_id(&pool, app_id, secret_id)
|
||||
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)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
Ok(Json(secret.into()))
|
||||
}
|
||||
@@ -78,8 +84,8 @@ async fn upsert_user_app_secret(
|
||||
Path((user_id, app_id, secret_id)): Path<(Uuid, Uuid, Uuid)>,
|
||||
Json(request): Json<UserAppSecretRequest>,
|
||||
) -> Result<(StatusCode, Json<CreatedUserAppSecretResponse>), AppError> {
|
||||
let expires_at = request.expires_at_utc();
|
||||
if expires_at <= chrono::Utc::now() {
|
||||
let now = chrono::Utc::now();
|
||||
if request.expires_at <= now {
|
||||
return Err(AppError::BadRequest(
|
||||
"expires_at must be in the future".to_owned(),
|
||||
));
|
||||
@@ -90,10 +96,14 @@ async fn upsert_user_app_secret(
|
||||
id: secret_id,
|
||||
app_id,
|
||||
secret_hash: hash_secret(&generated_secret),
|
||||
expires_at,
|
||||
created_at: chrono::Utc::now(),
|
||||
expires_at: request.expires_at,
|
||||
created_at: now,
|
||||
};
|
||||
let upsert = repository::user_app_secrets::upsert(&pool, secret).await?;
|
||||
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
ensure_app_ownership(&mut tx, user_id, app_id).await?;
|
||||
let upsert = repository::user_app_secrets::upsert(&mut *tx, secret).await?;
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
let (status, secret) = match upsert {
|
||||
Upsert::Created(secret) => (StatusCode::CREATED, secret),
|
||||
@@ -115,8 +125,27 @@ async fn delete_user_app_secret(
|
||||
State(pool): State<PgPool>,
|
||||
Path((user_id, app_id, secret_id)): Path<(Uuid, Uuid, Uuid)>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
match repository::user_app_secrets::delete_by_id(&pool, app_id, secret_id).await? {
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
ensure_app_ownership(&mut tx, user_id, app_id).await?;
|
||||
let result = repository::user_app_secrets::delete_by_id(&mut *tx, app_id, secret_id).await?;
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
match result {
|
||||
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
|
||||
Delete::NotFound => Err(AppError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
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(RepositoryError::NotFound {
|
||||
relation: ReferenceRelation::UserApp,
|
||||
}
|
||||
.into()),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user