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