torii-auth-password 0.2.0

Password authentication plugin 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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! A plugin for Torii that provides email and password authentication.
//!
//! This plugin allows users to register and authenticate using an email address and password.
//! It handles password hashing, validation, and session management.
//!
//! # Usage
//!
//! ```rust,no_run
//! use torii::Torii;
//! use torii_storage_sqlite::SqliteStorage;
//! use std::sync::Arc;
//!
//! let user_storage = Arc::new(SqliteStorage::new(pool.clone()));
//! let session_storage = Arc::new(SqliteStorage::new(pool.clone()));
//!
//! let torii = Torii::new(user_storage, session_storage)
//!     .with_password_plugin();
//!
//! // Register a new user
//! let user = torii.register_user_with_password("user@example.com", "password123").await?;
//!
//! // Login an existing user
//! let (user, session) = torii.login_user_with_password("user@example.com", "password123").await?;
//! ```
//!
//! The password plugin requires a storage implementation that implements the [`PasswordStorage`]
//! trait for storing user credentials and the [`SessionStorage`] trait for managing sessions.
//!
//! # Features
//!
//! - User registration with email and password
//! - Password hashing and validation
//! - Session management
//! - Optional email verification
//! - Event emission for authentication events

use chrono::{DateTime, Utc};
use password_auth::{generate_hash, verify_password};
use regex::Regex;
use torii_core::{
    Error, NewUser, Plugin, Session, SessionStorage, User, UserId,
    error::{AuthError, StorageError, ValidationError},
    events::{Event, EventBus},
    session::SessionId,
    storage::{PasswordStorage, Storage},
};

pub struct PasswordPlugin<U, S>
where
    U: PasswordStorage,
    S: SessionStorage,
{
    storage: Storage<U, S>,
    event_bus: Option<EventBus>,
}

impl<U, S> PasswordPlugin<U, S>
where
    U: PasswordStorage,
    S: SessionStorage,
{
    pub fn new(storage: Storage<U, S>) -> Self {
        Self {
            storage,
            event_bus: None,
        }
    }

    pub fn with_event_bus(mut self, event_bus: EventBus) -> Self {
        self.event_bus = Some(event_bus);
        self
    }
}

impl<U, S> Plugin for PasswordPlugin<U, S>
where
    U: PasswordStorage,
    S: SessionStorage,
{
    fn name(&self) -> String {
        "password".to_string()
    }
}

impl<U, S> PasswordPlugin<U, S>
where
    U: PasswordStorage,
    S: SessionStorage,
{
    pub async fn register_user_with_password(
        &self,
        email: &str,
        password: &str,
        email_verified_at: Option<DateTime<Utc>>,
    ) -> Result<User, Error> {
        if !is_valid_email(email) {
            return Err(Error::Validation(ValidationError::InvalidEmail));
        }
        if !is_valid_password(password) {
            return Err(Error::Validation(ValidationError::WeakPassword));
        }

        if let Some(_user) = self
            .storage
            .user_storage()
            .get_user_by_email(email)
            .await
            .map_err(|e| Error::Storage(StorageError::Database(e.to_string())))?
        {
            tracing::debug!(email = %email, "User already exists");
            return Err(Error::Auth(AuthError::UserAlreadyExists));
        }

        let new_user = NewUser::builder()
            .email(email.to_string())
            .email_verified_at(email_verified_at)
            .build()
            .unwrap();
        let user = self
            .storage
            .create_user(&new_user)
            .await
            .map_err(|e| Error::Storage(StorageError::Database(e.to_string())))?;

        let hash = generate_hash(password);
        self.storage
            .user_storage()
            .set_password_hash(&user.id, &hash)
            .await
            .map_err(|e| Error::Storage(StorageError::Database(e.to_string())))?;

        tracing::info!(
            user.id = %user.id,
            user.email = %user.email,
            user.name = ?user.name,
            "Created user",
        );

        self.emit_event(&Event::UserCreated(user.clone())).await?;

        Ok(user)
    }

    pub async fn change_user_password(
        &self,
        user_id: &UserId,
        old_password: &str,
        new_password: &str,
    ) -> Result<(), Error> {
        if !is_valid_password(new_password) {
            return Err(Error::Validation(ValidationError::WeakPassword));
        }

        let user = self
            .storage
            .user_storage()
            .get_user(user_id)
            .await
            .map_err(|e| Error::Storage(StorageError::Database(e.to_string())))?
            .ok_or(Error::Auth(AuthError::UserNotFound))?;

        let stored_hash = self
            .storage
            .user_storage()
            .get_password_hash(user_id)
            .await
            .map_err(|e| Error::Storage(StorageError::Database(e.to_string())))?;

        if stored_hash.is_none() {
            return Err(Error::Auth(AuthError::InvalidCredentials));
        }

        verify_password(old_password, &stored_hash.unwrap())
            .map_err(|_| Error::Auth(AuthError::InvalidCredentials))?;

        let new_hash = generate_hash(new_password);
        self.storage
            .user_storage()
            .set_password_hash(user_id, &new_hash)
            .await
            .map_err(|e| Error::Storage(StorageError::Database(e.to_string())))?;

        // Delete all existing sessions for this user for security
        self.delete_sessions_for_user(user_id).await?;

        tracing::info!(
            user.id = %user_id,
            "Changed user password",
        );

        self.emit_event(&Event::UserUpdated(user)).await?;

        Ok(())
    }

    pub async fn login_user_with_password(
        &self,
        email: &str,
        password: &str,
    ) -> Result<(User, Session), Error> {
        let user_storage = self.storage.user_storage();

        let user = user_storage
            .get_user_by_email(email)
            .await
            .map_err(|e| Error::Storage(StorageError::Database(e.to_string())))?
            .ok_or(Error::Auth(AuthError::UserNotFound))?;

        if !user.is_email_verified() {
            return Err(Error::Auth(AuthError::EmailNotVerified));
        }

        let hash = user_storage
            .get_password_hash(&user.id)
            .await
            .map_err(|e| Error::Storage(StorageError::Database(e.to_string())))?;

        if hash.is_none() {
            return Err(Error::Auth(AuthError::InvalidCredentials));
        }

        verify_password(password, &hash.unwrap())
            .map_err(|_| Error::Auth(AuthError::InvalidCredentials))?;

        let session = self.create_session(&user.id).await?;

        Ok((user, session))
    }

    async fn emit_event(&self, event: &Event) -> Result<(), Error> {
        if let Some(event_bus) = &self.event_bus {
            event_bus.emit(event).await?;
        }
        Ok(())
    }

    async fn create_session(&self, user_id: &UserId) -> Result<Session, Error> {
        let session = self
            .storage
            .create_session(&Session::builder().user_id(user_id.clone()).build().unwrap())
            .await
            .map_err(|e| Error::Storage(StorageError::Database(e.to_string())))?;

        self.emit_event(&Event::SessionCreated(user_id.clone(), session.clone()))
            .await?;

        Ok(session)
    }

    #[allow(unused)]
    async fn delete_session(&self, user_id: &UserId, session_id: &SessionId) -> Result<(), Error> {
        let session = self
            .storage
            .session_storage()
            .get_session(session_id)
            .await
            .map_err(|e| Error::Storage(StorageError::Database(e.to_string())))?
            .ok_or(Error::Auth(AuthError::SessionNotFound))?;

        self.storage
            .session_storage()
            .delete_session(session_id)
            .await
            .map_err(|e| Error::Storage(StorageError::Database(e.to_string())))?;

        self.emit_event(&Event::SessionDeleted(user_id.clone(), session.id))
            .await?;

        Ok(())
    }

    async fn delete_sessions_for_user(&self, user_id: &UserId) -> Result<(), Error> {
        self.storage
            .session_storage()
            .delete_sessions_for_user(user_id)
            .await
            .map_err(|e| Error::Storage(StorageError::Database(e.to_string())))?;

        self.emit_event(&Event::SessionsCleared(user_id.clone()))
            .await?;

        Ok(())
    }
}

/// Validate an email address.
fn is_valid_email(email: &str) -> bool {
    let email_regex = Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap();
    email_regex.is_match(email)
}

/// Validate a password.
fn is_valid_password(password: &str) -> bool {
    // TODO: Add more robust password validation
    password.len() >= 8
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use sqlx::SqlitePool;
    use std::sync::{
        Arc,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    };
    use torii_core::{PluginManager, error::EventError, events::EventHandler};
    use torii_storage_sqlite::SqliteStorage;

    async fn setup_plugin() -> Result<(PluginManager<SqliteStorage, SqliteStorage>,), Error> {
        let _ = tracing_subscriber::fmt().try_init();

        let pool = SqlitePool::connect("sqlite::memory:")
            .await
            .expect("Failed to create pool");

        let user_storage = Arc::new(SqliteStorage::new(pool.clone()));
        let session_storage = Arc::new(SqliteStorage::new(pool.clone()));

        let storage = Storage::new(user_storage.clone(), session_storage.clone());
        let mut manager = PluginManager::new(user_storage.clone(), session_storage.clone());
        manager.register_plugin(PasswordPlugin::new(storage));

        user_storage.migrate().await?;
        session_storage.migrate().await?;

        Ok((manager,))
    }

    #[test]
    fn test_is_valid_email() {
        // Valid email addresses
        assert!(is_valid_email("test@example.com"));
        assert!(is_valid_email("user.name@domain.co.uk"));
        assert!(is_valid_email("user+tag@example.com"));
        assert!(is_valid_email("123@domain.com"));

        // Invalid email addresses
        assert!(!is_valid_email(""));
        assert!(!is_valid_email("not-an-email"));
        assert!(!is_valid_email("@domain.com"));
        assert!(!is_valid_email("user@"));
        assert!(!is_valid_email("user@.com"));
        assert!(!is_valid_email("user@domain"));
        assert!(!is_valid_email("user name@domain.com"));
    }

    #[test]
    fn test_is_valid_password() {
        // Valid passwords (>= 8 characters)
        assert!(is_valid_password("password123"));
        assert!(is_valid_password("12345678"));
        assert!(is_valid_password("abcdefghijklmnop"));

        // Invalid passwords (< 8 characters)
        assert!(!is_valid_password(""));
        assert!(!is_valid_password("short"));
        assert!(!is_valid_password("1234567"));
    }

    #[tokio::test]
    async fn test_create_user_and_login_with_unverified_email() -> Result<(), Error> {
        let (manager,) = setup_plugin().await?;

        let user = manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .unwrap()
            .register_user_with_password("test@example.com", "password", None)
            .await?;
        assert_eq!(user.email, "test@example.com");

        let result = manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .unwrap()
            .login_user_with_password("test@example.com", "password")
            .await;
        assert!(matches!(
            result,
            Err(Error::Auth(AuthError::EmailNotVerified))
        ));

        Ok(())
    }

    #[tokio::test]
    async fn test_create_user_and_login_with_verified_email() -> Result<(), Error> {
        let (manager,) = setup_plugin().await?;

        let user = manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .unwrap()
            .register_user_with_password("test@example.com", "password", Some(Utc::now()))
            .await?;
        assert_eq!(user.email, "test@example.com");

        let (user, session) = manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .unwrap()
            .login_user_with_password("test@example.com", "password")
            .await?;
        assert_eq!(user.email, "test@example.com");
        assert_eq!(session.user_id, user.id);

        Ok(())
    }

    #[tokio::test]
    async fn test_create_duplicate_user() -> Result<(), Error> {
        let (manager,) = setup_plugin().await?;

        let _ = manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .unwrap()
            .register_user_with_password("test@example.com", "password", None)
            .await?;

        let result = manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .unwrap()
            .register_user_with_password("test@example.com", "password", None)
            .await;

        assert!(matches!(
            result,
            Err(Error::Auth(AuthError::UserAlreadyExists))
        ));

        Ok(())
    }

    #[tokio::test]
    async fn test_invalid_email_format() -> Result<(), Error> {
        let (manager,) = setup_plugin().await?;

        let result = manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .expect("Plugin should exist")
            .register_user_with_password("not-an-email", "password", None)
            .await;

        assert!(matches!(
            result,
            Err(Error::Validation(ValidationError::InvalidEmail))
        ));

        Ok(())
    }

    #[tokio::test]
    async fn test_weak_password() -> Result<(), Error> {
        let (manager,) = setup_plugin().await?;

        let result = manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .expect("Plugin should exist")
            .register_user_with_password("test@example.com", "123", None)
            .await;

        assert!(matches!(
            result,
            Err(Error::Validation(ValidationError::WeakPassword))
        ));

        Ok(())
    }

    #[tokio::test]
    async fn test_incorrect_password_login() -> Result<(), Error> {
        let (manager,) = setup_plugin().await?;

        manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .expect("Plugin should exist")
            .register_user_with_password("test@example.com", "password", Some(Utc::now()))
            .await?;

        let result = manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .expect("Plugin should exist")
            .login_user_with_password("test@example.com", "wrong-password")
            .await;

        assert!(matches!(
            result,
            Err(Error::Auth(AuthError::InvalidCredentials))
        ));

        Ok(())
    }

    #[tokio::test]
    async fn test_nonexistent_user_login() -> Result<(), Error> {
        let (manager,) = setup_plugin().await?;

        let result = manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .expect("Plugin should exist")
            .login_user_with_password("nonexistent@example.com", "password")
            .await;

        assert!(matches!(result, Err(Error::Auth(AuthError::UserNotFound))));

        Ok(())
    }

    #[tokio::test]
    async fn test_sql_injection_attempt() -> Result<(), Error> {
        let (manager,) = setup_plugin().await?;

        let _ = manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .expect("Plugin should exist")
            .register_user_with_password("test@example.com'; DROP TABLE users;--", "password", None)
            .await
            .expect_err("Should fail validation");

        Ok(())
    }

    #[tokio::test]
    async fn test_change_password() -> Result<(), Error> {
        let (manager,) = setup_plugin().await?;
        let plugin = manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .expect("Plugin should exist");

        // Create initial user
        let user = plugin
            .register_user_with_password("test@example.com", "password", Some(Utc::now()))
            .await?;

        let session = manager
            .storage()
            .create_session(&Session::builder().user_id(user.id.clone()).build().unwrap())
            .await?;

        // Verify initial session exists
        let initial_session = manager
            .storage()
            .get_session(&session.id)
            .await
            .expect("Failed to get session")
            .expect("Session should exist");
        assert_eq!(initial_session.user_id, user.id);

        // Change password
        plugin
            .change_user_password(&user.id, "password", "new-password")
            .await?;

        // Verify old session was deleted
        let deleted_session = manager.storage().get_session(&session.id).await;
        assert!(deleted_session.is_err());

        // Verify can login with new password
        let result = plugin
            .login_user_with_password("test@example.com", "new-password")
            .await;
        assert!(result.is_ok());

        // Verify can't login with old password
        let result = plugin
            .login_user_with_password("test@example.com", "password")
            .await;
        assert!(matches!(
            result,
            Err(Error::Auth(AuthError::InvalidCredentials))
        ));

        Ok(())
    }

    #[tokio::test]
    async fn test_event_handler_emitting() -> Result<(), Error> {
        let _ = tracing_subscriber::fmt().try_init();

        // Create in-memory SQLite database and storage
        let pool = SqlitePool::connect("sqlite::memory:")
            .await
            .expect("Failed to create pool");
        let user_storage = Arc::new(SqliteStorage::new(pool.clone()));
        let session_storage = Arc::new(SqliteStorage::new(pool));

        // Initialize database schema
        user_storage.migrate().await.unwrap();
        session_storage.migrate().await.unwrap();

        // Create plugin manager and event bus
        let storage = Storage::new(user_storage.clone(), session_storage.clone());
        let mut manager = PluginManager::new(user_storage, session_storage);
        let event_bus = EventBus::new();

        // Register plugin with event bus
        let plugin = PasswordPlugin::new(storage).with_event_bus(event_bus.clone());
        manager.register_plugin(plugin);

        // Create test event handler that tracks when events are emitted
        let event_was_emitted = Arc::new(AtomicBool::new(false));
        let event_count = Arc::new(AtomicUsize::new(0));
        let handler = TestEventHandler {
            called: event_was_emitted.clone(),
            call_count: event_count.clone(),
        };
        event_bus.register(Arc::new(handler)).await;

        let plugin = manager
            .get_plugin::<PasswordPlugin<SqliteStorage, SqliteStorage>>("password")
            .expect("Plugin should exist");

        // Test 1: Creating a user should emit an event
        let user = plugin
            .register_user_with_password("test@example.com", "password", Some(Utc::now()))
            .await?;
        assert!(
            event_was_emitted.load(Ordering::SeqCst),
            "No event emitted when creating user"
        );
        assert_eq!(event_count.load(Ordering::SeqCst), 1);

        // Test 2: Changing password should emit 2 events, one for the user update and one for the session deletion
        event_was_emitted.store(false, Ordering::SeqCst);
        plugin
            .change_user_password(&user.id, "password", "new-password")
            .await?;
        assert!(
            event_was_emitted.load(Ordering::SeqCst),
            "No event emitted when changing password"
        );
        assert_eq!(event_count.load(Ordering::SeqCst), 3);

        // Test 3: Logging in should emit 1 event
        event_was_emitted.store(false, Ordering::SeqCst);
        plugin
            .login_user_with_password("test@example.com", "new-password")
            .await?;
        assert!(
            event_was_emitted.load(Ordering::SeqCst),
            "No event emitted when logging in"
        );
        assert_eq!(event_count.load(Ordering::SeqCst), 4);

        Ok(())
    }

    struct TestEventHandler {
        called: Arc<AtomicBool>,
        call_count: Arc<AtomicUsize>,
    }

    #[async_trait]
    impl EventHandler for TestEventHandler {
        async fn handle_event(&self, _event: &Event) -> Result<(), EventError> {
            self.called.store(true, Ordering::SeqCst);
            self.call_count.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }
}