Skip to main content

auth_framework/testing/
utilities.rs

1#[derive(Debug, Clone)]
2pub struct MockAuthMethod {
3    /// Whether authentication should succeed
4    pub should_succeed: bool,
5    /// Simulated user profiles to return
6    pub user_profiles: HashMap<String, UserProfile>,
7    /// Simulated delay for authentication
8    pub delay: Option<Duration>,
9}
10
11impl MockAuthMethod {
12    /// Create a new mock authentication method that always succeeds
13    pub fn new_success() -> Self {
14        MockAuthMethod {
15            should_succeed: true,
16            user_profiles: HashMap::new(),
17            delay: None,
18        }
19    }
20
21    /// Add a user profile for a specific user ID
22    pub fn with_user(mut self, user_id: impl Into<String>, profile: UserProfile) -> Self {
23        self.user_profiles.insert(user_id.into(), profile);
24        self
25    }
26
27    /// Set a delay for authentication (useful for testing timeouts)
28    pub fn with_delay(mut self, delay: Duration) -> Self {
29        self.delay = Some(delay);
30        self
31    }
32}
33use crate::authentication::credentials::{Credential, CredentialMetadata};
34use crate::errors::{AuthError, Result};
35use crate::methods::{AuthMethod, MethodResult};
36use crate::providers::UserProfile;
37use crate::storage::AuthStorage;
38use crate::storage::core::SessionData;
39use crate::tokens::AuthToken;
40use dashmap::DashMap;
41use std::collections::HashMap;
42use std::sync::Arc;
43use std::time::Duration;
44use uuid::Uuid;
45// Ensure all top-level impls are closed before the test module
46#[cfg(test)]
47// use crate::security::SecurityConfig;
48#[tokio::test]
49async fn test_mock_storage() {
50    use crate::testing::test_infrastructure::TestEnvironmentGuard;
51    let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
52
53    let storage = MockStorage::new();
54    let token = helpers::create_test_token("testuser");
55    storage.store_token(&token).await.unwrap();
56    let retrieved = storage.get_token(&token.token_id).await.unwrap();
57    assert!(retrieved.is_some());
58    assert_eq!(retrieved.unwrap().token_id, token.token_id);
59}
60
61#[tokio::test]
62async fn test_failing_mock_storage() {
63    use crate::testing::test_infrastructure::TestEnvironmentGuard;
64    let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
65
66    let storage = MockStorage::new_failing();
67    let token = helpers::create_test_token("testuser");
68    let result = storage.store_token(&token).await;
69    assert!(result.is_err());
70}
71
72#[test]
73fn test_secret_loading_from_env() {
74    use crate::auth::AuthFramework;
75    use crate::config::AuthConfig;
76    use crate::testing::test_infrastructure::TestEnvironmentGuard;
77
78    let _env = TestEnvironmentGuard::new().with_jwt_secret("env_secret_value");
79
80    let config = AuthConfig::default().secret("config_secret_value");
81    let framework = AuthFramework::new(config.clone());
82    let token = framework
83        .token_manager()
84        .create_jwt_token("user", vec!["read".to_string()], None);
85    assert!(token.is_ok());
86}
87
88#[test]
89fn test_secret_loading_from_config() {
90    use crate::auth::AuthFramework;
91    use crate::config::AuthConfig;
92    use crate::testing::test_infrastructure::TestEnvironmentGuard;
93
94    // Ensure JWT_SECRET is not set in environment for this test
95    let _env = TestEnvironmentGuard::new();
96
97    let config = AuthConfig::default().secret("config_secret_value");
98    let framework = AuthFramework::new(config.clone());
99    let token = framework
100        .token_manager()
101        .create_jwt_token("user", vec!["read".to_string()], None);
102    assert!(token.is_ok());
103}
104
105#[test]
106fn test_secret_missing_returns_error() {
107    use crate::auth::AuthFramework;
108    use crate::config::AuthConfig;
109
110    // Ensure JWT_SECRET is not set for this test
111    unsafe {
112        std::env::remove_var("JWT_SECRET");
113    }
114
115    // In production mode, should return error instead of panic
116    unsafe {
117        std::env::set_var("ENVIRONMENT", "production");
118
119        let config = AuthConfig::default();
120        match AuthFramework::new_validated(config) {
121            Err(e) => {
122                // Should fail with proper error message about JWT secret
123                assert!(e.to_string().contains("JWT secret"));
124            }
125            Ok(_) => panic!("Expected error when JWT_SECRET is missing in production"),
126        }
127
128        // Clean up
129        std::env::remove_var("ENVIRONMENT");
130    }
131}
132
133impl AuthMethod for MockAuthMethod {
134    type MethodResult = MethodResult;
135    type AuthToken = AuthToken;
136
137    fn name(&self) -> &str {
138        "mock"
139    }
140
141    fn validate_config(&self) -> Result<()> {
142        Ok(())
143    }
144
145    async fn authenticate(
146        &self,
147        credential: Credential,
148        _metadata: CredentialMetadata,
149    ) -> Result<Self::MethodResult> {
150        // Simulate delay if configured
151        if let Some(delay) = self.delay {
152            tokio::time::sleep(delay).await;
153        }
154
155        if !self.should_succeed {
156            return Ok(MethodResult::Failure {
157                reason: "Mock authentication failed".to_string(),
158            });
159        }
160
161        // Extract user ID based on credential type
162        let user_id = match credential {
163            Credential::Password { username, .. } => username.clone(),
164            Credential::ApiKey { key } => format!("api_user_{}", &key[..8.min(key.len())]),
165            Credential::OAuth { .. } => "oauth_user".to_string(),
166            Credential::DeviceCode { .. } => "device_user".to_string(),
167            _ => "test_user".to_string(),
168        };
169
170        // Create a mock token
171        let token = AuthToken {
172            token_id: Uuid::new_v4().to_string(),
173            user_id: user_id.clone(),
174            access_token: format!("mock_token_{}", Uuid::new_v4()),
175            refresh_token: Some(format!("refresh_{}", Uuid::new_v4())),
176            token_type: Some("Bearer".to_string()),
177            expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
178            scopes: vec!["read".to_string(), "write".to_string()],
179            issued_at: chrono::Utc::now(),
180            auth_method: "mock".to_string(),
181            subject: Some(user_id.clone()),
182            issuer: Some("mock".to_string()),
183            user_profile: None,
184            client_id: Some("test_client".to_string()),
185            permissions: vec!["read:all".to_string(), "write:all".to_string()],
186            roles: vec!["mock_user".to_string()],
187            metadata: crate::tokens::TokenMetadata::default(),
188        };
189
190        Ok(MethodResult::Success(Box::new(token)))
191    }
192
193    async fn refresh_token(&self, _refresh_token: String) -> Result<Self::AuthToken> {
194        if !self.should_succeed {
195            return Err(AuthError::auth_method("mock", "Refresh failed"));
196        }
197
198        Ok(AuthToken {
199            token_id: Uuid::new_v4().to_string(),
200            user_id: "refreshed_user".to_string(),
201            access_token: "mock_refreshed_token".to_string(),
202            refresh_token: Some("mock_new_refresh_token".to_string()),
203            token_type: Some("Bearer".to_string()),
204            expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
205            scopes: vec!["read".to_string(), "write".to_string()],
206            issued_at: chrono::Utc::now(),
207            auth_method: "mock".to_string(),
208            client_id: Some("test_client".to_string()),
209            metadata: crate::tokens::TokenMetadata::default(),
210            subject: Some("refreshed_user".to_string()),
211            issuer: Some("mock".to_string()),
212            user_profile: None,
213            permissions: vec!["read:all".to_string(), "write:all".to_string()],
214            roles: vec!["refreshed_user".to_string()],
215        })
216    }
217}
218
219/// Mock storage implementation for testing with DashMap for deadlock-free operations.
220#[derive(Clone)]
221pub struct MockStorage {
222    tokens: Arc<DashMap<String, AuthToken>>,
223    sessions: Arc<DashMap<String, SessionData>>,
224    kv_store: Arc<DashMap<String, Vec<u8>>>,
225    should_fail: bool,
226}
227
228impl std::fmt::Debug for MockStorage {
229    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
230        let mut d = f.debug_struct("MockStorage");
231        d.field("tokens", &crate::utils::redact::redacted(&self.tokens));
232        d.field("sessions", &crate::utils::redact::redacted(&self.sessions));
233        d.field("kv_store", &crate::utils::redact::redacted(&self.kv_store));
234        d.field("should_fail", &self.should_fail);
235        d.finish()
236    }
237}
238
239impl MockStorage {
240    /// Create a new mock storage with DashMap for deadlock-free operations
241    pub fn new() -> Self {
242        Self {
243            tokens: Arc::new(DashMap::new()),
244            sessions: Arc::new(DashMap::new()),
245            kv_store: Arc::new(DashMap::new()),
246            should_fail: false,
247        }
248    }
249
250    /// Create a mock storage that fails operations
251    pub fn new_failing() -> Self {
252        let mut storage = Self::new();
253        storage.should_fail = true;
254        storage
255    }
256
257    /// Preset a token in storage
258    pub fn with_token(&self, token: AuthToken) -> Result<()> {
259        if self.should_fail {
260            return Err(AuthError::internal("Mock storage configured to fail"));
261        }
262
263        // Use DashMap deadlock-free insertion
264        self.tokens.insert(token.access_token.clone(), token);
265        Ok(())
266    }
267
268    /// Clear all storage using DashMap atomic operations
269    pub fn clear(&self) {
270        self.tokens.clear();
271        self.sessions.clear();
272        self.kv_store.clear();
273    }
274}
275
276impl Default for MockStorage {
277    fn default() -> Self {
278        Self::new()
279    }
280}
281
282#[async_trait::async_trait]
283impl AuthStorage for MockStorage {
284    async fn store_token(&self, token: &AuthToken) -> Result<()> {
285        if self.should_fail {
286            return Err(AuthError::internal("Mock storage configured to fail"));
287        }
288
289        // Use DashMap deadlock-free insertion
290        self.tokens
291            .insert(token.access_token.clone(), token.clone());
292        Ok(())
293    }
294
295    async fn get_token(&self, token_id: &str) -> Result<Option<AuthToken>> {
296        if self.should_fail {
297            return Err(AuthError::internal("Mock storage configured to fail"));
298        }
299
300        // Use DashMap deadlock-free iteration with immediate value extraction
301        for entry in self.tokens.iter() {
302            if entry.value().token_id == token_id {
303                return Ok(Some(entry.value().clone()));
304            }
305        }
306        Ok(None)
307    }
308
309    async fn get_token_by_access_token(&self, access_token: &str) -> Result<Option<AuthToken>> {
310        if self.should_fail {
311            return Err(AuthError::internal("Mock storage configured to fail"));
312        }
313
314        // Use DashMap deadlock-free get with immediate value extraction
315        Ok(self
316            .tokens
317            .get(access_token)
318            .map(|entry| entry.value().clone()))
319    }
320
321    async fn update_token(&self, token: &AuthToken) -> Result<()> {
322        if self.should_fail {
323            return Err(AuthError::internal("Mock storage configured to fail"));
324        }
325
326        // Use DashMap deadlock-free update
327        self.tokens
328            .insert(token.access_token.clone(), token.clone());
329        Ok(())
330    }
331
332    async fn delete_token(&self, token_id: &str) -> Result<()> {
333        if self.should_fail {
334            return Err(AuthError::internal("Mock storage configured to fail"));
335        }
336
337        // Use DashMap deadlock-free removal with retain-like operation
338        self.tokens.retain(|_, token| token.token_id != token_id);
339        Ok(())
340    }
341
342    async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
343        if self.should_fail {
344            return Err(AuthError::internal("Mock storage configured to fail"));
345        }
346
347        // Use DashMap with manual iteration to avoid API issues
348        let mut tokens = Vec::new();
349        for entry in self.tokens.iter() {
350            if entry.value().user_id == user_id {
351                tokens.push(entry.value().clone());
352            }
353        }
354        Ok(tokens)
355    }
356
357    async fn store_session(&self, session_id: &str, data: &SessionData) -> Result<()> {
358        if self.should_fail {
359            return Err(AuthError::internal("Mock storage configured to fail"));
360        }
361
362        // Use DashMap deadlock-free insertion
363        self.sessions.insert(session_id.to_string(), data.clone());
364        Ok(())
365    }
366
367    async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
368        if self.should_fail {
369            return Err(AuthError::internal("Mock storage configured to fail"));
370        }
371
372        // Use DashMap deadlock-free get with immediate value extraction
373        Ok(self
374            .sessions
375            .get(session_id)
376            .map(|entry| entry.value().clone()))
377    }
378
379    async fn delete_session(&self, session_id: &str) -> Result<()> {
380        if self.should_fail {
381            return Err(AuthError::internal("Mock storage configured to fail"));
382        }
383
384        // Use DashMap deadlock-free removal
385        self.sessions.remove(session_id);
386        Ok(())
387    }
388
389    async fn list_user_sessions(&self, user_id: &str) -> Result<Vec<SessionData>> {
390        if self.should_fail {
391            return Err(AuthError::internal("Mock storage configured to fail"));
392        }
393
394        // Use DashMap with manual iteration to avoid API issues
395        let mut sessions = Vec::new();
396        for entry in self.sessions.iter() {
397            if entry.value().user_id == user_id && !entry.value().is_expired() {
398                sessions.push(entry.value().clone());
399            }
400        }
401        Ok(sessions)
402    }
403
404    async fn store_kv(&self, key: &str, value: &[u8], _ttl: Option<Duration>) -> Result<()> {
405        if self.should_fail {
406            return Err(AuthError::internal("Mock storage configured to fail"));
407        }
408
409        // Use DashMap deadlock-free insertion
410        self.kv_store.insert(key.to_string(), value.to_vec());
411        Ok(())
412    }
413
414    async fn get_kv(&self, key: &str) -> Result<Option<Vec<u8>>> {
415        if self.should_fail {
416            return Err(AuthError::internal("Mock storage configured to fail"));
417        }
418
419        // Use DashMap deadlock-free get with immediate value extraction
420        Ok(self.kv_store.get(key).map(|entry| entry.value().clone()))
421    }
422
423    async fn delete_kv(&self, key: &str) -> Result<()> {
424        if self.should_fail {
425            return Err(AuthError::internal("Mock storage configured to fail"));
426        }
427
428        // Use DashMap deadlock-free removal
429        self.kv_store.remove(key);
430        Ok(())
431    }
432
433    async fn cleanup_expired(&self) -> Result<()> {
434        if self.should_fail {
435            return Err(AuthError::internal("Mock storage configured to fail"));
436        }
437
438        let now = chrono::Utc::now();
439
440        // Use DashMap deadlock-free retain operation
441        self.tokens.retain(|_, token| token.expires_at > now);
442
443        Ok(())
444    }
445
446    async fn count_active_sessions(&self) -> Result<u64> {
447        if self.should_fail {
448            return Err(AuthError::internal("Mock storage configured to fail"));
449        }
450
451        // Count non-expired sessions using DashMap with manual iteration
452        let mut count = 0u64;
453        for entry in self.sessions.iter() {
454            if !entry.value().is_expired() {
455                count += 1;
456            }
457        }
458        Ok(count)
459    }
460}
461
462/// Test helper functions
463pub mod helpers {
464    use super::*;
465    // use std::sync::Arc;  // Temporarily unused
466
467    /// Create a test user profile
468    pub fn create_test_user_profile(user_id: &str) -> UserProfile {
469        UserProfile::new()
470            .with_id(user_id)
471            .with_provider("test")
472            .with_name(Some(format!("Test User {}", user_id)))
473            .with_email(Some(format!("{}@test.com", user_id)))
474            .with_email_verified(true)
475    }
476
477    /// Create a test auth token
478    pub fn create_test_token(user_id: &str) -> AuthToken {
479        let now = chrono::Utc::now();
480        AuthToken {
481            token_id: Uuid::new_v4().to_string(),
482            user_id: user_id.to_string(),
483            access_token: format!("test_token_{}", Uuid::new_v4()),
484            refresh_token: Some(format!("refresh_token_{}", Uuid::new_v4())),
485            token_type: Some("Bearer".to_string()),
486            expires_at: now + chrono::Duration::seconds(3600),
487            scopes: vec!["read".to_string(), "write".to_string()],
488            issued_at: now,
489            auth_method: "test".to_string(),
490            client_id: Some("test_client".to_string()),
491            metadata: crate::tokens::TokenMetadata::default(),
492            subject: Some(user_id.to_string()),
493            issuer: Some("test".to_string()),
494            user_profile: None,
495            permissions: vec!["read:all".to_string(), "write:all".to_string()],
496            roles: vec!["test_user".to_string()],
497        }
498    }
499
500    /// Create test credentials
501    pub fn create_test_credentials() -> Vec<Credential> {
502        vec![
503            Credential::password("testuser", "testpass"),
504            Credential::api_key("test_api_key"),
505            Credential::oauth_code("test_auth_code"),
506            Credential::device_code("test_device_code", "test_client_id"),
507            Credential::jwt("test.jwt.token"),
508        ]
509    }
510}