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