tideway 0.7.17

A batteries-included Rust web framework built on Axum for building SaaS applications quickly
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
//! Password change flow for authenticated users.
//!
//! This module emits tracing events for security monitoring:
//! - `auth.password.change_failed` - Password change failed (wrong current password, weak new password)
//! - `auth.password.changed` - Password changed successfully

use crate::auth::password::{PasswordHasher, PasswordPolicy};
use crate::error::{Result, TidewayError};
use async_trait::async_trait;

use super::types::PasswordChangeRequest;

/// Trait for password change storage operations.
///
/// Implement this trait to connect the password change flow to your database.
#[async_trait]
pub trait PasswordChangeStore: Send + Sync {
    /// Get the user's current password hash by user ID.
    async fn get_password_hash(&self, user_id: &str) -> Result<Option<String>>;

    /// Update the user's password hash.
    async fn update_password(&self, user_id: &str, hash: &str) -> Result<()>;

    /// Invalidate all sessions except the current one.
    ///
    /// Called after successful password change to log out other devices.
    /// The `except_session_id` is the current session to keep active.
    async fn invalidate_other_sessions(
        &self,
        user_id: &str,
        except_session_id: Option<&str>,
    ) -> Result<usize>;
}

/// Configuration for password change flow.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PasswordChangeConfig {
    /// Whether to invalidate other sessions after password change.
    pub invalidate_sessions: bool,
}

impl Default for PasswordChangeConfig {
    fn default() -> Self {
        Self {
            invalidate_sessions: true,
        }
    }
}

impl PasswordChangeConfig {
    /// Create a new config with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set whether to invalidate other sessions after password change.
    #[must_use]
    pub fn invalidate_sessions(mut self, invalidate: bool) -> Self {
        self.invalidate_sessions = invalidate;
        self
    }
}

/// Handles password change for authenticated users.
///
/// Unlike password reset (which uses email tokens), password change requires
/// the user to verify their current password before setting a new one.
///
/// # Example
///
/// ```rust,ignore
/// use tideway::auth::flows::{PasswordChangeFlow, PasswordChangeRequest};
///
/// let flow = PasswordChangeFlow::new(store);
///
/// // User must be authenticated - we have their user_id from JWT
/// flow.change_password(
///     "user-123",
///     PasswordChangeRequest {
///         current_password: "old-password".to_string(),
///         new_password: "new-secure-password".to_string(),
///     },
///     Some("current-session-id"), // Keep this session active
/// ).await?;
/// ```
pub struct PasswordChangeFlow<S: PasswordChangeStore> {
    store: S,
    password_hasher: PasswordHasher,
    password_policy: PasswordPolicy,
    config: PasswordChangeConfig,
}

impl<S: PasswordChangeStore> PasswordChangeFlow<S> {
    /// Create a new password change flow.
    #[must_use]
    pub fn new(store: S) -> Self {
        Self {
            store,
            password_hasher: PasswordHasher::default(),
            password_policy: PasswordPolicy::modern(),
            config: PasswordChangeConfig::default(),
        }
    }

    /// Set a custom password policy.
    #[must_use]
    pub fn with_policy(mut self, policy: PasswordPolicy) -> Self {
        self.password_policy = policy;
        self
    }

    /// Set a custom configuration.
    #[must_use]
    pub fn with_config(mut self, config: PasswordChangeConfig) -> Self {
        self.config = config;
        self
    }

    /// Disable session invalidation after password change.
    #[must_use]
    pub fn without_session_invalidation(mut self) -> Self {
        self.config.invalidate_sessions = false;
        self
    }

    /// Change a user's password.
    ///
    /// # Arguments
    ///
    /// * `user_id` - The authenticated user's ID (from JWT claims)
    /// * `req` - The password change request with current and new passwords
    /// * `current_session_id` - Optional session ID to keep active (revokes all others)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The current password is incorrect
    /// - The new password doesn't meet the policy
    /// - The user doesn't exist
    #[cfg(feature = "auth")]
    pub async fn change_password(
        &self,
        user_id: &str,
        req: PasswordChangeRequest,
        current_session_id: Option<&str>,
    ) -> Result<()> {
        // Get current password hash
        let current_hash = match self.store.get_password_hash(user_id).await? {
            Some(hash) => hash,
            None => {
                tracing::warn!(
                    target: "auth.password.change_failed",
                    user_id = %user_id,
                    reason = "user_not_found",
                    "Password change failed: user not found"
                );
                return Err(TidewayError::Unauthorized("Invalid credentials".into()));
            }
        };

        // Verify current password
        if !self
            .password_hasher
            .verify(&req.current_password, &current_hash)?
        {
            tracing::warn!(
                target: "auth.password.change_failed",
                user_id = %user_id,
                reason = "wrong_password",
                "Password change failed: current password incorrect"
            );
            return Err(TidewayError::Unauthorized(
                "Current password is incorrect".into(),
            ));
        }

        // Validate new password against policy
        if let Err(e) = self.password_policy.check(&req.new_password) {
            tracing::info!(
                target: "auth.password.change_failed",
                user_id = %user_id,
                reason = "weak_password",
                "Password change failed: new password doesn't meet policy"
            );
            return Err(e);
        }

        // Prevent setting same password
        if self
            .password_hasher
            .verify(&req.new_password, &current_hash)?
        {
            tracing::info!(
                target: "auth.password.change_failed",
                user_id = %user_id,
                reason = "same_password",
                "Password change failed: new password same as current"
            );
            return Err(TidewayError::BadRequest(
                "New password must be different from current password".into(),
            ));
        }

        // Hash new password
        let new_hash = self.password_hasher.hash(&req.new_password)?;

        // Update password
        self.store.update_password(user_id, &new_hash).await?;

        // Invalidate other sessions
        let sessions_revoked = if self.config.invalidate_sessions {
            self.store
                .invalidate_other_sessions(user_id, current_session_id)
                .await?
        } else {
            0
        };

        tracing::info!(
            target: "auth.password.changed",
            user_id = %user_id,
            sessions_revoked = sessions_revoked,
            "Password changed successfully"
        );

        Ok(())
    }

    #[cfg(not(feature = "auth"))]
    pub async fn change_password(
        &self,
        _user_id: &str,
        _req: PasswordChangeRequest,
        _current_session_id: Option<&str>,
    ) -> Result<()> {
        Err(TidewayError::Internal("auth feature not enabled".into()))
    }

    /// Get a reference to the underlying store.
    #[must_use]
    pub fn store(&self) -> &S {
        &self.store
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::sync::RwLock;

    struct TestStore {
        passwords: RwLock<HashMap<String, String>>,
        invalidated_sessions: RwLock<Vec<(String, Option<String>)>>,
    }

    impl TestStore {
        fn new() -> Self {
            Self {
                passwords: RwLock::new(HashMap::new()),
                invalidated_sessions: RwLock::new(vec![]),
            }
        }

        fn add_user(&self, user_id: &str, password_hash: &str) {
            self.passwords
                .write()
                .unwrap()
                .insert(user_id.to_string(), password_hash.to_string());
        }

        fn get_invalidated(&self) -> Vec<(String, Option<String>)> {
            self.invalidated_sessions.read().unwrap().clone()
        }
    }

    #[async_trait]
    impl PasswordChangeStore for TestStore {
        async fn get_password_hash(&self, user_id: &str) -> Result<Option<String>> {
            Ok(self.passwords.read().unwrap().get(user_id).cloned())
        }

        async fn update_password(&self, user_id: &str, hash: &str) -> Result<()> {
            self.passwords
                .write()
                .unwrap()
                .insert(user_id.to_string(), hash.to_string());
            Ok(())
        }

        async fn invalidate_other_sessions(
            &self,
            user_id: &str,
            except_session_id: Option<&str>,
        ) -> Result<usize> {
            self.invalidated_sessions
                .write()
                .unwrap()
                .push((user_id.to_string(), except_session_id.map(String::from)));
            Ok(3) // Pretend we revoked 3 sessions
        }
    }

    fn create_test_hash(password: &str) -> String {
        let hasher = PasswordHasher::default();
        hasher.hash(password).unwrap()
    }

    #[tokio::test]
    async fn test_change_password_success() {
        let store = TestStore::new();
        let old_hash = create_test_hash("OldPassword123!");
        store.add_user("user-1", &old_hash);

        let flow = PasswordChangeFlow::new(store);

        let result = flow
            .change_password(
                "user-1",
                PasswordChangeRequest {
                    current_password: "OldPassword123!".to_string(),
                    new_password: "NewSecurePassword456!".to_string(),
                },
                Some("session-123"),
            )
            .await;

        assert!(result.is_ok());

        // Verify sessions were invalidated
        let invalidated = flow.store.get_invalidated();
        assert_eq!(invalidated.len(), 1);
        assert_eq!(invalidated[0].0, "user-1");
        assert_eq!(invalidated[0].1, Some("session-123".to_string()));

        // Verify password was updated (can verify new password)
        let new_hash = flow
            .store
            .get_password_hash("user-1")
            .await
            .unwrap()
            .unwrap();
        assert_ne!(new_hash, old_hash);

        let hasher = PasswordHasher::default();
        assert!(hasher.verify("NewSecurePassword456!", &new_hash).unwrap());
    }

    #[tokio::test]
    async fn test_change_password_wrong_current() {
        let store = TestStore::new();
        store.add_user("user-1", &create_test_hash("OldPassword123!"));

        let flow = PasswordChangeFlow::new(store);

        let result = flow
            .change_password(
                "user-1",
                PasswordChangeRequest {
                    current_password: "WrongPassword!".to_string(),
                    new_password: "NewSecurePassword456!".to_string(),
                },
                None,
            )
            .await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("incorrect"));
    }

    #[tokio::test]
    async fn test_change_password_weak_new_password() {
        let store = TestStore::new();
        store.add_user("user-1", &create_test_hash("OldPassword123!"));

        let flow = PasswordChangeFlow::new(store);

        let result = flow
            .change_password(
                "user-1",
                PasswordChangeRequest {
                    current_password: "OldPassword123!".to_string(),
                    new_password: "weak".to_string(),
                },
                None,
            )
            .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_change_password_same_password() {
        let store = TestStore::new();
        store.add_user("user-1", &create_test_hash("OldPassword123!"));

        let flow = PasswordChangeFlow::new(store);

        let result = flow
            .change_password(
                "user-1",
                PasswordChangeRequest {
                    current_password: "OldPassword123!".to_string(),
                    new_password: "OldPassword123!".to_string(),
                },
                None,
            )
            .await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("different"));
    }

    #[tokio::test]
    async fn test_change_password_user_not_found() {
        let store = TestStore::new();
        let flow = PasswordChangeFlow::new(store);

        let result = flow
            .change_password(
                "nonexistent",
                PasswordChangeRequest {
                    current_password: "anything".to_string(),
                    new_password: "NewSecurePassword456!".to_string(),
                },
                None,
            )
            .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_change_password_without_session_invalidation() {
        let store = TestStore::new();
        store.add_user("user-1", &create_test_hash("OldPassword123!"));

        let flow = PasswordChangeFlow::new(store).without_session_invalidation();

        let result = flow
            .change_password(
                "user-1",
                PasswordChangeRequest {
                    current_password: "OldPassword123!".to_string(),
                    new_password: "NewSecurePassword456!".to_string(),
                },
                None,
            )
            .await;

        assert!(result.is_ok());

        // Sessions should NOT be invalidated
        let invalidated = flow.store.get_invalidated();
        assert!(invalidated.is_empty());
    }

    #[tokio::test]
    async fn test_custom_policy() {
        let store = TestStore::new();
        store.add_user("user-1", &create_test_hash("OldPassword123!"));

        // Use strict policy requiring special char
        let flow = PasswordChangeFlow::new(store).with_policy(PasswordPolicy::strict());

        let result = flow
            .change_password(
                "user-1",
                PasswordChangeRequest {
                    current_password: "OldPassword123!".to_string(),
                    new_password: "NewPasswordWithoutSpecial123".to_string(),
                },
                None,
            )
            .await;

        assert!(result.is_err());
    }
}