1#[derive(Debug, Clone)]
9pub struct MockAuthMethod {
10 pub should_succeed: bool,
12 pub user_profiles: HashMap<String, ProviderProfile>,
14 pub delay: Option<Duration>,
16}
17
18impl MockAuthMethod {
19 pub fn new_success() -> Self {
27 MockAuthMethod {
28 should_succeed: true,
29 user_profiles: HashMap::new(),
30 delay: None,
31 }
32 }
33
34 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 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#[cfg(test)]
72#[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 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 let _env = TestEnvironmentGuard::new();
140
141 let config = AuthConfig::default().force_production_mode();
142 match AuthFramework::new_validated(config) {
143 Err(e) => {
144 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 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 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 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#[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 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 pub fn new_failing() -> Self {
279 let mut storage = Self::new();
280 storage.should_fail = true;
281 storage
282 }
283
284 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 self.tokens.insert(token.access_token.clone(), token);
298 Ok(())
299 }
300
301 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 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 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 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 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 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 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 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 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 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 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 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 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 Ok(self.kv_store.get(key).map(|entry| entry.value().clone()))
482 }
483
484 async fn list_kv_keys(&self, prefix: &str) -> Result<Vec<String>> {
485 if self.should_fail {
486 return Err(AuthError::internal("Mock storage configured to fail"));
487 }
488
489 Ok(self
490 .kv_store
491 .iter()
492 .filter(|entry| entry.key().starts_with(prefix))
493 .map(|entry| entry.key().clone())
494 .collect())
495 }
496
497 async fn delete_kv(&self, key: &str) -> Result<()> {
498 if self.should_fail {
499 return Err(AuthError::internal("Mock storage configured to fail"));
500 }
501
502 self.kv_store.remove(key);
504 Ok(())
505 }
506
507 async fn cleanup_expired(&self) -> Result<()> {
508 if self.should_fail {
509 return Err(AuthError::internal("Mock storage configured to fail"));
510 }
511
512 let now = chrono::Utc::now();
513
514 self.tokens.retain(|_, token| token.expires_at > now);
516
517 Ok(())
518 }
519
520 async fn count_active_sessions(&self) -> Result<u64> {
521 if self.should_fail {
522 return Err(AuthError::internal("Mock storage configured to fail"));
523 }
524
525 let mut count = 0u64;
527 for entry in self.sessions.iter() {
528 if !entry.value().is_expired() {
529 count += 1;
530 }
531 }
532 Ok(count)
533 }
534}
535
536pub mod helpers {
538 use super::*;
539 pub fn create_test_user_profile(user_id: &str) -> ProviderProfile {
548 ProviderProfile::new()
549 .with_id(user_id)
550 .with_provider("test")
551 .with_name(Some(format!("Test User {}", user_id)))
552 .with_email(Some(format!("{}@test.com", user_id)))
553 .with_email_verified(true)
554 }
555
556 pub fn create_test_token(user_id: &str) -> AuthToken {
564 let now = chrono::Utc::now();
565 AuthToken {
566 token_id: Uuid::new_v4().to_string(),
567 user_id: user_id.to_string(),
568 access_token: format!("test_token_{}", Uuid::new_v4()),
569 refresh_token: Some(format!("refresh_token_{}", Uuid::new_v4())),
570 token_type: Some("Bearer".to_string()),
571 expires_at: now + chrono::Duration::seconds(3600),
572 scopes: vec!["read".to_string(), "write".to_string()].into(),
573 issued_at: now,
574 auth_method: "test".to_string(),
575 client_id: Some("test_client".to_string()),
576 metadata: crate::tokens::TokenMetadata::default(),
577 subject: Some(user_id.to_string()),
578 issuer: Some("test".to_string()),
579 user_profile: None,
580 permissions: vec!["read:all".to_string(), "write:all".to_string()].into(),
581 roles: vec!["test_user".to_string()].into(),
582 }
583 }
584
585 pub fn create_test_credentials() -> Vec<Credential> {
593 vec![
594 Credential::password("testuser", "testpass"),
595 Credential::api_key("test_api_key"),
596 Credential::oauth_code("test_auth_code"),
597 Credential::device_code("test_device_code", "test_client_id"),
598 Credential::jwt("test.jwt.token"),
599 ]
600 }
601}
602
603#[cfg(test)]
606mod edge_tests {
607 use super::*;
608 use crate::testing::test_infrastructure::TestEnvironmentGuard;
609
610 #[tokio::test]
613 async fn test_mock_auth_failure_mode() {
614 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
615 let mock = MockAuthMethod {
616 should_succeed: false,
617 user_profiles: HashMap::new(),
618 delay: None,
619 };
620 let cred = Credential::password("user", "pass");
621 let meta = CredentialMetadata::default();
622 let result = mock.authenticate(cred, meta).await.unwrap();
623 match result {
624 MethodResult::Failure { reason } => {
625 assert!(reason.contains("failed"), "Expected failure: {reason}");
626 }
627 _ => panic!("Expected Failure variant"),
628 }
629 }
630
631 #[tokio::test]
632 async fn test_mock_auth_api_key_empty() {
633 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
634 let mock = MockAuthMethod::new_success();
635 let cred = Credential::api_key("");
636 let meta = CredentialMetadata::default();
637 let result = mock.authenticate(cred, meta).await.unwrap();
639 match result {
640 MethodResult::Success(token) => {
641 assert!(token.user_id.starts_with("api_user_"));
642 }
643 _ => panic!("Expected success"),
644 }
645 }
646
647 #[tokio::test]
648 async fn test_mock_auth_api_key_short() {
649 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
650 let mock = MockAuthMethod::new_success();
651 let cred = Credential::api_key("abc");
652 let meta = CredentialMetadata::default();
653 let result = mock.authenticate(cred, meta).await.unwrap();
654 match result {
655 MethodResult::Success(token) => {
656 assert_eq!(token.user_id, "api_user_abc");
657 }
658 _ => panic!("Expected success"),
659 }
660 }
661
662 #[tokio::test]
663 async fn test_mock_auth_catch_all_credential() {
664 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
665 let mock = MockAuthMethod::new_success();
666 let cred = Credential::jwt("some.jwt.token");
667 let meta = CredentialMetadata::default();
668 let result = mock.authenticate(cred, meta).await.unwrap();
669 match result {
670 MethodResult::Success(token) => {
671 assert_eq!(token.user_id, "test_user");
672 }
673 _ => panic!("Expected success"),
674 }
675 }
676
677 #[tokio::test]
680 async fn test_mock_refresh_success() {
681 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
682 let mock = MockAuthMethod::new_success();
683 let token = mock.refresh_token("old_refresh".to_string()).await.unwrap();
684 assert_eq!(token.user_id, "refreshed_user");
685 assert!(token.refresh_token.is_some());
686 }
687
688 #[tokio::test]
689 async fn test_mock_refresh_failure() {
690 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
691 let mock = MockAuthMethod {
692 should_succeed: false,
693 user_profiles: HashMap::new(),
694 delay: None,
695 };
696 let result = mock.refresh_token("old_refresh".to_string()).await;
697 assert!(result.is_err());
698 }
699
700 #[tokio::test]
703 async fn test_storage_get_token_by_access_token() {
704 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
705 let storage = MockStorage::new();
706 let token = helpers::create_test_token("user1");
707 let access = token.access_token.clone();
708 storage.store_token(&token).await.unwrap();
709 let found = storage.get_token_by_access_token(&access).await.unwrap();
710 assert!(found.is_some());
711 assert_eq!(found.unwrap().user_id, "user1");
712 }
713
714 #[tokio::test]
715 async fn test_storage_get_token_by_access_token_not_found() {
716 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
717 let storage = MockStorage::new();
718 let found = storage
719 .get_token_by_access_token("nonexistent")
720 .await
721 .unwrap();
722 assert!(found.is_none());
723 }
724
725 #[tokio::test]
726 async fn test_storage_update_token() {
727 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
728 let storage = MockStorage::new();
729 let mut token = helpers::create_test_token("user1");
730 storage.store_token(&token).await.unwrap();
731 token.user_id = "updated_user".to_string();
732 storage.update_token(&token).await.unwrap();
733 let found = storage
734 .get_token_by_access_token(&token.access_token)
735 .await
736 .unwrap()
737 .unwrap();
738 assert_eq!(found.user_id, "updated_user");
739 }
740
741 #[tokio::test]
742 async fn test_storage_delete_token() {
743 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
744 let storage = MockStorage::new();
745 let token = helpers::create_test_token("user1");
746 let tid = token.token_id.clone();
747 storage.store_token(&token).await.unwrap();
748 storage.delete_token(&tid).await.unwrap();
749 let found = storage.get_token(&tid).await.unwrap();
750 assert!(found.is_none());
751 }
752
753 #[tokio::test]
754 async fn test_storage_list_user_tokens_filters_by_user() {
755 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
756 let storage = MockStorage::new();
757 let t1 = helpers::create_test_token("alice");
758 let t2 = helpers::create_test_token("alice");
759 let t3 = helpers::create_test_token("bob");
760 storage.store_token(&t1).await.unwrap();
761 storage.store_token(&t2).await.unwrap();
762 storage.store_token(&t3).await.unwrap();
763 let alice_tokens = storage.list_user_tokens("alice").await.unwrap();
764 assert_eq!(alice_tokens.len(), 2);
765 let bob_tokens = storage.list_user_tokens("bob").await.unwrap();
766 assert_eq!(bob_tokens.len(), 1);
767 }
768
769 #[tokio::test]
772 async fn test_storage_session_crud() {
773 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
774 let storage = MockStorage::new();
775 let session = SessionData {
776 session_id: "sess1".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: Some("127.0.0.1".to_string()),
782 user_agent: None,
783 data: Default::default(),
784 };
785 storage.store_session("sess1", &session).await.unwrap();
786 let found = storage.get_session("sess1").await.unwrap();
787 assert!(found.is_some());
788 assert_eq!(found.unwrap().user_id, "user1");
789
790 storage.delete_session("sess1").await.unwrap();
791 let gone = storage.get_session("sess1").await.unwrap();
792 assert!(gone.is_none());
793 }
794
795 #[tokio::test]
796 async fn test_storage_list_user_sessions_filters_expired() {
797 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
798 let storage = MockStorage::new();
799 let active = SessionData {
800 session_id: "active".to_string(),
801 user_id: "user1".to_string(),
802 created_at: chrono::Utc::now(),
803 expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
804 last_activity: chrono::Utc::now(),
805 ip_address: None,
806 user_agent: None,
807 data: Default::default(),
808 };
809 let expired = SessionData {
810 session_id: "expired".to_string(),
811 user_id: "user1".to_string(),
812 created_at: chrono::Utc::now() - chrono::Duration::seconds(7200),
813 expires_at: chrono::Utc::now() - chrono::Duration::seconds(3600),
814 last_activity: chrono::Utc::now() - chrono::Duration::seconds(7200),
815 ip_address: None,
816 user_agent: None,
817 data: Default::default(),
818 };
819 storage.store_session("active", &active).await.unwrap();
820 storage.store_session("expired", &expired).await.unwrap();
821 let sessions = storage.list_user_sessions("user1").await.unwrap();
822 assert_eq!(sessions.len(), 1);
823 assert_eq!(sessions[0].session_id, "active");
824 }
825
826 #[tokio::test]
829 async fn test_storage_kv_crud() {
830 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
831 let storage = MockStorage::new();
832 storage.store_kv("key1", b"value1", None).await.unwrap();
833 let val = storage.get_kv("key1").await.unwrap();
834 assert_eq!(val.unwrap(), b"value1");
835
836 storage.delete_kv("key1").await.unwrap();
837 let gone = storage.get_kv("key1").await.unwrap();
838 assert!(gone.is_none());
839 }
840
841 #[tokio::test]
842 async fn test_storage_kv_not_found() {
843 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
844 let storage = MockStorage::new();
845 let val = storage.get_kv("nonexistent").await.unwrap();
846 assert!(val.is_none());
847 }
848
849 #[tokio::test]
852 async fn test_storage_cleanup_expired_tokens() {
853 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
854 let storage = MockStorage::new();
855 let mut expired_token = helpers::create_test_token("user1");
856 expired_token.expires_at = chrono::Utc::now() - chrono::Duration::seconds(10);
857 let valid_token = helpers::create_test_token("user2");
858 storage.store_token(&expired_token).await.unwrap();
859 storage.store_token(&valid_token).await.unwrap();
860 storage.cleanup_expired().await.unwrap();
861 let found_expired = storage
863 .get_token_by_access_token(&expired_token.access_token)
864 .await
865 .unwrap();
866 assert!(found_expired.is_none());
867 let found_valid = storage
869 .get_token_by_access_token(&valid_token.access_token)
870 .await
871 .unwrap();
872 assert!(found_valid.is_some());
873 }
874
875 #[test]
878 fn test_create_test_credentials_all_variants() {
879 let creds = helpers::create_test_credentials();
880 assert_eq!(creds.len(), 5);
881 assert!(matches!(&creds[0], Credential::Password { .. }));
882 assert!(matches!(&creds[1], Credential::ApiKey { .. }));
883 assert!(matches!(&creds[2], Credential::OAuth { .. }));
884 assert!(matches!(&creds[3], Credential::DeviceCode { .. }));
885 assert!(matches!(&creds[4], Credential::Jwt { .. }));
886 }
887
888 #[tokio::test]
891 async fn test_storage_count_active_sessions() {
892 let _env = TestEnvironmentGuard::new().with_jwt_secret("test-secret");
893 let storage = MockStorage::new();
894 let active = SessionData {
895 session_id: "active1".to_string(),
896 user_id: "user1".to_string(),
897 created_at: chrono::Utc::now(),
898 expires_at: chrono::Utc::now() + chrono::Duration::seconds(3600),
899 last_activity: chrono::Utc::now(),
900 ip_address: None,
901 user_agent: None,
902 data: Default::default(),
903 };
904 let expired = SessionData {
905 session_id: "expired1".to_string(),
906 user_id: "user2".to_string(),
907 created_at: chrono::Utc::now() - chrono::Duration::seconds(7200),
908 expires_at: chrono::Utc::now() - chrono::Duration::seconds(3600),
909 last_activity: chrono::Utc::now() - chrono::Duration::seconds(7200),
910 ip_address: None,
911 user_agent: None,
912 data: Default::default(),
913 };
914 storage.store_session("active1", &active).await.unwrap();
915 storage.store_session("expired1", &expired).await.unwrap();
916 let count = storage.count_active_sessions().await.unwrap();
917 assert_eq!(count, 1);
918 }
919}