1use super::reports::Mirror;
4use crate::codec::Format;
5use crate::model::{ExceptionItem, ExceptionList, Rule};
6use crate::normalize;
7use elasticctl_core::{Error, ErrorKind, Result};
8use serde_json::Value;
9use std::path::{Path, PathBuf};
10
11pub fn read_mirror(dir: &Path) -> Result<Mirror> {
19 let mut mirror = Mirror {
20 rules: Vec::new(),
21 lists: Vec::new(),
22 items: Vec::new(),
23 };
24
25 let rules_path = super::rules_dir(dir);
26 if let Some(paths) = mirror_root_files(&rules_path)? {
27 for path in paths {
28 let body = read_regular_file(&path)?;
29 let (mut rules, lists, items) = decode_rule_file(&body, Format::from_path(&path))?;
30 mirror.rules.append(&mut rules);
31 for mut list in lists {
32 let list_items = split_items(&mut list)?;
33 mirror.lists.push(list);
34 mirror.items.extend(list_items);
35 }
36 for item in &items {
37 validate_top_level_item(item)?;
38 }
39 mirror.items.extend(items);
40 }
41 }
42
43 let lists_path = super::exceptions_dir(dir);
44 if let Some(paths) = mirror_root_files(&lists_path)? {
45 for path in paths {
46 let body = read_regular_file(&path)?;
47 let mut list = decode_list_file(&body, Format::from_path(&path))?;
48 let items = split_items(&mut list)?;
49 mirror.lists.push(list);
50 mirror.items.extend(items);
51 }
52 }
53
54 normalize::sort_rules(&mut mirror.rules);
55 normalize::sort_lists(&mut mirror.lists);
56 normalize::sort_items(&mut mirror.items);
57 Ok(mirror)
58}
59
60fn validate_top_level_item(item: &ExceptionItem) -> Result<()> {
61 let item_id = item.item_id()?;
62 if item_id.is_empty() {
63 return Err(Error::new(
64 ErrorKind::Error,
65 "exception item field item_id must be a non-empty string",
66 ));
67 }
68 let list_id = item.list_id()?;
69 if list_id.is_empty() {
70 return Err(Error::new(
71 ErrorKind::Error,
72 "exception item field list_id must be a non-empty string",
73 ));
74 }
75 match item.as_map().get("namespace_type") {
76 None => Ok(()),
77 Some(Value::String(value)) if !value.is_empty() => Ok(()),
78 Some(_) => Err(Error::new(
79 ErrorKind::Error,
80 "exception item field namespace_type must be a non-empty string",
81 )),
82 }
83}
84
85pub fn read_local(dir: &Path) -> Result<Vec<Rule>> {
87 Ok(read_mirror(dir)?.rules)
88}
89
90fn mirror_root_files(dir: &Path) -> Result<Option<Vec<PathBuf>>> {
100 match std::fs::symlink_metadata(dir) {
101 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
102 Err(e) => Err(Error::new(
103 ErrorKind::Error,
104 format!("reading {}: {e}", dir.display()),
105 )),
106 Ok(metadata) => {
107 if metadata.file_type().is_symlink() || !metadata.is_dir() {
108 return Err(Error::new(
109 ErrorKind::Error,
110 format!("mirror directory {} is not a real directory", dir.display()),
111 ));
112 }
113 Ok(Some(mirror_files(dir)?))
114 }
115 }
116}
117
118fn mirror_files(dir: &Path) -> Result<Vec<PathBuf>> {
120 let mut out = Vec::new();
121 for entry in std::fs::read_dir(dir)
122 .map_err(|e| Error::new(ErrorKind::Error, format!("reading {}: {e}", dir.display())))?
123 {
124 if let Some(path) = mirror_entry_path(dir, entry)? {
125 out.push(path);
126 }
127 }
128 out.sort();
129 Ok(out)
130}
131
132fn mirror_entry_path(
136 dir: &Path,
137 entry: std::io::Result<std::fs::DirEntry>,
138) -> Result<Option<PathBuf>> {
139 let entry = entry
140 .map_err(|e| Error::new(ErrorKind::Error, format!("reading {}: {e}", dir.display())))?;
141 let path = entry.path();
142 if !super::is_rule_file(&path) {
143 return Ok(None);
144 }
145 let file_type = entry
148 .file_type()
149 .map_err(|e| Error::new(ErrorKind::Error, format!("reading {}: {e}", path.display())))?;
150 if !file_type.is_file() {
151 return Err(Error::new(
152 ErrorKind::Error,
153 format!("mirror entry {} is not a regular file", path.display()),
154 ));
155 }
156 Ok(Some(path))
157}
158
159#[cfg(unix)]
166fn read_regular_file(path: &Path) -> Result<String> {
167 use std::io::Read;
168 use std::os::unix::fs::OpenOptionsExt;
169 let mut file = std::fs::OpenOptions::new()
170 .read(true)
171 .custom_flags(libc::O_NOFOLLOW)
172 .open(path)
173 .map_err(|e| Error::new(ErrorKind::Error, format!("reading {}: {e}", path.display())))?;
174 let mut body = String::new();
175 file.read_to_string(&mut body)
176 .map_err(|e| Error::new(ErrorKind::Error, format!("reading {}: {e}", path.display())))?;
177 Ok(body)
178}
179
180#[cfg(not(unix))]
181fn read_regular_file(path: &Path) -> Result<String> {
182 std::fs::read_to_string(path)
183 .map_err(|e| Error::new(ErrorKind::Error, format!("reading {}: {e}", path.display())))
184}
185
186fn decode_rule_file(
194 body: &str,
195 format: Format,
196) -> Result<(Vec<Rule>, Vec<ExceptionList>, Vec<ExceptionItem>)> {
197 match format {
198 Format::Ndjson => {
199 let bundle = crate::codec::decode_bundle(body)?;
200 Ok((bundle.rules, bundle.lists, bundle.items))
201 }
202 Format::Yaml => {
203 let values: Vec<Value> = serde_yaml_ng::from_str(body)
204 .map_err(|e| Error::new(ErrorKind::Error, format!("parsing YAML: {e}")))?;
205 let mut rules = Vec::new();
206 let mut lists = Vec::new();
207 let mut items = Vec::new();
208 for value in values {
209 if value.get("rule_id").is_some() {
213 rules.push(Rule::from_value(value)?);
214 } else if value.get("item_id").is_some() {
215 items.push(ExceptionItem::from_value(value)?);
216 } else if value.get("list_id").is_some() {
217 lists.push(ExceptionList::from_value(value)?);
218 } else {
219 return Err(Error::new(
220 ErrorKind::Error,
221 "a mirror file entry has neither rule_id, item_id, nor list_id",
222 ));
223 }
224 }
225 Ok((rules, lists, items))
226 }
227 }
228}
229
230pub(crate) fn encode_rule_file(
233 rule: &Rule,
234 inline_lists: &[ExceptionList],
235 format: Format,
236) -> Result<String> {
237 let mut objects = Vec::with_capacity(1 + inline_lists.len());
238 objects.push(rule.clone().into_value());
239 for list in inline_lists {
240 objects.push(list.clone().into_value());
241 }
242 match format {
243 Format::Yaml => serde_yaml_ng::to_string(&objects)
244 .map_err(|e| Error::new(ErrorKind::Error, format!("encoding YAML: {e}"))),
245 Format::Ndjson => {
246 let mut out = String::new();
247 for object in &objects {
248 out.push_str(
249 &serde_json::to_string(object).map_err(|e| {
250 Error::new(ErrorKind::Error, format!("encoding NDJSON: {e}"))
251 })?,
252 );
253 out.push('\n');
254 }
255 Ok(out)
256 }
257 }
258}
259
260pub(crate) fn encode_list_file(list: &ExceptionList, format: Format) -> Result<String> {
263 match format {
264 Format::Yaml => serde_yaml_ng::to_string(list.as_map())
265 .map_err(|e| Error::new(ErrorKind::Error, format!("encoding YAML: {e}"))),
266 Format::Ndjson => Ok(format!(
267 "{}\n",
268 serde_json::to_string(list.as_map())
269 .map_err(|e| Error::new(ErrorKind::Error, format!("encoding NDJSON: {e}")))?
270 )),
271 }
272}
273
274fn decode_list_file(body: &str, format: Format) -> Result<ExceptionList> {
275 let value = match format {
276 Format::Yaml => serde_yaml_ng::from_str(body)
277 .map_err(|e| Error::new(ErrorKind::Error, format!("parsing exception list: {e}")))?,
278 Format::Ndjson => {
279 let mut lines = body.lines().filter(|line| !line.trim().is_empty());
280 let line = lines
281 .next()
282 .ok_or_else(|| Error::new(ErrorKind::Error, "empty exception list file"))?;
283 if lines.next().is_some() {
284 return Err(Error::new(
285 ErrorKind::Error,
286 "an exception mirror file must contain exactly one nonblank NDJSON object",
287 ));
288 }
289 serde_json::from_str(line.trim())
290 .map_err(|e| Error::new(ErrorKind::Error, format!("parsing exception list: {e}")))?
291 }
292 };
293 ExceptionList::from_value(value)
294}
295
296fn split_items(list: &mut ExceptionList) -> Result<Vec<ExceptionItem>> {
299 let items = match list.as_map_mut().remove("items") {
300 None => return Ok(Vec::new()),
301 Some(Value::Array(items)) => items,
302 Some(_) => {
303 return Err(Error::new(
304 ErrorKind::Error,
305 "exception list field items must be an array",
306 ));
307 }
308 };
309 let list_id = list.list_id()?.to_string();
310 let namespace = list.namespace_type().to_string();
311 items
312 .into_iter()
313 .map(|value| {
314 let mut item = ExceptionItem::from_value(value)?;
315 item.as_map_mut()
320 .insert("list_id".into(), Value::String(list_id.clone()));
321 item.as_map_mut()
322 .insert("namespace_type".into(), Value::String(namespace.clone()));
323 Ok(item)
324 })
325 .collect()
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331
332 #[test]
337 fn mirror_entry_path_reports_an_entry_read_error_naming_the_directory() {
338 let dir = Path::new("/mirror");
339 let err = mirror_entry_path(
340 dir,
341 Err(std::io::Error::new(
342 std::io::ErrorKind::PermissionDenied,
343 "denied",
344 )),
345 )
346 .unwrap_err();
347 assert_eq!(err.kind, ErrorKind::Error);
348 assert!(err.message.contains("/mirror"), "{}", err.message);
349 }
350}