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 from_api_state(state: &crate::api::ApiState) -> Self {
153 Self::new().with_trusted_proxies(state.trusted_proxies.clone())
154 }
155
156 pub fn with_trusted_proxies(mut self, proxies: Vec<IpAddr>) -> Self {
161 self.trusted_proxies = proxies;
162 self
163 }
164
165 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 pub fn with_corporate_networks(mut self, networks: Vec<ipnetwork::IpNetwork>) -> Self {
174 self.corporate_networks = networks;
175 self
176 }
177
178 pub fn with_holidays(mut self, holidays: Vec<chrono::NaiveDate>) -> Self {
180 self.holidays = holidays;
181 self
182 }
183
184 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 pub fn to_hashmap(&self, context: &AuthorizationContext) -> HashMap<String, String> {
216 let mut map = HashMap::new();
217
218 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 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 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 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 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 for (key, value) in &context.custom_attributes {
272 map.insert(format!("custom_{}", key), value.clone());
273 }
274
275 map
276 }
277
278 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 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 fn classify_time_of_day(&self, now: DateTime<Utc>) -> TimeOfDay {
305 let date = now.date_naive();
306
307 if self.holidays.contains(&date) {
309 return TimeOfDay::Holiday;
310 }
311
312 match now.weekday() {
314 Weekday::Sat | Weekday::Sun => return TimeOfDay::Weekend,
315 _ => {}
316 }
317
318 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 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 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 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 None => ConnectionType::Unknown,
399 }
400 }
401
402 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 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 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 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 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 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 if user_agent.is_none() {
464 risk_score += 20;
465 }
466
467 risk_score.min(100)
469 }
470
471 fn extract_custom_attributes(&self, request: &Request) -> HashMap<String, String> {
473 let mut attributes = HashMap::new();
474
475 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 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 pub fn enrich_context(&self, mut context: AuthorizationContext) -> AuthorizationContext {
506 let current_risk = context.risk_score;
508 context.risk_score = std::cmp::max(current_risk, 1); let now = chrono::Utc::now();
512 context
513 .custom_attributes
514 .insert("enriched_timestamp".to_string(), now.to_rfc3339());
515
516 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
531pub struct ConditionalEvaluator {
533 context_builder: ContextBuilder,
534}
535
536impl ConditionalEvaluator {
537 pub fn new(context_builder: ContextBuilder) -> Self {
539 Self { context_builder }
540 }
541
542 pub fn evaluate_time_conditions(
544 &self,
545 context: &AuthorizationContext,
546 conditions: &HashMap<String, String>,
547 ) -> bool {
548 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 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 pub fn evaluate_location_conditions(
573 &self,
574 context: &AuthorizationContext,
575 conditions: &HashMap<String, String>,
576 ) -> bool {
577 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 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 pub fn evaluate_device_conditions(
602 &self,
603 context: &AuthorizationContext,
604 conditions: &HashMap<String, String>,
605 ) -> bool {
606 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 pub fn evaluate_risk_conditions(
621 &self,
622 context: &AuthorizationContext,
623 conditions: &HashMap<String, String>,
624 ) -> bool {
625 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 pub fn evaluate_conditional_permission(
639 &self,
640 context: &AuthorizationContext,
641 permission_conditions: &HashMap<String, String>,
642 ) -> bool {
643 tracing::debug!(
645 "Evaluating conditional permission with conditions: {:?}",
646 permission_conditions
647 );
648
649 if permission_conditions.is_empty() {
651 return true;
652 }
653
654 let _enriched_context = self.context_builder.enrich_context(context.clone());
656
657 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 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 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 }
763}