Added user apps and token resources.

This commit is contained in:
2026-10-07 22:45:25 +02:00
parent 1f1f027368
commit 69afcedae1
47 changed files with 1940 additions and 28 deletions
@@ -0,0 +1,29 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT id, user_id\n FROM user_apps\n WHERE user_id = $1 AND id = $2\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "user_id",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
"nullable": [
false,
false
]
},
"hash": "1726695ea4d8786d8e489a763cd615644f66ad541bbad08d38f4a67c86c57a37"
}
@@ -0,0 +1,30 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT id, user_id\n FROM user_apps\n WHERE user_id = $1\n ORDER BY id\n LIMIT $2\n OFFSET $3\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "user_id",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid",
"Int8",
"Int8"
]
},
"nullable": [
false,
false
]
},
"hash": "1eec346cce152ba824c9f49b406986014a6f0615c17e9e8a6ecd776924562b99"
}
@@ -0,0 +1,23 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM user_app_secrets WHERE app_id = $1 AND id = $2 RETURNING id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
"nullable": [
false
]
},
"hash": "28650c14def0b3089a1c6f10d9947581bbc02bdac145f58d3c97d1d11671f949"
}
@@ -0,0 +1,23 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM user_apps WHERE user_id = $1 AND id = $2 RETURNING id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
"nullable": [
false
]
},
"hash": "38166013a2b30661d0666a7b6629904cf9c5e71ca6a8dee4ed3ebe7afec9383e"
}
@@ -0,0 +1,26 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE tokens\n SET access_token_hash = $2,\n refresh_token_hash = $3,\n access_expires_at = $4,\n refresh_expires_at = $5\n WHERE refresh_token_hash = $1\n AND revoked_at IS NULL\n AND refresh_expires_at > now()\n RETURNING id\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Bytea",
"Bytea",
"Bytea",
"Timestamptz",
"Timestamptz"
]
},
"nullable": [
false
]
},
"hash": "398a4f8e5438799586f42687d120fd055e342ba311a12264e34454414cb2325d"
}
@@ -0,0 +1,21 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO tokens (\n id, app_id, access_token_hash, refresh_token_hash,\n access_expires_at, refresh_expires_at, revoked_at, created_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid",
"Uuid",
"Bytea",
"Bytea",
"Timestamptz",
"Timestamptz",
"Timestamptz",
"Timestamptz"
]
},
"nullable": []
},
"hash": "3fcfa5b534e0ad39d2daecd9654ed22c38da844dbe7044cafc683bbcacb79d7a"
}
@@ -0,0 +1,48 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT id, app_id, secret_hash, expires_at, created_at\n FROM user_app_secrets\n WHERE app_id = $1\n ORDER BY created_at DESC, id DESC\n LIMIT $2\n OFFSET $3\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "app_id",
"type_info": "Uuid"
},
{
"ordinal": 2,
"name": "secret_hash",
"type_info": "Bytea"
},
{
"ordinal": 3,
"name": "expires_at",
"type_info": "Timestamptz"
},
{
"ordinal": 4,
"name": "created_at",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Uuid",
"Int8",
"Int8"
]
},
"nullable": [
false,
false,
false,
false,
false
]
},
"hash": "8d016626a5df98a049b4d32abe1fc8f4625ecc6abde27ae037a6e461e0fe0b6e"
}
@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE tokens\n SET revoked_at = COALESCE(revoked_at, now())\n WHERE access_token_hash = $1 OR refresh_token_hash = $1\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Bytea"
]
},
"nullable": []
},
"hash": "9f8fc6351a1261dcb91eb6f2bfe182a94adf1952a800371e668aeab6897c94c5"
}
@@ -0,0 +1,23 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT EXISTS (\n SELECT 1\n FROM user_app_secrets\n WHERE app_id = $1 AND secret_hash = $2 AND expires_at > now()\n ) AS \"is_valid!\"\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "is_valid!",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Uuid",
"Bytea"
]
},
"nullable": [
null
]
},
"hash": "a49a3149600f1ad83c82aee5910949e895611df56fb0c07a54b2536b6a3a6329"
}
@@ -0,0 +1,55 @@
{
"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 ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "old_id?",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "id!",
"type_info": "Uuid"
},
{
"ordinal": 2,
"name": "app_id!",
"type_info": "Uuid"
},
{
"ordinal": 3,
"name": "secret_hash!",
"type_info": "Bytea"
},
{
"ordinal": 4,
"name": "expires_at!",
"type_info": "Timestamptz"
},
{
"ordinal": 5,
"name": "created_at!",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Uuid",
"Uuid",
"Bytea",
"Timestamptz"
]
},
"nullable": [
false,
false,
false,
false,
false,
false
]
},
"hash": "b01b27f9cdf2ec1c9aa28be0e760d66d01c6083166bd6a6f53784ddcdc92f12c"
}
@@ -0,0 +1,47 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT id, app_id, secret_hash, expires_at, created_at\n FROM user_app_secrets\n WHERE app_id = $1 AND id = $2\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "app_id",
"type_info": "Uuid"
},
{
"ordinal": 2,
"name": "secret_hash",
"type_info": "Bytea"
},
{
"ordinal": 3,
"name": "expires_at",
"type_info": "Timestamptz"
},
{
"ordinal": 4,
"name": "created_at",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
"nullable": [
false,
false,
false,
false,
false
]
},
"hash": "b7d48fe3fd0300c94344d7d8e93ceead2cf1ff00bd837c0fc42ec81347faa383"
}
@@ -0,0 +1,35 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO user_apps (id, user_id)\n VALUES ($1, $2)\n ON CONFLICT (id) DO UPDATE SET\n id = EXCLUDED.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.user_id AS \"user_id!\"\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "old_id?",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "id!",
"type_info": "Uuid"
},
{
"ordinal": 2,
"name": "user_id!",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid",
"Uuid"
]
},
"nullable": [
false,
false,
false
]
},
"hash": "e4cc5672787e94ee849cb175416e92f053d6a36609af5f6a244a2c236e3ffb21"
}
+1
View File
@@ -1305,6 +1305,7 @@ dependencies = [
"axum",
"chrono",
"dotenv",
"ring",
"serde",
"serde_json",
"sqlx",
+1
View File
@@ -10,6 +10,7 @@ chrono = { version = "0.4.45", features = ["serde"] }
dotenv = "0.15.0"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151"
ring = "0.17.14"
sqlx = { version = "0.8.6", default-features = false, features = [
"runtime-tokio-rustls",
"postgres",
@@ -0,0 +1,4 @@
CREATE TABLE user_apps (
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
user_id UUID NOT NULL CONSTRAINT fk_user_apps_user REFERENCES users (id) ON DELETE CASCADE
);
@@ -0,0 +1,11 @@
CREATE TABLE user_app_secrets (
id UUID PRIMARY KEY 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()
);
CREATE INDEX ix_user_app_secrets_app_id ON user_app_secrets (app_id);
@@ -0,0 +1,14 @@
CREATE TABLE tokens (
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
app_id UUID NOT NULL CONSTRAINT fk_tokens_app REFERENCES user_apps (id) ON DELETE CASCADE,
access_token_hash BYTEA NOT NULL UNIQUE CHECK (
octet_length(access_token_hash) = 32
),
refresh_token_hash BYTEA NOT NULL UNIQUE CHECK (
octet_length(refresh_token_hash) = 32
),
access_expires_at TIMESTAMPTZ NOT NULL,
refresh_expires_at TIMESTAMPTZ NOT NULL,
revoked_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+44
View File
@@ -0,0 +1,44 @@
use ring::{
digest,
rand::{SecureRandom, SystemRandom},
};
pub fn generate_secret() -> Result<String, ring::error::Unspecified> {
let mut bytes = [0; 32];
SystemRandom::new().fill(&mut bytes)?;
let mut secret = String::with_capacity(bytes.len() * 2);
for byte in bytes {
use std::fmt::Write;
write!(&mut secret, "{byte:02x}").expect("writing to a String cannot fail");
}
Ok(secret)
}
pub fn hash_secret(secret: &str) -> Vec<u8> {
digest::digest(&digest::SHA256, secret.as_bytes())
.as_ref()
.to_vec()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generates_256_bit_hex_secrets() {
let first = generate_secret().unwrap();
let second = generate_secret().unwrap();
assert_eq!(first.len(), 64);
assert!(first.bytes().all(|byte| byte.is_ascii_hexdigit()));
assert_ne!(first, second);
}
#[test]
fn hashes_secrets_deterministically() {
assert_eq!(hash_secret("test-secret"), hash_secret("test-secret"));
assert_ne!(hash_secret("test-secret"), hash_secret("other-secret"));
}
}
+11
View File
@@ -2,7 +2,10 @@ pub mod accounts;
pub mod dtos;
mod error_codes;
pub mod recurring_transactions;
pub mod tokens;
pub mod transactions;
pub mod user_app_secrets;
pub mod user_apps;
pub mod users;
use error_codes::PG_FOREIGN_KEY_VIOLATION;
@@ -43,6 +46,12 @@ impl From<sqlx::Error> for DatabaseError {
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Constraint {
#[error("user app user constraint")]
UserAppUser,
#[error("user app secret app constraint")]
UserAppSecretApp,
#[error("transaction account constraint")]
TransactionAccount,
@@ -59,6 +68,8 @@ pub enum Constraint {
impl From<&str> for Constraint {
fn from(constraint: &str) -> Self {
match constraint {
"fk_user_apps_user" => Constraint::UserAppUser,
"fk_user_app_secrets_app" => Constraint::UserAppSecretApp,
"fk_transactions_account" => Constraint::TransactionAccount,
"fk_recurring_transactions_account" => Constraint::RecurringTransactionAccount,
_ => Constraint::Unknown(constraint.to_string()),
+6
View File
@@ -1,11 +1,17 @@
mod account;
mod recurring_transaction;
mod results;
mod token;
mod transaction;
mod user;
mod user_app;
mod user_app_secret;
pub use account::*;
pub use recurring_transaction::*;
pub use results::*;
pub use token::*;
pub use transaction::*;
pub use user::*;
pub use user_app::*;
pub use user_app_secret::*;
+13
View File
@@ -0,0 +1,13 @@
use chrono::{DateTime, Utc};
use uuid::Uuid;
pub struct TokenRow {
pub id: Uuid,
pub app_id: Uuid,
pub access_token_hash: Vec<u8>,
pub refresh_token_hash: Vec<u8>,
pub access_expires_at: DateTime<Utc>,
pub refresh_expires_at: DateTime<Utc>,
pub revoked_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
}
+6
View File
@@ -0,0 +1,6 @@
use uuid::Uuid;
pub struct UserAppRow {
pub id: Uuid,
pub user_id: Uuid,
}
@@ -0,0 +1,10 @@
use chrono::{DateTime, Utc};
use uuid::Uuid;
pub struct UserAppSecretRow {
pub id: Uuid,
pub app_id: Uuid,
pub secret_hash: Vec<u8>,
pub expires_at: DateTime<Utc>,
pub created_at: DateTime<Utc>,
}
+86
View File
@@ -0,0 +1,86 @@
use chrono::{DateTime, Utc};
use super::{DatabaseError, dtos::TokenRow};
pub async fn issue<'e, E>(executor: E, token: TokenRow) -> Result<(), DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query!(
r#"
INSERT INTO tokens (
id, app_id, access_token_hash, refresh_token_hash,
access_expires_at, refresh_expires_at, revoked_at, created_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
"#,
token.id,
token.app_id,
token.access_token_hash,
token.refresh_token_hash,
token.access_expires_at,
token.refresh_expires_at,
token.revoked_at,
token.created_at,
)
.execute(executor)
.await
.map_err(DatabaseError::from)?;
Ok(())
}
pub async fn rotate_refresh_token<'e, E>(
executor: E,
old_refresh_hash: &[u8],
access_token_hash: &[u8],
refresh_token_hash: &[u8],
access_expires_at: DateTime<Utc>,
refresh_expires_at: DateTime<Utc>,
) -> Result<bool, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query!(
r#"
UPDATE tokens
SET access_token_hash = $2,
refresh_token_hash = $3,
access_expires_at = $4,
refresh_expires_at = $5
WHERE refresh_token_hash = $1
AND revoked_at IS NULL
AND refresh_expires_at > now()
RETURNING id
"#,
old_refresh_hash,
access_token_hash,
refresh_token_hash,
access_expires_at,
refresh_expires_at,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(row.is_some())
}
pub async fn revoke<'e, E>(executor: E, token_hash: &[u8]) -> Result<(), DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query!(
r#"
UPDATE tokens
SET revoked_at = COALESCE(revoked_at, now())
WHERE access_token_hash = $1 OR refresh_token_hash = $1
"#,
token_hash,
)
.execute(executor)
.await
.map_err(DatabaseError::from)?;
Ok(())
}
+163
View File
@@ -0,0 +1,163 @@
use uuid::Uuid;
use super::{
DatabaseError,
dtos::{Delete, Upsert, UserAppSecretRow},
};
pub struct Query {
pub app_id: Uuid,
pub limit: Option<i64>,
pub offset: Option<i64>,
}
impl Default for Query {
fn default() -> Self {
Self {
app_id: Uuid::nil(),
limit: None,
offset: None,
}
}
}
pub async fn query<'e, E>(executor: E, query: Query) -> Result<Vec<UserAppSecretRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
UserAppSecretRow,
r#"
SELECT id, app_id, secret_hash, expires_at, created_at
FROM user_app_secrets
WHERE app_id = $1
ORDER BY created_at DESC, id DESC
LIMIT $2
OFFSET $3
"#,
query.app_id,
query.limit,
query.offset,
)
.fetch_all(executor)
.await
.map_err(DatabaseError::from)
}
pub async fn get_by_id<'e, E>(
executor: E,
app_id: Uuid,
id: Uuid,
) -> Result<Option<UserAppSecretRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
UserAppSecretRow,
r#"
SELECT id, app_id, secret_hash, expires_at, created_at
FROM user_app_secrets
WHERE app_id = $1 AND id = $2
"#,
app_id,
id,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)
}
pub async fn upsert<'e, E>(
executor: E,
secret: UserAppSecretRow,
) -> Result<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)
ON CONFLICT (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!",
new_row.app_id AS "app_id!",
new_row.secret_hash AS "secret_hash!",
new_row.expires_at AS "expires_at!",
new_row.created_at AS "created_at!"
"#,
secret.id,
secret.app_id,
secret.secret_hash,
secret.expires_at,
)
.fetch_one(executor)
.await
.map_err(DatabaseError::from)?;
let secret = UserAppSecretRow {
id: row.id,
app_id: row.app_id,
secret_hash: row.secret_hash,
expires_at: row.expires_at,
created_at: row.created_at,
};
Ok(if row.old_id.is_some() {
Upsert::Updated(secret)
} else {
Upsert::Created(secret)
})
}
pub async fn verify<'e, E>(
executor: E,
app_id: Uuid,
secret_hash: &[u8],
) -> Result<bool, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_scalar!(
r#"
SELECT EXISTS (
SELECT 1
FROM user_app_secrets
WHERE app_id = $1 AND secret_hash = $2 AND expires_at > now()
) AS "is_valid!"
"#,
app_id,
secret_hash,
)
.fetch_one(executor)
.await
.map_err(DatabaseError::from)
}
pub async fn delete_by_id<'e, E>(
executor: E,
app_id: Uuid,
id: Uuid,
) -> Result<Delete, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let deleted = sqlx::query!(
"DELETE FROM user_app_secrets WHERE app_id = $1 AND id = $2 RETURNING id",
app_id,
id,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(if deleted.is_some() {
Delete::Deleted
} else {
Delete::NotFound
})
}
+129
View File
@@ -0,0 +1,129 @@
use uuid::Uuid;
use super::{
DatabaseError,
dtos::{Delete, Upsert, UserAppRow},
};
pub struct Query {
pub user_id: Uuid,
pub limit: Option<i64>,
pub offset: Option<i64>,
}
impl Default for Query {
fn default() -> Self {
Self {
user_id: Uuid::nil(),
limit: None,
offset: None,
}
}
}
pub async fn query<'e, E>(executor: E, query: Query) -> Result<Vec<UserAppRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query_as!(
UserAppRow,
r#"
SELECT id, user_id
FROM user_apps
WHERE user_id = $1
ORDER BY id
LIMIT $2
OFFSET $3
"#,
query.user_id,
query.limit,
query.offset,
)
.fetch_all(executor)
.await
.map_err(DatabaseError::from)
}
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,
r#"
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 upsert<'e, E>(
executor: E,
app: UserAppRow,
) -> Result<Upsert<UserAppRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query!(
r#"
INSERT INTO user_apps (id, user_id)
VALUES ($1, $2)
ON CONFLICT (id) DO UPDATE SET
id = EXCLUDED.id
RETURNING WITH (OLD AS old_row, NEW AS new_row)
old_row.id AS "old_id?",
new_row.id AS "id!",
new_row.user_id AS "user_id!"
"#,
app.id,
app.user_id,
)
.fetch_one(executor)
.await
.map_err(DatabaseError::from)?;
let app = UserAppRow {
id: row.id,
user_id: row.user_id,
};
Ok(if row.old_id.is_some() {
Upsert::Updated(app)
} else {
Upsert::Created(app)
})
}
pub async fn delete_by_id<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Delete, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let deleted = sqlx::query!(
"DELETE FROM user_apps WHERE user_id = $1 AND id = $2 RETURNING id",
user_id,
id,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(if deleted.is_some() {
Delete::Deleted
} else {
Delete::NotFound
})
}
+6
View File
@@ -3,16 +3,22 @@ mod cents;
mod direction;
mod recurring_transaction;
mod schedule;
mod token;
mod transaction;
mod user;
mod user_app;
mod user_app_secret;
pub use account::*;
pub use cents::*;
pub use direction::*;
pub use recurring_transaction::*;
pub use schedule::*;
pub use token::*;
pub use transaction::*;
pub use user::*;
pub use user_app::*;
pub use user_app_secret::*;
#[derive(Debug, thiserror::Error)]
pub enum DomainError {
+14
View File
@@ -0,0 +1,14 @@
use chrono::{DateTime, Utc};
use uuid::Uuid;
#[derive(Clone, PartialEq, Eq)]
pub struct Token {
pub id: Uuid,
pub app_id: Uuid,
pub access_token_hash: Vec<u8>,
pub refresh_token_hash: Vec<u8>,
pub access_expires_at: DateTime<Utc>,
pub refresh_expires_at: DateTime<Utc>,
pub revoked_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
}
+7
View File
@@ -0,0 +1,7 @@
use uuid::Uuid;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserApp {
pub id: Uuid,
pub user_id: Uuid,
}
+11
View File
@@ -0,0 +1,11 @@
use chrono::{DateTime, Utc};
use uuid::Uuid;
#[derive(Clone, PartialEq, Eq)]
pub struct UserAppSecret {
pub id: Uuid,
pub app_id: Uuid,
pub secret_hash: Vec<u8>,
pub expires_at: DateTime<Utc>,
pub created_at: DateTime<Utc>,
}
+20
View File
@@ -16,6 +16,9 @@ pub enum AppError {
#[error("not found")]
NotFound,
#[error("unauthorized")]
Unauthorized,
#[error("domain error")]
Domain(#[from] DomainError),
@@ -35,6 +38,9 @@ impl IntoResponse for AppError {
Self::NotFound => {
return error_response(StatusCode::NOT_FOUND, "Not found");
}
Self::Unauthorized => {
return error_response(StatusCode::UNAUTHORIZED, "Invalid credentials");
}
Self::Domain(error) => {
return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
}
@@ -44,6 +50,20 @@ impl IntoResponse for AppError {
Self::Repository(RepositoryError::Decode(error)) => {
tracing::error!(%error, "invalid stored data");
}
Self::Repository(RepositoryError::ReferenceViolation {
relation: ReferenceRelation::User,
kind: ReferenceViolationKind::Missing,
..
}) => {
return error_response(StatusCode::NOT_FOUND, "User cannot be found");
}
Self::Repository(RepositoryError::ReferenceViolation {
relation: ReferenceRelation::UserApp,
kind: ReferenceViolationKind::Missing,
..
}) => {
return error_response(StatusCode::NOT_FOUND, "User app cannot be found");
}
Self::Repository(RepositoryError::ReferenceViolation {
relation: ReferenceRelation::Account,
kind: ReferenceViolationKind::Missing,
+1
View File
@@ -4,6 +4,7 @@ use anyhow::Context;
use sqlx::postgres::PgPoolOptions;
use tokio::net::TcpListener;
mod crypto;
mod database;
mod domain;
mod error;
+9
View File
@@ -7,7 +7,10 @@ pub mod accounts;
pub mod dtos;
mod encoding;
pub mod recurring_transactions;
pub mod tokens;
pub mod transactions;
pub mod user_app_secrets;
pub mod user_apps;
pub mod users;
#[derive(Debug, thiserror::Error)]
@@ -62,6 +65,12 @@ pub enum ReferenceRelation {
#[error("transaction")]
Transaction,
#[error("user")]
User,
#[error("user app")]
UserApp,
#[error("recurring transaction")]
RecurringTransaction,
}
+56
View File
@@ -0,0 +1,56 @@
use chrono::{DateTime, Utc};
use super::RepositoryError;
use crate::{
database::{dtos::TokenRow, tokens as db},
domain::Token,
};
pub async fn issue<'e, E>(executor: E, token: Token) -> Result<(), RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
Ok(db::issue(executor, encode(token)).await?)
}
pub async fn rotate_refresh_token<'e, E>(
executor: E,
old_refresh_hash: &[u8],
access_token_hash: &[u8],
refresh_token_hash: &[u8],
access_expires_at: DateTime<Utc>,
refresh_expires_at: DateTime<Utc>,
) -> Result<bool, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
Ok(db::rotate_refresh_token(
executor,
old_refresh_hash,
access_token_hash,
refresh_token_hash,
access_expires_at,
refresh_expires_at,
)
.await?)
}
pub async fn revoke<'e, E>(executor: E, token_hash: &[u8]) -> Result<(), RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
Ok(db::revoke(executor, token_hash).await?)
}
fn encode(token: Token) -> TokenRow {
TokenRow {
id: token.id,
app_id: token.app_id,
access_token_hash: token.access_token_hash,
refresh_token_hash: token.refresh_token_hash,
access_expires_at: token.access_expires_at,
refresh_expires_at: token.refresh_expires_at,
revoked_at: token.revoked_at,
created_at: token.created_at,
}
}
+194
View File
@@ -0,0 +1,194 @@
use uuid::Uuid;
use super::{
QueryConversionError, ReferenceRelation, ReferenceViolationKind, RepositoryError, dtos::Upsert,
};
use crate::{
database::{Constraint, DatabaseError, dtos::UserAppSecretRow, user_app_secrets as db},
domain::UserAppSecret,
};
pub struct Query {
pub app_id: Uuid,
pub limit: Option<u64>,
pub offset: Option<u64>,
}
impl Default for Query {
fn default() -> Self {
Self {
app_id: Uuid::nil(),
limit: None,
offset: None,
}
}
}
impl TryFrom<Query> for db::Query {
type Error = QueryConversionError;
fn try_from(query: Query) -> Result<Self, Self::Error> {
Ok(db::Query {
app_id: query.app_id,
limit: query
.limit
.map(|limit| i64::try_from(limit).map_err(|_| QueryConversionError::Limit(limit)))
.transpose()?,
offset: query
.offset
.map(|offset| {
i64::try_from(offset).map_err(|_| QueryConversionError::Offset(offset))
})
.transpose()?,
})
}
}
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<UserAppSecret>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
Ok(db::query(executor, query.try_into()?)
.await?
.into_iter()
.map(decode)
.collect())
}
pub async fn get<'e, E>(
executor: E,
app_id: Uuid,
id: Uuid,
) -> Result<Option<UserAppSecret>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
Ok(db::get_by_id(executor, app_id, id).await?.map(decode))
}
pub async fn upsert<'e, E>(
executor: E,
secret: UserAppSecret,
) -> Result<Upsert<UserAppSecret>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let upsert = db::upsert(executor, encode(secret))
.await
.map_err(classify_upsert_error)?;
Ok(match upsert {
crate::database::dtos::Upsert::Created(row) => Upsert::Created(decode(row)),
crate::database::dtos::Upsert::Updated(row) => Upsert::Updated(decode(row)),
})
}
fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
match &error {
DatabaseError::ForeignKeyViolation {
constraint: Constraint::UserAppSecretApp,
..
} => RepositoryError::ReferenceViolation {
relation: ReferenceRelation::UserApp,
kind: ReferenceViolationKind::Missing,
source: error,
},
_ => RepositoryError::Database(error),
}
}
pub async fn verify<'e, E>(
executor: E,
app_id: Uuid,
secret_hash: &[u8],
) -> Result<bool, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
Ok(db::verify(executor, app_id, secret_hash).await?)
}
pub async fn delete<'e, E>(
executor: E,
app_id: Uuid,
id: Uuid,
) -> Result<super::dtos::Delete, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
Ok(db::delete_by_id(executor, app_id, id).await?.into())
}
fn decode(row: UserAppSecretRow) -> UserAppSecret {
UserAppSecret {
id: row.id,
app_id: row.app_id,
secret_hash: row.secret_hash,
expires_at: row.expires_at,
created_at: row.created_at,
}
}
fn encode(secret: UserAppSecret) -> UserAppSecretRow {
UserAppSecretRow {
id: secret.id,
app_id: secret.app_id,
secret_hash: secret.secret_hash,
expires_at: secret.expires_at,
created_at: secret.created_at,
}
}
#[cfg(test)]
mod tests {
use chrono::Utc;
use super::*;
fn foreign_key_violation(constraint: Constraint) -> DatabaseError {
DatabaseError::ForeignKeyViolation {
constraint,
source: sqlx::Error::Protocol("test database cause".to_owned()),
}
}
#[test]
fn classifies_user_app_secret_upsert_foreign_key_violation() {
let error = classify_upsert_error(foreign_key_violation(Constraint::UserAppSecretApp));
assert!(matches!(
error,
RepositoryError::ReferenceViolation {
relation: ReferenceRelation::UserApp,
kind: ReferenceViolationKind::Missing,
..
}
));
}
#[test]
fn keeps_unknown_upsert_foreign_keys_generic() {
let error = classify_upsert_error(foreign_key_violation(Constraint::Unnamed));
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());
let round_trip = decode(encode(secret.clone()));
assert_eq!(round_trip.id, secret.id);
assert_eq!(round_trip.app_id, secret.app_id);
assert_eq!(round_trip.secret_hash, secret.secret_hash);
assert_eq!(round_trip.expires_at, secret.expires_at);
}
}
+172
View File
@@ -0,0 +1,172 @@
use uuid::Uuid;
use super::{QueryConversionError, RepositoryError, dtos::Upsert};
use crate::{
database::{Constraint, DatabaseError, dtos::UserAppRow, user_apps as db},
domain::UserApp,
};
pub struct Query {
pub user_id: Uuid,
pub limit: Option<u64>,
pub offset: Option<u64>,
}
impl Default for Query {
fn default() -> Self {
Self {
user_id: Uuid::nil(),
limit: None,
offset: None,
}
}
}
impl TryFrom<Query> for db::Query {
type Error = QueryConversionError;
fn try_from(query: Query) -> Result<Self, Self::Error> {
Ok(db::Query {
user_id: query.user_id,
limit: query
.limit
.map(|limit| i64::try_from(limit).map_err(|_| QueryConversionError::Limit(limit)))
.transpose()?,
offset: query
.offset
.map(|offset| {
i64::try_from(offset).map_err(|_| QueryConversionError::Offset(offset))
})
.transpose()?,
})
}
}
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<UserApp>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
Ok(db::query(executor, query.try_into()?)
.await?
.into_iter()
.map(decode)
.collect())
}
pub async fn get<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<Option<UserApp>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
Ok(db::get_by_id(executor, user_id, id).await?.map(decode))
}
pub async fn upsert<'e, E>(executor: E, app: UserApp) -> Result<Upsert<UserApp>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let upsert = db::upsert(executor, encode(app))
.await
.map_err(classify_upsert_error)?;
Ok(match upsert {
crate::database::dtos::Upsert::Created(row) => Upsert::Created(decode(row)),
crate::database::dtos::Upsert::Updated(row) => Upsert::Updated(decode(row)),
})
}
fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
match &error {
DatabaseError::ForeignKeyViolation {
constraint: Constraint::UserAppUser,
..
} => RepositoryError::ReferenceViolation {
relation: super::ReferenceRelation::User,
kind: super::ReferenceViolationKind::Missing,
source: error,
},
_ => RepositoryError::Database(error),
}
}
pub async fn delete<'e, E>(
executor: E,
user_id: Uuid,
id: Uuid,
) -> Result<super::dtos::Delete, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
Ok(db::delete_by_id(executor, user_id, id).await?.into())
}
fn decode(row: UserAppRow) -> UserApp {
UserApp {
id: row.id,
user_id: row.user_id,
}
}
fn encode(app: UserApp) -> UserAppRow {
UserAppRow {
id: app.id,
user_id: app.user_id,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn foreign_key_violation(constraint: Constraint) -> DatabaseError {
DatabaseError::ForeignKeyViolation {
constraint,
source: sqlx::Error::Protocol("test database cause".to_owned()),
}
}
#[test]
fn classifies_user_app_upsert_foreign_key_violation() {
let error = classify_upsert_error(foreign_key_violation(Constraint::UserAppUser));
assert!(matches!(
error,
RepositoryError::ReferenceViolation {
relation: super::super::ReferenceRelation::User,
kind: super::super::ReferenceViolationKind::Missing,
..
}
));
}
#[test]
fn keeps_unknown_upsert_foreign_keys_generic() {
let error = classify_upsert_error(foreign_key_violation(Constraint::Unnamed));
assert!(matches!(error, RepositoryError::Database(_)));
}
fn row() -> UserAppRow {
UserAppRow {
id: Uuid::new_v4(),
user_id: Uuid::new_v4(),
}
}
#[test]
fn decodes_valid_rows() {
let row = row();
let (id, user_id) = (row.id, row.user_id);
let app = decode(row);
assert_eq!(app.id, id);
assert_eq!(app.user_id, user_id);
}
#[test]
fn round_trips_through_rows() {
let app = decode(row());
assert_eq!(decode(encode(app.clone())), app);
}
}
+24 -21
View File
@@ -2,30 +2,33 @@ use axum::{http::StatusCode, routing::get};
use crate::error::AppError;
pub mod accounts;
pub mod auth_passkey;
pub mod auth_token;
pub mod dtos;
pub mod extractors;
pub mod scheduled_transactions;
pub mod transactions;
pub mod users;
mod accounts;
mod auth_passkey;
mod auth_token;
mod dtos;
mod extractors;
mod scheduled_transactions;
mod transactions;
mod user_app_secrets;
mod user_apps;
mod users;
pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
let auth_passkey = auth_passkey::create_router();
let auth_token = auth_token::create_router();
let accounts = accounts::create_router();
let scheduled_transactions = scheduled_transactions::create_router();
let transactions = transactions::create_router();
let users = users::create_router();
let api = axum::Router::new()
.nest("/auth/passkey", auth_passkey)
.nest("/auth/token", auth_token)
.nest("/accounts", accounts)
.nest("/scheduled-transactions", scheduled_transactions)
.nest("/transactions", transactions)
.nest("/users", users);
.nest("/auth/passkey", auth_passkey::create_router())
.nest("/auth/token", auth_token::create_router())
.nest("/accounts", accounts::create_router())
.nest(
"/scheduled-transactions",
scheduled_transactions::create_router(),
)
.nest("/transactions", transactions::create_router())
.nest("/users", users::create_router())
.nest("/users/{user_id}/apps", user_apps::create_router())
.nest(
"/users/{user_id}/apps/{app_id}/secrets",
user_app_secrets::create_router(),
);
axum::Router::new()
.nest("/api", api)
+119 -7
View File
@@ -1,7 +1,21 @@
use axum::routing::post;
use axum::{extract::State, routing::post};
use chrono::{Duration, Utc};
use sqlx::PgPool;
use uuid::Uuid;
use crate::error::AppError;
use crate::{
crypto::{generate_secret, hash_secret},
domain::Token,
error::AppError,
repository::{self, user_app_secrets},
routes::{
dtos::token::{TokenRequest, TokenResponse, TokenRevocationRequest, TokenType},
extractors::{form::Form, json::Json},
},
};
const ACCESS_TOKEN_LIFETIME_SECONDS: i64 = 3600;
const REFRESH_TOKEN_LIFETIME_SECONDS: i64 = 30 * 24 * 60 * 60;
pub fn create_router() -> axum::Router<PgPool> {
axum::Router::new()
@@ -10,13 +24,111 @@ pub fn create_router() -> axum::Router<PgPool> {
}
#[axum::debug_handler]
#[tracing::instrument()]
async fn issue_token() -> Result<(), AppError> {
Ok(())
#[tracing::instrument(skip(pool, token_request))]
async fn issue_token(
State(pool): State<PgPool>,
Form(token_request): Form<TokenRequest>,
) -> Result<Json<TokenResponse>, AppError> {
match token_request {
TokenRequest::ClientCredentials {
client_id,
client_secret,
} => {
let secret_hash = hash_secret(&client_secret);
if !user_app_secrets::verify(&pool, client_id, &secret_hash).await? {
return Err(AppError::Unauthorized);
}
let generated = generate_token_pair()?;
repository::tokens::issue(&pool, token(client_id, &generated)).await?;
Ok(Json(token_response(
generated.access_token,
generated.refresh_token,
)))
}
TokenRequest::RefreshToken { refresh_token } => {
let generated = generate_token_pair()?;
let old_refresh_hash = hash_secret(&refresh_token);
let mut tx = pool
.begin()
.await
.map_err(repository::RepositoryError::from)?;
let rotated = repository::tokens::rotate_refresh_token(
&mut *tx,
&old_refresh_hash,
&generated.access_token_hash,
&generated.refresh_token_hash,
generated.access_expires_at,
generated.refresh_expires_at,
)
.await?;
if !rotated {
return Err(AppError::Unauthorized);
}
tx.commit()
.await
.map_err(repository::RepositoryError::from)?;
Ok(Json(token_response(
generated.access_token,
generated.refresh_token,
)))
}
}
}
#[axum::debug_handler]
#[tracing::instrument()]
async fn revoke_token() -> Result<(), AppError> {
#[tracing::instrument(skip(pool, request))]
async fn revoke_token(
State(pool): State<PgPool>,
Form(request): Form<TokenRevocationRequest>,
) -> Result<(), AppError> {
repository::tokens::revoke(&pool, &hash_secret(&request.token)).await?;
Ok(())
}
struct GeneratedTokenPair {
access_token: String,
refresh_token: String,
access_token_hash: Vec<u8>,
refresh_token_hash: Vec<u8>,
access_expires_at: chrono::DateTime<Utc>,
refresh_expires_at: chrono::DateTime<Utc>,
}
fn generate_token_pair() -> Result<GeneratedTokenPair, AppError> {
let access_token = generate_secret().map_err(|_| AppError::Internal)?;
let refresh_token = generate_secret().map_err(|_| AppError::Internal)?;
let now = Utc::now();
Ok(GeneratedTokenPair {
access_token_hash: hash_secret(&access_token),
refresh_token_hash: hash_secret(&refresh_token),
access_expires_at: now + Duration::seconds(ACCESS_TOKEN_LIFETIME_SECONDS),
refresh_expires_at: now + Duration::seconds(REFRESH_TOKEN_LIFETIME_SECONDS),
access_token,
refresh_token,
})
}
fn token(app_id: Uuid, generated: &GeneratedTokenPair) -> Token {
Token {
id: Uuid::new_v4(),
app_id,
access_token_hash: generated.access_token_hash.clone(),
refresh_token_hash: generated.refresh_token_hash.clone(),
access_expires_at: generated.access_expires_at,
refresh_expires_at: generated.refresh_expires_at,
revoked_at: None,
created_at: Utc::now(),
}
}
fn token_response(access_token: String, refresh_token: String) -> TokenResponse {
TokenResponse {
access_token,
token_type: TokenType::Bearer,
expires_in: ACCESS_TOKEN_LIFETIME_SECONDS,
refresh_token: Some(refresh_token),
}
}
+3
View File
@@ -1,5 +1,8 @@
pub mod account;
pub mod direction;
pub mod scheduled_transaction;
pub mod token;
pub mod transaction;
pub mod user;
pub mod user_app;
pub mod user_app_secret;
+54
View File
@@ -0,0 +1,54 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Deserialize)]
#[serde(rename_all = "snake_case", tag = "grant_type")]
pub enum TokenRequest {
ClientCredentials {
client_id: Uuid,
client_secret: String,
},
RefreshToken {
refresh_token: String,
},
}
#[derive(Deserialize)]
pub struct TokenRevocationRequest {
pub token: String,
}
#[derive(Debug, Serialize)]
pub struct TokenResponse {
pub access_token: String,
pub token_type: TokenType,
pub expires_in: i64,
pub refresh_token: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TokenType {
Bearer,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serializes_token_response() {
let response = TokenResponse {
access_token: "access-token".to_string(),
token_type: TokenType::Bearer,
expires_in: 3600,
refresh_token: Some("refresh-token".to_string()),
};
let value = serde_json::to_value(response).unwrap();
assert_eq!(value["access_token"], "access-token");
assert_eq!(value["token_type"], "bearer");
assert_eq!(value["expires_in"], 3600);
assert_eq!(value["refresh_token"], "refresh-token");
}
}
+53
View File
@@ -0,0 +1,53 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::domain;
#[derive(Debug, Clone, Deserialize)]
pub struct UserAppRequest {}
impl UserAppRequest {
pub fn into_domain(self, user_id: Uuid, id: Uuid) -> domain::UserApp {
domain::UserApp { id, user_id }
}
}
#[derive(Debug, Clone, Serialize)]
pub struct UserAppResponse {
pub id: Uuid,
}
impl From<domain::UserApp> for UserAppResponse {
fn from(app: domain::UserApp) -> Self {
Self { id: app.id }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serializes_user_app_response() {
let id = Uuid::new_v4();
let response = UserAppResponse::from(domain::UserApp {
id,
user_id: Uuid::new_v4(),
});
assert_eq!(
serde_json::to_value(response).unwrap()["id"],
id.to_string()
);
}
#[test]
fn accepts_empty_put_payload() {
let request: UserAppRequest = serde_json::from_str("{}").unwrap();
let user_id = Uuid::new_v4();
let id = Uuid::new_v4();
let app = request.into_domain(user_id, id);
assert_eq!(app, domain::UserApp { id, user_id });
}
}
+80
View File
@@ -0,0 +1,80 @@
use chrono::{DateTime, FixedOffset, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
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)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct UserAppSecretResponse {
pub id: Uuid,
pub app_id: Uuid,
pub expires_at: DateTime<Utc>,
pub created_at: DateTime<Utc>,
}
impl From<domain::UserAppSecret> for UserAppSecretResponse {
fn from(secret: domain::UserAppSecret) -> Self {
Self {
id: secret.id,
app_id: secret.app_id,
expires_at: secret.expires_at,
created_at: secret.created_at,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct CreatedUserAppSecretResponse {
#[serde(flatten)]
pub credential: UserAppSecretResponse,
pub secret: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_timezone_aware_expiration() {
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"
);
}
#[test]
fn rejects_expiration_without_timezone() {
assert!(
serde_json::from_str::<UserAppSecretRequest>(r#"{"expires_at":"2030-01-01T12:00:00"}"#)
.is_err()
);
}
#[test]
fn read_response_does_not_expose_secret_hash() {
let response = UserAppSecretResponse {
id: Uuid::new_v4(),
app_id: Uuid::new_v4(),
expires_at: Utc::now(),
created_at: Utc::now(),
};
let value = serde_json::to_value(response).unwrap();
assert!(value.get("secret").is_none());
assert!(value.get("secret_hash").is_none());
}
}
+1
View File
@@ -1,3 +1,4 @@
pub mod form;
pub mod json;
pub mod path;
pub mod query;
+21
View File
@@ -0,0 +1,21 @@
use axum::extract::{FromRequest, Request};
use serde::de::DeserializeOwned;
use crate::error::AppError;
pub struct Form<T>(pub T);
impl<T, S> FromRequest<S> for Form<T>
where
T: DeserializeOwned,
S: Send + Sync,
{
type Rejection = AppError;
async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
axum::Form::<T>::from_request(request, state)
.await
.map(|axum::Form(value)| Self(value))
.map_err(|rejection| AppError::BadRequest(rejection.body_text()))
}
}
+123
View File
@@ -0,0 +1,123 @@
use axum::{extract::State, http::StatusCode};
use serde::Deserialize;
use sqlx::PgPool;
use uuid::Uuid;
use super::{
dtos::user_app_secret::{
CreatedUserAppSecretResponse, UserAppSecretRequest, UserAppSecretResponse,
},
extractors::{json::Json, path::Path, query::Query},
};
use crate::{
crypto::{generate_secret, hash_secret},
domain::UserAppSecret,
error::AppError,
repository::{
dtos::{Delete, Upsert},
user_app_secrets as repository,
},
};
pub fn create_router() -> axum::Router<PgPool> {
axum::Router::new()
.route("/", axum::routing::get(list_user_app_secrets))
.route(
"/{secret_id}",
axum::routing::get(get_user_app_secret)
.put(upsert_user_app_secret)
.delete(delete_user_app_secret),
)
}
#[derive(Debug, Deserialize)]
pub struct QueryParams {
pub limit: Option<u64>,
pub offset: Option<u64>,
}
#[axum::debug_handler]
#[tracing::instrument(skip(pool))]
async fn list_user_app_secrets(
State(pool): State<PgPool>,
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
Query(query): Query<QueryParams>,
) -> Result<Json<Vec<UserAppSecretResponse>>, AppError> {
let secrets = repository::list(
&pool,
repository::Query {
app_id,
limit: Some(query.limit.unwrap_or(20)),
offset: query.offset,
},
)
.await?
.into_iter()
.map(UserAppSecretResponse::from)
.collect();
Ok(Json(secrets))
}
#[axum::debug_handler]
#[tracing::instrument(skip(pool))]
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::get(&pool, app_id, secret_id)
.await?
.ok_or(AppError::NotFound)?;
Ok(Json(secret.into()))
}
#[axum::debug_handler]
#[tracing::instrument(skip(pool, request))]
async fn upsert_user_app_secret(
State(pool): State<PgPool>,
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() {
return Err(AppError::BadRequest(
"expires_at must be in the future".to_owned(),
));
}
let generated_secret = generate_secret().map_err(|_| AppError::Internal)?;
let secret = UserAppSecret {
id: secret_id,
app_id,
secret_hash: hash_secret(&generated_secret),
expires_at,
created_at: chrono::Utc::now(),
};
let upsert = repository::upsert(&pool, secret).await?;
let (status, secret) = match upsert {
Upsert::Created(secret) => (StatusCode::CREATED, secret),
Upsert::Updated(secret) => (StatusCode::OK, secret),
};
Ok((
status,
Json(CreatedUserAppSecretResponse {
credential: secret.into(),
secret: generated_secret,
}),
))
}
#[axum::debug_handler]
#[tracing::instrument(skip(pool))]
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::delete(&pool, app_id, secret_id).await? {
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
Delete::NotFound => Err(AppError::NotFound),
}
}
+99
View File
@@ -0,0 +1,99 @@
use axum::{extract::State, http::StatusCode};
use serde::Deserialize;
use sqlx::PgPool;
use uuid::Uuid;
use super::{
dtos::user_app::{UserAppRequest, UserAppResponse},
extractors::{json::Json, path::Path, query::Query},
};
use crate::{
error::AppError,
repository::{
dtos::{Delete, Upsert},
user_apps as repository,
},
};
pub fn create_router() -> axum::Router<PgPool> {
axum::Router::new()
.route("/", axum::routing::get(list_user_apps))
.route(
"/{app_id}",
axum::routing::get(get_user_app)
.put(upsert_user_app)
.delete(delete_user_app),
)
}
#[derive(Debug, Deserialize)]
pub struct QueryParams {
pub limit: Option<u64>,
pub offset: Option<u64>,
}
#[axum::debug_handler]
#[tracing::instrument(skip(pool))]
async fn list_user_apps(
State(pool): State<PgPool>,
Path(user_id): Path<Uuid>,
Query(query): Query<QueryParams>,
) -> Result<Json<Vec<UserAppResponse>>, AppError> {
let apps = repository::list(
&pool,
repository::Query {
user_id,
limit: Some(query.limit.unwrap_or(20)),
offset: query.offset,
},
)
.await?
.into_iter()
.map(UserAppResponse::from)
.collect();
Ok(Json(apps))
}
#[axum::debug_handler]
#[tracing::instrument(skip(pool))]
async fn get_user_app(
State(pool): State<PgPool>,
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
) -> Result<Json<UserAppResponse>, AppError> {
let app = repository::get(&pool, user_id, app_id)
.await?
.ok_or(AppError::NotFound)?;
Ok(Json(app.into()))
}
#[axum::debug_handler]
#[tracing::instrument(skip(pool, request))]
async fn upsert_user_app(
State(pool): State<PgPool>,
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
Json(request): Json<UserAppRequest>,
) -> Result<(StatusCode, Json<UserAppResponse>), AppError> {
let app = request.into_domain(user_id, app_id);
let upsert = repository::upsert(&pool, app).await?;
let (status, app) = match upsert {
Upsert::Created(app) => (StatusCode::CREATED, app),
Upsert::Updated(app) => (StatusCode::OK, app),
};
Ok((status, Json(app.into())))
}
#[axum::debug_handler]
#[tracing::instrument(skip(pool))]
async fn delete_user_app(
State(pool): State<PgPool>,
Path((user_id, app_id)): Path<(Uuid, Uuid)>,
) -> Result<StatusCode, AppError> {
match repository::delete(&pool, user_id, app_id).await? {
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
Delete::NotFound => Err(AppError::NotFound),
}
}