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