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(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 std::fmt::Debug for MockStorage {
256    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257        let mut d = f.debug_struct("MockStorage");
258        d.field("tokens", &crate::utils::redact::redacted(&self.tokens));
259        d.field("sessions", &crate::utils::redact::redacted(&self.sessions));
260        d.field("kv_store", &crate::utils::redact::redacted(&self.kv_store));
261        d.field("should_fail", &self.should_fail);
262        d.finish()
263    }
264}
265
266impl MockStorage {
267    /// Create a new mock storage with DashMap for deadlock-free operations.
268    ///
269    /// # Example
270    /// ```rust,ignore
271    /// let storage = MockStorage::new();
272    /// ```
273    pub fn new() -> Self {
274        Self {
275            tokens: Arc::new(DashMap::new()),
276            sessions: Arc::new(DashMap::new()),
277            kv_store: Arc::new(DashMap::new()),
278            should_fail: false,
279        }
280    }
281
282    /// Create a mock storage that fails operations.
283    ///
284    /// # Example
285    /// ```rust,ignore
286    /// let storage = MockStorage::new_failing();
287    /// assert!(storage.store_token(&token).await.is_err());
288    /// ```
289    pub fn new_failing() -> Self {
290        let mut storage = Self::new();
291        storage.should_fail = true;
292        storage
293    }
294
295    /// Preset a token in storage.
296    ///
297    /// # Example
298    /// ```rust,ignore
299    /// let storage = MockStorage::new();
300    /// storage.with_token(token).unwrap();
301    /// ```
302    pub fn with_token(&self, token: AuthToken) -> Result<()> {
303        if self.should_fail {
304            return Err(AuthError::internal("Mock storage configured to fail"));
305        }
306
307        // Use DashMap deadlock-free insertion
308        self.tokens.insert(token.access_token.clone(), token);
309        Ok(())
310    }
311
312    /// Clear all storage using DashMap atomic operations.
313    ///
314    /// # Example
315    /// ```rust,ignore
316    /// let storage = MockStorage::new();
317    /// storage.clear();
318    /// ```
319    pub fn clear(&self) {
320        self.tokens.clear();
321        self.sessions.clear();
322        self.kv_store.clear();
323    }
324}
325
326impl Default for MockStorage {
327    fn default() -> Self {
328        Self::new()
329    }
330}
331
332#[async_trait::async_trait]
333impl AuthStorage for MockStorage {
334    async fn store_token(&self, token: &AuthToken) -> Result<()> {
335        if self.should_fail {
336            return Err(AuthError::internal("Mock storage configured to fail"));
337        }
338
339        // Use DashMap deadlock-free insertion
340        self.tokens
341            .insert(token.access_token.clone(), token.clone());
342        Ok(())
343    }
344
345    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
346        if self.should_fail {
347            return Err(AuthError::internal("Mock storage configured to fail"));
348        }
349
350        // Use DashMap deadlock-free iteration with immediate value extraction
351        for entry in self.tokens.iter() {
352            if entry.value().token_id == token_id {
353                return Ok(Some(entry.value().clone()));
354            }
355        }
356        Ok(None)
357    }
358
359    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
360        if self.should_fail {
361            return Err(AuthError::internal("Mock storage configured to fail"));
362        }
363
364        // Use DashMap deadlock-free get with immediate value extraction
365        Ok(self
366            .tokens
367            .get(access_token)
368            .map(|entry| entry.value().clone()))
369    }
370
371    async fn update_token(&self, token: &AuthToken) -> Result<()> {
372        if self.should_fail {
373            return Err(AuthError::internal("Mock storage configured to fail"));
374        }
375
376        // Use DashMap deadlock-free update
377        self.tokens
378            .insert(token.access_token.clone(), token.clone());
379        Ok(())
380    }
381
382    async fn delete_token(&self, token_id: &str) -> Result<()> {
383        if self.should_fail {
384            return Err(AuthError::internal("Mock storage configured to fail"));
385        }
386
387        // Use DashMap deadlock-free removal with retain-like operation
388        self.tokens.retain(|_, token| token.token_id != token_id);
389        Ok(())
390    }
391
392    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
393        if self.should_fail {
394            return Err(AuthError::internal("Mock storage configured to fail"));
395        }
396
397        // Use DashMap with manual iteration to avoid API issues
398        let mut tokens = Vec::new();
399        for entry in self.tokens.iter() {
400            if entry.value().user_id == user_id {
401                tokens.push(entry.value().clone());
402            }
403        }
404        Ok(tokens)
405    }
406
407    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
408        if self.should_fail {
409            return Err(AuthError::internal("Mock storage configured to fail"));
410        }
411
412        // Use DashMap deadlock-free insertion
413        self.sessions.insert(session_id.to_string(), data.clone());
414        Ok(())
415    }
416
417    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
418        if self.should_fail {
419            return Err(AuthError::internal("Mock storage configured to fail"));
420        }
421
422        // Use DashMap deadlock-free get with immediate value extraction
423        Ok(self
424            .sessions
425            .get(session_id)
426            .map(|entry| entry.value().clone()))
427    }
428
429    async fn delete_session(&self, session_id: &str) -> Result<()> {
430        if self.should_fail {
431            return Err(AuthError::internal("Mock storage configured to fail"));
432        }
433
434        // Use DashMap deadlock-free removal
435        self.sessions.remove(session_id);
436        Ok(())
437    }
438
439    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
440        if self.should_fail {
441            return Err(AuthError::internal("Mock storage configured to fail"));
442        }
443
444        // Use DashMap with manual iteration to avoid API issues
445        let mut sessions = Vec::new();
446        for entry in self.sessions.iter() {
447            if entry.value().user_id == user_id && !entry.value().is_expired() {
448                sessions.push(entry.value().clone());
449            }
450        }
451        Ok(sessions)
452    }
453
454    async fn store_kv(&self, key: &str, value: &[u8], _ttl: Option<Duration>) -> Result<()> {
455        if self.should_fail {
456            return Err(AuthError::internal("Mock storage configured to fail"));
457        }
458
459        // Use DashMap deadlock-free insertion
460        self.kv_store.insert(key.to_string(), value.to_vec());
461        Ok(())
462    }
463
464    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
465        if self.should_fail {
466            return Err(AuthError::internal("Mock storage configured to fail"));
467        }
468
469        // Use DashMap deadlock-free get with immediate value extraction
470        Ok(self.kv_store.get(key).map(|entry| entry.value().clone()))
471    }
472
473    async fn delete_kv(&self, key: &str) -> Result<()> {
474        if self.should_fail {
475            return Err(AuthError::internal("Mock storage configured to fail"));
476        }
477
478        // Use DashMap deadlock-free removal
479        self.kv_store.remove(key);
480        Ok(())
481    }
482
483    async fn cleanup_expired(&self) -> Result<()> {
484        if self.should_fail {
485            return Err(AuthError::internal("Mock storage configured to fail"));
486        }
487
488        let now = chrono::Utc::now();
489
490        // Use DashMap deadlock-free retain operation
491        self.tokens.retain(|_, token| token.expires_at > now);
492
493        Ok(())
494    }
495
496    async fn count_active_sessions(&self) -> Result<u64> {
497        if self.should_fail {
498            return Err(AuthError::internal("Mock storage configured to fail"));
499        }
500
501        // Count non-expired sessions using DashMap with manual iteration
502        let mut count = 0u64;
503        for entry in self.sessions.iter() {
504            if !entry.value().is_expired() {
505                count += 1;
506            }
507        }
508        Ok(count)
509    }
510}
511
512/// Test helper functions
513pub mod helpers {
514    use super::*;
515    // use std::sync::Arc;  // Temporarily unused
516
517    /// Create a test user profile.
518    ///
519    /// # Example
520    /// ```rust,ignore
521    /// let profile = helpers::create_test_user_profile("user-1");
522    /// ```
523    pub fn create_test_user_profile(user_id: &str) -> ProviderProfile {
524        ProviderProfile::new()
525            .with_id(user_id)
526            .with_provider("test")
527            .with_name(Some(format!("Test User {}", user_id)))
528            .with_email(Some(format!("{}@test.com", user_id)))
529            .with_email_verified(true)
530    }
531
532    /// Create a test auth token.
533    ///
534    /// # Example
535    /// ```rust,ignore
536    /// let token = helpers::create_test_token("user-1");
537    /// assert_eq!(token.user_id, "user-1");
538    /// ```
539    pub fn create_test_token(user_id: &str) -> AuthToken {
540        let now = chrono::Utc::now();
541        AuthToken {
542            token_id: Uuid::new_v4().to_string(),
543            user_id: user_id.to_string(),
544            access_token: format!("test_token_{}", Uuid::new_v4()),
545            refresh_token: Some(format!("refresh_token_{}", Uuid::new_v4())),
546            token_type: Some("Bearer".to_string()),
547            expires_at: now + chrono::Duration::seconds(3600),
548            scopes: vec!["read".to_string(), "write".to_string()].into(),
549            issued_at: now,
550            auth_method: "test".to_string(),
551            client_id: Some("test_client".to_string()),
552            metadata: crate::tokens::TokenMetadata::default(),
553            subject: Some(user_id.to_string()),
554            issuer: Some("test".to_string()),
555            user_profile: None,
556            permissions: vec!["read:all".to_string(), "write:all".to_string()].into(),
557            roles: vec!["test_user".to_string()].into(),
558        }
559    }
560
561    /// Create test credentials.
562    ///
563    /// # Example
564    /// ```rust,ignore
565    /// let creds = helpers::create_test_credentials();
566    /// assert_eq!(creds.len(), 5);
567    /// ```
568    pub fn create_test_credentials() -> Vec<Credential> {
569        vec![
570            Credential::password("testuser", "testpass"),
571            Credential::api_key("test_api_key"),
572            Credential::oauth_code("test_auth_code"),
573            Credential::device_code("test_device_code", "test_client_id"),
574            Credential::jwt("test.jwt.token"),
575        ]
576    }
577}
578
579// ── Edge-case tests ──────────────────────────────────────────────────────
580
581#[cfg(test)]
582mod edge_tests {
583    use super::*;
584    use crate::testing::test_infrastructure::TestEnvironmentGuard;
585
586    // --- MockAuthMethod authenticate edge cases ---
587
588    #[tokio::test]
589    async fn test_mock_auth_failure_mode() {
590        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
591        let mock = MockAuthMethod {
592            should_succeed: false,
593            user_profiles: HashMap::new(),
594            delay: None,
595        };
596        let cred = Credential::password("user", "pass");
597        let meta = CredentialMetadata::default();
598        let result = mock.authenticate(cred, meta).await.unwrap();
599        match result {
600            MethodResult::Failure { reason } => {
601                assert!(reason.contains("failed"), "Expected failure: {reason}");
602            }
603            _ => panic!("Expected Failure variant"),
604        }
605    }
606
607    #[tokio::test]
608    async fn test_mock_auth_api_key_empty() {
609        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
610        let mock = MockAuthMethod::new_success();
611        let cred = Credential::api_key("");
612        let meta = CredentialMetadata::default();
613        // Should not panic with empty API key — &key[..0] is valid
614        let result = mock.authenticate(cred, meta).await.unwrap();
615        match result {
616            MethodResult::Success(token) => {
617                assert!(token.user_id.starts_with("api_user_"));
618            }
619            _ => panic!("Expected success"),
620        }
621    }
622
623    #[tokio::test]
624    async fn test_mock_auth_api_key_short() {
625        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
626        let mock = MockAuthMethod::new_success();
627        let cred = Credential::api_key("abc");
628        let meta = CredentialMetadata::default();
629        let result = mock.authenticate(cred, meta).await.unwrap();
630        match result {
631            MethodResult::Success(token) => {
632                assert_eq!(token.user_id, "api_user_abc");
633            }
634            _ => panic!("Expected success"),
635        }
636    }
637
638    #[tokio::test]
639    async fn test_mock_auth_catch_all_credential() {
640        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
641        let mock = MockAuthMethod::new_success();
642        let cred = Credential::jwt("some.jwt.token");
643        let meta = CredentialMetadata::default();
644        let result = mock.authenticate(cred, meta).await.unwrap();
645        match result {
646            MethodResult::Success(token) => {
647                assert_eq!(token.user_id, "test_user");
648            }
649            _ => panic!("Expected success"),
650        }
651    }
652
653    // --- MockAuthMethod refresh edge cases ---
654
655    #[tokio::test]
656    async fn test_mock_refresh_success() {
657        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
658        let mock = MockAuthMethod::new_success();
659        let token = mock.refresh_token("old_refresh".to_string()).await.unwrap();
660        assert_eq!(token.user_id, "refreshed_user");
661        assert!(token.refresh_token.is_some());
662    }
663
664    #[tokio::test]
665    async fn test_mock_refresh_failure() {
666        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
667        let mock = MockAuthMethod {
668            should_succeed: false,
669            user_profiles: HashMap::new(),
670            delay: None,
671        };
672        let result = mock.refresh_token("old_refresh".to_string()).await;
673        assert!(result.is_err());
674    }
675
676    // --- MockStorage token operations ---
677
678    #[tokio::test]
679    async fn test_storage_get_token_by_access_token() {
680        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
681        let storage = MockStorage::new();
682        let token = helpers::create_test_token("user1");
683        let access = token.access_token.clone();
684        storage.store_token(&token).await.unwrap();
685        let found = storage.get_token_by_access_token(&access).await.unwrap();
686        assert!(found.is_some());
687        assert_eq!(found.unwrap().user_id, "user1");
688    }
689
690    #[tokio::test]
691    async fn test_storage_get_token_by_access_token_not_found() {
692        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
693        let storage = MockStorage::new();
694        let found = storage
695            .get_token_by_access_token("nonexistent")
696            .await
697            .unwrap();
698        assert!(found.is_none());
699    }
700
701    #[tokio::test]
702    async fn test_storage_update_token() {
703        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
704        let storage = MockStorage::new();
705        let mut token = helpers::create_test_token("user1");
706        storage.store_token(&token).await.unwrap();
707        token.user_id = "updated_user".to_string();
708        storage.update_token(&token).await.unwrap();
709        let found = storage
710            .get_token_by_access_token(&token.access_token)
711            .await
712            .unwrap()
713            .unwrap();
714        assert_eq!(found.user_id, "updated_user");
715    }
716
717    #[tokio::test]
718    async fn test_storage_delete_token() {
719        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
720        let storage = MockStorage::new();
721        let token = helpers::create_test_token("user1");
722        let tid = token.token_id.clone();
723        storage.store_token(&token).await.unwrap();
724        storage.delete_token(&tid).await.unwrap();
725        let found = storage.get_token(&tid).await.unwrap();
726        assert!(found.is_none());
727    }
728
729    #[tokio::test]
730    async fn test_storage_list_user_tokens_filters_by_user() {
731        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
732        let storage = MockStorage::new();
733        let t1 = helpers::create_test_token("alice");
734        let t2 = helpers::create_test_token("alice");
735        let t3 = helpers::create_test_token("bob");
736        storage.store_token(&t1).await.unwrap();
737        storage.store_token(&t2).await.unwrap();
738        storage.store_token(&t3).await.unwrap();
739        let alice_tokens = storage.list_user_tokens("alice").await.unwrap();
740        assert_eq!(alice_tokens.len(), 2);
741        let bob_tokens = storage.list_user_tokens("bob").await.unwrap();
742        assert_eq!(bob_tokens.len(), 1);
743    }
744
745    // --- MockStorage session operations ---
746
747    #[tokio::test]
748    async fn test_storage_session_crud() {
749        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
750        let storage = MockStorage::new();
751        let session = SessionData {
752            session_id: "sess1".to_string(),
753            user_id: "user1".to_string(),
754            created_at: chrono::Utc::now(),
755            expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
756            last_activity: chrono::Utc::now(),
757            ip_address: Some("127.0.0.1".to_string()),
758            user_agent: None,
759            data: Default::default(),
760        };
761        storage.store_session("sess1", &session).await.unwrap();
762        let found = storage.get_session("sess1").await.unwrap();
763        assert!(found.is_some());
764        assert_eq!(found.unwrap().user_id, "user1");
765
766        storage.delete_session("sess1").await.unwrap();
767        let gone = storage.get_session("sess1").await.unwrap();
768        assert!(gone.is_none());
769    }
770
771    #[tokio::test]
772    async fn test_storage_list_user_sessions_filters_expired() {
773        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
774        let storage = MockStorage::new();
775        let active = SessionData {
776            session_id: "active".to_string(),
777            user_id: "user1".to_string(),
778            created_at: chrono::Utc::now(),
779            expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
780            last_activity: chrono::Utc::now(),
781            ip_address: None,
782            user_agent: None,
783            data: Default::default(),
784        };
785        let expired = SessionData {
786            session_id: "expired".to_string(),
787            user_id: "user1".to_string(),
788            created_at: chrono::Utc::now() - chrono::Duration::seconds(7200),
789            expires_at: chrono::Utc::now() - chrono::Duration::seconds(3600),
790            last_activity: chrono::Utc::now() - chrono::Duration::seconds(7200),
791            ip_address: None,
792            user_agent: None,
793            data: Default::default(),
794        };
795        storage.store_session("active", &active).await.unwrap();
796        storage.store_session("expired", &expired).await.unwrap();
797        let sessions = storage.list_user_sessions("user1").await.unwrap();
798        assert_eq!(sessions.len(), 1);
799        assert_eq!(sessions[0].session_id, "active");
800    }
801
802    // --- MockStorage KV operations ---
803
804    #[tokio::test]
805    async fn test_storage_kv_crud() {
806        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
807        let storage = MockStorage::new();
808        storage.store_kv("key1", b"value1", None).await.unwrap();
809        let val = storage.get_kv("key1").await.unwrap();
810        assert_eq!(val.unwrap(), b"value1");
811
812        storage.delete_kv("key1").await.unwrap();
813        let gone = storage.get_kv("key1").await.unwrap();
814        assert!(gone.is_none());
815    }
816
817    #[tokio::test]
818    async fn test_storage_kv_not_found() {
819        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
820        let storage = MockStorage::new();
821        let val = storage.get_kv("nonexistent").await.unwrap();
822        assert!(val.is_none());
823    }
824
825    // --- MockStorage cleanup ---
826
827    #[tokio::test]
828    async fn test_storage_cleanup_expired_tokens() {
829        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
830        let storage = MockStorage::new();
831        let mut expired_token = helpers::create_test_token("user1");
832        expired_token.expires_at = chrono::Utc::now() - chrono::Duration::seconds(10);
833        let valid_token = helpers::create_test_token("user2");
834        storage.store_token(&expired_token).await.unwrap();
835        storage.store_token(&valid_token).await.unwrap();
836        storage.cleanup_expired().await.unwrap();
837        // Expired token should be gone
838        let found_expired = storage
839            .get_token_by_access_token(&expired_token.access_token)
840            .await
841            .unwrap();
842        assert!(found_expired.is_none());
843        // Valid token should remain
844        let found_valid = storage
845            .get_token_by_access_token(&valid_token.access_token)
846            .await
847            .unwrap();
848        assert!(found_valid.is_some());
849    }
850
851    // --- helpers::create_test_credentials ---
852
853    #[test]
854    fn test_create_test_credentials_all_variants() {
855        let creds = helpers::create_test_credentials();
856        assert_eq!(creds.len(), 5);
857        assert!(matches!(&creds[0], Credential::Password { .. }));
858        assert!(matches!(&creds[1], Credential::ApiKey { .. }));
859        assert!(matches!(&creds[2], Credential::OAuth { .. }));
860        assert!(matches!(&creds[3], Credential::DeviceCode { .. }));
861        assert!(matches!(&creds[4], Credential::Jwt { .. }));
862    }
863
864    // --- MockStorage count_active_sessions ---
865
866    #[tokio::test]
867    async fn test_storage_count_active_sessions() {
868        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
869        let storage = MockStorage::new();
870        let active = SessionData {
871            session_id: "active1".to_string(),
872            user_id: "user1".to_string(),
873            created_at: chrono::Utc::now(),
874            expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
875            last_activity: chrono::Utc::now(),
876            ip_address: None,
877            user_agent: None,
878            data: Default::default(),
879        };
880        let expired = SessionData {
881            session_id: "expired1".to_string(),
882            user_id: "user2".to_string(),
883            created_at: chrono::Utc::now() - chrono::Duration::seconds(7200),
884            expires_at: chrono::Utc::now() - chrono::Duration::seconds(3600),
885            last_activity: chrono::Utc::now() - chrono::Duration::seconds(7200),
886            ip_address: None,
887            user_agent: None,
888            data: Default::default(),
889        };
890        storage.store_session("active1", &active).await.unwrap();
891        storage.store_session("expired1", &expired).await.unwrap();
892        let count = storage.count_active_sessions().await.unwrap();
893        assert_eq!(count, 1);
894    }
895}