mockforge-ui 0.3.88

Admin UI for MockForge - web-based interface for managing mock servers
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! Database-backed user store implementation
//!
//! This module provides a database-backed user store that replaces
//! the in-memory implementation for production use.

use crate::auth::password_policy::{PasswordPolicy, PasswordValidationError};
use bcrypt::{hash, verify, DEFAULT_COST};
use chrono::{DateTime, Utc};
use mockforge_collab::models::UserRole;
#[cfg(feature = "database-auth")]
use sqlx::{AnyPool, Row};
use std::sync::Arc;
use tokio::sync::RwLock;
use uuid::Uuid;

/// User struct for database-backed store
#[derive(Debug, Clone)]
pub struct DatabaseUser {
    pub id: String,
    pub username: String,
    pub password_hash: String,
    pub role: UserRole,
    pub email: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub last_login_at: Option<DateTime<Utc>>,
    pub failed_login_attempts: i32,
    pub locked_until: Option<DateTime<Utc>>,
}

/// Rate limiting for login attempts (in-memory for performance)
#[derive(Debug, Clone)]
pub struct RateLimiter {
    attempts: Arc<RwLock<std::collections::HashMap<String, Vec<std::time::Instant>>>>,
    max_attempts: usize,
    window_seconds: u64,
}

impl RateLimiter {
    pub fn new(max_attempts: usize, window_seconds: u64) -> Self {
        Self {
            attempts: Arc::new(RwLock::new(std::collections::HashMap::new())),
            max_attempts,
            window_seconds,
        }
    }

    pub async fn check_rate_limit(&self, username: &str) -> Result<(), String> {
        let mut attempts = self.attempts.write().await;
        let now = std::time::Instant::now();
        let window = std::time::Duration::from_secs(self.window_seconds);

        // Clean up old attempts
        let user_attempts = attempts.entry(username.to_string()).or_insert_with(Vec::new);
        user_attempts.retain(|&time| now.duration_since(time) < window);

        // Check if limit exceeded
        if user_attempts.len() >= self.max_attempts {
            return Err(format!(
                "Too many login attempts. Please try again in {} seconds.",
                self.window_seconds
            ));
        }

        // Record this attempt
        user_attempts.push(now);
        Ok(())
    }

    pub async fn reset_rate_limit(&self, username: &str) {
        let mut attempts = self.attempts.write().await;
        attempts.remove(username);
    }
}

/// Account lockout configuration
#[derive(Debug, Clone)]
pub struct AccountLockout {
    max_attempts: usize,
    lockout_duration_seconds: u64,
}

impl AccountLockout {
    pub fn new(max_attempts: usize, lockout_duration_seconds: u64) -> Self {
        Self {
            max_attempts,
            lockout_duration_seconds,
        }
    }
}

/// Database-backed user store
///
/// This implementation uses SQLite or PostgreSQL for persistent user storage.
#[derive(Clone)]
pub struct DatabaseUserStore {
    #[cfg(feature = "database-auth")]
    db: AnyPool,
    rate_limiter: RateLimiter,
    account_lockout: AccountLockout,
    password_policy: PasswordPolicy,
}

impl DatabaseUserStore {
    /// Create a new database-backed user store
    ///
    /// # Arguments
    /// * `database_url` - Database connection string (SQLite or PostgreSQL)
    ///
    /// # Example
    /// ```rust,no_run
    /// let store = DatabaseUserStore::new("sqlite://mockforge.db").await?;
    /// ```
    #[cfg(feature = "database-auth")]
    pub async fn new(database_url: &str) -> Result<Self, String> {
        // Connect to database using AnyPool (supports both SQLite and PostgreSQL)
        let pool = sqlx::any::AnyPoolOptions::new()
            .max_connections(10)
            .connect(database_url)
            .await
            .map_err(|e| format!("Failed to connect to database: {}", e))?;

        // Run migrations
        sqlx::migrate!("./migrations")
            .run(&pool)
            .await
            .map_err(|e| format!("Failed to run migrations: {}", e))?;

        Ok(Self {
            db: pool,
            rate_limiter: RateLimiter::new(5, 300), // 5 attempts per 5 minutes
            account_lockout: AccountLockout::new(5, 900), // 5 attempts, 15 minute lockout
            password_policy: PasswordPolicy::default(),
        })
    }

    /// Authenticate a user against the database
    #[cfg(feature = "database-auth")]
    pub async fn authenticate(
        &self,
        username: &str,
        password: &str,
        ip_address: Option<&str>,
        user_agent: Option<&str>,
    ) -> Result<DatabaseUser, String> {
        // Check rate limiting
        self.rate_limiter.check_rate_limit(username).await?;

        // Fetch user from database
        let row = sqlx::query(
            r#"
            SELECT id, username, password_hash, role, email, created_at, updated_at,
                   last_login_at, failed_login_attempts, locked_until
            FROM admin_users
            WHERE username = $1 AND (locked_until IS NULL OR locked_until < CURRENT_TIMESTAMP)
            "#
        )
        .bind(username)
        .fetch_optional(&self.db)
        .await
        .map_err(|e| format!("Database error: {}", e))?;

        let row = row.ok_or_else(|| "Invalid username or password".to_string())?;

        let mut user_row = DatabaseUserRow {
            id: row.try_get("id").map_err(|e| format!("Failed to read id: {}", e))?,
            username: row.try_get("username").map_err(|e| format!("Failed to read username: {}", e))?,
            password_hash: row.try_get("password_hash").map_err(|e| format!("Failed to read password_hash: {}", e))?,
            role: row.try_get("role").map_err(|e| format!("Failed to read role: {}", e))?,
            email: row.try_get("email").ok(),
            created_at: row.try_get::<chrono::NaiveDateTime, _>("created_at")
                .map_err(|e| format!("Failed to read created_at: {}", e))?
                .and_utc(),
            updated_at: row.try_get::<chrono::NaiveDateTime, _>("updated_at")
                .map_err(|e| format!("Failed to read updated_at: {}", e))?
                .and_utc(),
            last_login_at: row.try_get::<chrono::NaiveDateTime, _>("last_login_at")
                .ok()
                .map(|dt| dt.and_utc()),
            failed_login_attempts: row.try_get("failed_login_attempts").unwrap_or(0),
            locked_until: row.try_get::<chrono::NaiveDateTime, _>("locked_until")
                .ok()
                .map(|dt| dt.and_utc()),
        };

        // Check if account is locked
        if let Some(locked_until) = user_row.locked_until {
            if locked_until > Utc::now() {
                let remaining = (locked_until - Utc::now()).num_seconds();
                return Err(format!(
                    "Account is locked due to too many failed login attempts. Please try again in {} seconds.",
                    remaining
                ));
            }
        }

        // Verify password
        let password_valid = verify(password, &user_row.password_hash)
            .map_err(|e| format!("Password verification error: {}", e))?;

        // Record login attempt
        let attempt_id = Uuid::new_v4().to_string();
        sqlx::query(
            r#"
            INSERT INTO login_attempts (id, username, ip_address, user_agent, success, created_at)
            VALUES ($1, $2, $3, $4, $5, CURRENT_TIMESTAMP)
            "#
        )
        .bind(&attempt_id)
        .bind(username)
        .bind(ip_address)
        .bind(user_agent)
        .bind(if password_valid { 1 } else { 0 })
        .execute(&self.db)
        .await
        .ok(); // Don't fail on logging error

        if !password_valid {
            // Increment failed login attempts
            user_row.failed_login_attempts += 1;

            // Lock account if too many failures
            if user_row.failed_login_attempts >= self.account_lockout.max_attempts as i32 {
                let locked_until = Utc::now() + chrono::Duration::seconds(self.account_lockout.lockout_duration_seconds as i64);
                sqlx::query(
                    r#"
                    UPDATE admin_users
                    SET failed_login_attempts = $1, locked_until = $2, updated_at = CURRENT_TIMESTAMP
                    WHERE id = $3
                    "#
                )
                .bind(user_row.failed_login_attempts)
                .bind(locked_until.naive_utc())
                .bind(&user_row.id)
                .execute(&self.db)
                .await
                .ok();
            } else {
                sqlx::query(
                    r#"
                    UPDATE admin_users
                    SET failed_login_attempts = $1, updated_at = CURRENT_TIMESTAMP
                    WHERE id = $2
                    "#
                )
                .bind(user_row.failed_login_attempts)
                .bind(&user_row.id)
                .execute(&self.db)
                .await
                .ok();
            }

            return Err("Invalid username or password".to_string());
        }

        // Successful login - reset failed attempts and update last login
        sqlx::query(
            r#"
            UPDATE admin_users
            SET failed_login_attempts = 0, locked_until = NULL, last_login_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP
            WHERE id = $1
            "#
        )
        .bind(&user_row.id)
        .execute(&self.db)
        .await
        .map_err(|e| format!("Failed to update user: {}", e))?;

        // Reset rate limit
        self.rate_limiter.reset_rate_limit(username).await;

        // Convert to DatabaseUser
        Ok(DatabaseUser {
            id: user_row.id,
            username: user_row.username,
            password_hash: user_row.password_hash,
            role: parse_role(&user_row.role)?,
            email: user_row.email,
            created_at: user_row.created_at,
            updated_at: user_row.updated_at,
            last_login_at: user_row.last_login_at,
            failed_login_attempts: 0,
            locked_until: None,
        })
    }

    /// Get user by ID from database
    #[cfg(feature = "database-auth")]
    pub async fn get_user_by_id(&self, user_id: &str) -> Result<Option<DatabaseUser>, String> {
        let row = sqlx::query(
            r#"
            SELECT id, username, password_hash, role, email, created_at, updated_at,
                   last_login_at, failed_login_attempts, locked_until
            FROM admin_users
            WHERE id = $1
            "#
        )
        .bind(user_id)
        .fetch_optional(&self.db)
        .await
        .map_err(|e| format!("Database error: {}", e))?;

        Ok(row.map(|row| {
            DatabaseUser {
                id: row.try_get("id").unwrap_or_default(),
                username: row.try_get("username").unwrap_or_default(),
                password_hash: row.try_get("password_hash").unwrap_or_default(),
                role: parse_role(&row.try_get::<String, _>("role").unwrap_or_default()).unwrap_or(UserRole::Viewer),
                email: row.try_get("email").ok(),
                created_at: row.try_get::<chrono::NaiveDateTime, _>("created_at")
                    .unwrap_or_default()
                    .and_utc(),
                updated_at: row.try_get::<chrono::NaiveDateTime, _>("updated_at")
                    .unwrap_or_default()
                    .and_utc(),
                last_login_at: row.try_get::<chrono::NaiveDateTime, _>("last_login_at")
                    .ok()
                    .map(|dt| dt.and_utc()),
                failed_login_attempts: row.try_get("failed_login_attempts").unwrap_or(0),
                locked_until: row.try_get::<chrono::NaiveDateTime, _>("locked_until")
                    .ok()
                    .map(|dt| dt.and_utc()),
            }
        }))
    }

    /// Create a new user in the database
    #[cfg(feature = "database-auth")]
    pub async fn create_user(
        &self,
        username: String,
        password: String,
        role: UserRole,
        email: Option<String>,
    ) -> Result<DatabaseUser, String> {
        // Validate password against policy
        self.password_policy.validate(&password, Some(&username))
            .map_err(|e| e.to_string())?;

        // Check if user already exists
        let count: i64 = sqlx::query_scalar(
            r#"SELECT COUNT(*) FROM admin_users WHERE username = $1"#
        )
        .bind(&username)
        .fetch_one(&self.db)
        .await
        .map_err(|e| format!("Database error: {}", e))?;

        if count > 0 {
            return Err("Username already exists".to_string());
        }

        // Hash password
        let password_hash = hash(&password, DEFAULT_COST)
            .map_err(|e| format!("Failed to hash password: {}", e))?;

        // Create user
        let user_id = Uuid::new_v4().to_string();
        let now = Utc::now();
        let role_str = format!("{:?}", role).to_lowercase();
        let now_naive = now.naive_utc();

        sqlx::query(
            r#"
            INSERT INTO admin_users (id, username, password_hash, role, email, created_at, updated_at)
            VALUES ($1, $2, $3, $4, $5, $6, $7)
            "#
        )
        .bind(&user_id)
        .bind(&username)
        .bind(&password_hash)
        .bind(&role_str)
        .bind(&email)
        .bind(now_naive)
        .bind(now_naive)
        .execute(&self.db)
        .await
        .map_err(|e| format!("Failed to create user: {}", e))?;

        Ok(DatabaseUser {
            id: user_id,
            username,
            password_hash,
            role,
            email,
            created_at: now,
            updated_at: now,
            last_login_at: None,
            failed_login_attempts: 0,
            locked_until: None,
        })
    }

    /// Store a refresh token in the database
    #[cfg(feature = "database-auth")]
    pub async fn store_refresh_token(
        &self,
        user_id: &str,
        token_hash: &str,
        expires_at: DateTime<Utc>,
    ) -> Result<(), String> {
        let token_id = Uuid::new_v4().to_string();
        sqlx::query(
            r#"
            INSERT INTO refresh_tokens (id, user_id, token_hash, expires_at, created_at)
            VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP)
            "#
        )
        .bind(&token_id)
        .bind(user_id)
        .bind(token_hash)
        .bind(expires_at.naive_utc())
        .execute(&self.db)
        .await
        .map_err(|e| format!("Failed to store refresh token: {}", e))?;

        Ok(())
    }

    /// Validate and revoke a refresh token
    #[cfg(feature = "database-auth")]
    pub async fn validate_refresh_token(&self, token_hash: &str) -> Result<String, String> {
        let row = sqlx::query(
            r#"
            SELECT user_id, expires_at, revoked_at
            FROM refresh_tokens
            WHERE token_hash = $1 AND revoked_at IS NULL
            "#
        )
        .bind(token_hash)
        .fetch_optional(&self.db)
        .await
        .map_err(|e| format!("Database error: {}", e))?;

        let row = row.ok_or_else(|| "Invalid refresh token".to_string())?;

        // Check if token is expired
        let expires_at: DateTime<Utc> = row.try_get::<chrono::NaiveDateTime, _>("expires_at")
            .map_err(|_| "Invalid token expiration date".to_string())?
            .and_utc();

        if expires_at < Utc::now() {
            return Err("Refresh token has expired".to_string());
        }

        let user_id: String = row.try_get("user_id")
            .map_err(|_| "Invalid user_id".to_string())?;

        Ok(user_id)
    }

    /// Revoke a refresh token
    #[cfg(feature = "database-auth")]
    pub async fn revoke_refresh_token(&self, token_hash: &str) -> Result<(), String> {
        sqlx::query(
            r#"
            UPDATE refresh_tokens
            SET revoked_at = CURRENT_TIMESTAMP
            WHERE token_hash = $1 AND revoked_at IS NULL
            "#
        )
        .bind(token_hash)
        .execute(&self.db)
        .await
        .map_err(|e| format!("Failed to revoke refresh token: {}", e))?;

        Ok(())
    }

    /// Revoke all refresh tokens for a user
    #[cfg(feature = "database-auth")]
    pub async fn revoke_all_refresh_tokens(&self, user_id: &str) -> Result<(), String> {
        sqlx::query(
            r#"
            UPDATE refresh_tokens
            SET revoked_at = CURRENT_TIMESTAMP
            WHERE user_id = $1 AND revoked_at IS NULL
            "#
        )
        .bind(user_id)
        .execute(&self.db)
        .await
        .map_err(|e| format!("Failed to revoke refresh tokens: {}", e))?;

        Ok(())
    }
}

/// Database row representation
#[derive(Debug)]
struct DatabaseUserRow {
    id: String,
    username: String,
    password_hash: String,
    role: String,
    email: Option<String>,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
    last_login_at: Option<DateTime<Utc>>,
    failed_login_attempts: i32,
    locked_until: Option<DateTime<Utc>>,
}

/// Parse role string to UserRole enum
fn parse_role(role_str: &str) -> Result<UserRole, String> {
    match role_str.to_lowercase().as_str() {
        "admin" => Ok(UserRole::Admin),
        "editor" => Ok(UserRole::Editor),
        "viewer" => Ok(UserRole::Viewer),
        _ => Err(format!("Invalid role: {}", role_str)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_role_valid() {
        assert!(matches!(parse_role("admin"), Ok(UserRole::Admin)));
        assert!(matches!(parse_role("Admin"), Ok(UserRole::Admin)));
        assert!(matches!(parse_role("ADMIN"), Ok(UserRole::Admin)));
        assert!(matches!(parse_role("editor"), Ok(UserRole::Editor)));
        assert!(matches!(parse_role("Editor"), Ok(UserRole::Editor)));
        assert!(matches!(parse_role("viewer"), Ok(UserRole::Viewer)));
        assert!(matches!(parse_role("Viewer"), Ok(UserRole::Viewer)));
    }

    #[test]
    fn test_parse_role_invalid() {
        assert!(parse_role("invalid").is_err());
        assert!(parse_role("").is_err());
        assert!(parse_role("super_admin").is_err());
        assert!(parse_role("moderator").is_err());

        let err = parse_role("invalid").unwrap_err();
        assert!(err.contains("Invalid role"));
    }

    #[test]
    fn test_rate_limiter_creation() {
        let limiter = RateLimiter::new(5, 60);
        // Just verify it can be created
        assert_eq!(limiter.max_attempts, 5);
        assert_eq!(limiter.window_seconds, 60);
    }

    #[tokio::test]
    async fn test_rate_limiter_check_success() {
        let limiter = RateLimiter::new(5, 60);
        let result = limiter.check_rate_limit("test_user").await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_rate_limiter_exceeds_limit() {
        let limiter = RateLimiter::new(3, 60);

        // First 3 attempts should succeed
        for _ in 0..3 {
            assert!(limiter.check_rate_limit("test_user").await.is_ok());
        }

        // 4th attempt should fail
        let result = limiter.check_rate_limit("test_user").await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("Too many"));
    }

    #[tokio::test]
    async fn test_rate_limiter_reset() {
        let limiter = RateLimiter::new(2, 60);

        // Use up the limit
        limiter.check_rate_limit("test_user").await.ok();
        limiter.check_rate_limit("test_user").await.ok();

        // Should fail now
        assert!(limiter.check_rate_limit("test_user").await.is_err());

        // Reset
        limiter.reset_rate_limit("test_user").await;

        // Should work again
        assert!(limiter.check_rate_limit("test_user").await.is_ok());
    }

    #[tokio::test]
    async fn test_rate_limiter_different_users() {
        let limiter = RateLimiter::new(2, 60);

        // Use up limit for user1
        limiter.check_rate_limit("user1").await.ok();
        limiter.check_rate_limit("user1").await.ok();

        // user1 should be limited
        assert!(limiter.check_rate_limit("user1").await.is_err());

        // user2 should still work
        assert!(limiter.check_rate_limit("user2").await.is_ok());
    }

    #[test]
    fn test_account_lockout_creation() {
        let lockout = AccountLockout::new(5, 900);
        assert_eq!(lockout.max_attempts, 5);
        assert_eq!(lockout.lockout_duration_seconds, 900);
    }

    #[test]
    fn test_database_user_creation() {
        let user = DatabaseUser {
            id: "test-id".to_string(),
            username: "testuser".to_string(),
            password_hash: "hash".to_string(),
            role: UserRole::Editor,
            email: Some("test@example.com".to_string()),
            created_at: Utc::now(),
            updated_at: Utc::now(),
            last_login_at: None,
            failed_login_attempts: 0,
            locked_until: None,
        };

        assert_eq!(user.id, "test-id");
        assert_eq!(user.username, "testuser");
        assert_eq!(user.failed_login_attempts, 0);
        assert!(user.locked_until.is_none());
    }

    #[test]
    fn test_database_user_with_lockout() {
        let now = Utc::now();
        let locked_until = now + chrono::Duration::seconds(900);

        let user = DatabaseUser {
            id: "test-id".to_string(),
            username: "testuser".to_string(),
            password_hash: "hash".to_string(),
            role: UserRole::Viewer,
            email: None,
            created_at: now,
            updated_at: now,
            last_login_at: Some(now),
            failed_login_attempts: 5,
            locked_until: Some(locked_until),
        };

        assert_eq!(user.failed_login_attempts, 5);
        assert!(user.locked_until.is_some());
        assert!(user.locked_until.unwrap() > now);
    }

    #[test]
    fn test_database_user_clone() {
        let user = DatabaseUser {
            id: "test-id".to_string(),
            username: "testuser".to_string(),
            password_hash: "hash".to_string(),
            role: UserRole::Admin,
            email: Some("test@example.com".to_string()),
            created_at: Utc::now(),
            updated_at: Utc::now(),
            last_login_at: None,
            failed_login_attempts: 0,
            locked_until: None,
        };

        let cloned = user.clone();
        assert_eq!(cloned.id, user.id);
        assert_eq!(cloned.username, user.username);
        assert_eq!(cloned.role, user.role);
    }

    // Note: Full database integration tests would require database-auth feature
    // and an actual database connection. These tests focus on the non-database
    // logic that can be tested without a database.

    #[test]
    fn test_all_user_roles_supported() {
        let roles = vec!["admin", "editor", "viewer"];
        for role in roles {
            assert!(parse_role(role).is_ok());
        }
    }

    #[tokio::test]
    async fn test_rate_limiter_concurrent_access() {
        let limiter = Arc::new(RateLimiter::new(10, 60));
        let mut handles = vec![];

        // Spawn multiple tasks accessing rate limiter concurrently
        for i in 0..5 {
            let limiter_clone = limiter.clone();
            let handle = tokio::spawn(async move {
                limiter_clone.check_rate_limit(&format!("user{}", i)).await
            });
            handles.push(handle);
        }

        // All should succeed (different users)
        for handle in handles {
            let result = handle.await.unwrap();
            assert!(result.is_ok());
        }
    }

    #[test]
    fn test_rate_limiter_clone() {
        let limiter1 = RateLimiter::new(5, 60);
        let limiter2 = limiter1.clone();

        assert_eq!(limiter1.max_attempts, limiter2.max_attempts);
        assert_eq!(limiter1.window_seconds, limiter2.window_seconds);
    }

    #[test]
    fn test_account_lockout_clone() {
        let lockout1 = AccountLockout::new(5, 900);
        let lockout2 = lockout1.clone();

        assert_eq!(lockout1.max_attempts, lockout2.max_attempts);
        assert_eq!(lockout1.lockout_duration_seconds, lockout2.lockout_duration_seconds);
    }

    #[test]
    fn test_database_user_debug() {
        let user = DatabaseUser {
            id: "test-id".to_string(),
            username: "testuser".to_string(),
            password_hash: "hash".to_string(),
            role: UserRole::Viewer,
            email: None,
            created_at: Utc::now(),
            updated_at: Utc::now(),
            last_login_at: None,
            failed_login_attempts: 0,
            locked_until: None,
        };

        let debug_str = format!("{:?}", user);
        assert!(debug_str.contains("test-id"));
        assert!(debug_str.contains("testuser"));
    }
}