Skip to main content

auth_framework/authorization_enhanced/
context.rs

1//! Authorization context builders for enhanced RBAC
2//!
3//! This module provides utilities to build context objects for conditional
4//! permissions and request-specific authorization decisions.
5
6use crate::tokens::AuthToken;
7use axum::extract::Request;
8use chrono::{DateTime, Datelike, Timelike, Utc, Weekday};
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11use std::net::IpAddr;
12
13/// Request context for authorization decisions
14#[derive(Clone, Serialize, Deserialize)]
15pub struct AuthorizationContext {
16    /// User information
17    pub user_id: String,
18    pub roles: Vec<String>,
19    pub session_id: Option<String>,
20
21    /// Request metadata
22    pub method: String,
23    pub path: String,
24    pub ip_address: Option<IpAddr>,
25    pub user_agent: Option<String>,
26
27    /// Time-based context
28    pub request_time: DateTime<Utc>,
29    pub time_of_day: TimeOfDay,
30    pub day_type: DayType,
31
32    /// Device and connection info
33    pub device_type: DeviceType,
34    pub connection_type: ConnectionType,
35
36    /// Security context
37    pub security_level: SecurityLevel,
38    pub risk_score: u8, // 0-100
39
40    /// Custom attributes
41    pub custom_attributes: HashMap<String, String>,
42}
43
44impl std::fmt::Debug for AuthorizationContext {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        let mut d = f.debug_struct("AuthorizationContext");
47        d.field("user_id", &self.user_id);
48        d.field("roles", &self.roles);
49        d.field(
50            "session_id",
51            &crate::utils::redact::redacted(&self.session_id),
52        );
53        d.field("method", &self.method);
54        d.field("path", &self.path);
55        d.field("ip_address", &self.ip_address);
56        d.field("user_agent", &self.user_agent);
57        d.field("request_time", &self.request_time);
58        d.field("time_of_day", &self.time_of_day);
59        d.field("day_type", &self.day_type);
60        d.field("device_type", &self.device_type);
61        d.field("connection_type", &self.connection_type);
62        d.field("security_level", &self.security_level);
63        d.field("risk_score", &self.risk_score);
64        // The values come from `X-Auth-*` headers and `ctx_*` query parameters, which can carry
65        // a credential: only the names are shown.
66        let mut names: Vec<&String> = self.custom_attributes.keys().collect();
67        names.sort();
68        d.field("custom_attributes", &names);
69        d.finish()
70    }
71}
72
73/// Time of day classification
74#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
75pub enum TimeOfDay {
76    BusinessHours,
77    AfterHours,
78    Weekend,
79    Holiday,
80}
81
82/// Day type classification
83#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
84pub enum DayType {
85    Weekday,
86    Weekend,
87    Holiday,
88}
89
90/// Device type detection
91#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
92pub enum DeviceType {
93    Desktop,
94    Mobile,
95    Tablet,
96    Unknown,
97}
98
99/// Connection type analysis
100#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
101pub enum ConnectionType {
102    Direct,
103    VPN,
104    Proxy,
105    Tor,
106    Corporate,
107    Unknown,
108}
109
110/// Security level assessment
111#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
112pub enum SecurityLevel {
113    Low,
114    Medium,
115    High,
116    Critical,
117}
118
119/// Enhanced context builder for authorization decisions
120pub struct ContextBuilder {
121    /// Known holiday dates (could be loaded from config)
122    holidays: Vec<chrono::NaiveDate>,
123    /// Business hours configuration
124    business_start: u8,
125    business_end: u8,
126    /// IP ranges for corporate networks
127    corporate_networks: Vec<ipnetwork::IpNetwork>,
128}
129
130impl Default for ContextBuilder {
131    fn default() -> Self {
132        Self::new()
133    }
134}
135
136impl ContextBuilder {
137    /// Create a new context builder with default settings
138    pub fn new() -> Self {
139        Self {
140            holidays: Vec::new(),
141            business_start: 9,
142            business_end: 17,
143            corporate_networks: Vec::new(),
144        }
145    }
146
147    /// Configure business hours
148    pub fn with_business_hours(mut self, start: u8, end: u8) -> Self {
149        self.business_start = start;
150        self.business_end = end;
151        self
152    }
153
154    /// Add corporate network ranges
155    pub fn with_corporate_networks(mut self, networks: Vec<ipnetwork::IpNetwork>) -> Self {
156        self.corporate_networks = networks;
157        self
158    }
159
160    /// Add holiday dates
161    pub fn with_holidays(mut self, holidays: Vec<chrono::NaiveDate>) -> Self {
162        self.holidays = holidays;
163        self
164    }
165
166    /// Build authorization context from request and auth token
167    pub fn build_context(&self, request: &Request, auth_token: &AuthToken) -> AuthorizationContext {
168        let now = Utc::now();
169        let ip_address = self.extract_ip_address(request);
170        let user_agent = self.extract_user_agent(request);
171
172        AuthorizationContext {
173            user_id: auth_token.user_id.clone(),
174            roles: auth_token.roles.to_vec(),
175            session_id: auth_token.metadata.session_id.clone(),
176
177            method: request.method().to_string(),
178            path: request.uri().path().to_string(),
179            ip_address,
180            user_agent: user_agent.clone(),
181
182            request_time: now,
183            time_of_day: self.classify_time_of_day(now),
184            day_type: self.classify_day_type(now),
185
186            device_type: self.detect_device_type(&user_agent),
187            connection_type: self.analyze_connection_type(request, &ip_address),
188
189            security_level: self.assess_security_level(request),
190            risk_score: self.calculate_risk_score(request, &ip_address, &user_agent),
191
192            custom_attributes: self.extract_custom_attributes(request),
193        }
194    }
195
196    /// Convert context to HashMap for role-system compatibility
197    pub fn to_hashmap(&self, context: &AuthorizationContext) -> HashMap<String, String> {
198        let mut map = HashMap::new();
199
200        // User context
201        map.insert("user_id".to_string(), context.user_id.clone());
202        map.insert("roles".to_string(), context.roles.join(","));
203        if let Some(session_id) = &context.session_id {
204            map.insert("session_id".to_string(), session_id.clone());
205        }
206
207        // Request context
208        map.insert("method".to_string(), context.method.clone());
209        map.insert("path".to_string(), context.path.clone());
210        if let Some(ip) = &context.ip_address {
211            map.insert("ip_address".to_string(), ip.to_string());
212        }
213        if let Some(ua) = &context.user_agent {
214            map.insert("user_agent".to_string(), ua.clone());
215        }
216
217        // Time context
218        map.insert(
219            "time_of_day".to_string(),
220            format!("{:?}", context.time_of_day).to_lowercase(),
221        );
222        map.insert(
223            "day_type".to_string(),
224            format!("{:?}", context.day_type).to_lowercase(),
225        );
226        map.insert(
227            "request_hour".to_string(),
228            context.request_time.hour().to_string(),
229        );
230        map.insert(
231            "request_weekday".to_string(),
232            context.request_time.weekday().to_string(),
233        );
234
235        // Device and connection
236        map.insert(
237            "device_type".to_string(),
238            format!("{:?}", context.device_type).to_lowercase(),
239        );
240        map.insert(
241            "connection_type".to_string(),
242            format!("{:?}", context.connection_type).to_lowercase(),
243        );
244
245        // Security context
246        map.insert(
247            "security_level".to_string(),
248            format!("{:?}", context.security_level).to_lowercase(),
249        );
250        map.insert("risk_score".to_string(), context.risk_score.to_string());
251
252        // Custom attributes
253        for (key, value) in &context.custom_attributes {
254            map.insert(format!("custom_{}", key), value.clone());
255        }
256
257        map
258    }
259
260    /// Extract IP address from request headers
261    fn extract_ip_address(&self, request: &Request) -> Option<IpAddr> {
262        // Try X-Forwarded-For first
263        if let Some(forwarded) = request.headers().get("x-forwarded-for")
264            && let Ok(forwarded_str) = forwarded.to_str()
265        {
266            if let Some(ip_str) = forwarded_str.split(',').next()
267                && let Ok(ip) = ip_str.trim().parse()
268            {
269                return Some(ip);
270            }
271
272            // Try X-Real-IP
273            if let Some(real_ip) = request.headers().get("x-real-ip")
274                && let Ok(ip_str) = real_ip.to_str()
275                && let Ok(ip) = ip_str.parse()
276            {
277                return Some(ip);
278            }
279
280            // Could also get from connection info if available
281            None
282        } else {
283            // Fallback to remote address if no headers found
284            request
285                .extensions()
286                .get::<axum::extract::ConnectInfo<IpAddr>>()
287                .map(|info| info.0)
288        }
289    }
290
291    /// Extract user agent from request headers
292    fn extract_user_agent(&self, request: &Request) -> Option<String> {
293        request
294            .headers()
295            .get("user-agent")
296            .and_then(|ua| ua.to_str().ok())
297            .map(|s| s.to_string())
298    }
299
300    /// Classify time of day based on business hours and holidays
301    fn classify_time_of_day(&self, now: DateTime<Utc>) -> TimeOfDay {
302        let date = now.date_naive();
303
304        // Check if it's a holiday
305        if self.holidays.contains(&date) {
306            return TimeOfDay::Holiday;
307        }
308
309        // Check if it's weekend
310        match now.weekday() {
311            Weekday::Sat | Weekday::Sun => return TimeOfDay::Weekend,
312            _ => {}
313        }
314
315        // Check business hours
316        let hour = now.hour() as u8;
317        if hour >= self.business_start && hour < self.business_end {
318            TimeOfDay::BusinessHours
319        } else {
320            TimeOfDay::AfterHours
321        }
322    }
323
324    /// Classify day type
325    fn classify_day_type(&self, now: DateTime<Utc>) -> DayType {
326        let date = now.date_naive();
327
328        if self.holidays.contains(&date) {
329            DayType::Holiday
330        } else {
331            match now.weekday() {
332                Weekday::Sat | Weekday::Sun => DayType::Weekend,
333                _ => DayType::Weekday,
334            }
335        }
336    }
337
338    /// Detect device type from user agent
339    fn detect_device_type(&self, user_agent: &Option<String>) -> DeviceType {
340        let ua = match user_agent {
341            Some(ua) => ua.to_lowercase(),
342            None => return DeviceType::Unknown,
343        };
344
345        if ua.contains("mobile") || ua.contains("android") || ua.contains("iphone") {
346            DeviceType::Mobile
347        } else if ua.contains("tablet") || ua.contains("ipad") {
348            DeviceType::Tablet
349        } else if ua.contains("mozilla") || ua.contains("chrome") || ua.contains("firefox") {
350            DeviceType::Desktop
351        } else {
352            DeviceType::Unknown
353        }
354    }
355
356    /// Analyze connection type from headers and IP
357    fn analyze_connection_type(
358        &self,
359        request: &Request,
360        ip_address: &Option<IpAddr>,
361    ) -> ConnectionType {
362        // Check for VPN indicators in headers
363        if let Some(via) = request.headers().get("via")
364            && let Ok(via_str) = via.to_str()
365        {
366            if via_str.to_lowercase().contains("vpn") {
367                return ConnectionType::VPN;
368            }
369            if via_str.to_lowercase().contains("proxy") {
370                return ConnectionType::Proxy;
371            }
372
373            // Check for Tor indicators
374            if let Some(ua) = request.headers().get("user-agent")
375                && let Ok(ua_str) = ua.to_str()
376                && ua_str.contains("Tor")
377            {
378                return ConnectionType::Tor;
379            }
380
381            // Check if IP is in corporate network range
382            if let Some(ip) = ip_address {
383                for network in &self.corporate_networks {
384                    if network.contains(*ip) {
385                        return ConnectionType::Corporate;
386                    }
387                }
388            }
389
390            return ConnectionType::Direct;
391        }
392        // Fallback to unknown if no indicators found
393        ConnectionType::Unknown
394    }
395
396    /// Assess security level based on endpoint
397    fn assess_security_level(&self, request: &Request) -> SecurityLevel {
398        let path = request.uri().path();
399
400        match path {
401            _ if path.starts_with("/admin/system/") => SecurityLevel::Critical,
402            _ if path.starts_with("/admin/") => SecurityLevel::High,
403            _ if path.contains("/secrets/") => SecurityLevel::Critical,
404            _ if path.contains("/keys/") => SecurityLevel::High,
405            _ if path.starts_with("/api/") => SecurityLevel::Medium,
406            _ => SecurityLevel::Low,
407        }
408    }
409
410    /// Calculate risk score (0-100)
411    fn calculate_risk_score(
412        &self,
413        request: &Request,
414        ip_address: &Option<IpAddr>,
415        user_agent: &Option<String>,
416    ) -> u8 {
417        let mut risk_score = 0u8;
418
419        // Base risk from endpoint
420        let path = request.uri().path();
421        if path.starts_with("/admin/") {
422            risk_score += 30;
423        } else if path.contains("/secrets/") || path.contains("/keys/") {
424            risk_score += 40;
425        } else if path.starts_with("/api/") {
426            risk_score += 10;
427        }
428
429        // Risk from connection type
430        let connection_type = self.analyze_connection_type(request, ip_address);
431        match connection_type {
432            ConnectionType::Tor => risk_score += 50,
433            ConnectionType::VPN => risk_score += 20,
434            ConnectionType::Proxy => risk_score += 15,
435            ConnectionType::Corporate => risk_score = risk_score.saturating_sub(10),
436            ConnectionType::Direct => {}
437            ConnectionType::Unknown => risk_score += 10,
438        }
439
440        // Risk from device type
441        let device_type = self.detect_device_type(user_agent);
442        match device_type {
443            DeviceType::Mobile => risk_score += 5,
444            DeviceType::Unknown => risk_score += 15,
445            _ => {}
446        }
447
448        // Risk from time
449        let now = Utc::now();
450        match self.classify_time_of_day(now) {
451            TimeOfDay::AfterHours => risk_score += 10,
452            TimeOfDay::Weekend => risk_score += 5,
453            _ => {}
454        }
455
456        // Missing user agent is suspicious
457        if user_agent.is_none() {
458            risk_score += 20;
459        }
460
461        // Cap at 100
462        risk_score.min(100)
463    }
464
465    /// Extract custom attributes from headers
466    fn extract_custom_attributes(&self, request: &Request) -> HashMap<String, String> {
467        let mut attributes = HashMap::new();
468
469        // Extract custom headers starting with X-Auth-
470        for (name, value) in request.headers() {
471            let name_str = name.as_str().to_lowercase();
472            if let Some(attr_name) = name_str.strip_prefix("x-auth-")
473                && let Ok(value_str) = value.to_str()
474            {
475                attributes.insert(attr_name.to_string(), value_str.to_string());
476            }
477        }
478
479        // Extract query parameters for additional context
480        if let Some(query) = request.uri().query() {
481            for pair in query.split('&') {
482                if let Some((key, value)) = pair.split_once('=')
483                    && key.starts_with("ctx_")
484                {
485                    attributes.insert(
486                        key.strip_prefix("ctx_")
487                            .expect("guarded by starts_with check")
488                            .to_string(),
489                        urlencoding::decode(value).unwrap_or_default().to_string(),
490                    );
491                }
492            }
493        }
494
495        attributes
496    }
497
498    /// Enrich existing context with additional computed attributes
499    pub fn enrich_context(&self, mut context: AuthorizationContext) -> AuthorizationContext {
500        // Add computed risk factors
501        let current_risk = context.risk_score;
502        context.risk_score = std::cmp::max(current_risk, 1); // Ensure minimum risk
503
504        // Add time-based enrichment
505        let now = chrono::Utc::now();
506        context
507            .custom_attributes
508            .insert("enriched_timestamp".to_string(), now.to_rfc3339());
509
510        // Add security level enhancement
511        context.custom_attributes.insert(
512            "security_assessment".to_string(),
513            match context.security_level {
514                SecurityLevel::Low => "basic".to_string(),
515                SecurityLevel::Medium => "standard".to_string(),
516                SecurityLevel::High => "enhanced".to_string(),
517                SecurityLevel::Critical => "maximum".to_string(),
518            },
519        );
520
521        context
522    }
523}
524
525/// Conditional permission evaluator for enterprise security requirements
526pub struct ConditionalEvaluator {
527    context_builder: ContextBuilder,
528}
529
530impl ConditionalEvaluator {
531    /// Create new conditional evaluator
532    pub fn new(context_builder: ContextBuilder) -> Self {
533        Self { context_builder }
534    }
535
536    /// Evaluate time-based conditions
537    pub fn evaluate_time_conditions(
538        &self,
539        context: &AuthorizationContext,
540        conditions: &HashMap<String, String>,
541    ) -> bool {
542        // Check business hours requirement
543        if let Some(require_business_hours) = conditions.get("require_business_hours")
544            && require_business_hours == "true"
545        {
546            match context.time_of_day {
547                TimeOfDay::BusinessHours => {}
548                _ => return false,
549            }
550        }
551
552        // Check weekday requirement
553        if let Some(require_weekday) = conditions.get("require_weekday")
554            && require_weekday == "true"
555        {
556            match context.day_type {
557                DayType::Weekday => {}
558                _ => return false,
559            }
560        }
561
562        true
563    }
564
565    /// Evaluate location-based conditions
566    pub fn evaluate_location_conditions(
567        &self,
568        context: &AuthorizationContext,
569        conditions: &HashMap<String, String>,
570    ) -> bool {
571        // Check corporate network requirement
572        if let Some(require_corporate) = conditions.get("require_corporate_network")
573            && require_corporate == "true"
574        {
575            match context.connection_type {
576                ConnectionType::Corporate => {}
577                _ => return false,
578            }
579        }
580
581        // Check VPN restrictions
582        if let Some(block_vpn) = conditions.get("block_vpn")
583            && block_vpn == "true"
584        {
585            match context.connection_type {
586                ConnectionType::VPN | ConnectionType::Tor => return false,
587                _ => {}
588            }
589        }
590
591        true
592    }
593
594    /// Evaluate device-based conditions
595    pub fn evaluate_device_conditions(
596        &self,
597        context: &AuthorizationContext,
598        conditions: &HashMap<String, String>,
599    ) -> bool {
600        // Check device type restrictions
601        if let Some(allowed_devices) = conditions.get("allowed_device_types") {
602            let allowed: Vec<&str> = allowed_devices.split(',').collect();
603            let device_str = format!("{:?}", context.device_type).to_lowercase();
604
605            if !allowed.contains(&device_str.as_str()) {
606                return false;
607            }
608        }
609
610        true
611    }
612
613    /// Evaluate risk-based conditions
614    pub fn evaluate_risk_conditions(
615        &self,
616        context: &AuthorizationContext,
617        conditions: &HashMap<String, String>,
618    ) -> bool {
619        // Check maximum risk score
620        if let Some(max_risk_str) = conditions.get("max_risk_score")
621            && let Ok(max_risk) = max_risk_str.parse::<u8>()
622            && context.risk_score > max_risk
623        {
624            return false;
625        }
626
627        true
628    }
629
630    /// Main conditional evaluation method for production use
631    /// Evaluates complex conditional permission rules based on context
632    pub fn evaluate_conditional_permission(
633        &self,
634        context: &AuthorizationContext,
635        permission_conditions: &HashMap<String, String>,
636    ) -> bool {
637        // Evaluates time, location, device, and risk conditions — all must pass.
638        tracing::debug!(
639            "Evaluating conditional permission with conditions: {:?}",
640            permission_conditions
641        );
642
643        // If no conditions specified, allow by default
644        if permission_conditions.is_empty() {
645            return true;
646        }
647
648        // Enrich context using the context builder for more comprehensive evaluation
649        let _enriched_context = self.context_builder.enrich_context(context.clone());
650
651        // Evaluate all condition types - ALL must pass for conditional permission to be granted
652        let time_check = self.evaluate_time_conditions(context, permission_conditions);
653        let location_check = self.evaluate_location_conditions(context, permission_conditions);
654        let device_check = self.evaluate_device_conditions(context, permission_conditions);
655        let risk_check = self.evaluate_risk_conditions(context, permission_conditions);
656
657        let result = time_check && location_check && device_check && risk_check;
658
659        tracing::info!(
660            "Conditional evaluation result: {} (time: {}, location: {}, device: {}, risk: {})",
661            result,
662            time_check,
663            location_check,
664            device_check,
665            risk_check
666        );
667
668        result
669    }
670
671    /// Evaluate all conditions
672    pub fn evaluate_all_conditions(
673        &self,
674        context: &AuthorizationContext,
675        conditions: &HashMap<String, String>,
676    ) -> bool {
677        self.evaluate_time_conditions(context, conditions)
678            && self.evaluate_location_conditions(context, conditions)
679            && self.evaluate_device_conditions(context, conditions)
680            && self.evaluate_risk_conditions(context, conditions)
681    }
682}
683
684#[cfg(test)]
685mod tests {
686    use super::*;
687
688    #[test]
689    fn test_context_builder_creation() {
690        let builder = ContextBuilder::new()
691            .with_business_hours(8, 18)
692            .with_holidays(vec![chrono::NaiveDate::from_ymd_opt(2024, 12, 25).unwrap()]);
693
694        assert_eq!(builder.business_start, 8);
695        assert_eq!(builder.business_end, 18);
696        assert_eq!(builder.holidays.len(), 1);
697    }
698
699    #[test]
700    fn test_time_classification() {
701        let builder = ContextBuilder::new();
702
703        // Business hours
704        let business_time = chrono::Utc::now()
705            .with_hour(14)
706            .unwrap()
707            .with_minute(0)
708            .unwrap();
709
710        match business_time.weekday() {
711            Weekday::Sat | Weekday::Sun => {
712                assert!(matches!(
713                    builder.classify_time_of_day(business_time),
714                    TimeOfDay::Weekend
715                ));
716            }
717            _ => {
718                assert!(matches!(
719                    builder.classify_time_of_day(business_time),
720                    TimeOfDay::BusinessHours
721                ));
722            }
723        }
724    }
725
726    #[test]
727    fn test_device_detection() {
728        let builder = ContextBuilder::new();
729
730        let mobile_ua = Some("Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)".to_string());
731        assert!(matches!(
732            builder.detect_device_type(&mobile_ua),
733            DeviceType::Mobile
734        ));
735
736        let desktop_ua =
737            Some("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36".to_string());
738        assert!(matches!(
739            builder.detect_device_type(&desktop_ua),
740            DeviceType::Desktop
741        ));
742
743        assert!(matches!(
744            builder.detect_device_type(&None),
745            DeviceType::Unknown
746        ));
747    }
748
749    #[test]
750    fn test_risk_calculation() {
751        let _builder = ContextBuilder::new();
752
753        // Create a mock request - in real tests we'd use proper test utilities
754        // This is a simplified test to verify the logic structure
755        // NOTE: Complete test suite available with additional test infrastructure
756    }
757}