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 from_api_state(state: &crate::api::ApiState) -> Self {
124 Self::new().with_trusted_proxies(state.trusted_proxies.clone())
125 }
126
127 pub fn with_trusted_proxies(mut self, proxies: Vec<IpAddr>) -> Self {
132 self.trusted_proxies = proxies;
133 self
134 }
135
136 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 pub fn with_corporate_networks(mut self, networks: Vec<ipnetwork::IpNetwork>) -> Self {
145 self.corporate_networks = networks;
146 self
147 }
148
149 pub fn with_holidays(mut self, holidays: Vec<chrono::NaiveDate>) -> Self {
151 self.holidays = holidays;
152 self
153 }
154
155 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 pub fn to_hashmap(&self, context: &AuthorizationContext) -> HashMap<String, String> {
187 let mut map = HashMap::new();
188
189 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 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 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 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 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 for (key, value) in &context.custom_attributes {
243 map.insert(format!("custom_{}", key), value.clone());
244 }
245
246 map
247 }
248
249 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 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 fn classify_time_of_day(&self, now: DateTime<Utc>) -> TimeOfDay {
276 let date = now.date_naive();
277
278 if self.holidays.contains(&date) {
280 return TimeOfDay::Holiday;
281 }
282
283 match now.weekday() {
285 Weekday::Sat | Weekday::Sun => return TimeOfDay::Weekend,
286 _ => {}
287 }
288
289 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 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 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 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 None => ConnectionType::Unknown,
370 }
371 }
372
373 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 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 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 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 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 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 if user_agent.is_none() {
435 risk_score += 20;
436 }
437
438 risk_score.min(100)
440 }
441
442 fn extract_custom_attributes(&self, request: &Request) -> HashMap<String, String> {
444 let mut attributes = HashMap::new();
445
446 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 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 pub fn enrich_context(&self, mut context: AuthorizationContext) -> AuthorizationContext {
477 let current_risk = context.risk_score;
479 context.risk_score = std::cmp::max(current_risk, 1); let now = chrono::Utc::now();
483 context
484 .custom_attributes
485 .insert("enriched_timestamp".to_string(), now.to_rfc3339());
486
487 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
502pub struct ConditionalEvaluator {
504 context_builder: ContextBuilder,
505}
506
507impl ConditionalEvaluator {
508 pub fn new(context_builder: ContextBuilder) -> Self {
510 Self { context_builder }
511 }
512
513 pub fn evaluate_time_conditions(
515 &self,
516 context: &AuthorizationContext,
517 conditions: &HashMap<String, String>,
518 ) -> bool {
519 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 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 pub fn evaluate_location_conditions(
544 &self,
545 context: &AuthorizationContext,
546 conditions: &HashMap<String, String>,
547 ) -> bool {
548 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 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 pub fn evaluate_device_conditions(
573 &self,
574 context: &AuthorizationContext,
575 conditions: &HashMap<String, String>,
576 ) -> bool {
577 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 pub fn evaluate_risk_conditions(
592 &self,
593 context: &AuthorizationContext,
594 conditions: &HashMap<String, String>,
595 ) -> bool {
596 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 pub fn evaluate_conditional_permission(
610 &self,
611 context: &AuthorizationContext,
612 permission_conditions: &HashMap<String, String>,
613 ) -> bool {
614 tracing::debug!(
616 "Evaluating conditional permission with conditions: {:?}",
617 permission_conditions
618 );
619
620 if permission_conditions.is_empty() {
622 return true;
623 }
624
625 let _enriched_context = self.context_builder.enrich_context(context.clone());
627
628 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 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 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 }
734}