1use std::fs;
4use std::path::Path;
5use std::sync::Arc;
6
7use rustmaninoff_ir::{input_limit, Framework, Value, MAX_POLICY_BYTES};
8use serde::Deserialize;
9
10use crate::eval::Cond;
11
12#[derive(Debug, thiserror::Error)]
13pub enum PolicyError {
14 #[error("invalid policy: {0}")]
15 Invalid(String),
16 #[error("failed to read {path}: {source}")]
17 Io {
18 path: String,
19 source: std::io::Error,
20 },
21}
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
24pub enum Severity {
25 Low,
26 Medium,
27 High,
28 Critical,
29}
30
31impl Severity {
32 pub fn parse(text: &str) -> Option<Self> {
33 match text.trim().to_ascii_lowercase().as_str() {
34 "low" | "info" => Some(Self::Low),
35 "medium" | "med" => Some(Self::Medium),
36 "high" => Some(Self::High),
37 "critical" | "crit" => Some(Self::Critical),
38 _ => None,
39 }
40 }
41
42 pub fn as_str(self) -> &'static str {
43 match self {
44 Self::Low => "LOW",
45 Self::Medium => "MEDIUM",
46 Self::High => "HIGH",
47 Self::Critical => "CRITICAL",
48 }
49 }
50}
51
52impl std::fmt::Display for Severity {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 f.write_str(self.as_str())
55 }
56}
57
58#[derive(Clone, Debug)]
59pub struct Fixtures {
60 pub fail: String,
61 pub pass: String,
62}
63
64#[derive(Clone, Debug)]
65pub struct Policy {
66 pub id: Arc<str>,
67 pub name: Arc<str>,
68 pub category: Arc<str>,
69 pub severity: Severity,
70 pub framework: Option<Framework>,
71 pub guidelines: Option<Arc<str>>,
72 pub resource_types: Vec<String>,
73 pub definition: Cond,
74 pub fixtures: Option<Fixtures>,
75}
76
77#[derive(Debug, Deserialize)]
78struct RawPolicy {
79 metadata: RawMetadata,
80 #[serde(default)]
81 resource_types: YamlStringList,
82 definition: serde_yaml::Value,
83 #[serde(default)]
84 fixtures: Option<RawFixtures>,
85 #[serde(default)]
86 scope: Option<serde_yaml::Value>,
87}
88
89#[derive(Debug, Deserialize)]
90struct RawMetadata {
91 id: String,
92 name: String,
93 #[serde(default)]
94 category: Option<String>,
95 #[serde(default)]
96 severity: Option<String>,
97 #[serde(default)]
98 framework: Option<String>,
99 #[serde(default)]
100 guidelines: Option<String>,
101}
102
103#[derive(Debug, Deserialize)]
104struct RawFixtures {
105 fail: String,
106 #[serde(rename = "pass")]
107 pass_fixture: String,
108}
109
110#[derive(Debug, Default, Deserialize)]
111#[serde(untagged)]
112enum YamlStringList {
113 #[default]
114 Missing,
115 One(String),
116 Many(Vec<String>),
117}
118
119impl YamlStringList {
120 fn into_vec(self) -> Vec<String> {
121 match self {
122 Self::Missing => Vec::new(),
123 Self::One(value) => vec![value],
124 Self::Many(values) => values,
125 }
126 }
127}
128
129pub fn parse_policy(text: &str) -> Result<Policy, PolicyError> {
130 let raw: RawPolicy =
131 serde_yaml::from_str(text).map_err(|err| PolicyError::Invalid(format!("yaml: {err}")))?;
132 let _ = raw.scope;
133 let mut resource_types = raw.resource_types.into_vec();
134 if resource_types.is_empty() {
135 resource_types = resource_types_from_definition(&raw.definition);
136 }
137 if resource_types.is_empty() {
138 return Err(PolicyError::Invalid(format!(
139 "{} is missing resource_types",
140 raw.metadata.id
141 )));
142 }
143 let definition = Cond::from_yaml(&raw.definition)
144 .map_err(|err| PolicyError::Invalid(format!("{}: {err}", raw.metadata.id)))?;
145 let framework = match raw.metadata.framework {
146 Some(value) => Some(Framework::parse(&value).ok_or_else(|| {
147 PolicyError::Invalid(format!(
148 "unknown framework '{value}' on {}",
149 raw.metadata.id
150 ))
151 })?),
152 None => None,
153 };
154 let severity = match raw.metadata.severity {
155 Some(value) => Severity::parse(&value).ok_or_else(|| {
156 PolicyError::Invalid(format!("unknown severity '{value}' on {}", raw.metadata.id))
157 })?,
158 None => Severity::Medium,
159 };
160 let fixtures = raw.fixtures.map(|fixtures| Fixtures {
161 fail: fixtures.fail,
162 pass: fixtures.pass_fixture,
163 });
164 Ok(Policy {
165 id: Arc::from(raw.metadata.id),
166 name: Arc::from(raw.metadata.name),
167 category: Arc::from(
168 raw.metadata
169 .category
170 .unwrap_or_else(|| "GENERAL_SECURITY".to_string()),
171 ),
172 severity,
173 framework,
174 guidelines: raw.metadata.guidelines.map(Arc::from),
175 resource_types,
176 definition,
177 fixtures,
178 })
179}
180
181fn resource_types_from_definition(value: &serde_yaml::Value) -> Vec<String> {
182 let Some(map) = value.as_mapping() else {
183 return Vec::new();
184 };
185 for (key, item) in map {
186 if key.as_str() == Some("resource_types") {
187 return string_list(item);
188 }
189 }
190 Vec::new()
191}
192
193fn string_list(value: &serde_yaml::Value) -> Vec<String> {
194 if let Some(text) = value.as_str() {
195 return vec![text.to_string()];
196 }
197 value
198 .as_sequence()
199 .map(|items| {
200 items
201 .iter()
202 .filter_map(|item| item.as_str().map(str::to_string))
203 .collect()
204 })
205 .unwrap_or_default()
206}
207
208pub fn load_policy_dir(path: &Path) -> Result<Vec<Policy>, PolicyError> {
209 let mut policies = Vec::new();
210 load_dir(path, &mut policies)?;
211 policies.sort_by(|left, right| {
212 (
213 &left.id,
214 &left.name,
215 left.framework.map(|item| item.as_str()),
216 )
217 .cmp(&(
218 &right.id,
219 &right.name,
220 right.framework.map(|item| item.as_str()),
221 ))
222 });
223 Ok(policies)
224}
225
226fn load_dir(path: &Path, out: &mut Vec<Policy>) -> Result<(), PolicyError> {
227 let entries = fs::read_dir(path).map_err(|source| PolicyError::Io {
228 path: path.display().to_string(),
229 source,
230 })?;
231 let mut paths: Vec<_> =
232 entries
233 .collect::<Result<Vec<_>, _>>()
234 .map_err(|source| PolicyError::Io {
235 path: path.display().to_string(),
236 source,
237 })?;
238 paths.sort_by_key(|entry| entry.path());
239 for entry in paths {
240 let child = entry.path();
241 let Ok(file_type) = entry.file_type() else {
242 continue;
243 };
244 if file_type.is_symlink() {
245 continue;
246 }
247 if file_type.is_dir() {
248 load_dir(&child, out)?;
249 continue;
250 }
251 if !file_type.is_file() {
252 continue;
253 }
254 let Some(ext) = child.extension().and_then(|ext| ext.to_str()) else {
255 continue;
256 };
257 if ext != "yaml" && ext != "yml" {
258 continue;
259 }
260 let meta = fs::symlink_metadata(&child).map_err(|source| PolicyError::Io {
261 path: child.display().to_string(),
262 source,
263 })?;
264 if meta.len() > MAX_POLICY_BYTES {
265 return Err(PolicyError::Invalid(format!(
266 "{} exceeds 1MB",
267 child.display()
268 )));
269 }
270 let text = fs::read_to_string(&child).map_err(|source| PolicyError::Io {
271 path: child.display().to_string(),
272 source,
273 })?;
274 if let Some(message) = input_limit(&text) {
275 return Err(PolicyError::Invalid(format!(
276 "{}: {message}",
277 child.display()
278 )));
279 }
280 let policy = parse_policy(&text)
281 .map_err(|err| PolicyError::Invalid(format!("{}: {err}", child.display())))?;
282 out.push(policy);
283 }
284 Ok(())
285}
286
287pub fn yaml_to_value(value: &serde_yaml::Value) -> Value {
288 Value::from_yaml(value.clone())
289}