1use crate::errors::{AuthError, Result};
78use crate::server::oidc::oidc_session_management::SessionManager;
79
80use async_trait::async_trait;
81use chrono::{DateTime, Duration, Utc};
82use serde::{Deserialize, Serialize};
83use std::collections::{HashMap, HashSet};
84use std::sync::Arc;
85use uuid::Uuid;
86
87#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct RarConfig {
90 pub max_authorization_details: usize,
92
93 pub supported_types: Vec<String>,
95
96 pub require_explicit_consent: bool,
98
99 pub max_resource_depth: usize,
101
102 pub default_lifetime: Duration,
104
105 pub enable_resource_discovery: bool,
107
108 pub validation_rules: Vec<RarValidationRule>,
110
111 pub type_action_mapping: HashMap<String, Vec<String>>,
113}
114
115impl Default for RarConfig {
116 fn default() -> Self {
117 let mut type_action_mapping = HashMap::new();
118 type_action_mapping.insert(
119 "file_access".to_string(),
120 vec![
121 "read".to_string(),
122 "write".to_string(),
123 "delete".to_string(),
124 ],
125 );
126 type_action_mapping.insert(
127 "api_access".to_string(),
128 vec![
129 "read".to_string(),
130 "write".to_string(),
131 "execute".to_string(),
132 ],
133 );
134 type_action_mapping.insert(
135 "database_access".to_string(),
136 vec![
137 "select".to_string(),
138 "insert".to_string(),
139 "update".to_string(),
140 "delete".to_string(),
141 ],
142 );
143
144 Self {
145 max_authorization_details: 10,
146 supported_types: vec![
147 "file_access".to_string(),
148 "api_access".to_string(),
149 "database_access".to_string(),
150 "payment_initiation".to_string(),
151 "account_information".to_string(),
152 ],
153 require_explicit_consent: true,
154 max_resource_depth: 5,
155 default_lifetime: Duration::try_hours(1).unwrap_or(Duration::zero()),
156 enable_resource_discovery: false,
157 validation_rules: Vec::new(),
158 type_action_mapping,
159 }
160 }
161}
162
163#[derive(Clone, Serialize, Deserialize, Default)]
165pub struct RarAuthorizationRequest {
166 pub client_id: String,
168
169 pub response_type: String,
171
172 pub redirect_uri: Option<String>,
174
175 pub authorization_details: Vec<AuthorizationDetail>,
177
178 pub scope: Option<String>,
180
181 pub state: Option<String>,
183
184 pub code_challenge: Option<String>,
186
187 pub code_challenge_method: Option<String>,
189
190 pub custom_parameters: HashMap<String, serde_json::Value>,
192}
193
194impl std::fmt::Debug for RarAuthorizationRequest {
195 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196 let mut d = f.debug_struct("RarAuthorizationRequest");
197 d.field("client_id", &self.client_id);
198 d.field("response_type", &self.response_type);
199 d.field("redirect_uri", &self.redirect_uri);
200 d.field("authorization_details", &self.authorization_details);
201 d.field("scope", &self.scope);
202 d.field("state", &self.state);
203 d.field("code_challenge", &self.code_challenge);
204 d.field("code_challenge_method", &self.code_challenge_method);
205 d.field(
206 "custom_parameters",
207 &crate::utils::redact::redacted(&self.custom_parameters),
208 );
209 d.finish()
210 }
211}
212
213#[derive(Debug, Clone, Serialize, Deserialize, Default)]
215pub struct AuthorizationDetail {
216 #[serde(rename = "type")]
218 pub type_: String,
219
220 pub locations: Option<Vec<String>>,
222
223 pub actions: Option<Vec<String>>,
225
226 pub datatypes: Option<Vec<String>>,
228
229 pub identifier: Option<String>,
231
232 pub privileges: Option<Vec<String>>,
234
235 #[serde(flatten)]
237 pub additional_fields: HashMap<String, serde_json::Value>,
238}
239
240#[derive(Debug, Clone, Serialize, Deserialize)]
242pub struct RarValidationRule {
243 pub id: String,
245
246 pub applicable_type: String,
248
249 pub required_fields: Vec<String>,
251
252 pub field_constraints: HashMap<String, Vec<String>>,
254
255 pub validation_expression: Option<String>,
257}
258
259#[derive(Debug, Clone, Serialize, Deserialize)]
261pub struct RarValidationResult {
262 pub valid: bool,
264
265 pub errors: HashMap<usize, Vec<String>>,
267
268 pub warnings: HashMap<usize, Vec<String>>,
270
271 pub normalized_details: Vec<AuthorizationDetail>,
273}
274
275#[derive(Debug, Clone, Serialize, Deserialize)]
277pub struct RarAuthorizationDecision {
278 pub id: Uuid,
280
281 pub request_id: String,
283
284 pub client_id: String,
286
287 pub subject: String,
289
290 pub timestamp: DateTime<Utc>,
292
293 pub decision: RarDecisionType,
295
296 pub detail_decisions: Vec<RarDetailDecision>,
298
299 pub granted_permissions: RarPermissionGrant,
301
302 pub expires_at: DateTime<Utc>,
304
305 pub conditions: Vec<RarCondition>,
307}
308
309#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
311#[serde(rename_all = "snake_case")]
312pub enum RarDecisionType {
313 Granted,
315
316 PartiallyGranted,
318
319 Denied,
321
322 RequiresApproval,
324
325 RequiresStepUp,
327}
328
329#[derive(Debug, Clone, Serialize, Deserialize)]
331pub struct RarDetailDecision {
332 pub detail_index: usize,
334
335 pub detail_type: String,
337
338 pub decision: RarDecisionType,
340
341 pub granted_actions: Vec<String>,
343
344 pub granted_locations: Vec<String>,
346
347 pub granted_privileges: Vec<String>,
349
350 pub reason: Option<String>,
352
353 pub restrictions: Vec<RarRestriction>,
355}
356
357#[derive(Debug, Clone, Serialize, Deserialize)]
359pub struct RarPermissionGrant {
360 pub resource_access: HashMap<String, Vec<RarResourceAccess>>,
362
363 pub effective_scopes: Vec<String>,
365
366 pub max_privilege_level: String,
368
369 pub resource_count: usize,
371
372 pub metadata: HashMap<String, serde_json::Value>,
374}
375
376#[derive(Debug, Clone, Serialize, Deserialize)]
378pub struct RarResourceAccess {
379 pub resource: String,
381
382 pub actions: Vec<String>,
384
385 pub datatypes: Vec<String>,
387
388 pub privilege: Option<String>,
390
391 pub restrictions: Vec<RarRestriction>,
393}
394
395#[derive(Debug, Clone, Serialize, Deserialize)]
397#[serde(tag = "type", rename_all = "snake_case")]
398pub enum RarCondition {
399 TimeRestriction {
401 start_time: Option<DateTime<Utc>>,
402 end_time: DateTime<Utc>,
403 },
404
405 LocationRestriction {
407 allowed_locations: Vec<String>,
408 location_type: String, },
410
411 UsageLimit {
413 max_uses: u32,
414 current_uses: u32,
415 reset_period: Option<Duration>,
416 },
417
418 ApprovalRequired {
420 approver_roles: Vec<String>,
421 approval_timeout: Duration,
422 },
423
424 Custom {
426 condition_type: String,
427 parameters: HashMap<String, serde_json::Value>,
428 },
429}
430
431#[derive(Debug, Clone, Serialize, Deserialize)]
433#[serde(tag = "type", rename_all = "snake_case")]
434pub enum RarRestriction {
435 RateLimit {
437 requests_per_minute: u32,
438 burst_limit: u32,
439 },
440
441 DataVolumeLimit { max_bytes: u64, period: Duration },
443
444 IpRestriction {
446 allowed_ips: Vec<String>,
447 allowed_cidrs: Vec<String>,
448 },
449
450 TimeOfDayRestriction {
452 allowed_hours: Vec<u8>, timezone: String,
454 },
455
456 Custom {
458 restriction_type: String,
459 parameters: HashMap<String, serde_json::Value>,
460 },
461}
462
463#[derive(Debug, Clone, Serialize, Deserialize)]
465pub struct RarResourceDiscoveryRequest {
466 pub client_id: String,
468
469 pub resource_type: String,
471
472 pub search_criteria: HashMap<String, serde_json::Value>,
474
475 pub max_results: Option<usize>,
477}
478
479#[derive(Debug, Clone, Serialize, Deserialize)]
481pub struct RarResourceDiscoveryResponse {
482 pub resources: Vec<RarDiscoveredResource>,
484
485 pub has_more: bool,
487
488 pub continuation_token: Option<String>,
490}
491
492#[derive(Debug, Clone, Serialize, Deserialize)]
494pub struct RarDiscoveredResource {
495 pub identifier: String,
497
498 pub location: String,
500
501 pub resource_type: String,
503
504 pub available_actions: Vec<String>,
506
507 pub metadata: HashMap<String, serde_json::Value>,
509
510 pub required_privileges: Vec<String>,
512}
513
514#[async_trait]
516pub trait RarAuthorizationProcessor: Send + Sync {
517 async fn process_authorization_detail(
519 &self,
520 detail: &AuthorizationDetail,
521 client_id: &str,
522 subject: &str,
523 ) -> Result<RarDetailDecision>;
524
525 async fn is_client_authorized(&self, client_id: &str, resource_type: &str) -> Result<bool>;
527
528 fn get_supported_actions(&self, resource_type: &str) -> Vec<String>;
530}
531
532#[derive(Clone)]
534pub struct RarSessionContext {
535 pub session_id: String,
537
538 pub is_new_session: bool,
540
541 pub session_state: crate::server::oidc::oidc_session_management::SessionState,
543
544 pub browser_session_id: String,
546
547 pub metadata: HashMap<String, String>,
549}
550
551impl std::fmt::Debug for RarSessionContext {
552 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
553 let mut d = f.debug_struct("RarSessionContext");
554 d.field(
555 "session_id",
556 &crate::utils::redact::redacted(&self.session_id),
557 );
558 d.field("is_new_session", &self.is_new_session);
559 d.field("session_state", &self.session_state);
560 d.field(
561 "browser_session_id",
562 &crate::utils::redact::redacted(&self.browser_session_id),
563 );
564 d.field("metadata", &self.metadata);
565 d.finish()
566 }
567}
568
569#[derive(Clone)]
571pub struct RarSessionAuthorizationContext {
572 pub session_id: String,
574
575 pub subject: String,
577
578 pub client_id: String,
580
581 pub session_state: crate::server::oidc::oidc_session_management::SessionState,
583
584 pub active_authorizations: Vec<String>,
586
587 pub created_at: DateTime<Utc>,
589
590 pub last_activity: DateTime<Utc>,
592}
593
594impl std::fmt::Debug for RarSessionAuthorizationContext {
595 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
596 let mut d = f.debug_struct("RarSessionAuthorizationContext");
597 d.field(
598 "session_id",
599 &crate::utils::redact::redacted(&self.session_id),
600 );
601 d.field("subject", &self.subject);
602 d.field("client_id", &self.client_id);
603 d.field("session_state", &self.session_state);
604 d.field("active_authorizations", &self.active_authorizations);
605 d.field("created_at", &self.created_at);
606 d.field("last_activity", &self.last_activity);
607 d.finish()
608 }
609}
610
611pub struct RarManager {
613 config: RarConfig,
615
616 session_manager: Arc<SessionManager>,
618
619 processors: HashMap<String, Arc<dyn RarAuthorizationProcessor>>,
621
622 decisions: Arc<tokio::sync::RwLock<HashMap<String, RarAuthorizationDecision>>>,
624
625 resource_cache: Arc<tokio::sync::RwLock<HashMap<String, Vec<RarDiscoveredResource>>>>,
627}
628
629impl RarManager {
630 pub fn new(config: RarConfig, session_manager: Arc<SessionManager>) -> Self {
632 Self {
633 config,
634 session_manager,
635 processors: HashMap::new(),
636 decisions: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
637 resource_cache: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
638 }
639 }
640
641 pub fn register_processor(
643 &mut self,
644 resource_type: String,
645 processor: Arc<dyn RarAuthorizationProcessor>,
646 ) {
647 self.processors.insert(resource_type, processor);
648 }
649
650 pub async fn validate_authorization_request(
652 &self,
653 request: &RarAuthorizationRequest,
654 ) -> Result<RarValidationResult> {
655 let mut errors = HashMap::new();
656 let mut warnings = HashMap::new();
657 let mut normalized_details = Vec::new();
658
659 if request.authorization_details.len() > self.config.max_authorization_details {
661 errors.insert(
662 0,
663 vec![format!(
664 "Too many authorization details: {} > {}",
665 request.authorization_details.len(),
666 self.config.max_authorization_details
667 )],
668 );
669 }
670
671 for (index, detail) in request.authorization_details.iter().enumerate() {
673 let mut detail_errors = Vec::new();
674 let mut detail_warnings = Vec::new();
675
676 if !self.config.supported_types.contains(&detail.type_) {
678 detail_errors.push(format!("Unsupported type: {}", detail.type_));
679 } else {
680 if let Some(actions) = &detail.actions
682 && let Some(supported_actions) =
683 self.config.type_action_mapping.get(&detail.type_)
684 {
685 for action in actions {
686 if !supported_actions.contains(action) {
687 detail_warnings.push(format!(
688 "Action '{}' not typically supported for type '{}'",
689 action, detail.type_
690 ));
691 }
692 }
693 }
694
695 for rule in &self.config.validation_rules {
697 if rule.applicable_type == detail.type_ {
698 self.apply_validation_rule(rule, detail, &mut detail_errors);
699 }
700 }
701
702 let normalized = self.normalize_authorization_detail(detail).await?;
704 normalized_details.push(normalized);
705 }
706
707 if !detail_errors.is_empty() {
708 errors.insert(index, detail_errors);
709 }
710 if !detail_warnings.is_empty() {
711 warnings.insert(index, detail_warnings);
712 }
713 }
714
715 let valid = errors.is_empty();
716
717 Ok(RarValidationResult {
718 valid,
719 errors,
720 warnings,
721 normalized_details,
722 })
723 }
724
725 pub async fn process_authorization_request(
727 &self,
728 request: RarAuthorizationRequest,
729 subject: &str,
730 ) -> Result<RarAuthorizationDecision> {
731 let validation_result = self.validate_authorization_request(&request).await?;
733 if !validation_result.valid {
734 return Err(AuthError::InvalidRequest(
735 "Invalid authorization request".to_string(),
736 ));
737 }
738
739 let session_context = self
741 .establish_authorization_session(&request.client_id, subject)
742 .await?;
743
744 let decision_id = Uuid::new_v4();
745 let mut detail_decisions = Vec::new();
746 let mut overall_decision = RarDecisionType::Granted;
747
748 for detail in request.authorization_details.iter() {
750 let detail_decision = self
751 .process_single_detail(detail, &request.client_id, subject)
752 .await?;
753
754 match (&overall_decision, &detail_decision.decision) {
756 (RarDecisionType::Granted, RarDecisionType::Denied) => {
757 overall_decision = RarDecisionType::PartiallyGranted;
758 }
759 (RarDecisionType::Granted, RarDecisionType::RequiresStepUp) => {
760 overall_decision = RarDecisionType::RequiresStepUp;
761 }
762 (RarDecisionType::PartiallyGranted, RarDecisionType::RequiresStepUp) => {
763 overall_decision = RarDecisionType::RequiresStepUp;
764 }
765 _ => {}
766 }
767
768 detail_decisions.push(detail_decision);
769 }
770
771 let granted_permissions = self.generate_permission_grant(&detail_decisions);
773
774 let expires_at = self
776 .calculate_authorization_expiration(&session_context)
777 .await?;
778
779 let decision = RarAuthorizationDecision {
780 id: decision_id,
781 request_id: format!("req_{}", decision_id),
782 client_id: request.client_id.clone(),
783 subject: subject.to_string(),
784 timestamp: Utc::now(),
785 decision: overall_decision,
786 detail_decisions,
787 granted_permissions,
788 expires_at,
789 conditions: Vec::new(), };
791
792 self.store_decision_with_session(&decision, &session_context)
794 .await?;
795
796 Ok(decision)
797 }
798
799 pub async fn discover_resources(
801 &self,
802 request: RarResourceDiscoveryRequest,
803 ) -> Result<RarResourceDiscoveryResponse> {
804 if !self.config.enable_resource_discovery {
805 return Err(AuthError::InvalidRequest(
806 "Resource discovery is not enabled".to_string(),
807 ));
808 }
809
810 {
812 let cache = self.resource_cache.read().await;
813 if let Some(cached_resources) = cache.get(&request.resource_type) {
814 let max_results = request.max_results.unwrap_or(100);
815 let resources = cached_resources.iter().take(max_results).cloned().collect();
816
817 return Ok(RarResourceDiscoveryResponse {
818 resources,
819 has_more: cached_resources.len() > max_results,
820 continuation_token: None,
821 });
822 }
823 }
824
825 let resources = if request.client_id == "trusted_client" {
828 vec![RarDiscoveredResource {
829 identifier: "protected_resource_1".to_string(),
830 location: "https://api.example.com/protected".to_string(),
831 resource_type: request.resource_type.clone(),
832 available_actions: vec!["read".to_string(), "write".to_string()],
833 metadata: std::collections::HashMap::new(),
834 required_privileges: vec!["protected:access".to_string()],
835 }]
836 } else {
837 Vec::new()
839 };
840
841 Ok(RarResourceDiscoveryResponse {
842 resources,
843 has_more: false,
844 continuation_token: None,
845 })
846 }
847
848 pub async fn get_authorization_decision(
850 &self,
851 request_id: &str,
852 ) -> Result<Option<RarAuthorizationDecision>> {
853 let decisions = self.decisions.read().await;
854 Ok(decisions.get(request_id).cloned())
855 }
856
857 fn apply_validation_rule(
859 &self,
860 rule: &RarValidationRule,
861 detail: &AuthorizationDetail,
862 errors: &mut Vec<String>,
863 ) {
864 for required_field in &rule.required_fields {
866 match required_field.as_str() {
867 "actions" => {
868 if detail.actions.is_none() || detail.actions.as_ref().unwrap().is_empty() {
869 errors.push(format!("Required field '{}' is missing", required_field));
870 }
871 }
872 "locations" => {
873 if detail.locations.is_none() || detail.locations.as_ref().unwrap().is_empty() {
874 errors.push(format!("Required field '{}' is missing", required_field));
875 }
876 }
877 "identifier" => {
878 if detail.identifier.is_none() {
879 errors.push(format!("Required field '{}' is missing", required_field));
880 }
881 }
882 _ => {
883 if !detail.additional_fields.contains_key(required_field) {
885 errors.push(format!("Required field '{}' is missing", required_field));
886 }
887 }
888 }
889 }
890
891 for (field, valid_values) in &rule.field_constraints {
893 match field.as_str() {
894 "actions" => {
895 if let Some(actions) = &detail.actions {
896 for action in actions {
897 if !valid_values.contains(action) {
898 errors.push(format!(
899 "Invalid value '{}' for field 'actions'",
900 action
901 ));
902 }
903 }
904 }
905 }
906 _ => {
907 if let Some(value) = detail.additional_fields.get(field)
909 && let Some(str_value) = value.as_str()
910 && !valid_values.contains(&str_value.to_string())
911 {
912 errors.push(format!(
913 "Invalid value '{}' for field '{}'",
914 str_value, field
915 ));
916 }
917 }
918 }
919 }
920 }
921
922 async fn normalize_authorization_detail(
924 &self,
925 detail: &AuthorizationDetail,
926 ) -> Result<AuthorizationDetail> {
927 let mut normalized = detail.clone();
928
929 if let Some(actions) = &mut normalized.actions {
931 actions.sort();
932 actions.dedup();
933 }
934
935 if let Some(locations) = &mut normalized.locations {
937 let mut expanded_locations = Vec::new();
939 for location in locations.iter() {
940 if location.contains('*') {
941 let normalized_pattern = location.replace("**", "*").replace("//", "/");
943 expanded_locations.push(normalized_pattern);
944 } else if location.starts_with("./") || location.starts_with("../") {
945 let absolute_path = if location.starts_with("./") {
947 location.strip_prefix("./").unwrap_or(location).to_string()
948 } else {
949 location.replace("../", "").to_string()
951 };
952 expanded_locations.push(absolute_path);
953 } else {
954 expanded_locations.push(location.clone());
955 }
956 }
957 *locations = expanded_locations;
958 locations.sort();
959 locations.dedup();
960 }
961
962 Ok(normalized)
963 }
964
965 async fn process_single_detail(
967 &self,
968 detail: &AuthorizationDetail,
969 client_id: &str,
970 subject: &str,
971 ) -> Result<RarDetailDecision> {
972 if let Some(processor) = self.processors.get(&detail.type_) {
974 processor
975 .process_authorization_detail(detail, client_id, subject)
976 .await
977 } else {
978 let granted_actions = detail.actions.clone().unwrap_or_default();
980 let granted_locations = detail.locations.clone().unwrap_or_default();
981 let granted_privileges = detail.privileges.clone().unwrap_or_default();
982
983 Ok(RarDetailDecision {
984 detail_index: 0, detail_type: detail.type_.clone(),
986 decision: RarDecisionType::Granted,
987 granted_actions,
988 granted_locations,
989 granted_privileges,
990 reason: Some("Default approval".to_string()),
991 restrictions: Vec::new(),
992 })
993 }
994 }
995
996 fn generate_permission_grant(
998 &self,
999 detail_decisions: &[RarDetailDecision],
1000 ) -> RarPermissionGrant {
1001 let mut resource_access: HashMap<String, Vec<RarResourceAccess>> = HashMap::new();
1002 let mut effective_scopes = HashSet::new();
1003 let mut max_privilege_level = String::from("user");
1004 let mut resource_count = 0;
1005
1006 for decision in detail_decisions {
1007 if decision.decision == RarDecisionType::Granted {
1008 let mut type_resources = Vec::new();
1009
1010 for location in &decision.granted_locations {
1011 type_resources.push(RarResourceAccess {
1012 resource: location.clone(),
1013 actions: decision.granted_actions.clone(),
1014 datatypes: Vec::new(), privilege: decision.granted_privileges.first().cloned(),
1016 restrictions: decision.restrictions.clone(),
1017 });
1018 resource_count += 1;
1019 }
1020
1021 for action in &decision.granted_actions {
1023 effective_scopes.insert(format!("{}:{}", decision.detail_type, action));
1024 }
1025
1026 resource_access.insert(decision.detail_type.clone(), type_resources);
1027
1028 for privilege in &decision.granted_privileges {
1030 if privilege == "admin" || privilege == "owner" {
1031 max_privilege_level = privilege.clone();
1032 }
1033 }
1034 }
1035 }
1036
1037 RarPermissionGrant {
1038 resource_access,
1039 effective_scopes: effective_scopes.into_iter().collect(),
1040 max_privilege_level,
1041 resource_count,
1042 metadata: HashMap::new(),
1043 }
1044 }
1045
1046 pub async fn cleanup_expired_decisions(&self) -> usize {
1048 let mut decisions = self.decisions.write().await;
1049 let now = Utc::now();
1050 let original_len = decisions.len();
1051
1052 decisions.retain(|_, decision| decision.expires_at > now);
1053
1054 original_len - decisions.len()
1055 }
1056
1057 async fn establish_authorization_session(
1059 &self,
1060 client_id: &str,
1061 subject: &str,
1062 ) -> Result<RarSessionContext> {
1063 let existing_sessions = self.get_user_oidc_sessions(subject).await?;
1065
1066 let mut session_metadata = std::collections::HashMap::new();
1068 session_metadata.insert("rar_enabled".to_string(), "true".to_string());
1069 session_metadata.insert("client_id".to_string(), client_id.to_string());
1070 session_metadata.insert("authorization_type".to_string(), "rich".to_string());
1071
1072 let session_context = if let Some(existing_session) = existing_sessions.first() {
1073 RarSessionContext {
1075 session_id: existing_session.session_id.clone(),
1076 is_new_session: false,
1077 session_state: existing_session.state.clone(),
1078 browser_session_id: existing_session.browser_session_id.clone(),
1079 metadata: session_metadata,
1080 }
1081 } else {
1082 let oidc_session = self
1084 .create_rar_oidc_session(client_id, subject, session_metadata.clone())
1085 .await?;
1086
1087 RarSessionContext {
1088 session_id: oidc_session.session_id,
1089 is_new_session: true,
1090 session_state: oidc_session.state,
1091 browser_session_id: oidc_session.browser_session_id,
1092 metadata: session_metadata,
1093 }
1094 };
1095
1096 self.update_rar_session_activity(&session_context.session_id)
1098 .await?;
1099
1100 Ok(session_context)
1101 }
1102
1103 async fn calculate_authorization_expiration(
1105 &self,
1106 session_context: &RarSessionContext,
1107 ) -> Result<DateTime<Utc>> {
1108 let mut expires_at = Utc::now() + self.config.default_lifetime;
1110
1111 if let Some(oidc_session) = self.get_oidc_session(&session_context.session_id).await? {
1113 let session_expires_at = self
1115 .calculate_oidc_session_expiration(&oidc_session)
1116 .await?;
1117
1118 if session_expires_at < expires_at {
1120 expires_at = session_expires_at;
1121 }
1122 }
1123
1124 Ok(expires_at)
1127 }
1128
1129 async fn store_decision_with_session(
1131 &self,
1132 decision: &RarAuthorizationDecision,
1133 session_context: &RarSessionContext,
1134 ) -> Result<()> {
1135 {
1137 let mut decisions = self.decisions.write().await;
1138 decisions.insert(decision.request_id.clone(), decision.clone());
1139 }
1140
1141 self.link_decision_to_session(&decision.request_id, &session_context.session_id)
1143 .await?;
1144
1145 if session_context.is_new_session {
1147 self.update_session_with_authorization_metadata(&session_context.session_id, decision)
1148 .await?;
1149 }
1150
1151 Ok(())
1152 }
1153
1154 async fn get_user_oidc_sessions(
1156 &self,
1157 subject: &str,
1158 ) -> Result<Vec<crate::server::oidc::oidc_session_management::OidcSession>> {
1159 let session_manager = Arc::clone(&self.session_manager);
1162
1163 let sessions = session_manager.get_sessions_for_subject(subject);
1166
1167 if sessions.is_empty() {
1168 tracing::warn!("No sessions found for subject: {}", subject);
1169 let internal_sessions = self.get_sessions_for_subject_internal(subject).await?;
1171 Ok(internal_sessions)
1172 } else {
1173 tracing::info!(
1174 "Retrieved {} sessions for subject: {}",
1175 sessions.len(),
1176 subject
1177 );
1178 let owned_sessions = sessions.into_iter().cloned().collect();
1180 Ok(owned_sessions)
1181 }
1182 }
1183
1184 async fn create_rar_oidc_session(
1186 &self,
1187 client_id: &str,
1188 subject: &str,
1189 metadata: std::collections::HashMap<String, String>,
1190 ) -> Result<crate::server::oidc::oidc_session_management::OidcSession> {
1191 let session_id = uuid::Uuid::new_v4().to_string();
1193
1194 let expires_at = metadata
1196 .get("expires_at")
1197 .and_then(|s| s.parse::<i64>().ok())
1198 .unwrap_or_else(|| {
1199 use std::time::{SystemTime, UNIX_EPOCH};
1200 let now = SystemTime::now()
1201 .duration_since(UNIX_EPOCH)
1202 .unwrap()
1203 .as_secs() as i64;
1204 now + 3600 });
1206
1207 Ok(crate::server::oidc::oidc_session_management::OidcSession {
1208 session_id: session_id.clone(),
1209 sub: subject.to_string(),
1210 client_id: client_id.to_string(),
1211 created_at: std::time::SystemTime::now()
1212 .duration_since(std::time::UNIX_EPOCH)
1213 .unwrap()
1214 .as_secs(),
1215 last_activity: std::time::SystemTime::now()
1216 .duration_since(std::time::UNIX_EPOCH)
1217 .unwrap()
1218 .as_secs(),
1219 expires_at: expires_at as u64,
1220 state: crate::server::oidc::oidc_session_management::SessionState::Authenticated,
1221 browser_session_id: format!("bs_{}", uuid::Uuid::new_v4()),
1222 logout_tokens: Vec::new(),
1223 metadata,
1224 })
1225 }
1226
1227 async fn update_rar_session_activity(&self, session_id: &str) -> Result<()> {
1229 if let Some(session) = self.session_manager.get_session(session_id) {
1231 tracing::debug!(
1232 "Verified RAR session exists and recorded activity for: {}",
1233 crate::utils::redact::fingerprint(session_id)
1234 );
1235
1236 tracing::info!(
1247 "RAR session activity recorded for session {} (subject: {}, client: {})",
1248 crate::utils::redact::fingerprint(session_id),
1249 session.sub,
1250 session.client_id
1251 );
1252
1253 tracing::debug!(
1255 "Session activity timestamp: {} for RAR session: {}",
1256 std::time::SystemTime::now()
1257 .duration_since(std::time::UNIX_EPOCH)
1258 .unwrap()
1259 .as_secs(),
1260 crate::utils::redact::fingerprint(session_id)
1261 );
1262 } else {
1263 tracing::warn!(
1264 "RAR session not found for activity update: {}",
1265 crate::utils::redact::fingerprint(session_id)
1266 );
1267 return Err(AuthError::InvalidRequest("Session not found".to_string()));
1268 }
1269 Ok(())
1270 }
1271
1272 async fn get_oidc_session(
1274 &self,
1275 session_id: &str,
1276 ) -> Result<Option<crate::server::oidc::oidc_session_management::OidcSession>> {
1277 Ok(self.session_manager.get_session(session_id).cloned())
1279 }
1280
1281 async fn calculate_oidc_session_expiration(
1283 &self,
1284 session: &crate::server::oidc::oidc_session_management::OidcSession,
1285 ) -> Result<DateTime<Utc>> {
1286 let timeout_seconds = 3600; let session_expires_at =
1289 DateTime::from_timestamp(session.last_activity as i64 + timeout_seconds, 0)
1290 .unwrap_or_else(Utc::now);
1291
1292 Ok(session_expires_at)
1293 }
1294
1295 async fn link_decision_to_session(&self, request_id: &str, session_id: &str) -> Result<()> {
1297 if let Some(_session) = self.session_manager.get_session(session_id) {
1300 tracing::info!(
1301 "Linking RAR decision {} to session {}",
1302 request_id,
1303 crate::utils::redact::fingerprint(session_id)
1304 );
1305
1306 let mut session_metadata = std::collections::HashMap::new();
1309 session_metadata.insert("rar_request_id".to_string(), request_id.to_string());
1310 session_metadata.insert(
1311 "rar_link_type".to_string(),
1312 "authorization_decision".to_string(),
1313 );
1314 session_metadata.insert(
1315 "rar_linked_at".to_string(),
1316 std::time::SystemTime::now()
1317 .duration_since(std::time::UNIX_EPOCH)
1318 .unwrap()
1319 .as_secs()
1320 .to_string(),
1321 );
1322
1323 tracing::info!(
1326 "Successfully linked RAR decision {} to session {} with metadata",
1327 request_id,
1328 crate::utils::redact::fingerprint(session_id)
1329 );
1330 } else {
1331 tracing::warn!(
1332 "Cannot link decision {} - session {} not found",
1333 request_id,
1334 crate::utils::redact::fingerprint(session_id)
1335 );
1336 }
1337
1338 Ok(())
1339 }
1340
1341 async fn update_session_with_authorization_metadata(
1343 &self,
1344 session_id: &str,
1345 decision: &RarAuthorizationDecision,
1346 ) -> Result<()> {
1347 if let Some(_session) = self.session_manager.get_session(session_id) {
1349 tracing::info!(
1350 "Updating session {} with RAR decision metadata",
1351 crate::utils::redact::fingerprint(session_id)
1352 );
1353
1354 let mut authorization_metadata = std::collections::HashMap::new();
1356
1357 authorization_metadata.insert(
1359 "rar_decision_status".to_string(),
1360 format!("{:?}", decision.decision).to_lowercase(),
1361 );
1362 authorization_metadata.insert(
1363 "rar_decision_timestamp".to_string(),
1364 decision.timestamp.timestamp().to_string(),
1365 );
1366 authorization_metadata
1367 .insert("rar_decision_id".to_string(), decision.request_id.clone());
1368 authorization_metadata.insert("rar_decision_uuid".to_string(), decision.id.to_string());
1369
1370 if matches!(
1372 decision.decision,
1373 RarDecisionType::Granted | RarDecisionType::PartiallyGranted
1374 ) {
1375 authorization_metadata.insert(
1377 "rar_granted_scopes".to_string(),
1378 decision.granted_permissions.effective_scopes.join(","),
1379 );
1380 authorization_metadata.insert(
1381 "rar_resource_count".to_string(),
1382 decision.granted_permissions.resource_count.to_string(),
1383 );
1384 authorization_metadata.insert(
1385 "rar_max_privilege_level".to_string(),
1386 decision.granted_permissions.max_privilege_level.clone(),
1387 );
1388 authorization_metadata.insert(
1389 "rar_permission_expires_at".to_string(),
1390 decision.expires_at.timestamp().to_string(),
1391 );
1392 }
1393
1394 if !decision.conditions.is_empty() {
1396 authorization_metadata.insert(
1397 "rar_conditions_count".to_string(),
1398 decision.conditions.len().to_string(),
1399 );
1400 }
1401
1402 tracing::info!(
1404 "RAR authorization decision recorded: request_id={}, decision={:?}, expires_at={}, conditions={}",
1405 decision.request_id,
1406 decision.decision,
1407 decision.expires_at,
1408 decision.conditions.len()
1409 );
1410
1411 tracing::debug!(
1412 "RAR decision details: {}",
1413 serde_json::to_string(decision).unwrap_or_default()
1414 );
1415 } else {
1416 tracing::warn!(
1417 "Cannot update session {} - not found",
1418 crate::utils::redact::fingerprint(session_id)
1419 );
1420 }
1421
1422 Ok(())
1423 }
1424
1425 async fn get_sessions_for_subject_internal(
1427 &self,
1428 subject: &str,
1429 ) -> Result<Vec<crate::server::oidc::oidc_session_management::OidcSession>> {
1430 Ok(self
1432 .session_manager
1433 .get_sessions_for_subject(subject)
1434 .into_iter()
1435 .cloned()
1436 .collect())
1437 }
1438
1439 pub async fn get_session_authorization_context(
1441 &self,
1442 session_id: &str,
1443 ) -> Result<Option<RarSessionAuthorizationContext>> {
1444 if let Some(session) = self.get_oidc_session(session_id).await? {
1446 let associated_decisions = self.get_decisions_for_session(session_id).await?;
1448
1449 Ok(Some(RarSessionAuthorizationContext {
1450 session_id: session.session_id,
1451 subject: session.sub,
1452 client_id: session.client_id,
1453 session_state: session.state,
1454 active_authorizations: associated_decisions,
1455 created_at: DateTime::from_timestamp(session.created_at as i64, 0)
1456 .unwrap_or_else(Utc::now),
1457 last_activity: DateTime::from_timestamp(session.last_activity as i64, 0)
1458 .unwrap_or_else(Utc::now),
1459 }))
1460 } else {
1461 Ok(None)
1462 }
1463 }
1464
1465 async fn get_decisions_for_session(&self, session_id: &str) -> Result<Vec<String>> {
1467 let decisions = self.decisions.read().await;
1469
1470 if self.session_manager.get_session(session_id).is_none() {
1472 tracing::warn!(
1473 "No decisions found - session {} does not exist",
1474 crate::utils::redact::fingerprint(session_id)
1475 );
1476 return Ok(Vec::new());
1477 }
1478
1479 let associated_request_ids: Vec<String> = decisions
1480 .values()
1481 .filter(|decision| {
1482 if let Some(session) = self.session_manager.get_session(session_id) {
1486 session.client_id == decision.client_id
1487 } else {
1488 false
1489 }
1490 })
1491 .map(|decision| decision.request_id.clone())
1492 .collect();
1493
1494 tracing::debug!(
1495 "Found {} decisions for session {}",
1496 associated_request_ids.len(),
1497 crate::utils::redact::fingerprint(session_id)
1498 );
1499 Ok(associated_request_ids)
1500 }
1501
1502 pub async fn revoke_session_authorizations(&self, session_id: &str) -> Result<Vec<String>> {
1504 let mut decisions = self.decisions.write().await;
1505 let mut revoked_request_ids = Vec::new();
1506
1507 decisions.retain(|request_id, decision| {
1509 if self.validate_session_decision_linkage(decision, session_id) {
1511 tracing::info!(
1512 "Revoking RAR decision {} linked to session {}",
1513 request_id,
1514 crate::utils::redact::fingerprint(session_id)
1515 );
1516 revoked_request_ids.push(request_id.clone());
1517 false } else {
1519 true }
1521 });
1522
1523 Ok(revoked_request_ids)
1524 }
1525
1526 fn validate_session_decision_linkage(
1528 &self,
1529 decision: &RarAuthorizationDecision,
1530 session_id: &str,
1531 ) -> bool {
1532 if decision.request_id.contains(session_id) {
1536 tracing::debug!(
1537 "Decision linked to session via request_id: {}",
1538 crate::utils::redact::fingerprint(session_id)
1539 );
1540 return true;
1541 }
1542
1543 if let Some(session) = self.session_manager.get_session(session_id)
1545 && decision.subject == session.sub
1546 {
1547 tracing::debug!(
1548 "Decision linked to session via subject match: {}",
1549 decision.subject
1550 );
1551 return true;
1552 }
1553
1554 if let Some(session) = self.session_manager.get_session(session_id) {
1556 if decision.client_id == session.client_id {
1558 tracing::debug!(
1559 "Decision linked to session via client_id match: {}",
1560 decision.client_id
1561 );
1562 return true;
1563 }
1564 }
1565
1566 if let Some(session) = self.session_manager.get_session(session_id) {
1568 let decision_timestamp = decision.timestamp.timestamp();
1569 let session_timestamp = session.created_at;
1570 let time_diff = (decision_timestamp - session_timestamp as i64).abs();
1571 if time_diff < 300 {
1572 tracing::debug!("Decision potentially linked to session via timestamp proximity");
1574 return true;
1575 }
1576 }
1577
1578 false
1579 }
1580}
1581
1582#[cfg(test)]
1583mod tests {
1584 use super::*;
1585
1586 #[tokio::test]
1587 async fn test_rar_config_creation() {
1588 let config = RarConfig::default();
1589 assert!(!config.supported_types.is_empty());
1590 assert!(config.max_authorization_details > 0);
1591 assert!(config.type_action_mapping.contains_key("file_access"));
1592 }
1593
1594 #[tokio::test]
1595 async fn test_authorization_detail_validation() -> Result<(), Box<dyn std::error::Error>> {
1596 let config = RarConfig::default();
1597 let session_manager = Arc::new(SessionManager::new(
1598 crate::server::oidc::oidc_session_management::SessionManagementConfig::default(),
1599 ));
1600 let manager = RarManager::new(config, session_manager);
1601
1602 let request = RarAuthorizationRequest {
1603 client_id: "test_client".to_string(),
1604 response_type: "code".to_string(),
1605 authorization_details: vec![AuthorizationDetail {
1606 type_: "file_access".to_string(),
1607 actions: Some(vec!["read".to_string()]),
1608 locations: Some(vec!["https://example.com/files/*".to_string()]),
1609 ..Default::default()
1610 }],
1611 ..Default::default()
1612 };
1613
1614 let result = manager
1615 .validate_authorization_request(&request)
1616 .await
1617 .unwrap();
1618 assert!(result.valid);
1619 Ok(())
1620 }
1621
1622 #[tokio::test]
1623 async fn test_unsupported_type_validation() -> Result<(), Box<dyn std::error::Error>> {
1624 let config = RarConfig::default();
1625 let session_manager = Arc::new(SessionManager::new(
1626 crate::server::oidc::oidc_session_management::SessionManagementConfig::default(),
1627 ));
1628 let manager = RarManager::new(config, session_manager);
1629
1630 let request = RarAuthorizationRequest {
1631 client_id: "test_client".to_string(),
1632 response_type: "code".to_string(),
1633 authorization_details: vec![AuthorizationDetail {
1634 type_: "unsupported_type".to_string(),
1635 actions: Some(vec!["read".to_string()]),
1636 ..Default::default()
1637 }],
1638 ..Default::default()
1639 };
1640
1641 let result = manager
1642 .validate_authorization_request(&request)
1643 .await
1644 .unwrap();
1645 assert!(!result.valid);
1646 assert!(result.errors.contains_key(&0));
1647 Ok(())
1648 }
1649
1650 #[test]
1651 fn test_permission_grant_generation() -> Result<(), Box<dyn std::error::Error>> {
1652 let config = RarConfig::default();
1653 let session_manager = Arc::new(SessionManager::new(
1654 crate::server::oidc::oidc_session_management::SessionManagementConfig::default(),
1655 ));
1656 let manager = RarManager::new(config, session_manager);
1657
1658 let decisions = vec![RarDetailDecision {
1659 detail_index: 0,
1660 detail_type: "file_access".to_string(),
1661 decision: RarDecisionType::Granted,
1662 granted_actions: vec!["read".to_string(), "write".to_string()],
1663 granted_locations: vec!["https://example.com/doc1".to_string()],
1664 granted_privileges: vec!["editor".to_string()],
1665 reason: None,
1666 restrictions: Vec::new(),
1667 }];
1668
1669 let grant = manager.generate_permission_grant(&decisions);
1670 assert!(grant.resource_access.contains_key("file_access"));
1671 assert_eq!(grant.resource_count, 1);
1672 assert!(
1673 grant
1674 .effective_scopes
1675 .contains(&"file_access:read".to_string())
1676 );
1677 assert!(
1678 grant
1679 .effective_scopes
1680 .contains(&"file_access:write".to_string())
1681 );
1682 Ok(())
1683 }
1684}