axum-gate 1.1.0

Flexible authentication and authorization for Axum with JWT cookies or bearer tokens, optional OAuth2, and role/group/permission RBAC. Suitable for single-node and distributed systems.
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! SurrealDB-backed repositories for accounts and secrets with constant-time credential verification.

use super::TableName;
use crate::accounts::Account;
use crate::accounts::AccountRepository;
use crate::authz::AccessHierarchy;
use crate::credentials::Credentials;
use crate::credentials::CredentialsVerifier;
use crate::errors::{Error, Result};
use crate::hashing::HashingService;
use crate::hashing::argon2::Argon2Hasher;
use crate::permissions::PermissionId;
use crate::permissions::mapping::PermissionMapping;
use crate::permissions::mapping::PermissionMappingRepository;
use crate::repositories::{DatabaseError, DatabaseOperation};
use crate::secrets::{Secret, SecretRepository};
use crate::verification_result::VerificationResult;

use std::default::Default;

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use surrealdb::{Connection, RecordId, RecordIdKey, Surreal};
use uuid::Uuid;

/// Scope configuration (namespace, database, table names) used by `SurrealDbRepository`.
///
/// Most users can rely on `DatabaseScope::default()`. Override fields only if you
/// need custom namespace / database names or different table naming.
#[derive(Clone, Debug)]
pub struct DatabaseScope {
    /// Accounts table (stores user id, groups, roles).
    pub accounts: String,
    /// Credentials table (stores hashed secrets).
    pub credentials: String,
    /// Permission mappings table (stores normalized string <-> id mapping).
    pub permission_mappings: String,
    /// Namespace where data is stored.
    pub namespace: String,
    /// Database name where data is stored.
    pub database: String,
}

impl Default for DatabaseScope {
    fn default() -> Self {
        Self {
            accounts: TableName::AxumGateAccounts.to_string(),
            credentials: TableName::AxumGateCredentials.to_string(),
            permission_mappings: TableName::AxumGatePermissionMappings.to_string(),
            namespace: "axumGate".to_string(),
            database: "axumGate".to_string(),
        }
    }
}

/// SurrealDB-backed repository offering CRUD for accounts & secrets plus constant-time
/// credential verification (uses a precomputed dummy Argon2 hash when a secret is absent).
///
/// Use `SurrealDbRepository::new(db, DatabaseScope::default())` for standard setups.
#[derive(Clone)]
pub struct SurrealDbRepository<S>
where
    S: Connection,
{
    db: Surreal<S>,
    scope_settings: DatabaseScope,
    /// Precomputed dummy Argon2 hash used when a user's secret does not exist.
    /// Ensures the Argon2 verification path is always exercised.
    dummy_hash: String,
}

impl<S> SurrealDbRepository<S>
where
    S: Connection,
{
    /// Creates a new repository that uses the given database connection limited by the given scope.
    pub fn new(db: Surreal<S>, scope_settings: DatabaseScope) -> Result<Self> {
        let hasher = Argon2Hasher::new_recommended()?;
        // Panic on failure here is acceptable: construction failure indicates a
        // fundamental issue (e.g. RNG) and mirrors the in‑memory repo strategy.
        let dummy_hash = hasher.hash_value("dummy_password")?;
        Ok(Self {
            db,
            scope_settings,
            dummy_hash,
        })
    }

    /// Sets the correct namespace and database to use.
    async fn use_ns_db(&self) -> Result<()> {
        self.db
            .use_ns(&self.scope_settings.namespace)
            .use_db(&self.scope_settings.database)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Connect,
                    format!("Failed to set namespace/database: {}", e),
                    None,
                    None,
                ))
            })
    }
}

impl<R, G, S> AccountRepository<R, G> for SurrealDbRepository<S>
where
    R: AccessHierarchy + Eq + DeserializeOwned + Serialize + Send + Sync + 'static,
    G: Serialize + DeserializeOwned + Eq + Clone + Send + Sync + 'static,
    S: Connection,
{
    async fn query_account_by_user_id(&self, user_id: &str) -> Result<Option<Account<R, G>>> {
        self.use_ns_db().await?;
        let db_account: Option<Account<R, G>> = self
            .db
            .select(RecordId::from_table_key(
                &self.scope_settings.accounts,
                user_id,
            ))
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Query,
                    format!("Failed to query account by user_id: {}", e),
                    Some(self.scope_settings.accounts.clone()),
                    Some(user_id.to_string()),
                ))
            })?;
        Ok(db_account)
    }

    async fn store_account(&self, account: Account<R, G>) -> Result<Option<Account<R, G>>> {
        self.use_ns_db().await?;
        let record_id =
            RecordId::from_table_key(self.scope_settings.accounts.clone(), &account.user_id);
        let user_id = account.user_id.clone();
        let db_account: Option<Account<R, G>> = self
            .db
            .insert(record_id)
            .content(account)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Insert,
                    format!("Could not insert account: {}", e),
                    Some(self.scope_settings.accounts.clone()),
                    Some(user_id),
                ))
            })?;
        Ok(db_account)
    }

    async fn delete_account(&self, user_id: &str) -> Result<Option<Account<R, G>>> {
        self.use_ns_db().await?;
        let db_account: Option<Account<R, G>> = self
            .db
            .delete(RecordId::from_table_key(
                self.scope_settings.accounts.clone(),
                user_id,
            ))
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Delete,
                    format!("Failed to delete account: {}", e),
                    Some(self.scope_settings.accounts.clone()),
                    Some(user_id.to_string()),
                ))
            })?;
        Ok(db_account)
    }

    async fn update_account(&self, account: Account<R, G>) -> Result<Option<Account<R, G>>> {
        self.use_ns_db().await?;
        let record_id =
            RecordId::from_table_key(self.scope_settings.accounts.clone(), &account.user_id);
        let db_account: Option<Account<R, G>> = self.db.update(&record_id).content(account).await?;
        Ok(db_account)
    }
}

impl<S> SecretRepository for SurrealDbRepository<S>
where
    S: Connection,
{
    async fn store_secret(&self, secret: Secret) -> Result<bool> {
        self.use_ns_db().await?;

        let record_id =
            RecordId::from_table_key(self.scope_settings.credentials.clone(), secret.account_id);

        let account_id = secret.account_id;
        let db_credentials: Option<Secret> = self
            .db
            .insert(&record_id)
            .content(secret)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Insert,
                    format!("Failed to store secret: {}", e),
                    Some(self.scope_settings.credentials.clone()),
                    Some(account_id.to_string()),
                ))
            })?;
        Ok(db_credentials.is_some())
    }

    async fn delete_secret(&self, id: &Uuid) -> Result<Option<Secret>> {
        self.use_ns_db().await?;
        let record_id = RecordId::from_table_key(self.scope_settings.credentials.clone(), *id);
        let result: Option<Secret> = self.db.delete(record_id).await.map_err(|e| {
            Error::Database(DatabaseError::with_context(
                DatabaseOperation::Delete,
                format!("Failed to delete and return secret: {}", e),
                Some(self.scope_settings.credentials.clone()),
                Some(id.to_string()),
            ))
        })?;
        Ok(result)
    }

    async fn update_secret(&self, secret: Secret) -> Result<()> {
        self.use_ns_db().await?;

        let record_id =
            RecordId::from_table_key(self.scope_settings.credentials.clone(), secret.account_id);
        let account_id = secret.account_id;
        let _: Option<Secret> = self
            .db
            .update(record_id)
            .content(secret)
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Update,
                    format!("Failed to update secret: {}", e),
                    Some(self.scope_settings.credentials.clone()),
                    Some(account_id.to_string()),
                ))
            })?;
        Ok(())
    }
}

impl<S, Id> CredentialsVerifier<Id> for SurrealDbRepository<S>
where
    S: Connection,
    Id: Into<RecordIdKey>,
{
    async fn verify_credentials(&self, credentials: Credentials<Id>) -> Result<VerificationResult> {
        use subtle::Choice;

        self.use_ns_db().await?;
        let record_id =
            RecordId::from_table_key(self.scope_settings.credentials.clone(), credentials.id);

        // Step 1: Query stored secret (if any)
        let exists_query = "SELECT VALUE secret FROM only $record_id".to_string();
        let mut exists_response = self
            .db
            .query(exists_query)
            .bind(("record_id", record_id))
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Query,
                    format!("Failed to check user existence: {}", e),
                    Some(self.scope_settings.credentials.clone()),
                    None,
                ))
            })?;

        let stored_secret: Option<String> = exists_response.take(0).map_err(|e| {
            Error::Database(DatabaseError::with_context(
                DatabaseOperation::Query,
                format!("Failed to extract secret: {}", e),
                Some(self.scope_settings.credentials.clone()),
                None,
            ))
        })?;

        // Step 2: Select hash to verify against (always perform verification)
        let (hash_for_verification, user_exists_choice) = match stored_secret {
            Some(secret) => (secret, Choice::from(1u8)),
            None => (self.dummy_hash.clone(), Choice::from(0u8)),
        };

        // Step 3: Perform Argon2 verification inside the database engine (SurrealDB function)
        let verify_query =
            "crypto::argon2::compare(type::string($stored_hash), type::string($request_secret))"
                .to_string();
        let mut verify_response = self
            .db
            .query(verify_query)
            .bind(("stored_hash", hash_for_verification))
            .bind(("request_secret", credentials.secret))
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Query,
                    format!("Failed to verify credentials: {}", e),
                    Some(self.scope_settings.credentials.clone()),
                    None,
                ))
            })?;

        let hash_matches: Option<bool> = verify_response.take(0).map_err(|e| {
            Error::Database(DatabaseError::with_context(
                DatabaseOperation::Query,
                format!("Failed to extract verification result: {}", e),
                Some(self.scope_settings.credentials.clone()),
                None,
            ))
        })?;

        // Step 4: Constant-time combination: success only if user exists AND hash matches
        let hash_matches_choice = Choice::from(if hash_matches.unwrap_or(false) {
            1u8
        } else {
            0u8
        });
        let final_success_choice = user_exists_choice & hash_matches_choice;

        // Step 5: Convert to domain result
        let final_result = if bool::from(final_success_choice) {
            VerificationResult::Ok
        } else {
            VerificationResult::Unauthorized
        };

        Ok(final_result)
    }
}

/// Adapter for persisting `PermissionMapping` in SurrealDB.
///
/// SurrealDB can deserialize numeric fields as signed 64-bit integers (i64),
/// while our permission IDs are computed 64-bit values that may exceed the
/// positive i63 range. Persisting `permission_id` as a `String` avoids
/// signedness/width pitfalls across different SurrealDB backends and ensures
/// stable round‑trips regardless of how numbers are represented internally.
#[derive(Clone, Debug, Serialize, Deserialize)]
struct SurrealPermissionMapping {
    normalized_string: String,
    permission_id: String,
}

impl From<PermissionMapping> for SurrealPermissionMapping {
    fn from(m: PermissionMapping) -> Self {
        Self {
            normalized_string: m.normalized_string().to_string(),
            permission_id: m.permission_id().as_u64().to_string(),
        }
    }
}

impl std::convert::TryFrom<SurrealPermissionMapping> for PermissionMapping {
    type Error = String;

    fn try_from(value: SurrealPermissionMapping) -> std::result::Result<Self, Self::Error> {
        let id_u64 = value.permission_id.parse::<u64>().map_err(|e| {
            format!(
                "invalid permission_id string '{}': {}",
                value.permission_id, e
            )
        })?;
        let id = PermissionId::from_u64(id_u64);
        PermissionMapping::new(value.normalized_string.clone(), id)
            .map_err(|e| format!("failed to construct PermissionMapping: {}", e))
    }
}

impl<S> PermissionMappingRepository for SurrealDbRepository<S>
where
    S: Connection,
{
    async fn store_mapping(&self, mapping: PermissionMapping) -> Result<Option<PermissionMapping>> {
        // Validate the mapping first
        if let Err(e) = mapping.validate() {
            // Treat validation failures as infrastructure-safe errors for this backend
            return Err(Error::Database(DatabaseError::with_context(
                DatabaseOperation::Insert,
                format!("Invalid permission mapping: {}", e),
                Some(self.scope_settings.permission_mappings.clone()),
                None,
            )));
        }

        self.use_ns_db().await?;

        // Enforce uniqueness by permission ID (direct WHERE query)
        let query_id = "SELECT * FROM type::table($table) WHERE permission_id = $pid LIMIT 1";
        let mut res_id = self
            .db
            .query(query_id)
            .bind(("table", self.scope_settings.permission_mappings.clone()))
            .bind(("pid", mapping.permission_id().as_u64().to_string()))
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Query,
                    format!("Failed to check existing mapping by id: {}", e),
                    Some(self.scope_settings.permission_mappings.clone()),
                    Some(mapping.permission_id().as_u64().to_string()),
                ))
            })?;
        let exists_by_id: Vec<SurrealPermissionMapping> = res_id.take(0).map_err(|e| {
            Error::Database(DatabaseError::with_context(
                DatabaseOperation::Query,
                format!("Failed to extract existing mapping by id: {}", e),
                Some(self.scope_settings.permission_mappings.clone()),
                Some(mapping.permission_id().as_u64().to_string()),
            ))
        })?;
        if !exists_by_id.is_empty() {
            return Ok(None);
        }

        // Enforce uniqueness by normalized string (record key)
        let record_id = RecordId::from_table_key(
            self.scope_settings.permission_mappings.clone(),
            mapping.normalized_string(),
        );
        let exists_by_string: Option<SurrealPermissionMapping> =
            self.db.select(&record_id).await.map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Query,
                    format!("Failed to check existing mapping by string: {}", e),
                    Some(self.scope_settings.permission_mappings.clone()),
                    None,
                ))
            })?;
        if exists_by_string.is_some() {
            return Ok(None);
        }

        // Insert mapping using normalized string as the record key
        let stored_spm: Option<SurrealPermissionMapping> = self
            .db
            .insert(&record_id)
            .content(SurrealPermissionMapping::from(mapping))
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Insert,
                    format!("Failed to store permission mapping: {}", e),
                    Some(self.scope_settings.permission_mappings.clone()),
                    None,
                ))
            })?;

        let stored = match stored_spm {
            Some(spm) => {
                let dom = PermissionMapping::try_from(spm).map_err(|e| {
                    Error::Database(DatabaseError::with_context(
                        DatabaseOperation::Insert,
                        format!("Failed to convert stored permission mapping: {}", e),
                        Some(self.scope_settings.permission_mappings.clone()),
                        None,
                    ))
                })?;
                Some(dom)
            }
            None => None,
        };

        Ok(stored)
    }

    async fn remove_mapping_by_id(&self, id: PermissionId) -> Result<Option<PermissionMapping>> {
        self.use_ns_db().await?;

        // Delete directly by permission_id and return the removed record (if any)
        let query = "DELETE type::table($table) WHERE permission_id = $pid RETURN BEFORE";
        let mut res = self
            .db
            .query(query)
            .bind(("table", self.scope_settings.permission_mappings.clone()))
            .bind(("pid", id.as_u64().to_string()))
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Delete,
                    format!("Failed to delete permission mapping by id: {}", e),
                    Some(self.scope_settings.permission_mappings.clone()),
                    Some(id.as_u64().to_string()),
                ))
            })?;

        let removed: Vec<SurrealPermissionMapping> = res.take(0).map_err(|e| {
            Error::Database(DatabaseError::with_context(
                DatabaseOperation::Delete,
                format!("Failed to extract deleted permission mapping: {}", e),
                Some(self.scope_settings.permission_mappings.clone()),
                Some(id.as_u64().to_string()),
            ))
        })?;

        removed
            .into_iter()
            .next()
            .map(|spm| {
                PermissionMapping::try_from(spm).map_err(|e| {
                    Error::Database(DatabaseError::with_context(
                        DatabaseOperation::Delete,
                        format!("Failed to convert deleted permission mapping: {}", e),
                        Some(self.scope_settings.permission_mappings.clone()),
                        Some(id.as_u64().to_string()),
                    ))
                })
            })
            .transpose()
    }

    async fn remove_mapping_by_string(
        &self,
        permission: &str,
    ) -> Result<Option<PermissionMapping>> {
        self.use_ns_db().await?;

        // Normalize via domain logic
        let normalized = PermissionMapping::from(permission)
            .normalized_string()
            .to_string();

        // Delete directly by normalized string and return the removed record (if any)
        let query = "DELETE type::table($table) WHERE normalized_string = $ns RETURN BEFORE";
        let mut res = self
            .db
            .query(query)
            .bind(("table", self.scope_settings.permission_mappings.clone()))
            .bind(("ns", normalized))
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Delete,
                    format!("Failed to delete permission mapping by string: {}", e),
                    Some(self.scope_settings.permission_mappings.clone()),
                    None,
                ))
            })?;

        let removed: Vec<SurrealPermissionMapping> = res.take(0).map_err(|e| {
            Error::Database(DatabaseError::with_context(
                DatabaseOperation::Delete,
                format!("Failed to extract deleted permission mapping: {}", e),
                Some(self.scope_settings.permission_mappings.clone()),
                None,
            ))
        })?;

        removed
            .into_iter()
            .next()
            .map(|spm| {
                PermissionMapping::try_from(spm).map_err(|e| {
                    Error::Database(DatabaseError::with_context(
                        DatabaseOperation::Delete,
                        format!("Failed to convert deleted permission mapping: {}", e),
                        Some(self.scope_settings.permission_mappings.clone()),
                        None,
                    ))
                })
            })
            .transpose()
    }

    async fn query_mapping_by_id(&self, id: PermissionId) -> Result<Option<PermissionMapping>> {
        self.use_ns_db().await?;

        // Direct WHERE query by permission_id
        let query = "SELECT * FROM type::table($table) WHERE permission_id = $pid LIMIT 1";
        let mut res = self
            .db
            .query(query)
            .bind(("table", self.scope_settings.permission_mappings.clone()))
            .bind(("pid", id.as_u64().to_string()))
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Query,
                    format!("Failed to query permission mapping by id: {}", e),
                    Some(self.scope_settings.permission_mappings.clone()),
                    None,
                ))
            })?;

        let found: Vec<SurrealPermissionMapping> = res.take(0).map_err(|e| {
            Error::Database(DatabaseError::with_context(
                DatabaseOperation::Query,
                format!("Failed to extract permission mapping by id: {}", e),
                Some(self.scope_settings.permission_mappings.clone()),
                Some(id.as_u64().to_string()),
            ))
        })?;

        found
            .into_iter()
            .next()
            .map(|spm| {
                PermissionMapping::try_from(spm).map_err(|e| {
                    Error::Database(DatabaseError::with_context(
                        DatabaseOperation::Query,
                        format!("Failed to convert permission mapping: {}", e),
                        Some(self.scope_settings.permission_mappings.clone()),
                        Some(id.as_u64().to_string()),
                    ))
                })
            })
            .transpose()
    }

    async fn query_mapping_by_string(&self, permission: &str) -> Result<Option<PermissionMapping>> {
        self.use_ns_db().await?;

        let normalized = PermissionMapping::from(permission)
            .normalized_string()
            .to_string();

        // Direct select by record key (normalized string)
        let record_id = RecordId::from_table_key(
            self.scope_settings.permission_mappings.clone(),
            normalized.clone(),
        );

        let mapping_spm: Option<SurrealPermissionMapping> =
            self.db.select(record_id).await.map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Query,
                    format!("Failed to query permission mapping by string: {}", e),
                    Some(self.scope_settings.permission_mappings.clone()),
                    None,
                ))
            })?;

        mapping_spm
            .map(|spm| {
                PermissionMapping::try_from(spm).map_err(|e| {
                    Error::Database(DatabaseError::with_context(
                        DatabaseOperation::Query,
                        format!("Failed to convert permission mapping: {}", e),
                        Some(self.scope_settings.permission_mappings.clone()),
                        None,
                    ))
                })
            })
            .transpose()
    }

    async fn list_all_mappings(&self) -> Result<Vec<PermissionMapping>> {
        self.use_ns_db().await?;

        let all_spm: Vec<SurrealPermissionMapping> = self
            .db
            .select(self.scope_settings.permission_mappings.clone())
            .await
            .map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Query,
                    format!("Failed to list permission mappings: {}", e),
                    Some(self.scope_settings.permission_mappings.clone()),
                    None,
                ))
            })?;

        let mut out = Vec::with_capacity(all_spm.len());
        for spm in all_spm {
            let dom = PermissionMapping::try_from(spm).map_err(|e| {
                Error::Database(DatabaseError::with_context(
                    DatabaseOperation::Query,
                    format!("Failed to convert permission mapping: {}", e),
                    Some(self.scope_settings.permission_mappings.clone()),
                    None,
                ))
            })?;
            out.push(dom);
        }
        Ok(out)
    }
}

#[test]
#[allow(clippy::unwrap_used)]
fn secret_repository() {
    tokio_test::block_on(async move {
        use crate::hashing::argon2::Argon2Hasher;
        use surrealdb::engine::local::Mem;

        // create a repository
        let db = Surreal::new::<Mem>(()).await.unwrap();
        let scope = DatabaseScope::default();
        let repo = SurrealDbRepository::new(db, scope).unwrap();

        repo.use_ns_db().await.unwrap();

        // create a secret
        let hasher = Argon2Hasher::new_recommended().unwrap();
        let secret = Secret::new(&Uuid::now_v7(), "my_secret", hasher).unwrap();

        // store it
        assert!(repo.store_secret(secret.clone()).await.unwrap());

        // update it
        let mut secret_new = secret.clone();
        secret_new.secret = secret.secret.clone();
        repo.update_secret(secret_new.clone()).await.unwrap();

        // verify it
        let credentials = Credentials::new(&secret.account_id, "my_secret");
        assert!(matches!(
            repo.verify_credentials(credentials).await,
            Ok(VerificationResult::Ok)
        ));
    });
}