Skip to main content

rustmaninoff_engine/
eval.rs

1//! Attribute condition evaluation.
2
3use rustmaninoff_ir::{lookup_path, AttrPath, Value};
4
5use crate::policy::{yaml_to_value, Severity};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum Missing {
9    Pass,
10    Fail,
11    Unknown,
12}
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum Operator {
16    Equals,
17    NotEquals,
18    EqualsAny,
19    Exists,
20    NotExists,
21    Contains,
22    NotContains,
23    Within,
24    NotWithin,
25    RegexMatch,
26    NotRegexMatch,
27    StartingWith,
28    NotStartingWith,
29    EndingWith,
30    NotEndingWith,
31    GreaterThan,
32    GreaterThanOrEqual,
33    LessThan,
34    LessThanOrEqual,
35    IsEmpty,
36    IsNotEmpty,
37    IsTrue,
38    IsFalse,
39    LengthEquals,
40    LengthGreaterThan,
41    LengthGreaterThanOrEqual,
42    LengthLessThan,
43    LengthLessThanOrEqual,
44    Intersects,
45    NotIntersects,
46    Any,
47    ImageTagPinned,
48}
49
50impl Operator {
51    pub fn parse(text: &str) -> Option<Self> {
52        let normalized = text.trim().to_ascii_lowercase().replace([' ', '-'], "_");
53        Some(match normalized.as_str() {
54            "equals" | "eq" => Self::Equals,
55            "not_equals" | "not_eq" => Self::NotEquals,
56            "equals_any" | "any_equals" => Self::EqualsAny,
57            "exists" => Self::Exists,
58            "not_exists" | "notexists" => Self::NotExists,
59            "contains" => Self::Contains,
60            "not_contains" => Self::NotContains,
61            "within" => Self::Within,
62            "not_within" => Self::NotWithin,
63            "regex_match" => Self::RegexMatch,
64            "not_regex_match" => Self::NotRegexMatch,
65            "starting_with" => Self::StartingWith,
66            "not_starting_with" => Self::NotStartingWith,
67            "ending_with" => Self::EndingWith,
68            "not_ending_with" => Self::NotEndingWith,
69            "greater_than" => Self::GreaterThan,
70            "greater_than_or_equal" => Self::GreaterThanOrEqual,
71            "less_than" => Self::LessThan,
72            "less_than_or_equal" => Self::LessThanOrEqual,
73            "is_empty" => Self::IsEmpty,
74            "is_not_empty" => Self::IsNotEmpty,
75            "is_true" => Self::IsTrue,
76            "is_false" => Self::IsFalse,
77            "length_equals" => Self::LengthEquals,
78            "length_greater_than" => Self::LengthGreaterThan,
79            "length_greater_than_or_equal" => Self::LengthGreaterThanOrEqual,
80            "length_less_than" => Self::LengthLessThan,
81            "length_less_than_or_equal" => Self::LengthLessThanOrEqual,
82            "intersects" => Self::Intersects,
83            "not_intersects" => Self::NotIntersects,
84            "any" => Self::Any,
85            "image_tag_pinned" => Self::ImageTagPinned,
86            _ => return None,
87        })
88    }
89
90    fn default_missing(self) -> Missing {
91        match self {
92            Self::NotEquals
93            | Self::NotExists
94            | Self::NotContains
95            | Self::NotWithin
96            | Self::NotRegexMatch
97            | Self::NotStartingWith
98            | Self::NotEndingWith
99            | Self::NotIntersects
100            | Self::IsEmpty => Missing::Pass,
101            _ => Missing::Fail,
102        }
103    }
104}
105
106#[derive(Clone, Debug)]
107pub enum Cond {
108    Attribute {
109        path: AttrPath,
110        operator: Operator,
111        value: Option<Value>,
112        missing: Option<Missing>,
113        regex: Option<regex::Regex>,
114    },
115    And(Vec<Cond>),
116    Or(Vec<Cond>),
117    Not(Box<Cond>),
118    NoElement {
119        path: AttrPath,
120        where_cond: Box<Cond>,
121    },
122    ForbidResource,
123}
124
125impl Cond {
126    pub fn from_yaml(value: &serde_yaml::Value) -> Result<Self, String> {
127        let map = value
128            .as_mapping()
129            .ok_or_else(|| "condition must be a mapping".to_string())?;
130        if let Some(items) = mapping_get(map, "and") {
131            return Ok(Self::And(parse_list(items)?));
132        }
133        if let Some(items) = mapping_get(map, "or") {
134            return Ok(Self::Or(parse_list(items)?));
135        }
136        if let Some(item) = mapping_get(map, "not") {
137            return Ok(Self::Not(Box::new(Self::from_yaml(item)?)));
138        }
139        let kind = mapping_get(map, "cond_type")
140            .and_then(|item| item.as_str())
141            .unwrap_or("attribute");
142        match kind {
143            "attribute" => {
144                let attribute = required_string(map, "attribute")?;
145                let operator = Operator::parse(&required_string(map, "operator")?)
146                    .ok_or_else(|| format!("unknown operator on attribute {attribute}"))?;
147                let value = mapping_get(map, "value").map(yaml_to_value);
148                let missing = mapping_get(map, "missing")
149                    .and_then(|item| item.as_str())
150                    .map(parse_missing)
151                    .transpose()?;
152                let regex = if matches!(operator, Operator::RegexMatch | Operator::NotRegexMatch) {
153                    value
154                        .as_ref()
155                        .and_then(Value::as_str)
156                        .and_then(compile_pattern)
157                } else {
158                    None
159                };
160                Ok(Self::Attribute {
161                    path: AttrPath::parse(&attribute),
162                    operator,
163                    value,
164                    missing,
165                    regex,
166                })
167            }
168            "no_element" => {
169                let attribute = required_string(map, "attribute")?;
170                let where_value = mapping_get(map, "where")
171                    .ok_or_else(|| format!("no_element {attribute} is missing where"))?;
172                Ok(Self::NoElement {
173                    path: AttrPath::parse(&attribute),
174                    where_cond: Box::new(Self::from_yaml(where_value)?),
175                })
176            }
177            "forbid_resource" => Ok(Self::ForbidResource),
178            other => Err(format!("unsupported cond_type '{other}'")),
179        }
180    }
181}
182
183fn parse_missing(text: &str) -> Result<Missing, String> {
184    match text.trim().to_ascii_lowercase().as_str() {
185        "pass" => Ok(Missing::Pass),
186        "fail" => Ok(Missing::Fail),
187        "unknown" => Ok(Missing::Unknown),
188        other => Err(format!("unknown missing behavior '{other}'")),
189    }
190}
191
192fn parse_list(value: &serde_yaml::Value) -> Result<Vec<Cond>, String> {
193    let items = value
194        .as_sequence()
195        .ok_or_else(|| "logical operator expects a list".to_string())?;
196    items.iter().map(Cond::from_yaml).collect()
197}
198
199fn mapping_get<'a>(map: &'a serde_yaml::Mapping, key: &str) -> Option<&'a serde_yaml::Value> {
200    map.iter()
201        .find(|(candidate, _)| candidate.as_str() == Some(key))
202        .map(|(_, value)| value)
203}
204
205fn compile_pattern(pattern: &str) -> Option<regex::Regex> {
206    if pattern.len() > 1_024 {
207        return None;
208    }
209    regex::RegexBuilder::new(pattern)
210        .size_limit(1 << 20)
211        .dfa_size_limit(1 << 20)
212        .nest_limit(32)
213        .build()
214        .ok()
215}
216
217fn required_string(map: &serde_yaml::Mapping, key: &str) -> Result<String, String> {
218    mapping_get(map, key)
219        .and_then(|value| value.as_str())
220        .map(str::to_string)
221        .ok_or_else(|| format!("missing string field '{key}'"))
222}
223
224#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
225pub enum Status {
226    Passed = 0,
227    Skipped = 1,
228    Unknown = 2,
229    Failed = 3,
230}
231
232pub fn eval_cond(cond: &Cond, root: &Value) -> Status {
233    match cond {
234        Cond::Attribute {
235            path,
236            operator,
237            value,
238            missing,
239            regex,
240        } => eval_attribute(
241            root,
242            path,
243            *operator,
244            value.as_ref(),
245            *missing,
246            regex.as_ref(),
247        ),
248        Cond::And(items) => items.iter().map(|item| eval_cond(item, root)).fold(
249            Status::Passed,
250            |acc, status| match (acc, status) {
251                (Status::Failed, _) | (_, Status::Failed) => Status::Failed,
252                (Status::Unknown, _) | (_, Status::Unknown) => Status::Unknown,
253                _ => Status::Passed,
254            },
255        ),
256        Cond::Or(items) => items.iter().map(|item| eval_cond(item, root)).fold(
257            Status::Failed,
258            |acc, status| match (acc, status) {
259                (Status::Passed, _) | (_, Status::Passed) => Status::Passed,
260                (Status::Unknown, _) | (_, Status::Unknown) => Status::Unknown,
261                _ => Status::Failed,
262            },
263        ),
264        Cond::Not(inner) => match eval_cond(inner, root) {
265            Status::Passed => Status::Failed,
266            Status::Failed => Status::Passed,
267            other => other,
268        },
269        Cond::NoElement { path, where_cond } => eval_no_element(root, path, where_cond),
270        Cond::ForbidResource => Status::Failed,
271    }
272}
273
274fn eval_no_element(root: &Value, path: &AttrPath, where_cond: &Cond) -> Status {
275    let resolved = lookup_path(root, path);
276    if resolved.values.is_empty() {
277        return if resolved.unknown {
278            Status::Unknown
279        } else {
280            Status::Passed
281        };
282    }
283    let mut unknown = resolved.unknown;
284    for value in elements_of(&resolved.values) {
285        if matches!(value, Value::Unknown { .. }) {
286            unknown = true;
287            continue;
288        }
289        match eval_cond(where_cond, value) {
290            Status::Passed => return Status::Failed,
291            Status::Unknown => unknown = true,
292            Status::Failed | Status::Skipped => {}
293        }
294    }
295    if unknown {
296        Status::Unknown
297    } else {
298        Status::Passed
299    }
300}
301
302fn elements_of<'a>(values: &[&'a Value]) -> Vec<&'a Value> {
303    if values.len() == 1 {
304        if let Value::Array(items) = values[0] {
305            return items.iter().collect();
306        }
307        if let Value::Object(map) = values[0] {
308            return map.values().collect();
309        }
310    }
311    values.to_vec()
312}
313
314fn eval_attribute(
315    root: &Value,
316    path: &AttrPath,
317    operator: Operator,
318    expected: Option<&Value>,
319    missing_override: Option<Missing>,
320    regex: Option<&regex::Regex>,
321) -> Status {
322    let resolved = lookup_path(root, path);
323    let missing_behavior = missing_override.unwrap_or_else(|| operator.default_missing());
324    if operator == Operator::Exists {
325        return exists_status(&resolved, missing_behavior);
326    }
327    if operator == Operator::NotExists {
328        return match exists_status(&resolved, Missing::Fail) {
329            Status::Passed => Status::Failed,
330            Status::Failed => Status::Passed,
331            other => other,
332        };
333    }
334    if resolved.unknown && resolved.values.is_empty() {
335        return Status::Unknown;
336    }
337    if resolved.values.is_empty() {
338        return missing_to_status(missing_behavior);
339    }
340
341    let mut saw_unknown = resolved.unknown;
342    let mut saw_value = false;
343    for value in &resolved.values {
344        if matches!(value, Value::Unknown { .. }) {
345            saw_unknown = true;
346            continue;
347        }
348        saw_value = true;
349        let matched = leaf_matches(operator, value, expected, regex);
350        let all = !matches!(operator, Operator::EqualsAny | Operator::Intersects);
351        if all && !matched {
352            return Status::Failed;
353        }
354        if !all && matched {
355            return Status::Passed;
356        }
357    }
358    if !saw_value {
359        return if saw_unknown {
360            Status::Unknown
361        } else {
362            missing_to_status(missing_behavior)
363        };
364    }
365    if matches!(operator, Operator::EqualsAny | Operator::Intersects) {
366        return if saw_unknown {
367            Status::Unknown
368        } else {
369            Status::Failed
370        };
371    }
372    if saw_unknown {
373        return Status::Unknown;
374    }
375    if resolved.missing {
376        return missing_to_status(missing_behavior);
377    }
378    Status::Passed
379}
380
381fn exists_status(resolved: &rustmaninoff_ir::Resolved<'_>, missing: Missing) -> Status {
382    let present = resolved.values.iter().any(|value| !value.is_null());
383    if present && resolved.unknown {
384        return Status::Unknown;
385    }
386    if present {
387        return Status::Passed;
388    }
389    if resolved.unknown {
390        return Status::Unknown;
391    }
392    missing_to_status(missing)
393}
394
395fn missing_to_status(missing: Missing) -> Status {
396    match missing {
397        Missing::Pass => Status::Passed,
398        Missing::Fail => Status::Failed,
399        Missing::Unknown => Status::Unknown,
400    }
401}
402
403fn leaf_matches(
404    operator: Operator,
405    value: &Value,
406    expected: Option<&Value>,
407    regex: Option<&regex::Regex>,
408) -> bool {
409    match operator {
410        Operator::Equals => values_equal(value, expected.unwrap_or(&Value::Null)),
411        Operator::NotEquals => !values_equal(value, expected.unwrap_or(&Value::Null)),
412        Operator::EqualsAny => any_equals(value, expected.unwrap_or(&Value::Null)),
413        Operator::Contains => contains(value, expected.unwrap_or(&Value::Null)),
414        Operator::NotContains => !contains(value, expected.unwrap_or(&Value::Null)),
415        Operator::Within => within(value, expected),
416        Operator::NotWithin => !within(value, expected),
417        Operator::RegexMatch => regex_match(value, regex, true),
418        Operator::NotRegexMatch => regex_match(value, regex, false),
419        Operator::StartingWith => string_affix(value, expected, true, true),
420        Operator::NotStartingWith => string_affix(value, expected, true, false),
421        Operator::EndingWith => string_affix(value, expected, false, true),
422        Operator::NotEndingWith => string_affix(value, expected, false, false),
423        Operator::GreaterThan => numeric_cmp(value, expected, |left, right| left > right),
424        Operator::GreaterThanOrEqual => numeric_cmp(value, expected, |left, right| left >= right),
425        Operator::LessThan => numeric_cmp(value, expected, |left, right| left < right),
426        Operator::LessThanOrEqual => numeric_cmp(value, expected, |left, right| left <= right),
427        Operator::IsEmpty => is_empty(value),
428        Operator::IsNotEmpty => !is_empty(value),
429        Operator::IsTrue => is_bool(value, true),
430        Operator::IsFalse => is_bool(value, false),
431        Operator::LengthEquals => length_cmp(value, expected, |left, right| left == right),
432        Operator::LengthGreaterThan => length_cmp(value, expected, |left, right| left > right),
433        Operator::LengthGreaterThanOrEqual => {
434            length_cmp(value, expected, |left, right| left >= right)
435        }
436        Operator::LengthLessThan => length_cmp(value, expected, |left, right| left < right),
437        Operator::LengthLessThanOrEqual => length_cmp(value, expected, |left, right| left <= right),
438        Operator::Intersects => intersects(value, expected),
439        Operator::NotIntersects => !intersects(value, expected),
440        Operator::Any => !matches!(value, Value::Null | Value::Unknown { .. }),
441        Operator::ImageTagPinned => image_tag_pinned(value),
442        Operator::Exists | Operator::NotExists => false,
443    }
444}
445
446fn values_equal(left: &Value, right: &Value) -> bool {
447    match (unwrap_single(left), unwrap_single(right)) {
448        (Value::Number(a), Value::Number(b)) => a.as_f64() == b.as_f64() && a.as_f64().is_some(),
449        (Value::String(a), Value::Bool(b)) => {
450            a.eq_ignore_ascii_case(if *b { "true" } else { "false" })
451        }
452        (Value::Bool(a), Value::String(b)) => {
453            b.eq_ignore_ascii_case(if *a { "true" } else { "false" })
454        }
455        (Value::String(a), Value::Number(b)) => a.parse::<f64>().ok() == b.as_f64(),
456        (Value::Number(a), Value::String(b)) => b.parse::<f64>().ok() == a.as_f64(),
457        (a, b) => a == b,
458    }
459}
460
461fn unwrap_single(value: &Value) -> &Value {
462    match value {
463        Value::Array(items) if items.len() == 1 => &items[0],
464        other => other,
465    }
466}
467
468fn any_equals(value: &Value, expected: &Value) -> bool {
469    match value {
470        Value::Array(items) => items.iter().any(|item| any_equals(item, expected)),
471        other => values_equal(other, expected),
472    }
473}
474
475fn contains(value: &Value, expected: &Value) -> bool {
476    match unwrap_single(value) {
477        Value::String(text) => expected
478            .as_str()
479            .map(|needle| text.contains(needle))
480            .unwrap_or(false),
481        Value::Array(items) => items.iter().any(|item| {
482            values_equal(item, expected)
483                || contains(item, expected) && !matches!(item, Value::String(_))
484        }),
485        other => values_equal(other, expected),
486    }
487}
488
489fn within(value: &Value, expected: Option<&Value>) -> bool {
490    let Some(expected) = expected else {
491        return false;
492    };
493    let candidates: Vec<&Value> = match expected {
494        Value::Array(items) => items.iter().collect(),
495        other => vec![other],
496    };
497    match unwrap_single(value) {
498        Value::Array(items) => items.iter().all(|item| {
499            candidates
500                .iter()
501                .any(|candidate| values_equal(item, candidate))
502        }),
503        other => candidates
504            .iter()
505            .any(|candidate| values_equal(other, candidate)),
506    }
507}
508
509fn regex_match(value: &Value, regex: Option<&regex::Regex>, positive: bool) -> bool {
510    let Some(regex) = regex else {
511        return !positive;
512    };
513    let matched = match unwrap_single(value) {
514        Value::String(text) => regex.is_match(text),
515        Value::Array(items) => items.iter().all(|item| {
516            item.as_str()
517                .map(|text| regex.is_match(text))
518                .unwrap_or(false)
519        }),
520        _ => false,
521    };
522    if positive {
523        matched
524    } else {
525        !matched
526    }
527}
528
529fn string_affix(value: &Value, expected: Option<&Value>, prefix: bool, positive: bool) -> bool {
530    let Some(needle) = expected.and_then(Value::as_str) else {
531        return !positive;
532    };
533    let matched = match unwrap_single(value) {
534        Value::String(text) => {
535            if prefix {
536                text.starts_with(needle)
537            } else {
538                text.ends_with(needle)
539            }
540        }
541        _ => false,
542    };
543    if positive {
544        matched
545    } else {
546        !matched
547    }
548}
549
550fn numeric_cmp(value: &Value, expected: Option<&Value>, cmp: impl Fn(f64, f64) -> bool) -> bool {
551    let Some(right) = expected.and_then(Value::as_f64) else {
552        return false;
553    };
554    unwrap_single(value)
555        .as_f64()
556        .map(|left| cmp(left, right))
557        .unwrap_or(false)
558}
559
560fn is_empty(value: &Value) -> bool {
561    match unwrap_single(value) {
562        Value::Null => true,
563        Value::String(text) => text.is_empty(),
564        Value::Array(items) => items.is_empty(),
565        Value::Object(map) => map.is_empty(),
566        _ => false,
567    }
568}
569
570fn is_bool(value: &Value, expected: bool) -> bool {
571    match unwrap_single(value) {
572        Value::Bool(value) => *value == expected,
573        Value::String(text) => text.eq_ignore_ascii_case(if expected { "true" } else { "false" }),
574        _ => false,
575    }
576}
577
578fn length_of(value: &Value) -> Option<f64> {
579    match unwrap_single(value) {
580        Value::String(text) => Some(text.chars().count() as f64),
581        Value::Array(items) => Some(items.len() as f64),
582        Value::Object(map) => Some(map.len() as f64),
583        _ => None,
584    }
585}
586
587fn length_cmp(value: &Value, expected: Option<&Value>, cmp: impl Fn(f64, f64) -> bool) -> bool {
588    let Some(right) = expected.and_then(Value::as_f64) else {
589        return false;
590    };
591    length_of(value)
592        .map(|left| cmp(left, right))
593        .unwrap_or(false)
594}
595
596fn intersects(value: &Value, expected: Option<&Value>) -> bool {
597    let mut haystack = Vec::new();
598    collect_strings(value, &mut haystack);
599    if haystack.iter().any(|item| item == "*" || item == "*:*") {
600        return expected.is_some();
601    }
602    let Some(expected) = expected else {
603        return false;
604    };
605    let mut needles = Vec::new();
606    collect_strings(expected, &mut needles);
607    haystack
608        .iter()
609        .any(|item| needles.iter().any(|needle| item == needle))
610}
611
612fn collect_strings(value: &Value, out: &mut Vec<String>) {
613    match value {
614        Value::String(text) => out.push(text.clone()),
615        Value::Number(number) => out.push(number.to_string()),
616        Value::Bool(value) => out.push(value.to_string()),
617        Value::Array(items) => {
618            for item in items {
619                collect_strings(item, out);
620            }
621        }
622        _ => {}
623    }
624}
625
626fn image_tag_pinned(value: &Value) -> bool {
627    let Some(image) = unwrap_single(value).as_str() else {
628        return false;
629    };
630    if image.eq_ignore_ascii_case("scratch") {
631        return true;
632    }
633    if image.contains('@') {
634        return true;
635    }
636    let name = image.rsplit('/').next().unwrap_or(image);
637    match name.rsplit_once(':') {
638        Some((_, tag)) => !tag.is_empty() && !tag.eq_ignore_ascii_case("latest"),
639        None => false,
640    }
641}
642
643#[derive(Clone, Debug, PartialEq, Eq)]
644pub struct Finding {
645    pub check_id: std::sync::Arc<str>,
646    pub check_name: std::sync::Arc<str>,
647    pub category: std::sync::Arc<str>,
648    pub severity: Severity,
649    pub status: Status,
650    pub resource_address: std::sync::Arc<str>,
651    pub resource_type: std::sync::Arc<str>,
652    pub resource_name: std::sync::Arc<str>,
653    pub framework: std::sync::Arc<str>,
654    pub file: std::sync::Arc<str>,
655    pub start_line: usize,
656    pub end_line: usize,
657    pub guidelines: Option<std::sync::Arc<str>>,
658    pub skip_reason: Option<String>,
659}