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(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
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 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#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
75pub enum TimeOfDay {
76 BusinessHours,
77 AfterHours,
78 Weekend,
79 Holiday,
80}
81
82#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
84pub enum DayType {
85 Weekday,
86 Weekend,
87 Holiday,
88}
89
90#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
92pub enum DeviceType {
93 Desktop,
94 Mobile,
95 Tablet,
96 Unknown,
97}
98
99#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
101pub enum ConnectionType {
102 Direct,
103 VPN,
104 Proxy,
105 Tor,
106 Corporate,
107 Unknown,
108}
109
110#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
112pub enum SecurityLevel {
113 Low,
114 Medium,
115 High,
116 Critical,
117}
118
119pub struct ContextBuilder {
121 holidays: Vec<chrono::NaiveDate>,
123 business_start: u8,
125 business_end: u8,
126 corporate_networks: Vec<ipnetwork::IpNetwork>,
128 trusted_proxies: Vec<IpAddr>,
130}
131
132impl Default for ContextBuilder {
133 fn default() -> Self {
134 Self::new()
135 }
136}
137
138impl ContextBuilder {
139 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 pub fn with_trusted_proxies(mut self, proxies: Vec<IpAddr>) -> Self {
158 self.trusted_proxies = proxies;
159 self
160 }
161
162 pub fn with_business_hours(mut self, start: u8, end: u8) -> Self {
164 self.business_start = start;
165 self.business_end = end;
166 self
167 }
168
169 pub fn with_corporate_networks(mut self, networks: Vec<ipnetwork::IpNetwork>) -> Self {
171 self.corporate_networks = networks;
172 self
173 }
174
175 pub fn with_holidays(mut self, holidays: Vec<chrono::NaiveDate>) -> Self {
177 self.holidays = holidays;
178 self
179 }
180
181 pub fn build_context(&self, request: &Request, auth_token: &AuthToken) -> AuthorizationContext {
183 let now = Utc::now();
184 let ip_address = self.extract_ip_address(request);
185 let user_agent = self.extract_user_agent(request);
186
187 AuthorizationContext {
188 user_id: auth_token.user_id.clone(),
189 roles: auth_token.roles.clone(),
190 session_id: auth_token.metadata.session_id.clone(),
191
192 method: request.method().to_string(),
193 path: request.uri().path().to_string(),
194 ip_address,
195 user_agent: user_agent.clone(),
196
197 request_time: now,
198 time_of_day: self.classify_time_of_day(now),
199 day_type: self.classify_day_type(now),
200
201 device_type: self.detect_device_type(&user_agent),
202 connection_type: self.analyze_connection_type(request, &ip_address),
203
204 security_level: self.assess_security_level(request),
205 risk_score: self.calculate_risk_score(request, &ip_address, &user_agent),
206
207 custom_attributes: self.extract_custom_attributes(request),
208 }
209 }
210
211 pub fn to_hashmap(&self, context: &AuthorizationContext) -> HashMap<String, String> {
213 let mut map = HashMap::new();
214
215 map.insert("user_id".to_string(), context.user_id.clone());
217 map.insert("roles".to_string(), context.roles.join(","));
218 if let Some(session_id) = &context.session_id {
219 map.insert("session_id".to_string(), session_id.clone());
220 }
221
222 map.insert("method".to_string(), context.method.clone());
224 map.insert("path".to_string(), context.path.clone());
225 if let Some(ip) = &context.ip_address {
226 map.insert("ip_address".to_string(), ip.to_string());
227 }
228 if let Some(ua) = &context.user_agent {
229 map.insert("user_agent".to_string(), ua.clone());
230 }
231
232 map.insert(
234 "time_of_day".to_string(),
235 format!("{:?}", context.time_of_day).to_lowercase(),
236 );
237 map.insert(
238 "day_type".to_string(),
239 format!("{:?}", context.day_type).to_lowercase(),
240 );
241 map.insert(
242 "request_hour".to_string(),
243 context.request_time.hour().to_string(),
244 );
245 map.insert(
246 "request_weekday".to_string(),
247 context.request_time.weekday().to_string(),
248 );
249
250 map.insert(
252 "device_type".to_string(),
253 format!("{:?}", context.device_type).to_lowercase(),
254 );
255 map.insert(
256 "connection_type".to_string(),
257 format!("{:?}", context.connection_type).to_lowercase(),
258 );
259
260 map.insert(
262 "security_level".to_string(),
263 format!("{:?}", context.security_level).to_lowercase(),
264 );
265 map.insert("risk_score".to_string(), context.risk_score.to_string());
266
267 for (key, value) in &context.custom_attributes {
269 map.insert(format!("custom_{}", key), value.clone());
270 }
271
272 map
273 }
274
275 fn extract_ip_address(&self, request: &Request) -> Option<IpAddr> {
280 let peer = request
281 .extensions()
282 .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
283 .map(|info| info.0.ip())?;
284 Some(crate::api::middleware::forwarded_client_ip(
285 peer,
286 request.headers(),
287 &self.trusted_proxies,
288 ))
289 }
290
291 fn extract_user_agent(&self, request: &Request) -> Option<String> {
293 request
294 .headers()
295 .get("user-agent")
296 .and_then(|ua| ua.to_str().ok())
297 .map(|s| s.to_string())
298 }
299
300 fn classify_time_of_day(&self, now: DateTime<Utc>) -> TimeOfDay {
302 let date = now.date_naive();
303
304 if self.holidays.contains(&date) {
306 return TimeOfDay::Holiday;
307 }
308
309 match now.weekday() {
311 Weekday::Sat | Weekday::Sun => return TimeOfDay::Weekend,
312 _ => {}
313 }
314
315 let hour = now.hour() as u8;
317 if hour >= self.business_start && hour < self.business_end {
318 TimeOfDay::BusinessHours
319 } else {
320 TimeOfDay::AfterHours
321 }
322 }
323
324 fn classify_day_type(&self, now: DateTime<Utc>) -> DayType {
326 let date = now.date_naive();
327
328 if self.holidays.contains(&date) {
329 DayType::Holiday
330 } else {
331 match now.weekday() {
332 Weekday::Sat | Weekday::Sun => DayType::Weekend,
333 _ => DayType::Weekday,
334 }
335 }
336 }
337
338 fn detect_device_type(&self, user_agent: &Option<String>) -> DeviceType {
340 let ua = match user_agent {
341 Some(ua) => ua.to_lowercase(),
342 None => return DeviceType::Unknown,
343 };
344
345 if ua.contains("mobile") || ua.contains("android") || ua.contains("iphone") {
346 DeviceType::Mobile
347 } else if ua.contains("tablet") || ua.contains("ipad") {
348 DeviceType::Tablet
349 } else if ua.contains("mozilla") || ua.contains("chrome") || ua.contains("firefox") {
350 DeviceType::Desktop
351 } else {
352 DeviceType::Unknown
353 }
354 }
355
356 fn analyze_connection_type(
363 &self,
364 request: &Request,
365 ip_address: &Option<IpAddr>,
366 ) -> ConnectionType {
367 if let Some(via) = request.headers().get("via")
368 && let Ok(via_str) = via.to_str()
369 {
370 let via_str = via_str.to_lowercase();
371 if via_str.contains("vpn") {
372 return ConnectionType::VPN;
373 }
374 if via_str.contains("proxy") {
375 return ConnectionType::Proxy;
376 }
377 }
378
379 if let Some(ua) = request.headers().get("user-agent")
380 && let Ok(ua_str) = ua.to_str()
381 && ua_str.contains("Tor")
382 {
383 return ConnectionType::Tor;
384 }
385
386 match ip_address {
387 Some(ip) => {
388 if self.corporate_networks.iter().any(|n| n.contains(*ip)) {
389 ConnectionType::Corporate
390 } else {
391 ConnectionType::Direct
392 }
393 }
394 None => ConnectionType::Unknown,
396 }
397 }
398
399 fn assess_security_level(&self, request: &Request) -> SecurityLevel {
401 let path = request.uri().path();
402
403 match path {
404 _ if path.starts_with("/admin/system/") => SecurityLevel::Critical,
405 _ if path.starts_with("/admin/") => SecurityLevel::High,
406 _ if path.contains("/secrets/") => SecurityLevel::Critical,
407 _ if path.contains("/keys/") => SecurityLevel::High,
408 _ if path.starts_with("/api/") => SecurityLevel::Medium,
409 _ => SecurityLevel::Low,
410 }
411 }
412
413 fn calculate_risk_score(
415 &self,
416 request: &Request,
417 ip_address: &Option<IpAddr>,
418 user_agent: &Option<String>,
419 ) -> u8 {
420 let mut risk_score = 0u8;
421
422 let path = request.uri().path();
424 if path.starts_with("/admin/") {
425 risk_score += 30;
426 } else if path.contains("/secrets/") || path.contains("/keys/") {
427 risk_score += 40;
428 } else if path.starts_with("/api/") {
429 risk_score += 10;
430 }
431
432 let connection_type = self.analyze_connection_type(request, ip_address);
434 match connection_type {
435 ConnectionType::Tor => risk_score += 50,
436 ConnectionType::VPN => risk_score += 20,
437 ConnectionType::Proxy => risk_score += 15,
438 ConnectionType::Corporate => risk_score = risk_score.saturating_sub(10),
439 ConnectionType::Direct => {}
440 ConnectionType::Unknown => risk_score += 10,
441 }
442
443 let device_type = self.detect_device_type(user_agent);
445 match device_type {
446 DeviceType::Mobile => risk_score += 5,
447 DeviceType::Unknown => risk_score += 15,
448 _ => {}
449 }
450
451 let now = Utc::now();
453 match self.classify_time_of_day(now) {
454 TimeOfDay::AfterHours => risk_score += 10,
455 TimeOfDay::Weekend => risk_score += 5,
456 _ => {}
457 }
458
459 if user_agent.is_none() {
461 risk_score += 20;
462 }
463
464 risk_score.min(100)
466 }
467
468 fn extract_custom_attributes(&self, request: &Request) -> HashMap<String, String> {
470 let mut attributes = HashMap::new();
471
472 for (name, value) in request.headers() {
474 let name_str = name.as_str().to_lowercase();
475 if let Some(attr_name) = name_str.strip_prefix("x-auth-")
476 && let Ok(value_str) = value.to_str()
477 {
478 attributes.insert(attr_name.to_string(), value_str.to_string());
479 }
480 }
481
482 if let Some(query) = request.uri().query() {
484 for pair in query.split('&') {
485 if let Some((key, value)) = pair.split_once('=')
486 && key.starts_with("ctx_")
487 {
488 attributes.insert(
489 key.strip_prefix("ctx_").unwrap().to_string(),
490 urlencoding::decode(value).unwrap_or_default().to_string(),
491 );
492 }
493 }
494 }
495
496 attributes
497 }
498
499 pub fn enrich_context(&self, mut context: AuthorizationContext) -> AuthorizationContext {
501 let current_risk = context.risk_score;
503 context.risk_score = std::cmp::max(current_risk, 1); let now = chrono::Utc::now();
507 context
508 .custom_attributes
509 .insert("enriched_timestamp".to_string(), now.to_rfc3339());
510
511 context.custom_attributes.insert(
513 "security_assessment".to_string(),
514 match context.security_level {
515 SecurityLevel::Low => "basic".to_string(),
516 SecurityLevel::Medium => "standard".to_string(),
517 SecurityLevel::High => "enhanced".to_string(),
518 SecurityLevel::Critical => "maximum".to_string(),
519 },
520 );
521
522 context
523 }
524}
525
526pub struct ConditionalEvaluator {
529 context_builder: ContextBuilder,
530}
531
532impl ConditionalEvaluator {
533 pub fn new(context_builder: ContextBuilder) -> Self {
535 Self { context_builder }
536 }
537
538 pub fn evaluate_time_conditions(
540 &self,
541 context: &AuthorizationContext,
542 conditions: &HashMap<String, String>,
543 ) -> bool {
544 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 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 pub fn evaluate_location_conditions(
569 &self,
570 context: &AuthorizationContext,
571 conditions: &HashMap<String, String>,
572 ) -> bool {
573 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 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 pub fn evaluate_device_conditions(
598 &self,
599 context: &AuthorizationContext,
600 conditions: &HashMap<String, String>,
601 ) -> bool {
602 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 pub fn evaluate_risk_conditions(
617 &self,
618 context: &AuthorizationContext,
619 conditions: &HashMap<String, String>,
620 ) -> bool {
621 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 pub fn evaluate_conditional_permission(
635 &self,
636 context: &AuthorizationContext,
637 permission_conditions: &HashMap<String, String>,
638 ) -> bool {
639 tracing::debug!(
641 "Evaluating conditional permission with conditions: {:?}",
642 permission_conditions
643 );
644
645 if permission_conditions.is_empty() {
647 return true;
648 }
649
650 let _enriched_context = self.context_builder.enrich_context(context.clone());
652
653 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 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 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 }
759}