Skip to main content

rustmaninoff_engine/
lib.rs

1//! Checkov-compatible attribute policy engine.
2
3mod eval;
4mod policy;
5
6pub use eval::{eval_cond, eval_graph_cond, Cond, Finding, Status};
7pub use policy::{load_policy_dir, parse_policy, Policy, PolicyError, Severity};
8
9use std::collections::{BTreeMap, HashMap};
10use std::sync::Arc;
11
12use rayon::prelude::*;
13use rustmaninoff_ir::{Edge, Framework, Resource};
14
15/// Evaluate attribute policies against `resources`.
16///
17/// Graph (`connection`) policies are skipped here; use [`evaluate_graph`].
18///
19/// Results that share a check id and resource are collapsed to the worst status,
20/// so a security group and its rule form can share one Checkov id.
21pub fn evaluate(resources: &[Resource], policies: &[Policy]) -> Vec<Finding> {
22    if resources.is_empty() || policies.is_empty() {
23        return Vec::new();
24    }
25    let attribute_policies: Vec<&Policy> = policies
26        .iter()
27        .filter(|policy| !policy.definition.needs_graph())
28        .collect();
29    if attribute_policies.is_empty() {
30        return Vec::new();
31    }
32    let index = PolicyIndex::build(&attribute_policies);
33    let findings = if resources.len() < 32 {
34        resources
35            .iter()
36            .flat_map(|resource| eval_resource(resource, &index))
37            .collect()
38    } else {
39        resources
40            .par_iter()
41            .flat_map(|resource| eval_resource(resource, &index))
42            .collect()
43    };
44    collapse(findings)
45}
46
47/// Evaluate graph (`connection`) policies using IR edges.
48pub fn evaluate_graph(resources: &[Resource], edges: &[Edge], policies: &[Policy]) -> Vec<Finding> {
49    if resources.is_empty() || policies.is_empty() {
50        return Vec::new();
51    }
52    let graph_policies: Vec<&Policy> = policies
53        .iter()
54        .filter(|policy| policy.definition.needs_graph())
55        .collect();
56    if graph_policies.is_empty() {
57        return Vec::new();
58    }
59    let index = PolicyIndex::build(&graph_policies);
60    let findings = if resources.len() < 32 {
61        resources
62            .iter()
63            .flat_map(|resource| eval_graph_resource(resource, resources, edges, &index))
64            .collect()
65    } else {
66        resources
67            .par_iter()
68            .flat_map(|resource| eval_graph_resource(resource, resources, edges, &index))
69            .collect()
70    };
71    collapse(findings)
72}
73
74struct PolicyIndex<'a> {
75    exact: HashMap<Framework, HashMap<String, Vec<&'a Policy>>>,
76    wild: HashMap<Framework, Vec<&'a Policy>>,
77    unscoped_exact: HashMap<String, Vec<&'a Policy>>,
78    unscoped_wild: Vec<&'a Policy>,
79}
80
81impl<'a> PolicyIndex<'a> {
82    fn build(policies: &[&'a Policy]) -> Self {
83        let mut index = Self {
84            exact: HashMap::new(),
85            wild: HashMap::new(),
86            unscoped_exact: HashMap::new(),
87            unscoped_wild: Vec::new(),
88        };
89        for policy in policies {
90            let wild = policy
91                .resource_types
92                .iter()
93                .any(|resource_type| resource_type == "*" || resource_type == "all");
94            match policy.framework {
95                Some(framework) => {
96                    if wild {
97                        index.wild.entry(framework).or_default().push(policy);
98                    }
99                    for resource_type in &policy.resource_types {
100                        if resource_type == "*" || resource_type == "all" {
101                            continue;
102                        }
103                        index
104                            .exact
105                            .entry(framework)
106                            .or_default()
107                            .entry(resource_type.clone())
108                            .or_default()
109                            .push(policy);
110                    }
111                }
112                None => {
113                    if wild {
114                        index.unscoped_wild.push(policy);
115                    }
116                    for resource_type in &policy.resource_types {
117                        if resource_type == "*" || resource_type == "all" {
118                            continue;
119                        }
120                        index
121                            .unscoped_exact
122                            .entry(resource_type.clone())
123                            .or_default()
124                            .push(policy);
125                    }
126                }
127            }
128        }
129        index
130    }
131}
132
133fn eval_resource(resource: &Resource, index: &PolicyIndex<'_>) -> Vec<Finding> {
134    visit_policies(resource, index, |policy| {
135        eval_cond(&policy.definition, &resource.attributes)
136    })
137}
138
139fn eval_graph_resource(
140    resource: &Resource,
141    resources: &[Resource],
142    edges: &[Edge],
143    index: &PolicyIndex<'_>,
144) -> Vec<Finding> {
145    visit_policies(resource, index, |policy| {
146        eval_graph_cond(&policy.definition, resource, resources, edges)
147    })
148}
149
150fn visit_policies(
151    resource: &Resource,
152    index: &PolicyIndex<'_>,
153    mut eval: impl FnMut(&Policy) -> Status,
154) -> Vec<Finding> {
155    let shared = SharedIds {
156        address: Arc::from(format!("{}.{}", resource.resource_type, resource.name)),
157        file: Arc::from(resource.file.display().to_string()),
158        resource_type: Arc::from(resource.resource_type.as_str()),
159        resource_name: Arc::from(resource.name.as_str()),
160        framework: Arc::from(resource.framework.as_str()),
161    };
162    let mut findings = Vec::new();
163    let mut visit = |policy: &Policy| {
164        if let Some(skip) = resource
165            .skips
166            .iter()
167            .find(|skip| skip.check_id == policy.id.as_ref())
168        {
169            findings.push(make_finding(
170                policy,
171                Status::Skipped,
172                &shared,
173                resource,
174                skip.reason.clone(),
175            ));
176            return;
177        }
178        let status = eval(policy);
179        findings.push(make_finding(policy, status, &shared, resource, None));
180    };
181    if let Some(by_type) = index.exact.get(&resource.framework) {
182        if let Some(list) = by_type.get(resource.resource_type.as_str()) {
183            for policy in list {
184                visit(policy);
185            }
186        }
187    }
188    if let Some(list) = index.wild.get(&resource.framework) {
189        for policy in list {
190            visit(policy);
191        }
192    }
193    if let Some(list) = index.unscoped_exact.get(resource.resource_type.as_str()) {
194        for policy in list {
195            visit(policy);
196        }
197    }
198    for policy in &index.unscoped_wild {
199        visit(policy);
200    }
201    findings
202}
203
204struct SharedIds {
205    address: Arc<str>,
206    file: Arc<str>,
207    resource_type: Arc<str>,
208    resource_name: Arc<str>,
209    framework: Arc<str>,
210}
211
212fn make_finding(
213    policy: &Policy,
214    status: Status,
215    shared: &SharedIds,
216    resource: &Resource,
217    skip_reason: Option<String>,
218) -> Finding {
219    Finding {
220        check_id: Arc::clone(&policy.id),
221        check_name: Arc::clone(&policy.name),
222        category: Arc::clone(&policy.category),
223        severity: policy.severity,
224        status,
225        resource_address: Arc::clone(&shared.address),
226        resource_type: Arc::clone(&shared.resource_type),
227        resource_name: Arc::clone(&shared.resource_name),
228        framework: Arc::clone(&shared.framework),
229        file: Arc::clone(&shared.file),
230        start_line: resource.start_line,
231        end_line: resource.end_line,
232        guidelines: policy.guidelines.clone(),
233        skip_reason,
234    }
235}
236
237type FindingKey = (Arc<str>, Arc<str>, Arc<str>);
238
239fn collapse(findings: Vec<Finding>) -> Vec<Finding> {
240    let mut grouped: BTreeMap<FindingKey, Finding> = BTreeMap::new();
241    for finding in findings {
242        let key = (
243            Arc::clone(&finding.check_id),
244            Arc::clone(&finding.file),
245            Arc::clone(&finding.resource_address),
246        );
247        match grouped.get(&key) {
248            Some(existing) if existing.status >= finding.status => {}
249            _ => {
250                grouped.insert(key, finding);
251            }
252        }
253    }
254    grouped.into_values().collect()
255}
256
257#[cfg(test)]
258mod coverage;
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use rustmaninoff_ir::{Framework, Value};
264    use std::path::PathBuf;
265
266    fn resource(resource_type: &str, name: &str, attributes: Value) -> Resource {
267        Resource {
268            framework: Framework::Terraform,
269            kind: rustmaninoff_ir::ResourceKind::Managed,
270            resource_type: resource_type.to_string(),
271            name: name.to_string(),
272            attributes,
273            file: PathBuf::from("main.tf"),
274            start_line: 1,
275            end_line: 4,
276            skips: Vec::new(),
277        }
278    }
279
280    fn policy(yaml: &str) -> Policy {
281        parse_policy(yaml).expect("policy")
282    }
283
284    #[test]
285    fn equals_true_fails_when_false() {
286        let policy = policy(
287            r#"
288metadata:
289  id: CKV_AWS_3
290  name: encrypted
291  severity: HIGH
292  framework: terraform
293resource_types:
294  - aws_ebs_volume
295definition:
296  cond_type: attribute
297  attribute: encrypted
298  operator: equals
299  value: true
300"#,
301        );
302        let bad = resource(
303            "aws_ebs_volume",
304            "bad",
305            Value::Object(
306                [("encrypted".into(), Value::Bool(false))]
307                    .into_iter()
308                    .collect(),
309            ),
310        );
311        let findings = evaluate(&[bad], &[policy]);
312        assert_eq!(findings.len(), 1);
313        assert_eq!(findings[0].status, Status::Failed);
314    }
315
316    #[test]
317    fn unknown_does_not_fail() {
318        let policy = policy(
319            r#"
320metadata:
321  id: CKV_AWS_3
322  name: encrypted
323  severity: HIGH
324  framework: terraform
325resource_types: [aws_ebs_volume]
326definition:
327  cond_type: attribute
328  attribute: encrypted
329  operator: equals
330  value: true
331"#,
332        );
333        let unknown = resource(
334            "aws_ebs_volume",
335            "x",
336            Value::Object(
337                [(
338                    "encrypted".into(),
339                    Value::Unknown {
340                        expr: "var.x".into(),
341                    },
342                )]
343                .into_iter()
344                .collect(),
345            ),
346        );
347        let findings = evaluate(&[unknown], &[policy]);
348        assert_eq!(findings[0].status, Status::Unknown);
349    }
350
351    #[test]
352    fn no_element_detects_open_ingress() {
353        let policy = policy(
354            r#"
355metadata:
356  id: CKV_AWS_24
357  name: ssh
358  severity: HIGH
359  framework: terraform
360resource_types: [aws_security_group]
361definition:
362  cond_type: no_element
363  attribute: ingress
364  where:
365    and:
366      - cond_type: attribute
367        attribute: from_port
368        operator: less_than_or_equal
369        value: 22
370      - cond_type: attribute
371        attribute: to_port
372        operator: greater_than_or_equal
373        value: 22
374      - cond_type: attribute
375        attribute: cidr_blocks
376        operator: contains
377        value: "0.0.0.0/0"
378"#,
379        );
380        let bad = resource(
381            "aws_security_group",
382            "bad",
383            Value::from_json(serde_json::json!({
384                "ingress": [{"from_port": 22, "to_port": 22, "cidr_blocks": ["0.0.0.0/0"]}]
385            })),
386        );
387        let good = resource(
388            "aws_security_group",
389            "good",
390            Value::from_json(serde_json::json!({
391                "ingress": [{"from_port": 443, "to_port": 443, "cidr_blocks": ["0.0.0.0/0"]}]
392            })),
393        );
394        assert_eq!(
395            evaluate(&[bad], std::slice::from_ref(&policy))[0].status,
396            Status::Failed
397        );
398        assert_eq!(evaluate(&[good], &[policy])[0].status, Status::Passed);
399    }
400
401    #[test]
402    fn numeric_comparisons_agree_with_integers() {
403        let policy = policy(
404            r#"
405metadata:
406  id: NUM
407  name: length
408  framework: terraform
409resource_types: [aws_iam_account_password_policy]
410definition:
411  cond_type: attribute
412  attribute: minimum_password_length
413  operator: greater_than_or_equal
414  value: 14
415"#,
416        );
417        for length in 0..40 {
418            let resource = resource(
419                "aws_iam_account_password_policy",
420                "p",
421                Value::from_json(serde_json::json!({"minimum_password_length": length})),
422            );
423            let status = evaluate(&[resource], std::slice::from_ref(&policy))[0].status;
424            if length >= 14 {
425                assert_eq!(status, Status::Passed, "{length}");
426            } else {
427                assert_eq!(status, Status::Failed, "{length}");
428            }
429        }
430    }
431
432    #[test]
433    fn connection_requires_logging_neighbor() {
434        use rustmaninoff_ir::{Edge, EdgeKind, ResourceRef};
435
436        let policy = policy(
437            r#"
438metadata:
439  id: CKV2_AWS_S3_LOGGING
440  name: bucket has logging
441  severity: MEDIUM
442  framework: terraform
443resource_types:
444  - aws_s3_bucket
445definition:
446  cond_type: connection
447  connected_resource_types:
448    - aws_s3_bucket_logging
449  operator: exists
450"#,
451        );
452        let bucket = resource("aws_s3_bucket", "data", Value::Object(Default::default()));
453        let logging = resource(
454            "aws_s3_bucket_logging",
455            "data",
456            Value::Object(Default::default()),
457        );
458        let edge = Edge::new(
459            ResourceRef::from_resource(&bucket),
460            ResourceRef::from_resource(&logging),
461            EdgeKind::References,
462        )
463        .via("bucket");
464        assert!(evaluate(
465            &[bucket.clone(), logging.clone()],
466            std::slice::from_ref(&policy)
467        )
468        .is_empty());
469        let failed = evaluate_graph(
470            std::slice::from_ref(&bucket),
471            &[],
472            std::slice::from_ref(&policy),
473        );
474        assert_eq!(failed[0].status, Status::Failed);
475        let passed = evaluate_graph(&[bucket, logging], &[edge], std::slice::from_ref(&policy));
476        assert_eq!(passed[0].status, Status::Passed);
477    }
478}