1pub mod jwt_server {
9 use crate::errors::Result;
10 use crate::storage::AuthStorage;
11 use serde::{Deserialize, Serialize};
12 use std::sync::Arc;
13
14 #[derive(Debug, Clone)]
21 pub struct JwtServerConfig {
22 pub issuer: String,
23 pub key_id: String,
24 }
25
26 impl Default for JwtServerConfig {
27 fn default() -> Self {
28 Self {
29 issuer: "https://auth.example.com".to_string(),
30 key_id: "default".to_string(),
31 }
32 }
33 }
34
35 pub struct JwtServer {
36 config: JwtServerConfig,
37 storage: Arc<dyn AuthStorage>,
38 }
39
40 impl JwtServer {
41 pub async fn new(config: JwtServerConfig, storage: Arc<dyn AuthStorage>) -> Result<Self> {
48 Ok(Self { config, storage })
49 }
50
51 pub async fn initialize(&self) -> Result<()> {
62 Ok(())
63 }
64
65 pub async fn get_well_known_jwt_configuration(&self) -> Result<JwtWellKnownConfiguration> {
73 Ok(JwtWellKnownConfiguration {
74 issuer: self.config.issuer.clone(),
75 jwks_uri: format!("{}/jwks", self.config.issuer),
76 })
77 }
78
79 pub async fn store_jwt_metadata(&self, metadata: &JwtWellKnownConfiguration) -> Result<()> {
87 let key = format!("jwt_metadata:{}", self.config.issuer);
88 let value = serde_json::to_string(metadata).map_err(|e| {
89 crate::errors::AuthError::internal(format!("Serialization error: {}", e))
90 })?;
91
92 self.storage.store_kv(&key, value.as_bytes(), None).await?;
93 tracing::info!("Stored JWT metadata for issuer: {}", self.config.issuer);
94 Ok(())
95 }
96
97 pub async fn get_stored_metadata(&self) -> Result<Option<JwtWellKnownConfiguration>> {
106 let key = format!("jwt_metadata:{}", self.config.issuer);
107
108 if let Some(value_bytes) = self.storage.get_kv(&key).await? {
109 let value = String::from_utf8(value_bytes).map_err(|e| {
110 crate::errors::AuthError::internal(format!("UTF-8 conversion error: {}", e))
111 })?;
112 let metadata: JwtWellKnownConfiguration =
113 serde_json::from_str(&value).map_err(|e| {
114 crate::errors::AuthError::internal(format!("Deserialization error: {}", e))
115 })?;
116 Ok(Some(metadata))
117 } else {
118 Ok(None)
119 }
120 }
121
122 pub async fn store_signing_key(&self, key_data: &str) -> Result<()> {
129 let key = format!("jwt_key:{}", self.config.key_id);
130 self.storage
131 .store_kv(&key, key_data.as_bytes(), None)
132 .await?;
133 tracing::info!("Stored JWT signing key: {}", self.config.key_id);
134 Ok(())
135 }
136 }
137
138 #[derive(Debug, Clone, Serialize, Deserialize)]
145 pub struct JwtWellKnownConfiguration {
146 pub issuer: String,
147 pub jwks_uri: String,
148 }
149}
150
151pub mod api_gateway {
153 use crate::errors::Result;
154 use crate::storage::AuthStorage;
155 use std::sync::Arc;
156
157 #[derive(Debug, Clone)]
164 pub struct ApiGatewayConfig {
165 pub name: String,
166 }
167
168 impl Default for ApiGatewayConfig {
169 fn default() -> Self {
170 Self {
171 name: "API Gateway".to_string(),
172 }
173 }
174 }
175
176 pub struct ApiGateway {
177 config: ApiGatewayConfig,
178 storage: Arc<dyn AuthStorage>,
179 }
180
181 impl ApiGateway {
182 pub async fn new(config: ApiGatewayConfig, storage: Arc<dyn AuthStorage>) -> Result<Self> {
189 Ok(Self { config, storage })
190 }
191
192 pub async fn initialize(&self) -> Result<()> {
203 Ok(())
204 }
205
206 pub async fn store_gateway_metadata(&self) -> Result<()> {
213 let key = format!("api_gateway_config:{}", self.config.name);
214 let metadata = serde_json::json!({
215 "name": self.config.name,
216 "initialized_at": chrono::Utc::now().to_rfc3339()
217 });
218 let value = serde_json::to_string(&metadata).map_err(|e| {
219 crate::errors::AuthError::internal(format!("Serialization error: {}", e))
220 })?;
221
222 self.storage.store_kv(&key, value.as_bytes(), None).await?;
223 tracing::info!("Stored API Gateway metadata for: {}", self.config.name);
224 Ok(())
225 }
226
227 pub async fn store_route_config(&self, route_path: &str, config_data: &str) -> Result<()> {
234 let key = format!("api_gateway_route:{}:{}", self.config.name, route_path);
235 self.storage
236 .store_kv(&key, config_data.as_bytes(), None)
237 .await?;
238 tracing::info!(
239 "Stored route config for {} on gateway: {}",
240 route_path,
241 self.config.name
242 );
243 Ok(())
244 }
245
246 pub async fn get_route_config(&self, route_path: &str) -> Result<Option<String>> {
255 let key = format!("api_gateway_route:{}:{}", self.config.name, route_path);
256
257 if let Some(config_bytes) = self.storage.get_kv(&key).await? {
258 let config = String::from_utf8(config_bytes).map_err(|e| {
259 crate::errors::AuthError::internal(format!("UTF-8 conversion error: {}", e))
260 })?;
261 Ok(Some(config))
262 } else {
263 Ok(None)
264 }
265 }
266
267 pub fn get_gateway_name(&self) -> &str {
274 &self.config.name
275 }
276 }
277}
278
279pub mod saml_idp {
281 use crate::errors::Result;
282 use crate::storage::AuthStorage;
283 use serde::{Deserialize, Serialize};
284 use std::sync::Arc;
285
286 #[derive(Debug, Clone)]
293 pub struct SamlIdpConfig {
294 pub entity_id: String,
295 }
296
297 impl Default for SamlIdpConfig {
298 fn default() -> Self {
299 Self {
300 entity_id: "https://auth.example.com".to_string(),
301 }
302 }
303 }
304
305 pub struct SamlIdentityProvider {
306 config: SamlIdpConfig,
307 storage: Arc<dyn AuthStorage>,
308 }
309
310 impl SamlIdentityProvider {
311 pub async fn new(config: SamlIdpConfig, storage: Arc<dyn AuthStorage>) -> Result<Self> {
318 Ok(Self { config, storage })
319 }
320
321 pub async fn initialize(&self) -> Result<()> {
332 Ok(())
333 }
334
335 pub async fn get_metadata(&self) -> Result<SamlMetadata> {
343 Ok(SamlMetadata {
344 entity_id: self.config.entity_id.clone(),
345 })
346 }
347
348 pub async fn store_saml_metadata(&self, metadata: &SamlMetadata) -> Result<()> {
355 let key = format!("saml_metadata:{}", self.config.entity_id);
356 let value = serde_json::to_string(metadata).map_err(|e| {
357 crate::errors::AuthError::internal(format!("Serialization error: {}", e))
358 })?;
359
360 self.storage.store_kv(&key, value.as_bytes(), None).await?;
361 tracing::info!("Stored SAML metadata for entity: {}", self.config.entity_id);
362 Ok(())
363 }
364
365 pub async fn store_assertion(
372 &self,
373 assertion_id: &str,
374 assertion_data: &str,
375 ) -> Result<()> {
376 let key = format!("saml_assertion:{}:{}", self.config.entity_id, assertion_id);
377 self.storage
378 .store_kv(
379 &key,
380 assertion_data.as_bytes(),
381 Some(std::time::Duration::from_secs(3600)),
382 )
383 .await?;
384 tracing::info!(
385 "Stored SAML assertion {} for entity: {}",
386 assertion_id,
387 self.config.entity_id
388 );
389 Ok(())
390 }
391
392 pub async fn get_assertion(&self, assertion_id: &str) -> Result<Option<String>> {
401 let key = format!("saml_assertion:{}:{}", self.config.entity_id, assertion_id);
402
403 if let Some(assertion_bytes) = self.storage.get_kv(&key).await? {
404 let assertion = String::from_utf8(assertion_bytes).map_err(|e| {
405 crate::errors::AuthError::internal(format!("UTF-8 conversion error: {}", e))
406 })?;
407 Ok(Some(assertion))
408 } else {
409 Ok(None)
410 }
411 }
412 }
413
414 #[derive(Debug, Clone, Serialize, Deserialize)]
421 pub struct SamlMetadata {
422 pub entity_id: String,
423 }
424}
425
426pub mod consent {
429 use crate::errors::Result;
432 use crate::storage::AuthStorage;
433 use serde::{Deserialize, Serialize};
434 use std::collections::HashMap;
435 use std::sync::Arc;
436
437 #[derive(Debug, Clone, Serialize, Deserialize)]
444 pub struct ConsentConfig {
445 pub require_explicit_consent: bool,
447 pub remember_consent_ttl_secs: u64,
449 }
450
451 impl Default for ConsentConfig {
452 fn default() -> Self {
453 Self {
454 require_explicit_consent: true,
455 remember_consent_ttl_secs: 86_400, }
457 }
458 }
459
460 #[derive(Debug, Clone, Serialize, Deserialize)]
470 pub struct ConsentRecord {
471 pub user_id: String,
472 pub client_id: String,
473 pub scopes: Vec<String>,
474 pub granted_at: u64,
475 pub expires_at: Option<u64>,
476 }
477
478 pub struct ConsentManager {
485 config: ConsentConfig,
486 records: HashMap<String, ConsentRecord>,
488 storage: Option<Arc<dyn AuthStorage>>,
489 }
490
491 impl std::fmt::Debug for ConsentManager {
492 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
493 f.debug_struct("ConsentManager")
494 .field("config", &self.config)
495 .field("records", &crate::utils::redact::redacted(&self.records))
496 .field("storage", &self.storage.is_some())
497 .finish()
498 }
499 }
500
501 impl Default for ConsentManager {
502 fn default() -> Self {
503 Self::new(ConsentConfig::default())
504 }
505 }
506
507 impl ConsentManager {
508 pub fn new(config: ConsentConfig) -> Self {
515 Self {
516 config,
517 records: HashMap::new(),
518 storage: None,
519 }
520 }
521
522 pub fn new_with_storage(config: ConsentConfig, storage: Arc<dyn AuthStorage>) -> Self {
530 Self {
531 config,
532 records: HashMap::new(),
533 storage: Some(storage),
534 }
535 }
536
537 fn storage_key(user_id: &str, client_id: &str) -> String {
539 format!("consent:{}:{}", user_id, client_id)
540 }
541
542 pub async fn grant(&mut self, record: ConsentRecord) -> Result<()> {
549 let key = format!("{}:{}", record.user_id, record.client_id);
550 if let Some(storage) = &self.storage {
551 let storage_key = Self::storage_key(&record.user_id, &record.client_id);
552 let ttl = if record.expires_at.is_some() {
553 Some(std::time::Duration::from_secs(
554 self.config.remember_consent_ttl_secs,
555 ))
556 } else {
557 None
558 };
559 let bytes = serde_json::to_vec(&record).map_err(|e| {
560 crate::errors::AuthError::internal(format!(
561 "Consent serialization error: {}",
562 e
563 ))
564 })?;
565 storage.store_kv(&storage_key, &bytes, ttl).await?;
566 }
567 self.records.insert(key, record);
568 Ok(())
569 }
570
571 pub async fn revoke(&mut self, user_id: &str, client_id: &str) -> Result<bool> {
578 let key = format!("{}:{}", user_id, client_id);
579 if let Some(storage) = &self.storage {
580 let storage_key = Self::storage_key(user_id, client_id);
581 let _ = storage.delete_kv(&storage_key).await;
583 }
584 Ok(self.records.remove(&key).is_some())
585 }
586
587 pub async fn has_consent(
595 &mut self,
596 user_id: &str,
597 client_id: &str,
598 scopes: &[String],
599 ) -> Result<bool> {
600 if !self.config.require_explicit_consent {
601 return Ok(true);
602 }
603 let key = format!("{}:{}", user_id, client_id);
604
605 if !self.records.contains_key(&key)
607 && let Some(storage) = &self.storage
608 {
609 let storage_key = Self::storage_key(user_id, client_id);
610 if let Ok(Some(bytes)) = storage.get_kv(&storage_key).await
611 && let Ok(record) = serde_json::from_slice::<ConsentRecord>(&bytes)
612 {
613 self.records.insert(key.clone(), record);
614 }
615 }
616
617 Ok(self
618 .records
619 .get(&key)
620 .is_some_and(|record| scopes.iter().all(|s| record.scopes.contains(s))))
621 }
622
623 pub fn config(&self) -> &ConsentConfig {
631 &self.config
632 }
633 }
634}
635
636pub mod introspection {
637 use serde::{Deserialize, Serialize};
640
641 #[derive(Debug, Clone, Serialize, Deserialize)]
648 pub struct IntrospectionConfig {
649 pub restrict_to_registered_servers: bool,
651 pub include_claims: bool,
653 }
654
655 impl Default for IntrospectionConfig {
656 fn default() -> Self {
657 Self {
658 restrict_to_registered_servers: false,
659 include_claims: true,
660 }
661 }
662 }
663
664 #[derive(Debug, Clone, Serialize, Deserialize)]
672 pub struct IntrospectionResponse {
673 pub active: bool,
674 #[serde(skip_serializing_if = "Option::is_none")]
675 pub scope: Option<String>,
676 #[serde(skip_serializing_if = "Option::is_none")]
677 pub client_id: Option<String>,
678 #[serde(skip_serializing_if = "Option::is_none")]
679 pub sub: Option<String>,
680 #[serde(skip_serializing_if = "Option::is_none")]
681 pub exp: Option<i64>,
682 #[serde(skip_serializing_if = "Option::is_none")]
683 pub iat: Option<i64>,
684 #[serde(skip_serializing_if = "Option::is_none")]
685 pub token_type: Option<String>,
686 }
687
688 impl IntrospectionResponse {
689 pub fn inactive() -> Self {
696 Self {
697 active: false,
698 scope: None,
699 client_id: None,
700 sub: None,
701 exp: None,
702 iat: None,
703 token_type: None,
704 }
705 }
706 }
707
708 #[derive(Debug, Default)]
710 pub struct IntrospectionManager {
711 config: IntrospectionConfig,
712 }
713
714 impl IntrospectionManager {
715 pub fn new(config: IntrospectionConfig) -> Self {
722 Self { config }
723 }
724
725 pub fn config(&self) -> &IntrospectionConfig {
732 &self.config
733 }
734 }
735}
736
737pub mod device_flow_server {
738 use crate::errors::Result;
741 use crate::storage::AuthStorage;
742 use serde::{Deserialize, Serialize};
743 use std::collections::HashMap;
744 use std::sync::Arc;
745
746 #[derive(Debug, Clone, Serialize, Deserialize)]
754 pub struct DeviceFlowConfig {
755 pub user_code_length: usize,
757 pub device_code_ttl_secs: u64,
759 pub polling_interval_secs: u64,
761 pub verification_uri: String,
763 }
764
765 impl Default for DeviceFlowConfig {
766 fn default() -> Self {
767 Self {
768 user_code_length: 8,
769 device_code_ttl_secs: 1800, polling_interval_secs: 5,
771 verification_uri: "https://example.com/device".to_string(),
772 }
773 }
774 }
775
776 #[derive(Clone, Serialize, Deserialize)]
783 pub enum DeviceAuthState {
784 Pending,
785 Authorized { access_token: String },
786 Denied,
787 Expired,
788 }
789
790 impl std::fmt::Debug for DeviceAuthState {
791 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
792 match self {
793 Self::Pending => f.write_str("Pending"),
794 Self::Authorized { access_token } => f
795 .debug_struct("Authorized")
796 .field(
797 "access_token",
798 &crate::utils::redact::redacted(access_token),
799 )
800 .finish(),
801 Self::Denied => f.write_str("Denied"),
802 Self::Expired => f.write_str("Expired"),
803 }
804 }
805 }
806
807 #[derive(Clone, Serialize, Deserialize)]
817 pub struct DeviceAuthRecord {
818 pub device_code: String,
819 pub user_code: String,
820 pub client_id: String,
821 pub scopes: Vec<String>,
822 pub state: DeviceAuthState,
823 pub expires_at: u64,
824 }
825
826 impl std::fmt::Debug for DeviceAuthRecord {
827 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
828 let mut d = f.debug_struct("DeviceAuthRecord");
829 d.field(
830 "device_code",
831 &crate::utils::redact::redacted(&self.device_code),
832 );
833 d.field("user_code", &self.user_code);
834 d.field("client_id", &self.client_id);
835 d.field("scopes", &self.scopes);
836 d.field("state", &self.state);
837 d.field("expires_at", &self.expires_at);
838 d.finish()
839 }
840 }
841
842 pub struct DeviceFlowManager {
850 config: DeviceFlowConfig,
851 records: HashMap<String, DeviceAuthRecord>,
853 storage: Option<Arc<dyn AuthStorage>>,
854 }
855
856 impl std::fmt::Debug for DeviceFlowManager {
857 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
858 f.debug_struct("DeviceFlowManager")
859 .field("config", &self.config)
860 .field("records", &crate::utils::redact::redacted(&self.records))
861 .field("storage", &self.storage.is_some())
862 .finish()
863 }
864 }
865
866 impl Default for DeviceFlowManager {
867 fn default() -> Self {
868 Self::new(DeviceFlowConfig::default())
869 }
870 }
871
872 impl DeviceFlowManager {
873 pub fn new(config: DeviceFlowConfig) -> Self {
880 Self {
881 config,
882 records: HashMap::new(),
883 storage: None,
884 }
885 }
886
887 pub fn new_with_storage(config: DeviceFlowConfig, storage: Arc<dyn AuthStorage>) -> Self {
895 Self {
896 config,
897 records: HashMap::new(),
898 storage: Some(storage),
899 }
900 }
901
902 fn storage_key(device_code: &str) -> String {
904 format!("device_flow:{}", device_code)
905 }
906
907 pub async fn register(&mut self, record: DeviceAuthRecord) -> Result<()> {
914 if let Some(storage) = &self.storage {
915 let key = Self::storage_key(&record.device_code);
916 let ttl = Some(std::time::Duration::from_secs(
917 self.config.device_code_ttl_secs,
918 ));
919 let bytes = serde_json::to_vec(&record).map_err(|e| {
920 crate::errors::AuthError::internal(format!(
921 "DeviceFlowRecord serialization error: {}",
922 e
923 ))
924 })?;
925 storage.store_kv(&key, &bytes, ttl).await?;
926 }
927 self.records.insert(record.device_code.clone(), record);
928 Ok(())
929 }
930
931 pub async fn get(&mut self, device_code: &str) -> Result<Option<DeviceAuthRecord>> {
940 if let Some(record) = self.records.get(device_code) {
941 return Ok(Some(record.clone()));
942 }
943 if let Some(storage) = &self.storage {
944 let key = Self::storage_key(device_code);
945 if let Some(bytes) = storage.get_kv(&key).await?
946 && let Ok(record) = serde_json::from_slice::<DeviceAuthRecord>(&bytes)
947 {
948 self.records.insert(device_code.to_string(), record.clone());
949 return Ok(Some(record));
950 }
951 }
952 Ok(None)
953 }
954
955 pub async fn approve(&mut self, user_code: &str, access_token: String) -> Result<bool> {
962 let device_code = self
964 .records
965 .values()
966 .find(|r| r.user_code == user_code)
967 .map(|r| r.device_code.clone());
968
969 if let Some(dc) = device_code {
970 if let Some(record) = self.records.get_mut(&dc) {
971 record.state = DeviceAuthState::Authorized {
972 access_token: access_token.clone(),
973 };
974 if let Some(storage) = &self.storage {
975 let key = Self::storage_key(&dc);
976 let bytes = serde_json::to_vec(&*record).map_err(|e| {
977 crate::errors::AuthError::internal(format!(
978 "DeviceFlowRecord serialization error: {}",
979 e
980 ))
981 })?;
982 storage.store_kv(&key, &bytes, None).await?;
984 }
985 }
986 return Ok(true);
987 }
988 Ok(false)
989 }
990
991 pub fn config(&self) -> &DeviceFlowConfig {
999 &self.config
1000 }
1001 }
1002}
1003
1004#[cfg(test)]
1005mod tests {
1006 use super::*;
1007 use crate::storage::MemoryStorage;
1008 use std::sync::Arc;
1009 use std::time::{SystemTime, UNIX_EPOCH};
1010
1011 fn now_secs() -> u64 {
1012 SystemTime::now()
1013 .duration_since(UNIX_EPOCH)
1014 .unwrap()
1015 .as_secs()
1016 }
1017
1018 #[tokio::test]
1021 async fn test_jwt_server_store_and_get_metadata() {
1022 let storage: Arc<dyn crate::storage::AuthStorage> = Arc::new(MemoryStorage::new());
1023 let config = jwt_server::JwtServerConfig {
1024 issuer: "https://auth.example.com".into(),
1025 key_id: "key_1".into(),
1026 };
1027 let server = jwt_server::JwtServer::new(config, storage).await.unwrap();
1028 server.initialize().await.unwrap();
1029
1030 let wkc = server.get_well_known_jwt_configuration().await.unwrap();
1031 assert_eq!(wkc.issuer, "https://auth.example.com");
1032
1033 server.store_jwt_metadata(&wkc).await.unwrap();
1034 let retrieved = server.get_stored_metadata().await.unwrap();
1035 assert!(retrieved.is_some());
1036 }
1037
1038 #[tokio::test]
1039 async fn test_jwt_server_store_signing_key() {
1040 let storage: Arc<dyn crate::storage::AuthStorage> = Arc::new(MemoryStorage::new());
1041 let config = jwt_server::JwtServerConfig {
1042 issuer: "https://auth.example.com".into(),
1043 key_id: "key_2".into(),
1044 };
1045 let server = jwt_server::JwtServer::new(config, storage).await.unwrap();
1046 server.store_signing_key("test-key-data").await.unwrap();
1047 }
1048
1049 #[tokio::test]
1052 async fn test_api_gateway_store_and_get_route() {
1053 let storage: Arc<dyn crate::storage::AuthStorage> = Arc::new(MemoryStorage::new());
1054 let config = api_gateway::ApiGatewayConfig {
1055 name: "test-gw".into(),
1056 };
1057 let gw = api_gateway::ApiGateway::new(config, storage).await.unwrap();
1058 gw.initialize().await.unwrap();
1059 assert_eq!(gw.get_gateway_name(), "test-gw");
1060
1061 gw.store_route_config("/api/v1/users", r#"{"auth":"required"}"#)
1062 .await
1063 .unwrap();
1064 let route = gw.get_route_config("/api/v1/users").await.unwrap();
1065 assert!(route.is_some());
1066 }
1067
1068 #[tokio::test]
1069 async fn test_api_gateway_get_route_not_found() {
1070 let storage: Arc<dyn crate::storage::AuthStorage> = Arc::new(MemoryStorage::new());
1071 let config = api_gateway::ApiGatewayConfig { name: "gw2".into() };
1072 let gw = api_gateway::ApiGateway::new(config, storage).await.unwrap();
1073 assert!(gw.get_route_config("/nope").await.unwrap().is_none());
1074 }
1075
1076 #[tokio::test]
1079 async fn test_saml_idp_store_and_get_assertion() {
1080 let storage: Arc<dyn crate::storage::AuthStorage> = Arc::new(MemoryStorage::new());
1081 let config = saml_idp::SamlIdpConfig {
1082 entity_id: "urn:example:idp".into(),
1083 };
1084 let saml = saml_idp::SamlIdentityProvider::new(config, storage)
1085 .await
1086 .unwrap();
1087 saml.initialize().await.unwrap();
1088 saml.store_assertion("assert_1", "<Assertion/>")
1089 .await
1090 .unwrap();
1091 let a = saml.get_assertion("assert_1").await.unwrap();
1092 assert_eq!(a.as_deref(), Some("<Assertion/>"));
1093 }
1094
1095 #[tokio::test]
1096 async fn test_saml_idp_get_assertion_not_found() {
1097 let storage: Arc<dyn crate::storage::AuthStorage> = Arc::new(MemoryStorage::new());
1098 let config = saml_idp::SamlIdpConfig {
1099 entity_id: "urn:example:idp2".into(),
1100 };
1101 let saml = saml_idp::SamlIdentityProvider::new(config, storage)
1102 .await
1103 .unwrap();
1104 assert!(saml.get_assertion("nope").await.unwrap().is_none());
1105 }
1106
1107 #[tokio::test]
1108 async fn test_saml_idp_metadata() {
1109 let storage: Arc<dyn crate::storage::AuthStorage> = Arc::new(MemoryStorage::new());
1110 let config = saml_idp::SamlIdpConfig {
1111 entity_id: "urn:example:idp3".into(),
1112 };
1113 let saml = saml_idp::SamlIdentityProvider::new(config, storage)
1114 .await
1115 .unwrap();
1116 let meta = saml.get_metadata().await.unwrap();
1117 assert_eq!(meta.entity_id, "urn:example:idp3");
1118 }
1119
1120 #[tokio::test]
1123 async fn test_consent_grant_and_check() {
1124 let config = consent::ConsentConfig {
1125 require_explicit_consent: true,
1126 remember_consent_ttl_secs: 3600,
1127 };
1128 let mut cm = consent::ConsentManager::new(config);
1129 let record = consent::ConsentRecord {
1130 user_id: "user1".into(),
1131 client_id: "client1".into(),
1132 scopes: vec!["read".into(), "write".into()],
1133 granted_at: now_secs(),
1134 expires_at: Some(now_secs() + 3600),
1135 };
1136 cm.grant(record).await.unwrap();
1137 assert!(
1138 cm.has_consent("user1", "client1", &["read".into()])
1139 .await
1140 .unwrap()
1141 );
1142 }
1143
1144 #[tokio::test]
1145 async fn test_consent_no_consent_by_default() {
1146 let config = consent::ConsentConfig {
1147 require_explicit_consent: true,
1148 remember_consent_ttl_secs: 3600,
1149 };
1150 let mut cm = consent::ConsentManager::new(config);
1151 assert!(
1152 !cm.has_consent("user1", "client1", &["read".into()])
1153 .await
1154 .unwrap()
1155 );
1156 }
1157
1158 #[tokio::test]
1159 async fn test_consent_revoke() {
1160 let config = consent::ConsentConfig {
1161 require_explicit_consent: true,
1162 remember_consent_ttl_secs: 3600,
1163 };
1164 let mut cm = consent::ConsentManager::new(config);
1165 cm.grant(consent::ConsentRecord {
1166 user_id: "user2".into(),
1167 client_id: "client2".into(),
1168 scopes: vec!["read".into()],
1169 granted_at: now_secs(),
1170 expires_at: None,
1171 })
1172 .await
1173 .unwrap();
1174 let revoked = cm.revoke("user2", "client2").await.unwrap();
1175 assert!(revoked);
1176 assert!(
1177 !cm.has_consent("user2", "client2", &["read".into()])
1178 .await
1179 .unwrap()
1180 );
1181 }
1182
1183 #[tokio::test]
1184 async fn test_consent_revoke_nonexistent() {
1185 let config = consent::ConsentConfig {
1186 require_explicit_consent: true,
1187 remember_consent_ttl_secs: 3600,
1188 };
1189 let mut cm = consent::ConsentManager::new(config);
1190 let revoked = cm.revoke("ghost", "ghost_client").await.unwrap();
1191 assert!(!revoked);
1192 }
1193
1194 #[tokio::test]
1195 async fn test_consent_with_storage() {
1196 let storage: Arc<dyn crate::storage::AuthStorage> = Arc::new(MemoryStorage::new());
1197 let config = consent::ConsentConfig {
1198 require_explicit_consent: true,
1199 remember_consent_ttl_secs: 3600,
1200 };
1201 let mut cm = consent::ConsentManager::new_with_storage(config, storage);
1202 cm.grant(consent::ConsentRecord {
1203 user_id: "user3".into(),
1204 client_id: "client3".into(),
1205 scopes: vec!["openid".into()],
1206 granted_at: now_secs(),
1207 expires_at: None,
1208 })
1209 .await
1210 .unwrap();
1211 assert!(
1212 cm.has_consent("user3", "client3", &["openid".into()])
1213 .await
1214 .unwrap()
1215 );
1216 }
1217
1218 #[tokio::test]
1221 async fn test_device_flow_register_and_get() {
1222 let config = device_flow_server::DeviceFlowConfig {
1223 user_code_length: 8,
1224 device_code_ttl_secs: 300,
1225 polling_interval_secs: 5,
1226 verification_uri: "https://auth.example.com/device".into(),
1227 };
1228 let mut df = device_flow_server::DeviceFlowManager::new(config);
1229 df.register(device_flow_server::DeviceAuthRecord {
1230 device_code: "dev_code_1".into(),
1231 user_code: "ABCD-EFGH".into(),
1232 client_id: "mobile_app".into(),
1233 scopes: vec!["read".into()],
1234 state: device_flow_server::DeviceAuthState::Pending,
1235 expires_at: now_secs() + 300,
1236 })
1237 .await
1238 .unwrap();
1239 let record = df.get("dev_code_1").await.unwrap();
1240 assert!(record.is_some());
1241 assert_eq!(record.unwrap().user_code, "ABCD-EFGH");
1242 }
1243
1244 #[tokio::test]
1245 async fn test_device_flow_get_not_found() {
1246 let config = device_flow_server::DeviceFlowConfig {
1247 user_code_length: 8,
1248 device_code_ttl_secs: 300,
1249 polling_interval_secs: 5,
1250 verification_uri: "https://auth.example.com/device".into(),
1251 };
1252 let mut df = device_flow_server::DeviceFlowManager::new(config);
1253 assert!(df.get("nonexistent").await.unwrap().is_none());
1254 }
1255
1256 #[tokio::test]
1257 async fn test_device_flow_approve() {
1258 let config = device_flow_server::DeviceFlowConfig {
1259 user_code_length: 8,
1260 device_code_ttl_secs: 300,
1261 polling_interval_secs: 5,
1262 verification_uri: "https://auth.example.com/device".into(),
1263 };
1264 let mut df = device_flow_server::DeviceFlowManager::new(config);
1265 df.register(device_flow_server::DeviceAuthRecord {
1266 device_code: "dev_code_2".into(),
1267 user_code: "WXYZ-1234".into(),
1268 client_id: "tv_app".into(),
1269 scopes: vec!["read".into()],
1270 state: device_flow_server::DeviceAuthState::Pending,
1271 expires_at: now_secs() + 300,
1272 })
1273 .await
1274 .unwrap();
1275 let approved = df
1276 .approve("WXYZ-1234", "access_token_here".into())
1277 .await
1278 .unwrap();
1279 assert!(approved);
1280
1281 let record = df.get("dev_code_2").await.unwrap().unwrap();
1282 matches!(
1283 record.state,
1284 device_flow_server::DeviceAuthState::Authorized { .. }
1285 );
1286 }
1287
1288 #[tokio::test]
1289 async fn test_device_flow_approve_nonexistent() {
1290 let config = device_flow_server::DeviceFlowConfig {
1291 user_code_length: 8,
1292 device_code_ttl_secs: 300,
1293 polling_interval_secs: 5,
1294 verification_uri: "https://auth.example.com/device".into(),
1295 };
1296 let mut df = device_flow_server::DeviceFlowManager::new(config);
1297 let approved = df.approve("NO_CODE", "token".into()).await.unwrap();
1298 assert!(!approved);
1299 }
1300
1301 #[tokio::test]
1302 async fn test_device_flow_with_storage() {
1303 let storage: Arc<dyn crate::storage::AuthStorage> = Arc::new(MemoryStorage::new());
1304 let config = device_flow_server::DeviceFlowConfig {
1305 user_code_length: 8,
1306 device_code_ttl_secs: 300,
1307 polling_interval_secs: 5,
1308 verification_uri: "https://auth.example.com/device".into(),
1309 };
1310 let mut df = device_flow_server::DeviceFlowManager::new_with_storage(config, storage);
1311 df.register(device_flow_server::DeviceAuthRecord {
1312 device_code: "stored_code".into(),
1313 user_code: "ST0R-ED00".into(),
1314 client_id: "app".into(),
1315 scopes: vec![],
1316 state: device_flow_server::DeviceAuthState::Pending,
1317 expires_at: now_secs() + 300,
1318 })
1319 .await
1320 .unwrap();
1321 let record = df.get("stored_code").await.unwrap();
1322 assert!(record.is_some());
1323 }
1324
1325 #[test]
1328 fn test_introspection_inactive_response() {
1329 let resp = introspection::IntrospectionResponse::inactive();
1330 assert!(!resp.active);
1331 }
1332}