1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use std::fmt;
5use std::ops::Not;
6use thiserror::Error;
7
8#[derive(Debug, Clone)]
11pub struct ValidationError {
12 pub field: String,
13 pub error_type: ValidationErrorType,
14 pub message: String,
15 pub suggestion: Option<String>,
16}
17
18impl std::fmt::Display for ValidationError {
19 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20 write!(f, "{}: {}", self.field, self.message)?;
21 if let Some(suggestion) = &self.suggestion {
22 write!(f, " (suggestion: {})", suggestion)?;
23 }
24 Ok(())
25 }
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum ValidationErrorType {
31 Required,
32 InvalidFormat,
33 OutOfRange,
34 FqnParseError,
35 NamespaceNotRegistered,
36 InvalidUuid,
37 EmptyList,
38}
39
40#[derive(Debug, Error)]
41pub enum PolicyError {
42 #[error("Invalid attribute: {fqn} - {reason}")]
43 InvalidAttribute { fqn: String, reason: String },
44
45 #[error("Invalid operator '{operator}' in context: {context}")]
46 InvalidOperator { operator: String, context: String },
47
48 #[error("Invalid value type for attribute '{attribute}': expected {expected}, got {actual}")]
49 InvalidValueType {
50 attribute: String,
51 expected: String,
52 actual: String,
53 },
54
55 #[error("Policy evaluation error: {reason}")]
56 EvaluationError {
57 reason: String,
58 attribute: Option<String>,
59 },
60
61 #[error("Policy validation failed with {} error(s)", .0.len())]
62 ValidationFailed(Vec<ValidationError>),
63
64 #[error("Serialization error: {0}")]
65 SerializationError(#[from] serde_json::Error),
66
67 #[error("FQN parse error: {0}")]
68 FqnError(#[from] FqnError),
69}
70
71#[derive(Debug, Error, Clone)]
73pub enum FqnError {
74 #[error("Invalid URL scheme: expected '{expected}', found '{found}'")]
75 InvalidScheme {
76 expected: &'static str,
77 found: String,
78 },
79
80 #[error("URL must use HTTPS scheme: {url}")]
81 NotHttps { url: String },
82
83 #[error("FQN missing required /attr/ structure: {url}")]
84 MissingAttrStructure { url: String },
85
86 #[error("Invalid namespace '{namespace}': {reason}")]
87 InvalidNamespace { namespace: String, reason: String },
88
89 #[error("Namespace not registered: {namespace}")]
90 NamespaceNotRegistered { namespace: String },
91
92 #[error("Malformed URL: {0}")]
93 MalformedUrl(String),
94
95 #[error("Missing required component: {component}")]
96 MissingComponent { component: &'static str },
97}
98
99impl FqnError {
100 pub fn kind(&self) -> FqnErrorKind {
102 match self {
103 FqnError::InvalidScheme { .. } => FqnErrorKind::InvalidScheme,
104 FqnError::NotHttps { .. } => FqnErrorKind::NotHttps,
105 FqnError::MissingAttrStructure { .. } => FqnErrorKind::MissingAttrStructure,
106 FqnError::InvalidNamespace { .. } => FqnErrorKind::InvalidNamespace,
107 FqnError::NamespaceNotRegistered { .. } => FqnErrorKind::NamespaceNotRegistered,
108 FqnError::MalformedUrl(_) => FqnErrorKind::MalformedUrl,
109 FqnError::MissingComponent { .. } => FqnErrorKind::MissingComponent,
110 }
111 }
112
113 pub fn hint(&self) -> &'static str {
115 match self {
116 FqnError::InvalidScheme { expected, .. } => {
117 if *expected == "https" {
118 "Use HTTPS scheme: https://example.com/attr/name/value/val"
119 } else {
120 "Use correct URL scheme"
121 }
122 }
123 FqnError::NotHttps { .. } => {
124 "FQNs must use HTTPS for security. Example: https://example.com/attr/name/value/val"
125 }
126 FqnError::MissingAttrStructure { .. } => {
127 "FQN must follow format: https://<namespace>/attr/<name>/value/<value>"
128 }
129 FqnError::InvalidNamespace { .. } => {
130 "Namespace must be a valid domain-like identifier (lowercase, no special chars)"
131 }
132 FqnError::NamespaceNotRegistered { .. } => {
133 "Register the namespace using NamespaceRegistry::register() before use"
134 }
135 FqnError::MalformedUrl(_) => "Ensure URL is properly formatted with scheme://host/path",
136 FqnError::MissingComponent { component } => match *component {
137 "namespace" => "Provide a namespace: https://namespace.com/...",
138 "name" => "Provide an attribute name: .../attr/name/...",
139 _ => "Ensure all required FQN components are present",
140 },
141 }
142 }
143
144 pub fn error_code(&self) -> &'static str {
146 match self {
147 FqnError::InvalidScheme { .. } => "OPENTDF_E_FQN_SCHEME_INVALID",
148 FqnError::NotHttps { .. } => "OPENTDF_E_FQN_NOT_HTTPS",
149 FqnError::MissingAttrStructure { .. } => "OPENTDF_E_FQN_STRUCTURE",
150 FqnError::InvalidNamespace { .. } => "OPENTDF_E_FQN_NAMESPACE_INVALID",
151 FqnError::NamespaceNotRegistered { .. } => "OPENTDF_E_FQN_NAMESPACE_UNREGISTERED",
152 FqnError::MalformedUrl(_) => "OPENTDF_E_FQN_MALFORMED",
153 FqnError::MissingComponent { .. } => "OPENTDF_E_FQN_COMPONENT_MISSING",
154 }
155 }
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub enum FqnErrorKind {
161 InvalidScheme,
162 NotHttps,
163 MissingAttrStructure,
164 InvalidNamespace,
165 NamespaceNotRegistered,
166 MalformedUrl,
167 MissingComponent,
168}
169
170impl PolicyError {
171 pub fn is_retryable(&self) -> bool {
173 matches!(self, PolicyError::SerializationError(_))
174 }
175
176 pub fn suggestion(&self) -> Option<&str> {
178 match self {
179 PolicyError::InvalidAttribute { .. } => {
180 Some("Use AttributeFqn::parse() to validate FQN format")
181 }
182 PolicyError::ValidationFailed(errors) if !errors.is_empty() => {
183 errors[0].suggestion.as_deref()
184 }
185 PolicyError::FqnError(FqnError::NotHttps { .. }) => Some(
186 "Use HTTPS URLs for attribute FQNs (e.g., https://example.com/attr/name/value/val)",
187 ),
188 PolicyError::FqnError(FqnError::MissingAttrStructure { .. }) => {
189 Some("FQN must follow format: https://<namespace>/attr/<name>/value/<value>")
190 }
191 _ => None,
192 }
193 }
194
195 pub fn error_code(&self) -> &'static str {
200 match self {
201 PolicyError::InvalidAttribute { .. } => "OPENTDF_E_POLICY_ATTRIBUTE_INVALID",
202 PolicyError::InvalidOperator { .. } => "OPENTDF_E_POLICY_OPERATOR_INVALID",
203 PolicyError::InvalidValueType { .. } => "OPENTDF_E_POLICY_VALUE_TYPE",
204 PolicyError::EvaluationError { .. } => "OPENTDF_E_POLICY_EVALUATION",
205 PolicyError::ValidationFailed(_) => "OPENTDF_E_POLICY_VALIDATION",
206 PolicyError::SerializationError(_) => "OPENTDF_E_POLICY_SERIALIZATION",
207 PolicyError::FqnError(_) => "OPENTDF_E_FQN",
208 }
209 }
210}
211
212#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
214pub struct AttributeIdentifier {
215 pub namespace: String,
216 pub name: String,
217}
218
219impl AttributeIdentifier {
220 pub fn new(namespace: impl Into<String>, name: impl Into<String>) -> Self {
221 Self {
222 namespace: namespace.into(),
223 name: name.into(),
224 }
225 }
226
227 pub fn from_string(s: &str) -> Result<Self, PolicyError> {
229 let parts: Vec<&str> = s.split(':').collect();
230 if parts.len() != 2 {
231 return Err(PolicyError::InvalidAttribute {
232 fqn: s.to_string(),
233 reason: "Attribute must be in format 'namespace:name'".to_string(),
234 });
235 }
236 Ok(Self::new(parts[0], parts[1]))
237 }
238
239 pub fn as_string(&self) -> String {
241 format!("{}:{}", self.namespace, self.name)
242 }
243}
244
245impl fmt::Display for AttributeIdentifier {
246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247 write!(f, "{}:{}", self.namespace, self.name)
248 }
249}
250
251#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
253#[serde(untagged)]
254pub enum AttributeValue {
255 String(String),
256 Number(f64),
257 Boolean(bool),
258 DateTime(DateTime<Utc>),
259 StringArray(Vec<String>),
260 NumberArray(Vec<f64>),
261}
262
263impl AttributeValue {
264 pub fn as_string(&self) -> Option<&str> {
265 match self {
266 AttributeValue::String(s) => Some(s),
267 _ => None,
268 }
269 }
270
271 pub fn as_number(&self) -> Option<f64> {
272 match self {
273 AttributeValue::Number(n) => Some(*n),
274 _ => None,
275 }
276 }
277
278 pub fn as_boolean(&self) -> Option<bool> {
279 match self {
280 AttributeValue::Boolean(b) => Some(*b),
281 _ => None,
282 }
283 }
284
285 pub fn as_datetime(&self) -> Option<&DateTime<Utc>> {
286 match self {
287 AttributeValue::DateTime(dt) => Some(dt),
288 _ => None,
289 }
290 }
291
292 pub fn as_string_array(&self) -> Option<&[String]> {
293 match self {
294 AttributeValue::StringArray(arr) => Some(arr),
295 _ => None,
296 }
297 }
298
299 pub fn as_number_array(&self) -> Option<&[f64]> {
300 match self {
301 AttributeValue::NumberArray(arr) => Some(arr),
302 _ => None,
303 }
304 }
305}
306
307#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
309#[serde(rename_all = "camelCase")]
310pub enum Operator {
311 Equals,
312 NotEquals,
313 GreaterThan,
314 GreaterThanOrEqual,
315 LessThan,
316 LessThanOrEqual,
317 Contains,
318 In,
319 AllOf,
320 AnyOf,
321 NotIn,
322 MinimumOf, MaximumOf, Present, NotPresent, }
327
328#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
330pub struct AttributeCondition {
331 pub attribute: AttributeIdentifier,
332 pub operator: Operator,
333 #[serde(skip_serializing_if = "Option::is_none")]
334 pub value: Option<AttributeValue>,
335}
336
337impl AttributeCondition {
338 pub fn new(
339 attribute: AttributeIdentifier,
340 operator: Operator,
341 value: Option<AttributeValue>,
342 ) -> Self {
343 Self {
344 attribute,
345 operator,
346 value,
347 }
348 }
349
350 pub fn present(attribute: AttributeIdentifier) -> Self {
352 Self::new(attribute, Operator::Present, None)
353 }
354
355 pub fn equals(attribute: AttributeIdentifier, value: AttributeValue) -> Self {
357 Self::new(attribute, Operator::Equals, Some(value))
358 }
359}
360
361#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
363#[serde(rename_all = "UPPERCASE", tag = "type")]
364pub enum LogicalOperator {
365 AND { conditions: Vec<AttributePolicy> },
366 OR { conditions: Vec<AttributePolicy> },
367 NOT { condition: Box<AttributePolicy> },
368}
369
370#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
372#[serde(untagged)]
373pub enum AttributePolicy {
374 Condition(AttributeCondition),
375 Logical(LogicalOperator),
376}
377
378impl AttributePolicy {
379 pub fn condition(
381 attribute: AttributeIdentifier,
382 operator: Operator,
383 value: AttributeValue,
384 ) -> Self {
385 AttributePolicy::Condition(AttributeCondition::new(attribute, operator, Some(value)))
386 }
387
388 pub fn and(conditions: Vec<AttributePolicy>) -> Self {
390 AttributePolicy::Logical(LogicalOperator::AND { conditions })
391 }
392
393 pub fn or(conditions: Vec<AttributePolicy>) -> Self {
395 AttributePolicy::Logical(LogicalOperator::OR { conditions })
396 }
397
398 pub fn create_not(condition: AttributePolicy) -> Self {
400 AttributePolicy::Logical(LogicalOperator::NOT {
401 condition: Box::new(condition),
402 })
403 }
404}
405
406impl Not for AttributePolicy {
407 type Output = Self;
408
409 fn not(self) -> Self::Output {
410 AttributePolicy::Logical(LogicalOperator::NOT {
411 condition: Box::new(self),
412 })
413 }
414}
415
416impl AttributePolicy {
417 pub fn evaluate(
423 &self,
424 attributes: &HashMap<AttributeIdentifier, AttributeValue>,
425 ) -> Result<bool, PolicyError> {
426 if self.depth() > 50 {
428 self.evaluate_iterative(attributes)
429 } else {
430 self.evaluate_recursive(attributes)
431 }
432 }
433
434 pub fn depth(&self) -> usize {
436 match self {
437 AttributePolicy::Condition(_) => 1,
438 AttributePolicy::Logical(operator) => match operator {
439 LogicalOperator::AND { conditions } | LogicalOperator::OR { conditions } => {
440 1 + conditions.iter().map(|c| c.depth()).max().unwrap_or(0)
441 }
442 LogicalOperator::NOT { condition } => 1 + condition.depth(),
443 },
444 }
445 }
446
447 fn evaluate_recursive(
449 &self,
450 attributes: &HashMap<AttributeIdentifier, AttributeValue>,
451 ) -> Result<bool, PolicyError> {
452 match self {
453 AttributePolicy::Condition(condition) => evaluate_condition(condition, attributes),
454 AttributePolicy::Logical(operator) => match operator {
455 LogicalOperator::AND { conditions } => {
456 for condition in conditions {
457 if !condition.evaluate_recursive(attributes)? {
458 return Ok(false);
459 }
460 }
461 Ok(true)
462 }
463 LogicalOperator::OR { conditions } => {
464 for condition in conditions {
465 if condition.evaluate_recursive(attributes)? {
466 return Ok(true);
467 }
468 }
469 Ok(false)
470 }
471 LogicalOperator::NOT { condition } => {
472 Ok(!condition.evaluate_recursive(attributes)?)
473 }
474 },
475 }
476 }
477
478 fn evaluate_iterative(
481 &self,
482 attributes: &HashMap<AttributeIdentifier, AttributeValue>,
483 ) -> Result<bool, PolicyError> {
484 enum EvalTask<'a> {
486 Evaluate(&'a AttributePolicy),
487 EvaluateAnd(&'a [AttributePolicy], usize), EvaluateOr(&'a [AttributePolicy], usize), ApplyNot,
490 }
491
492 let mut results = Vec::new();
494 let mut tasks = vec![EvalTask::Evaluate(self)];
495
496 while let Some(task) = tasks.pop() {
498 match task {
499 EvalTask::Evaluate(policy) => match policy {
500 AttributePolicy::Condition(condition) => {
501 let result = evaluate_condition(condition, attributes)?;
502 results.push(result);
503 }
504 AttributePolicy::Logical(LogicalOperator::AND { conditions }) => {
505 if conditions.is_empty() {
506 results.push(true); } else {
508 tasks.push(EvalTask::EvaluateAnd(conditions, 0));
509 }
510 }
511 AttributePolicy::Logical(LogicalOperator::OR { conditions }) => {
512 if conditions.is_empty() {
513 results.push(false); } else {
515 tasks.push(EvalTask::EvaluateOr(conditions, 0));
516 }
517 }
518 AttributePolicy::Logical(LogicalOperator::NOT { condition }) => {
519 tasks.push(EvalTask::ApplyNot);
520 tasks.push(EvalTask::Evaluate(condition));
521 }
522 },
523 EvalTask::EvaluateAnd(conditions, idx) => {
524 if idx == 0 {
525 results.push(true);
527 }
528
529 let current_result = *results.last().unwrap();
531
532 if !current_result {
533 continue;
535 }
536
537 if idx < conditions.len() {
538 tasks.push(EvalTask::EvaluateAnd(conditions, idx + 1));
540
541 tasks.push(EvalTask::Evaluate(&conditions[idx]));
543
544 results.pop();
546 }
547 }
548 EvalTask::EvaluateOr(conditions, idx) => {
549 if idx == 0 {
550 results.push(false);
552 }
553
554 let current_result = *results.last().unwrap();
556
557 if current_result {
558 continue;
560 }
561
562 if idx < conditions.len() {
563 tasks.push(EvalTask::EvaluateOr(conditions, idx + 1));
565
566 tasks.push(EvalTask::Evaluate(&conditions[idx]));
568
569 results.pop();
571 }
572 }
573 EvalTask::ApplyNot => {
574 let result = results.pop().unwrap();
576 results.push(!result);
577 }
578 }
579 }
580
581 if results.len() != 1 {
583 return Err(PolicyError::EvaluationError {
584 reason: "Invalid policy evaluation state".to_string(),
585 attribute: None,
586 });
587 }
588
589 Ok(results[0])
590 }
591}
592
593#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
595pub struct Policy {
596 pub uuid: String,
597 #[serde(skip_serializing_if = "Option::is_none")]
598 pub valid_from: Option<DateTime<Utc>>,
599 #[serde(skip_serializing_if = "Option::is_none")]
600 pub valid_to: Option<DateTime<Utc>>,
601 pub body: PolicyBody,
602}
603
604#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
609pub struct PolicyBody {
610 #[serde(
611 rename = "dataAttributes",
612 default,
613 serialize_with = "serialize_empty_vec_as_null",
614 deserialize_with = "deserialize_null_as_empty_vec"
615 )]
616 pub attributes: Vec<AttributePolicy>,
617 #[serde(
618 default,
619 serialize_with = "serialize_empty_vec_as_null",
620 deserialize_with = "deserialize_null_as_empty_vec"
621 )]
622 pub dissem: Vec<String>, }
624
625fn serialize_empty_vec_as_null<T, S>(vec: &Vec<T>, serializer: S) -> Result<S::Ok, S::Error>
628where
629 T: serde::Serialize,
630 S: serde::Serializer,
631{
632 if vec.is_empty() {
633 serializer.serialize_none()
634 } else {
635 vec.serialize(serializer)
636 }
637}
638
639fn deserialize_null_as_empty_vec<'de, T, D>(deserializer: D) -> Result<Vec<T>, D::Error>
641where
642 T: serde::Deserialize<'de>,
643 D: serde::Deserializer<'de>,
644{
645 let opt = Option::<Vec<T>>::deserialize(deserializer)?;
646 Ok(opt.unwrap_or_default())
647}
648
649impl Policy {
650 pub fn new(uuid: String, attributes: Vec<AttributePolicy>, dissem: Vec<String>) -> Self {
652 Self {
653 uuid,
654 valid_from: None,
655 valid_to: None,
656 body: PolicyBody { attributes, dissem },
657 }
658 }
659
660 pub fn with_time_window(
662 mut self,
663 valid_from: Option<DateTime<Utc>>,
664 valid_to: Option<DateTime<Utc>>,
665 ) -> Self {
666 self.valid_from = valid_from;
667 self.valid_to = valid_to;
668 self
669 }
670
671 pub fn to_json(&self) -> Result<String, PolicyError> {
673 serde_json::to_string(self).map_err(PolicyError::from)
674 }
675
676 pub fn from_json(json: &str) -> Result<Self, PolicyError> {
678 serde_json::from_str(json).map_err(PolicyError::from)
679 }
680
681 pub fn is_valid_at(&self, time: DateTime<Utc>) -> bool {
683 let after_start = self.valid_from.is_none_or(|from| time >= from);
684 let before_end = self.valid_to.is_none_or(|to| time <= to);
685 after_start && before_end
686 }
687
688 pub fn validate(&self) -> Result<(), PolicyError> {
712 let mut errors = Vec::new();
713
714 if let Err(e) = uuid::Uuid::parse_str(&self.uuid) {
716 errors.push(ValidationError {
717 field: "uuid".to_string(),
718 error_type: ValidationErrorType::InvalidFormat,
719 message: format!("Invalid UUID format: {}", e),
720 suggestion: Some(
721 "Use PolicyBuilder::id_auto() to generate a valid UUID".to_string(),
722 ),
723 });
724 }
725
726 if let (Some(from), Some(to)) = (self.valid_from, self.valid_to)
728 && from >= to
729 {
730 errors.push(ValidationError {
731 field: "time_window".to_string(),
732 error_type: ValidationErrorType::OutOfRange,
733 message: format!("valid_from ({}) must be before valid_to ({})", from, to),
734 suggestion: Some("Ensure valid_from is earlier than valid_to".to_string()),
735 });
736 }
737
738 for (idx, attr_policy) in self.body.attributes.iter().enumerate() {
740 if let Err(e) = validate_policy(attr_policy) {
741 errors.push(ValidationError {
742 field: format!("attributes[{}]", idx),
743 error_type: ValidationErrorType::InvalidFormat,
744 message: format!("Invalid attribute policy: {}", e),
745 suggestion: None,
746 });
747 }
748 }
749
750 if self.body.dissem.is_empty() && !self.body.attributes.is_empty() {
752 errors.push(ValidationError {
753 field: "dissem".to_string(),
754 error_type: ValidationErrorType::EmptyList,
755 message: "Dissemination list is empty but attributes are defined".to_string(),
756 suggestion: Some(
757 "Add at least one dissemination entity or remove all attributes".to_string(),
758 ),
759 });
760 }
761
762 let mut seen = std::collections::HashSet::new();
764 for (idx, entity) in self.body.dissem.iter().enumerate() {
765 if entity.trim().is_empty() {
766 errors.push(ValidationError {
767 field: format!("dissem[{}]", idx),
768 error_type: ValidationErrorType::InvalidFormat,
769 message: "Empty dissemination entity".to_string(),
770 suggestion: Some("Remove empty entries from dissemination list".to_string()),
771 });
772 } else if !seen.insert(entity) {
773 errors.push(ValidationError {
774 field: format!("dissem[{}]", idx),
775 error_type: ValidationErrorType::InvalidFormat,
776 message: format!("Duplicate dissemination entity: {}", entity),
777 suggestion: Some(
778 "Remove duplicate entries from dissemination list".to_string(),
779 ),
780 });
781 }
782 }
783
784 if errors.is_empty() {
785 Ok(())
786 } else {
787 Err(PolicyError::ValidationFailed(errors))
788 }
789 }
790
791 pub fn evaluate(
796 &self,
797 attributes: &HashMap<AttributeIdentifier, AttributeValue>,
798 ) -> Result<bool, PolicyError> {
799 for policy in &self.body.attributes {
801 validate_policy(policy)?;
802 }
803
804 if !self.is_valid_at(Utc::now()) {
806 return Ok(false);
807 }
808
809 if self.body.attributes.is_empty() {
811 return Ok(true);
812 }
813
814 for policy in &self.body.attributes {
816 if !policy.evaluate(attributes)? {
817 return Ok(false);
818 }
819 }
820
821 Ok(true)
822 }
823
824 pub fn has_attribute(&self, fqn: &crate::fqn::AttributeFqn) -> bool {
849 self.find_attribute(fqn).is_some()
850 }
851
852 pub fn find_attribute(&self, fqn: &crate::fqn::AttributeFqn) -> Option<&AttributeCondition> {
897 let mut pending: Vec<&AttributePolicy> = self.body.attributes.iter().rev().collect();
901
902 while let Some(node) = pending.pop() {
903 match node {
904 AttributePolicy::Condition(condition) => {
905 if condition_matches_fqn(condition, fqn) {
906 return Some(condition);
907 }
908 }
909 AttributePolicy::Logical(
910 LogicalOperator::AND { conditions } | LogicalOperator::OR { conditions },
911 ) => pending.extend(conditions.iter().rev()),
912 AttributePolicy::Logical(LogicalOperator::NOT { condition }) => {
913 pending.push(condition);
914 }
915 }
916 }
917
918 None
919 }
920}
921
922fn condition_matches_fqn(condition: &AttributeCondition, fqn: &crate::fqn::AttributeFqn) -> bool {
926 if condition.attribute.namespace.to_lowercase() != fqn.get_namespace() {
928 return false;
929 }
930
931 let wanted_value = fqn.get_value();
932
933 if fqn.get_name().is_empty() && wanted_value.is_none() {
935 return true;
936 }
937 if condition.attribute.name != fqn.get_name() {
938 return false;
939 }
940
941 match wanted_value {
942 None => true,
943 Some(wanted) => {
944 condition.operator == Operator::Equals
945 && matches!(&condition.value, Some(AttributeValue::String(value)) if value == wanted)
946 }
947 }
948}
949
950#[derive(Debug, Default)]
966pub struct PolicyBuilder {
967 uuid: Option<String>,
968 valid_from: Option<DateTime<Utc>>,
969 valid_to: Option<DateTime<Utc>>,
970 attributes: Vec<AttributePolicy>,
971 dissem: Vec<String>,
972}
973
974impl PolicyBuilder {
975 pub fn new() -> Self {
977 Self::default()
978 }
979
980 #[must_use]
982 pub fn id(mut self, uuid: impl Into<String>) -> Self {
983 self.uuid = Some(uuid.into());
984 self
985 }
986
987 #[must_use]
989 pub fn id_auto(mut self) -> Self {
990 self.uuid = Some(uuid::Uuid::new_v4().to_string());
991 self
992 }
993
994 #[must_use]
996 pub fn attribute(mut self, policy: AttributePolicy) -> Self {
997 self.attributes.push(policy);
998 self
999 }
1000
1001 pub fn attribute_fqn(mut self, fqn: impl AsRef<str>) -> Result<Self, PolicyError> {
1007 use crate::fqn::AttributeFqn;
1008
1009 let parsed = AttributeFqn::parse(fqn.as_ref())?;
1010 let identifier = parsed.to_identifier();
1011
1012 if let Some(value) = parsed.get_value() {
1013 self.attributes
1015 .push(AttributePolicy::Condition(AttributeCondition {
1016 attribute: identifier,
1017 operator: Operator::Equals,
1018 value: Some(AttributeValue::String(value.to_string())),
1019 }));
1020 } else {
1021 self.attributes
1023 .push(AttributePolicy::Condition(AttributeCondition {
1024 attribute: identifier,
1025 operator: Operator::Present,
1026 value: None,
1027 }));
1028 }
1029
1030 Ok(self)
1031 }
1032
1033 #[must_use]
1035 pub fn attributes(mut self, policies: impl IntoIterator<Item = AttributePolicy>) -> Self {
1036 self.attributes.extend(policies);
1037 self
1038 }
1039
1040 #[must_use]
1042 pub fn dissem(mut self, target: impl Into<String>) -> Self {
1043 self.dissem.push(target.into());
1044 self
1045 }
1046
1047 #[must_use]
1049 pub fn dissemination(mut self, targets: impl IntoIterator<Item = impl Into<String>>) -> Self {
1050 self.dissem.extend(targets.into_iter().map(|t| t.into()));
1051 self
1052 }
1053
1054 #[must_use]
1056 pub fn valid_from(mut self, time: DateTime<Utc>) -> Self {
1057 self.valid_from = Some(time);
1058 self
1059 }
1060
1061 #[must_use]
1063 pub fn valid_to(mut self, time: DateTime<Utc>) -> Self {
1064 self.valid_to = Some(time);
1065 self
1066 }
1067
1068 #[must_use]
1070 pub fn valid_window(mut self, from: DateTime<Utc>, to: DateTime<Utc>) -> Self {
1071 self.valid_from = Some(from);
1072 self.valid_to = Some(to);
1073 self
1074 }
1075
1076 #[must_use]
1078 pub fn valid_for(mut self, duration: chrono::Duration) -> Self {
1079 let now = Utc::now();
1080 self.valid_from = Some(now);
1081 self.valid_to = Some(now + duration);
1082 self
1083 }
1084
1085 #[must_use]
1087 pub fn valid_for_days(self, days: i64) -> Self {
1088 self.valid_for(chrono::Duration::days(days))
1089 }
1090
1091 pub fn build(self) -> Result<Policy, PolicyError> {
1095 let uuid = self
1096 .uuid
1097 .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
1098
1099 Ok(Policy {
1100 uuid,
1101 valid_from: self.valid_from,
1102 valid_to: self.valid_to,
1103 body: PolicyBody {
1104 attributes: self.attributes,
1105 dissem: self.dissem,
1106 },
1107 })
1108 }
1109}
1110
1111#[derive(Debug, Clone, PartialEq)]
1116pub struct ClearanceHierarchy {
1117 pub levels: HashMap<String, i32>,
1119}
1120
1121impl Default for ClearanceHierarchy {
1122 fn default() -> Self {
1123 let mut levels = HashMap::new();
1124 levels.insert("TOP_SECRET".to_string(), 4);
1125 levels.insert("SECRET".to_string(), 3);
1126 levels.insert("CONFIDENTIAL".to_string(), 2);
1127 levels.insert("PUBLIC".to_string(), 1);
1128 Self { levels }
1129 }
1130}
1131
1132pub static CLEARANCE_HIERARCHY: std::sync::OnceLock<ClearanceHierarchy> =
1134 std::sync::OnceLock::new();
1135
1136fn get_clearance_hierarchy() -> &'static ClearanceHierarchy {
1138 CLEARANCE_HIERARCHY.get_or_init(|| {
1139 ClearanceHierarchy::default()
1141 })
1142}
1143
1144pub fn validate_policy(policy: &AttributePolicy) -> Result<(), PolicyError> {
1147 match policy {
1148 AttributePolicy::Condition(condition) => validate_condition(condition),
1149 AttributePolicy::Logical(operator) => match operator {
1150 LogicalOperator::AND { conditions } | LogicalOperator::OR { conditions } => {
1151 for condition in conditions {
1152 validate_policy(condition)?;
1153 }
1154 Ok(())
1155 }
1156 LogicalOperator::NOT { condition } => validate_policy(condition),
1157 },
1158 }
1159}
1160
1161fn validate_condition(condition: &AttributeCondition) -> Result<(), PolicyError> {
1163 match condition.operator {
1165 Operator::Present | Operator::NotPresent => return Ok(()),
1166 _ => {}
1167 }
1168
1169 if condition.value.is_none() {
1171 return Err(PolicyError::InvalidValueType {
1172 attribute: condition.attribute.as_string(),
1173 expected: "a value".to_string(),
1174 actual: "None".to_string(),
1175 });
1176 }
1177
1178 if let Some(value) = &condition.value {
1180 match condition.operator {
1181 Operator::AllOf | Operator::AnyOf => {
1183 if !matches!(value, AttributeValue::StringArray(_)) {
1184 return Err(PolicyError::InvalidValueType {
1185 attribute: condition.attribute.as_string(),
1186 expected: "string array".to_string(),
1187 actual: format!("{:?}", value),
1188 });
1189 }
1190 }
1191
1192 Operator::In | Operator::NotIn => {
1194 if !matches!(
1195 value,
1196 AttributeValue::StringArray(_) | AttributeValue::NumberArray(_)
1197 ) {
1198 return Err(PolicyError::InvalidValueType {
1199 attribute: condition.attribute.as_string(),
1200 expected: "array (string or number)".to_string(),
1201 actual: format!("{:?}", value),
1202 });
1203 }
1204 }
1205
1206 Operator::Contains => {
1208 if !matches!(value, AttributeValue::String(_)) {
1209 return Err(PolicyError::InvalidValueType {
1210 attribute: condition.attribute.as_string(),
1211 expected: "string".to_string(),
1212 actual: format!("{:?}", value),
1213 });
1214 }
1215 }
1216
1217 Operator::GreaterThan
1219 | Operator::GreaterThanOrEqual
1220 | Operator::LessThan
1221 | Operator::LessThanOrEqual => {
1222 if !matches!(
1223 value,
1224 AttributeValue::Number(_) | AttributeValue::DateTime(_)
1225 ) {
1226 return Err(PolicyError::InvalidValueType {
1227 attribute: condition.attribute.as_string(),
1228 expected: "number or datetime".to_string(),
1229 actual: format!("{:?}", value),
1230 });
1231 }
1232 }
1233
1234 Operator::Equals
1236 | Operator::NotEquals
1237 | Operator::MinimumOf
1238 | Operator::MaximumOf
1239 | Operator::Present
1240 | Operator::NotPresent => {}
1241 }
1242 }
1243
1244 Ok(())
1245}
1246
1247fn evaluate_condition(
1249 condition: &AttributeCondition,
1250 attributes: &HashMap<AttributeIdentifier, AttributeValue>,
1251) -> Result<bool, PolicyError> {
1252 validate_condition(condition)?;
1254
1255 match condition.operator {
1257 Operator::Present => return Ok(attributes.contains_key(&condition.attribute)),
1258 Operator::NotPresent => return Ok(!attributes.contains_key(&condition.attribute)),
1259 _ => {}
1260 }
1261
1262 let attr_value = match attributes.get(&condition.attribute) {
1264 Some(value) => value,
1265 None => return Ok(false), };
1267
1268 let expected_value = match &condition.value {
1270 Some(value) => value,
1271 None => {
1272 return Err(PolicyError::EvaluationError {
1273 reason: "Value required for this operator".to_string(),
1274 attribute: Some(condition.attribute.as_string()),
1275 });
1276 }
1277 };
1278
1279 match condition.operator {
1281 Operator::Equals => Ok(compare_values(attr_value, expected_value, |a, b| a == b)?),
1282 Operator::NotEquals => Ok(compare_values(attr_value, expected_value, |a, b| a != b)?),
1283 Operator::GreaterThan => Ok(compare_numeric(attr_value, expected_value, |a, b| a > b)?),
1284 Operator::GreaterThanOrEqual => {
1285 Ok(compare_numeric(attr_value, expected_value, |a, b| a >= b)?)
1286 }
1287 Operator::LessThan => Ok(compare_numeric(attr_value, expected_value, |a, b| a < b)?),
1288 Operator::LessThanOrEqual => {
1289 Ok(compare_numeric(attr_value, expected_value, |a, b| a <= b)?)
1290 }
1291 Operator::Contains => match (attr_value, expected_value) {
1292 (AttributeValue::String(haystack), AttributeValue::String(needle)) => {
1293 Ok(haystack.contains(needle.as_str()))
1294 }
1295 _ => Err(PolicyError::InvalidValueType {
1296 attribute: condition.attribute.as_string(),
1297 expected: "string values".to_string(),
1298 actual: format!("attr={:?}, value={:?}", attr_value, expected_value),
1299 }),
1300 },
1301 Operator::In => match expected_value {
1302 AttributeValue::StringArray(values) => match attr_value {
1303 AttributeValue::String(s) => Ok(values.contains(s)),
1304 _ => Err(PolicyError::InvalidValueType {
1305 attribute: condition.attribute.as_string(),
1306 expected: "string".to_string(),
1307 actual: format!("{:?}", attr_value),
1308 }),
1309 },
1310 AttributeValue::NumberArray(values) => match attr_value {
1311 AttributeValue::Number(n) => Ok(values.contains(n)),
1312 _ => Err(PolicyError::InvalidValueType {
1313 attribute: condition.attribute.as_string(),
1314 expected: "number".to_string(),
1315 actual: format!("{:?}", attr_value),
1316 }),
1317 },
1318 _ => Err(PolicyError::InvalidValueType {
1319 attribute: condition.attribute.as_string(),
1320 expected: "array value".to_string(),
1321 actual: format!("{:?}", expected_value),
1322 }),
1323 },
1324 Operator::NotIn => match expected_value {
1325 AttributeValue::StringArray(values) => match attr_value {
1326 AttributeValue::String(s) => Ok(!values.contains(s)),
1327 _ => Err(PolicyError::InvalidValueType {
1328 attribute: condition.attribute.as_string(),
1329 expected: "string".to_string(),
1330 actual: format!("{:?}", attr_value),
1331 }),
1332 },
1333 AttributeValue::NumberArray(values) => match attr_value {
1334 AttributeValue::Number(n) => Ok(!values.contains(n)),
1335 _ => Err(PolicyError::InvalidValueType {
1336 attribute: condition.attribute.as_string(),
1337 expected: "number".to_string(),
1338 actual: format!("{:?}", attr_value),
1339 }),
1340 },
1341 _ => Err(PolicyError::InvalidValueType {
1342 attribute: condition.attribute.as_string(),
1343 expected: "array value".to_string(),
1344 actual: format!("{:?}", expected_value),
1345 }),
1346 },
1347 Operator::MinimumOf => {
1348 match (attr_value, expected_value) {
1351 (AttributeValue::String(a), AttributeValue::String(b)) => {
1352 if a == b {
1354 return Ok(true);
1355 }
1356
1357 let a_upper = a.to_uppercase();
1359 let b_upper = b.to_uppercase();
1360
1361 let hierarchy = get_clearance_hierarchy();
1363
1364 let level_a = hierarchy.levels.get(&a_upper).copied().unwrap_or(0);
1366 let level_b = hierarchy.levels.get(&b_upper).copied().unwrap_or(0);
1367
1368 Ok(level_a >= level_b)
1370 }
1371 _ => compare_numeric(attr_value, expected_value, |a, b| a >= b),
1372 }
1373 }
1374 Operator::MaximumOf => {
1375 match (attr_value, expected_value) {
1377 (AttributeValue::String(a), AttributeValue::String(b)) => {
1378 if a == b {
1380 return Ok(true);
1381 }
1382
1383 let a_upper = a.to_uppercase();
1385 let b_upper = b.to_uppercase();
1386
1387 let hierarchy = get_clearance_hierarchy();
1389
1390 let level_a = hierarchy.levels.get(&a_upper).copied().unwrap_or(0);
1392 let level_b = hierarchy.levels.get(&b_upper).copied().unwrap_or(0);
1393
1394 Ok(level_a <= level_b)
1396 }
1397 _ => compare_numeric(attr_value, expected_value, |a, b| a <= b),
1398 }
1399 }
1400 Operator::AllOf => match (expected_value, attr_value) {
1401 (AttributeValue::StringArray(required), AttributeValue::StringArray(actual)) => {
1402 Ok(required.iter().all(|r| actual.contains(r)))
1403 }
1404 _ => Err(PolicyError::InvalidValueType {
1405 attribute: condition.attribute.as_string(),
1406 expected: "string arrays".to_string(),
1407 actual: format!("expected={:?}, actual={:?}", expected_value, attr_value),
1408 }),
1409 },
1410 Operator::AnyOf => match (expected_value, attr_value) {
1411 (AttributeValue::StringArray(required), AttributeValue::StringArray(actual)) => {
1412 Ok(required.iter().any(|r| actual.contains(r)))
1413 }
1414 _ => Err(PolicyError::InvalidValueType {
1415 attribute: condition.attribute.as_string(),
1416 expected: "string arrays".to_string(),
1417 actual: format!("expected={:?}, actual={:?}", expected_value, attr_value),
1418 }),
1419 },
1420 Operator::Present | Operator::NotPresent => {
1422 unreachable!("These operators should be handled earlier")
1423 }
1424 }
1425}
1426
1427fn compare_values<F>(
1429 actual: &AttributeValue,
1430 expected: &AttributeValue,
1431 compare: F,
1432) -> Result<bool, PolicyError>
1433where
1434 F: Fn(&AttributeValue, &AttributeValue) -> bool,
1435{
1436 Ok(compare(actual, expected))
1438}
1439
1440fn compare_numeric<F>(
1442 actual: &AttributeValue,
1443 expected: &AttributeValue,
1444 compare: F,
1445) -> Result<bool, PolicyError>
1446where
1447 F: Fn(f64, f64) -> bool,
1448{
1449 match (actual, expected) {
1450 (AttributeValue::Number(a), AttributeValue::Number(b)) => Ok(compare(*a, *b)),
1451 (AttributeValue::DateTime(a), AttributeValue::DateTime(b)) => {
1452 Ok(compare(a.timestamp() as f64, b.timestamp() as f64))
1454 }
1455 _ => Err(PolicyError::InvalidValueType {
1456 attribute: "unknown".to_string(),
1457 expected: "number or datetime".to_string(),
1458 actual: format!("actual={:?}, expected={:?}", actual, expected),
1459 }),
1460 }
1461}
1462
1463#[cfg(test)]
1464mod tests {
1465 use super::*;
1466 use chrono::{Duration, TimeZone};
1467
1468 #[test]
1469 fn test_attribute_identifier_parsing() {
1470 let attr = AttributeIdentifier::from_string("clearance:SECRET").unwrap();
1471 assert_eq!(attr.namespace, "clearance");
1472 assert_eq!(attr.name, "SECRET");
1473
1474 let result = AttributeIdentifier::from_string("invalid_format");
1475 assert!(result.is_err());
1476 }
1477
1478 #[test]
1479 fn test_simple_equals_condition() {
1480 let attr_id = AttributeIdentifier::new("clearance", "level");
1481 let condition = AttributeCondition::equals(
1482 attr_id.clone(),
1483 AttributeValue::String("SECRET".to_string()),
1484 );
1485
1486 let mut attributes = HashMap::new();
1487 attributes.insert(
1488 attr_id.clone(),
1489 AttributeValue::String("SECRET".to_string()),
1490 );
1491
1492 let policy = AttributePolicy::Condition(condition);
1493 assert!(policy.evaluate(&attributes).unwrap());
1494
1495 attributes.insert(attr_id, AttributeValue::String("CONFIDENTIAL".to_string()));
1497 assert!(!policy.evaluate(&attributes).unwrap());
1498 }
1499
1500 #[test]
1501 fn test_logical_operators() {
1502 let dept_attr = AttributeIdentifier::new("department", "name");
1503 let level_attr = AttributeIdentifier::new("clearance", "level");
1504
1505 let dept_condition = AttributePolicy::condition(
1506 dept_attr.clone(),
1507 Operator::Equals,
1508 AttributeValue::String("FINANCE".to_string()),
1509 );
1510
1511 let level_condition = AttributePolicy::condition(
1512 level_attr.clone(),
1513 Operator::MinimumOf,
1514 AttributeValue::String("CONFIDENTIAL".to_string()),
1515 );
1516
1517 let and_policy =
1518 AttributePolicy::and(vec![dept_condition.clone(), level_condition.clone()]);
1519 let or_policy = AttributePolicy::or(vec![dept_condition.clone(), level_condition.clone()]);
1520
1521 let mut attributes = HashMap::new();
1522 attributes.insert(
1523 dept_attr.clone(),
1524 AttributeValue::String("FINANCE".to_string()),
1525 );
1526 attributes.insert(
1527 level_attr.clone(),
1528 AttributeValue::String("SECRET".to_string()),
1529 );
1530
1531 assert!(and_policy.evaluate(&attributes).unwrap());
1533 assert!(or_policy.evaluate(&attributes).unwrap());
1534
1535 attributes.insert(
1537 dept_attr.clone(),
1538 AttributeValue::String("ENGINEERING".to_string()),
1539 );
1540 assert!(!and_policy.evaluate(&attributes).unwrap());
1541 assert!(or_policy.evaluate(&attributes).unwrap());
1542
1543 let level_exact_match = AttributePolicy::condition(
1547 level_attr.clone(),
1548 Operator::Equals, AttributeValue::String("CONFIDENTIAL".to_string()),
1550 );
1551
1552 let and_policy_exact =
1553 AttributePolicy::and(vec![dept_condition.clone(), level_exact_match.clone()]);
1554 let or_policy_exact =
1555 AttributePolicy::or(vec![dept_condition.clone(), level_exact_match.clone()]);
1556
1557 attributes.insert(level_attr, AttributeValue::String("PUBLIC".to_string()));
1558 assert!(!and_policy_exact.evaluate(&attributes).unwrap());
1559 assert!(!or_policy_exact.evaluate(&attributes).unwrap());
1560
1561 let not_policy = !dept_condition.clone();
1563 assert!(not_policy.evaluate(&attributes).unwrap());
1564
1565 attributes.insert(dept_attr, AttributeValue::String("FINANCE".to_string()));
1566 assert!(!not_policy.evaluate(&attributes).unwrap());
1567 }
1568
1569 #[test]
1570 fn test_array_operators() {
1571 let locations = AttributeIdentifier::new("location", "allowed");
1572 let in_condition = AttributePolicy::condition(
1573 locations.clone(),
1574 Operator::In,
1575 AttributeValue::StringArray(vec![
1576 "USA".to_string(),
1577 "CANADA".to_string(),
1578 "UK".to_string(),
1579 ]),
1580 );
1581
1582 let mut attributes = HashMap::new();
1583 attributes.insert(locations.clone(), AttributeValue::String("USA".to_string()));
1584 assert!(in_condition.evaluate(&attributes).unwrap());
1585
1586 attributes.insert(
1587 locations.clone(),
1588 AttributeValue::String("FRANCE".to_string()),
1589 );
1590 assert!(!in_condition.evaluate(&attributes).unwrap());
1591
1592 let not_in_condition = AttributePolicy::condition(
1594 locations.clone(),
1595 Operator::NotIn,
1596 AttributeValue::StringArray(vec!["CHINA".to_string(), "RUSSIA".to_string()]),
1597 );
1598
1599 attributes.insert(locations, AttributeValue::String("USA".to_string()));
1600 assert!(not_in_condition.evaluate(&attributes).unwrap());
1601 }
1602
1603 #[test]
1604 fn test_time_based_policy() {
1605 let now = Utc::now();
1606 let tomorrow = now + Duration::days(1);
1607 let yesterday = now - Duration::days(1);
1608
1609 let mut policy = Policy::new(
1610 "test-uuid".to_string(),
1611 vec![],
1612 vec!["user@example.com".to_string()],
1613 );
1614
1615 assert!(policy.is_valid_at(now));
1617
1618 policy = policy.with_time_window(Some(tomorrow), None);
1620 assert!(!policy.is_valid_at(now));
1621
1622 policy = policy.with_time_window(Some(yesterday), None);
1624 assert!(policy.is_valid_at(now));
1625
1626 policy = policy.with_time_window(Some(yesterday), Some(tomorrow));
1628 assert!(policy.is_valid_at(now));
1629
1630 policy = policy.with_time_window(None, Some(yesterday));
1632 assert!(!policy.is_valid_at(now));
1633 }
1634
1635 #[test]
1636 fn test_policy_serialization() {
1637 let dept_attr = AttributeIdentifier::new("department", "name");
1638 let level_attr = AttributeIdentifier::new("clearance", "level");
1639
1640 let dept_condition = AttributePolicy::condition(
1641 dept_attr,
1642 Operator::Equals,
1643 AttributeValue::String("FINANCE".to_string()),
1644 );
1645
1646 let level_condition = AttributePolicy::condition(
1647 level_attr,
1648 Operator::MinimumOf,
1649 AttributeValue::String("CONFIDENTIAL".to_string()),
1650 );
1651
1652 let policy = Policy::new(
1653 "test-uuid".to_string(),
1654 vec![dept_condition, level_condition],
1655 vec!["user@example.com".to_string()],
1656 );
1657
1658 let json = policy.to_json().unwrap();
1659 let deserialized = Policy::from_json(&json).unwrap();
1660
1661 assert_eq!(policy.uuid, deserialized.uuid);
1662 assert_eq!(policy.body.dissem, deserialized.body.dissem);
1663 assert_eq!(
1664 policy.body.attributes.len(),
1665 deserialized.body.attributes.len()
1666 );
1667 }
1668
1669 #[test]
1670 fn test_complex_policy_evaluation() {
1671 let dept_attr = AttributeIdentifier::new("department", "name");
1673 let level_attr = AttributeIdentifier::new("clearance", "level");
1674 let region_attr = AttributeIdentifier::new("region", "code");
1675
1676 let finance_condition = AttributePolicy::condition(
1677 dept_attr.clone(),
1678 Operator::Equals,
1679 AttributeValue::String("FINANCE".to_string()),
1680 );
1681
1682 let legal_condition = AttributePolicy::condition(
1683 dept_attr.clone(),
1684 Operator::Equals,
1685 AttributeValue::String("LEGAL".to_string()),
1686 );
1687
1688 let clearance_condition = AttributePolicy::condition(
1689 level_attr.clone(),
1690 Operator::Equals,
1691 AttributeValue::String("SECRET".to_string()),
1692 );
1693
1694 let apac_condition = AttributePolicy::condition(
1695 region_attr.clone(),
1696 Operator::Equals,
1697 AttributeValue::String("APAC".to_string()),
1698 );
1699
1700 let dept_policy = AttributePolicy::or(vec![finance_condition, legal_condition]);
1701 let not_apac = AttributePolicy::not(apac_condition);
1702
1703 let complex_policy = AttributePolicy::and(vec![dept_policy, clearance_condition, not_apac]);
1704
1705 let mut attributes = HashMap::new();
1707 attributes.insert(
1708 dept_attr.clone(),
1709 AttributeValue::String("FINANCE".to_string()),
1710 );
1711 attributes.insert(
1712 level_attr.clone(),
1713 AttributeValue::String("SECRET".to_string()),
1714 );
1715 attributes.insert(
1716 region_attr.clone(),
1717 AttributeValue::String("EMEA".to_string()),
1718 );
1719
1720 assert!(complex_policy.evaluate(&attributes).unwrap());
1721
1722 attributes.insert(
1724 dept_attr.clone(),
1725 AttributeValue::String("LEGAL".to_string()),
1726 );
1727 assert!(complex_policy.evaluate(&attributes).unwrap());
1728
1729 attributes.insert(
1731 dept_attr.clone(),
1732 AttributeValue::String("FINANCE".to_string()),
1733 );
1734 attributes.insert(
1735 region_attr.clone(),
1736 AttributeValue::String("APAC".to_string()),
1737 );
1738 assert!(!complex_policy.evaluate(&attributes).unwrap());
1739
1740 attributes.insert(dept_attr, AttributeValue::String("MARKETING".to_string()));
1742 attributes.insert(region_attr, AttributeValue::String("EMEA".to_string()));
1743 assert!(!complex_policy.evaluate(&attributes).unwrap());
1744
1745 attributes.insert(
1747 level_attr,
1748 AttributeValue::String("CONFIDENTIAL".to_string()),
1749 );
1750 assert!(!complex_policy.evaluate(&attributes).unwrap());
1751 }
1752
1753 #[test]
1754 fn test_datetime_comparison() {
1755 let time_attr = AttributeIdentifier::new("access", "time");
1756
1757 let base_time = Utc.with_ymd_and_hms(2023, 4, 1, 9, 0, 0).unwrap();
1759
1760 let condition = AttributePolicy::condition(
1761 time_attr.clone(),
1762 Operator::GreaterThan,
1763 AttributeValue::DateTime(base_time),
1764 );
1765
1766 let mut attributes = HashMap::new();
1767
1768 let later = base_time + Duration::hours(1);
1770 attributes.insert(time_attr.clone(), AttributeValue::DateTime(later));
1771 assert!(condition.evaluate(&attributes).unwrap());
1772
1773 let earlier = base_time - Duration::hours(1);
1775 attributes.insert(time_attr, AttributeValue::DateTime(earlier));
1776 assert!(!condition.evaluate(&attributes).unwrap());
1777 }
1778}
1779
1780#[test]
1781fn test_empty_policy_serialization_compatibility() {
1782 let policy = Policy::new("test-uuid".to_string(), vec![], vec![]);
1785 let json_str = policy.to_json().unwrap();
1786
1787 println!("Serialized empty policy: {}", json_str);
1788
1789 assert!(
1791 json_str.contains(r#""dataAttributes":null"#),
1792 "Empty dataAttributes should serialize as null, got: {}",
1793 json_str
1794 );
1795 assert!(
1796 json_str.contains(r#""dissem":null"#),
1797 "Empty dissem should serialize as null, got: {}",
1798 json_str
1799 );
1800
1801 let parsed = Policy::from_json(&json_str).unwrap();
1803 assert_eq!(parsed.body.attributes.len(), 0);
1804 assert_eq!(parsed.body.dissem.len(), 0);
1805}
1806
1807#[test]
1808fn test_policy_validate_valid_policy() {
1809 let policy = PolicyBuilder::new()
1811 .id_auto()
1812 .attribute_fqn("https://example.com/attr/clearance/value/secret")
1813 .unwrap()
1814 .dissemination(["user@example.com"])
1815 .build()
1816 .unwrap();
1817
1818 assert!(policy.validate().is_ok());
1820}
1821
1822#[test]
1823fn test_policy_validate_invalid_uuid() {
1824 let policy = Policy::new("not-a-valid-uuid".to_string(), vec![], vec![]);
1826
1827 let result = policy.validate();
1828 assert!(result.is_err());
1829
1830 if let Err(PolicyError::ValidationFailed(errors)) = result {
1831 assert_eq!(errors.len(), 1);
1832 assert_eq!(errors[0].field, "uuid");
1833 assert_eq!(errors[0].error_type, ValidationErrorType::InvalidFormat);
1834 assert!(errors[0].suggestion.is_some());
1835 } else {
1836 panic!("Expected ValidationFailed error");
1837 }
1838}
1839
1840#[test]
1841fn test_policy_validate_invalid_time_window() {
1842 use chrono::Duration;
1843
1844 let now = Utc::now();
1845 let future = now + Duration::days(7);
1846 let past = now - Duration::days(7);
1847
1848 let mut policy = PolicyBuilder::new()
1850 .id_auto()
1851 .dissemination(["user@example.com"])
1852 .build()
1853 .unwrap();
1854
1855 policy.valid_from = Some(future);
1856 policy.valid_to = Some(past);
1857
1858 let result = policy.validate();
1859 assert!(result.is_err());
1860
1861 if let Err(PolicyError::ValidationFailed(errors)) = result {
1862 assert!(errors.iter().any(|e| e.field == "time_window"));
1863 assert!(
1864 errors
1865 .iter()
1866 .any(|e| e.error_type == ValidationErrorType::OutOfRange)
1867 );
1868 } else {
1869 panic!("Expected ValidationFailed error");
1870 }
1871}
1872
1873#[test]
1874fn test_policy_validate_empty_dissem_with_attributes() {
1875 let attr_policy = AttributePolicy::condition(
1877 AttributeIdentifier::new("example.com", "clearance"),
1878 Operator::Equals,
1879 AttributeValue::String("secret".to_string()),
1880 );
1881
1882 let policy = Policy::new(uuid::Uuid::new_v4().to_string(), vec![attr_policy], vec![]);
1883
1884 let result = policy.validate();
1885 assert!(result.is_err());
1886
1887 if let Err(PolicyError::ValidationFailed(errors)) = result {
1888 assert!(errors.iter().any(|e| e.field == "dissem"));
1889 assert!(
1890 errors
1891 .iter()
1892 .any(|e| e.error_type == ValidationErrorType::EmptyList)
1893 );
1894 } else {
1895 panic!("Expected ValidationFailed error");
1896 }
1897}
1898
1899#[test]
1900fn test_policy_validate_duplicate_dissem_entities() {
1901 let policy = PolicyBuilder::new()
1903 .id_auto()
1904 .attribute_fqn("https://example.com/attr/clearance/value/secret")
1905 .unwrap()
1906 .dissemination(["user@example.com", "admin@example.com", "user@example.com"])
1907 .build()
1908 .unwrap();
1909
1910 let result = policy.validate();
1911 assert!(result.is_err());
1912
1913 if let Err(PolicyError::ValidationFailed(errors)) = result {
1914 assert!(errors.iter().any(|e| e.field.starts_with("dissem[")));
1915 assert!(
1916 errors
1917 .iter()
1918 .any(|e| e.message.contains("Duplicate dissemination entity"))
1919 );
1920 } else {
1921 panic!("Expected ValidationFailed error");
1922 }
1923}
1924
1925#[test]
1926fn test_policy_validate_empty_dissem_entry() {
1927 let mut policy = PolicyBuilder::new()
1929 .id_auto()
1930 .attribute_fqn("https://example.com/attr/clearance/value/secret")
1931 .unwrap()
1932 .dissemination(["user@example.com"])
1933 .build()
1934 .unwrap();
1935
1936 policy.body.dissem.push("".to_string());
1938 policy.body.dissem.push(" ".to_string()); let result = policy.validate();
1941 assert!(result.is_err());
1942
1943 if let Err(PolicyError::ValidationFailed(errors)) = result {
1944 assert!(errors.len() >= 2); assert!(
1946 errors
1947 .iter()
1948 .any(|e| e.message.contains("Empty dissemination entity"))
1949 );
1950 } else {
1951 panic!("Expected ValidationFailed error");
1952 }
1953}
1954
1955#[test]
1956fn test_policy_validate_multiple_errors() {
1957 let mut policy = Policy::new("invalid-uuid".to_string(), vec![], vec![]);
1959
1960 let now = Utc::now();
1962 policy.valid_from = Some(now);
1963 policy.valid_to = Some(now - chrono::Duration::days(1));
1964
1965 let result = policy.validate();
1966 assert!(result.is_err());
1967
1968 if let Err(PolicyError::ValidationFailed(errors)) = result {
1969 assert!(errors.len() >= 2);
1971 assert!(errors.iter().any(|e| e.field == "uuid"));
1972 assert!(errors.iter().any(|e| e.field == "time_window"));
1973 } else {
1974 panic!("Expected ValidationFailed error");
1975 }
1976}
1977
1978#[cfg(test)]
1979mod attribute_lookup_tests {
1980 use super::*;
1981 use crate::fqn::AttributeFqn;
1982
1983 const NS: &str = "example.com";
1984
1985 fn string(value: &str) -> AttributeValue {
1986 AttributeValue::String(value.to_string())
1987 }
1988
1989 fn equals(name: &str, value: &str) -> AttributeCondition {
1990 AttributeCondition::equals(AttributeIdentifier::new(NS, name), string(value))
1991 }
1992
1993 fn policy(attributes: Vec<AttributePolicy>) -> Policy {
1994 Policy::new(
1995 "00000000-0000-0000-0000-000000000000".to_string(),
1996 attributes,
1997 vec![],
1998 )
1999 }
2000
2001 fn fqn(url: &str) -> AttributeFqn {
2002 AttributeFqn::parse(url).unwrap()
2003 }
2004
2005 #[test]
2006 fn finds_condition_built_from_the_same_fqn() {
2007 let url = "https://example.com/attr/storage/value/permanent";
2008 let policy = PolicyBuilder::new()
2009 .id_auto()
2010 .dissem("user@example.com")
2011 .attribute_fqn(url)
2012 .unwrap()
2013 .build()
2014 .unwrap();
2015
2016 assert!(policy.has_attribute(&fqn(url)));
2017 assert_eq!(
2018 policy.find_attribute(&fqn(url)),
2019 Some(&equals("storage", "permanent"))
2020 );
2021
2022 for miss in [
2024 "https://example.com/attr/storage/value/temporary",
2025 "https://example.com/attr/retention/value/permanent",
2026 "https://other.example.com/attr/storage/value/permanent",
2027 "https://example.com/attr/Storage/value/permanent",
2028 "https://example.com/attr/storage/value/Permanent",
2029 ] {
2030 assert!(!policy.has_attribute(&fqn(miss)), "{miss}");
2031 assert_eq!(policy.find_attribute(&fqn(miss)), None, "{miss}");
2032 }
2033 }
2034
2035 #[test]
2036 fn empty_policy_has_no_attributes() {
2037 let policy = policy(vec![]);
2038 assert!(!policy.has_attribute(&fqn("https://example.com")));
2039 assert_eq!(
2040 policy.find_attribute(&fqn("https://example.com/attr/storage")),
2041 None
2042 );
2043 }
2044
2045 #[test]
2046 fn attribute_fqn_without_value_matches_any_operator() {
2047 let id = AttributeIdentifier::new(NS, "storage");
2048 let conditions = [
2049 AttributeCondition::present(id.clone()),
2050 AttributeCondition::new(id.clone(), Operator::NotPresent, None),
2051 AttributeCondition::new(id.clone(), Operator::NotEquals, Some(string("permanent"))),
2052 AttributeCondition::new(
2053 id.clone(),
2054 Operator::In,
2055 Some(AttributeValue::StringArray(vec!["permanent".to_string()])),
2056 ),
2057 AttributeCondition::new(id, Operator::GreaterThan, Some(AttributeValue::Number(1.0))),
2058 ];
2059
2060 for condition in conditions {
2061 let policy = policy(vec![AttributePolicy::Condition(condition.clone())]);
2062 assert_eq!(
2063 policy.find_attribute(&fqn("https://example.com/attr/storage")),
2064 Some(&condition),
2065 "{condition:?}"
2066 );
2067 assert!(!policy.has_attribute(&fqn("https://example.com/attr/retention")));
2069 }
2070 }
2071
2072 #[test]
2073 fn value_fqn_matches_only_string_equality() {
2074 let id = AttributeIdentifier::new(NS, "storage");
2075 let wanted = fqn("https://example.com/attr/storage/value/permanent");
2076 let mentions_but_does_not_require = [
2077 AttributeCondition::present(id.clone()),
2078 AttributeCondition::new(id.clone(), Operator::NotEquals, Some(string("permanent"))),
2079 AttributeCondition::new(id.clone(), Operator::MinimumOf, Some(string("permanent"))),
2080 AttributeCondition::new(id.clone(), Operator::Contains, Some(string("permanent"))),
2081 AttributeCondition::new(
2082 id.clone(),
2083 Operator::In,
2084 Some(AttributeValue::StringArray(vec!["permanent".to_string()])),
2085 ),
2086 AttributeCondition::new(
2087 id.clone(),
2088 Operator::AnyOf,
2089 Some(AttributeValue::StringArray(vec!["permanent".to_string()])),
2090 ),
2091 AttributeCondition::new(
2093 id.clone(),
2094 Operator::Equals,
2095 Some(AttributeValue::StringArray(vec!["permanent".to_string()])),
2096 ),
2097 AttributeCondition::new(id.clone(), Operator::Equals, None),
2098 ];
2099
2100 for condition in mentions_but_does_not_require {
2101 let policy = policy(vec![AttributePolicy::Condition(condition.clone())]);
2102 assert!(!policy.has_attribute(&wanted), "{condition:?}");
2103 }
2104
2105 let numeric = policy(vec![AttributePolicy::Condition(
2107 AttributeCondition::equals(id, AttributeValue::Number(5.0)),
2108 )]);
2109 assert!(!numeric.has_attribute(&fqn("https://example.com/attr/storage/value/5")));
2110 }
2111
2112 #[test]
2113 fn namespace_fqn_matches_any_attribute_in_the_namespace() {
2114 let policy = policy(vec![
2115 AttributePolicy::Condition(equals("storage", "permanent")),
2116 AttributePolicy::Condition(equals("retention", "7y")),
2117 ]);
2118
2119 assert_eq!(
2121 policy.find_attribute(&fqn("https://example.com")),
2122 Some(&equals("storage", "permanent"))
2123 );
2124 assert_eq!(
2125 policy.find_attribute(&AttributeFqn::namespace(NS)),
2126 Some(&equals("storage", "permanent"))
2127 );
2128 assert!(!policy.has_attribute(&fqn("https://other.example.com")));
2129 assert!(!policy.has_attribute(&fqn("https://example.co")));
2131 assert!(!policy.has_attribute(&fqn("https://sub.example.com")));
2132 assert!(!policy.has_attribute(&AttributeFqn::with_value(NS, "", "permanent")));
2134 }
2135
2136 #[test]
2137 fn namespace_is_compared_case_insensitively() {
2138 let condition = AttributeCondition::equals(
2140 AttributeIdentifier::new("Example.COM", "storage"),
2141 string("permanent"),
2142 );
2143 let policy = policy(vec![AttributePolicy::Condition(condition.clone())]);
2144
2145 for url in [
2146 "https://example.com",
2147 "https://EXAMPLE.com/attr/storage",
2148 "https://example.com/attr/storage/value/permanent",
2149 ] {
2150 assert_eq!(policy.find_attribute(&fqn(url)), Some(&condition), "{url}");
2151 }
2152 }
2153
2154 #[test]
2155 fn finds_conditions_nested_in_logical_operators() {
2156 let policy = policy(vec![
2157 AttributePolicy::Condition(equals("top", "1")),
2158 AttributePolicy::and(vec![
2159 AttributePolicy::or(vec![
2160 AttributePolicy::Condition(equals("in-or", "2")),
2161 AttributePolicy::create_not(AttributePolicy::Condition(equals("in-not", "3"))),
2162 ]),
2163 AttributePolicy::Condition(equals("in-and", "4")),
2164 ]),
2165 ]);
2166
2167 for (name, value) in [
2168 ("top", "1"),
2169 ("in-or", "2"),
2170 ("in-not", "3"),
2171 ("in-and", "4"),
2172 ] {
2173 let url = format!("https://example.com/attr/{name}/value/{value}");
2174 assert_eq!(
2175 policy.find_attribute(&fqn(&url)),
2176 Some(&equals(name, value)),
2177 "{url}"
2178 );
2179 }
2180 assert!(!policy.has_attribute(&fqn("https://example.com/attr/absent")));
2181 }
2182
2183 #[test]
2184 fn returns_the_first_match_in_document_order() {
2185 let policy = policy(vec![
2186 AttributePolicy::or(vec![
2187 AttributePolicy::Condition(equals("other", "x")),
2188 AttributePolicy::and(vec![AttributePolicy::Condition(equals(
2189 "storage", "nested",
2190 ))]),
2191 AttributePolicy::Condition(equals("storage", "sibling")),
2192 ]),
2193 AttributePolicy::Condition(equals("storage", "top-level")),
2194 ]);
2195
2196 assert_eq!(
2197 policy.find_attribute(&fqn("https://example.com/attr/storage")),
2198 Some(&equals("storage", "nested"))
2199 );
2200 assert_eq!(
2202 policy.find_attribute(&fqn("https://example.com/attr/storage/value/top-level")),
2203 Some(&equals("storage", "top-level"))
2204 );
2205 }
2206
2207 #[test]
2208 fn finds_attribute_in_policy_parsed_from_manifest_json() {
2209 let json = r#"{
2210 "uuid": "00000000-0000-0000-0000-000000000000",
2211 "body": {
2212 "dataAttributes": [{
2213 "type": "AND",
2214 "conditions": [{
2215 "attribute": {"namespace": "example.com", "name": "storage"},
2216 "operator": "equals",
2217 "value": "permanent"
2218 }]
2219 }],
2220 "dissem": null
2221 }
2222 }"#;
2223 let policy = Policy::from_json(json).unwrap();
2224
2225 assert!(policy.has_attribute(&fqn("https://example.com/attr/storage/value/permanent")));
2226 assert!(!policy.has_attribute(&fqn("https://example.com/attr/storage/value/other")));
2227 }
2228
2229 #[test]
2230 fn deeply_nested_policy_is_searched_without_recursion() {
2231 let mut nested = AttributePolicy::Condition(equals("storage", "permanent"));
2232 for _ in 0..2_000 {
2233 nested = AttributePolicy::create_not(nested);
2234 }
2235 let policy = policy(vec![nested]);
2236
2237 assert!(policy.has_attribute(&fqn("https://example.com/attr/storage/value/permanent")));
2238 assert!(!policy.has_attribute(&fqn("https://example.com/attr/absent")));
2239 }
2240}