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 store_kv_if_absent(
465        &self,
466        key: &str,
467        value: &[u8],
468        _ttl: Option<Duration>,
469    ) -> Result<bool> {
470        use dashmap::mapref::entry::Entry;
471
472        if self.should_fail {
473            return Err(AuthError::internal("Mock storage configured to fail"));
474        }
475
476        // `entry` holds the shard lock across the check and the insert: atomic.
477        match self.kv_store.entry(key.to_string()) {
478            Entry::Occupied(_) => Ok(false),
479            Entry::Vacant(slot) => {
480                slot.insert(value.to_vec());
481                Ok(true)
482            }
483        }
484    }
485
486    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
487        if self.should_fail {
488            return Err(AuthError::internal("Mock storage configured to fail"));
489        }
490
491        // Use DashMap deadlock-free get with immediate value extraction
492        Ok(self.kv_store.get(key).map(|entry| entry.value().clone()))
493    }
494
495    async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> {
496        if self.should_fail {
497            return Err(AuthError::internal("Mock storage configured to fail"));
498        }
499
500        Ok(self
501            .kv_store
502            .iter()
503            .filter(|entry| entry.key().starts_with(prefix))
504            .map(|entry| entry.key().clone())
505            .collect())
506    }
507
508    async fn delete_kv(&self, key: &str) -> Result<()> {
509        if self.should_fail {
510            return Err(AuthError::internal("Mock storage configured to fail"));
511        }
512
513        // Use DashMap deadlock-free removal
514        self.kv_store.remove(key);
515        Ok(())
516    }
517
518    async fn cleanup_expired(&self) -> Result<()> {
519        if self.should_fail {
520            return Err(AuthError::internal("Mock storage configured to fail"));
521        }
522
523        let now = chrono::Utc::now();
524
525        // Use DashMap deadlock-free retain operation
526        self.tokens.retain(|_, token| token.expires_at > now);
527
528        Ok(())
529    }
530
531    async fn count_active_sessions(&self) -> Result<u64> {
532        if self.should_fail {
533            return Err(AuthError::internal("Mock storage configured to fail"));
534        }
535
536        // Count non-expired sessions using DashMap with manual iteration
537        let mut count = 0u64;
538        for entry in self.sessions.iter() {
539            if !entry.value().is_expired() {
540                count += 1;
541            }
542        }
543        Ok(count)
544    }
545}
546
547/// Test helper functions
548pub mod helpers {
549    use super::*;
550    // use std::sync::Arc;  // Temporarily unused
551
552    /// Create a test user profile.
553    ///
554    /// # Example
555    /// ```rust,ignore
556    /// let profile = helpers::create_test_user_profile("user-1");
557    /// ```
558    pub fn create_test_user_profile(user_id: &str) -> ProviderProfile {
559        ProviderProfile::new()
560            .with_id(user_id)
561            .with_provider("test")
562            .with_name(Some(format!("Test User {}", user_id)))
563            .with_email(Some(format!("{}@test.com", user_id)))
564            .with_email_verified(true)
565    }
566
567    /// Create a test auth token.
568    ///
569    /// # Example
570    /// ```rust,ignore
571    /// let token = helpers::create_test_token("user-1");
572    /// assert_eq!(token.user_id, "user-1");
573    /// ```
574    pub fn create_test_token(user_id: &str) -> AuthToken {
575        let now = chrono::Utc::now();
576        AuthToken {
577            token_id: Uuid::new_v4().to_string(),
578            user_id: user_id.to_string(),
579            access_token: format!("test_token_{}", Uuid::new_v4()),
580            refresh_token: Some(format!("refresh_token_{}", Uuid::new_v4())),
581            token_type: Some("Bearer".to_string()),
582            expires_at: now + chrono::Duration::seconds(3600),
583            scopes: vec!["read".to_string(), "write".to_string()].into(),
584            issued_at: now,
585            auth_method: "test".to_string(),
586            client_id: Some("test_client".to_string()),
587            metadata: crate::tokens::TokenMetadata::default(),
588            subject: Some(user_id.to_string()),
589            issuer: Some("test".to_string()),
590            user_profile: None,
591            permissions: vec!["read:all".to_string(), "write:all".to_string()].into(),
592            roles: vec!["test_user".to_string()].into(),
593        }
594    }
595
596    /// Create test credentials.
597    ///
598    /// # Example
599    /// ```rust,ignore
600    /// let creds = helpers::create_test_credentials();
601    /// assert_eq!(creds.len(), 5);
602    /// ```
603    pub fn create_test_credentials() -> Vec<Credential> {
604        vec![
605            Credential::password("testuser", "testpass"),
606            Credential::api_key("test_api_key"),
607            Credential::oauth_code("test_auth_code"),
608            Credential::device_code("test_device_code", "test_client_id"),
609            Credential::jwt("test.jwt.token"),
610        ]
611    }
612}
613
614// ── Edge-case tests ──────────────────────────────────────────────────────
615
616#[cfg(test)]
617mod edge_tests {
618    use super::*;
619    use crate::testing::test_infrastructure::TestEnvironmentGuard;
620
621    // --- MockAuthMethod authenticate edge cases ---
622
623    #[tokio::test]
624    async fn test_mock_auth_failure_mode() {
625        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
626        let mock = MockAuthMethod {
627            should_succeed: false,
628            user_profiles: HashMap::new(),
629            delay: None,
630        };
631        let cred = Credential::password("user", "pass");
632        let meta = CredentialMetadata::default();
633        let result = mock.authenticate(cred, meta).await.unwrap();
634        match result {
635            MethodResult::Failure { reason } => {
636                assert!(reason.contains("failed"), "Expected failure: {reason}");
637            }
638            _ => panic!("Expected Failure variant"),
639        }
640    }
641
642    #[tokio::test]
643    async fn test_mock_auth_api_key_empty() {
644        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
645        let mock = MockAuthMethod::new_success();
646        let cred = Credential::api_key("");
647        let meta = CredentialMetadata::default();
648        // Should not panic with empty API key — &key[..0] is valid
649        let result = mock.authenticate(cred, meta).await.unwrap();
650        match result {
651            MethodResult::Success(token) => {
652                assert!(token.user_id.starts_with("api_user_"));
653            }
654            _ => panic!("Expected success"),
655        }
656    }
657
658    #[tokio::test]
659    async fn test_mock_auth_api_key_short() {
660        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
661        let mock = MockAuthMethod::new_success();
662        let cred = Credential::api_key("abc");
663        let meta = CredentialMetadata::default();
664        let result = mock.authenticate(cred, meta).await.unwrap();
665        match result {
666            MethodResult::Success(token) => {
667                assert_eq!(token.user_id, "api_user_abc");
668            }
669            _ => panic!("Expected success"),
670        }
671    }
672
673    #[tokio::test]
674    async fn test_mock_auth_catch_all_credential() {
675        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
676        let mock = MockAuthMethod::new_success();
677        let cred = Credential::jwt("some.jwt.token");
678        let meta = CredentialMetadata::default();
679        let result = mock.authenticate(cred, meta).await.unwrap();
680        match result {
681            MethodResult::Success(token) => {
682                assert_eq!(token.user_id, "test_user");
683            }
684            _ => panic!("Expected success"),
685        }
686    }
687
688    // --- MockAuthMethod refresh edge cases ---
689
690    #[tokio::test]
691    async fn test_mock_refresh_success() {
692        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
693        let mock = MockAuthMethod::new_success();
694        let token = mock.refresh_token("old_refresh".to_string()).await.unwrap();
695        assert_eq!(token.user_id, "refreshed_user");
696        assert!(token.refresh_token.is_some());
697    }
698
699    #[tokio::test]
700    async fn test_mock_refresh_failure() {
701        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
702        let mock = MockAuthMethod {
703            should_succeed: false,
704            user_profiles: HashMap::new(),
705            delay: None,
706        };
707        let result = mock.refresh_token("old_refresh".to_string()).await;
708        assert!(result.is_err());
709    }
710
711    // --- MockStorage token operations ---
712
713    #[tokio::test]
714    async fn test_storage_get_token_by_access_token() {
715        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
716        let storage = MockStorage::new();
717        let token = helpers::create_test_token("user1");
718        let access = token.access_token.clone();
719        storage.store_token(&token).await.unwrap();
720        let found = storage.get_token_by_access_token(&access).await.unwrap();
721        assert!(found.is_some());
722        assert_eq!(found.unwrap().user_id, "user1");
723    }
724
725    #[tokio::test]
726    async fn test_storage_get_token_by_access_token_not_found() {
727        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
728        let storage = MockStorage::new();
729        let found = storage
730            .get_token_by_access_token("nonexistent")
731            .await
732            .unwrap();
733        assert!(found.is_none());
734    }
735
736    #[tokio::test]
737    async fn test_storage_update_token() {
738        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
739        let storage = MockStorage::new();
740        let mut token = helpers::create_test_token("user1");
741        storage.store_token(&token).await.unwrap();
742        token.user_id = "updated_user".to_string();
743        storage.update_token(&token).await.unwrap();
744        let found = storage
745            .get_token_by_access_token(&token.access_token)
746            .await
747            .unwrap()
748            .unwrap();
749        assert_eq!(found.user_id, "updated_user");
750    }
751
752    #[tokio::test]
753    async fn test_storage_delete_token() {
754        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
755        let storage = MockStorage::new();
756        let token = helpers::create_test_token("user1");
757        let tid = token.token_id.clone();
758        storage.store_token(&token).await.unwrap();
759        storage.delete_token(&tid).await.unwrap();
760        let found = storage.get_token(&tid).await.unwrap();
761        assert!(found.is_none());
762    }
763
764    #[tokio::test]
765    async fn test_storage_list_user_tokens_filters_by_user() {
766        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
767        let storage = MockStorage::new();
768        let t1 = helpers::create_test_token("alice");
769        let t2 = helpers::create_test_token("alice");
770        let t3 = helpers::create_test_token("bob");
771        storage.store_token(&t1).await.unwrap();
772        storage.store_token(&t2).await.unwrap();
773        storage.store_token(&t3).await.unwrap();
774        let alice_tokens = storage.list_user_tokens("alice").await.unwrap();
775        assert_eq!(alice_tokens.len(), 2);
776        let bob_tokens = storage.list_user_tokens("bob").await.unwrap();
777        assert_eq!(bob_tokens.len(), 1);
778    }
779
780    // --- MockStorage session operations ---
781
782    #[tokio::test]
783    async fn test_storage_session_crud() {
784        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
785        let storage = MockStorage::new();
786        let session = SessionData {
787            session_id: "sess1".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: Some("127.0.0.1".to_string()),
793            user_agent: None,
794            data: Default::default(),
795        };
796        storage.store_session("sess1", &session).await.unwrap();
797        let found = storage.get_session("sess1").await.unwrap();
798        assert!(found.is_some());
799        assert_eq!(found.unwrap().user_id, "user1");
800
801        storage.delete_session("sess1").await.unwrap();
802        let gone = storage.get_session("sess1").await.unwrap();
803        assert!(gone.is_none());
804    }
805
806    #[tokio::test]
807    async fn test_storage_list_user_sessions_filters_expired() {
808        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
809        let storage = MockStorage::new();
810        let active = SessionData {
811            session_id: "active".to_string(),
812            user_id: "user1".to_string(),
813            created_at: chrono::Utc::now(),
814            expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
815            last_activity: chrono::Utc::now(),
816            ip_address: None,
817            user_agent: None,
818            data: Default::default(),
819        };
820        let expired = SessionData {
821            session_id: "expired".to_string(),
822            user_id: "user1".to_string(),
823            created_at: chrono::Utc::now() - chrono::Duration::seconds(7200),
824            expires_at: chrono::Utc::now() - chrono::Duration::seconds(3600),
825            last_activity: chrono::Utc::now() - chrono::Duration::seconds(7200),
826            ip_address: None,
827            user_agent: None,
828            data: Default::default(),
829        };
830        storage.store_session("active", &active).await.unwrap();
831        storage.store_session("expired", &expired).await.unwrap();
832        let sessions = storage.list_user_sessions("user1").await.unwrap();
833        assert_eq!(sessions.len(), 1);
834        assert_eq!(sessions[0].session_id, "active");
835    }
836
837    // --- MockStorage KV operations ---
838
839    #[tokio::test]
840    async fn test_storage_kv_crud() {
841        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
842        let storage = MockStorage::new();
843        storage.store_kv("key1", b"value1", None).await.unwrap();
844        let val = storage.get_kv("key1").await.unwrap();
845        assert_eq!(val.unwrap(), b"value1");
846
847        storage.delete_kv("key1").await.unwrap();
848        let gone = storage.get_kv("key1").await.unwrap();
849        assert!(gone.is_none());
850    }
851
852    #[tokio::test]
853    async fn test_storage_kv_not_found() {
854        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
855        let storage = MockStorage::new();
856        let val = storage.get_kv("nonexistent").await.unwrap();
857        assert!(val.is_none());
858    }
859
860    // --- MockStorage cleanup ---
861
862    #[tokio::test]
863    async fn test_storage_cleanup_expired_tokens() {
864        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
865        let storage = MockStorage::new();
866        let mut expired_token = helpers::create_test_token("user1");
867        expired_token.expires_at = chrono::Utc::now() - chrono::Duration::seconds(10);
868        let valid_token = helpers::create_test_token("user2");
869        storage.store_token(&expired_token).await.unwrap();
870        storage.store_token(&valid_token).await.unwrap();
871        storage.cleanup_expired().await.unwrap();
872        // Expired token should be gone
873        let found_expired = storage
874            .get_token_by_access_token(&expired_token.access_token)
875            .await
876            .unwrap();
877        assert!(found_expired.is_none());
878        // Valid token should remain
879        let found_valid = storage
880            .get_token_by_access_token(&valid_token.access_token)
881            .await
882            .unwrap();
883        assert!(found_valid.is_some());
884    }
885
886    // --- helpers::create_test_credentials ---
887
888    #[test]
889    fn test_create_test_credentials_all_variants() {
890        let creds = helpers::create_test_credentials();
891        assert_eq!(creds.len(), 5);
892        assert!(matches!(&creds[0], Credential::Password { .. }));
893        assert!(matches!(&creds[1], Credential::ApiKey { .. }));
894        assert!(matches!(&creds[2], Credential::OAuth { .. }));
895        assert!(matches!(&creds[3], Credential::DeviceCode { .. }));
896        assert!(matches!(&creds[4], Credential::Jwt { .. }));
897    }
898
899    // --- MockStorage count_active_sessions ---
900
901    #[tokio::test]
902    async fn test_storage_count_active_sessions() {
903        let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
904        let storage = MockStorage::new();
905        let active = SessionData {
906            session_id: "active1".to_string(),
907            user_id: "user1".to_string(),
908            created_at: chrono::Utc::now(),
909            expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
910            last_activity: chrono::Utc::now(),
911            ip_address: None,
912            user_agent: None,
913            data: Default::default(),
914        };
915        let expired = SessionData {
916            session_id: "expired1".to_string(),
917            user_id: "user2".to_string(),
918            created_at: chrono::Utc::now() - chrono::Duration::seconds(7200),
919            expires_at: chrono::Utc::now() - chrono::Duration::seconds(3600),
920            last_activity: chrono::Utc::now() - chrono::Duration::seconds(7200),
921            ip_address: None,
922            user_agent: None,
923            data: Default::default(),
924        };
925        storage.store_session("active1", &active).await.unwrap();
926        storage.store_session("expired1", &expired).await.unwrap();
927        let count = storage.count_active_sessions().await.unwrap();
928        assert_eq!(count, 1);
929    }
930}