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 resource_type: resource_type.to_string(),
213 name: name.to_string(),
214 attributes,
215 file: PathBuf::from("main.tf"),
216 start_line: 1,
217 end_line: 4,
218 skips: Vec::new(),
219 }
220 }
221
222 fn policy(yaml: &str) -> Policy {
223 parse_policy(yaml).expect("policy")
224 }
225
226 #[test]
227 fn equals_true_fails_when_false() {
228 let policy = policy(
229 r#"
230metadata:
231 id: CKV_AWS_3
232 name: encrypted
233 severity: HIGH
234 framework: terraform
235resource_types:
236 - aws_ebs_volume
237definition:
238 cond_type: attribute
239 attribute: encrypted
240 operator: equals
241 value: true
242"#,
243 );
244 let bad = resource(
245 "aws_ebs_volume",
246 "bad",
247 Value::Object(
248 [("encrypted".into(), Value::Bool(false))]
249 .into_iter()
250 .collect(),
251 ),
252 );
253 let findings = evaluate(&[bad], &[policy]);
254 assert_eq!(findings.len(), 1);
255 assert_eq!(findings[0].status, Status::Failed);
256 }
257
258 #[test]
259 fn unknown_does_not_fail() {
260 let policy = policy(
261 r#"
262metadata:
263 id: CKV_AWS_3
264 name: encrypted
265 severity: HIGH
266 framework: terraform
267resource_types: [aws_ebs_volume]
268definition:
269 cond_type: attribute
270 attribute: encrypted
271 operator: equals
272 value: true
273"#,
274 );
275 let unknown = resource(
276 "aws_ebs_volume",
277 "x",
278 Value::Object(
279 [(
280 "encrypted".into(),
281 Value::Unknown {
282 expr: "var.x".into(),
283 },
284 )]
285 .into_iter()
286 .collect(),
287 ),
288 );
289 let findings = evaluate(&[unknown], &[policy]);
290 assert_eq!(findings[0].status, Status::Unknown);
291 }
292
293 #[test]
294 fn no_element_detects_open_ingress() {
295 let policy = policy(
296 r#"
297metadata:
298 id: CKV_AWS_24
299 name: ssh
300 severity: HIGH
301 framework: terraform
302resource_types: [aws_security_group]
303definition:
304 cond_type: no_element
305 attribute: ingress
306 where:
307 and:
308 - cond_type: attribute
309 attribute: from_port
310 operator: less_than_or_equal
311 value: 22
312 - cond_type: attribute
313 attribute: to_port
314 operator: greater_than_or_equal
315 value: 22
316 - cond_type: attribute
317 attribute: cidr_blocks
318 operator: contains
319 value: "0.0.0.0/0"
320"#,
321 );
322 let bad = resource(
323 "aws_security_group",
324 "bad",
325 Value::from_json(serde_json::json!({
326 "ingress": [{"from_port": 22, "to_port": 22, "cidr_blocks": ["0.0.0.0/0"]}]
327 })),
328 );
329 let good = resource(
330 "aws_security_group",
331 "good",
332 Value::from_json(serde_json::json!({
333 "ingress": [{"from_port": 443, "to_port": 443, "cidr_blocks": ["0.0.0.0/0"]}]
334 })),
335 );
336 assert_eq!(
337 evaluate(&[bad], std::slice::from_ref(&policy))[0].status,
338 Status::Failed
339 );
340 assert_eq!(evaluate(&[good], &[policy])[0].status, Status::Passed);
341 }
342
343 #[test]
344 fn numeric_comparisons_agree_with_integers() {
345 let policy = policy(
346 r#"
347metadata:
348 id: NUM
349 name: length
350 framework: terraform
351resource_types: [aws_iam_account_password_policy]
352definition:
353 cond_type: attribute
354 attribute: minimum_password_length
355 operator: greater_than_or_equal
356 value: 14
357"#,
358 );
359 for length in 0..40 {
360 let resource = resource(
361 "aws_iam_account_password_policy",
362 "p",
363 Value::from_json(serde_json::json!({"minimum_password_length": length})),
364 );
365 let status = evaluate(&[resource], std::slice::from_ref(&policy))[0].status;
366 if length >= 14 {
367 assert_eq!(status, Status::Passed, "{length}");
368 } else {
369 assert_eq!(status, Status::Failed, "{length}");
370 }
371 }
372 }
373}