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