1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct AuthorizationContext {
16 pub user_id: String,
18 pub roles: Vec<String>,
19 pub session_id: Option<String>,
20
21 pub method: String,
23 pub path: String,
24 pub ip_address: Option<IpAddr>,
25 pub user_agent: Option<String>,
26
27 pub request_time: DateTime<Utc>,
29 pub time_of_day: TimeOfDay,
30 pub day_type: DayType,
31
32 pub device_type: DeviceType,
34 pub connection_type: ConnectionType,
35
36 pub security_level: SecurityLevel,
38 pub risk_score: u8, pub custom_attributes: HashMap<String, String>,
42}
43
44#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
46pub enum TimeOfDay {
47 BusinessHours,
48 AfterHours,
49 Weekend,
50 Holiday,
51}
52
53#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
55pub enum DayType {
56 Weekday,
57 Weekend,
58 Holiday,
59}
60
61#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
63pub enum DeviceType {
64 Desktop,
65 Mobile,
66 Tablet,
67 Unknown,
68}
69
70#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
72pub enum ConnectionType {
73 Direct,
74 VPN,
75 Proxy,
76 Tor,
77 Corporate,
78 Unknown,
79}
80
81#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
83pub enum SecurityLevel {
84 Low,
85 Medium,
86 High,
87 Critical,
88}
89
90pub struct ContextBuilder {
92 holidays: Vec<chrono::NaiveDate>,
94 business_start: u8,
96 business_end: u8,
97 corporate_networks: Vec<ipnetwork::IpNetwork>,
99 trusted_proxies: Vec<IpAddr>,
101}
102
103impl Default for ContextBuilder {
104 fn default() -> Self {
105 Self::new()
106 }
107}
108
109impl ContextBuilder {
110 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 pub fn with_trusted_proxies(mut self, proxies: Vec<IpAddr>) -> Self {
129 self.trusted_proxies = proxies;
130 self
131 }
132
133 pub fn with_business_hours(mut self, start: u8, end: u8) -> Self {
135 self.business_start = start;
136 self.business_end = end;
137 self
138 }
139
140 pub fn with_corporate_networks(mut self, networks: Vec<ipnetwork::IpNetwork>) -> Self {
142 self.corporate_networks = networks;
143 self
144 }
145
146 pub fn with_holidays(mut self, holidays: Vec<chrono::NaiveDate>) -> Self {
148 self.holidays = holidays;
149 self
150 }
151
152 pub fn build_context(&self, request: &Request, auth_token: &AuthToken) -> AuthorizationContext {
154 let now = Utc::now();
155 let ip_address = self.extract_ip_address(request);
156 let user_agent = self.extract_user_agent(request);
157
158 AuthorizationContext {
159 user_id: auth_token.user_id.clone(),
160 roles: auth_token.roles.clone(),
161 session_id: auth_token.metadata.session_id.clone(),
162
163 method: request.method().to_string(),
164 path: request.uri().path().to_string(),
165 ip_address,
166 user_agent: user_agent.clone(),
167
168 request_time: now,
169 time_of_day: self.classify_time_of_day(now),
170 day_type: self.classify_day_type(now),
171
172 device_type: self.detect_device_type(&user_agent),
173 connection_type: self.analyze_connection_type(request, &ip_address),
174
175 security_level: self.assess_security_level(request),
176 risk_score: self.calculate_risk_score(request, &ip_address, &user_agent),
177
178 custom_attributes: self.extract_custom_attributes(request),
179 }
180 }
181
182 pub fn to_hashmap(&self, context: &AuthorizationContext) -> HashMap<String, String> {
184 let mut map = HashMap::new();
185
186 map.insert("user_id".to_string(), context.user_id.clone());
188 map.insert("roles".to_string(), context.roles.join(","));
189 if let Some(session_id) = &context.session_id {
190 map.insert("session_id".to_string(), session_id.clone());
191 }
192
193 map.insert("method".to_string(), context.method.clone());
195 map.insert("path".to_string(), context.path.clone());
196 if let Some(ip) = &context.ip_address {
197 map.insert("ip_address".to_string(), ip.to_string());
198 }
199 if let Some(ua) = &context.user_agent {
200 map.insert("user_agent".to_string(), ua.clone());
201 }
202
203 map.insert(
205 "time_of_day".to_string(),
206 format!("{:?}", context.time_of_day).to_lowercase(),
207 );
208 map.insert(
209 "day_type".to_string(),
210 format!("{:?}", context.day_type).to_lowercase(),
211 );
212 map.insert(
213 "request_hour".to_string(),
214 context.request_time.hour().to_string(),
215 );
216 map.insert(
217 "request_weekday".to_string(),
218 context.request_time.weekday().to_string(),
219 );
220
221 map.insert(
223 "device_type".to_string(),
224 format!("{:?}", context.device_type).to_lowercase(),
225 );
226 map.insert(
227 "connection_type".to_string(),
228 format!("{:?}", context.connection_type).to_lowercase(),
229 );
230
231 map.insert(
233 "security_level".to_string(),
234 format!("{:?}", context.security_level).to_lowercase(),
235 );
236 map.insert("risk_score".to_string(), context.risk_score.to_string());
237
238 for (key, value) in &context.custom_attributes {
240 map.insert(format!("custom_{}", key), value.clone());
241 }
242
243 map
244 }
245
246 fn extract_ip_address(&self, request: &Request) -> Option<IpAddr> {
251 let peer = request
252 .extensions()
253 .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
254 .map(|info| info.0.ip())?;
255 Some(crate::api::middleware::forwarded_client_ip(
256 peer,
257 request.headers(),
258 &self.trusted_proxies,
259 ))
260 }
261
262 fn extract_user_agent(&self, request: &Request) -> Option<String> {
264 request
265 .headers()
266 .get("user-agent")
267 .and_then(|ua| ua.to_str().ok())
268 .map(|s| s.to_string())
269 }
270
271 fn classify_time_of_day(&self, now: DateTime<Utc>) -> TimeOfDay {
273 let date = now.date_naive();
274
275 if self.holidays.contains(&date) {
277 return TimeOfDay::Holiday;
278 }
279
280 match now.weekday() {
282 Weekday::Sat | Weekday::Sun => return TimeOfDay::Weekend,
283 _ => {}
284 }
285
286 let hour = now.hour() as u8;
288 if hour >= self.business_start && hour < self.business_end {
289 TimeOfDay::BusinessHours
290 } else {
291 TimeOfDay::AfterHours
292 }
293 }
294
295 fn classify_day_type(&self, now: DateTime<Utc>) -> DayType {
297 let date = now.date_naive();
298
299 if self.holidays.contains(&date) {
300 DayType::Holiday
301 } else {
302 match now.weekday() {
303 Weekday::Sat | Weekday::Sun => DayType::Weekend,
304 _ => DayType::Weekday,
305 }
306 }
307 }
308
309 fn detect_device_type(&self, user_agent: &Option<String>) -> DeviceType {
311 let ua = match user_agent {
312 Some(ua) => ua.to_lowercase(),
313 None => return DeviceType::Unknown,
314 };
315
316 if ua.contains("mobile") || ua.contains("android") || ua.contains("iphone") {
317 DeviceType::Mobile
318 } else if ua.contains("tablet") || ua.contains("ipad") {
319 DeviceType::Tablet
320 } else if ua.contains("mozilla") || ua.contains("chrome") || ua.contains("firefox") {
321 DeviceType::Desktop
322 } else {
323 DeviceType::Unknown
324 }
325 }
326
327 fn analyze_connection_type(
334 &self,
335 request: &Request,
336 ip_address: &Option<IpAddr>,
337 ) -> ConnectionType {
338 if let Some(via) = request.headers().get("via")
339 && let Ok(via_str) = via.to_str()
340 {
341 let via_str = via_str.to_lowercase();
342 if via_str.contains("vpn") {
343 return ConnectionType::VPN;
344 }
345 if via_str.contains("proxy") {
346 return ConnectionType::Proxy;
347 }
348 }
349
350 if let Some(ua) = request.headers().get("user-agent")
351 && let Ok(ua_str) = ua.to_str()
352 && ua_str.contains("Tor")
353 {
354 return ConnectionType::Tor;
355 }
356
357 match ip_address {
358 Some(ip) => {
359 if self.corporate_networks.iter().any(|n| n.contains(*ip)) {
360 ConnectionType::Corporate
361 } else {
362 ConnectionType::Direct
363 }
364 }
365 None => ConnectionType::Unknown,
367 }
368 }
369
370 fn assess_security_level(&self, request: &Request) -> SecurityLevel {
372 let path = request.uri().path();
373
374 match path {
375 _ if path.starts_with("/admin/system/") => SecurityLevel::Critical,
376 _ if path.starts_with("/admin/") => SecurityLevel::High,
377 _ if path.contains("/secrets/") => SecurityLevel::Critical,
378 _ if path.contains("/keys/") => SecurityLevel::High,
379 _ if path.starts_with("/api/") => SecurityLevel::Medium,
380 _ => SecurityLevel::Low,
381 }
382 }
383
384 fn calculate_risk_score(
386 &self,
387 request: &Request,
388 ip_address: &Option<IpAddr>,
389 user_agent: &Option<String>,
390 ) -> u8 {
391 let mut risk_score = 0u8;
392
393 let path = request.uri().path();
395 if path.starts_with("/admin/") {
396 risk_score += 30;
397 } else if path.contains("/secrets/") || path.contains("/keys/") {
398 risk_score += 40;
399 } else if path.starts_with("/api/") {
400 risk_score += 10;
401 }
402
403 let connection_type = self.analyze_connection_type(request, ip_address);
405 match connection_type {
406 ConnectionType::Tor => risk_score += 50,
407 ConnectionType::VPN => risk_score += 20,
408 ConnectionType::Proxy => risk_score += 15,
409 ConnectionType::Corporate => risk_score = risk_score.saturating_sub(10),
410 ConnectionType::Direct => {}
411 ConnectionType::Unknown => risk_score += 10,
412 }
413
414 let device_type = self.detect_device_type(user_agent);
416 match device_type {
417 DeviceType::Mobile => risk_score += 5,
418 DeviceType::Unknown => risk_score += 15,
419 _ => {}
420 }
421
422 let now = Utc::now();
424 match self.classify_time_of_day(now) {
425 TimeOfDay::AfterHours => risk_score += 10,
426 TimeOfDay::Weekend => risk_score += 5,
427 _ => {}
428 }
429
430 if user_agent.is_none() {
432 risk_score += 20;
433 }
434
435 risk_score.min(100)
437 }
438
439 fn extract_custom_attributes(&self, request: &Request) -> HashMap<String, String> {
441 let mut attributes = HashMap::new();
442
443 for (name, value) in request.headers() {
445 let name_str = name.as_str().to_lowercase();
446 if let Some(attr_name) = name_str.strip_prefix("x-auth-")
447 && let Ok(value_str) = value.to_str()
448 {
449 attributes.insert(attr_name.to_string(), value_str.to_string());
450 }
451 }
452
453 if let Some(query) = request.uri().query() {
455 for pair in query.split('&') {
456 if let Some((key, value)) = pair.split_once('=')
457 && key.starts_with("ctx_")
458 {
459 attributes.insert(
460 key.strip_prefix("ctx_").unwrap().to_string(),
461 urlencoding::decode(value).unwrap_or_default().to_string(),
462 );
463 }
464 }
465 }
466
467 attributes
468 }
469
470 pub fn enrich_context(&self, mut context: AuthorizationContext) -> AuthorizationContext {
472 let current_risk = context.risk_score;
474 context.risk_score = std::cmp::max(current_risk, 1); let now = chrono::Utc::now();
478 context
479 .custom_attributes
480 .insert("enriched_timestamp".to_string(), now.to_rfc3339());
481
482 context.custom_attributes.insert(
484 "security_assessment".to_string(),
485 match context.security_level {
486 SecurityLevel::Low => "basic".to_string(),
487 SecurityLevel::Medium => "standard".to_string(),
488 SecurityLevel::High => "enhanced".to_string(),
489 SecurityLevel::Critical => "maximum".to_string(),
490 },
491 );
492
493 context
494 }
495}
496
497pub struct ConditionalEvaluator {
500 context_builder: ContextBuilder,
501}
502
503impl ConditionalEvaluator {
504 pub fn new(context_builder: ContextBuilder) -> Self {
506 Self { context_builder }
507 }
508
509 pub fn evaluate_time_conditions(
511 &self,
512 context: &AuthorizationContext,
513 conditions: &HashMap<String, String>,
514 ) -> bool {
515 if let Some(require_business_hours) = conditions.get("require_business_hours")
517 && require_business_hours == "true"
518 {
519 match context.time_of_day {
520 TimeOfDay::BusinessHours => {}
521 _ => return false,
522 }
523 }
524
525 if let Some(require_weekday) = conditions.get("require_weekday")
527 && require_weekday == "true"
528 {
529 match context.day_type {
530 DayType::Weekday => {}
531 _ => return false,
532 }
533 }
534
535 true
536 }
537
538 pub fn evaluate_location_conditions(
540 &self,
541 context: &AuthorizationContext,
542 conditions: &HashMap<String, String>,
543 ) -> bool {
544 if let Some(require_corporate) = conditions.get("require_corporate_network")
546 && require_corporate == "true"
547 {
548 match context.connection_type {
549 ConnectionType::Corporate => {}
550 _ => return false,
551 }
552 }
553
554 if let Some(block_vpn) = conditions.get("block_vpn")
556 && block_vpn == "true"
557 {
558 match context.connection_type {
559 ConnectionType::VPN | ConnectionType::Tor => return false,
560 _ => {}
561 }
562 }
563
564 true
565 }
566
567 pub fn evaluate_device_conditions(
569 &self,
570 context: &AuthorizationContext,
571 conditions: &HashMap<String, String>,
572 ) -> bool {
573 if let Some(allowed_devices) = conditions.get("allowed_device_types") {
575 let allowed: Vec<&str> = allowed_devices.split(',').collect();
576 let device_str = format!("{:?}", context.device_type).to_lowercase();
577
578 if !allowed.contains(&device_str.as_str()) {
579 return false;
580 }
581 }
582
583 true
584 }
585
586 pub fn evaluate_risk_conditions(
588 &self,
589 context: &AuthorizationContext,
590 conditions: &HashMap<String, String>,
591 ) -> bool {
592 if let Some(max_risk_str) = conditions.get("max_risk_score")
594 && let Ok(max_risk) = max_risk_str.parse::<u8>()
595 && context.risk_score > max_risk
596 {
597 return false;
598 }
599
600 true
601 }
602
603 pub fn evaluate_conditional_permission(
606 &self,
607 context: &AuthorizationContext,
608 permission_conditions: &HashMap<String, String>,
609 ) -> bool {
610 tracing::debug!(
612 "Evaluating conditional permission with conditions: {:?}",
613 permission_conditions
614 );
615
616 if permission_conditions.is_empty() {
618 return true;
619 }
620
621 let _enriched_context = self.context_builder.enrich_context(context.clone());
623
624 let time_check = self.evaluate_time_conditions(context, permission_conditions);
626 let location_check = self.evaluate_location_conditions(context, permission_conditions);
627 let device_check = self.evaluate_device_conditions(context, permission_conditions);
628 let risk_check = self.evaluate_risk_conditions(context, permission_conditions);
629
630 let result = time_check && location_check && device_check && risk_check;
631
632 tracing::info!(
633 "Conditional evaluation result: {} (time: {}, location: {}, device: {}, risk: {})",
634 result,
635 time_check,
636 location_check,
637 device_check,
638 risk_check
639 );
640
641 result
642 }
643
644 pub fn evaluate_all_conditions(
646 &self,
647 context: &AuthorizationContext,
648 conditions: &HashMap<String, String>,
649 ) -> bool {
650 self.evaluate_time_conditions(context, conditions)
651 && self.evaluate_location_conditions(context, conditions)
652 && self.evaluate_device_conditions(context, conditions)
653 && self.evaluate_risk_conditions(context, conditions)
654 }
655}
656
657#[cfg(test)]
658mod tests {
659 use super::*;
660
661 #[test]
662 fn test_context_builder_creation() {
663 let builder = ContextBuilder::new()
664 .with_business_hours(8, 18)
665 .with_holidays(vec![chrono::NaiveDate::from_ymd_opt(2024, 12, 25).unwrap()]);
666
667 assert_eq!(builder.business_start, 8);
668 assert_eq!(builder.business_end, 18);
669 assert_eq!(builder.holidays.len(), 1);
670 }
671
672 #[test]
673 fn test_time_classification() {
674 let builder = ContextBuilder::new();
675
676 let business_time = chrono::Utc::now()
678 .with_hour(14)
679 .unwrap()
680 .with_minute(0)
681 .unwrap();
682
683 match business_time.weekday() {
684 Weekday::Sat | Weekday::Sun => {
685 assert!(matches!(
686 builder.classify_time_of_day(business_time),
687 TimeOfDay::Weekend
688 ));
689 }
690 _ => {
691 assert!(matches!(
692 builder.classify_time_of_day(business_time),
693 TimeOfDay::BusinessHours
694 ));
695 }
696 }
697 }
698
699 #[test]
700 fn test_device_detection() {
701 let builder = ContextBuilder::new();
702
703 let mobile_ua = Some("Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)".to_string());
704 assert!(matches!(
705 builder.detect_device_type(&mobile_ua),
706 DeviceType::Mobile
707 ));
708
709 let desktop_ua =
710 Some("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36".to_string());
711 assert!(matches!(
712 builder.detect_device_type(&desktop_ua),
713 DeviceType::Desktop
714 ));
715
716 assert!(matches!(
717 builder.detect_device_type(&None),
718 DeviceType::Unknown
719 ));
720 }
721
722 #[test]
723 fn test_risk_calculation() {
724 let _builder = ContextBuilder::new();
725
726 }
730}