Reimplemented access and refresh tokens.

This commit is contained in:
2026-10-18 13:21:48 +02:00
parent 4343959c74
commit 26999d690f
28 changed files with 1510 additions and 480 deletions
+2
View File
@@ -2,3 +2,5 @@ RUST_LOG=info
HOST=127.0.0.1
PORT=3000
DATABASE_URL=postgres://expenses:expenses@localhost:5432/expenses
ACCESS_TOKEN_LIFETIME_SECONDS=3600 # 1 hour
REFRESH_TOKEN_LIFETIME_SECONDS=2592000 # 30 days
@@ -0,0 +1,93 @@
{
"db_name": "PostgreSQL",
"query": "\n\t\tINSERT INTO access_tokens (id, user_id, user_app_id, secret_hash, expires_at, issued_at)\n\t\tVALUES ($1, $2, $3, $4, $5, $6)\n\t\tRETURNING id, user_id, user_app_id, secret_hash, expires_at, issued_at\n\t\t",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "user_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "user_id"
}
}
},
{
"ordinal": 2,
"name": "user_app_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "user_app_id"
}
}
},
{
"ordinal": 3,
"name": "secret_hash",
"type_info": "Bytea",
"origin": {
"Table": {
"table": "access_tokens",
"name": "secret_hash"
}
}
},
{
"ordinal": 4,
"name": "expires_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "access_tokens",
"name": "expires_at"
}
}
},
{
"ordinal": 5,
"name": "issued_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "access_tokens",
"name": "issued_at"
}
}
}
],
"parameters": {
"Left": [
"Uuid",
"Uuid",
"Uuid",
"Bytea",
"Timestamptz",
"Timestamptz"
]
},
"nullable": [
false,
false,
true,
false,
false,
false
]
},
"hash": "0d7964d66f11a466461a5938ef1a0aa89ba9e99d8f22b06343ab27188233ec22"
}
@@ -0,0 +1,79 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE refresh_tokens\n SET secret_hash = $2,\n expires_at = $3,\n issued_at = $4\n WHERE secret_hash = $1\n RETURNING id, access_token_id, secret_hash, expires_at, issued_at\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "access_token_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "access_token_id"
}
}
},
{
"ordinal": 2,
"name": "secret_hash",
"type_info": "Bytea",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "secret_hash"
}
}
},
{
"ordinal": 3,
"name": "expires_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "expires_at"
}
}
},
{
"ordinal": 4,
"name": "issued_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "issued_at"
}
}
}
],
"parameters": {
"Left": [
"Bytea",
"Bytea",
"Timestamptz",
"Timestamptz"
]
},
"nullable": [
false,
false,
false,
false,
false
]
},
"hash": "4b8559a53ceed6a384e287d52dcb67edcae1bb076099c81637f2b882637419b7"
}
@@ -0,0 +1,88 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n id,\n user_id,\n user_app_id,\n secret_hash,\n expires_at,\n issued_at\n FROM access_tokens\n WHERE secret_hash = $1\n AND expires_at > now()\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "user_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "user_id"
}
}
},
{
"ordinal": 2,
"name": "user_app_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "user_app_id"
}
}
},
{
"ordinal": 3,
"name": "secret_hash",
"type_info": "Bytea",
"origin": {
"Table": {
"table": "access_tokens",
"name": "secret_hash"
}
}
},
{
"ordinal": 4,
"name": "expires_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "access_tokens",
"name": "expires_at"
}
}
},
{
"ordinal": 5,
"name": "issued_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "access_tokens",
"name": "issued_at"
}
}
}
],
"parameters": {
"Left": [
"Bytea"
]
},
"nullable": [
false,
false,
true,
false,
false,
false
]
},
"hash": "50a9f81495657e35bedbf7fa3107f63c401aea690fdae95d74d03d86bdaa2a56"
}
@@ -0,0 +1,76 @@
{
"db_name": "PostgreSQL",
"query": "\n DELETE FROM refresh_tokens\n WHERE secret_hash = $1\n RETURNING id, access_token_id, secret_hash, expires_at, issued_at\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "access_token_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "access_token_id"
}
}
},
{
"ordinal": 2,
"name": "secret_hash",
"type_info": "Bytea",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "secret_hash"
}
}
},
{
"ordinal": 3,
"name": "expires_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "expires_at"
}
}
},
{
"ordinal": 4,
"name": "issued_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "issued_at"
}
}
}
],
"parameters": {
"Left": [
"Bytea"
]
},
"nullable": [
false,
false,
false,
false,
false
]
},
"hash": "6262f385b10112a7d3cc98121c8ba104132c065ac1c1522c3dd80b4284faf1a1"
}
@@ -1,136 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n id,\n user_id,\n user_app_id,\n access_token_hash,\n refresh_token_hash,\n access_expires_at,\n refresh_expires_at,\n refreshed_at,\n revoked_at,\n created_at\n FROM tokens\n WHERE access_token_hash = $1\n AND access_expires_at > now()\n AND revoked_at IS NULL\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "tokens",
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "user_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "tokens",
"name": "user_id"
}
}
},
{
"ordinal": 2,
"name": "user_app_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "tokens",
"name": "user_app_id"
}
}
},
{
"ordinal": 3,
"name": "access_token_hash",
"type_info": "Bytea",
"origin": {
"Table": {
"table": "tokens",
"name": "access_token_hash"
}
}
},
{
"ordinal": 4,
"name": "refresh_token_hash",
"type_info": "Bytea",
"origin": {
"Table": {
"table": "tokens",
"name": "refresh_token_hash"
}
}
},
{
"ordinal": 5,
"name": "access_expires_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "tokens",
"name": "access_expires_at"
}
}
},
{
"ordinal": 6,
"name": "refresh_expires_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "tokens",
"name": "refresh_expires_at"
}
}
},
{
"ordinal": 7,
"name": "refreshed_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "tokens",
"name": "refreshed_at"
}
}
},
{
"ordinal": 8,
"name": "revoked_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "tokens",
"name": "revoked_at"
}
}
},
{
"ordinal": 9,
"name": "created_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "tokens",
"name": "created_at"
}
}
}
],
"parameters": {
"Left": [
"Bytea"
]
},
"nullable": [
false,
false,
true,
false,
false,
false,
false,
true,
true,
false
]
},
"hash": "755b789df9d3d7f92243481e8fc8b724cae757c55579da8f86adb778eefdbc48"
}
@@ -1,23 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO tokens (\n id,\n user_id,\n user_app_id,\n access_token_hash,\n refresh_token_hash,\n access_expires_at,\n refresh_expires_at,\n refreshed_at,\n revoked_at,\n created_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid",
"Uuid",
"Uuid",
"Bytea",
"Bytea",
"Timestamptz",
"Timestamptz",
"Timestamptz",
"Timestamptz",
"Timestamptz"
]
},
"nullable": []
},
"hash": "768ccffe4387ae725e2e2ab1f5544f7536d0b7c0c657aa87dc7539dcdbbc5014"
}
@@ -0,0 +1,76 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n id,\n access_token_id,\n secret_hash,\n expires_at,\n issued_at\n FROM refresh_tokens\n WHERE secret_hash = $1\n AND expires_at > now()\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "access_token_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "access_token_id"
}
}
},
{
"ordinal": 2,
"name": "secret_hash",
"type_info": "Bytea",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "secret_hash"
}
}
},
{
"ordinal": 3,
"name": "expires_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "expires_at"
}
}
},
{
"ordinal": 4,
"name": "issued_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "issued_at"
}
}
}
],
"parameters": {
"Left": [
"Bytea"
]
},
"nullable": [
false,
false,
false,
false,
false
]
},
"hash": "8a5728429d71470fc276d2572f9b36d316eca63173b1463d5b3bed3e08d7ab19"
}
@@ -1,14 +0,0 @@
{
"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,80 @@
{
"db_name": "PostgreSQL",
"query": "\n\t\tINSERT INTO refresh_tokens (id, access_token_id, secret_hash, expires_at, issued_at)\n\t\tVALUES ($1, $2, $3, $4, $5)\n\t\tRETURNING id, access_token_id, secret_hash, expires_at, issued_at\n\t\t",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "access_token_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "access_token_id"
}
}
},
{
"ordinal": 2,
"name": "secret_hash",
"type_info": "Bytea",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "secret_hash"
}
}
},
{
"ordinal": 3,
"name": "expires_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "expires_at"
}
}
},
{
"ordinal": 4,
"name": "issued_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "refresh_tokens",
"name": "issued_at"
}
}
}
],
"parameters": {
"Left": [
"Uuid",
"Uuid",
"Bytea",
"Timestamptz",
"Timestamptz"
]
},
"nullable": [
false,
false,
false,
false,
false
]
},
"hash": "a1d81c17935a785a1001ee0673e1bbb02a64b5743406428dd18f8199ad8fb77b"
}
@@ -0,0 +1,88 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n a.id,\n a.user_id,\n a.user_app_id,\n a.secret_hash,\n a.expires_at,\n a.issued_at\n FROM access_tokens a\n JOIN refresh_tokens r ON r.access_token_id = a.id\n WHERE r.secret_hash = $1\n AND r.expires_at > now()\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "user_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "user_id"
}
}
},
{
"ordinal": 2,
"name": "user_app_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "user_app_id"
}
}
},
{
"ordinal": 3,
"name": "secret_hash",
"type_info": "Bytea",
"origin": {
"Table": {
"table": "access_tokens",
"name": "secret_hash"
}
}
},
{
"ordinal": 4,
"name": "expires_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "access_tokens",
"name": "expires_at"
}
}
},
{
"ordinal": 5,
"name": "issued_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "access_tokens",
"name": "issued_at"
}
}
}
],
"parameters": {
"Left": [
"Bytea"
]
},
"nullable": [
false,
false,
true,
false,
false,
false
]
},
"hash": "e5c0bc537264fb01e0eaca622ccac4f7b0ee2940954d7e902e6952488b9cb18a"
}
@@ -0,0 +1,91 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE access_tokens\n SET secret_hash = $2,\n expires_at = $3,\n issued_at = $4\n WHERE secret_hash = $1\n RETURNING id, user_id, user_app_id, secret_hash, expires_at, issued_at\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "user_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "user_id"
}
}
},
{
"ordinal": 2,
"name": "user_app_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "user_app_id"
}
}
},
{
"ordinal": 3,
"name": "secret_hash",
"type_info": "Bytea",
"origin": {
"Table": {
"table": "access_tokens",
"name": "secret_hash"
}
}
},
{
"ordinal": 4,
"name": "expires_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "access_tokens",
"name": "expires_at"
}
}
},
{
"ordinal": 5,
"name": "issued_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "access_tokens",
"name": "issued_at"
}
}
}
],
"parameters": {
"Left": [
"Bytea",
"Bytea",
"Timestamptz",
"Timestamptz"
]
},
"nullable": [
false,
false,
true,
false,
false,
false
]
},
"hash": "e9ab22c5b968148c8b1eeb03a120863e865e799bd347d84885e563e7761d2e06"
}
@@ -0,0 +1,88 @@
{
"db_name": "PostgreSQL",
"query": "\n DELETE FROM access_tokens\n WHERE secret_hash = $1\n RETURNING id, user_id, user_app_id, secret_hash, expires_at, issued_at\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "id"
}
}
},
{
"ordinal": 1,
"name": "user_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "user_id"
}
}
},
{
"ordinal": 2,
"name": "user_app_id",
"type_info": "Uuid",
"origin": {
"Table": {
"table": "access_tokens",
"name": "user_app_id"
}
}
},
{
"ordinal": 3,
"name": "secret_hash",
"type_info": "Bytea",
"origin": {
"Table": {
"table": "access_tokens",
"name": "secret_hash"
}
}
},
{
"ordinal": 4,
"name": "expires_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "access_tokens",
"name": "expires_at"
}
}
},
{
"ordinal": 5,
"name": "issued_at",
"type_info": "Timestamptz",
"origin": {
"Table": {
"table": "access_tokens",
"name": "issued_at"
}
}
}
],
"parameters": {
"Left": [
"Bytea"
]
},
"nullable": [
false,
false,
true,
false,
false,
false
]
},
"hash": "f052080688bdab0724707575aa61dfccde168a6ce21992c556938940f8f49b91"
}
@@ -1,32 +0,0 @@
{
"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 refreshed_at = now()\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",
"origin": {
"Table": {
"table": "tokens",
"name": "id"
}
}
}
],
"parameters": {
"Left": [
"Bytea",
"Bytea",
"Bytea",
"Timestamptz",
"Timestamptz"
]
},
"nullable": [
false
]
},
"hash": "f90d488ec2fff2e09bfbc83c287313aaeaa275cf6e41272347821735d4b401d6"
}
@@ -1,16 +1,20 @@
CREATE TABLE tokens (
CREATE TABLE access_tokens (
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
user_id UUID NOT NULL CONSTRAINT fk_tokens_user REFERENCES users (id) ON DELETE CASCADE,
user_app_id UUID 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
user_id UUID NOT NULL CONSTRAINT fk_access_tokens_user REFERENCES users (id) ON DELETE CASCADE,
user_app_id UUID CONSTRAINT fk_access_tokens_app REFERENCES user_apps (id) ON DELETE CASCADE,
secret_hash BYTEA NOT NULL UNIQUE CHECK (
octet_length(secret_hash) = 32
),
refresh_token_hash BYTEA NOT NULL UNIQUE CHECK (
octet_length(refresh_token_hash) = 32
expires_at TIMESTAMPTZ NOT NULL,
issued_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE refresh_tokens (
id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
access_token_id UUID NOT NULL UNIQUE CONSTRAINT fk_refresh_tokens_access_token REFERENCES access_tokens (id) ON DELETE CASCADE,
secret_hash BYTEA NOT NULL UNIQUE CHECK (
octet_length(secret_hash) = 32
),
access_expires_at TIMESTAMPTZ NOT NULL,
refresh_expires_at TIMESTAMPTZ NOT NULL,
refreshed_at TIMESTAMPTZ,
revoked_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL
expires_at TIMESTAMPTZ NOT NULL,
issued_at TIMESTAMPTZ NOT NULL
);
+12
View File
@@ -105,6 +105,15 @@ pub enum Constraint {
#[error("user app secret app constraint")]
UserAppSecretApp,
#[error("access token user constraint")]
AccessTokenUser,
#[error("access token user app constraint")]
AccessTokenUserApp,
#[error("refresh token access token constraint")]
RefreshTokenAccessToken,
#[error("transaction account constraint")]
TransactionAccount,
@@ -121,10 +130,13 @@ pub enum Constraint {
impl From<&str> for Constraint {
fn from(constraint: &str) -> Self {
match constraint {
"fk_access_tokens_user" => Constraint::AccessTokenUser,
"fk_access_tokens_app" => Constraint::AccessTokenUserApp,
"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_refresh_tokens_access_token" => Constraint::RefreshTokenAccessToken,
"fk_user_apps_user" => Constraint::UserAppUser,
"fk_user_app_secrets_app" => Constraint::UserAppSecretApp,
"fk_transactions_account" => Constraint::TransactionAccount,
+12 -8
View File
@@ -1,15 +1,19 @@
use chrono::{DateTime, Utc};
use uuid::Uuid;
pub struct TokenRow {
pub struct AccessTokenRow {
pub id: Uuid,
pub user_id: Uuid,
pub user_app_id: Option<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 refreshed_at: Option<DateTime<Utc>>,
pub revoked_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
pub secret_hash: Vec<u8>,
pub expires_at: DateTime<Utc>,
pub issued_at: DateTime<Utc>,
}
pub struct RefreshTokenRow {
pub id: Uuid,
pub access_token_id: Uuid,
pub secret_hash: Vec<u8>,
pub expires_at: DateTime<Utc>,
pub issued_at: DateTime<Utc>,
}
+225 -88
View File
@@ -1,34 +1,29 @@
use chrono::{DateTime, Utc};
use super::{DatabaseError, dtos::TokenRow};
use super::{DatabaseError, dtos::AccessTokenRow, dtos::RefreshTokenRow};
pub async fn get_by_access_token_hash<'e, E>(
pub async fn get_access_token_by_hash<'e, E>(
executor: E,
access_token_hash: &[u8],
) -> Result<Option<TokenRow>, DatabaseError>
secret_hash: &[u8],
) -> Result<Option<AccessTokenRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query_as!(
TokenRow,
AccessTokenRow,
r#"
SELECT
id,
user_id,
user_app_id,
access_token_hash,
refresh_token_hash,
access_expires_at,
refresh_expires_at,
refreshed_at,
revoked_at,
created_at
FROM tokens
WHERE access_token_hash = $1
AND access_expires_at > now()
AND revoked_at IS NULL
secret_hash,
expires_at,
issued_at
FROM access_tokens
WHERE secret_hash = $1
AND expires_at > now()
"#,
access_token_hash,
secret_hash,
)
.fetch_optional(executor)
.await
@@ -37,96 +32,238 @@ where
Ok(row)
}
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,
user_id,
user_app_id,
access_token_hash,
refresh_token_hash,
access_expires_at,
refresh_expires_at,
refreshed_at,
revoked_at,
created_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
"#,
token.id,
token.user_id,
token.user_app_id,
token.access_token_hash,
token.refresh_token_hash,
token.access_expires_at,
token.refresh_expires_at,
token.refreshed_at,
token.revoked_at,
token.created_at,
)
.execute(executor)
.await
.map_err(DatabaseError::from)?;
Ok(())
}
pub async fn rotate_refresh_token<'e, E>(
pub async fn get_access_token_by_refresh_secret_hash<'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>
refresh_secret_hash: &[u8],
) -> Result<Option<AccessTokenRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query!(
let row = sqlx::query_as!(
AccessTokenRow,
r#"
UPDATE tokens
SET access_token_hash = $2,
refresh_token_hash = $3,
access_expires_at = $4,
refresh_expires_at = $5,
refreshed_at = now()
WHERE refresh_token_hash = $1
AND revoked_at IS NULL
AND refresh_expires_at > now()
RETURNING id
SELECT
a.id,
a.user_id,
a.user_app_id,
a.secret_hash,
a.expires_at,
a.issued_at
FROM access_tokens a
JOIN refresh_tokens r ON r.access_token_id = a.id
WHERE r.secret_hash = $1
AND r.expires_at > now()
"#,
old_refresh_hash,
access_token_hash,
refresh_token_hash,
access_expires_at,
refresh_expires_at,
refresh_secret_hash,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(row.is_some())
Ok(row)
}
pub async fn revoke<'e, E>(executor: E, token_hash: &[u8]) -> Result<(), DatabaseError>
pub async fn insert_access_token<'e, E>(
executor: E,
access_token: AccessTokenRow,
) -> Result<AccessTokenRow, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
sqlx::query!(
let row = sqlx::query!(
r#"
UPDATE tokens
SET revoked_at = COALESCE(revoked_at, now())
WHERE access_token_hash = $1 OR refresh_token_hash = $1
"#,
token_hash,
INSERT INTO access_tokens (id, user_id, user_app_id, secret_hash, expires_at, issued_at)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, user_id, user_app_id, secret_hash, expires_at, issued_at
"#,
access_token.id,
access_token.user_id,
access_token.user_app_id,
access_token.secret_hash,
access_token.expires_at,
access_token.issued_at,
)
.execute(executor)
.fetch_one(executor)
.await
.map_err(DatabaseError::from)?;
Ok(())
Ok(AccessTokenRow {
id: row.id,
user_id: row.user_id,
user_app_id: row.user_app_id,
secret_hash: row.secret_hash,
expires_at: row.expires_at,
issued_at: row.issued_at,
})
}
pub async fn update_access_token_by_hash<'e, E>(
executor: E,
secret_hash: &[u8],
new_secret_hash: &[u8],
new_expires_at: DateTime<Utc>,
new_issued_at: DateTime<Utc>,
) -> Result<Option<AccessTokenRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query_as!(
AccessTokenRow,
r#"
UPDATE access_tokens
SET secret_hash = $2,
expires_at = $3,
issued_at = $4
WHERE secret_hash = $1
RETURNING id, user_id, user_app_id, secret_hash, expires_at, issued_at
"#,
secret_hash,
new_secret_hash,
new_expires_at,
new_issued_at,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(row)
}
pub async fn delete_access_token_by_hash<'e, E>(
executor: E,
secret_hash: &[u8],
) -> Result<Option<AccessTokenRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query_as!(
AccessTokenRow,
r#"
DELETE FROM access_tokens
WHERE secret_hash = $1
RETURNING id, user_id, user_app_id, secret_hash, expires_at, issued_at
"#,
secret_hash,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(row)
}
pub async fn get_refresh_token_by_hash<'e, E>(
executor: E,
secret_hash: &[u8],
) -> Result<Option<RefreshTokenRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query_as!(
RefreshTokenRow,
r#"
SELECT
id,
access_token_id,
secret_hash,
expires_at,
issued_at
FROM refresh_tokens
WHERE secret_hash = $1
AND expires_at > now()
"#,
secret_hash,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(row)
}
// pub async fn insert_refresh_token<'e, E>(
// executor: E,
// refresh_token: RefreshTokenRow,
// ) -> Result<RefreshTokenRow, DatabaseError>
// where
// E: sqlx::Executor<'e, Database = sqlx::Postgres>,
// {
// let row = sqlx::query!(
// r#"
// INSERT INTO refresh_tokens (id, access_token_id, secret_hash, expires_at, issued_at)
// VALUES ($1, $2, $3, $4, $5)
// RETURNING id, access_token_id, secret_hash, expires_at, issued_at
// "#,
// refresh_token.id,
// refresh_token.access_token_id,
// refresh_token.secret_hash,
// refresh_token.expires_at,
// refresh_token.issued_at,
// )
// .fetch_one(executor)
// .await
// .map_err(DatabaseError::from)?;
// Ok(RefreshTokenRow {
// id: row.id,
// access_token_id: row.access_token_id,
// secret_hash: row.secret_hash,
// expires_at: row.expires_at,
// issued_at: row.issued_at,
// })
// }
pub async fn update_refresh_token_by_hash<'e, E>(
executor: E,
secret_hash: &[u8],
new_secret_hash: &[u8],
new_expires_at: DateTime<Utc>,
new_issued_at: DateTime<Utc>,
) -> Result<Option<RefreshTokenRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query_as!(
RefreshTokenRow,
r#"
UPDATE refresh_tokens
SET secret_hash = $2,
expires_at = $3,
issued_at = $4
WHERE secret_hash = $1
RETURNING id, access_token_id, secret_hash, expires_at, issued_at
"#,
secret_hash,
new_secret_hash,
new_expires_at,
new_issued_at,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(row)
}
pub async fn delete_refresh_token_by_hash<'e, E>(
executor: E,
secret_hash: &[u8],
) -> Result<Option<RefreshTokenRow>, DatabaseError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let row = sqlx::query_as!(
RefreshTokenRow,
r#"
DELETE FROM refresh_tokens
WHERE secret_hash = $1
RETURNING id, access_token_id, secret_hash, expires_at, issued_at
"#,
secret_hash,
)
.fetch_optional(executor)
.await
.map_err(DatabaseError::from)?;
Ok(row)
}
+5
View File
@@ -4,6 +4,7 @@ mod cents;
mod direction;
mod recurring_transaction;
mod schedule;
mod secret;
mod token;
mod transaction;
mod user;
@@ -16,6 +17,7 @@ pub use cents::*;
pub use direction::*;
pub use recurring_transaction::*;
pub use schedule::*;
pub use secret::*;
pub use token::*;
pub use transaction::*;
pub use user::*;
@@ -27,6 +29,9 @@ pub enum DomainError {
#[error(transparent)]
Amount(#[from] CentsError),
#[error(transparent)]
Secret(#[from] SecretError),
#[error(transparent)]
Schedule(#[from] ScheduleError),
+79
View File
@@ -0,0 +1,79 @@
use crate::crypto::{generate_secret, hash_secret};
#[derive(Clone, PartialEq, Eq)]
pub struct Secret(String);
impl Secret {
pub fn generate() -> Result<Self, SecretError> {
Ok(Self(generate_secret().map_err(|_| SecretError)?))
}
pub fn secret(&self) -> &str {
&self.0
}
pub fn hash(&self) -> HashedSecret {
HashedSecret::from(self)
}
}
impl From<String> for Secret {
fn from(value: String) -> Self {
Self(value)
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct HashedSecret(Vec<u8>);
impl HashedSecret {
pub fn hash(&self) -> &[u8] {
&self.0
}
}
impl From<Vec<u8>> for HashedSecret {
fn from(value: Vec<u8>) -> Self {
Self(value)
}
}
impl From<&Secret> for HashedSecret {
fn from(secret: &Secret) -> Self {
Self(hash_secret(&secret.0))
}
}
#[derive(Debug, thiserror::Error)]
#[error("secret error")]
pub struct SecretError;
#[cfg(test)]
mod tests {
use super::{HashedSecret, Secret};
use crate::crypto::hash_secret;
#[test]
fn hash_matches_sha256_of_secret_value() {
let secret = Secret::generate().unwrap();
assert_eq!(secret.hash().hash(), hash_secret(secret.secret()));
assert_eq!(secret.hash().hash().len(), 32);
}
#[test]
fn hash_is_deterministic_and_matches_new() {
let secret = Secret::generate().unwrap();
assert!(secret.hash() == secret.hash());
assert!(secret.hash() == HashedSecret::from(&secret));
}
#[test]
fn different_secrets_have_different_hashes() {
let first = Secret::generate().unwrap();
let second = Secret::generate().unwrap();
assert!(first.hash() != second.hash());
}
}
+117 -9
View File
@@ -1,16 +1,124 @@
use chrono::{DateTime, Utc};
use chrono::{DateTime, Duration, Utc};
use uuid::Uuid;
use super::DomainError;
use crate::domain::{HashedSecret, Secret};
#[derive(Clone, PartialEq, Eq)]
pub struct Token {
pub struct AccessToken {
pub id: Uuid,
pub user_id: Uuid,
pub user_app_id: Option<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 refreshed_at: Option<DateTime<Utc>>,
pub revoked_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
pub secret: Secret,
pub expires_at: DateTime<Utc>,
pub issued_at: DateTime<Utc>,
}
impl AccessToken {
pub fn new(
user_id: Uuid,
user_app_id: Option<Uuid>,
lifetime: Duration,
) -> Result<Self, DomainError> {
let now = Utc::now();
Ok(Self {
id: Uuid::new_v4(),
user_id,
user_app_id,
secret: Secret::generate()?,
expires_at: now + lifetime,
issued_at: now,
})
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct HashedAccessToken {
pub id: Uuid,
pub user_id: Uuid,
pub user_app_id: Option<Uuid>,
pub secret_hash: HashedSecret,
pub expires_at: DateTime<Utc>,
pub issued_at: DateTime<Utc>,
}
impl HashedAccessToken {
pub fn refresh(self, lifetime: Duration) -> Result<AccessToken, DomainError> {
Ok(AccessToken {
id: self.id,
user_id: self.user_id,
user_app_id: self.user_app_id,
secret: Secret::generate()?,
expires_at: Utc::now() + lifetime,
issued_at: Utc::now(),
})
}
}
impl From<AccessToken> for HashedAccessToken {
fn from(value: AccessToken) -> Self {
Self {
id: value.id,
user_id: value.user_id,
user_app_id: value.user_app_id,
secret_hash: value.secret.hash(),
expires_at: value.expires_at,
issued_at: value.issued_at,
}
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct RefreshToken {
pub id: Uuid,
pub token_id: Uuid,
pub secret: Secret,
pub expires_at: DateTime<Utc>,
pub issued_at: DateTime<Utc>,
}
impl RefreshToken {
// pub fn generate(token_id: Uuid, lifetime: Duration) -> Result<Self, DomainError> {
// let now = Utc::now();
// Ok(Self {
// id: Uuid::new_v4(),
// token_id,
// secret: Secret::generate()?,
// expires_at: now + lifetime,
// issued_at: now,
// })
// }
}
#[derive(Clone, PartialEq, Eq)]
pub struct HashedRefreshToken {
pub id: Uuid,
pub token_id: Uuid,
pub secret_hash: HashedSecret,
pub expires_at: DateTime<Utc>,
pub issued_at: DateTime<Utc>,
}
impl HashedRefreshToken {
pub fn refresh(self, lifetime: Duration) -> Result<RefreshToken, DomainError> {
Ok(RefreshToken {
id: self.id,
token_id: self.token_id,
secret: Secret::generate()?,
expires_at: Utc::now() + lifetime,
issued_at: Utc::now(),
})
}
}
impl From<RefreshToken> for HashedRefreshToken {
fn from(value: RefreshToken) -> Self {
Self {
id: value.id,
token_id: value.token_id,
secret_hash: value.secret.hash(),
expires_at: value.expires_at,
issued_at: value.issued_at,
}
}
}
+3
View File
@@ -79,6 +79,9 @@ pub enum ReferenceRelation {
#[error("account member")]
AccountMember,
#[error("access token")]
AccessToken,
#[error("account")]
Account,
+197 -61
View File
@@ -1,94 +1,230 @@
use chrono::{DateTime, Utc};
use super::RepositoryError;
use super::{ReferenceRelation, ReferenceViolationKind, RepositoryError};
use crate::{
database::{self, dtos::TokenRow},
domain::Token,
database::{
self, Constraint, DatabaseError,
dtos::{AccessTokenRow, RefreshTokenRow},
},
domain::{HashedAccessToken, HashedRefreshToken, HashedSecret},
};
pub async fn get_by_access_token_hash<'e, E>(
#[tracing::instrument(skip(executor, secret_hash))]
pub async fn get_access_token_by_hash<'e, E>(
executor: E,
access_token_hash: &[u8],
) -> Result<Option<Token>, RepositoryError>
secret_hash: &HashedSecret,
) -> Result<Option<HashedAccessToken>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let token = database::tokens::get_by_access_token_hash(executor, access_token_hash)
let token = database::tokens::get_access_token_by_hash(executor, secret_hash.hash())
.await?
.map(decode)
.transpose()?;
.map(decode_access_token);
Ok(token)
}
pub async fn issue<'e, E>(executor: E, token: Token) -> Result<(), RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
database::tokens::issue(executor, encode(token)).await?;
Ok(())
}
pub async fn rotate_refresh_token<'e, E>(
#[tracing::instrument(skip(executor, secret_hash))]
pub async fn get_access_token_by_refresh_hash<'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>
secret_hash: &HashedSecret,
) -> Result<Option<HashedAccessToken>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let rotated = database::tokens::rotate_refresh_token(
let token =
database::tokens::get_access_token_by_refresh_secret_hash(executor, secret_hash.hash())
.await?
.map(decode_access_token);
Ok(token)
}
#[tracing::instrument(skip(executor, access_token))]
pub async fn insert_access_token<'e, E>(
executor: E,
access_token: HashedAccessToken,
) -> Result<HashedAccessToken, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let token = database::tokens::insert_access_token(executor, encode_access_token(access_token))
.await
.map_err(classify_insert_error)?;
Ok(decode_access_token(token))
}
#[tracing::instrument(skip(executor, secret_hash, new_secret_hash))]
pub async fn update_access_token_by_hash<'e, E>(
executor: E,
secret_hash: &HashedSecret,
new_secret_hash: &HashedSecret,
new_expires_at: DateTime<Utc>,
new_issued_at: DateTime<Utc>,
) -> Result<Option<HashedAccessToken>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let token = database::tokens::update_access_token_by_hash(
executor,
old_refresh_hash,
access_token_hash,
refresh_token_hash,
access_expires_at,
refresh_expires_at,
secret_hash.hash(),
new_secret_hash.hash(),
new_expires_at,
new_issued_at,
)
.await?;
.await?
.map(decode_access_token);
Ok(rotated)
Ok(token)
}
pub async fn revoke<'e, E>(executor: E, token_hash: &[u8]) -> Result<(), RepositoryError>
#[tracing::instrument(skip(executor, secret_hash))]
pub async fn delete_access_token_by_hash<'e, E>(
executor: E,
secret_hash: &HashedSecret,
) -> Result<Option<HashedAccessToken>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
database::tokens::revoke(executor, token_hash).await?;
let token = database::tokens::delete_access_token_by_hash(executor, secret_hash.hash())
.await?
.map(decode_access_token);
Ok(())
Ok(token)
}
fn decode(token: TokenRow) -> Result<Token, RepositoryError> {
Ok(Token {
id: token.id,
user_id: token.user_id,
user_app_id: token.user_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,
refreshed_at: token.refreshed_at,
revoked_at: token.revoked_at,
created_at: token.created_at,
})
#[tracing::instrument(skip(executor, secret_hash))]
pub async fn get_refresh_token_by_hash<'e, E>(
executor: E,
secret_hash: &HashedSecret,
) -> Result<Option<HashedRefreshToken>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let token = database::tokens::get_refresh_token_by_hash(executor, secret_hash.hash())
.await?
.map(decode_refresh_token);
Ok(token)
}
fn encode(token: Token) -> TokenRow {
TokenRow {
id: token.id,
user_id: token.user_id,
user_app_id: token.user_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,
refreshed_at: token.refreshed_at,
revoked_at: token.revoked_at,
created_at: token.created_at,
// pub async fn insert_refresh_token<'e, E>(
// executor: E,
// refresh_token: HashedRefreshToken,
// ) -> Result<HashedRefreshToken, RepositoryError>
// where
// E: sqlx::Executor<'e, Database = sqlx::Postgres>,
// {
// let token =
// database::tokens::insert_refresh_token(executor, encode_refresh_token(refresh_token))
// .await
// .map_err(classify_insert_error)?;
// Ok(decode_refresh_token(token))
// }
#[tracing::instrument(skip(executor, secret_hash, new_secret_hash))]
pub async fn update_refresh_token_by_hash<'e, E>(
executor: E,
secret_hash: &HashedSecret,
new_secret_hash: &HashedSecret,
new_expires_at: DateTime<Utc>,
new_issued_at: DateTime<Utc>,
) -> Result<Option<HashedRefreshToken>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let token = database::tokens::update_refresh_token_by_hash(
executor,
secret_hash.hash(),
new_secret_hash.hash(),
new_expires_at,
new_issued_at,
)
.await?
.map(decode_refresh_token);
Ok(token)
}
#[tracing::instrument(skip(executor, secret_hash))]
pub async fn delete_refresh_token_by_hash<'e, E>(
executor: E,
secret_hash: &HashedSecret,
) -> Result<Option<HashedRefreshToken>, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let token = database::tokens::delete_refresh_token_by_hash(executor, secret_hash.hash())
.await?
.map(decode_refresh_token);
Ok(token)
}
fn classify_insert_error(error: DatabaseError) -> RepositoryError {
let relation = match &error {
DatabaseError::ForeignKeyViolation {
constraint: Constraint::AccessTokenUser,
..
} => ReferenceRelation::User,
DatabaseError::ForeignKeyViolation {
constraint: Constraint::AccessTokenUserApp,
..
} => ReferenceRelation::UserApp,
DatabaseError::ForeignKeyViolation {
constraint: Constraint::RefreshTokenAccessToken,
..
} => ReferenceRelation::AccessToken,
_ => return RepositoryError::Database(error),
};
RepositoryError::ReferenceViolation {
relation,
kind: ReferenceViolationKind::Missing,
source: error,
}
}
fn decode_access_token(row: AccessTokenRow) -> HashedAccessToken {
HashedAccessToken {
id: row.id,
user_id: row.user_id,
user_app_id: row.user_app_id,
secret_hash: HashedSecret::from(row.secret_hash),
expires_at: row.expires_at,
issued_at: row.issued_at,
}
}
fn encode_access_token(token: HashedAccessToken) -> AccessTokenRow {
AccessTokenRow {
id: token.id,
user_id: token.user_id,
user_app_id: token.user_app_id,
secret_hash: token.secret_hash.hash().to_vec(),
expires_at: token.expires_at,
issued_at: token.issued_at,
}
}
fn decode_refresh_token(row: RefreshTokenRow) -> HashedRefreshToken {
HashedRefreshToken {
id: row.id,
token_id: row.access_token_id,
secret_hash: HashedSecret::from(row.secret_hash),
expires_at: row.expires_at,
issued_at: row.issued_at,
}
}
// fn encode_refresh_token(token: HashedRefreshToken) -> RefreshTokenRow {
// RefreshTokenRow {
// id: token.id,
// access_token_id: token.token_id,
// secret_hash: token.secret_hash.hash().to_vec(),
// expires_at: token.expires_at,
// issued_at: token.issued_at,
// }
// }
+3 -3
View File
@@ -5,7 +5,7 @@ use super::{
};
use crate::{
database::{self, Constraint, DatabaseError, dtos::UserAppSecretRow},
domain::UserAppSecret,
domain::{HashedSecret, UserAppSecret},
repository::DecodeError,
};
@@ -95,12 +95,12 @@ fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
pub async fn verify<'e, E>(
executor: E,
app_id: Uuid,
secret_hash: &[u8],
secret_hash: &HashedSecret,
) -> Result<bool, RepositoryError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
{
let is_valid = database::user_app_secrets::verify(executor, app_id, secret_hash).await?;
let is_valid = database::user_app_secrets::verify(executor, app_id, secret_hash.hash()).await?;
Ok(is_valid)
}
+52 -83
View File
@@ -1,16 +1,13 @@
use axum::{extract::State, routing::post};
use chrono::{DateTime, Utc};
use sqlx::PgPool;
use uuid::Uuid;
use crate::{
config::TokenConfig,
crypto::{generate_secret, hash_secret},
domain::{self, Token},
domain::{AccessToken, Secret},
error::AppError,
repository,
routes::{
dtos::token::{TokenRequest, TokenResponse, TokenRevocationRequest, TokenType},
dtos::token::{TokenRequest, TokenResponse, TokenRevocationRequest},
extractors::{Form, Json},
},
};
@@ -33,41 +30,57 @@ async fn issue_token(
client_id,
client_secret,
} => {
let token_pair = TokenPair::from_config(&token_config)?;
let secret_hash = hash_secret(&client_secret);
if !repository::user_app_secrets::verify(&pool, client_id, &secret_hash).await? {
let token_hash = Secret::from(client_secret).hash();
let (true, Some(app)) = (
repository::user_app_secrets::verify(&pool, client_id, &token_hash).await?,
repository::user_apps::get_by_id_unscoped(&pool, client_id).await?,
) else {
return Err(AppError::InvalidClientCredentials);
}
};
let app = repository::user_apps::get_by_id_unscoped(&pool, client_id)
.await?
.ok_or(AppError::InvalidClientCredentials)?;
let access_token = AccessToken::new(
app.user_id,
Some(app.id),
token_config.access_token_lifetime,
)?;
let token = token(&app, &token_pair);
repository::tokens::insert_access_token(&pool, access_token.clone().into()).await?;
repository::tokens::issue(&pool, token).await?;
Ok(Json(token_response(&token_pair, &token_config)))
Ok(Json(TokenResponse::new(access_token, None)))
}
TokenRequest::RefreshToken { refresh_token } => {
let token_pair = TokenPair::from_config(&token_config)?;
let old_refresh_token_hash = hash_secret(&refresh_token);
if !repository::tokens::rotate_refresh_token(
&pool,
&old_refresh_token_hash,
&token_pair.access_token_hash,
&token_pair.refresh_token_hash,
token_pair.access_expires_at,
token_pair.refresh_expires_at,
)
.await?
{
let token_hash = Secret::from(refresh_token).hash();
let (Some(access_token), Some(refresh_token)) = (
repository::tokens::get_access_token_by_refresh_hash(&pool, &token_hash).await?,
repository::tokens::get_refresh_token_by_hash(&pool, &token_hash).await?,
) else {
return Err(AppError::InvalidRefreshToken);
}
};
Ok(Json(token_response(&token_pair, &token_config)))
let new_access_token = access_token.refresh(token_config.access_token_lifetime)?;
repository::tokens::update_access_token_by_hash(
&pool,
&token_hash,
&new_access_token.secret.hash(),
new_access_token.expires_at,
new_access_token.issued_at,
)
.await?;
let new_refresh_token = refresh_token.refresh(token_config.refresh_token_lifetime)?;
repository::tokens::update_refresh_token_by_hash(
&pool,
&token_hash,
&new_refresh_token.secret.hash(),
new_refresh_token.expires_at,
new_refresh_token.issued_at,
)
.await?;
Ok(Json(TokenResponse::new(
new_access_token,
Some(new_refresh_token),
)))
}
}
}
@@ -78,58 +91,14 @@ async fn revoke_token(
State(pool): State<PgPool>,
Form(request): Form<TokenRevocationRequest>,
) -> Result<(), AppError> {
let token_hash = hash_secret(&request.token);
let token_hash = Secret::from(request.token).hash();
repository::tokens::revoke(&pool, &token_hash).await?;
repository::tokens::delete_access_token_by_hash(&pool, &token_hash)
.await
.ok();
repository::tokens::delete_refresh_token_by_hash(&pool, &token_hash)
.await
.ok();
Ok(())
}
struct TokenPair {
access_token: String,
refresh_token: String,
access_token_hash: Vec<u8>,
refresh_token_hash: Vec<u8>,
access_expires_at: DateTime<Utc>,
refresh_expires_at: DateTime<Utc>,
}
impl TokenPair {
fn from_config(token_config: &TokenConfig) -> Result<Self, AppError> {
let access_token = generate_secret().map_err(|_| AppError::Unknown)?;
let refresh_token = generate_secret().map_err(|_| AppError::Unknown)?;
let now = Utc::now();
Ok(TokenPair {
access_token_hash: hash_secret(&access_token),
refresh_token_hash: hash_secret(&refresh_token),
access_expires_at: now + token_config.access_token_lifetime,
refresh_expires_at: now + token_config.refresh_token_lifetime,
access_token,
refresh_token,
})
}
}
fn token(user_app: &domain::UserApp, generated: &TokenPair) -> Token {
Token {
id: Uuid::new_v4(),
user_id: user_app.user_id,
user_app_id: Some(user_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,
refreshed_at: None,
revoked_at: None,
created_at: Utc::now(),
}
}
fn token_response(generated: &TokenPair, token_config: &TokenConfig) -> TokenResponse {
TokenResponse {
access_token: generated.access_token.clone(),
token_type: TokenType::Bearer,
expires_in: token_config.access_token_lifetime.num_seconds(),
refresh_token: Some(generated.refresh_token.clone()),
}
}
+16
View File
@@ -1,6 +1,9 @@
use chrono::Utc;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::domain::{AccessToken, RefreshToken};
#[derive(Deserialize)]
#[serde(rename_all = "snake_case", tag = "grant_type")]
pub enum TokenRequest {
@@ -23,9 +26,22 @@ pub struct TokenResponse {
pub access_token: String,
pub token_type: TokenType,
pub expires_in: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
}
impl TokenResponse {
pub fn new(access_token: AccessToken, refresh_token: Option<RefreshToken>) -> Self {
Self {
access_token: access_token.secret.secret().to_string(),
token_type: TokenType::Bearer,
expires_in: (access_token.expires_at - Utc::now()).num_seconds(),
refresh_token: refresh_token.map(|r| r.secret.secret().to_string()),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TokenType {
+8 -7
View File
@@ -61,13 +61,14 @@ impl ClientError for AppError {
impl ClientError for DomainError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
let message: String = match self {
Self::Amount(error) => error.to_string(),
Self::Schedule(error) => error.to_string(),
Self::UserAppSecret(error) => error.to_string(),
};
(StatusCode::UNPROCESSABLE_ENTITY, message.into())
match self {
Self::Amount(error) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string().into()),
Self::Secret(_) => internal_error(),
Self::Schedule(error) => (StatusCode::UNPROCESSABLE_ENTITY, error.to_string().into()),
Self::UserAppSecret(error) => {
(StatusCode::UNPROCESSABLE_ENTITY, error.to_string().into())
}
}
}
}
+3 -3
View File
@@ -3,7 +3,7 @@ use sqlx::PgPool;
use super::{AuthScheme, Authorizer, Principal};
use crate::{
crypto::hash_secret,
domain::Secret,
repository::{self, RepositoryError},
};
@@ -32,8 +32,8 @@ where
) -> Result<Principal<Self>, Self::Error> {
let pool = PgPool::from_ref(state);
let token_hash = hash_secret(&credentials.0);
let token = repository::tokens::get_by_access_token_hash(&pool, &token_hash)
let token_hash = Secret::from(credentials.0).hash();
let token = repository::tokens::get_access_token_by_hash(&pool, &token_hash)
.await
.map_err(BearerError::Repository)?
.ok_or(BearerError::InvalidCredentials)?;