Skip to main content

wabot_addon_auth_pg/
lib.rs

1//! # wabot-addon-auth-pg
2//!
3//! Postgres storage for auth. Port of `ApiKeyPgQueries` and
4//! `JwtRefreshTokenPgQueries` in wabot-ts,
5//! on top of [`PgJsonbStore`] — so an API key is a document in the
6//! same table shape every other stored entity uses, and the two stacks
7//! can share it.
8//!
9//! ```ignore
10//! let repository = Arc::new(PgApiKeyRepository::new(pool));
11//! register_api_key_repository(&container, repository);
12//! register_singletons!(&container, ApiKeyGuard);
13//! ```
14//!
15//! Both API keys and refresh tokens live here, because they are the
16//! same problem twice: a stored credential looked up by the hash of a
17//! secret nobody else holds.
18//!
19//! ## The lookup is by hash, and it is indexed
20//!
21//! Only the SHA-256 hash of a secret is stored, and authentication
22//! looks a key up *by that hash* — database read access alone doesn't
23//! let anyone in. That makes the hash the hot column, so it is
24//! promoted out of the JSON document and indexed; a sequential scan
25//! over every key on every request would be a denial-of-service
26//! waiting for the key table to grow.
27
28use std::sync::Arc;
29
30use async_trait::async_trait;
31use sqlx::PgPool;
32use wabot_addon_auth_api_key::{ApiKey, ApiKeyData, ApiKeyError, ApiKeyRepository};
33use wabot_feature_pg::{PgJsonbStore, PromotedColumn};
34
35/// API keys in a Postgres table.
36pub struct PgApiKeyRepository {
37    store: PgJsonbStore<ApiKeyData>,
38}
39
40impl PgApiKeyRepository {
41    /// Keys in `api_keys`.
42    pub fn new(pool: PgPool) -> Self {
43        Self::with_table(pool, "api_keys")
44    }
45
46    pub fn with_table(pool: PgPool, table: impl Into<String>) -> Self {
47        let store = PgJsonbStore::<ApiKeyData>::new(pool, table)
48            // Promoted because every authentication filters on it —
49            // see the module note.
50            .with_promoted_column(PromotedColumn {
51                name: "secret_hash",
52                ddl_type: "TEXT",
53                value: |data: &ApiKeyData| data.secret_hash.clone(),
54            })
55            .with_index(
56                "CREATE UNIQUE INDEX IF NOT EXISTS api_keys_secret_hash_idx \
57                 ON \"public\".\"api_keys\" (\"secret_hash\")",
58            );
59        Self { store }
60    }
61
62    pub fn store(&self) -> &PgJsonbStore<ApiKeyData> {
63        &self.store
64    }
65}
66
67fn storage_error(error: wabot_feature_pg::PgError) -> ApiKeyError {
68    ApiKeyError::Storage(error.to_string())
69}
70
71#[async_trait]
72impl ApiKeyRepository for PgApiKeyRepository {
73    async fn find_by_hash(&self, secret_hash: &str) -> Result<Option<ApiKey>, ApiKeyError> {
74        let sql = format!(
75            "SELECT \"data\" FROM {} WHERE \"secret_hash\" = $1 LIMIT 1",
76            self.store.table()
77        );
78        let hash = secret_hash.to_string();
79        self.store
80            .query_opt(&sql, move |q| q.bind(hash))
81            .await
82            .map_err(storage_error)
83    }
84
85    async fn create(&self, key: &ApiKey) -> Result<(), ApiKeyError> {
86        self.store.create(key).await.map_err(storage_error)
87    }
88
89    async fn update(&self, key: &ApiKey) -> Result<(), ApiKeyError> {
90        // `save`, not `update`: revoking a key that another node
91        // already wrote must not fail on a primary-key conflict, and
92        // an update that matched nothing is not something a caller can
93        // act on differently here.
94        self.store.save(key).await.map_err(storage_error)
95    }
96}
97
98/// Register a Postgres-backed API-key repository.
99pub fn register_pg_api_key_repository(
100    container: &wabot_core::injection::Container,
101    pool: PgPool,
102) -> Arc<PgApiKeyRepository> {
103    let repository = Arc::new(PgApiKeyRepository::new(pool));
104    wabot_addon_auth_api_key::register_api_key_repository(container, repository.clone());
105    repository
106}
107
108// ---------- refresh tokens ------------------------------------------
109
110use wabot_addon_auth_jwt::refresh::{RefreshToken, RefreshTokenData, RefreshTokenRepository};
111use wabot_addon_auth_jwt::RefreshError;
112
113/// Refresh tokens in a Postgres table.
114///
115/// Same shape as the API-key repository, and for the same reason: a
116/// session is looked up by the hash of a secret, so the hash is
117/// promoted and indexed.
118pub struct PgRefreshTokenRepository {
119    store: PgJsonbStore<RefreshTokenData>,
120}
121
122impl PgRefreshTokenRepository {
123    /// Sessions in `jwt_refresh_tokens`.
124    pub fn new(pool: PgPool) -> Self {
125        Self::with_table(pool, "jwt_refresh_tokens")
126    }
127
128    pub fn with_table(pool: PgPool, table: impl Into<String>) -> Self {
129        let table = table.into();
130        let index = Box::leak(
131            format!(
132                "CREATE UNIQUE INDEX IF NOT EXISTS {table}_secret_hash_idx \
133                 ON \"public\".\"{table}\" (\"secret_hash\")"
134            )
135            .into_boxed_str(),
136        );
137        let store = PgJsonbStore::<RefreshTokenData>::new(pool, table)
138            .with_promoted_column(PromotedColumn {
139                name: "secret_hash",
140                ddl_type: "TEXT",
141                value: |data: &RefreshTokenData| data.secret_hash.clone(),
142            })
143            .with_index(index);
144        Self { store }
145    }
146
147    pub fn store(&self) -> &PgJsonbStore<RefreshTokenData> {
148        &self.store
149    }
150}
151
152fn refresh_storage_error(error: wabot_feature_pg::PgError) -> RefreshError {
153    RefreshError::Storage(error.to_string())
154}
155
156#[async_trait]
157impl RefreshTokenRepository for PgRefreshTokenRepository {
158    async fn find_by_hash(&self, secret_hash: &str) -> Result<Option<RefreshToken>, RefreshError> {
159        let sql = format!(
160            "SELECT \"data\" FROM {} WHERE \"secret_hash\" = $1 LIMIT 1",
161            self.store.table()
162        );
163        let hash = secret_hash.to_string();
164        self.store
165            .query_opt(&sql, move |q| q.bind(hash))
166            .await
167            .map_err(refresh_storage_error)
168    }
169
170    async fn create(&self, token: &RefreshToken) -> Result<(), RefreshError> {
171        self.store
172            .create(token)
173            .await
174            .map_err(refresh_storage_error)
175    }
176
177    async fn update(&self, token: &RefreshToken) -> Result<(), RefreshError> {
178        // `save`: revoking a session another node already wrote must
179        // not fail on a primary-key conflict.
180        self.store.save(token).await.map_err(refresh_storage_error)
181    }
182}
183
184/// Register Postgres-backed refresh-token storage.
185pub fn register_pg_refresh_token_repository(
186    container: &wabot_core::injection::Container,
187    pool: PgPool,
188) -> Arc<PgRefreshTokenRepository> {
189    let repository = Arc::new(PgRefreshTokenRepository::new(pool));
190    wabot_addon_auth_jwt::register_refresh_token_repository(container, repository.clone());
191    repository
192}