auth-framework 0.6.0-rc85

A comprehensive, production-ready authentication and authorization framework for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use crate::errors::{AuthError, Result, StorageError};
use crate::storage::{AuthStorage, SessionData};
use crate::tokens::AuthToken;
use async_trait::async_trait;
use chrono::Utc;
use sqlx::{Row, SqlitePool};
use std::time::Duration;

fn storage_err(error: sqlx::Error) -> AuthError {
    AuthError::Storage(StorageError::ConnectionFailed {
        message: error.to_string(),
    })
}

pub struct SqliteStorage {
    pool: SqlitePool,
}

impl SqliteStorage {
    pub fn new(pool: SqlitePool) -> Self {
        Self { pool }
    }

    pub async fn migrate(&self) -> Result<()> {
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS kv_store (
                key TEXT PRIMARY KEY,
                value BLOB NOT NULL,
                expires_at INTEGER
            )",
        )
        .execute(&self.pool)
        .await
        .map_err(storage_err)?;

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS auth_tokens (
                token_id TEXT PRIMARY KEY,
                user_id TEXT NOT NULL,
                access_token TEXT NOT NULL UNIQUE,
                data TEXT NOT NULL,
                expires_at INTEGER NOT NULL
            )",
        )
        .execute(&self.pool)
        .await
        .map_err(storage_err)?;

        sqlx::query("CREATE INDEX IF NOT EXISTS idx_auth_tokens_user_id ON auth_tokens(user_id)")
            .execute(&self.pool)
            .await
            .map_err(storage_err)?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_auth_tokens_access_token ON auth_tokens(access_token)",
        )
        .execute(&self.pool)
        .await
        .map_err(storage_err)?;

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS sessions (
                session_id TEXT PRIMARY KEY,
                user_id TEXT NOT NULL,
                data TEXT NOT NULL,
                expires_at INTEGER NOT NULL
            )",
        )
        .execute(&self.pool)
        .await
        .map_err(storage_err)?;

        sqlx::query("CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id)")
            .execute(&self.pool)
            .await
            .map_err(storage_err)?;

        Ok(())
    }
}

/// The `expires_at` (whole seconds) for an entry stored now with `ttl`.
///
/// An entry is alive while `expires_at >= now` (in whole seconds), i.e. through the second named
/// by `expires_at`. Using `floor((now + ttl) - 1ms)` makes it alive until the end of the second
/// that contains the true expiry instant, so it never expires EARLY and is at most one second
/// late. (`ttl.as_secs()` truncated the sub-second part, which made a TTL such as 1.5 s expire
/// anywhere between 0.5 s and 1.5 s after being stored.)
fn expires_at_secs(ttl: Duration) -> i64 {
    let expires_ms = Utc::now().timestamp_millis() + ttl.as_millis() as i64;
    (expires_ms - 1).div_euclid(1000)
}

#[async_trait]
impl AuthStorage for SqliteStorage {
    async fn store_token(&self, token: &AuthToken) -> Result<()> {
        let data = serde_json::to_string(token).map_err(|e| AuthError::internal(e.to_string()))?;
        let expires_at = token.expires_at.timestamp();

        sqlx::query(
            "INSERT INTO auth_tokens (token_id, user_id, access_token, data, expires_at)
             VALUES (?, ?, ?, ?, ?)
             ON CONFLICT(token_id) DO UPDATE SET
             user_id=excluded.user_id,
             access_token=excluded.access_token,
             data=excluded.data,
             expires_at=excluded.expires_at",
        )
        .bind(&token.token_id)
        .bind(&token.user_id)
        .bind(&token.access_token)
        .bind(data)
        .bind(expires_at)
        .execute(&self.pool)
        .await
        .map_err(storage_err)?;

        Ok(())
    }

    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
        let row = sqlx::query("SELECT data FROM auth_tokens WHERE token_id = ?")
            .bind(token_id)
            .fetch_optional(&self.pool)
            .await
            .map_err(storage_err)?;

        row.map(|row| {
            let data: String = row.get("data");
            serde_json::from_str(&data).map_err(|e| AuthError::internal(e.to_string()))
        })
        .transpose()
    }

    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
        let row = sqlx::query("SELECT data FROM auth_tokens WHERE access_token = ?")
            .bind(access_token)
            .fetch_optional(&self.pool)
            .await
            .map_err(storage_err)?;

        row.map(|row| {
            let data: String = row.get("data");
            serde_json::from_str(&data).map_err(|e| AuthError::internal(e.to_string()))
        })
        .transpose()
    }

    async fn update_token(&self, token: &AuthToken) -> Result<()> {
        self.store_token(token).await
    }

    async fn delete_token(&self, token_id: &str) -> Result<()> {
        sqlx::query("DELETE FROM auth_tokens WHERE token_id = ?")
            .bind(token_id)
            .execute(&self.pool)
            .await
            .map_err(storage_err)?;
        Ok(())
    }

    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
        let rows = sqlx::query("SELECT data FROM auth_tokens WHERE user_id = ?")
            .bind(user_id)
            .fetch_all(&self.pool)
            .await
            .map_err(storage_err)?;

        rows.into_iter()
            .map(|row| {
                let data: String = row.get("data");
                serde_json::from_str(&data).map_err(|e| AuthError::internal(e.to_string()))
            })
            .collect()
    }

    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
        let json = serde_json::to_string(data).map_err(|e| AuthError::internal(e.to_string()))?;
        let expires_at = data.expires_at.timestamp();

        sqlx::query(
            "INSERT INTO sessions (session_id, user_id, data, expires_at)
             VALUES (?, ?, ?, ?)
             ON CONFLICT(session_id) DO UPDATE SET
             user_id=excluded.user_id,
             data=excluded.data,
             expires_at=excluded.expires_at",
        )
        .bind(session_id)
        .bind(&data.user_id)
        .bind(json)
        .bind(expires_at)
        .execute(&self.pool)
        .await
        .map_err(storage_err)?;

        Ok(())
    }

    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
        let row = sqlx::query("SELECT data FROM sessions WHERE session_id = ?")
            .bind(session_id)
            .fetch_optional(&self.pool)
            .await
            .map_err(storage_err)?;

        row.map(|row| {
            let json: String = row.get("data");
            serde_json::from_str(&json).map_err(|e| AuthError::internal(e.to_string()))
        })
        .transpose()
    }

    async fn delete_session(&self, session_id: &str) -> Result<()> {
        sqlx::query("DELETE FROM sessions WHERE session_id = ?")
            .bind(session_id)
            .execute(&self.pool)
            .await
            .map_err(storage_err)?;
        Ok(())
    }

    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
        let rows = sqlx::query("SELECT data FROM sessions WHERE user_id = ?")
            .bind(user_id)
            .fetch_all(&self.pool)
            .await
            .map_err(storage_err)?;

        rows.into_iter()
            .map(|row| {
                let json: String = row.get("data");
                serde_json::from_str(&json).map_err(|e| AuthError::internal(e.to_string()))
            })
            .collect()
    }

    async fn count_active_sessions(&self) -> Result<u64> {
        let now = Utc::now().timestamp();
        let row = sqlx::query("SELECT COUNT(*) as cnt FROM sessions WHERE expires_at > ?")
            .bind(now)
            .fetch_one(&self.pool)
            .await
            .map_err(storage_err)?;
        let count: i64 = row.get("cnt");
        Ok(count as u64)
    }

    async fn store_kv(&self, key: &str, value: &[u8], ttl: Option<Duration>) -> Result<()> {
        let expires_at = ttl.map(expires_at_secs);

        sqlx::query(
            "INSERT INTO kv_store (key, value, expires_at)
             VALUES (?, ?, ?)
             ON CONFLICT(key) DO UPDATE SET
             value=excluded.value,
             expires_at=excluded.expires_at",
        )
        .bind(key)
        .bind(value)
        .bind(expires_at)
        .execute(&self.pool)
        .await
        .map_err(storage_err)?;

        Ok(())
    }

    async fn store_kv_if_absent(
        &self,
        key: &str,
        value: &[u8],
        ttl: Option<Duration>,
    ) -> Result<bool> {
        let now = Utc::now().timestamp();
        let expires_at = ttl.map(expires_at_secs);

        // One statement: insert, or take over an EXPIRED row; a live row is left alone.
        let result = sqlx::query(
            "INSERT INTO kv_store (key, value, expires_at)
             VALUES (?, ?, ?)
             ON CONFLICT(key) DO UPDATE SET
             value=excluded.value,
             expires_at=excluded.expires_at
             WHERE kv_store.expires_at IS NOT NULL AND kv_store.expires_at < ?",
        )
        .bind(key)
        .bind(value)
        .bind(expires_at)
        .bind(now)
        .execute(&self.pool)
        .await
        .map_err(storage_err)?;

        Ok(result.rows_affected() == 1)
    }

    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
        let now = Utc::now().timestamp();
        let row = sqlx::query("SELECT value, expires_at FROM kv_store WHERE key = ?")
            .bind(key)
            .fetch_optional(&self.pool)
            .await
            .map_err(storage_err)?;

        match row {
            Some(row) => {
                let expires_at: Option<i64> = row.get("expires_at");
                if expires_at.is_some_and(|expires_at| expires_at < now) {
                    return Ok(None);
                }

                let value: Vec<u8> = row.get("value");
                Ok(Some(value))
            }
            None => Ok(None),
        }
    }

    async fn get_kv_ttl(&self, key: &str) -> Result<Option<Duration>> {
        let now = Utc::now().timestamp();
        let row = sqlx::query("SELECT expires_at FROM kv_store WHERE key = ?")
            .bind(key)
            .fetch_optional(&self.pool)
            .await
            .map_err(storage_err)?;
        Ok(row
            .and_then(|row| row.get::<Option<i64>, _>("expires_at"))
            // `get_kv` treats `expires_at == now` as still alive, so report
            // it (as zero seconds left) rather than as "no expiry".
            .and_then(|expires_at| u64::try_from(expires_at - now).ok())
            .map(Duration::from_secs))
    }

    fn tracks_kv_ttl(&self) -> bool {
        true
    }

    async fn delete_kv(&self, key: &str) -> Result<()> {
        sqlx::query("DELETE FROM kv_store WHERE key = ?")
            .bind(key)
            .execute(&self.pool)
            .await
            .map_err(storage_err)?;
        Ok(())
    }

    async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> {
        let now = Utc::now().timestamp();
        let rows = sqlx::query(
            "SELECT key FROM kv_store WHERE key LIKE ? AND (expires_at IS NULL OR expires_at >= ?) ORDER BY key",
        )
        .bind(format!("{prefix}%"))
        .bind(now)
        .fetch_all(&self.pool)
        .await
        .map_err(storage_err)?;

        Ok(rows.into_iter().map(|row| row.get("key")).collect())
    }

    async fn cleanup_expired(&self) -> Result<()> {
        let now = Utc::now().timestamp();

        sqlx::query("DELETE FROM kv_store WHERE expires_at IS NOT NULL AND expires_at < ?")
            .bind(now)
            .execute(&self.pool)
            .await
            .map_err(storage_err)?;

        sqlx::query("DELETE FROM auth_tokens WHERE expires_at < ?")
            .bind(now)
            .execute(&self.pool)
            .await
            .map_err(storage_err)?;

        sqlx::query("DELETE FROM sessions WHERE expires_at < ?")
            .bind(now)
            .execute(&self.pool)
            .await
            .map_err(storage_err)?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tokens::TokenMetadata;
    use std::collections::HashMap;

    async fn create_test_storage() -> SqliteStorage {
        let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
        let storage = SqliteStorage::new(pool);
        storage.migrate().await.unwrap();
        storage
    }

    fn create_test_token(id: &str, user_id: &str) -> AuthToken {
        AuthToken {
            token_id: id.to_string(),
            user_id: user_id.to_string(),
            access_token: format!("access_{id}"),
            token_type: Some("bearer".to_string()),
            subject: Some(user_id.to_string()),
            issuer: Some("test".to_string()),
            refresh_token: Some(format!("refresh_{id}")),
            issued_at: Utc::now(),
            expires_at: Utc::now() + chrono::Duration::hours(1),
            scopes: vec!["read".to_string()].into(),
            auth_method: "password".to_string(),
            client_id: Some("test_client".to_string()),
            user_profile: None,
            permissions: vec![].into(),
            roles: vec![].into(),
            metadata: TokenMetadata {
                issued_ip: None,
                user_agent: None,
                device_id: None,
                session_id: None,
                revoked: false,
                revoked_at: None,
                revoked_reason: None,
                last_used: None,
                use_count: 0,
                custom: HashMap::new(),
            },
        }
    }

    #[tokio::test]
    async fn stores_and_fetches_tokens() {
        let storage = create_test_storage().await;
        let token = create_test_token("t1", "user1");

        storage.store_token(&token).await.unwrap();
        let loaded = storage.get_token("t1").await.unwrap().unwrap();

        assert_eq!(loaded.token_id, token.token_id);
        assert_eq!(loaded.user_id, token.user_id);
    }

    #[tokio::test]
    async fn stores_and_fetches_kv_entries() {
        let storage = create_test_storage().await;

        storage.store_kv("key", b"value", None).await.unwrap();
        let loaded = storage.get_kv("key").await.unwrap().unwrap();

        assert_eq!(loaded, b"value");
    }

    #[tokio::test]
    async fn get_kv_ttl_reports_remaining_lifetime() {
        let storage = create_test_storage().await;
        assert!(storage.tracks_kv_ttl());
        storage
            .store_kv("k:ttl", b"v", Some(Duration::from_secs(600)))
            .await
            .unwrap();
        storage.store_kv("k:forever", b"v", None).await.unwrap();
        let ttl = storage.get_kv_ttl("k:ttl").await.unwrap().unwrap();
        assert!(ttl > Duration::from_secs(590) && ttl <= Duration::from_secs(600));
        assert_eq!(storage.get_kv_ttl("k:forever").await.unwrap(), None);
        assert_eq!(storage.get_kv_ttl("k:missing").await.unwrap(), None);
    }
}