1use super::expression::{BinaryOp, Expression, UnaryOp};
2use super::violation::{Severity, Violation};
3use crate::graph::Graph;
4use crate::policy::ThreeValuedBool;
5use crate::units::get_default_registry;
6use crate::{ConceptId, SemanticVersion};
7use rust_decimal::prelude::{FromPrimitive, FromStr};
8use rust_decimal::Decimal;
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12pub enum PolicyModality {
13 Obligation,
14 Prohibition,
15 Permission,
16}
17
18#[allow(unused_imports)]
20pub use PolicyModality as DeonticModality;
21
22#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
23pub enum PolicyKind {
24 Constraint,
25 Derivation,
26 Obligation,
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct Policy {
31 pub id: ConceptId,
32 pub name: String,
33 pub namespace: String,
34 pub version: SemanticVersion,
35 expression: Expression,
36 pub modality: PolicyModality,
37 pub kind: PolicyKind,
38 pub priority: i32,
39 pub rationale: Option<String>,
40 pub tags: Vec<String>,
41 #[serde(skip)]
42 cached_normalized_expr: std::sync::OnceLock<super::NormalizedExpression>,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct EvaluationResult {
47 pub is_satisfied: bool,
50 pub is_satisfied_tristate: Option<bool>,
52 pub violations: Vec<Violation>,
53}
54
55impl Policy {
56 #[must_use]
60 pub fn normalized_expression(&self) -> &super::NormalizedExpression {
61 self.cached_normalized_expr
62 .get_or_init(|| self.expression.normalize())
63 }
64
65 pub fn expression(&self) -> &Expression {
67 &self.expression
68 }
69
70 pub fn set_expression(&mut self, expr: Expression) {
72 self.expression = expr;
73 self.cached_normalized_expr = std::sync::OnceLock::new();
75 }
76
77 pub fn new(name: impl Into<String>, expression: Expression) -> Self {
78 let name = name.into();
79 Self {
80 id: ConceptId::from_concept("default", &name),
81 name,
82 namespace: "default".to_string(),
83 version: SemanticVersion::default(),
84 expression,
85 modality: PolicyModality::Obligation,
86 kind: PolicyKind::Constraint,
87 priority: 0,
88 rationale: None,
89 tags: Vec::new(),
90 cached_normalized_expr: std::sync::OnceLock::new(),
91 }
92 }
93
94 pub fn new_with_namespace(
95 name: impl Into<String>,
96 namespace: impl Into<String>,
97 expression: Expression,
98 ) -> Self {
99 let namespace = namespace.into();
100 let name = name.into();
101 let id = ConceptId::from_concept(&namespace, &name);
102
103 Self {
104 id,
105 name,
106 namespace,
107 version: SemanticVersion::default(),
108 expression,
109 modality: PolicyModality::Obligation,
110 kind: PolicyKind::Constraint,
111 priority: 0,
112 rationale: None,
113 tags: Vec::new(),
114 cached_normalized_expr: std::sync::OnceLock::new(),
115 }
116 }
117
118 pub fn with_modality(mut self, modality: PolicyModality) -> Self {
119 self.modality = modality;
120 self
121 }
122
123 pub fn with_version(mut self, version: SemanticVersion) -> Self {
124 self.version = version;
125 self
126 }
127
128 pub fn with_kind(mut self, kind: PolicyKind) -> Self {
129 self.kind = kind;
130 self
131 }
132
133 pub fn with_priority(mut self, priority: i32) -> Self {
134 self.priority = priority;
135 self
136 }
137
138 pub fn with_rationale(mut self, rationale: impl Into<String>) -> Self {
139 self.rationale = Some(rationale.into());
140 self
141 }
142
143 pub fn with_tags<I, S>(mut self, tags: I) -> Self
144 where
145 I: IntoIterator<Item = S>,
146 S: Into<String>,
147 {
148 self.tags = tags.into_iter().map(Into::into).collect();
149 self
150 }
151
152 pub fn with_metadata(
153 mut self,
154 kind: Option<PolicyKind>,
155 modality: Option<PolicyModality>,
156 priority: Option<i32>,
157 rationale: Option<String>,
158 tags: Vec<String>,
159 ) -> Self {
160 if let Some(kind) = kind {
161 self.kind = kind;
162 }
163 if let Some(modality) = modality {
164 self.modality = modality;
165 }
166 if let Some(priority) = priority {
167 self.priority = priority;
168 }
169 self.rationale = rationale;
170 if !tags.is_empty() {
171 self.tags = tags;
172 }
173 self
174 }
175
176 pub fn kind(&self) -> &PolicyKind {
177 &self.kind
178 }
179
180 pub fn evaluate(&self, graph: &Graph) -> Result<EvaluationResult, String> {
181 self.evaluate_with_mode(graph, graph.use_three_valued_logic())
182 }
183
184 pub fn evaluate_with_mode(
185 &self,
186 graph: &Graph,
187 use_three_valued_logic: bool,
188 ) -> Result<EvaluationResult, String> {
189 Self::validate_aggregation_usage(&self.expression, true)?;
190
191 let expanded = self.expression.expand(graph)?;
192
193 let is_satisfied_tristate: Option<bool> = if use_three_valued_logic {
196 match self.evaluate_expression_three_valued(&expanded, graph)? {
197 ThreeValuedBool::True => Some(true),
198 ThreeValuedBool::False => Some(false),
199 ThreeValuedBool::Null => None,
200 }
201 } else {
202 Some(self.evaluate_expression_boolean(&expanded, graph)?)
203 };
204
205 let is_satisfied = is_satisfied_tristate.unwrap_or(false);
206
207 let violations = if is_satisfied_tristate == Some(true) {
208 vec![]
209 } else if is_satisfied_tristate == Some(false) {
210 vec![Violation::new(
211 &self.name,
212 format!("Policy '{}' was violated", self.name),
213 self.modality.to_severity(),
214 )]
215 } else {
216 vec![Violation::new(
218 &self.name,
219 format!("Policy '{}' evaluation is UNKNOWN (NULL)", self.name),
220 self.modality.to_severity(),
221 )]
222 };
223
224 Ok(EvaluationResult {
225 is_satisfied,
226 is_satisfied_tristate,
227 violations,
228 })
229 }
230
231 fn validate_aggregation_usage(
232 expr: &Expression,
233 in_boolean_context: bool,
234 ) -> Result<(), String> {
235 match expr {
236 Expression::Aggregation { .. } | Expression::AggregationComprehension { .. } => {
237 if in_boolean_context {
238 Err("Aggregation in boolean context requires explicit comparison (e.g., COUNT(...) > 0)".to_string())
239 } else {
240 Ok(())
241 }
242 }
243 Expression::Binary { op, left, right } => {
244 let child_boolean = matches!(op, BinaryOp::And | BinaryOp::Or);
245 Self::validate_aggregation_usage(left, child_boolean)?;
246 Self::validate_aggregation_usage(right, child_boolean)?;
247 Ok(())
248 }
249 Expression::Unary { op, operand } => {
250 let child_boolean = matches!(op, UnaryOp::Not);
251 Self::validate_aggregation_usage(operand, child_boolean)
252 }
253 Expression::Quantifier {
254 collection,
255 condition,
256 ..
257 } => {
258 Self::validate_aggregation_usage(collection, false)?;
259 Self::validate_aggregation_usage(condition, true)
260 }
261 Expression::GroupBy {
262 collection,
263 filter,
264 key,
265 condition,
266 ..
267 } => {
268 Self::validate_aggregation_usage(collection, false)?;
269 if let Some(f) = filter {
270 Self::validate_aggregation_usage(f, true)?;
271 }
272 Self::validate_aggregation_usage(key, false)?;
273 Self::validate_aggregation_usage(condition, true)
274 }
275 _ => Ok(()),
276 }
277 }
278
279 fn evaluate_expression_boolean(
280 &self,
281 expr: &Expression,
282 graph: &Graph,
283 ) -> Result<bool, String> {
284 match expr {
285 Expression::Literal(v) => v
286 .as_bool()
287 .ok_or_else(|| format!("Expected boolean literal, got: {}", v)),
288 Expression::Variable(name) => {
289 Err(format!("Cannot evaluate unexpanded variable: {}", name))
290 }
291 Expression::Cast { .. } => {
292 let val = Self::get_runtime_value(expr, graph)?;
293 val.as_bool()
294 .ok_or_else(|| format!("Expected boolean from cast, got: {}", val))
295 }
296 Expression::Binary { op, left, right } => match op {
297 BinaryOp::And | BinaryOp::Or => {
298 let left_val = self.evaluate_expression_boolean(left, graph)?;
299 let right_val = self.evaluate_expression_boolean(right, graph)?;
300
301 Ok(match op {
302 BinaryOp::And => left_val && right_val,
303 BinaryOp::Or => left_val || right_val,
304 _ => unreachable!(),
305 })
306 }
307 BinaryOp::Equal | BinaryOp::NotEqual => {
308 self.compare_values(left, right, graph, |l, r| match op {
309 BinaryOp::Equal => l == r,
310 BinaryOp::NotEqual => l != r,
311 _ => unreachable!(),
312 })
313 }
314 BinaryOp::GreaterThan
315 | BinaryOp::LessThan
316 | BinaryOp::GreaterThanOrEqual
317 | BinaryOp::LessThanOrEqual => {
318 self.compare_numeric(left, right, graph, |l, r| match op {
319 BinaryOp::GreaterThan => l > r,
320 BinaryOp::LessThan => l < r,
321 BinaryOp::GreaterThanOrEqual => l >= r,
322 BinaryOp::LessThanOrEqual => l <= r,
323 _ => unreachable!(),
324 })
325 }
326 BinaryOp::Plus | BinaryOp::Minus | BinaryOp::Multiply | BinaryOp::Divide => {
327 Err("Arithmetic operations not supported in boolean context".to_string())
328 }
329 BinaryOp::Contains | BinaryOp::StartsWith | BinaryOp::EndsWith => self
330 .compare_strings(left, right, graph, |l, r| match op {
331 BinaryOp::Contains => l.contains(r),
332 BinaryOp::StartsWith => l.starts_with(r),
333 BinaryOp::EndsWith => l.ends_with(r),
334 _ => unreachable!(),
335 }),
336 BinaryOp::HasRole => self.evaluate_has_role(left, right, graph),
337 BinaryOp::Matches => self.evaluate_pattern_match(left, right, graph),
338 BinaryOp::Before | BinaryOp::After | BinaryOp::During => {
339 let left_str = self.get_string_value(left, graph)?;
341 let right_str = self.get_string_value(right, graph)?;
342
343 let left_dt = chrono::DateTime::parse_from_rfc3339(&left_str).map_err(|e| {
345 format!("Failed to parse left timestamp '{}': {}", left_str, e)
346 })?;
347 let right_dt =
348 chrono::DateTime::parse_from_rfc3339(&right_str).map_err(|e| {
349 format!("Failed to parse right timestamp '{}': {}", right_str, e)
350 })?;
351
352 let result = match op {
353 BinaryOp::Before => left_dt < right_dt,
354 BinaryOp::After => left_dt > right_dt,
355 BinaryOp::During => {
356 return Err("'during' operator requires interval semantics which are not yet implemented. Use 'before' and 'after' for timestamp comparisons.".to_string())
357 }
358 _ => unreachable!(),
359 };
360 Ok(result)
361 }
362 },
363 Expression::Unary { op, operand } => {
364 let val = self.evaluate_expression_boolean(operand, graph)?;
365 Ok(match op {
366 UnaryOp::Not => !val,
367 UnaryOp::Negate => {
368 return Err("Negate operator not supported in boolean context".to_string())
369 }
370 })
371 }
372 Expression::Quantifier { .. } => {
373 Err("Cannot evaluate non-expanded quantifier".to_string())
374 }
375 Expression::MemberAccess { object, member } => {
376 let value = Self::get_runtime_value(expr, graph)?;
377 match value {
378 serde_json::Value::Bool(v) => Ok(v),
379 serde_json::Value::Null => Ok(false),
380 _ => Err(format!(
381 "Expected boolean value for member '{}.{}', but found {:?}",
382 object, member, value
383 )),
384 }
385 }
386 Expression::Aggregation { .. } => {
387 Err("Cannot evaluate non-expanded aggregation".to_string())
388 }
389 Expression::AggregationComprehension { .. } => {
390 Err("Cannot evaluate non-expanded aggregation comprehension".to_string())
391 }
392 Expression::QuantityLiteral { .. } => {
393 Err("Cannot evaluate quantity literal in boolean context".to_string())
394 }
395 Expression::TimeLiteral(_) => {
396 Err("Cannot evaluate time literal in boolean context".to_string())
397 }
398 Expression::IntervalLiteral { .. } => {
399 Err("Cannot evaluate interval literal in boolean context".to_string())
400 }
401 Expression::GroupBy { .. } => Err("Cannot evaluate non-expanded group_by".to_string()),
402 Expression::RoleReference { .. } => {
403 Err("Cannot evaluate role reference outside application policy context".to_string())
404 }
405 }
406 }
407
408 fn evaluate_expression_three_valued(
409 &self,
410 expr: &Expression,
411 graph: &Graph,
412 ) -> Result<ThreeValuedBool, String> {
413 use ThreeValuedBool as T;
414
415 match expr {
416 Expression::Literal(v) => Ok(T::from_option_bool(v.as_bool())),
417 Expression::Variable(name) => Err(format!("Cannot evaluate unexpanded variable: {}", name)),
418 Expression::Cast { .. } => {
419 let val = Self::get_runtime_value(expr, graph)?;
420 Ok(T::from_option_bool(val.as_bool()))
421 }
422 Expression::Binary { op, left, right } => match op {
423 BinaryOp::And | BinaryOp::Or => {
424 let l = self.evaluate_expression_three_valued(left, graph)?;
425 let r = self.evaluate_expression_three_valued(right, graph)?;
426 Ok(match op {
427 BinaryOp::And => l.and(r),
428 BinaryOp::Or => l.or(r),
429 _ => unreachable!(),
430 })
431 }
432 BinaryOp::Equal | BinaryOp::NotEqual => {
433 let left_val = Self::get_runtime_value(left, graph);
434 let right_val = Self::get_runtime_value(right, graph);
435 match (left_val, right_val) {
436 (Ok(lv), Ok(rv)) => {
437 if lv.is_null() || rv.is_null() {
439 Ok(T::Null)
440 } else {
441 let numeric_eq = match (
442 Self::parse_numeric_with_unit_value(&lv),
443 Self::parse_numeric_with_unit_value(&rv),
444 ) {
445 (Ok(ln), Ok(rn)) => {
446 self.normalize_units_nullable(ln, rn)?
447 .map(|(l, r)| l == r)
448 }
449 _ => None,
450 };
451
452 let equality = if let Some(eq) = numeric_eq {
453 Some(eq)
454 } else if lv.is_number() || rv.is_number() {
455 None
456 } else {
457 Some(lv == rv)
458 };
459
460 let eq = match (op, equality) {
461 (_, None) => return Ok(T::Null),
462 (BinaryOp::Equal, Some(true)) => true,
463 (BinaryOp::Equal, Some(false)) => false,
464 (BinaryOp::NotEqual, Some(true)) => false,
465 (BinaryOp::NotEqual, Some(false)) => true,
466 _ => unreachable!(),
467 };
468
469 Ok(T::from_option_bool(Some(eq)))
470 }
471 }
472 _ => Ok(T::Null),
473 }
474 }
475 BinaryOp::GreaterThan
476 | BinaryOp::LessThan
477 | BinaryOp::GreaterThanOrEqual
478 | BinaryOp::LessThanOrEqual => {
479 let left_v = Self::get_runtime_value(left, graph);
480 let right_v = Self::get_runtime_value(right, graph);
481 match (left_v, right_v) {
482 (Ok(lv), Ok(rv)) => {
483 if lv.is_null() || rv.is_null() {
484 Ok(T::Null)
485 } else {
486 let numeric = self
487 .normalize_units_nullable(
488 Self::parse_numeric_with_unit_value(&lv)
489 .ok()
490 .flatten(),
491 Self::parse_numeric_with_unit_value(&rv)
492 .ok()
493 .flatten(),
494 )?
495 .map(|(l, r)| match op {
496 BinaryOp::GreaterThan => l > r,
497 BinaryOp::LessThan => l < r,
498 BinaryOp::GreaterThanOrEqual => l >= r,
499 BinaryOp::LessThanOrEqual => l <= r,
500 _ => unreachable!(),
501 });
502
503 Ok(T::from_option_bool(numeric))
504 }
505 }
506 _ => Ok(T::Null),
507 }
508 }
509 BinaryOp::Plus | BinaryOp::Minus | BinaryOp::Multiply | BinaryOp::Divide => {
510 Err("Arithmetic operations not supported in boolean context".to_string())
511 }
512 BinaryOp::Contains | BinaryOp::StartsWith | BinaryOp::EndsWith => {
513 let left_v = Self::get_runtime_value(left, graph);
514 let right_v = Self::get_runtime_value(right, graph);
515 match (left_v, right_v) {
516 (Ok(lv), Ok(rv)) => {
517 if lv.is_null() || rv.is_null() {
518 Ok(T::Null)
519 } else if let (Some(ls), Some(rs)) = (lv.as_str(), rv.as_str()) {
520 let ok = match op {
521 BinaryOp::Contains => ls.contains(rs),
522 BinaryOp::StartsWith => ls.starts_with(rs),
523 BinaryOp::EndsWith => ls.ends_with(rs),
524 _ => unreachable!(),
525 };
526 Ok(T::from_option_bool(Some(ok)))
527 } else {
528 Ok(T::Null)
529 }
530 }
531 _ => Ok(T::Null),
532 }
533 }
534 BinaryOp::HasRole => {
535 let role_check = self.evaluate_has_role(left, right, graph)?;
536 Ok(T::from_option_bool(Some(role_check)))
537 }
538 BinaryOp::Matches => {
539 let left_v = Self::get_runtime_value(left, graph);
540 let right_v = Self::get_runtime_value(right, graph);
541
542 match (left_v, right_v) {
543 (Ok(lv), Ok(rv)) => {
544 if lv.is_null() || rv.is_null() {
545 return Ok(T::Null);
546 }
547
548 if let (Some(candidate), Some(pattern_name)) = (lv.as_str(), rv.as_str()) {
549 let pattern = graph
550 .find_pattern(pattern_name, Some(&self.namespace))
551 .ok_or_else(|| {
552 format!(
553 "Pattern '{}' not found in namespace '{}'",
554 pattern_name, self.namespace
555 )
556 })?;
557 let is_match = pattern.is_match(candidate).map_err(|e| {
558 format!(
559 "Pattern '{}' failed to evaluate: {}",
560 pattern_name, e
561 )
562 })?;
563 Ok(T::from_option_bool(Some(is_match)))
564 } else {
565 Ok(T::Null)
566 }
567 }
568 _ => Ok(T::Null),
569 }
570 }
571 BinaryOp::Before | BinaryOp::After | BinaryOp::During => {
572 if matches!(op, BinaryOp::During) {
574 return Err("'during' operator requires interval semantics which are not yet implemented. Use 'before' and 'after' for timestamp comparisons.".to_string());
575 }
576
577 let left_v = Self::get_runtime_value(left, graph);
579 let right_v = Self::get_runtime_value(right, graph);
580 match (left_v, right_v) {
581 (Ok(lv), Ok(rv)) => {
582 if lv.is_null() || rv.is_null() {
583 Ok(T::Null)
584 } else if let (Some(ls), Some(rs)) = (lv.as_str(), rv.as_str()) {
585 let left_dt = match chrono::DateTime::parse_from_rfc3339(ls) {
587 Ok(dt) => dt,
588 Err(_) => return Ok(T::Null), };
590 let right_dt = match chrono::DateTime::parse_from_rfc3339(rs) {
591 Ok(dt) => dt,
592 Err(_) => return Ok(T::Null), };
594
595 let result = match op {
596 BinaryOp::Before => left_dt < right_dt,
597 BinaryOp::After => left_dt > right_dt,
598 _ => unreachable!(),
599 };
600 Ok(T::from_option_bool(Some(result)))
601 } else {
602 Ok(T::Null)
603 }
604 }
605 _ => Ok(T::Null),
606 }
607 }
608 },
609 Expression::Unary { op, operand } => {
610 let v = self.evaluate_expression_three_valued(operand, graph)?;
611 Ok(match op {
612 UnaryOp::Not => v.not(),
613 UnaryOp::Negate => return Err("Negate operator not supported in boolean context".to_string()),
614 })
615 }
616 Expression::Quantifier { quantifier, variable, collection, condition } => {
617 let items = Expression::get_collection(collection, graph)?;
619 use super::expression::Quantifier as Q;
620
621 let mut saw_true = 0usize;
622 let mut saw_false = 0usize;
623 let mut saw_null = 0usize;
624
625 for item in items {
626 let substituted = condition.substitute(variable, &item)?;
627 let val = self.evaluate_expression_three_valued(&substituted, graph)?;
628 match val {
629 T::True => saw_true += 1,
630 T::False => saw_false += 1,
631 T::Null => saw_null += 1,
632 }
633 }
634
635 match quantifier {
636 Q::ForAll => {
637 if saw_false > 0 { return Ok(T::False); }
638 if saw_null > 0 { return Ok(T::Null); }
639 Ok(T::True)
640 }
641 Q::Exists => {
642 if saw_true > 0 { return Ok(T::True); }
643 if saw_null > 0 { return Ok(T::Null); }
644 Ok(T::False)
645 }
646 Q::ExistsUnique => {
647 if saw_true > 1 { return Ok(T::False); }
648 if saw_true == 1 && saw_null == 0 { return Ok(T::True); }
649 if saw_true == 1 && saw_null > 0 { return Ok(T::Null); }
650 if saw_true == 0 && saw_null > 0 { return Ok(T::Null); }
651 Ok(T::False)
652 }
653 }
654 }
655 Expression::MemberAccess { object: _, member: _ } => {
656 let value = Self::get_runtime_value(expr, graph)?;
658 Ok(T::from_option_bool(value.as_bool()))
659 }
660 Expression::Aggregation { .. } => Err("Aggregation in boolean context requires explicit comparison (e.g., COUNT(...) > 0)".to_string()),
661 Expression::AggregationComprehension { .. } => Err("Aggregation in boolean context requires explicit comparison (e.g., COUNT(...) > 0)".to_string()),
662 Expression::QuantityLiteral { .. } => Err("Cannot convert quantity to boolean; compare against a threshold instead".to_string()),
663 Expression::TimeLiteral(_) => Err("Cannot convert time to boolean; use temporal comparison operators".to_string()),
664 Expression::IntervalLiteral { .. } => Err("Cannot convert interval to boolean; use temporal comparison operators".to_string()),
665 Expression::GroupBy { .. } => Err("Cannot evaluate non-expanded group_by".to_string()),
666 Expression::RoleReference { .. } => Err(
667 "Cannot evaluate role reference outside application policy context".to_string(),
668 ),
669 }
670 }
671
672 fn compare_values<F>(
673 &self,
674 left: &Expression,
675 right: &Expression,
676 graph: &Graph,
677 op: F,
678 ) -> Result<bool, String>
679 where
680 F: Fn(&serde_json::Value, &serde_json::Value) -> bool,
681 {
682 let left_val = self
683 .get_literal_value(left)
684 .or_else(|_| Self::get_runtime_value(left, graph))?;
685 let right_val = self
686 .get_literal_value(right)
687 .or_else(|_| Self::get_runtime_value(right, graph))?;
688 Ok(op(&left_val, &right_val))
689 }
690
691 fn compare_numeric<F>(
692 &self,
693 left: &Expression,
694 right: &Expression,
695 graph: &Graph,
696 op: F,
697 ) -> Result<bool, String>
698 where
699 F: Fn(Decimal, Decimal) -> bool,
700 {
701 let left_val = self.resolve_numeric_with_unit(left, graph)?;
702 let right_val = self.resolve_numeric_with_unit(right, graph)?;
703 let (left_aligned, right_aligned) = self.normalize_units_strict(left_val, right_val)?;
704 Ok(op(left_aligned, right_aligned))
705 }
706
707 fn compare_strings<F>(
708 &self,
709 left: &Expression,
710 right: &Expression,
711 graph: &Graph,
712 op: F,
713 ) -> Result<bool, String>
714 where
715 F: Fn(&str, &str) -> bool,
716 {
717 let left_val = self.get_string_value(left, graph)?;
718 let right_val = self.get_string_value(right, graph)?;
719 Ok(op(&left_val, &right_val))
720 }
721
722 fn evaluate_pattern_match(
723 &self,
724 left: &Expression,
725 right: &Expression,
726 graph: &Graph,
727 ) -> Result<bool, String> {
728 let candidate = self.get_string_value(left, graph)?;
729 let pattern_name = self.get_string_value(right, graph)?;
730
731 let pattern = graph
732 .find_pattern(&pattern_name, Some(&self.namespace))
733 .ok_or_else(|| {
734 format!(
735 "Pattern '{}' not found in namespace '{}'",
736 pattern_name, self.namespace
737 )
738 })?;
739
740 pattern
741 .is_match(&candidate)
742 .map_err(|e| format!("Pattern '{}' failed to evaluate: {}", pattern_name, e))
743 }
744
745 fn evaluate_has_role(
746 &self,
747 left: &Expression,
748 right: &Expression,
749 graph: &Graph,
750 ) -> Result<bool, String> {
751 let target_role = self.get_string_value(right, graph)?;
752 let roles = self.collect_roles(left, graph)?;
753
754 Ok(roles
755 .iter()
756 .any(|role| role.eq_ignore_ascii_case(&target_role)))
757 }
758
759 fn collect_roles(&self, expr: &Expression, graph: &Graph) -> Result<Vec<String>, String> {
760 let value = Self::get_runtime_value(expr, graph)?;
761
762 if let Some(arr) = value.as_array() {
763 return Ok(arr
764 .iter()
765 .filter_map(|v| v.as_str().map(|s| s.to_string()))
766 .collect());
767 }
768
769 if let Some(obj) = value.as_object() {
770 if let Some(roles) = obj.get("roles").and_then(|r| r.as_array()) {
771 return Ok(roles
772 .iter()
773 .filter_map(|v| v.as_str().map(|s| s.to_string()))
774 .collect());
775 }
776
777 if let Some(name) = obj.get("name").and_then(|v| v.as_str()) {
778 if let Some(entity_id) = graph.find_entity_by_name(name) {
779 return Ok(graph.role_names_for_entity(&entity_id));
780 }
781 }
782 }
783
784 if let Some(name) = value.as_str() {
785 if let Some(entity_id) = graph.find_entity_by_name(name) {
786 return Ok(graph.role_names_for_entity(&entity_id));
787 }
788
789 if let Some(role_id) = graph.find_role_by_name(name) {
790 if let Some(role) = graph.get_role(&role_id) {
791 return Ok(vec![role.name().to_string()]);
792 }
793 }
794 }
795
796 Ok(Vec::new())
797 }
798
799 fn get_literal_value(&self, expr: &Expression) -> Result<serde_json::Value, String> {
800 match expr {
801 Expression::Literal(v) => Ok(v.clone()),
802 _ => Err("Expected literal value".to_string()),
803 }
804 }
805
806 fn parse_decimal_value(value: &serde_json::Value) -> Result<Decimal, String> {
807 if let Some(s) = value.as_str() {
808 Decimal::from_str(s).map_err(|e| e.to_string())
809 } else if let Some(f) = value.as_f64() {
810 Decimal::from_f64(f).ok_or_else(|| format!("Unable to represent {} as Decimal", f))
811 } else if let Some(i) = value.as_i64() {
812 Ok(Decimal::from(i))
813 } else if let Some(u) = value.as_u64() {
814 Decimal::from_u64(u).ok_or_else(|| format!("Unable to represent {} as Decimal", u))
815 } else {
816 Err(format!("Expected numeric value, got: {}", value))
817 }
818 }
819
820 fn parse_numeric_with_unit_value(
821 value: &serde_json::Value,
822 ) -> Result<Option<(Decimal, Option<String>)>, String> {
823 if let Some(obj) = value.as_object() {
824 match (obj.get("__quantity_value"), obj.get("__quantity_unit")) {
825 (Some(q_val), Some(q_unit)) => {
826 let unit_str = q_unit
827 .as_str()
828 .ok_or_else(|| {
829 format!("Expected __quantity_unit to be string, got: {}", q_unit)
830 })?
831 .to_string();
832 let value_dec = Self::parse_decimal_value(q_val)
833 .map_err(|e| format!("Invalid __quantity_value: {}", e))?;
834 return Ok(Some((value_dec, Some(unit_str))));
835 }
836 (Some(_), None) | (None, Some(_)) => {
837 return Err(
838 "Quantity object must include both __quantity_value and __quantity_unit"
839 .to_string(),
840 )
841 }
842 _ => {}
843 }
844 }
845
846 if value.is_number() || value.is_string() {
847 return Ok(Some((Self::parse_decimal_value(value)?, None)));
848 }
849
850 Ok(None)
851 }
852
853 fn resolve_numeric_with_unit(
854 &self,
855 expr: &Expression,
856 graph: &Graph,
857 ) -> Result<(Decimal, Option<String>), String> {
858 let value = self
859 .get_literal_value(expr)
860 .or_else(|_| Self::get_runtime_value(expr, graph))?;
861 Self::parse_numeric_with_unit_value(&value)?
862 .ok_or_else(|| format!("Expected numeric value, got: {}", value))
863 }
864
865 fn normalize_units_strict(
866 &self,
867 left: (Decimal, Option<String>),
868 right: (Decimal, Option<String>),
869 ) -> Result<(Decimal, Decimal), String> {
870 match (left.1, right.1) {
871 (Some(l_unit), Some(r_unit)) => {
872 let registry = get_default_registry();
873 let registry = registry
874 .read()
875 .map_err(|e| format!("Failed to lock unit registry: {}", e))?;
876
877 if l_unit == r_unit {
878 Ok((left.0, right.0))
879 } else {
880 let from = registry
881 .get_unit(&r_unit)
882 .map_err(|e| format!("Invalid unit '{}': {}", r_unit, e))?;
883 let to = registry
884 .get_unit(&l_unit)
885 .map_err(|e| format!("Invalid unit '{}': {}", l_unit, e))?;
886 let converted = registry
887 .convert(right.0, from, to)
888 .map_err(|e| format!("Unit conversion failed: {}", e))?;
889 Ok((left.0, converted))
890 }
891 }
892 (None, None) => Ok((left.0, right.0)),
893 (Some(l_unit), None) => Err(format!(
894 "Cannot compare quantity with unit '{}' to unitless value",
895 l_unit
896 )),
897 (None, Some(r_unit)) => Err(format!(
898 "Cannot compare unitless value to quantity with unit '{}'",
899 r_unit
900 )),
901 }
902 }
903
904 fn normalize_units_nullable(
905 &self,
906 left: Option<(Decimal, Option<String>)>,
907 right: Option<(Decimal, Option<String>)>,
908 ) -> Result<Option<(Decimal, Decimal)>, String> {
909 let (left, right) = match (left, right) {
910 (Some(l), Some(r)) => (l, r),
911 _ => return Ok(None),
912 };
913
914 match (left.1.clone(), right.1.clone()) {
915 (Some(l_unit), Some(r_unit)) => {
916 let registry = get_default_registry();
917 let registry = registry
918 .read()
919 .map_err(|e| format!("Failed to lock unit registry: {}", e))?;
920 if l_unit == r_unit {
921 Ok(Some((left.0, right.0)))
922 } else {
923 let from = registry.get_unit(&r_unit);
924 let to = registry.get_unit(&l_unit);
925 if let (Ok(from), Ok(to)) = (from, to) {
926 match registry.convert(right.0, from, to) {
927 Ok(converted) => Ok(Some((left.0, converted))),
928 Err(_) => Ok(None),
929 }
930 } else {
931 Ok(None)
932 }
933 }
934 }
935 (None, None) => Ok(Some((left.0, right.0))),
936 _ => Ok(None),
937 }
938 }
939
940 fn get_string_value(&self, expr: &Expression, graph: &Graph) -> Result<String, String> {
941 let v = self
942 .get_literal_value(expr)
943 .or_else(|_| Self::get_runtime_value(expr, graph))?;
944 v.as_str()
945 .map(|s| s.to_string())
946 .ok_or_else(|| "Expected string value".to_string())
947 }
948
949 fn get_runtime_value(expr: &Expression, graph: &Graph) -> Result<serde_json::Value, String> {
950 match expr {
951 Expression::Literal(v) => Ok(v.clone()),
952 Expression::MemberAccess { object, member } => {
953 if let Some(id) = graph.find_entity_by_name(object) {
955 if let Some(entity) = graph.get_entity(&id) {
956 if member == "id" {
958 return Ok(serde_json::json!(entity.id().to_string()));
959 } else if member == "name" {
960 return Ok(serde_json::json!(entity.name()));
961 } else if member == "namespace" {
962 return Ok(serde_json::json!(entity.namespace()));
963 }
964 if let Some(val) = entity.get_attribute(member) {
965 if val.is_null() {
966 log::debug!(
967 "Entity '{}' member '{}' present but NULL; returning Null",
968 object,
969 member
970 );
971 }
972 return Ok(val.clone());
973 }
974 log::debug!(
975 "Entity '{}' found but member '{}' missing; returning Null",
976 object,
977 member
978 );
979 return Ok(serde_json::Value::Null);
980 } else {
981 log::debug!(
982 "Entity lookup for '{}' returned id {} but entity missing; returning Null",
983 object, id
984 );
985 }
986 } else {
987 log::debug!(
988 "Entity '{}' not found while resolving member '{}'; continuing lookup",
989 object,
990 member
991 );
992 }
993
994 if let Some(id) = graph.find_resource_by_name(object) {
995 if let Some(resource) = graph.get_resource(&id) {
996 if member == "id" {
997 return Ok(serde_json::json!(resource.id().to_string()));
998 } else if member == "name" {
999 return Ok(serde_json::json!(resource.name()));
1000 } else if member == "unit" {
1001 return Ok(serde_json::json!(resource.unit()));
1002 }
1003 if let Some(val) = resource.get_attribute(member) {
1004 if val.is_null() {
1005 log::debug!(
1006 "Resource '{}' member '{}' present but NULL; returning Null",
1007 object,
1008 member
1009 );
1010 }
1011 return Ok(val.clone());
1012 }
1013 log::debug!(
1014 "Resource '{}' found but member '{}' missing; returning Null",
1015 object,
1016 member
1017 );
1018 return Ok(serde_json::Value::Null);
1019 } else {
1020 log::debug!(
1021 "Resource lookup for '{}' returned id {} but resource missing; returning Null",
1022 object, id
1023 );
1024 }
1025 } else {
1026 log::debug!(
1027 "Resource '{}' not found while resolving member '{}'; returning Null",
1028 object,
1029 member
1030 );
1031 }
1032
1033 log::debug!(
1035 "Member access '{}.{}' did not resolve to entity or resource; returning Null",
1036 object,
1037 member
1038 );
1039 Ok(serde_json::Value::Null)
1040 }
1041 Expression::Aggregation {
1042 function,
1043 collection,
1044 field,
1045 filter,
1046 } => {
1047 let v =
1048 Expression::evaluate_aggregation(function, collection, field, filter, graph)?;
1049 Ok(v)
1050 }
1051 Expression::AggregationComprehension {
1052 function,
1053 variable,
1054 collection,
1055 window,
1056 predicate,
1057 projection,
1058 target_unit,
1059 } => {
1060 let v = Expression::evaluate_aggregation_comprehension(
1061 function,
1062 variable,
1063 collection,
1064 window,
1065 predicate,
1066 projection,
1067 target_unit.as_deref(),
1068 graph,
1069 )?;
1070 Ok(v)
1071 }
1072 Expression::Cast {
1073 operand,
1074 target_type,
1075 } => {
1076 let val = Self::get_runtime_value(operand, graph)?;
1077 let (value_dec, source_unit) = Self::parse_numeric_with_unit_value(&val)
1078 .map_err(|e| format!("Invalid cast operand: {}", e))?
1079 .ok_or_else(|| {
1080 format!("Cannot cast non-numeric value {} to {}", val, target_type)
1081 })?;
1082
1083 let registry = get_default_registry();
1084 let registry = registry
1085 .read()
1086 .map_err(|e| format!("Failed to lock unit registry: {}", e))?;
1087 let target_unit = registry
1088 .get_unit(target_type)
1089 .map_err(|e| format!("Unknown target unit '{}': {}", target_type, e))?;
1090
1091 let converted_value = if let Some(from_unit_symbol) = source_unit {
1092 let from_unit = registry
1093 .get_unit(&from_unit_symbol)
1094 .map_err(|e| format!("Unknown unit '{}': {}", from_unit_symbol, e))?;
1095 if from_unit.dimension() != target_unit.dimension() {
1096 return Err(format!(
1097 "Cannot cast from '{}' ({:?}) to '{}' ({:?})",
1098 from_unit_symbol,
1099 from_unit.dimension(),
1100 target_type,
1101 target_unit.dimension()
1102 ));
1103 }
1104 registry
1105 .convert(value_dec, from_unit, target_unit)
1106 .map_err(|e| format!("Unit conversion failed: {}", e))?
1107 } else {
1108 value_dec
1109 };
1110
1111 Ok(serde_json::json!({
1112 "__quantity_value": converted_value.to_string(),
1113 "__quantity_unit": target_type
1114 }))
1115 }
1116 Expression::QuantityLiteral { value, unit } => Ok(
1117 serde_json::json!({"__quantity_value": value.to_string(), "__quantity_unit": unit}),
1118 ),
1119 Expression::TimeLiteral(timestamp) => Ok(serde_json::json!(timestamp)),
1120 Expression::IntervalLiteral { start, end } => {
1121 Ok(serde_json::json!({"__interval_start": start, "__interval_end": end}))
1122 }
1123 _ => Err(
1124 "Expected a runtime-resolvable expression (literal, member access, or aggregation)"
1125 .to_string(),
1126 ),
1127 }
1128 }
1129}
1130
1131impl PolicyModality {
1132 pub fn to_severity(&self) -> Severity {
1133 match self {
1134 Self::Obligation => Severity::Error,
1135 Self::Prohibition => Severity::Error,
1136 Self::Permission => Severity::Info,
1137 }
1138 }
1139}
1140
1141impl EvaluationResult {
1142 pub fn has_errors(&self) -> bool {
1143 self.violations
1144 .iter()
1145 .any(|v| v.severity == Severity::Error)
1146 }
1147
1148 pub fn error_count(&self) -> usize {
1149 self.violations
1150 .iter()
1151 .filter(|v| v.severity == Severity::Error)
1152 .count()
1153 }
1154}