torii-storage-postgres 0.5.2

Postgres storage backend for the torii authentication ecosystem
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
use async_trait::async_trait;
use chrono::Utc;
use sqlx::{Database, PgPool, Postgres};
use torii_migration::{Migration, MigrationError, MigrationManager, MigrationRecord};

pub struct PostgresMigrationManager {
    pool: PgPool,
}

impl PostgresMigrationManager {
    #[allow(dead_code)]
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }
}

#[async_trait]
impl MigrationManager<Postgres> for PostgresMigrationManager {
    async fn initialize(&self) -> Result<(), MigrationError> {
        sqlx::query(
            format!(
                r#"
            CREATE TABLE IF NOT EXISTS {} (
                version INTEGER PRIMARY KEY,
                name TEXT NOT NULL,
                applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
            );"#,
                self.get_migration_table_name()
            )
            .as_str(),
        )
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    async fn up(&self, migrations: &[Box<dyn Migration<Postgres>>]) -> Result<(), MigrationError> {
        for migration in migrations {
            if !self.is_applied(migration.version()).await? {
                let mut tx = self.pool.begin().await?;

                tracing::info!(
                    "Applying migration {} ({})",
                    migration.name(),
                    migration.version()
                );

                migration
                    .up(&mut *tx as &mut <Postgres as Database>::Connection)
                    .await?;

                sqlx::query(
                    format!(
                        "INSERT INTO {} (version, name, applied_at) VALUES ($1, $2, $3)",
                        self.get_migration_table_name()
                    )
                    .as_str(),
                )
                .bind(migration.version())
                .bind(migration.name())
                .bind(Utc::now())
                .execute(&mut *tx)
                .await?;

                tx.commit().await?;
            }
        }
        Ok(())
    }

    async fn down(
        &self,
        migrations: &[Box<dyn Migration<Postgres>>],
    ) -> Result<(), MigrationError> {
        for migration in migrations {
            if self.is_applied(migration.version()).await? {
                let mut tx = self.pool.begin().await?;

                tracing::info!(
                    "Rolling back migration {} ({})",
                    migration.name(),
                    migration.version()
                );

                migration
                    .down(&mut *tx as &mut <Postgres as Database>::Connection)
                    .await?;

                sqlx::query(
                    format!(
                        "DELETE FROM {} WHERE version = $1",
                        self.get_migration_table_name()
                    )
                    .as_str(),
                )
                .bind(migration.version())
                .execute(&mut *tx)
                .await?;

                tx.commit().await?;
            }
        }
        Ok(())
    }

    async fn get_applied_migrations(&self) -> Result<Vec<MigrationRecord>, MigrationError> {
        let records = sqlx::query_as::<_, MigrationRecord>(
            format!(
                "SELECT version, name, applied_at FROM {}",
                self.get_migration_table_name()
            )
            .as_str(),
        )
        .fetch_all(&self.pool)
        .await?;
        Ok(records)
    }

    async fn is_applied(&self, version: i64) -> Result<bool, MigrationError> {
        let result: bool = sqlx::query_scalar(
            format!(
                "SELECT EXISTS(SELECT 1 FROM {} WHERE version = $1)",
                self.get_migration_table_name()
            )
            .as_str(),
        )
        .bind(version)
        .fetch_one(&self.pool)
        .await?;
        Ok(result)
    }
}

pub struct CreateUsersTable;

#[async_trait]
impl Migration<Postgres> for CreateUsersTable {
    fn version(&self) -> i64 {
        1
    }

    fn name(&self) -> &str {
        "CreateUsersTable"
    }

    async fn up<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        sqlx::query(r#"CREATE EXTENSION IF NOT EXISTS "pgcrypto""#)
            .execute(&mut *conn)
            .await?;

        sqlx::query(
            r#"
            CREATE TABLE IF NOT EXISTS users (
                id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
                name TEXT,
                email TEXT NOT NULL,
                email_verified_at TIMESTAMPTZ,
                password_hash TEXT,
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                UNIQUE(email),
                UNIQUE(id)
            )"#,
        )
        .execute(&mut *conn)
        .await?;
        Ok(())
    }

    async fn down<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        sqlx::query("DROP TABLE IF EXISTS users CASCADE")
            .execute(conn)
            .await?;
        Ok(())
    }
}

pub struct CreateSessionsTable;

#[async_trait]
impl Migration<Postgres> for CreateSessionsTable {
    fn version(&self) -> i64 {
        2
    }

    fn name(&self) -> &str {
        "CreateSessionsTable"
    }

    async fn up<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        sqlx::query(
            r#"
            CREATE TABLE IF NOT EXISTS sessions (
                id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
                user_id TEXT NOT NULL,
                user_agent TEXT,
                ip_address TEXT,
                token TEXT NOT NULL,
                expires_at TIMESTAMPTZ NOT NULL,
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
            );"#,
        )
        .execute(&mut *conn)
        .await?;
        Ok(())
    }

    async fn down<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        sqlx::query("DROP TABLE IF EXISTS sessions CASCADE")
            .execute(&mut *conn)
            .await?;
        Ok(())
    }
}

pub struct CreateOAuthAccountsTable;

#[async_trait]
impl Migration<Postgres> for CreateOAuthAccountsTable {
    fn version(&self) -> i64 {
        3
    }

    fn name(&self) -> &str {
        "CreateOAuthAccountsTable"
    }

    async fn up<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        sqlx::query(
            r#"
            CREATE TABLE IF NOT EXISTS oauth_accounts (
                id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
                user_id TEXT NOT NULL,
                provider TEXT NOT NULL,
                subject TEXT NOT NULL,
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
                UNIQUE(user_id, provider, subject)
            );"#,
        )
        .execute(&mut *conn)
        .await?;
        Ok(())
    }

    async fn down<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        sqlx::query("DROP TABLE IF EXISTS oauth_accounts CASCADE")
            .execute(&mut *conn)
            .await?;
        Ok(())
    }
}

pub struct CreatePasskeysTable;

#[async_trait]
impl Migration<Postgres> for CreatePasskeysTable {
    fn version(&self) -> i64 {
        4
    }

    fn name(&self) -> &str {
        "CreatePasskeysTable"
    }

    async fn up<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        sqlx::query(
            r#"
            CREATE TABLE IF NOT EXISTS passkeys (
                id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
                credential_id TEXT NOT NULL,
                user_id TEXT NOT NULL,
                public_key TEXT NOT NULL,
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
            );"#,
        )
        .execute(conn)
        .await?;
        Ok(())
    }

    async fn down<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        sqlx::query("DROP TABLE IF EXISTS passkeys")
            .execute(conn)
            .await?;
        Ok(())
    }
}

pub struct CreatePasskeyChallengesTable;

#[async_trait]
impl Migration<Postgres> for CreatePasskeyChallengesTable {
    fn version(&self) -> i64 {
        5
    }

    fn name(&self) -> &str {
        "CreatePasskeyChallengesTable"
    }

    async fn up<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        sqlx::query(
            r#"
            CREATE TABLE IF NOT EXISTS passkey_challenges (
                id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
                challenge_id TEXT NOT NULL,
                challenge TEXT NOT NULL,
                expires_at TIMESTAMPTZ NOT NULL,
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                UNIQUE(challenge_id)
            );"#,
        )
        .execute(conn)
        .await?;
        Ok(())
    }

    async fn down<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        sqlx::query("DROP TABLE IF EXISTS passkey_challenges")
            .execute(conn)
            .await?;
        Ok(())
    }
}

pub struct CreateIndexes;

#[async_trait]
impl Migration<Postgres> for CreateIndexes {
    fn version(&self) -> i64 {
        6
    }

    fn name(&self) -> &str {
        "CreateIndexes"
    }

    async fn up<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        // Index for email searches
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)")
            .execute(&mut *conn)
            .await?;

        // Index for sessions user_id foreign key
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id)")
            .execute(&mut *conn)
            .await?;

        // Index for sessions expiration
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at)")
            .execute(&mut *conn)
            .await?;

        // Indexes for oauth_accounts lookups
        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_oauth_accounts_user_id ON oauth_accounts(user_id)",
        )
        .execute(&mut *conn)
        .await?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_oauth_accounts_provider_subject ON oauth_accounts(provider, subject)",
        )
        .execute(&mut *conn)
        .await?;

        // Index for passkeys user_id
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_passkeys_user_id ON passkeys(user_id)")
            .execute(&mut *conn)
            .await?;

        // Index for passkey credential lookup
        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_passkeys_credential_id ON passkeys(credential_id)",
        )
        .execute(&mut *conn)
        .await?;

        // Index for passkey challenges expiration
        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_passkey_challenges_expires_at ON passkey_challenges(expires_at)",
        )
        .execute(&mut *conn)
        .await?;

        Ok(())
    }

    async fn down<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        sqlx::query("DROP INDEX IF EXISTS idx_users_email")
            .execute(&mut *conn)
            .await?;
        sqlx::query("DROP INDEX IF EXISTS idx_sessions_user_id")
            .execute(&mut *conn)
            .await?;
        sqlx::query("DROP INDEX IF EXISTS idx_sessions_expires_at")
            .execute(&mut *conn)
            .await?;
        sqlx::query("DROP INDEX IF EXISTS idx_oauth_accounts_user_id")
            .execute(&mut *conn)
            .await?;
        sqlx::query("DROP INDEX IF EXISTS idx_oauth_accounts_provider_subject")
            .execute(&mut *conn)
            .await?;
        sqlx::query("DROP INDEX IF EXISTS idx_passkeys_user_id")
            .execute(&mut *conn)
            .await?;
        sqlx::query("DROP INDEX IF EXISTS idx_passkeys_credential_id")
            .execute(&mut *conn)
            .await?;
        sqlx::query("DROP INDEX IF EXISTS idx_passkey_challenges_expires_at")
            .execute(&mut *conn)
            .await?;
        Ok(())
    }
}

pub struct CreateMagicLinksTable;

#[async_trait::async_trait]
impl Migration<Postgres> for CreateMagicLinksTable {
    fn version(&self) -> i64 {
        7
    }

    fn name(&self) -> &str {
        "CreateMagicLinksTable"
    }

    async fn up<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        sqlx::query(
            r#"
            CREATE TABLE IF NOT EXISTS magic_links (
                id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
                user_id TEXT NOT NULL,
                token TEXT NOT NULL,
                used_at TIMESTAMPTZ,
                expires_at TIMESTAMPTZ NOT NULL,
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
                UNIQUE(token)
            )"#,
        )
        .execute(&mut *conn)
        .await?;

        sqlx::query("CREATE INDEX IF NOT EXISTS idx_magic_links_used_at ON magic_links(used_at)")
            .execute(&mut *conn)
            .await?;

        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_magic_links_expires_at ON magic_links(expires_at)",
        )
        .execute(&mut *conn)
        .await?;

        sqlx::query("CREATE INDEX IF NOT EXISTS idx_magic_links_user_id ON magic_links(user_id)")
            .execute(&mut *conn)
            .await?;

        sqlx::query("CREATE INDEX IF NOT EXISTS idx_magic_links_token ON magic_links(token)")
            .execute(&mut *conn)
            .await?;

        Ok(())
    }

    async fn down<'a>(
        &'a self,
        conn: &'a mut <Postgres as Database>::Connection,
    ) -> Result<(), MigrationError> {
        sqlx::query("DROP INDEX IF EXISTS idx_magic_links_expires_at")
            .execute(&mut *conn)
            .await?;

        sqlx::query("DROP INDEX IF EXISTS idx_magic_links_user_id")
            .execute(&mut *conn)
            .await?;

        sqlx::query("DROP INDEX IF EXISTS idx_magic_links_token")
            .execute(&mut *conn)
            .await?;

        sqlx::query("DROP TABLE IF EXISTS magic_links")
            .execute(&mut *conn)
            .await?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::Rng;
    use sqlx::PgPool;

    pub(crate) async fn setup_test() -> Result<PostgresMigrationManager, sqlx::Error> {
        // TODO: this function is leaking postgres databases after the test is done.
        // We should find a way to clean up the database after the test is done.

        let _ = tracing_subscriber::fmt().try_init();

        let pool = PgPool::connect("postgres://postgres:postgres@localhost:5432/postgres")
            .await
            .expect("Failed to create pool");

        let db_name = format!("torii_test_{}", rand::rng().random_range(1..i64::MAX));

        // Drop the database if it exists
        sqlx::query(format!("DROP DATABASE IF EXISTS {db_name}").as_str())
            .execute(&pool)
            .await
            .expect("Failed to drop database");

        // Create a new database for the test
        sqlx::query(format!("CREATE DATABASE {db_name}").as_str())
            .execute(&pool)
            .await
            .expect("Failed to create database");

        let pool = PgPool::connect(
            format!("postgres://postgres:postgres@localhost:5432/{db_name}").as_str(),
        )
        .await
        .expect("Failed to create pool");

        // Initialize migrations table
        let manager = PostgresMigrationManager::new(pool);
        manager
            .initialize()
            .await
            .expect("Failed to initialize migrations");

        Ok(manager)
    }

    #[tokio::test]
    async fn test_migrations() -> Result<(), MigrationError> {
        let manager = setup_test().await.map_err(MigrationError::Sqlx)?;

        // Test up migrations
        let migrations: Vec<Box<dyn Migration<Postgres>>> = vec![
            Box::new(CreateUsersTable),
            Box::new(CreateSessionsTable),
            Box::new(CreateOAuthAccountsTable),
            Box::new(CreatePasskeysTable),
            Box::new(CreatePasskeyChallengesTable),
            Box::new(CreateIndexes),
            Box::new(CreateMagicLinksTable),
        ];
        manager.up(&migrations).await?;

        // Verify migration was applied
        let applied = manager.is_applied(7).await?;
        assert!(applied, "Migration should be applied");

        // Test down migrations
        manager.down(&migrations).await?;

        // Verify migration was rolled back
        let applied = manager.is_applied(7).await?;
        assert!(!applied, "Migration should be rolled back");

        Ok(())
    }

    #[tokio::test]
    async fn test_up_down_up() -> Result<(), MigrationError> {
        let manager = setup_test().await.map_err(MigrationError::Sqlx)?;

        // Test up migrations
        let migrations: Vec<Box<dyn Migration<Postgres>>> = vec![
            Box::new(CreateUsersTable),
            Box::new(CreateSessionsTable),
            Box::new(CreateOAuthAccountsTable),
            Box::new(CreatePasskeysTable),
            Box::new(CreatePasskeyChallengesTable),
            Box::new(CreateIndexes),
            Box::new(CreateMagicLinksTable),
        ];
        manager.up(&migrations).await?;

        Ok(())
    }
}