rsigma_parser/diagnostic.rs
1//! Problems the parser reports while building a
2//! [`SigmaCollection`](crate::SigmaCollection).
3//!
4//! A collection keeps every document it could parse and records one
5//! [`CollectionDiagnostic`] per problem. An error means a document was
6//! dropped; a warning means the document was kept but part of it was ignored.
7//!
8//! # Examples
9//!
10//! ```
11//! use rsigma_parser::{DiagnosticKind, DiagnosticSeverity, parse_sigma_yaml};
12//!
13//! let collection = parse_sigma_yaml(
14//! r#"
15//! title: Kept with a warning
16//! status: unknown
17//! logsource:
18//! category: test
19//! detection:
20//! selection:
21//! field: value
22//! condition: selection
23//! "#,
24//! )
25//! .unwrap();
26//!
27//! assert_eq!(collection.rules.len(), 1);
28//! assert!(!collection.has_errors());
29//! let warning = &collection.diagnostics[0];
30//! assert_eq!(warning.severity, DiagnosticSeverity::Warning);
31//! assert_eq!(warning.kind, DiagnosticKind::Metadata);
32//! assert_eq!(warning.to_string(), "invalid status: 'unknown'");
33//! ```
34
35use std::fmt;
36use std::path::{Path, PathBuf};
37
38use serde::Serialize;
39
40use crate::error::{SigmaParserError, SigmaParserErrorKind, SourceLocation};
41
42/// How serious a [`CollectionDiagnostic`] is.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
44#[serde(rename_all = "lowercase")]
45pub enum DiagnosticSeverity {
46 /// The document, file, or rest of the stream was dropped.
47 Error,
48 /// The document was kept, but an invalid value in it was ignored.
49 Warning,
50}
51
52impl fmt::Display for DiagnosticSeverity {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 f.write_str(match self {
55 DiagnosticSeverity::Error => "error",
56 DiagnosticSeverity::Warning => "warning",
57 })
58 }
59}
60
61/// What a [`CollectionDiagnostic`] reports.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
63#[serde(rename_all = "snake_case")]
64#[non_exhaustive]
65pub enum DiagnosticKind {
66 /// The YAML stream is malformed. Parsing stops at the first such error.
67 YamlSyntax,
68 /// A document is not a YAML mapping.
69 NotAMapping,
70 /// A collection `action` is not a string, is unknown, or is `repeat`
71 /// without a previous document.
72 CollectionAction,
73 /// A document could not be parsed into a rule, correlation, or filter.
74 Document(SigmaParserErrorKind),
75 /// A `status`, `level`, `related`, or `sigma-version` value is invalid
76 /// and was ignored.
77 Metadata,
78 /// A file could not be read or parsed at all.
79 File(SigmaParserErrorKind),
80}
81
82/// A problem found while building a [`SigmaCollection`](crate::SigmaCollection).
83///
84/// `Display` prints [`message`](Self::message).
85#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
86#[non_exhaustive]
87pub struct CollectionDiagnostic {
88 pub kind: DiagnosticKind,
89 pub severity: DiagnosticSeverity,
90 pub message: String,
91 /// Zero-based index of the YAML document within its file or string.
92 #[serde(skip_serializing_if = "Option::is_none")]
93 pub document: Option<usize>,
94 /// The file the problem was found in, when the collection was read from
95 /// disk.
96 #[serde(skip_serializing_if = "Option::is_none")]
97 pub path: Option<PathBuf>,
98 /// Position within the document, for YAML syntax and condition errors.
99 #[serde(skip_serializing_if = "Option::is_none")]
100 pub location: Option<SourceLocation>,
101}
102
103impl CollectionDiagnostic {
104 /// An error diagnostic.
105 pub fn error(kind: DiagnosticKind, message: impl Into<String>) -> Self {
106 Self::new(kind, DiagnosticSeverity::Error, message.into())
107 }
108
109 /// A warning diagnostic.
110 pub fn warning(kind: DiagnosticKind, message: impl Into<String>) -> Self {
111 Self::new(kind, DiagnosticSeverity::Warning, message.into())
112 }
113
114 /// An error for a document the parser rejected.
115 pub fn document(error: &SigmaParserError) -> Self {
116 Self::error(DiagnosticKind::Document(error.kind()), error.to_string())
117 .with_location(error.location())
118 }
119
120 /// An error for a file that could not be read or parsed at all.
121 pub fn file(path: &Path, error: &SigmaParserError) -> Self {
122 Self::error(
123 DiagnosticKind::File(error.kind()),
124 format!("{}: {error}", path.display()),
125 )
126 .with_path(path)
127 .with_location(error.location())
128 }
129
130 fn new(kind: DiagnosticKind, severity: DiagnosticSeverity, message: String) -> Self {
131 Self {
132 kind,
133 severity,
134 message,
135 document: None,
136 path: None,
137 location: None,
138 }
139 }
140
141 /// Set the zero-based index of the YAML document.
142 pub fn with_document(mut self, index: usize) -> Self {
143 self.document = Some(index);
144 self
145 }
146
147 /// Set the file the problem was found in.
148 pub fn with_path(mut self, path: impl Into<PathBuf>) -> Self {
149 self.path = Some(path.into());
150 self
151 }
152
153 /// Set the position within the document.
154 pub fn with_location(mut self, location: Option<SourceLocation>) -> Self {
155 self.location = location;
156 self
157 }
158
159 /// True for [`DiagnosticSeverity::Error`].
160 pub fn is_error(&self) -> bool {
161 self.severity == DiagnosticSeverity::Error
162 }
163}
164
165impl fmt::Display for CollectionDiagnostic {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 f.write_str(&self.message)
168 }
169}