Skip to main content

logicaffeine_compile/semantics/
policy.rs

1//! Security-policy evaluation (`Check …` statements).
2
3use crate::analysis::{PolicyCondition, PolicyRegistry};
4use crate::intern::{Interner, Symbol};
5use crate::interpreter::RuntimeValue;
6
7use super::compare::values_equal;
8
9/// Evaluate one policy condition against a subject (and optional object).
10pub fn evaluate_policy_condition(
11    registry: Option<&PolicyRegistry>,
12    interner: &Interner,
13    condition: &PolicyCondition,
14    subject: &RuntimeValue,
15    object: Option<&RuntimeValue>,
16) -> bool {
17    match condition {
18        PolicyCondition::FieldEquals {
19            field,
20            value,
21            is_string_literal,
22        } => {
23            if let RuntimeValue::Struct(s) = subject {
24                let field_name = interner.resolve(*field);
25                if let Some(field_val) = s.fields.get(field_name) {
26                    let expected = interner.resolve(*value);
27                    match field_val {
28                        RuntimeValue::Text(s) => s.as_str() == expected,
29                        RuntimeValue::Int(n) => {
30                            if *is_string_literal {
31                                false
32                            } else {
33                                expected.parse::<i64>().map(|e| *n == e).unwrap_or(false)
34                            }
35                        }
36                        RuntimeValue::Bool(b) => {
37                            if *is_string_literal {
38                                false
39                            } else {
40                                expected.parse::<bool>().map(|e| *b == e).unwrap_or(false)
41                            }
42                        }
43                        _ => false,
44                    }
45                } else {
46                    false
47                }
48            } else {
49                false
50            }
51        }
52        PolicyCondition::FieldBool { field, value } => {
53            if let RuntimeValue::Struct(s) = subject {
54                let field_name = interner.resolve(*field);
55                if let Some(RuntimeValue::Bool(b)) = s.fields.get(field_name) {
56                    *b == *value
57                } else {
58                    false
59                }
60            } else {
61                false
62            }
63        }
64        PolicyCondition::Predicate { predicate, .. } => {
65            if let Some(registry) = registry {
66                if let RuntimeValue::Struct(s) = subject {
67                    if let Some(subj_type_sym) = interner.lookup(&s.type_name) {
68                        if let Some(preds) = registry.get_predicates(subj_type_sym) {
69                            if let Some(pred) =
70                                preds.iter().find(|p| p.predicate_name == *predicate)
71                            {
72                                return evaluate_policy_condition(
73                                    Some(registry),
74                                    interner,
75                                    &pred.condition,
76                                    subject,
77                                    object,
78                                );
79                            }
80                        }
81                    }
82                }
83            }
84            false
85        }
86        PolicyCondition::ObjectFieldEquals {
87            subject: subj_field,
88            object: obj_sym,
89            field,
90        } => {
91            let obj = match object {
92                Some(o) => o,
93                None => return false,
94            };
95            if let (RuntimeValue::Struct(subj_s), RuntimeValue::Struct(obj_s)) = (subject, obj) {
96                let subj_field_name = interner.resolve(*subj_field);
97                let obj_field_name = interner.resolve(*field);
98                if let (Some(subj_val), Some(obj_val)) = (
99                    subj_s.fields.get(subj_field_name),
100                    obj_s.fields.get(obj_field_name),
101                ) {
102                    values_equal(subj_val, obj_val)
103                } else {
104                    let _obj_sym_name = interner.resolve(*obj_sym);
105                    false
106                }
107            } else {
108                false
109            }
110        }
111        PolicyCondition::SubjectFieldEqualsObjectField {
112            subject_field,
113            object: _,
114            object_field,
115        } => {
116            let obj = match object {
117                Some(o) => o,
118                None => return false,
119            };
120            if let (RuntimeValue::Struct(subj_s), RuntimeValue::Struct(obj_s)) = (subject, obj) {
121                let subj_field_name = interner.resolve(*subject_field);
122                let obj_field_name = interner.resolve(*object_field);
123                if let (Some(a), Some(b)) = (
124                    subj_s.fields.get(subj_field_name),
125                    obj_s.fields.get(obj_field_name),
126                ) {
127                    values_equal(a, b)
128                } else {
129                    false
130                }
131            } else {
132                false
133            }
134        }
135        PolicyCondition::Or(left, right) => {
136            evaluate_policy_condition(registry, interner, left, subject, object)
137                || evaluate_policy_condition(registry, interner, right, subject, object)
138        }
139        PolicyCondition::And(left, right) => {
140            evaluate_policy_condition(registry, interner, left, subject, object)
141                && evaluate_policy_condition(registry, interner, right, subject, object)
142        }
143    }
144}
145
146/// Run a `Check` statement against already-resolved subject/object values.
147/// Every error string lives here — both engines produce the identical text.
148pub fn check_policy(
149    registry: &PolicyRegistry,
150    interner: &Interner,
151    subject: &RuntimeValue,
152    predicate: Symbol,
153    is_capability: bool,
154    object: Option<&RuntimeValue>,
155    source_text: &str,
156) -> Result<(), String> {
157    let subj_type_name = match subject {
158        RuntimeValue::Struct(s) => s.type_name.clone(),
159        _ => {
160            return Err(format!(
161                "Check subject must be a struct, got {}",
162                subject.type_name()
163            ));
164        }
165    };
166
167    let subj_type_sym = match interner.lookup(&subj_type_name) {
168        Some(sym) => sym,
169        None => {
170            return Err(format!(
171                "Unknown type '{}' in Check statement",
172                subj_type_name
173            ));
174        }
175    };
176
177    let passed = if is_capability {
178        let caps = registry.get_capabilities(subj_type_sym);
179        let cap = caps.and_then(|caps| caps.iter().find(|c| c.action == predicate));
180        match cap {
181            Some(cap) => {
182                evaluate_policy_condition(Some(registry), interner, &cap.condition, subject, object)
183            }
184            None => {
185                let pred_name = interner.resolve(predicate);
186                return Err(format!(
187                    "No capability '{}' defined for type '{}'",
188                    pred_name, subj_type_name
189                ));
190            }
191        }
192    } else {
193        let preds = registry.get_predicates(subj_type_sym);
194        let pred_def = preds.and_then(|preds| preds.iter().find(|p| p.predicate_name == predicate));
195        match pred_def {
196            Some(pred) => {
197                evaluate_policy_condition(Some(registry), interner, &pred.condition, subject, None)
198            }
199            None => {
200                return Err(no_predicate(interner.resolve(predicate), &subj_type_name));
201            }
202        }
203    };
204
205    if !passed {
206        return Err(check_failed(source_text));
207    }
208    Ok(())
209}
210
211/// The reason a `Check` in a program with no `## Policy` block stops the program with.
212pub const NO_POLICIES: &str =
213    "Security Check requires policies. Use compiled Rust or add ## Policy block.";
214
215/// The reason a `Check` naming a predicate its subject's type does not define stops the program with.
216pub fn no_predicate(predicate: &str, type_name: &str) -> String {
217    format!("No predicate '{predicate}' defined for type '{type_name}'")
218}
219
220/// The reason a `Check` that does not hold stops the program with — the one wording every tier reports.
221pub fn check_failed(source_text: &str) -> String {
222    format!("Security Check Failed: {source_text}")
223}