Skip to main content

auth_framework/testing/
utilities.rs

1/// Mock authentication method for testing.
2///
3/// # Example
4/// ```rust,ignore
5/// let mock = MockAuthMethod::new_success();
6/// assert!(mock.should_succeed);
7/// ```
8#[derive(Debug, Clone)]
9pub struct MockAuthMethod {
10    /// Whether authentication should succeed
11    pub should_succeed: bool,
12    /// Simulated user profiles to return
13    pub user_profiles: HashMap<String, ProviderProfile>,
14    /// Simulated delay for authentication
15    pub delay: Option<Duration>,
16}
17
18impl MockAuthMethod {
19    /// Create a new mock authentication method that always succeeds.
20    ///
21    /// # Example
22    /// ```rust,ignore
23    /// let mock = MockAuthMethod::new_success();
24    /// assert!(mock.should_succeed);
25    /// ```
26    pub fn new_success() -> Self {
27        MockAuthMethod {
28            should_succeed: true,
29            user_profiles: HashMap::new(),
30            delay: None,
31        }
32    }
33
34    /// Add a user profile for a specific user ID.
35    ///
36    /// # Example
37    /// ```rust,ignore
38    /// let mock = MockAuthMethod::new_success()
39    ///     .with_user("user-1", ProviderProfile::new().with_id("user-1"));
40    /// ```
41    pub fn with_user(mut self, user_id: impl Into<String>, profile: ProviderProfile) -> Self {
42        self.user_profiles.insert(user_id.into(), profile);
43        self
44    }
45
46    /// Set a delay for authentication (useful for testing timeouts).
47    ///
48    /// # Example
49    /// ```rust,ignore
50    /// let mock = MockAuthMethod::new_success()
51    ///     .with_delay(Duration::from_millis(100));
52    /// ```
53    pub fn with_delay(mut self, delay: Duration) -> Self {
54        self.delay = Some(delay);
55        self
56    }
57}
58use crate::authentication::credentials::{Credential, CredentialMetadata};
59use crate::errors::{AuthError, Result};
60use crate::methods::{AuthMethod, MethodResult};
61use crate::providers::ProviderProfile;
62use crate::storage::AuthStorage;
63use crate::storage::core::SessionData;
64use crate::tokens::AuthToken;
65use dashmap::DashMap;
66use std::collections::HashMap;
67use std::sync::Arc;
68use std::time::Duration;
69use uuid::Uuid;
70// Ensure all top-level impls are closed before the test module
71#[cfg(test)]
72// use crate::security::SecurityConfig;
73#[tokio::test]
74async fn test_mock_storage() {
75    use crate::testing::test_infrastructure::TestEnvironmentGuard;
76    let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
77
78    let storage = MockStorage::new();
79    let token = helpers::create_test_token("testuser");
80    storage.store_token(&token).await.unwrap();
81    let retrieved = storage.get_token(&token.token_id).await.unwrap();
82    assert!(retrieved.is_some());
83    assert_eq!(retrieved.unwrap().token_id, token.token_id);
84}
85
86#[tokio::test]
87async fn test_failing_mock_storage() {
88    use crate::testing::test_infrastructure::TestEnvironmentGuard;
89    let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
90
91    let storage = MockStorage::new_failing();
92    let token = helpers::create_test_token("testuser");
93    let result = storage.store_token(&token).await;
94    assert!(result.is_err());
95}
96
97#[test]
98fn test_secret_loading_from_env() {
99    use crate::auth::AuthFramework;
100    use crate::config::AuthConfig;
101    use crate::testing::test_infrastructure::TestEnvironmentGuard;
102
103    let _env = TestEnvironmentGuard::new().with_jwt_secret("env_secret_value");
104
105    let config = AuthConfig::default().secret("config_secret_value");
106    let framework = AuthFramework::new(config.clone());
107    let token = framework
108        .token_manager()
109        .create_jwt_token("user", vec!["read".to_string()], None);
110    assert!(token.is_ok());
111}
112
113#[test]
114fn test_secret_loading_from_config() {
115    use crate::auth::AuthFramework;
116    use crate::config::AuthConfig;
117    use crate::testing::test_infrastructure::TestEnvironmentGuard;
118
119    // Ensure JWT_SECRET is not set in environment for this test
120    let _env = TestEnvironmentGuard::new();
121
122    let config = AuthConfig::default().secret("config_secret_value");
123    let framework = AuthFramework::new(config.clone());
124    let token = framework
125        .token_manager()
126        .create_jwt_token("user", vec!["read".to_string()], None);
127    assert!(token.is_ok());
128}
129
130#[test]
131fn test_secret_missing_returns_error() {
132    use crate::auth::AuthFramework;
133    use crate::config::AuthConfig;
134    use crate::testing::test_infrastructure::TestEnvironmentGuard;
135
136    // Guard clears JWT_SECRET and sets RUST_TEST=1 for proper isolation.
137    // force_production_mode() on the config drives production validation without
138    // touching the global ENVIRONMENT variable, eliminating the parallel-test race.
139    let _env = TestEnvironmentGuard::new();
140
141    let config = AuthConfig::default().force_production_mode();
142    match AuthFramework::new_validated(config) {
143        Err(e) => {
144            // Should fail with proper error message about JWT secret
145            assert!(
146                e.to_string().contains("JWT secret"),
147                "Expected JWT secret error, got: {e}"
148            );
149        }
150        Ok(_) => panic!("Expected error when JWT_SECRET is missing in production"),
151    }
152}
153
154impl AuthMethod for MockAuthMethod {
155    type MethodResult = MethodResult;
156    type AuthToken = AuthToken;
157
158    fn name(&self) -> &str {
159        "mock"
160    }
161
162    fn validate_config(&self) -> Result<()> {
163        Ok(())
164    }
165
166    async fn authenticate(
167        &self,
168        credential: Credential,
169        _metadata: CredentialMetadata,
170    ) -> Result<Self::MethodResult> {
171        // Simulate delay if configured
172        if let Some(delay) = self.delay {
173            tokio::time::sleep(delay).await;
174        }
175
176        if !self.should_succeed {
177            return Ok(MethodResult::Failure {
178                reason: "Mock authentication failed".to_string(),
179            });
180        }
181
182        // Extract user ID based on credential type
183        let user_id = match credential {
184            Credential::Password { username, .. } => username.clone(),
185            Credential::ApiKey { key } => format!("api_user_{}", &key[..8.min(key.len())]),
186            Credential::OAuth { .. } => "oauth_user".to_string(),
187            Credential::DeviceCode { .. } => "device_user".to_string(),
188            _ => "test_user".to_string(),
189        };
190
191        // Create a mock token
192        let token = AuthToken {
193            token_id: Uuid::new_v4().to_string(),
194            user_id: user_id.clone(),
195            access_token: format!("mock_token_{}", Uuid::new_v4()),
196            refresh_token: Some(format!("refresh_{}", Uuid::new_v4())),
197            token_type: Some("Bearer".to_string()),
198            expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
199            scopes: vec!["read".to_string(), "write".to_string()].into(),
200            issued_at: chrono::Utc::now(),
201            auth_method: "mock".to_string(),
202            subject: Some(user_id.clone()),
203            issuer: Some("mock".to_string()),
204            user_profile: None,
205            client_id: Some("test_client".to_string()),
206            permissions: vec!["read:all".to_string(), "write:all".to_string()].into(),
207            roles: vec!["mock_user".to_string()].into(),
208            metadata: crate::tokens::TokenMetadata::default(),
209        };
210
211        Ok(MethodResult::Success(Box::new(token)))
212    }
213
214    async fn refresh_token(&self, _refresh_token: String) -> Result<Self::AuthToken> {
215        if !self.should_succeed {
216            return Err(AuthError::auth_method("mock", "Refresh failed"));
217        }
218
219        Ok(AuthToken {
220            token_id: Uuid::new_v4().to_string(),
221            user_id: "refreshed_user".to_string(),
222            access_token: "mock_refreshed_token".to_string(),
223            refresh_token: Some("mock_new_refresh_token".to_string()),
224            token_type: Some("Bearer".to_string()),
225            expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
226            scopes: vec!["read".to_string(), "write".to_string()].into(),
227            issued_at: chrono::Utc::now(),
228            auth_method: "mock".to_string(),
229            client_id: Some("test_client".to_string()),
230            metadata: crate::tokens::TokenMetadata::default(),
231            subject: Some("refreshed_user".to_string()),
232            issuer: Some("mock".to_string()),
233            user_profile: None,
234            permissions: vec!["read:all".to_string(), "write:all".to_string()].into(),
235            roles: vec!["refreshed_user".to_string()].into(),
236        })
237    }
238}
239
240/// Mock storage implementation for testing with DashMap for deadlock-free operations.
241///
242/// # Example
243/// ```rust,ignore
244/// let storage = MockStorage::new();
245/// storage.store_token(&token).await.unwrap();
246/// ```
247#[derive(Debug, Clone)]
248pub struct MockStorage {
249    tokens: Arc<DashMap<String, AuthToken>>,
250    sessions: Arc<DashMap<String, SessionData>>,
251    kv_store: Arc<DashMap<String, Vec<u8>>>,
252    should_fail: bool,
253}
254
255impl MockStorage {
256    /// Create a new mock storage with DashMap for deadlock-free operations.
257    ///
258    /// # Example
259    /// ```rust,ignore
260    /// let storage = MockStorage::new();
261    /// ```
262    pub fn new() -> Self {
263        Self {
264            tokens: Arc::new(DashMap::new()),
265            sessions: Arc::new(DashMap::new()),
266            kv_store: Arc::new(DashMap::new()),
267            should_fail: false,
268        }
269    }
270
271    /// Create a mock storage that fails operations.
272    ///
273    /// # Example
274    /// ```rust,ignore
275    /// let storage = MockStorage::new_failing();
276    /// assert!(storage.store_token(&token).await.is_err());
277    /// ```
278    pub fn new_failing() -> Self {
279        let mut storage = Self::new();
280        storage.should_fail = true;
281        storage
282    }
283
284    /// Preset a token in storage.
285    ///
286    /// # Example
287    /// ```rust,ignore
288    /// let storage = MockStorage::new();
289    /// storage.with_token(token).unwrap();
290    /// ```
291    pub fn with_token(&self, token: AuthToken) -> Result<()> {
292        if self.should_fail {
293            return Err(AuthError::internal("Mock storage configured to fail"));
294        }
295
296        // Use DashMap deadlock-free insertion
297        self.tokens.insert(token.access_token.clone(), token);
298        Ok(())
299    }
300
301    /// Clear all storage using DashMap atomic operations.
302    ///
303    /// # Example
304    /// ```rust,ignore
305    /// let storage = MockStorage::new();
306    /// storage.clear();
307    /// ```
308    pub fn clear(&self) {
309        self.tokens.clear();
310        self.sessions.clear();
311        self.kv_store.clear();
312    }
313}
314
315impl Default for MockStorage {
316    fn default() -> Self {
317        Self::new()
318    }
319}
320
321#[async_trait::async_trait]
322impl AuthStorage for MockStorage {
323    async fn store_token(&self, token: &AuthToken) -> Result<()> {
324        if self.should_fail {
325            return Err(AuthError::internal("Mock storage configured to fail"));
326        }
327
328        // Use DashMap deadlock-free insertion
329        self.tokens
330            .insert(token.access_token.clone(), token.clone());
331        Ok(())
332    }
333
334    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
335        if self.should_fail {
336            return Err(AuthError::internal("Mock storage configured to fail"));
337        }
338
339        // Use DashMap deadlock-free iteration with immediate value extraction
340        for entry in self.tokens.iter() {
341            if entry.value().token_id == token_id {
342                return Ok(Some(entry.value().clone()));
343            }
344        }
345        Ok(None)
346    }
347
348    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
349        if self.should_fail {
350            return Err(AuthError::internal("Mock storage configured to fail"));
351        }
352
353        // Use DashMap deadlock-free get with immediate value extraction
354        Ok(self
355            .tokens
356            .get(access_token)
357            .map(|entry| entry.value().clone()))
358    }
359
360    async fn update_token(&self, token: &AuthToken) -> Result<()> {
361        if self.should_fail {
362            return Err(AuthError::internal("Mock storage configured to fail"));
363        }
364
365        // Use DashMap deadlock-free update
366        self.tokens
367            .insert(token.access_token.clone(), token.clone());
368        Ok(())
369    }
370
371    async fn delete_token(&self, token_id: &str) -> Result<()> {
372        if self.should_fail {
373            return Err(AuthError::internal("Mock storage configured to fail"));
374        }
375
376        // Use DashMap deadlock-free removal with retain-like operation
377        self.tokens.retain(|_, token| token.token_id != token_id);
378        Ok(())
379    }
380
381    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
382        if self.should_fail {
383            return Err(AuthError::internal("Mock storage configured to fail"));
384        }
385
386        // Use DashMap with manual iteration to avoid API issues
387        let mut tokens = Vec::new();
388        for entry in self.tokens.iter() {
389            if entry.value().user_id == user_id {
390                tokens.push(entry.value().clone());
391            }
392        }
393        Ok(tokens)
394    }
395
396    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
397        if self.should_fail {
398            return Err(AuthError::internal("Mock storage configured to fail"));
399        }
400
401        // Use DashMap deadlock-free insertion
402        self.sessions.insert(session_id.to_string(), data.clone());
403        Ok(())
404    }
405
406    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
407        if self.should_fail {
408            return Err(AuthError::internal("Mock storage configured to fail"));
409        }
410
411        // Use DashMap deadlock-free get with immediate value extraction
412        Ok(self
413            .sessions
414            .get(session_id)
415            .map(|entry| entry.value().clone()))
416    }
417
418    async fn delete_session(&self, session_id: &str) -> Result<()> {
419        if self.should_fail {
420            return Err(AuthError::internal("Mock storage configured to fail"));
421        }
422
423        // Use DashMap deadlock-free removal
424        self.sessions.remove(session_id);
425        Ok(())
426    }
427
428    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
429        if self.should_fail {
430            return Err(AuthError::internal("Mock storage configured to fail"));
431        }
432
433        // Use DashMap with manual iteration to avoid API issues
434        let mut sessions = Vec::new();
435        for entry in self.sessions.iter() {
436            if entry.value().user_id == user_id && !entry.value().is_expired() {
437                sessions.push(entry.value().clone());
438            }
439        }
440        Ok(sessions)
441    }
442
443    async fn store_kv(&self, key: &str, value: &[u8], _ttl: Option<Duration>) -> Result<()> {
444        if self.should_fail {
445            return Err(AuthError::internal("Mock storage configured to fail"));
446        }
447
448        // Use DashMap deadlock-free insertion
449        self.kv_store.insert(key.to_string(), value.to_vec());
450        Ok(())
451    }
452
453    async fn store_kv_if_absent(
454        &self,
455        key: &str,
456        value: &[u8],
457        _ttl: Option<Duration>,
458    ) -> Result<bool> {
459        use dashmap::mapref::entry::Entry;
460
461        if self.should_fail {
462            return Err(AuthError::internal("Mock storage configured to fail"));
463        }
464
465        // `entry` holds the shard lock across the check and the insert: atomic.
466        match self.kv_store.entry(key.to_string()) {
467            Entry::Occupied(_) => Ok(false),
468            Entry::Vacant(slot) => {
469                slot.insert(value.to_vec());
470                Ok(true)
471            }
472        }
473    }
474
475    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
476        if self.should_fail {
477            return Err(AuthError::internal("Mock storage configured to fail"));
478        }
479
480        // Use DashMap deadlock-free get with immediate value extraction
481        Ok(self.kv_store.get(key).map(|entry| entry.value().clone()))
482    }
483
484    async fn delete_kv(&self, key: &str) -> Result<()> {
485        if self.should_fail {
486            return Err(AuthError::internal("Mock storage configured to fail"));
487        }
488
489        // Use DashMap deadlock-free removal
490        self.kv_store.remove(key);
491        Ok(())
492    }
493
494    async fn cleanup_expired(&self) -> Result<()> {
495        if self.should_fail {
496            return Err(AuthError::internal("Mock storage configured to fail"));
497        }
498
499        let now = chrono::Utc::now();
500
501        // Use DashMap deadlock-free retain operation
502        self.tokens.retain(|_, token| token.expires_at > now);
503
504        Ok(())
505    }
506
507    async fn count_active_sessions(&self) -> Result<u64> {
508        if self.should_fail {
509            return Err(AuthError::internal("Mock storage configured to fail"));
510        }
511
512        // Count non-expired sessions using DashMap with manual iteration
513        let mut count = 0u64;
514        for entry in self.sessions.iter() {
515            if !entry.value().is_expired() {
516                count += 1;
517            }
518        }
519        Ok(count)
520    }
521}
522
523/// Test helper functions
524pub mod helpers {
525    use super::*;
526    // use std::sync::Arc;  // Temporarily unused
527
528    /// Create a test user profile.
529    ///
530    /// # Example
531    /// ```rust,ignore
532    /// let profile = helpers::create_test_user_profile("user-1");
533    /// ```
534    pub fn create_test_user_profile(user_id: &str) -> ProviderProfile {
535        ProviderProfile::new()
536            .with_id(user_id)
537            .with_provider("test")
538            .with_name(Some(format!("Test User {}", user_id)))
539            .with_email(Some(format!("{}@test.com", user_id)))
540            .with_email_verified(true)
541    }
542
543    /// Create a test auth token.
544    ///
545    /// # Example
546    /// ```rust,ignore
547    /// let token = helpers::create_test_token("user-1");
548    /// assert_eq!(token.user_id, "user-1");
549    /// ```
550    pub fn create_test_token(user_id: &str) -> AuthToken {
551        let now = chrono::Utc::now();
552        AuthToken {
553            token_id: Uuid::new_v4().to_string(),
554            user_id: user_id.to_string(),
555            access_token: format!("test_token_{}", Uuid::new_v4()),
556            refresh_token: Some(format!("refresh_token_{}", Uuid::new_v4())),
557            token_type: Some("Bearer".to_string()),
558            expires_at: now + chrono::Duration::seconds(3600),
559            scopes: vec!["read".to_string(), "write".to_string()].into(),
560            issued_at: now,
561            auth_method: "test".to_string(),
562            client_id: Some("test_client".to_string()),
563            metadata: crate::tokens::TokenMetadata::default(),
564            subject: Some(user_id.to_string()),
565            issuer: Some("test".to_string()),
566            user_profile: None,
567            permissions: vec!["read:all".to_string(), "write:all".to_string()].into(),
568            roles: vec!["test_user".to_string()].into(),
569        }
570    }
571
572    /// Create test credentials.
573    ///
574    /// # Example
575    /// ```rust,ignore
576    /// let creds = helpers::create_test_credentials();
577    /// assert_eq!(creds.len(), 5);
578    /// ```
579    pub fn create_test_credentials() -> Vec<Credential> {
580        vec![
581            Credential::password("testuser", "testpass"),
582            Credential::api_key("test_api_key"),
583            Credential::oauth_code("test_auth_code"),
584            Credential::device_code("test_device_code", "test_client_id"),
585            Credential::jwt("test.jwt.token"),
586        ]
587    }
588}
589
590// ── Edge-case tests ──────────────────────────────────────────────────────
591
592#[cfg(test)]
593mod edge_tests {
594    use super::*;
595    use crate::testing::test_infrastructure::TestEnvironmentGuard;
596
597    // --- MockAuthMethod authenticate edge cases ---
598
599    #[tokio::test]
600    async fn test_mock_auth_failure_mode() {
601        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
602        let mock = MockAuthMethod {
603            should_succeed: false,
604            user_profiles: HashMap::new(),
605            delay: None,
606        };
607        let cred = Credential::password("user", "pass");
608        let meta = CredentialMetadata::default();
609        let result = mock.authenticate(cred, meta).await.unwrap();
610        match result {
611            MethodResult::Failure { reason } => {
612                assert!(reason.contains("failed"), "Expected failure: {reason}");
613            }
614            _ => panic!("Expected Failure variant"),
615        }
616    }
617
618    #[tokio::test]
619    async fn test_mock_auth_api_key_empty() {
620        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
621        let mock = MockAuthMethod::new_success();
622        let cred = Credential::api_key("");
623        let meta = CredentialMetadata::default();
624        // Should not panic with empty API key — &key[..0] is valid
625        let result = mock.authenticate(cred, meta).await.unwrap();
626        match result {
627            MethodResult::Success(token) => {
628                assert!(token.user_id.starts_with("api_user_"));
629            }
630            _ => panic!("Expected success"),
631        }
632    }
633
634    #[tokio::test]
635    async fn test_mock_auth_api_key_short() {
636        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
637        let mock = MockAuthMethod::new_success();
638        let cred = Credential::api_key("abc");
639        let meta = CredentialMetadata::default();
640        let result = mock.authenticate(cred, meta).await.unwrap();
641        match result {
642            MethodResult::Success(token) => {
643                assert_eq!(token.user_id, "api_user_abc");
644            }
645            _ => panic!("Expected success"),
646        }
647    }
648
649    #[tokio::test]
650    async fn test_mock_auth_catch_all_credential() {
651        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
652        let mock = MockAuthMethod::new_success();
653        let cred = Credential::jwt("some.jwt.token");
654        let meta = CredentialMetadata::default();
655        let result = mock.authenticate(cred, meta).await.unwrap();
656        match result {
657            MethodResult::Success(token) => {
658                assert_eq!(token.user_id, "test_user");
659            }
660            _ => panic!("Expected success"),
661        }
662    }
663
664    // --- MockAuthMethod refresh edge cases ---
665
666    #[tokio::test]
667    async fn test_mock_refresh_success() {
668        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
669        let mock = MockAuthMethod::new_success();
670        let token = mock.refresh_token("old_refresh".to_string()).await.unwrap();
671        assert_eq!(token.user_id, "refreshed_user");
672        assert!(token.refresh_token.is_some());
673    }
674
675    #[tokio::test]
676    async fn test_mock_refresh_failure() {
677        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
678        let mock = MockAuthMethod {
679            should_succeed: false,
680            user_profiles: HashMap::new(),
681            delay: None,
682        };
683        let result = mock.refresh_token("old_refresh".to_string()).await;
684        assert!(result.is_err());
685    }
686
687    // --- MockStorage token operations ---
688
689    #[tokio::test]
690    async fn test_storage_get_token_by_access_token() {
691        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
692        let storage = MockStorage::new();
693        let token = helpers::create_test_token("user1");
694        let access = token.access_token.clone();
695        storage.store_token(&token).await.unwrap();
696        let found = storage.get_token_by_access_token(&access).await.unwrap();
697        assert!(found.is_some());
698        assert_eq!(found.unwrap().user_id, "user1");
699    }
700
701    #[tokio::test]
702    async fn test_storage_get_token_by_access_token_not_found() {
703        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
704        let storage = MockStorage::new();
705        let found = storage
706            .get_token_by_access_token("nonexistent")
707            .await
708            .unwrap();
709        assert!(found.is_none());
710    }
711
712    #[tokio::test]
713    async fn test_storage_update_token() {
714        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
715        let storage = MockStorage::new();
716        let mut token = helpers::create_test_token("user1");
717        storage.store_token(&token).await.unwrap();
718        token.user_id = "updated_user".to_string();
719        storage.update_token(&token).await.unwrap();
720        let found = storage
721            .get_token_by_access_token(&token.access_token)
722            .await
723            .unwrap()
724            .unwrap();
725        assert_eq!(found.user_id, "updated_user");
726    }
727
728    #[tokio::test]
729    async fn test_storage_delete_token() {
730        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
731        let storage = MockStorage::new();
732        let token = helpers::create_test_token("user1");
733        let tid = token.token_id.clone();
734        storage.store_token(&token).await.unwrap();
735        storage.delete_token(&tid).await.unwrap();
736        let found = storage.get_token(&tid).await.unwrap();
737        assert!(found.is_none());
738    }
739
740    #[tokio::test]
741    async fn test_storage_list_user_tokens_filters_by_user() {
742        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
743        let storage = MockStorage::new();
744        let t1 = helpers::create_test_token("alice");
745        let t2 = helpers::create_test_token("alice");
746        let t3 = helpers::create_test_token("bob");
747        storage.store_token(&t1).await.unwrap();
748        storage.store_token(&t2).await.unwrap();
749        storage.store_token(&t3).await.unwrap();
750        let alice_tokens = storage.list_user_tokens("alice").await.unwrap();
751        assert_eq!(alice_tokens.len(), 2);
752        let bob_tokens = storage.list_user_tokens("bob").await.unwrap();
753        assert_eq!(bob_tokens.len(), 1);
754    }
755
756    // --- MockStorage session operations ---
757
758    #[tokio::test]
759    async fn test_storage_session_crud() {
760        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
761        let storage = MockStorage::new();
762        let session = SessionData {
763            session_id: "sess1".to_string(),
764            user_id: "user1".to_string(),
765            created_at: chrono::Utc::now(),
766            expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
767            last_activity: chrono::Utc::now(),
768            ip_address: Some("127.0.0.1".to_string()),
769            user_agent: None,
770            data: Default::default(),
771        };
772        storage.store_session("sess1", &session).await.unwrap();
773        let found = storage.get_session("sess1").await.unwrap();
774        assert!(found.is_some());
775        assert_eq!(found.unwrap().user_id, "user1");
776
777        storage.delete_session("sess1").await.unwrap();
778        let gone = storage.get_session("sess1").await.unwrap();
779        assert!(gone.is_none());
780    }
781
782    #[tokio::test]
783    async fn test_storage_list_user_sessions_filters_expired() {
784        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
785        let storage = MockStorage::new();
786        let active = SessionData {
787            session_id: "active".to_string(),
788            user_id: "user1".to_string(),
789            created_at: chrono::Utc::now(),
790            expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
791            last_activity: chrono::Utc::now(),
792            ip_address: None,
793            user_agent: None,
794            data: Default::default(),
795        };
796        let expired = SessionData {
797            session_id: "expired".to_string(),
798            user_id: "user1".to_string(),
799            created_at: chrono::Utc::now() - chrono::Duration::seconds(7200),
800            expires_at: chrono::Utc::now() - chrono::Duration::seconds(3600),
801            last_activity: chrono::Utc::now() - chrono::Duration::seconds(7200),
802            ip_address: None,
803            user_agent: None,
804            data: Default::default(),
805        };
806        storage.store_session("active", &active).await.unwrap();
807        storage.store_session("expired", &expired).await.unwrap();
808        let sessions = storage.list_user_sessions("user1").await.unwrap();
809        assert_eq!(sessions.len(), 1);
810        assert_eq!(sessions[0].session_id, "active");
811    }
812
813    // --- MockStorage KV operations ---
814
815    #[tokio::test]
816    async fn test_storage_kv_crud() {
817        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
818        let storage = MockStorage::new();
819        storage.store_kv("key1", b"value1", None).await.unwrap();
820        let val = storage.get_kv("key1").await.unwrap();
821        assert_eq!(val.unwrap(), b"value1");
822
823        storage.delete_kv("key1").await.unwrap();
824        let gone = storage.get_kv("key1").await.unwrap();
825        assert!(gone.is_none());
826    }
827
828    #[tokio::test]
829    async fn test_storage_kv_not_found() {
830        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
831        let storage = MockStorage::new();
832        let val = storage.get_kv("nonexistent").await.unwrap();
833        assert!(val.is_none());
834    }
835
836    // --- MockStorage cleanup ---
837
838    #[tokio::test]
839    async fn test_storage_cleanup_expired_tokens() {
840        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
841        let storage = MockStorage::new();
842        let mut expired_token = helpers::create_test_token("user1");
843        expired_token.expires_at = chrono::Utc::now() - chrono::Duration::seconds(10);
844        let valid_token = helpers::create_test_token("user2");
845        storage.store_token(&expired_token).await.unwrap();
846        storage.store_token(&valid_token).await.unwrap();
847        storage.cleanup_expired().await.unwrap();
848        // Expired token should be gone
849        let found_expired = storage
850            .get_token_by_access_token(&expired_token.access_token)
851            .await
852            .unwrap();
853        assert!(found_expired.is_none());
854        // Valid token should remain
855        let found_valid = storage
856            .get_token_by_access_token(&valid_token.access_token)
857            .await
858            .unwrap();
859        assert!(found_valid.is_some());
860    }
861
862    // --- helpers::create_test_credentials ---
863
864    #[test]
865    fn test_create_test_credentials_all_variants() {
866        let creds = helpers::create_test_credentials();
867        assert_eq!(creds.len(), 5);
868        assert!(matches!(&creds[0], Credential::Password { .. }));
869        assert!(matches!(&creds[1], Credential::ApiKey { .. }));
870        assert!(matches!(&creds[2], Credential::OAuth { .. }));
871        assert!(matches!(&creds[3], Credential::DeviceCode { .. }));
872        assert!(matches!(&creds[4], Credential::Jwt { .. }));
873    }
874
875    // --- MockStorage count_active_sessions ---
876
877    #[tokio::test]
878    async fn test_storage_count_active_sessions() {
879        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
880        let storage = MockStorage::new();
881        let active = SessionData {
882            session_id: "active1".to_string(),
883            user_id: "user1".to_string(),
884            created_at: chrono::Utc::now(),
885            expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
886            last_activity: chrono::Utc::now(),
887            ip_address: None,
888            user_agent: None,
889            data: Default::default(),
890        };
891        let expired = SessionData {
892            session_id: "expired1".to_string(),
893            user_id: "user2".to_string(),
894            created_at: chrono::Utc::now() - chrono::Duration::seconds(7200),
895            expires_at: chrono::Utc::now() - chrono::Duration::seconds(3600),
896            last_activity: chrono::Utc::now() - chrono::Duration::seconds(7200),
897            ip_address: None,
898            user_agent: None,
899            data: Default::default(),
900        };
901        storage.store_session("active1", &active).await.unwrap();
902        storage.store_session("expired1", &expired).await.unwrap();
903        let count = storage.count_active_sessions().await.unwrap();
904        assert_eq!(count, 1);
905    }
906}