Skip to main content

rustmaninoff_engine/
eval.rs

1//! Attribute condition evaluation.
2
3use rustmaninoff_ir::{lookup_path, AttrPath, EdgeKind, 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    Unique,
49}
50
51impl Operator {
52    pub fn parse(text: &str) -> Option<Self> {
53        let normalized = text.trim().to_ascii_lowercase().replace([' ', '-'], "_");
54        Some(match normalized.as_str() {
55            "equals" | "eq" => Self::Equals,
56            "not_equals" | "not_eq" => Self::NotEquals,
57            "equals_any" | "any_equals" => Self::EqualsAny,
58            "exists" => Self::Exists,
59            "not_exists" | "notexists" => Self::NotExists,
60            "contains" => Self::Contains,
61            "not_contains" => Self::NotContains,
62            "within" => Self::Within,
63            "not_within" => Self::NotWithin,
64            "regex_match" => Self::RegexMatch,
65            "not_regex_match" => Self::NotRegexMatch,
66            "starting_with" => Self::StartingWith,
67            "not_starting_with" => Self::NotStartingWith,
68            "ending_with" => Self::EndingWith,
69            "not_ending_with" => Self::NotEndingWith,
70            "greater_than" => Self::GreaterThan,
71            "greater_than_or_equal" => Self::GreaterThanOrEqual,
72            "less_than" => Self::LessThan,
73            "less_than_or_equal" => Self::LessThanOrEqual,
74            "is_empty" => Self::IsEmpty,
75            "is_not_empty" => Self::IsNotEmpty,
76            "is_true" => Self::IsTrue,
77            "is_false" => Self::IsFalse,
78            "length_equals" => Self::LengthEquals,
79            "length_greater_than" => Self::LengthGreaterThan,
80            "length_greater_than_or_equal" => Self::LengthGreaterThanOrEqual,
81            "length_less_than" => Self::LengthLessThan,
82            "length_less_than_or_equal" => Self::LengthLessThanOrEqual,
83            "intersects" => Self::Intersects,
84            "not_intersects" => Self::NotIntersects,
85            "any" => Self::Any,
86            "image_tag_pinned" => Self::ImageTagPinned,
87            "unique" | "is_unique" => Self::Unique,
88            _ => return None,
89        })
90    }
91
92    fn default_missing(self) -> Missing {
93        match self {
94            Self::NotEquals
95            | Self::NotExists
96            | Self::NotContains
97            | Self::NotWithin
98            | Self::NotRegexMatch
99            | Self::NotStartingWith
100            | Self::NotEndingWith
101            | Self::NotIntersects
102            | Self::IsEmpty
103            | Self::Unique => Missing::Pass,
104            _ => Missing::Fail,
105        }
106    }
107}
108
109#[derive(Clone, Debug)]
110pub enum Cond {
111    Attribute {
112        path: AttrPath,
113        operator: Operator,
114        value: Option<Value>,
115        missing: Option<Missing>,
116        regex: Option<regex::Regex>,
117    },
118    And(Vec<Cond>),
119    Or(Vec<Cond>),
120    Not(Box<Cond>),
121    NoElement {
122        path: AttrPath,
123        where_cond: Box<Cond>,
124    },
125    /// Neighbor relationship over IR edges (Checkov-shaped `connection`).
126    Connection {
127        connected_resource_types: Vec<String>,
128        edge_kinds: Vec<EdgeKind>,
129        exists: bool,
130        neighbor_filter: Option<Box<Cond>>,
131    },
132    ForbidResource,
133}
134
135impl Cond {
136    /// True when this condition (or a nested child) needs the resource graph.
137    pub fn needs_graph(&self) -> bool {
138        match self {
139            Self::Connection { .. } => true,
140            Self::And(items) | Self::Or(items) => items.iter().any(Self::needs_graph),
141            Self::Not(inner)
142            | Self::NoElement {
143                where_cond: inner, ..
144            } => inner.needs_graph(),
145            Self::Attribute { .. } | Self::ForbidResource => false,
146        }
147    }
148
149    pub fn from_yaml(value: &serde_yaml::Value) -> Result<Self, String> {
150        let map = value
151            .as_mapping()
152            .ok_or_else(|| "condition must be a mapping".to_string())?;
153        if let Some(items) = mapping_get(map, "and") {
154            return Ok(Self::And(parse_list(items)?));
155        }
156        if let Some(items) = mapping_get(map, "or") {
157            return Ok(Self::Or(parse_list(items)?));
158        }
159        if let Some(item) = mapping_get(map, "not") {
160            return Ok(Self::Not(Box::new(Self::from_yaml(item)?)));
161        }
162        let kind = mapping_get(map, "cond_type")
163            .and_then(|item| item.as_str())
164            .unwrap_or("attribute");
165        match kind {
166            "attribute" | "filter" => {
167                let attribute = required_string(map, "attribute")?;
168                let operator = Operator::parse(&required_string(map, "operator")?)
169                    .ok_or_else(|| format!("unknown operator on attribute {attribute}"))?;
170                let value = mapping_get(map, "value").map(yaml_to_value);
171                let missing = mapping_get(map, "missing")
172                    .and_then(|item| item.as_str())
173                    .map(parse_missing)
174                    .transpose()?;
175                let regex = if matches!(operator, Operator::RegexMatch | Operator::NotRegexMatch) {
176                    value
177                        .as_ref()
178                        .and_then(Value::as_str)
179                        .and_then(compile_pattern)
180                } else {
181                    None
182                };
183                Ok(Self::Attribute {
184                    path: AttrPath::parse(&attribute),
185                    operator,
186                    value,
187                    missing,
188                    regex,
189                })
190            }
191            "no_element" => {
192                let attribute = required_string(map, "attribute")?;
193                let where_value = mapping_get(map, "where")
194                    .ok_or_else(|| format!("no_element {attribute} is missing where"))?;
195                Ok(Self::NoElement {
196                    path: AttrPath::parse(&attribute),
197                    where_cond: Box::new(Self::from_yaml(where_value)?),
198                })
199            }
200            "connection" => {
201                let connected = mapping_get(map, "connected_resource_types")
202                    .map(string_list_value)
203                    .unwrap_or_default();
204                if connected.is_empty() {
205                    return Err("connection requires connected_resource_types".into());
206                }
207                let edge_kinds = mapping_get(map, "edge_kinds")
208                    .map(parse_edge_kinds)
209                    .transpose()?
210                    .unwrap_or_default();
211                let operator = mapping_get(map, "operator")
212                    .and_then(|item| item.as_str())
213                    .unwrap_or("exists");
214                let exists = match operator.trim().to_ascii_lowercase().as_str() {
215                    "exists" => true,
216                    "not_exists" | "does_not_exist" => false,
217                    other => {
218                        return Err(format!(
219                            "connection operator must be exists or not_exists, got '{other}'"
220                        ))
221                    }
222                };
223                let neighbor_filter = mapping_get(map, "attribute_filter")
224                    .or_else(|| mapping_get(map, "filter"))
225                    .map(Self::from_yaml)
226                    .transpose()?
227                    .map(Box::new);
228                Ok(Self::Connection {
229                    connected_resource_types: connected,
230                    edge_kinds,
231                    exists,
232                    neighbor_filter,
233                })
234            }
235            "forbid_resource" => Ok(Self::ForbidResource),
236            other => Err(format!("unsupported cond_type '{other}'")),
237        }
238    }
239}
240
241fn string_list_value(value: &serde_yaml::Value) -> Vec<String> {
242    if let Some(text) = value.as_str() {
243        return vec![text.to_string()];
244    }
245    value
246        .as_sequence()
247        .map(|items| {
248            items
249                .iter()
250                .filter_map(|item| item.as_str().map(str::to_string))
251                .collect()
252        })
253        .unwrap_or_default()
254}
255
256fn parse_edge_kinds(value: &serde_yaml::Value) -> Result<Vec<EdgeKind>, String> {
257    string_list_value(value)
258        .into_iter()
259        .map(|text| EdgeKind::parse(&text).ok_or_else(|| format!("unknown edge kind '{text}'")))
260        .collect()
261}
262
263fn parse_missing(text: &str) -> Result<Missing, String> {
264    match text.trim().to_ascii_lowercase().as_str() {
265        "pass" => Ok(Missing::Pass),
266        "fail" => Ok(Missing::Fail),
267        "unknown" => Ok(Missing::Unknown),
268        other => Err(format!("unknown missing behavior '{other}'")),
269    }
270}
271
272fn parse_list(value: &serde_yaml::Value) -> Result<Vec<Cond>, String> {
273    let items = value
274        .as_sequence()
275        .ok_or_else(|| "logical operator expects a list".to_string())?;
276    items.iter().map(Cond::from_yaml).collect()
277}
278
279fn mapping_get<'a>(map: &'a serde_yaml::Mapping, key: &str) -> Option<&'a serde_yaml::Value> {
280    map.iter()
281        .find(|(candidate, _)| candidate.as_str() == Some(key))
282        .map(|(_, value)| value)
283}
284
285fn compile_pattern(pattern: &str) -> Option<regex::Regex> {
286    if pattern.len() > 1_024 {
287        return None;
288    }
289    regex::RegexBuilder::new(pattern)
290        .size_limit(1 << 20)
291        .dfa_size_limit(1 << 20)
292        .nest_limit(32)
293        .build()
294        .ok()
295}
296
297fn required_string(map: &serde_yaml::Mapping, key: &str) -> Result<String, String> {
298    mapping_get(map, key)
299        .and_then(|value| value.as_str())
300        .map(str::to_string)
301        .ok_or_else(|| format!("missing string field '{key}'"))
302}
303
304#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
305pub enum Status {
306    Passed = 0,
307    Skipped = 1,
308    Unknown = 2,
309    Failed = 3,
310}
311
312pub fn eval_cond(cond: &Cond, root: &Value) -> Status {
313    match cond {
314        Cond::Attribute {
315            path,
316            operator,
317            value,
318            missing,
319            regex,
320        } => eval_attribute(
321            root,
322            path,
323            *operator,
324            value.as_ref(),
325            *missing,
326            regex.as_ref(),
327        ),
328        Cond::And(items) => items.iter().map(|item| eval_cond(item, root)).fold(
329            Status::Passed,
330            |acc, status| match (acc, status) {
331                (Status::Failed, _) | (_, Status::Failed) => Status::Failed,
332                (Status::Unknown, _) | (_, Status::Unknown) => Status::Unknown,
333                _ => Status::Passed,
334            },
335        ),
336        Cond::Or(items) => items.iter().map(|item| eval_cond(item, root)).fold(
337            Status::Failed,
338            |acc, status| match (acc, status) {
339                (Status::Passed, _) | (_, Status::Passed) => Status::Passed,
340                (Status::Unknown, _) | (_, Status::Unknown) => Status::Unknown,
341                _ => Status::Failed,
342            },
343        ),
344        Cond::Not(inner) => match eval_cond(inner, root) {
345            Status::Passed => Status::Failed,
346            Status::Failed => Status::Passed,
347            other => other,
348        },
349        Cond::NoElement { path, where_cond } => eval_no_element(root, path, where_cond),
350        // Graph connections need `eval_graph_cond`; attribute path treats them as unknown.
351        Cond::Connection { .. } => Status::Unknown,
352        Cond::ForbidResource => Status::Failed,
353    }
354}
355
356fn eval_no_element(root: &Value, path: &AttrPath, where_cond: &Cond) -> Status {
357    let resolved = lookup_path(root, path);
358    if resolved.values.is_empty() {
359        return if resolved.unknown {
360            Status::Unknown
361        } else {
362            Status::Passed
363        };
364    }
365    let mut unknown = resolved.unknown;
366    for value in elements_of(&resolved.values) {
367        if matches!(value, Value::Unknown { .. }) {
368            unknown = true;
369            continue;
370        }
371        match eval_cond(where_cond, value) {
372            Status::Passed => return Status::Failed,
373            Status::Unknown => unknown = true,
374            Status::Failed | Status::Skipped => {}
375        }
376    }
377    if unknown {
378        Status::Unknown
379    } else {
380        Status::Passed
381    }
382}
383
384fn elements_of<'a>(values: &[&'a Value]) -> Vec<&'a Value> {
385    if values.len() == 1 {
386        if let Value::Array(items) = values[0] {
387            return items.iter().collect();
388        }
389        if let Value::Object(map) = values[0] {
390            return map.values().collect();
391        }
392    }
393    values.to_vec()
394}
395
396fn eval_attribute(
397    root: &Value,
398    path: &AttrPath,
399    operator: Operator,
400    expected: Option<&Value>,
401    missing_override: Option<Missing>,
402    regex: Option<&regex::Regex>,
403) -> Status {
404    let resolved = lookup_path(root, path);
405    let missing_behavior = missing_override.unwrap_or_else(|| operator.default_missing());
406    if operator == Operator::Exists {
407        return exists_status(&resolved, missing_behavior);
408    }
409    if operator == Operator::NotExists {
410        return match exists_status(&resolved, Missing::Fail) {
411            Status::Passed => Status::Failed,
412            Status::Failed => Status::Passed,
413            other => other,
414        };
415    }
416    if operator == Operator::Unique {
417        return eval_unique(&resolved, missing_behavior);
418    }
419    if resolved.unknown && resolved.values.is_empty() {
420        return Status::Unknown;
421    }
422    if resolved.values.is_empty() {
423        return missing_to_status(missing_behavior);
424    }
425
426    let mut saw_unknown = resolved.unknown;
427    let mut saw_value = false;
428    for value in &resolved.values {
429        if matches!(value, Value::Unknown { .. }) {
430            saw_unknown = true;
431            continue;
432        }
433        saw_value = true;
434        let matched = leaf_matches(operator, value, expected, regex);
435        let all = !matches!(operator, Operator::EqualsAny | Operator::Intersects);
436        if all && !matched {
437            return Status::Failed;
438        }
439        if !all && matched {
440            return Status::Passed;
441        }
442    }
443    if !saw_value {
444        return if saw_unknown {
445            Status::Unknown
446        } else {
447            missing_to_status(missing_behavior)
448        };
449    }
450    if matches!(operator, Operator::EqualsAny | Operator::Intersects) {
451        return if saw_unknown {
452            Status::Unknown
453        } else {
454            Status::Failed
455        };
456    }
457    if saw_unknown {
458        return Status::Unknown;
459    }
460    if resolved.missing {
461        return missing_to_status(missing_behavior);
462    }
463    Status::Passed
464}
465
466fn exists_status(resolved: &rustmaninoff_ir::Resolved<'_>, missing: Missing) -> Status {
467    let present = resolved.values.iter().any(|value| !value.is_null());
468    if present && resolved.unknown {
469        return Status::Unknown;
470    }
471    if present {
472        return Status::Passed;
473    }
474    if resolved.unknown {
475        return Status::Unknown;
476    }
477    missing_to_status(missing)
478}
479
480fn missing_to_status(missing: Missing) -> Status {
481    match missing {
482        Missing::Pass => Status::Passed,
483        Missing::Fail => Status::Failed,
484        Missing::Unknown => Status::Unknown,
485    }
486}
487
488fn leaf_matches(
489    operator: Operator,
490    value: &Value,
491    expected: Option<&Value>,
492    regex: Option<&regex::Regex>,
493) -> bool {
494    match operator {
495        Operator::Equals => values_equal(value, expected.unwrap_or(&Value::Null)),
496        Operator::NotEquals => !values_equal(value, expected.unwrap_or(&Value::Null)),
497        Operator::EqualsAny => any_equals(value, expected.unwrap_or(&Value::Null)),
498        Operator::Contains => contains(value, expected.unwrap_or(&Value::Null)),
499        Operator::NotContains => !contains(value, expected.unwrap_or(&Value::Null)),
500        Operator::Within => within(value, expected),
501        Operator::NotWithin => !within(value, expected),
502        Operator::RegexMatch => regex_match(value, regex, true),
503        Operator::NotRegexMatch => regex_match(value, regex, false),
504        Operator::StartingWith => string_affix(value, expected, true, true),
505        Operator::NotStartingWith => string_affix(value, expected, true, false),
506        Operator::EndingWith => string_affix(value, expected, false, true),
507        Operator::NotEndingWith => string_affix(value, expected, false, false),
508        Operator::GreaterThan => numeric_cmp(value, expected, |left, right| left > right),
509        Operator::GreaterThanOrEqual => numeric_cmp(value, expected, |left, right| left >= right),
510        Operator::LessThan => numeric_cmp(value, expected, |left, right| left < right),
511        Operator::LessThanOrEqual => numeric_cmp(value, expected, |left, right| left <= right),
512        Operator::IsEmpty => is_empty(value),
513        Operator::IsNotEmpty => !is_empty(value),
514        Operator::IsTrue => is_bool(value, true),
515        Operator::IsFalse => is_bool(value, false),
516        Operator::LengthEquals => length_cmp(value, expected, |left, right| left == right),
517        Operator::LengthGreaterThan => length_cmp(value, expected, |left, right| left > right),
518        Operator::LengthGreaterThanOrEqual => {
519            length_cmp(value, expected, |left, right| left >= right)
520        }
521        Operator::LengthLessThan => length_cmp(value, expected, |left, right| left < right),
522        Operator::LengthLessThanOrEqual => length_cmp(value, expected, |left, right| left <= right),
523        Operator::Intersects => intersects(value, expected),
524        Operator::NotIntersects => !intersects(value, expected),
525        Operator::Any => !matches!(value, Value::Null | Value::Unknown { .. }),
526        Operator::ImageTagPinned => image_tag_pinned(value),
527        Operator::Unique | Operator::Exists | Operator::NotExists => false,
528    }
529}
530
531fn eval_unique(resolved: &rustmaninoff_ir::Resolved<'_>, missing: Missing) -> Status {
532    if resolved.values.is_empty() {
533        return missing_to_status(missing);
534    }
535    let mut seen = std::collections::BTreeSet::new();
536    let mut saw_value = false;
537    let mut saw_unknown = resolved.unknown;
538    for value in &resolved.values {
539        if collect_unique_items(value, &mut seen, &mut saw_unknown, &mut saw_value) {
540            return Status::Failed;
541        }
542    }
543    if !saw_value {
544        return if saw_unknown {
545            Status::Unknown
546        } else {
547            missing_to_status(missing)
548        };
549    }
550    if saw_unknown {
551        return Status::Unknown;
552    }
553    Status::Passed
554}
555
556fn collect_unique_items(
557    value: &Value,
558    seen: &mut std::collections::BTreeSet<String>,
559    saw_unknown: &mut bool,
560    saw_value: &mut bool,
561) -> bool {
562    match unwrap_single(value) {
563        Value::Unknown { .. } => {
564            *saw_unknown = true;
565            false
566        }
567        Value::Null => false,
568        Value::Array(items) => {
569            for item in items {
570                if collect_unique_items(item, seen, saw_unknown, saw_value) {
571                    return true;
572                }
573            }
574            false
575        }
576        Value::String(text) => {
577            if text.is_empty() {
578                return false;
579            }
580            *saw_value = true;
581            !seen.insert(text.clone())
582        }
583        other => {
584            *saw_value = true;
585            let key = format!("{other:?}");
586            !seen.insert(key)
587        }
588    }
589}
590
591fn values_equal(left: &Value, right: &Value) -> bool {
592    match (unwrap_single(left), unwrap_single(right)) {
593        (Value::Number(a), Value::Number(b)) => a.as_f64() == b.as_f64() && a.as_f64().is_some(),
594        (Value::String(a), Value::Bool(b)) => {
595            a.eq_ignore_ascii_case(if *b { "true" } else { "false" })
596        }
597        (Value::Bool(a), Value::String(b)) => {
598            b.eq_ignore_ascii_case(if *a { "true" } else { "false" })
599        }
600        (Value::String(a), Value::Number(b)) => a.parse::<f64>().ok() == b.as_f64(),
601        (Value::Number(a), Value::String(b)) => b.parse::<f64>().ok() == a.as_f64(),
602        (a, b) => a == b,
603    }
604}
605
606fn unwrap_single(value: &Value) -> &Value {
607    match value {
608        Value::Array(items) if items.len() == 1 => &items[0],
609        other => other,
610    }
611}
612
613fn any_equals(value: &Value, expected: &Value) -> bool {
614    match value {
615        Value::Array(items) => items.iter().any(|item| any_equals(item, expected)),
616        other => values_equal(other, expected),
617    }
618}
619
620fn contains(value: &Value, expected: &Value) -> bool {
621    match unwrap_single(value) {
622        Value::String(text) => expected
623            .as_str()
624            .map(|needle| text.contains(needle))
625            .unwrap_or(false),
626        Value::Array(items) => items.iter().any(|item| {
627            values_equal(item, expected)
628                || contains(item, expected) && !matches!(item, Value::String(_))
629        }),
630        other => values_equal(other, expected),
631    }
632}
633
634fn within(value: &Value, expected: Option<&Value>) -> bool {
635    let Some(expected) = expected else {
636        return false;
637    };
638    let candidates: Vec<&Value> = match expected {
639        Value::Array(items) => items.iter().collect(),
640        other => vec![other],
641    };
642    match unwrap_single(value) {
643        Value::Array(items) => items.iter().all(|item| {
644            candidates
645                .iter()
646                .any(|candidate| values_equal(item, candidate))
647        }),
648        other => candidates
649            .iter()
650            .any(|candidate| values_equal(other, candidate)),
651    }
652}
653
654fn regex_match(value: &Value, regex: Option<&regex::Regex>, positive: bool) -> bool {
655    let Some(regex) = regex else {
656        return !positive;
657    };
658    let matched = match unwrap_single(value) {
659        Value::String(text) => regex.is_match(text),
660        Value::Array(items) => items.iter().all(|item| {
661            item.as_str()
662                .map(|text| regex.is_match(text))
663                .unwrap_or(false)
664        }),
665        _ => false,
666    };
667    if positive {
668        matched
669    } else {
670        !matched
671    }
672}
673
674fn string_affix(value: &Value, expected: Option<&Value>, prefix: bool, positive: bool) -> bool {
675    let Some(needle) = expected.and_then(Value::as_str) else {
676        return !positive;
677    };
678    let matched = match unwrap_single(value) {
679        Value::String(text) => {
680            if prefix {
681                text.starts_with(needle)
682            } else {
683                text.ends_with(needle)
684            }
685        }
686        _ => false,
687    };
688    if positive {
689        matched
690    } else {
691        !matched
692    }
693}
694
695fn numeric_cmp(value: &Value, expected: Option<&Value>, cmp: impl Fn(f64, f64) -> bool) -> bool {
696    let Some(right) = expected.and_then(Value::as_f64) else {
697        return false;
698    };
699    unwrap_single(value)
700        .as_f64()
701        .map(|left| cmp(left, right))
702        .unwrap_or(false)
703}
704
705fn is_empty(value: &Value) -> bool {
706    match unwrap_single(value) {
707        Value::Null => true,
708        Value::String(text) => text.is_empty(),
709        Value::Array(items) => items.is_empty(),
710        Value::Object(map) => map.is_empty(),
711        _ => false,
712    }
713}
714
715fn is_bool(value: &Value, expected: bool) -> bool {
716    match unwrap_single(value) {
717        Value::Bool(value) => *value == expected,
718        Value::String(text) => text.eq_ignore_ascii_case(if expected { "true" } else { "false" }),
719        _ => false,
720    }
721}
722
723fn length_of(value: &Value) -> Option<f64> {
724    match unwrap_single(value) {
725        Value::String(text) => Some(text.chars().count() as f64),
726        Value::Array(items) => Some(items.len() as f64),
727        Value::Object(map) => Some(map.len() as f64),
728        _ => None,
729    }
730}
731
732fn length_cmp(value: &Value, expected: Option<&Value>, cmp: impl Fn(f64, f64) -> bool) -> bool {
733    let Some(right) = expected.and_then(Value::as_f64) else {
734        return false;
735    };
736    length_of(value)
737        .map(|left| cmp(left, right))
738        .unwrap_or(false)
739}
740
741fn intersects(value: &Value, expected: Option<&Value>) -> bool {
742    let mut haystack = Vec::new();
743    collect_strings(value, &mut haystack);
744    if haystack.iter().any(|item| item == "*" || item == "*:*") {
745        return expected.is_some();
746    }
747    let Some(expected) = expected else {
748        return false;
749    };
750    let mut needles = Vec::new();
751    collect_strings(expected, &mut needles);
752    haystack
753        .iter()
754        .any(|item| needles.iter().any(|needle| item == needle))
755}
756
757fn collect_strings(value: &Value, out: &mut Vec<String>) {
758    match value {
759        Value::String(text) => out.push(text.clone()),
760        Value::Number(number) => out.push(number.to_string()),
761        Value::Bool(value) => out.push(value.to_string()),
762        Value::Array(items) => {
763            for item in items {
764                collect_strings(item, out);
765            }
766        }
767        _ => {}
768    }
769}
770
771fn image_tag_pinned(value: &Value) -> bool {
772    let Some(image) = unwrap_single(value).as_str() else {
773        return false;
774    };
775    if image.eq_ignore_ascii_case("scratch") {
776        return true;
777    }
778    if image.contains('@') {
779        return true;
780    }
781    let name = image.rsplit('/').next().unwrap_or(image);
782    match name.rsplit_once(':') {
783        Some((_, tag)) => !tag.is_empty() && !tag.eq_ignore_ascii_case("latest"),
784        None => false,
785    }
786}
787
788/// Evaluate a condition that may include `connection` nodes against a resource graph.
789pub fn eval_graph_cond(
790    cond: &Cond,
791    resource: &rustmaninoff_ir::Resource,
792    resources: &[rustmaninoff_ir::Resource],
793    edges: &[rustmaninoff_ir::Edge],
794) -> Status {
795    match cond {
796        Cond::And(items) => items
797            .iter()
798            .map(|item| eval_graph_cond(item, resource, resources, edges))
799            .fold(Status::Passed, |acc, status| match (acc, status) {
800                (Status::Failed, _) | (_, Status::Failed) => Status::Failed,
801                (Status::Unknown, _) | (_, Status::Unknown) => Status::Unknown,
802                _ => Status::Passed,
803            }),
804        Cond::Or(items) => items
805            .iter()
806            .map(|item| eval_graph_cond(item, resource, resources, edges))
807            .fold(Status::Failed, |acc, status| match (acc, status) {
808                (Status::Passed, _) | (_, Status::Passed) => Status::Passed,
809                (Status::Unknown, _) | (_, Status::Unknown) => Status::Unknown,
810                _ => Status::Failed,
811            }),
812        Cond::Not(inner) => match eval_graph_cond(inner, resource, resources, edges) {
813            Status::Passed => Status::Failed,
814            Status::Failed => Status::Passed,
815            other => other,
816        },
817        Cond::Connection {
818            connected_resource_types,
819            edge_kinds,
820            exists,
821            neighbor_filter,
822        } => eval_connection(
823            resource,
824            resources,
825            edges,
826            connected_resource_types,
827            edge_kinds,
828            *exists,
829            neighbor_filter.as_deref(),
830        ),
831        other => eval_cond(other, &resource.attributes),
832    }
833}
834
835fn eval_connection(
836    resource: &rustmaninoff_ir::Resource,
837    resources: &[rustmaninoff_ir::Resource],
838    edges: &[rustmaninoff_ir::Edge],
839    connected_types: &[String],
840    edge_kinds: &[EdgeKind],
841    exists: bool,
842    neighbor_filter: Option<&Cond>,
843) -> Status {
844    let from = rustmaninoff_ir::ResourceRef::from_resource(resource);
845    let matched = edges.iter().any(|edge| {
846        if !edge_kinds.is_empty() && !edge_kinds.contains(&edge.kind) {
847            return false;
848        }
849        let neighbor_ref = if edge.from.matches(&from) {
850            &edge.to
851        } else if edge.to.matches(&from) {
852            &edge.from
853        } else {
854            return false;
855        };
856        let Some(neighbor) = find_neighbor(resources, neighbor_ref, connected_types) else {
857            return false;
858        };
859        match neighbor_filter {
860            None => true,
861            Some(filter) => matches!(eval_cond(filter, &neighbor.attributes), Status::Passed),
862        }
863    });
864    match (exists, matched) {
865        (true, true) | (false, false) => Status::Passed,
866        (true, false) | (false, true) => Status::Failed,
867    }
868}
869
870fn find_neighbor<'a>(
871    resources: &'a [rustmaninoff_ir::Resource],
872    neighbor_ref: &rustmaninoff_ir::ResourceRef,
873    connected_types: &[String],
874) -> Option<&'a rustmaninoff_ir::Resource> {
875    let type_ok = |resource_type: &str| {
876        connected_types.iter().any(|allowed| allowed == "*")
877            || connected_types
878                .iter()
879                .any(|allowed| allowed == resource_type)
880    };
881    resources.iter().find(|item| {
882        if !type_ok(&item.resource_type) {
883            return false;
884        }
885        if !neighbor_ref.resource_type.is_empty()
886            && neighbor_ref.resource_type != item.resource_type
887        {
888            return false;
889        }
890        let candidate = rustmaninoff_ir::ResourceRef::from_resource(item);
891        neighbor_ref.matches(&candidate) || neighbor_ref.name == item.name
892    })
893}
894
895#[derive(Clone, Debug, PartialEq, Eq)]
896pub struct Finding {
897    pub check_id: std::sync::Arc<str>,
898    pub check_name: std::sync::Arc<str>,
899    pub category: std::sync::Arc<str>,
900    pub severity: Severity,
901    pub status: Status,
902    pub resource_address: std::sync::Arc<str>,
903    pub resource_type: std::sync::Arc<str>,
904    pub resource_name: std::sync::Arc<str>,
905    pub framework: std::sync::Arc<str>,
906    pub file: std::sync::Arc<str>,
907    pub start_line: usize,
908    pub end_line: usize,
909    pub guidelines: Option<std::sync::Arc<str>>,
910    pub skip_reason: Option<String>,
911}