cot 0.5.0

The Rust web framework for lazy developers.
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
//! Database-backed user authentication backend.
//!
//! This module provides a user type and an authentication backend that stores
//! the user data in a database using the Cot ORM.

use std::any::Any;
use std::borrow::Cow;
use std::fmt::{Display, Formatter};

use async_trait::async_trait;
// Importing `Auto` from `cot` instead of `crate` so that the migration generator
// can figure out it's an autogenerated field
use cot::db::Auto;
use cot_macros::AdminModel;
use hmac::{Hmac, Mac};
use sha2::Sha512;
use thiserror::Error;

use crate::App;
use crate::admin::{AdminModelManager, DefaultAdminModelManager};
use crate::auth::{
    AuthBackend, AuthError, PasswordHash, PasswordVerificationResult, Result, SessionAuthHash,
    User, UserId,
};
use crate::common_types::Password;
use crate::config::SecretKey;
use crate::db::migrations::SyncDynMigration;
use crate::db::{Database, DatabaseBackend, LimitedString, Model, model, query};
use crate::form::Form;

pub mod migrations;

pub(crate) const MAX_USERNAME_LENGTH: u32 = 255;

/// A user stored in the database.
#[derive(Debug, Clone, Form, AdminModel)]
#[model]
pub struct DatabaseUser {
    #[model(primary_key)]
    id: Auto<i64>,
    #[model(unique)]
    username: LimitedString<MAX_USERNAME_LENGTH>,
    password: PasswordHash,
}

/// An error that occurs when creating a user.
#[derive(Debug, Clone, Error)]
#[non_exhaustive]
pub enum CreateUserError {
    /// The username is too long.
    #[error("username is too long (max {MAX_USERNAME_LENGTH} characters, got {0})")]
    UsernameTooLong(usize),
}

impl DatabaseUser {
    #[must_use]
    fn new(
        id: Auto<i64>,
        username: LimitedString<MAX_USERNAME_LENGTH>,
        password: &Password,
    ) -> Self {
        Self {
            id,
            username,
            password: PasswordHash::from_password(password),
        }
    }

    /// Create a new user and save it to the database.
    ///
    /// # Errors
    ///
    /// Returns an error if the user could not be saved to the database.
    ///
    /// # Example
    ///
    /// ```
    /// use cot::auth::db::DatabaseUser;
    /// use cot::common_types::Password;
    /// use cot::db::Database;
    /// use cot::html::Html;
    ///
    /// async fn view(db: Database) -> cot::Result<Html> {
    ///     let user =
    ///         DatabaseUser::create_user(&db, "testuser".to_string(), &Password::new("password123"))
    ///             .await?;
    ///
    ///     Ok(Html::new("User created!"))
    /// }
    ///
    /// # #[tokio::main]
    /// # async fn main() -> cot::Result<()> {
    /// #     use cot::test::{TestDatabase, TestRequestBuilder};
    /// #     let mut test_database = TestDatabase::new_sqlite().await?;
    /// #     test_database.with_auth().run_migrations().await;
    /// #     view(test_database.database()).await?;
    /// #     test_database.cleanup().await?;
    /// #     Ok(())
    /// # }
    /// ```
    pub async fn create_user<DB: DatabaseBackend, T: Into<String>, U: Into<Password>>(
        db: &DB,
        username: T,
        password: U,
    ) -> Result<Self> {
        let username = username.into();
        let username_length = username.len();
        let username = LimitedString::<MAX_USERNAME_LENGTH>::new(username).map_err(|_| {
            AuthError::backend_error(CreateUserError::UsernameTooLong(username_length))
        })?;

        let mut user = Self::new(Auto::auto(), username, &password.into());
        user.insert(db).await.map_err(AuthError::backend_error)?;

        Ok(user)
    }

    /// Get a user by their integer ID. Returns [`None`] if the user does not
    /// exist.
    ///
    /// # Errors
    ///
    /// Returns an error if there was an error querying the database.
    ///
    /// # Panics
    ///
    /// Panics if the user ID provided is not an integer.
    ///
    /// # Example
    ///
    /// ```
    /// use cot::auth::UserId;
    /// use cot::auth::db::DatabaseUser;
    /// use cot::common_types::Password;
    /// use cot::db::Database;
    /// use cot::html::Html;
    ///
    /// async fn view(db: Database) -> cot::Result<Html> {
    ///     let user =
    ///         DatabaseUser::create_user(&db, "testuser".to_string(), &Password::new("password123"))
    ///             .await?;
    ///
    ///     let user_from_db = DatabaseUser::get_by_id(&db, user.id()).await?;
    ///
    ///     Ok(Html::new("User created!"))
    /// }
    ///
    /// # #[tokio::main]
    /// # async fn main() -> cot::Result<()> {
    /// #     use cot::test::{TestDatabase, TestRequestBuilder};
    /// #     let mut test_database = TestDatabase::new_sqlite().await?;
    /// #     test_database.with_auth().run_migrations().await;
    /// #     view(test_database.database()).await?;
    /// #     test_database.cleanup().await?;
    /// #     Ok(())
    /// # }
    /// ```
    pub async fn get_by_id<DB: DatabaseBackend>(db: &DB, id: i64) -> Result<Option<Self>> {
        let db_user = query!(DatabaseUser, $id == id)
            .get(db)
            .await
            .map_err(AuthError::backend_error)?;

        Ok(db_user)
    }

    /// Get a user by their username. Returns [`None`] if the user does not
    /// exist.
    ///
    /// # Errors
    ///
    /// Returns an error if there was an error querying the database.
    ///
    /// # Example
    ///
    /// ```
    /// use cot::auth::UserId;
    /// use cot::auth::db::DatabaseUser;
    /// use cot::common_types::Password;
    /// use cot::db::Database;
    /// use cot::html::Html;
    ///
    /// async fn view(db: Database) -> cot::Result<Html> {
    ///     let user =
    ///         DatabaseUser::create_user(&db, "testuser".to_string(), &Password::new("password123"))
    ///             .await?;
    ///
    ///     let user_from_db = DatabaseUser::get_by_username(&db, "testuser").await?;
    ///
    ///     Ok(Html::new("User created!"))
    /// }
    ///
    /// # #[tokio::main]
    /// # async fn main() -> cot::Result<()> {
    /// #     use cot::test::{TestDatabase, TestRequestBuilder};
    /// #     let mut test_database = TestDatabase::new_sqlite().await?;
    /// #     test_database.with_auth().run_migrations().await;
    /// #     view(test_database.database()).await?;
    /// #     test_database.cleanup().await?;
    /// #     Ok(())
    /// # }
    /// ```
    pub async fn get_by_username<DB: DatabaseBackend>(
        db: &DB,
        username: &str,
    ) -> Result<Option<Self>> {
        let username = LimitedString::<MAX_USERNAME_LENGTH>::new(username).map_err(|_| {
            AuthError::backend_error(CreateUserError::UsernameTooLong(username.len()))
        })?;
        let db_user = query!(DatabaseUser, $username == username)
            .get(db)
            .await
            .map_err(AuthError::backend_error)?;

        Ok(db_user)
    }

    /// Authenticate a user.
    ///
    /// # Errors
    ///
    /// Returns an error if there was an error querying the database.
    pub async fn authenticate<DB: DatabaseBackend>(
        db: &DB,
        credentials: &DatabaseUserCredentials,
    ) -> Result<Option<Self>> {
        let username = credentials.username();
        let username_limited = LimitedString::<MAX_USERNAME_LENGTH>::new(username.to_string())
            .map_err(|_| {
                AuthError::backend_error(CreateUserError::UsernameTooLong(username.len()))
            })?;
        let user = query!(DatabaseUser, $username == username_limited)
            .get(db)
            .await
            .map_err(AuthError::backend_error)?;

        if let Some(mut user) = user {
            let password_hash = &user.password;
            match password_hash.verify(credentials.password()) {
                PasswordVerificationResult::Ok => Ok(Some(user)),
                PasswordVerificationResult::OkObsolete(new_hash) => {
                    user.password = new_hash;
                    user.save(db).await.map_err(AuthError::backend_error)?;
                    Ok(Some(user))
                }
                PasswordVerificationResult::Invalid => Ok(None),
            }
        } else {
            // SECURITY: If no user was found, run the same hashing function to prevent
            // timing attacks from being used to determine if a user exists. Additionally,
            // do something with the result to prevent the compiler from optimizing out the
            // operation.
            // TODO: benchmark this to make sure it works as expected
            let dummy_hash = PasswordHash::from_password(credentials.password());
            if let PasswordVerificationResult::Invalid = dummy_hash.verify(credentials.password()) {
                unreachable!(
                    "Password hash verification should never fail for a newly generated hash"
                );
            }
            Ok(None)
        }
    }

    /// Get the ID of the user.
    ///
    /// # Example
    ///
    /// ```
    /// use cot::auth::UserId;
    /// use cot::auth::db::DatabaseUser;
    /// use cot::common_types::Password;
    /// use cot::db::Database;
    /// use cot::html::Html;
    ///
    /// async fn view(db: Database) -> cot::Result<Html> {
    ///     let user =
    ///         DatabaseUser::create_user(&db, "testuser".to_string(), &Password::new("password123"))
    ///             .await?;
    ///
    ///     Ok(Html::new(format!("User ID: {}", user.id())))
    /// }
    /// #
    /// # #[tokio::main]
    /// # async fn main() -> cot::Result<()> {
    /// #     use cot::test::{TestDatabase, TestRequestBuilder};
    /// #     use cot::request::Request;
    /// #     use cot::RequestHandler;
    /// #     let mut test_database = TestDatabase::new_sqlite().await?;
    /// #     test_database.with_auth().run_migrations().await;
    /// #     let request = TestRequestBuilder::get("/")
    /// #         .with_db_auth(test_database.database())
    /// #         .await
    /// #         .build();
    /// #     view.handle(request).await?;
    /// #     test_database.cleanup().await?;
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn id(&self) -> i64 {
        match self.id {
            Auto::Fixed(id) => id,
            Auto::Auto => unreachable!("DatabaseUser constructed with an unknown ID"),
        }
    }

    /// Get the username of the user.
    ///
    /// # Example
    ///
    /// ```
    /// use cot::auth::UserId;
    /// use cot::auth::db::DatabaseUser;
    /// use cot::common_types::Password;
    /// use cot::db::Database;
    /// use cot::html::Html;
    ///
    /// async fn view(db: Database) -> cot::Result<Html> {
    ///     let user =
    ///         DatabaseUser::create_user(&db, "testuser".to_string(), &Password::new("password123"))
    ///             .await?;
    ///
    ///     Ok(Html::new(format!("Username: {}", user.username())))
    /// }
    /// #
    /// # #[tokio::main]
    /// # async fn main() -> cot::Result<()> {
    /// #     use cot::test::{TestDatabase, TestRequestBuilder};
    /// #     use cot::request::Request;
    /// #     use cot::RequestHandler;
    /// #     let mut test_database = TestDatabase::new_sqlite().await?;
    /// #     test_database.with_auth().run_migrations().await;
    /// #     let request = TestRequestBuilder::get("/")
    /// #         .with_db_auth(test_database.database())
    /// #         .await
    /// #         .build();
    /// #     view.handle(request).await?;
    /// #     test_database.cleanup().await?;
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn username(&self) -> &str {
        &self.username
    }
}

type SessionAuthHmac = Hmac<Sha512>;

impl User for DatabaseUser {
    fn id(&self) -> Option<UserId> {
        Some(UserId::Int(self.id()))
    }

    fn username(&self) -> Option<Cow<'_, str>> {
        Some(Cow::from(self.username.as_str()))
    }

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

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

    fn session_auth_hash(&self, secret_key: &SecretKey) -> Option<SessionAuthHash> {
        let mut mac = SessionAuthHmac::new_from_slice(secret_key.as_bytes())
            .expect("HMAC can take key of any size");
        mac.update(self.password.as_str().as_bytes());
        let hmac_data = mac.finalize().into_bytes();

        Some(SessionAuthHash::new(&hmac_data))
    }
}

impl Display for DatabaseUser {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.username)
    }
}

/// Credentials for authenticating a user stored in the database.
///
/// This struct is used to authenticate a user stored in the database. It
/// contains the username and password of the user.
///
/// Can be passed to [`Auth::authenticate`](crate::auth::Auth::authenticate) to
/// authenticate a user when using the [`DatabaseUserBackend`].
#[derive(Debug, Clone)]
pub struct DatabaseUserCredentials {
    username: String,
    password: Password,
}

impl DatabaseUserCredentials {
    /// Create a new instance of the database user credentials.
    ///
    /// # Example
    ///
    /// ```
    /// use cot::auth::db::DatabaseUserCredentials;
    /// use cot::common_types::Password;
    ///
    /// let credentials =
    ///     DatabaseUserCredentials::new(String::from("testuser"), Password::new("password123"));
    /// ```
    #[must_use]
    pub fn new(username: String, password: Password) -> Self {
        Self { username, password }
    }

    /// Get the username of the user.
    ///
    /// # Example
    ///
    /// ```
    /// use cot::auth::db::DatabaseUserCredentials;
    /// use cot::common_types::Password;
    ///
    /// let credentials =
    ///     DatabaseUserCredentials::new(String::from("testuser"), Password::new("password123"));
    /// assert_eq!(credentials.username(), "testuser");
    /// ```
    #[must_use]
    pub fn username(&self) -> &str {
        &self.username
    }

    /// Get the password of the user.
    ///
    /// # Example
    ///
    /// ```
    /// use cot::auth::db::DatabaseUserCredentials;
    /// use cot::common_types::Password;
    ///
    /// let credentials =
    ///     DatabaseUserCredentials::new(String::from("testuser"), Password::new("password123"));
    /// assert!(!credentials.password().as_str().is_empty());
    /// ```
    #[must_use]
    pub fn password(&self) -> &Password {
        &self.password
    }
}

/// The authentication backend for users stored in the database.
///
/// This is the default authentication backend for Cot. It authenticates
/// users stored in the database using the [`DatabaseUser`] model.
///
/// This backend supports authenticating users using the
/// [`DatabaseUserCredentials`] struct and ignores all other credential types.
#[derive(Debug, Clone)]
pub struct DatabaseUserBackend {
    database: Database,
}

impl DatabaseUserBackend {
    /// Create a new instance of the database user authentication backend.
    ///
    /// # Example
    ///
    /// ```
    /// use std::sync::Arc;
    ///
    /// use cot::auth::AuthBackend;
    /// use cot::auth::db::DatabaseUserBackend;
    /// use cot::config::ProjectConfig;
    /// use cot::project::{AuthBackendContext, WithApps};
    /// use cot::{Project, ProjectContext};
    ///
    /// struct HelloProject;
    /// impl Project for HelloProject {
    ///     fn auth_backend(&self, context: &AuthBackendContext) -> Arc<dyn AuthBackend> {
    ///         Arc::new(DatabaseUserBackend::new(context.database().clone()))
    ///         // note that it's usually better to just set the auth backend in the config
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn new(database: Database) -> Self {
        Self { database }
    }
}

#[async_trait]
impl AuthBackend for DatabaseUserBackend {
    async fn authenticate(
        &self,
        credentials: &(dyn Any + Send + Sync),
    ) -> Result<Option<Box<dyn User + Send + Sync>>> {
        if let Some(credentials) = credentials.downcast_ref::<DatabaseUserCredentials>() {
            #[expect(trivial_casts)] // Upcast to the correct Box type
            Ok(DatabaseUser::authenticate(&self.database, credentials)
                .await
                .map(|user| user.map(|user| Box::new(user) as Box<dyn User + Send + Sync>))?)
        } else {
            Err(AuthError::CredentialsTypeNotSupported)
        }
    }

    async fn get_by_id(&self, id: UserId) -> Result<Option<Box<dyn User + Send + Sync>>> {
        let UserId::Int(id) = id else {
            return Err(AuthError::UserIdTypeNotSupported);
        };

        #[expect(trivial_casts)] // Upcast to the correct Box type
        Ok(DatabaseUser::get_by_id(&self.database, id)
            .await?
            .map(|user| Box::new(user) as Box<dyn User + Send + Sync>))
    }
}

/// An app that provides authentication via a user model stored in the database.
#[derive(Debug, Copy, Clone)]
pub struct DatabaseUserApp;

impl Default for DatabaseUserApp {
    fn default() -> Self {
        Self::new()
    }
}

impl DatabaseUserApp {
    /// Create a new instance of the database user authentication app.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use cot::auth::db::DatabaseUserApp;
    /// use cot::config::{DatabaseConfig, ProjectConfig};
    /// use cot::project::RegisterAppsContext;
    /// use cot::{App, AppBuilder, Project};
    ///
    /// struct HelloProject;
    /// impl Project for HelloProject {
    ///     fn config(&self, config_name: &str) -> cot::Result<ProjectConfig> {
    ///         Ok(ProjectConfig::builder()
    ///             .database(DatabaseConfig::builder().url("sqlite::memory:").build())
    ///             .build())
    ///     }
    ///
    ///     fn register_apps(&self, apps: &mut AppBuilder, _context: &RegisterAppsContext) {
    ///         use cot::project::{RegisterAppsContext, WithConfig};
    ///         apps.register_with_views(DatabaseUserApp::new(), "");
    ///     }
    /// }
    ///
    /// #[cot::main]
    /// fn main() -> impl Project {
    ///     HelloProject
    /// }
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {}
    }
}

impl App for DatabaseUserApp {
    fn name(&self) -> &'static str {
        "cot_db_user"
    }

    fn admin_model_managers(&self) -> Vec<Box<dyn AdminModelManager>> {
        vec![Box::new(DefaultAdminModelManager::<DatabaseUser>::new())]
    }

    fn migrations(&self) -> Vec<Box<SyncDynMigration>> {
        cot::db::migrations::wrap_migrations(migrations::MIGRATIONS)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::SecretKey;
    use crate::db::MockDatabaseBackend;

    #[test]
    #[cfg_attr(miri, ignore)]
    fn session_auth_hash() {
        let user = DatabaseUser::new(
            Auto::fixed(1),
            LimitedString::new("testuser").unwrap(),
            &Password::new("password123"),
        );
        let secret_key = SecretKey::new(b"supersecretkey");

        let hash = user.session_auth_hash(&secret_key);
        assert!(hash.is_some());
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    fn database_user_traits() {
        let user = DatabaseUser::new(
            Auto::fixed(1),
            LimitedString::new("testuser").unwrap(),
            &Password::new("password123"),
        );
        let user_ref: &dyn User = &user;
        assert_eq!(user_ref.id(), Some(UserId::Int(1)));
        assert_eq!(user_ref.username(), Some(Cow::from("testuser")));
        assert!(user_ref.is_active());
        assert!(user_ref.is_authenticated());
        assert!(
            user_ref
                .session_auth_hash(&SecretKey::new(b"supersecretkey"))
                .is_some()
        );
    }

    #[cot::test]
    #[cfg_attr(miri, ignore)]
    async fn create_user() {
        let mut mock_db = MockDatabaseBackend::new();
        mock_db
            .expect_insert::<DatabaseUser>()
            .returning(|_| Ok(()));

        let username = "testuser".to_string();
        let password = Password::new("password123");

        let user = DatabaseUser::create_user(&mock_db, username.clone(), &password)
            .await
            .unwrap();
        assert_eq!(user.username(), username);
    }

    #[cot::test]
    #[cfg_attr(miri, ignore)]
    async fn get_by_id() {
        let mut mock_db = MockDatabaseBackend::new();
        let user = DatabaseUser::new(
            Auto::fixed(1),
            LimitedString::new("testuser").unwrap(),
            &Password::new("password123"),
        );

        mock_db
            .expect_get::<DatabaseUser>()
            .returning(move |_| Ok(Some(user.clone())));

        let result = DatabaseUser::get_by_id(&mock_db, 1).await.unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().username(), "testuser");
    }

    #[cot::test]
    #[cfg_attr(miri, ignore)]
    async fn authenticate() {
        let mut mock_db = MockDatabaseBackend::new();
        let user = DatabaseUser::new(
            Auto::fixed(1),
            LimitedString::new("testuser").unwrap(),
            &Password::new("password123"),
        );

        mock_db
            .expect_get::<DatabaseUser>()
            .returning(move |_| Ok(Some(user.clone())));

        let credentials =
            DatabaseUserCredentials::new("testuser".to_string(), Password::new("password123"));
        let result = DatabaseUser::authenticate(&mock_db, &credentials)
            .await
            .unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().username(), "testuser");
    }

    #[cot::test]
    #[cfg_attr(miri, ignore)]
    async fn authenticate_non_existing() {
        let mut mock_db = MockDatabaseBackend::new();

        mock_db
            .expect_get::<DatabaseUser>()
            .returning(move |_| Ok(None));

        let credentials =
            DatabaseUserCredentials::new("testuser".to_string(), Password::new("password123"));
        let result = DatabaseUser::authenticate(&mock_db, &credentials)
            .await
            .unwrap();
        assert!(result.is_none());
    }

    #[cot::test]
    #[cfg_attr(miri, ignore)]
    async fn authenticate_invalid_password() {
        let mut mock_db = MockDatabaseBackend::new();
        let user = DatabaseUser::new(
            Auto::fixed(1),
            LimitedString::new("testuser").unwrap(),
            &Password::new("password123"),
        );

        mock_db
            .expect_get::<DatabaseUser>()
            .returning(move |_| Ok(Some(user.clone())));

        let credentials =
            DatabaseUserCredentials::new("testuser".to_string(), Password::new("invalid"));
        let result = DatabaseUser::authenticate(&mock_db, &credentials)
            .await
            .unwrap();
        assert!(result.is_none());
    }
}