Skip to main content

goliath_rule/
path.rs

1//! Dotted paths into an OCSF event.
2
3use std::fmt;
4
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7
8use crate::error::PathError;
9
10/// A dotted path to an attribute of an OCSF event, such as
11/// `process.parent_process.file.path`.
12///
13/// Arrays are traversed transparently: `observables.value` reaches the `value`
14/// of every element of `observables`. OCSF nests arrays of objects throughout,
15/// and a rule asking about a field means any occurrence of it.
16#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
17#[serde(try_from = "String", into = "String")]
18pub struct FieldPath {
19    text: String,
20    segments: Vec<String>,
21}
22
23impl FieldPath {
24    /// Parses a dotted path.
25    ///
26    /// Segments are otherwise unrestricted, because `unmapped.<name>` carries
27    /// field names exactly as the source spelled them.
28    ///
29    /// # Errors
30    ///
31    /// Returns [`PathError`] if the path or any of its segments is empty.
32    pub fn parse(text: &str) -> Result<Self, PathError> {
33        if text.is_empty() {
34            return Err(PathError::Empty);
35        }
36        let segments: Vec<String> = text.split('.').map(str::to_owned).collect();
37        if let Some(position) = segments.iter().position(String::is_empty) {
38            return Err(PathError::EmptySegment {
39                path: text.to_owned(),
40                position,
41            });
42        }
43        Ok(Self {
44            text: text.to_owned(),
45            segments,
46        })
47    }
48
49    /// Returns the path as written.
50    pub fn as_str(&self) -> &str {
51        &self.text
52    }
53
54    /// Returns the segments in order.
55    pub fn segments(&self) -> &[String] {
56        &self.segments
57    }
58
59    /// Returns every value this path reaches in `root`.
60    ///
61    /// Empty when the path reaches nothing. An array met along the way or at
62    /// the end contributes each of its elements, so the result never contains
63    /// an array. A JSON `null` is returned as found; deciding what it means is
64    /// the caller's business.
65    pub fn lookup<'a>(&self, root: &'a Value) -> Vec<&'a Value> {
66        let mut found = Vec::new();
67        self.visit(root, &mut |value| found.push(value));
68        found
69    }
70
71    /// Calls `visit` on every value this path reaches in `root`, in the order
72    /// [`lookup`](Self::lookup) returns them, without allocating.
73    pub fn visit<'a>(&self, root: &'a Value, visit: &mut impl FnMut(&'a Value)) {
74        walk(root, &self.segments, visit);
75    }
76}
77
78fn walk<'a>(value: &'a Value, segments: &[String], visit: &mut impl FnMut(&'a Value)) {
79    match value {
80        Value::Array(items) => {
81            for item in items {
82                walk(item, segments, visit);
83            }
84        }
85        _ => match segments.split_first() {
86            None => visit(value),
87            Some((head, rest)) => {
88                if let Some(child) = value.get(head.as_str()) {
89                    walk(child, rest, visit);
90                }
91            }
92        },
93    }
94}
95
96impl fmt::Display for FieldPath {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        f.write_str(&self.text)
99    }
100}
101
102impl TryFrom<String> for FieldPath {
103    type Error = PathError;
104
105    fn try_from(text: String) -> Result<Self, Self::Error> {
106        Self::parse(&text)
107    }
108}
109
110impl From<FieldPath> for String {
111    fn from(path: FieldPath) -> Self {
112        path.text
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use serde_json::json;
119
120    use super::*;
121
122    fn path(text: &str) -> FieldPath {
123        FieldPath::parse(text).expect("valid path")
124    }
125
126    #[test]
127    fn rejects_empty_paths_and_segments() {
128        assert_eq!(FieldPath::parse(""), Err(PathError::Empty));
129        assert!(matches!(
130            FieldPath::parse("process..path"),
131            Err(PathError::EmptySegment { position: 1, .. })
132        ));
133        assert!(FieldPath::parse(".process").is_err());
134        assert!(FieldPath::parse("process.").is_err());
135    }
136
137    #[test]
138    fn reaches_a_nested_attribute() {
139        let event = json!({ "process": { "file": { "path": r"C:\a.exe" } } });
140        assert_eq!(
141            path("process.file.path").lookup(&event),
142            [&json!(r"C:\a.exe")]
143        );
144    }
145
146    #[test]
147    fn a_missing_attribute_reaches_nothing() {
148        let event = json!({ "process": { "name": "a.exe" } });
149        assert!(path("process.file.path").lookup(&event).is_empty());
150        assert!(path("process.name.more").lookup(&event).is_empty());
151    }
152
153    #[test]
154    fn arrays_are_traversed_along_the_way() {
155        let event = json!({
156            "observables": [
157                { "name": "ip", "value": "10.0.0.1" },
158                { "name": "host" },
159                { "name": "user", "value": "adam" },
160            ]
161        });
162        assert_eq!(
163            path("observables.value").lookup(&event),
164            [&json!("10.0.0.1"), &json!("adam")]
165        );
166    }
167
168    #[test]
169    fn an_array_at_the_end_contributes_its_elements() {
170        let event = json!({ "tags": ["a", ["b", "c"]] });
171        assert_eq!(
172            path("tags").lookup(&event),
173            [&json!("a"), &json!("b"), &json!("c")]
174        );
175    }
176
177    #[test]
178    fn null_is_returned_as_found() {
179        let event = json!({ "user": null });
180        assert_eq!(path("user").lookup(&event), [&Value::Null]);
181    }
182
183    #[test]
184    fn unmapped_source_field_names_keep_their_spelling() {
185        let event = json!({ "unmapped": { "EventID": 4688 } });
186        assert_eq!(path("unmapped.EventID").lookup(&event), [&json!(4688)]);
187    }
188
189    #[test]
190    fn serializes_as_the_dotted_text() {
191        let original = path("process.cmd_line");
192        let text = serde_json::to_string(&original).expect("serialize");
193        assert_eq!(text, r#""process.cmd_line""#);
194        let parsed: FieldPath = serde_json::from_str(&text).expect("deserialize");
195        assert_eq!(parsed, original);
196        assert!(serde_json::from_str::<FieldPath>(r#""a..b""#).is_err());
197    }
198}