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