From 26999d690f34ab9b1acf25e2c19179345ceb1978 Mon Sep 17 00:00:00 2001 From: Rogier Reerink Date: Sun, 18 Oct 2026 13:21:48 +0200 Subject: [PATCH] Reimplemented access and refresh tokens. --- server/.env.example | 4 +- ...a0aa89ba9e99d8f22b06343ab27188233ec22.json | 93 ++++++ ...b67edcae1bb076099c81637f2b882637419b7.json | 79 +++++ ...7f63c401aea690fdae95d74d03d86bdaa2a56.json | 88 +++++ ...ba104132c065ac1c1522c3dd80b4284faf1a1.json | 76 +++++ ...8b724cae757c55579da8f86adb778eefdbc48.json | 136 -------- ...44f7536d0b7c0c657aa87dc7539dcdbbc5014.json | 23 -- ...b36d316eca63173b1463d5b3bed3e08d7ab19.json | 76 +++++ ...182a94adf1952a800371e668aeab6897c94c5.json | 14 - ...1bbb02a64b5743406428dd18f8199ad8fb77b.json | 80 +++++ ...ac4f7b0ee2940954d7e902e6952488b9cb18a.json | 88 +++++ ...0863e865e799bd347d84885e563e7761d2e06.json | 91 +++++ ...1dfccde168a6ce21992c556938940f8f49b91.json | 88 +++++ ...313aaeaa275cf6e41272347821735d4b401d6.json | 32 -- .../20261007000002_create_tokens.sql | 28 +- server/src/database.rs | 12 + server/src/database/dtos/token.rs | 20 +- server/src/database/tokens.rs | 313 +++++++++++++----- server/src/domain.rs | 5 + server/src/domain/secret.rs | 79 +++++ server/src/domain/token.rs | 126 ++++++- server/src/repository.rs | 3 + server/src/repository/tokens.rs | 258 +++++++++++---- server/src/repository/user_app_secrets.rs | 6 +- server/src/routes/auth_token.rs | 135 +++----- server/src/routes/dtos/token.rs | 16 + server/src/routes/errors.rs | 15 +- server/src/routes/extractors/auth/bearer.rs | 6 +- 28 files changed, 1510 insertions(+), 480 deletions(-) create mode 100644 server/.sqlx/query-0d7964d66f11a466461a5938ef1a0aa89ba9e99d8f22b06343ab27188233ec22.json create mode 100644 server/.sqlx/query-4b8559a53ceed6a384e287d52dcb67edcae1bb076099c81637f2b882637419b7.json create mode 100644 server/.sqlx/query-50a9f81495657e35bedbf7fa3107f63c401aea690fdae95d74d03d86bdaa2a56.json create mode 100644 server/.sqlx/query-6262f385b10112a7d3cc98121c8ba104132c065ac1c1522c3dd80b4284faf1a1.json delete mode 100644 server/.sqlx/query-755b789df9d3d7f92243481e8fc8b724cae757c55579da8f86adb778eefdbc48.json delete mode 100644 server/.sqlx/query-768ccffe4387ae725e2e2ab1f5544f7536d0b7c0c657aa87dc7539dcdbbc5014.json create mode 100644 server/.sqlx/query-8a5728429d71470fc276d2572f9b36d316eca63173b1463d5b3bed3e08d7ab19.json delete mode 100644 server/.sqlx/query-9f8fc6351a1261dcb91eb6f2bfe182a94adf1952a800371e668aeab6897c94c5.json create mode 100644 server/.sqlx/query-a1d81c17935a785a1001ee0673e1bbb02a64b5743406428dd18f8199ad8fb77b.json create mode 100644 server/.sqlx/query-e5c0bc537264fb01e0eaca622ccac4f7b0ee2940954d7e902e6952488b9cb18a.json create mode 100644 server/.sqlx/query-e9ab22c5b968148c8b1eeb03a120863e865e799bd347d84885e563e7761d2e06.json create mode 100644 server/.sqlx/query-f052080688bdab0724707575aa61dfccde168a6ce21992c556938940f8f49b91.json delete mode 100644 server/.sqlx/query-f90d488ec2fff2e09bfbc83c287313aaeaa275cf6e41272347821735d4b401d6.json create mode 100644 server/src/domain/secret.rs diff --git a/server/.env.example b/server/.env.example index 4cd3c57..0f0a241 100644 --- a/server/.env.example +++ b/server/.env.example @@ -1,4 +1,6 @@ RUST_LOG=info HOST=127.0.0.1 PORT=3000 -DATABASE_URL=postgres://expenses:expenses@localhost:5432/expenses \ No newline at end of file +DATABASE_URL=postgres://expenses:expenses@localhost:5432/expenses +ACCESS_TOKEN_LIFETIME_SECONDS=3600 # 1 hour +REFRESH_TOKEN_LIFETIME_SECONDS=2592000 # 30 days \ No newline at end of file diff --git a/server/.sqlx/query-0d7964d66f11a466461a5938ef1a0aa89ba9e99d8f22b06343ab27188233ec22.json b/server/.sqlx/query-0d7964d66f11a466461a5938ef1a0aa89ba9e99d8f22b06343ab27188233ec22.json new file mode 100644 index 0000000..caf7f53 --- /dev/null +++ b/server/.sqlx/query-0d7964d66f11a466461a5938ef1a0aa89ba9e99d8f22b06343ab27188233ec22.json @@ -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" +} diff --git a/server/.sqlx/query-4b8559a53ceed6a384e287d52dcb67edcae1bb076099c81637f2b882637419b7.json b/server/.sqlx/query-4b8559a53ceed6a384e287d52dcb67edcae1bb076099c81637f2b882637419b7.json new file mode 100644 index 0000000..4fe8816 --- /dev/null +++ b/server/.sqlx/query-4b8559a53ceed6a384e287d52dcb67edcae1bb076099c81637f2b882637419b7.json @@ -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" +} diff --git a/server/.sqlx/query-50a9f81495657e35bedbf7fa3107f63c401aea690fdae95d74d03d86bdaa2a56.json b/server/.sqlx/query-50a9f81495657e35bedbf7fa3107f63c401aea690fdae95d74d03d86bdaa2a56.json new file mode 100644 index 0000000..ccd892f --- /dev/null +++ b/server/.sqlx/query-50a9f81495657e35bedbf7fa3107f63c401aea690fdae95d74d03d86bdaa2a56.json @@ -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" +} diff --git a/server/.sqlx/query-6262f385b10112a7d3cc98121c8ba104132c065ac1c1522c3dd80b4284faf1a1.json b/server/.sqlx/query-6262f385b10112a7d3cc98121c8ba104132c065ac1c1522c3dd80b4284faf1a1.json new file mode 100644 index 0000000..c1c802a --- /dev/null +++ b/server/.sqlx/query-6262f385b10112a7d3cc98121c8ba104132c065ac1c1522c3dd80b4284faf1a1.json @@ -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" +} diff --git a/server/.sqlx/query-755b789df9d3d7f92243481e8fc8b724cae757c55579da8f86adb778eefdbc48.json b/server/.sqlx/query-755b789df9d3d7f92243481e8fc8b724cae757c55579da8f86adb778eefdbc48.json deleted file mode 100644 index 450d122..0000000 --- a/server/.sqlx/query-755b789df9d3d7f92243481e8fc8b724cae757c55579da8f86adb778eefdbc48.json +++ /dev/null @@ -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" -} diff --git a/server/.sqlx/query-768ccffe4387ae725e2e2ab1f5544f7536d0b7c0c657aa87dc7539dcdbbc5014.json b/server/.sqlx/query-768ccffe4387ae725e2e2ab1f5544f7536d0b7c0c657aa87dc7539dcdbbc5014.json deleted file mode 100644 index 2612a28..0000000 --- a/server/.sqlx/query-768ccffe4387ae725e2e2ab1f5544f7536d0b7c0c657aa87dc7539dcdbbc5014.json +++ /dev/null @@ -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" -} diff --git a/server/.sqlx/query-8a5728429d71470fc276d2572f9b36d316eca63173b1463d5b3bed3e08d7ab19.json b/server/.sqlx/query-8a5728429d71470fc276d2572f9b36d316eca63173b1463d5b3bed3e08d7ab19.json new file mode 100644 index 0000000..8f4a7c6 --- /dev/null +++ b/server/.sqlx/query-8a5728429d71470fc276d2572f9b36d316eca63173b1463d5b3bed3e08d7ab19.json @@ -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" +} diff --git a/server/.sqlx/query-9f8fc6351a1261dcb91eb6f2bfe182a94adf1952a800371e668aeab6897c94c5.json b/server/.sqlx/query-9f8fc6351a1261dcb91eb6f2bfe182a94adf1952a800371e668aeab6897c94c5.json deleted file mode 100644 index dbec2c0..0000000 --- a/server/.sqlx/query-9f8fc6351a1261dcb91eb6f2bfe182a94adf1952a800371e668aeab6897c94c5.json +++ /dev/null @@ -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" -} diff --git a/server/.sqlx/query-a1d81c17935a785a1001ee0673e1bbb02a64b5743406428dd18f8199ad8fb77b.json b/server/.sqlx/query-a1d81c17935a785a1001ee0673e1bbb02a64b5743406428dd18f8199ad8fb77b.json new file mode 100644 index 0000000..8b44597 --- /dev/null +++ b/server/.sqlx/query-a1d81c17935a785a1001ee0673e1bbb02a64b5743406428dd18f8199ad8fb77b.json @@ -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" +} diff --git a/server/.sqlx/query-e5c0bc537264fb01e0eaca622ccac4f7b0ee2940954d7e902e6952488b9cb18a.json b/server/.sqlx/query-e5c0bc537264fb01e0eaca622ccac4f7b0ee2940954d7e902e6952488b9cb18a.json new file mode 100644 index 0000000..33ca233 --- /dev/null +++ b/server/.sqlx/query-e5c0bc537264fb01e0eaca622ccac4f7b0ee2940954d7e902e6952488b9cb18a.json @@ -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" +} diff --git a/server/.sqlx/query-e9ab22c5b968148c8b1eeb03a120863e865e799bd347d84885e563e7761d2e06.json b/server/.sqlx/query-e9ab22c5b968148c8b1eeb03a120863e865e799bd347d84885e563e7761d2e06.json new file mode 100644 index 0000000..fc7d2cc --- /dev/null +++ b/server/.sqlx/query-e9ab22c5b968148c8b1eeb03a120863e865e799bd347d84885e563e7761d2e06.json @@ -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" +} diff --git a/server/.sqlx/query-f052080688bdab0724707575aa61dfccde168a6ce21992c556938940f8f49b91.json b/server/.sqlx/query-f052080688bdab0724707575aa61dfccde168a6ce21992c556938940f8f49b91.json new file mode 100644 index 0000000..fefa838 --- /dev/null +++ b/server/.sqlx/query-f052080688bdab0724707575aa61dfccde168a6ce21992c556938940f8f49b91.json @@ -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" +} diff --git a/server/.sqlx/query-f90d488ec2fff2e09bfbc83c287313aaeaa275cf6e41272347821735d4b401d6.json b/server/.sqlx/query-f90d488ec2fff2e09bfbc83c287313aaeaa275cf6e41272347821735d4b401d6.json deleted file mode 100644 index 3a1b8e2..0000000 --- a/server/.sqlx/query-f90d488ec2fff2e09bfbc83c287313aaeaa275cf6e41272347821735d4b401d6.json +++ /dev/null @@ -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" -} diff --git a/server/migrations/20261007000002_create_tokens.sql b/server/migrations/20261007000002_create_tokens.sql index 39cbb5f..626ccee 100644 --- a/server/migrations/20261007000002_create_tokens.sql +++ b/server/migrations/20261007000002_create_tokens.sql @@ -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 ); \ No newline at end of file diff --git a/server/src/database.rs b/server/src/database.rs index 5855ae0..4e66961 100644 --- a/server/src/database.rs +++ b/server/src/database.rs @@ -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, diff --git a/server/src/database/dtos/token.rs b/server/src/database/dtos/token.rs index fc3460c..b462817 100644 --- a/server/src/database/dtos/token.rs +++ b/server/src/database/dtos/token.rs @@ -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, - pub access_token_hash: Vec, - pub refresh_token_hash: Vec, - pub access_expires_at: DateTime, - pub refresh_expires_at: DateTime, - pub refreshed_at: Option>, - pub revoked_at: Option>, - pub created_at: DateTime, + pub secret_hash: Vec, + pub expires_at: DateTime, + pub issued_at: DateTime, +} + +pub struct RefreshTokenRow { + pub id: Uuid, + pub access_token_id: Uuid, + pub secret_hash: Vec, + pub expires_at: DateTime, + pub issued_at: DateTime, } diff --git a/server/src/database/tokens.rs b/server/src/database/tokens.rs index ec90e9c..f710c5f 100644 --- a/server/src/database/tokens.rs +++ b/server/src/database/tokens.rs @@ -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, DatabaseError> + secret_hash: &[u8], +) -> Result, 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, - refresh_expires_at: DateTime, -) -> Result + refresh_secret_hash: &[u8], +) -> Result, 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 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, + new_issued_at: DateTime, +) -> Result, 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, 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, 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 +// 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, + new_issued_at: DateTime, +) -> Result, 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, 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) } diff --git a/server/src/domain.rs b/server/src/domain.rs index 5785064..565a40b 100644 --- a/server/src/domain.rs +++ b/server/src/domain.rs @@ -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), diff --git a/server/src/domain/secret.rs b/server/src/domain/secret.rs new file mode 100644 index 0000000..cc9e483 --- /dev/null +++ b/server/src/domain/secret.rs @@ -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 { + Ok(Self(generate_secret().map_err(|_| SecretError)?)) + } + + pub fn secret(&self) -> &str { + &self.0 + } + + pub fn hash(&self) -> HashedSecret { + HashedSecret::from(self) + } +} + +impl From for Secret { + fn from(value: String) -> Self { + Self(value) + } +} + +#[derive(Clone, PartialEq, Eq)] +pub struct HashedSecret(Vec); + +impl HashedSecret { + pub fn hash(&self) -> &[u8] { + &self.0 + } +} + +impl From> for HashedSecret { + fn from(value: Vec) -> 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()); + } +} diff --git a/server/src/domain/token.rs b/server/src/domain/token.rs index 72d69ce..8283049 100644 --- a/server/src/domain/token.rs +++ b/server/src/domain/token.rs @@ -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, - pub access_token_hash: Vec, - pub refresh_token_hash: Vec, - pub access_expires_at: DateTime, - pub refresh_expires_at: DateTime, - pub refreshed_at: Option>, - pub revoked_at: Option>, - pub created_at: DateTime, + pub secret: Secret, + pub expires_at: DateTime, + pub issued_at: DateTime, +} + +impl AccessToken { + pub fn new( + user_id: Uuid, + user_app_id: Option, + lifetime: Duration, + ) -> Result { + 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, + pub secret_hash: HashedSecret, + pub expires_at: DateTime, + pub issued_at: DateTime, +} + +impl HashedAccessToken { + pub fn refresh(self, lifetime: Duration) -> Result { + 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 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, + pub issued_at: DateTime, +} + +impl RefreshToken { + // pub fn generate(token_id: Uuid, lifetime: Duration) -> Result { + // 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, + pub issued_at: DateTime, +} + +impl HashedRefreshToken { + pub fn refresh(self, lifetime: Duration) -> Result { + Ok(RefreshToken { + id: self.id, + token_id: self.token_id, + secret: Secret::generate()?, + expires_at: Utc::now() + lifetime, + issued_at: Utc::now(), + }) + } +} + +impl From 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, + } + } } diff --git a/server/src/repository.rs b/server/src/repository.rs index e178efb..0940ad7 100644 --- a/server/src/repository.rs +++ b/server/src/repository.rs @@ -79,6 +79,9 @@ pub enum ReferenceRelation { #[error("account member")] AccountMember, + #[error("access token")] + AccessToken, + #[error("account")] Account, diff --git a/server/src/repository/tokens.rs b/server/src/repository/tokens.rs index cc39438..4b52fff 100644 --- a/server/src/repository/tokens.rs +++ b/server/src/repository/tokens.rs @@ -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, RepositoryError> + secret_hash: &HashedSecret, +) -> Result, 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, - refresh_expires_at: DateTime, -) -> Result + secret_hash: &HashedSecret, +) -> Result, 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 +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, + new_issued_at: DateTime, +) -> Result, 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, 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 { - 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, 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 +// 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, + new_issued_at: DateTime, +) -> Result, 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, 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, +// } +// } diff --git a/server/src/repository/user_app_secrets.rs b/server/src/repository/user_app_secrets.rs index 758f28b..627378f 100644 --- a/server/src/repository/user_app_secrets.rs +++ b/server/src/repository/user_app_secrets.rs @@ -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 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) } diff --git a/server/src/routes/auth_token.rs b/server/src/routes/auth_token.rs index 0ead054..262cfee 100644 --- a/server/src/routes/auth_token.rs +++ b/server/src/routes/auth_token.rs @@ -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, Form(request): Form, ) -> 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, - refresh_token_hash: Vec, - access_expires_at: DateTime, - refresh_expires_at: DateTime, -} - -impl TokenPair { - fn from_config(token_config: &TokenConfig) -> Result { - 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()), - } -} diff --git a/server/src/routes/dtos/token.rs b/server/src/routes/dtos/token.rs index 0c83449..ff839cf 100644 --- a/server/src/routes/dtos/token.rs +++ b/server/src/routes/dtos/token.rs @@ -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, } +impl TokenResponse { + pub fn new(access_token: AccessToken, refresh_token: Option) -> 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 { diff --git a/server/src/routes/errors.rs b/server/src/routes/errors.rs index 778ac8c..7e89fc4 100644 --- a/server/src/routes/errors.rs +++ b/server/src/routes/errors.rs @@ -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()) + } + } } } diff --git a/server/src/routes/extractors/auth/bearer.rs b/server/src/routes/extractors/auth/bearer.rs index 4da6e85..1237e2f 100644 --- a/server/src/routes/extractors/auth/bearer.rs +++ b/server/src/routes/extractors/auth/bearer.rs @@ -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, 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)?;