Skip to main content

iicp_management_core/
lib.rs

1use serde::{Deserialize, Serialize};
2use serde_json::{Map, Value};
3use sha2::{Digest, Sha256};
4use std::collections::{BTreeMap, BTreeSet};
5use std::time::{Duration, Instant};
6use thiserror::Error;
7
8pub mod adapters;
9pub mod apply_gate;
10pub mod bootstrap;
11pub mod controller;
12pub mod diagnostics;
13pub mod execution;
14pub mod ipc;
15pub mod policy_lifecycle;
16pub mod profile;
17pub mod progressive_authority;
18pub mod reconciliation;
19pub mod recovery;
20pub mod resolution;
21pub mod rollout;
22pub mod routing_enforcement;
23pub mod runtime_observation;
24pub mod sandbox;
25pub mod templates;
26pub mod trial;
27
28pub const CONTRACT_VERSION: &str = "1";
29pub const PLANNER_VERSION: &str = "iicp-management-planner/0.1.0";
30pub const POLICY_PROFILE: &str = "iicp.management-policy.typed-v0";
31pub const MAX_POLICY_DEPTH: usize = 16;
32pub const MAX_COLLECTION_VALUES: usize = 1024;
33pub const MAX_POLICY_FUEL: usize = 50_000;
34pub const MAX_POLICY_BYTES: usize = 1024 * 1024;
35pub const MAX_POLICY_RULES: usize = 1_000;
36pub const MAX_AST_NODES_PER_RULE: usize = 256;
37pub const MAX_CONTEXT_BYTES: usize = 2 * 1024 * 1024;
38pub const MAX_REFERENCE_DEPTH: usize = 16;
39pub const MAX_POLICY_DURATION: Duration = Duration::from_millis(100);
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct EvaluationLimits {
43    pub policy_bytes: usize,
44    pub rules: usize,
45    pub ast_nodes_per_rule: usize,
46    pub expression_depth: usize,
47    pub collection_values: usize,
48    pub context_bytes: usize,
49    pub reference_depth: usize,
50    pub fuel: usize,
51    pub wall_clock: Duration,
52}
53
54impl Default for EvaluationLimits {
55    fn default() -> Self {
56        Self {
57            policy_bytes: MAX_POLICY_BYTES,
58            rules: MAX_POLICY_RULES,
59            ast_nodes_per_rule: MAX_AST_NODES_PER_RULE,
60            expression_depth: MAX_POLICY_DEPTH,
61            collection_values: MAX_COLLECTION_VALUES,
62            context_bytes: MAX_CONTEXT_BYTES,
63            reference_depth: MAX_REFERENCE_DEPTH,
64            fuel: MAX_POLICY_FUEL,
65            wall_clock: MAX_POLICY_DURATION,
66        }
67    }
68}
69
70impl EvaluationLimits {
71    fn profile_compliant(self) -> bool {
72        [
73            (self.policy_bytes, MAX_POLICY_BYTES),
74            (self.rules, MAX_POLICY_RULES),
75            (self.ast_nodes_per_rule, MAX_AST_NODES_PER_RULE),
76            (self.expression_depth, MAX_POLICY_DEPTH),
77            (self.collection_values, MAX_COLLECTION_VALUES),
78            (self.context_bytes, MAX_CONTEXT_BYTES),
79            (self.reference_depth, MAX_REFERENCE_DEPTH),
80            (self.fuel, MAX_POLICY_FUEL),
81        ]
82        .into_iter()
83        .all(|(value, maximum)| value > 0 && value <= maximum)
84            && self.wall_clock <= MAX_POLICY_DURATION
85    }
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
89#[serde(deny_unknown_fields)]
90pub struct DesiredStateBundle {
91    pub schema_version: String,
92    pub bundle_id: String,
93    pub issuer: String,
94    pub audience: String,
95    pub expected_generation: u64,
96    pub resources: Vec<ManagedResource>,
97    #[serde(default)]
98    pub extensions: Vec<ExtensionRequirement>,
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
102#[serde(deny_unknown_fields)]
103pub struct ManagedResource {
104    pub resource_id: String,
105    pub kind: String,
106    pub desired: Value,
107    #[serde(default)]
108    pub secret_refs: BTreeMap<String, String>,
109}
110
111#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
112#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
113pub enum ExtensionClass {
114    OptionalIgnorable,
115    OptionalNegotiable,
116    RequiredUnderstood,
117    RequiredSecurityCritical,
118}
119
120#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
121#[serde(deny_unknown_fields)]
122pub struct ExtensionRequirement {
123    pub id: String,
124    pub class: ExtensionClass,
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
128#[serde(deny_unknown_fields)]
129pub struct AcceptedState {
130    pub generation: u64,
131    pub resource_digests: BTreeMap<String, String>,
132}
133
134#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
135#[serde(deny_unknown_fields)]
136pub struct Plan {
137    pub schema_version: String,
138    pub planner_version: String,
139    pub bundle_id: String,
140    pub bundle_digest: String,
141    pub expected_generation: u64,
142    pub target_generation: u64,
143    pub operations: Vec<Operation>,
144}
145
146#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
147#[serde(deny_unknown_fields)]
148pub struct Operation {
149    pub operation_id: String,
150    pub resource_id: String,
151    pub action: String,
152    pub before_digest: String,
153    pub after_digest: String,
154    pub expected_generation: u64,
155    pub target_generation: u64,
156    pub idempotency_key: String,
157}
158
159#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
160#[serde(deny_unknown_fields)]
161pub struct Approval {
162    pub schema_version: String,
163    pub approval_id: String,
164    pub audience: String,
165    pub bundle_digest: String,
166    pub plan_digest: String,
167    pub expected_generation: u64,
168}
169
170#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
171#[serde(rename_all = "snake_case")]
172pub enum ConvergenceState {
173    Converged,
174    PartiallyConverged,
175    Failed,
176}
177
178#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
179#[serde(deny_unknown_fields)]
180pub struct Observation {
181    pub schema_version: String,
182    pub resource_id: String,
183    pub observed_generation: u64,
184    pub observed_digest: String,
185    pub state: ConvergenceState,
186}
187
188#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
189#[serde(deny_unknown_fields)]
190pub struct Receipt {
191    pub schema_version: String,
192    pub receipt_id: String,
193    pub audience: String,
194    pub bundle_digest: String,
195    pub plan_digest: String,
196    pub accepted_generation: u64,
197    pub effective_state: ConvergenceState,
198    pub observations: Vec<Observation>,
199}
200
201#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
202#[serde(rename_all = "snake_case")]
203pub enum PolicyDecision {
204    Allow,
205    Deny,
206    Indeterminate,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
210#[serde(deny_unknown_fields)]
211pub struct PolicyResult {
212    pub decision: PolicyDecision,
213    pub reason_codes: Vec<String>,
214    pub input_digest: String,
215    pub policy_digest: String,
216    pub evaluator_profile: String,
217}
218
219#[derive(Debug, Error, PartialEq, Eq)]
220pub enum ManagementError {
221    #[error("SCHEMA_UNSUPPORTED_VERSION")]
222    UnsupportedVersion,
223    #[error("SEMANTIC_EMPTY_IDENTIFIER")]
224    EmptyIdentifier,
225    #[error("SEMANTIC_DUPLICATE_RESOURCE")]
226    DuplicateResource,
227    #[error("SECRET_INLINE_VALUE_FORBIDDEN")]
228    InlineSecret,
229    #[error("PROFILE_UNSUPPORTED_REQUIRED:{0}")]
230    UnsupportedRequiredExtension(String),
231    #[error("PLAN_STALE_GENERATION")]
232    StaleGeneration,
233    #[error("PLAN_APPROVAL_DIGEST_MISMATCH")]
234    ApprovalDigestMismatch,
235    #[error("AUTHZ_WRONG_AUDIENCE")]
236    WrongAudience,
237    #[error("PLAN_RESOURCE_LIMIT")]
238    ResourceLimit,
239    #[error("PLAN_CANCELLED")]
240    Cancelled,
241    #[error("RECEIPT_BINDING_MISMATCH")]
242    ReceiptBindingMismatch,
243    #[error("RECEIPT_EFFECTIVE_STATE_MISMATCH")]
244    ReceiptStateMismatch,
245    #[error("SCHEMA_SERIALIZATION")]
246    Serialization,
247}
248
249pub fn canonical_json(value: &Value) -> Value {
250    match value {
251        Value::Object(map) => {
252            let sorted: BTreeMap<_, _> = map
253                .iter()
254                .map(|(key, value)| (key.clone(), canonical_json(value)))
255                .collect();
256            Value::Object(Map::from_iter(sorted))
257        }
258        Value::Array(values) => Value::Array(values.iter().map(canonical_json).collect()),
259        other => other.clone(),
260    }
261}
262
263pub fn digest<T: Serialize>(value: &T) -> Result<String, ManagementError> {
264    let bytes = serde_jcs::to_vec(value).map_err(|_| ManagementError::Serialization)?;
265    Ok(format!("sha256:{:x}", Sha256::digest(bytes)))
266}
267
268fn contains_inline_secret(value: &Value) -> bool {
269    match value {
270        Value::Object(map) => map.iter().any(|(key, value)| {
271            matches!(
272                key.as_str(),
273                "secret" | "secret_value" | "password" | "token" | "private_key"
274            ) || contains_inline_secret(value)
275        }),
276        Value::Array(values) => values.iter().any(contains_inline_secret),
277        _ => false,
278    }
279}
280
281pub fn validate_bundle(
282    bundle: &DesiredStateBundle,
283    supported_extensions: &BTreeSet<String>,
284    max_resources: usize,
285) -> Result<(), ManagementError> {
286    if bundle.schema_version != CONTRACT_VERSION {
287        return Err(ManagementError::UnsupportedVersion);
288    }
289    if bundle.bundle_id.is_empty() || bundle.issuer.is_empty() || bundle.audience.is_empty() {
290        return Err(ManagementError::EmptyIdentifier);
291    }
292    if bundle.resources.len() > max_resources {
293        return Err(ManagementError::ResourceLimit);
294    }
295    let mut ids = BTreeSet::new();
296    for resource in &bundle.resources {
297        if resource.resource_id.is_empty() || resource.kind.is_empty() {
298            return Err(ManagementError::EmptyIdentifier);
299        }
300        if !ids.insert(&resource.resource_id) {
301            return Err(ManagementError::DuplicateResource);
302        }
303        if contains_inline_secret(&resource.desired) {
304            return Err(ManagementError::InlineSecret);
305        }
306    }
307    for extension in &bundle.extensions {
308        if !supported_extensions.contains(&extension.id)
309            && matches!(
310                extension.class,
311                ExtensionClass::RequiredUnderstood | ExtensionClass::RequiredSecurityCritical
312            )
313        {
314            return Err(ManagementError::UnsupportedRequiredExtension(
315                extension.id.clone(),
316            ));
317        }
318    }
319    Ok(())
320}
321
322pub fn plan(
323    bundle: &DesiredStateBundle,
324    accepted: &AcceptedState,
325    supported_extensions: &BTreeSet<String>,
326    max_resources: usize,
327) -> Result<Plan, ManagementError> {
328    plan_with_control(
329        bundle,
330        accepted,
331        supported_extensions,
332        PlanningControl {
333            max_resources,
334            cancelled: false,
335        },
336    )
337}
338
339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340pub struct PlanningControl {
341    pub max_resources: usize,
342    pub cancelled: bool,
343}
344
345pub fn plan_with_control(
346    bundle: &DesiredStateBundle,
347    accepted: &AcceptedState,
348    supported_extensions: &BTreeSet<String>,
349    control: PlanningControl,
350) -> Result<Plan, ManagementError> {
351    if control.cancelled {
352        return Err(ManagementError::Cancelled);
353    }
354    validate_bundle(bundle, supported_extensions, control.max_resources)?;
355    if bundle.expected_generation != accepted.generation {
356        return Err(ManagementError::StaleGeneration);
357    }
358    let mut normalized_bundle = bundle.clone();
359    normalized_bundle
360        .resources
361        .sort_by(|a, b| a.resource_id.cmp(&b.resource_id));
362    normalized_bundle.extensions.sort_by(|a, b| {
363        let left = format!("{:?}:{}", a.class, a.id);
364        let right = format!("{:?}:{}", b.class, b.id);
365        left.cmp(&right)
366    });
367    let bundle_digest = digest(&normalized_bundle)?;
368    let target_generation = accepted.generation + 1;
369    let mut resources = bundle.resources.clone();
370    resources.sort_by(|a, b| a.resource_id.cmp(&b.resource_id));
371    let mut operations = Vec::with_capacity(resources.len());
372    for (index, resource) in resources.iter().enumerate() {
373        let after_digest = digest(&resource.desired)?;
374        let before_digest = accepted
375            .resource_digests
376            .get(&resource.resource_id)
377            .cloned()
378            .unwrap_or_else(|| "absent".to_string());
379        let action = if before_digest == "absent" {
380            "create"
381        } else {
382            "update"
383        };
384        operations.push(Operation {
385            operation_id: format!("op-{:04}", index + 1),
386            resource_id: resource.resource_id.clone(),
387            action: action.to_string(),
388            before_digest,
389            after_digest,
390            expected_generation: accepted.generation,
391            target_generation,
392            idempotency_key: format!("{}:{}", bundle.bundle_id, resource.resource_id),
393        });
394    }
395    Ok(Plan {
396        schema_version: CONTRACT_VERSION.to_string(),
397        planner_version: PLANNER_VERSION.to_string(),
398        bundle_id: bundle.bundle_id.clone(),
399        bundle_digest,
400        expected_generation: accepted.generation,
401        target_generation,
402        operations,
403    })
404}
405
406pub fn authorize_plan(
407    approval: &Approval,
408    plan: &Plan,
409    local_audience: &str,
410) -> Result<(), ManagementError> {
411    if approval.audience != local_audience {
412        return Err(ManagementError::WrongAudience);
413    }
414    if approval.expected_generation != plan.expected_generation
415        || approval.bundle_digest != plan.bundle_digest
416        || approval.plan_digest != digest(plan)?
417    {
418        return Err(ManagementError::ApprovalDigestMismatch);
419    }
420    Ok(())
421}
422
423pub fn derive_effective_state(observations: &[Observation]) -> ConvergenceState {
424    let converged = observations
425        .iter()
426        .filter(|observation| observation.state == ConvergenceState::Converged)
427        .count();
428    let failed = observations
429        .iter()
430        .filter(|observation| observation.state == ConvergenceState::Failed)
431        .count();
432    if !observations.is_empty() && converged == observations.len() {
433        ConvergenceState::Converged
434    } else if observations.is_empty() || failed == observations.len() {
435        ConvergenceState::Failed
436    } else {
437        ConvergenceState::PartiallyConverged
438    }
439}
440
441fn observations_match_plan(receipt: &Receipt, plan: &Plan) -> bool {
442    if receipt.observations.len() != plan.operations.len() {
443        return false;
444    }
445    let mut seen = BTreeSet::new();
446    for observation in &receipt.observations {
447        let Some(operation) = plan
448            .operations
449            .iter()
450            .find(|operation| operation.resource_id == observation.resource_id)
451        else {
452            return false;
453        };
454        if observation.schema_version != CONTRACT_VERSION
455            || observation.observed_generation != receipt.accepted_generation
456            || !seen.insert(&observation.resource_id)
457            || (observation.state == ConvergenceState::Converged
458                && observation.observed_digest != operation.after_digest)
459        {
460            return false;
461        }
462    }
463    true
464}
465
466pub fn verify_receipt(
467    receipt: &Receipt,
468    plan: &Plan,
469    local_audience: &str,
470) -> Result<(), ManagementError> {
471    if receipt.schema_version != CONTRACT_VERSION
472        || receipt.audience != local_audience
473        || receipt.bundle_digest != plan.bundle_digest
474        || receipt.plan_digest != digest(plan)?
475        || receipt.accepted_generation != plan.target_generation
476        || !observations_match_plan(receipt, plan)
477    {
478        return Err(ManagementError::ReceiptBindingMismatch);
479    }
480    if receipt.effective_state != derive_effective_state(&receipt.observations) {
481        return Err(ManagementError::ReceiptStateMismatch);
482    }
483    Ok(())
484}
485
486#[derive(Debug, Clone, Copy, PartialEq, Eq)]
487enum Eval {
488    True,
489    False,
490    Unknown,
491    Stale,
492    Invalid,
493    Limit,
494}
495
496fn serialized_len(value: &Value) -> Result<usize, ManagementError> {
497    serde_json::to_vec(value)
498        .map(|bytes| bytes.len())
499        .map_err(|_| ManagementError::Serialization)
500}
501
502fn validate_value_shape(
503    value: &Value,
504    limits: EvaluationLimits,
505    depth: usize,
506    nodes: &mut usize,
507) -> Eval {
508    if depth > limits.expression_depth {
509        return Eval::Limit;
510    }
511    *nodes += 1;
512    if *nodes > limits.ast_nodes_per_rule {
513        return Eval::Limit;
514    }
515    match value {
516        Value::Array(values) => {
517            if values.len() > limits.collection_values {
518                return Eval::Limit;
519            }
520            for item in values {
521                let result = validate_value_shape(item, limits, depth + 1, nodes);
522                if result != Eval::True {
523                    return result;
524                }
525            }
526        }
527        Value::Object(values) => {
528            for item in values.values() {
529                let result = validate_value_shape(item, limits, depth + 1, nodes);
530                if result != Eval::True {
531                    return result;
532                }
533            }
534        }
535        _ => {}
536    }
537    Eval::True
538}
539
540fn validate_context_collections(value: &Value, limit: usize) -> Eval {
541    match value {
542        Value::Array(values) => {
543            if values.len() > limit {
544                return Eval::Limit;
545            }
546            for item in values {
547                let result = validate_context_collections(item, limit);
548                if result != Eval::True {
549                    return result;
550                }
551            }
552        }
553        Value::Object(values) => {
554            for item in values.values() {
555                let result = validate_context_collections(item, limit);
556                if result != Eval::True {
557                    return result;
558                }
559            }
560        }
561        _ => {}
562    }
563    Eval::True
564}
565
566fn resolve_value(
567    value: &Value,
568    rules: &Map<String, Value>,
569    limits: EvaluationLimits,
570    stack: &mut Vec<String>,
571) -> Result<Value, Eval> {
572    if let Some(reference) = value
573        .as_object()
574        .filter(|object| object.len() == 1)
575        .and_then(|object| object.get("ref"))
576        .and_then(Value::as_str)
577    {
578        if stack.iter().any(|item| item == reference) {
579            return Err(Eval::Invalid);
580        }
581        if stack.len() >= limits.reference_depth {
582            return Err(Eval::Limit);
583        }
584        let referenced = rules.get(reference).ok_or(Eval::Invalid)?;
585        stack.push(reference.to_string());
586        let resolved = resolve_value(referenced, rules, limits, stack);
587        stack.pop();
588        return resolved;
589    }
590    match value {
591        Value::Array(values) => values
592            .iter()
593            .map(|item| resolve_value(item, rules, limits, stack))
594            .collect::<Result<Vec<_>, _>>()
595            .map(Value::Array),
596        Value::Object(values) => values
597            .iter()
598            .map(|(key, item)| {
599                resolve_value(item, rules, limits, stack).map(|value| (key.clone(), value))
600            })
601            .collect::<Result<Map<_, _>, _>>()
602            .map(Value::Object),
603        _ => Ok(value.clone()),
604    }
605}
606
607fn prepare_policy(policy: &Value, limits: EvaluationLimits) -> Result<Value, Eval> {
608    let has_rules = policy.get("rules").is_some();
609    let has_entry = policy.get("entry").is_some();
610    if has_rules != has_entry {
611        return Err(Eval::Invalid);
612    }
613    if !has_rules {
614        let mut nodes = 0;
615        let result = validate_value_shape(policy, limits, 0, &mut nodes);
616        return if result == Eval::True {
617            Ok(policy.clone())
618        } else {
619            Err(result)
620        };
621    }
622    let rules = policy
623        .get("rules")
624        .and_then(Value::as_object)
625        .ok_or(Eval::Invalid)?;
626    if rules.len() > limits.rules {
627        return Err(Eval::Limit);
628    }
629    for rule in rules.values() {
630        let mut nodes = 0;
631        let result = validate_value_shape(rule, limits, 0, &mut nodes);
632        if result != Eval::True {
633            return Err(result);
634        }
635    }
636    let entry = policy.get("entry").ok_or(Eval::Invalid)?;
637    let resolved = resolve_value(entry, rules, limits, &mut Vec::new())?;
638    let mut nodes = 0;
639    let result = validate_value_shape(&resolved, limits, 0, &mut nodes);
640    if result == Eval::True {
641        Ok(resolved)
642    } else {
643        Err(result)
644    }
645}
646
647fn validate_policy_inputs(
648    context: &Value,
649    policy: &Value,
650    limits: EvaluationLimits,
651) -> Result<Value, Eval> {
652    if !limits.profile_compliant() {
653        return Err(Eval::Invalid);
654    }
655    if serialized_len(policy).map_err(|_| Eval::Invalid)? > limits.policy_bytes
656        || serialized_len(context).map_err(|_| Eval::Invalid)? > limits.context_bytes
657    {
658        return Err(Eval::Limit);
659    }
660    let context_shape = validate_context_collections(context, limits.collection_values);
661    if context_shape != Eval::True {
662        return Err(context_shape);
663    }
664    prepare_policy(policy, limits)
665}
666
667fn context_value<'a>(context: &'a Value, name: &str) -> Option<&'a Value> {
668    context.as_object()?.get(name)
669}
670
671fn eval_all(
672    items: &[Value],
673    context: &Value,
674    depth: usize,
675    fuel: &mut usize,
676    limits: EvaluationLimits,
677) -> Eval {
678    let mut result = Eval::True;
679    for item in items {
680        match eval_expr(item, context, depth + 1, fuel, limits) {
681            Eval::True => {}
682            Eval::False => result = Eval::False,
683            other => return other,
684        }
685    }
686    result
687}
688
689fn eval_any(
690    items: &[Value],
691    context: &Value,
692    depth: usize,
693    fuel: &mut usize,
694    limits: EvaluationLimits,
695) -> Eval {
696    let mut saw_unknown = false;
697    for item in items {
698        match eval_expr(item, context, depth + 1, fuel, limits) {
699            Eval::True => return Eval::True,
700            Eval::False => {}
701            Eval::Unknown => saw_unknown = true,
702            other => return other,
703        }
704    }
705    if saw_unknown {
706        Eval::Unknown
707    } else {
708        Eval::False
709    }
710}
711
712fn eval_binary(operator: &str, arguments: &[Value], context: &Value) -> Eval {
713    if arguments.len() != 2 {
714        return Eval::Invalid;
715    }
716    let Some(name) = arguments[0].as_str() else {
717        return Eval::Invalid;
718    };
719    let Some(actual) = context_value(context, name) else {
720        return Eval::Unknown;
721    };
722    if actual.is_null() {
723        return Eval::Unknown;
724    }
725    match operator {
726        "eq" => Eval::from(actual == &arguments[1]),
727        "lte" => eval_lte(name, actual, &arguments[1]),
728        "in" => eval_in(actual, &arguments[1]),
729        "contains" => eval_contains(actual, &arguments[1]),
730        _ => Eval::Invalid,
731    }
732}
733
734fn eval_lte(name: &str, actual: &Value, expected: &Value) -> Eval {
735    match (actual.as_f64(), expected.as_f64()) {
736        (Some(left), Some(right)) if left <= right => Eval::True,
737        (Some(_), Some(_)) if name.contains("evidence_age") => Eval::Stale,
738        (Some(_), Some(_)) => Eval::False,
739        _ => Eval::Invalid,
740    }
741}
742
743fn eval_in(actual: &Value, expected: &Value) -> Eval {
744    match expected.as_array() {
745        Some(_) if actual.is_array() || actual.is_object() => Eval::Invalid,
746        Some(values) if values.len() <= MAX_COLLECTION_VALUES => {
747            Eval::from(values.contains(actual))
748        }
749        Some(_) => Eval::Limit,
750        None => Eval::Invalid,
751    }
752}
753
754fn eval_contains(actual: &Value, expected: &Value) -> Eval {
755    match actual.as_array() {
756        Some(values) if values.len() <= MAX_COLLECTION_VALUES => {
757            Eval::from(values.contains(expected))
758        }
759        Some(_) => Eval::Limit,
760        None => Eval::Invalid,
761    }
762}
763
764impl From<bool> for Eval {
765    fn from(value: bool) -> Self {
766        if value {
767            Self::True
768        } else {
769            Self::False
770        }
771    }
772}
773
774fn eval_generated(
775    object: &Map<String, Value>,
776    context: &Value,
777    limits: EvaluationLimits,
778) -> Option<Eval> {
779    if let Some(generated) = object.get("generated_nesting").and_then(Value::as_u64) {
780        return Some(if generated as usize > limits.expression_depth {
781            Eval::Limit
782        } else {
783            Eval::True
784        });
785    }
786    if object.contains_key("all_values_must_be_true") {
787        let size = context
788            .get("generated_collection_size")
789            .and_then(Value::as_u64)
790            .unwrap_or_default() as usize;
791        return Some(if size > limits.collection_values {
792            Eval::Limit
793        } else {
794            Eval::True
795        });
796    }
797    object
798        .contains_key("evaluate_generated_operations")
799        .then(|| {
800            let operations = context
801                .get("generated_operations")
802                .and_then(Value::as_u64)
803                .unwrap_or_default() as usize;
804            if operations > limits.fuel {
805                Eval::Limit
806            } else {
807                Eval::True
808            }
809        })
810}
811
812fn eval_compound(
813    object: &Map<String, Value>,
814    context: &Value,
815    depth: usize,
816    fuel: &mut usize,
817    limits: EvaluationLimits,
818) -> Option<Eval> {
819    if let Some(items) = object.get("all").and_then(Value::as_array) {
820        return Some(eval_all(items, context, depth, fuel, limits));
821    }
822    object
823        .get("any")
824        .and_then(Value::as_array)
825        .map(|items| eval_any(items, context, depth, fuel, limits))
826}
827
828fn eval_known_binary(object: &Map<String, Value>, context: &Value) -> Option<Eval> {
829    ["eq", "lte", "in", "contains"].iter().find_map(|operator| {
830        object
831            .get(*operator)
832            .and_then(Value::as_array)
833            .map(|arguments| eval_binary(operator, arguments, context))
834    })
835}
836
837fn eval_expr(
838    expr: &Value,
839    context: &Value,
840    depth: usize,
841    fuel: &mut usize,
842    limits: EvaluationLimits,
843) -> Eval {
844    if depth > limits.expression_depth || *fuel == 0 {
845        return Eval::Limit;
846    }
847    *fuel -= 1;
848    let Some(object) = expr.as_object() else {
849        return Eval::Invalid;
850    };
851    if let Some(result) = eval_generated(object, context, limits) {
852        return result;
853    }
854    if let Some(result) = eval_compound(object, context, depth, fuel, limits) {
855        return result;
856    }
857    eval_known_binary(object, context).unwrap_or(Eval::Invalid)
858}
859
860fn evaluate_adapter(context: &Value, policy: &Value) -> Option<(Eval, &'static str)> {
861    policy.get("require_adapter_allow")?;
862    Some(
863        if context.get("adapter_result").and_then(Value::as_str) == Some("allow") {
864            (Eval::True, "IICP-POLICY-ALLOW")
865        } else {
866            (Eval::Invalid, "IICP-POLICY-ADAPTER-ERROR")
867        },
868    )
869}
870
871fn evaluate_evidence_time(context: &Value, policy: &Value) -> Option<Eval> {
872    policy.get("evidence_valid_at")?;
873    Some(
874        match (
875            context.get("evaluated_at").and_then(Value::as_str),
876            context.get("evidence_expires_at").and_then(Value::as_str),
877        ) {
878            (Some(now), Some(expires)) if now <= expires => Eval::True,
879            (Some(_), Some(_)) => Eval::Stale,
880            _ => Eval::Unknown,
881        },
882    )
883}
884
885fn apply_authority_denied(context: &Value, policy: &Value) -> bool {
886    policy.get("action").and_then(Value::as_str) == Some("apply")
887        && policy.get("requires_authority").and_then(Value::as_bool) == Some(true)
888        && context.get("apply_authority").and_then(Value::as_bool) != Some(true)
889}
890
891fn evaluate_allow_deny(context: &Value, policy: &Value, limits: EvaluationLimits) -> Option<Eval> {
892    let (allow, deny) = (policy.get("allow")?, policy.get("deny")?);
893    let mut fuel = limits.fuel;
894    match eval_expr(deny, context, 0, &mut fuel, limits) {
895        Eval::True => Some(Eval::False),
896        Eval::False => Some(eval_expr(allow, context, 0, &mut fuel, limits)),
897        other => Some(other),
898    }
899}
900
901fn explicit_deny_matches(context: &Value, policy: &Value, limits: EvaluationLimits) -> bool {
902    let Some(deny) = policy.get("deny") else {
903        return false;
904    };
905    let mut fuel = limits.fuel;
906    eval_expr(deny, context, 0, &mut fuel, limits) == Eval::True
907}
908
909fn preflight_policy(
910    context: &Value,
911    policy: &Value,
912    limits: EvaluationLimits,
913) -> Option<(PolicyDecision, &'static str)> {
914    if let Some((result, reason)) = evaluate_adapter(context, policy) {
915        let decision = if result == Eval::True {
916            PolicyDecision::Allow
917        } else {
918            PolicyDecision::Indeterminate
919        };
920        return Some((decision, reason));
921    }
922    if apply_authority_denied(context, policy) {
923        return Some((PolicyDecision::Deny, "IICP-POLICY-AUTHORITY-DENIED"));
924    }
925    if policy.get("allow").is_some() && explicit_deny_matches(context, policy, limits) {
926        return Some((PolicyDecision::Deny, "IICP-POLICY-EXPLICIT-DENY"));
927    }
928    None
929}
930
931fn evaluate_policy_body(context: &Value, policy: &Value, limits: EvaluationLimits) -> Eval {
932    if let Some(result) = evaluate_evidence_time(context, policy) {
933        return result;
934    }
935    if let Some(result) = evaluate_allow_deny(context, policy, limits) {
936        return result;
937    }
938    let mut fuel = limits.fuel;
939    eval_expr(policy, context, 0, &mut fuel, limits)
940}
941
942fn eval_disposition(result: Eval) -> (PolicyDecision, &'static str) {
943    match result {
944        Eval::True => (PolicyDecision::Allow, "IICP-POLICY-ALLOW"),
945        Eval::False => (PolicyDecision::Deny, "IICP-POLICY-DEFAULT-DENY"),
946        Eval::Unknown => (
947            PolicyDecision::Indeterminate,
948            "IICP-POLICY-EVIDENCE-UNKNOWN",
949        ),
950        Eval::Stale => (PolicyDecision::Deny, "IICP-POLICY-EVIDENCE-STALE"),
951        Eval::Invalid => (PolicyDecision::Indeterminate, "IICP-POLICY-INPUT-INVALID"),
952        Eval::Limit => (PolicyDecision::Indeterminate, "IICP-POLICY-LIMIT-EXCEEDED"),
953    }
954}
955
956pub fn evaluate_policy(context: &Value, policy: &Value) -> Result<PolicyResult, ManagementError> {
957    evaluate_policy_with_limits(context, policy, EvaluationLimits::default())
958}
959
960pub fn evaluate_policy_with_limits(
961    context: &Value,
962    policy: &Value,
963    limits: EvaluationLimits,
964) -> Result<PolicyResult, ManagementError> {
965    let started = Instant::now();
966    let input_digest = digest(context)?;
967    let policy_digest = digest(policy)?;
968    let prepared = match validate_policy_inputs(context, policy, limits) {
969        Ok(prepared) => prepared,
970        Err(result) => {
971            let (decision, reason) = eval_disposition(result);
972            return Ok(policy_result(decision, reason, input_digest, policy_digest));
973        }
974    };
975    if let Some((decision, reason)) = preflight_policy(context, &prepared, limits) {
976        return Ok(policy_result(decision, reason, input_digest, policy_digest));
977    }
978    let evaluated = evaluate_policy_body(context, &prepared, limits);
979    let result = if started.elapsed() > limits.wall_clock {
980        Eval::Limit
981    } else {
982        evaluated
983    };
984    let (decision, reason) = eval_disposition(result);
985    Ok(policy_result(decision, reason, input_digest, policy_digest))
986}
987
988fn policy_result(
989    decision: PolicyDecision,
990    reason: &str,
991    input_digest: String,
992    policy_digest: String,
993) -> PolicyResult {
994    PolicyResult {
995        decision,
996        reason_codes: vec![reason.to_string()],
997        input_digest,
998        policy_digest,
999        evaluator_profile: POLICY_PROFILE.to_string(),
1000    }
1001}
1002
1003pub mod completion;