1mod 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
15pub 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
47pub 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 policy_frameworks_for(framework: Framework) -> Vec<Framework> {
151 match framework {
152 Framework::TerraformPlan => vec![Framework::TerraformPlan, Framework::Terraform],
153 other => vec![other],
154 }
155}
156
157fn visit_policies(
158 resource: &Resource,
159 index: &PolicyIndex<'_>,
160 mut eval: impl FnMut(&Policy) -> Status,
161) -> Vec<Finding> {
162 let shared = SharedIds {
163 address: Arc::from(format!("{}.{}", resource.resource_type, resource.name)),
164 file: Arc::from(resource.file.display().to_string()),
165 resource_type: Arc::from(resource.resource_type.as_str()),
166 resource_name: Arc::from(resource.name.as_str()),
167 framework: Arc::from(resource.framework.as_str()),
168 };
169 let mut findings = Vec::new();
170 let mut visit = |policy: &Policy| {
171 if let Some(skip) = resource
172 .skips
173 .iter()
174 .find(|skip| skip.check_id == policy.id.as_ref())
175 {
176 findings.push(make_finding(
177 policy,
178 Status::Skipped,
179 &shared,
180 resource,
181 skip.reason.clone(),
182 ));
183 return;
184 }
185 let status = eval(policy);
186 findings.push(make_finding(policy, status, &shared, resource, None));
187 };
188 let policy_frameworks = policy_frameworks_for(resource.framework);
189 for framework in policy_frameworks {
190 if let Some(by_type) = index.exact.get(&framework) {
191 if let Some(list) = by_type.get(resource.resource_type.as_str()) {
192 for policy in list {
193 visit(policy);
194 }
195 }
196 }
197 if let Some(list) = index.wild.get(&framework) {
198 for policy in list {
199 visit(policy);
200 }
201 }
202 }
203 if let Some(list) = index.unscoped_exact.get(resource.resource_type.as_str()) {
204 for policy in list {
205 visit(policy);
206 }
207 }
208 for policy in &index.unscoped_wild {
209 visit(policy);
210 }
211 findings
212}
213
214struct SharedIds {
215 address: Arc<str>,
216 file: Arc<str>,
217 resource_type: Arc<str>,
218 resource_name: Arc<str>,
219 framework: Arc<str>,
220}
221
222fn make_finding(
223 policy: &Policy,
224 status: Status,
225 shared: &SharedIds,
226 resource: &Resource,
227 skip_reason: Option<String>,
228) -> Finding {
229 Finding {
230 check_id: Arc::clone(&policy.id),
231 check_name: Arc::clone(&policy.name),
232 category: Arc::clone(&policy.category),
233 severity: policy.severity,
234 status,
235 resource_address: Arc::clone(&shared.address),
236 resource_type: Arc::clone(&shared.resource_type),
237 resource_name: Arc::clone(&shared.resource_name),
238 framework: Arc::clone(&shared.framework),
239 file: Arc::clone(&shared.file),
240 start_line: resource.start_line,
241 end_line: resource.end_line,
242 guidelines: policy.guidelines.clone(),
243 skip_reason,
244 }
245}
246
247type FindingKey = (Arc<str>, Arc<str>, Arc<str>);
248
249fn collapse(findings: Vec<Finding>) -> Vec<Finding> {
250 let mut grouped: BTreeMap<FindingKey, Finding> = BTreeMap::new();
251 for finding in findings {
252 let key = (
253 Arc::clone(&finding.check_id),
254 Arc::clone(&finding.file),
255 Arc::clone(&finding.resource_address),
256 );
257 match grouped.get(&key) {
258 Some(existing) if existing.status >= finding.status => {}
259 _ => {
260 grouped.insert(key, finding);
261 }
262 }
263 }
264 grouped.into_values().collect()
265}
266
267#[cfg(test)]
268mod coverage;
269#[cfg(test)]
270mod plan_policy_tests;
271
272#[cfg(test)]
273mod tests {
274 use super::*;
275 use rustmaninoff_ir::{Framework, Value};
276 use std::path::PathBuf;
277
278 fn resource(resource_type: &str, name: &str, attributes: Value) -> Resource {
279 Resource {
280 framework: Framework::Terraform,
281 kind: rustmaninoff_ir::ResourceKind::Managed,
282 resource_type: resource_type.to_string(),
283 name: name.to_string(),
284 attributes,
285 file: PathBuf::from("main.tf"),
286 start_line: 1,
287 end_line: 4,
288 skips: Vec::new(),
289 }
290 }
291
292 fn policy(yaml: &str) -> Policy {
293 parse_policy(yaml).expect("policy")
294 }
295
296 #[test]
297 fn equals_true_fails_when_false() {
298 let policy = policy(
299 r#"
300metadata:
301 id: CKV_AWS_3
302 name: encrypted
303 severity: HIGH
304 framework: terraform
305resource_types:
306 - aws_ebs_volume
307definition:
308 cond_type: attribute
309 attribute: encrypted
310 operator: equals
311 value: true
312"#,
313 );
314 let bad = resource(
315 "aws_ebs_volume",
316 "bad",
317 Value::Object(
318 [("encrypted".into(), Value::Bool(false))]
319 .into_iter()
320 .collect(),
321 ),
322 );
323 let findings = evaluate(&[bad], &[policy]);
324 assert_eq!(findings.len(), 1);
325 assert_eq!(findings[0].status, Status::Failed);
326 }
327
328 #[test]
329 fn unknown_does_not_fail() {
330 let policy = policy(
331 r#"
332metadata:
333 id: CKV_AWS_3
334 name: encrypted
335 severity: HIGH
336 framework: terraform
337resource_types: [aws_ebs_volume]
338definition:
339 cond_type: attribute
340 attribute: encrypted
341 operator: equals
342 value: true
343"#,
344 );
345 let unknown = resource(
346 "aws_ebs_volume",
347 "x",
348 Value::Object(
349 [(
350 "encrypted".into(),
351 Value::Unknown {
352 expr: "var.x".into(),
353 },
354 )]
355 .into_iter()
356 .collect(),
357 ),
358 );
359 let findings = evaluate(&[unknown], &[policy]);
360 assert_eq!(findings[0].status, Status::Unknown);
361 }
362
363 #[test]
364 fn no_element_detects_open_ingress() {
365 let policy = policy(
366 r#"
367metadata:
368 id: CKV_AWS_24
369 name: ssh
370 severity: HIGH
371 framework: terraform
372resource_types: [aws_security_group]
373definition:
374 cond_type: no_element
375 attribute: ingress
376 where:
377 and:
378 - cond_type: attribute
379 attribute: from_port
380 operator: less_than_or_equal
381 value: 22
382 - cond_type: attribute
383 attribute: to_port
384 operator: greater_than_or_equal
385 value: 22
386 - cond_type: attribute
387 attribute: cidr_blocks
388 operator: contains
389 value: "0.0.0.0/0"
390"#,
391 );
392 let bad = resource(
393 "aws_security_group",
394 "bad",
395 Value::from_json(serde_json::json!({
396 "ingress": [{"from_port": 22, "to_port": 22, "cidr_blocks": ["0.0.0.0/0"]}]
397 })),
398 );
399 let good = resource(
400 "aws_security_group",
401 "good",
402 Value::from_json(serde_json::json!({
403 "ingress": [{"from_port": 443, "to_port": 443, "cidr_blocks": ["0.0.0.0/0"]}]
404 })),
405 );
406 assert_eq!(
407 evaluate(&[bad], std::slice::from_ref(&policy))[0].status,
408 Status::Failed
409 );
410 assert_eq!(evaluate(&[good], &[policy])[0].status, Status::Passed);
411 }
412
413 #[test]
414 fn numeric_comparisons_agree_with_integers() {
415 let policy = policy(
416 r#"
417metadata:
418 id: NUM
419 name: length
420 framework: terraform
421resource_types: [aws_iam_account_password_policy]
422definition:
423 cond_type: attribute
424 attribute: minimum_password_length
425 operator: greater_than_or_equal
426 value: 14
427"#,
428 );
429 for length in 0..40 {
430 let resource = resource(
431 "aws_iam_account_password_policy",
432 "p",
433 Value::from_json(serde_json::json!({"minimum_password_length": length})),
434 );
435 let status = evaluate(&[resource], std::slice::from_ref(&policy))[0].status;
436 if length >= 14 {
437 assert_eq!(status, Status::Passed, "{length}");
438 } else {
439 assert_eq!(status, Status::Failed, "{length}");
440 }
441 }
442 }
443
444 #[test]
445 fn connection_requires_logging_neighbor() {
446 use rustmaninoff_ir::{Edge, EdgeKind, ResourceRef};
447
448 let policy = policy(
449 r#"
450metadata:
451 id: CKV2_AWS_S3_LOGGING
452 name: bucket has logging
453 severity: MEDIUM
454 framework: terraform
455resource_types:
456 - aws_s3_bucket
457definition:
458 cond_type: connection
459 connected_resource_types:
460 - aws_s3_bucket_logging
461 operator: exists
462"#,
463 );
464 let bucket = resource("aws_s3_bucket", "data", Value::Object(Default::default()));
465 let logging = resource(
466 "aws_s3_bucket_logging",
467 "data",
468 Value::Object(Default::default()),
469 );
470 let edge = Edge::new(
471 ResourceRef::from_resource(&bucket),
472 ResourceRef::from_resource(&logging),
473 EdgeKind::References,
474 )
475 .via("bucket");
476 assert!(evaluate(
477 &[bucket.clone(), logging.clone()],
478 std::slice::from_ref(&policy)
479 )
480 .is_empty());
481 let failed = evaluate_graph(
482 std::slice::from_ref(&bucket),
483 &[],
484 std::slice::from_ref(&policy),
485 );
486 assert_eq!(failed[0].status, Status::Failed);
487 let passed = evaluate_graph(&[bucket, logging], &[edge], std::slice::from_ref(&policy));
488 assert_eq!(passed[0].status, Status::Passed);
489 }
490}