1mod eval;
4mod policy;
5
6pub use eval::{eval_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::{Framework, Resource};
14
15pub fn evaluate(resources: &[Resource], policies: &[Policy]) -> Vec<Finding> {
20 if resources.is_empty() || policies.is_empty() {
21 return Vec::new();
22 }
23 let index = PolicyIndex::build(policies);
24 let findings = if resources.len() < 32 {
25 resources
26 .iter()
27 .flat_map(|resource| eval_resource(resource, &index))
28 .collect()
29 } else {
30 resources
31 .par_iter()
32 .flat_map(|resource| eval_resource(resource, &index))
33 .collect()
34 };
35 collapse(findings)
36}
37
38struct PolicyIndex<'a> {
39 exact: HashMap<Framework, HashMap<String, Vec<&'a Policy>>>,
40 wild: HashMap<Framework, Vec<&'a Policy>>,
41 unscoped_exact: HashMap<String, Vec<&'a Policy>>,
42 unscoped_wild: Vec<&'a Policy>,
43}
44
45impl<'a> PolicyIndex<'a> {
46 fn build(policies: &'a [Policy]) -> Self {
47 let mut index = Self {
48 exact: HashMap::new(),
49 wild: HashMap::new(),
50 unscoped_exact: HashMap::new(),
51 unscoped_wild: Vec::new(),
52 };
53 for policy in policies {
54 let wild = policy
55 .resource_types
56 .iter()
57 .any(|resource_type| resource_type == "*" || resource_type == "all");
58 match policy.framework {
59 Some(framework) => {
60 if wild {
61 index.wild.entry(framework).or_default().push(policy);
62 }
63 for resource_type in &policy.resource_types {
64 if resource_type == "*" || resource_type == "all" {
65 continue;
66 }
67 index
68 .exact
69 .entry(framework)
70 .or_default()
71 .entry(resource_type.clone())
72 .or_default()
73 .push(policy);
74 }
75 }
76 None => {
77 if wild {
78 index.unscoped_wild.push(policy);
79 }
80 for resource_type in &policy.resource_types {
81 if resource_type == "*" || resource_type == "all" {
82 continue;
83 }
84 index
85 .unscoped_exact
86 .entry(resource_type.clone())
87 .or_default()
88 .push(policy);
89 }
90 }
91 }
92 }
93 index
94 }
95}
96
97fn eval_resource(resource: &Resource, index: &PolicyIndex<'_>) -> Vec<Finding> {
98 let shared = SharedIds {
99 address: Arc::from(format!("{}.{}", resource.resource_type, resource.name)),
100 file: Arc::from(resource.file.display().to_string()),
101 resource_type: Arc::from(resource.resource_type.as_str()),
102 resource_name: Arc::from(resource.name.as_str()),
103 framework: Arc::from(resource.framework.as_str()),
104 };
105 let mut findings = Vec::new();
106 let mut visit = |policy: &Policy| {
107 if let Some(skip) = resource
108 .skips
109 .iter()
110 .find(|skip| skip.check_id == policy.id.as_ref())
111 {
112 findings.push(make_finding(
113 policy,
114 Status::Skipped,
115 &shared,
116 resource,
117 skip.reason.clone(),
118 ));
119 return;
120 }
121 let status = eval_cond(&policy.definition, &resource.attributes);
122 findings.push(make_finding(policy, status, &shared, resource, None));
123 };
124 if let Some(by_type) = index.exact.get(&resource.framework) {
125 if let Some(list) = by_type.get(resource.resource_type.as_str()) {
126 for policy in list {
127 visit(policy);
128 }
129 }
130 }
131 if let Some(list) = index.wild.get(&resource.framework) {
132 for policy in list {
133 visit(policy);
134 }
135 }
136 if let Some(list) = index.unscoped_exact.get(resource.resource_type.as_str()) {
137 for policy in list {
138 visit(policy);
139 }
140 }
141 for policy in &index.unscoped_wild {
142 visit(policy);
143 }
144 findings
145}
146
147struct SharedIds {
148 address: Arc<str>,
149 file: Arc<str>,
150 resource_type: Arc<str>,
151 resource_name: Arc<str>,
152 framework: Arc<str>,
153}
154
155fn make_finding(
156 policy: &Policy,
157 status: Status,
158 shared: &SharedIds,
159 resource: &Resource,
160 skip_reason: Option<String>,
161) -> Finding {
162 Finding {
163 check_id: Arc::clone(&policy.id),
164 check_name: Arc::clone(&policy.name),
165 category: Arc::clone(&policy.category),
166 severity: policy.severity,
167 status,
168 resource_address: Arc::clone(&shared.address),
169 resource_type: Arc::clone(&shared.resource_type),
170 resource_name: Arc::clone(&shared.resource_name),
171 framework: Arc::clone(&shared.framework),
172 file: Arc::clone(&shared.file),
173 start_line: resource.start_line,
174 end_line: resource.end_line,
175 guidelines: policy.guidelines.clone(),
176 skip_reason,
177 }
178}
179
180type FindingKey = (Arc<str>, Arc<str>, Arc<str>);
181
182fn collapse(findings: Vec<Finding>) -> Vec<Finding> {
183 let mut grouped: BTreeMap<FindingKey, Finding> = BTreeMap::new();
184 for finding in findings {
185 let key = (
186 Arc::clone(&finding.check_id),
187 Arc::clone(&finding.file),
188 Arc::clone(&finding.resource_address),
189 );
190 match grouped.get(&key) {
191 Some(existing) if existing.status >= finding.status => {}
192 _ => {
193 grouped.insert(key, finding);
194 }
195 }
196 }
197 grouped.into_values().collect()
198}
199
200#[cfg(test)]
201mod coverage;
202
203#[cfg(test)]
204mod tests {
205 use super::*;
206 use rustmaninoff_ir::{Framework, Value};
207 use std::path::PathBuf;
208
209 fn resource(resource_type: &str, name: &str, attributes: Value) -> Resource {
210 Resource {
211 framework: Framework::Terraform,
212 kind: rustmaninoff_ir::ResourceKind::Managed,
213 resource_type: resource_type.to_string(),
214 name: name.to_string(),
215 attributes,
216 file: PathBuf::from("main.tf"),
217 start_line: 1,
218 end_line: 4,
219 skips: Vec::new(),
220 }
221 }
222
223 fn policy(yaml: &str) -> Policy {
224 parse_policy(yaml).expect("policy")
225 }
226
227 #[test]
228 fn equals_true_fails_when_false() {
229 let policy = policy(
230 r#"
231metadata:
232 id: CKV_AWS_3
233 name: encrypted
234 severity: HIGH
235 framework: terraform
236resource_types:
237 - aws_ebs_volume
238definition:
239 cond_type: attribute
240 attribute: encrypted
241 operator: equals
242 value: true
243"#,
244 );
245 let bad = resource(
246 "aws_ebs_volume",
247 "bad",
248 Value::Object(
249 [("encrypted".into(), Value::Bool(false))]
250 .into_iter()
251 .collect(),
252 ),
253 );
254 let findings = evaluate(&[bad], &[policy]);
255 assert_eq!(findings.len(), 1);
256 assert_eq!(findings[0].status, Status::Failed);
257 }
258
259 #[test]
260 fn unknown_does_not_fail() {
261 let policy = policy(
262 r#"
263metadata:
264 id: CKV_AWS_3
265 name: encrypted
266 severity: HIGH
267 framework: terraform
268resource_types: [aws_ebs_volume]
269definition:
270 cond_type: attribute
271 attribute: encrypted
272 operator: equals
273 value: true
274"#,
275 );
276 let unknown = resource(
277 "aws_ebs_volume",
278 "x",
279 Value::Object(
280 [(
281 "encrypted".into(),
282 Value::Unknown {
283 expr: "var.x".into(),
284 },
285 )]
286 .into_iter()
287 .collect(),
288 ),
289 );
290 let findings = evaluate(&[unknown], &[policy]);
291 assert_eq!(findings[0].status, Status::Unknown);
292 }
293
294 #[test]
295 fn no_element_detects_open_ingress() {
296 let policy = policy(
297 r#"
298metadata:
299 id: CKV_AWS_24
300 name: ssh
301 severity: HIGH
302 framework: terraform
303resource_types: [aws_security_group]
304definition:
305 cond_type: no_element
306 attribute: ingress
307 where:
308 and:
309 - cond_type: attribute
310 attribute: from_port
311 operator: less_than_or_equal
312 value: 22
313 - cond_type: attribute
314 attribute: to_port
315 operator: greater_than_or_equal
316 value: 22
317 - cond_type: attribute
318 attribute: cidr_blocks
319 operator: contains
320 value: "0.0.0.0/0"
321"#,
322 );
323 let bad = resource(
324 "aws_security_group",
325 "bad",
326 Value::from_json(serde_json::json!({
327 "ingress": [{"from_port": 22, "to_port": 22, "cidr_blocks": ["0.0.0.0/0"]}]
328 })),
329 );
330 let good = resource(
331 "aws_security_group",
332 "good",
333 Value::from_json(serde_json::json!({
334 "ingress": [{"from_port": 443, "to_port": 443, "cidr_blocks": ["0.0.0.0/0"]}]
335 })),
336 );
337 assert_eq!(
338 evaluate(&[bad], std::slice::from_ref(&policy))[0].status,
339 Status::Failed
340 );
341 assert_eq!(evaluate(&[good], &[policy])[0].status, Status::Passed);
342 }
343
344 #[test]
345 fn numeric_comparisons_agree_with_integers() {
346 let policy = policy(
347 r#"
348metadata:
349 id: NUM
350 name: length
351 framework: terraform
352resource_types: [aws_iam_account_password_policy]
353definition:
354 cond_type: attribute
355 attribute: minimum_password_length
356 operator: greater_than_or_equal
357 value: 14
358"#,
359 );
360 for length in 0..40 {
361 let resource = resource(
362 "aws_iam_account_password_policy",
363 "p",
364 Value::from_json(serde_json::json!({"minimum_password_length": length})),
365 );
366 let status = evaluate(&[resource], std::slice::from_ref(&policy))[0].status;
367 if length >= 14 {
368 assert_eq!(status, Status::Passed, "{length}");
369 } else {
370 assert_eq!(status, Status::Failed, "{length}");
371 }
372 }
373 }
374}