Skip to main content

rsigma_parser/ruleset/
error.rs

1//! Errors raised while resolving a named ruleset.
2
3use std::path::PathBuf;
4
5use thiserror::Error;
6
7/// A failure while resolving a ruleset. Every variant maps to a configuration
8/// error (exit 3) at the CLI, except source parse errors, which follow each
9/// command's existing policy.
10///
11/// Errors returned by [`resolve_ruleset`](super::resolve_ruleset) and
12/// [`resolve_loaded`](super::resolve_loaded) name the ruleset exactly once at
13/// the start of their message. The list variants carry messages that are
14/// already prefixed; the path variants carry the ruleset name in `ruleset`,
15/// which is `None` only when they come straight from
16/// [`load_sources`](super::load_sources) or an [`OverlayLoader`](super::OverlayLoader).
17#[derive(Debug, Error)]
18#[non_exhaustive]
19pub enum RulesetError {
20    /// The spec failed static validation; one message per problem.
21    #[error("{}", .0.join("; "))]
22    InvalidSpec(Vec<String>),
23    /// A declared source does not exist.
24    #[error("{}source path does not exist: {}", prefix(ruleset), path.display())]
25    MissingSource {
26        /// The ruleset, once known.
27        ruleset: Option<String>,
28        /// The missing source.
29        path: PathBuf,
30    },
31    /// A source or overlay file could not be read.
32    #[error("{}cannot read {}: {source}", prefix(ruleset), path.display())]
33    Io {
34        /// The ruleset, once known.
35        ruleset: Option<String>,
36        /// The path that failed.
37        path: PathBuf,
38        /// The underlying error.
39        #[source]
40        source: std::io::Error,
41    },
42    /// A path resolved outside [`ResolveOptions::confine_to`](super::ResolveOptions::confine_to).
43    #[error("{}path escapes the confined root: {}", prefix(ruleset), path.display())]
44    Confinement {
45        /// The ruleset, once known.
46        ruleset: Option<String>,
47        /// The offending path.
48        path: PathBuf,
49    },
50    /// A selector could not be compiled.
51    #[error("{0}")]
52    Selector(String),
53    /// Correlation references that do not resolve under the policy.
54    #[error("{}", .0.join("; "))]
55    Dependency(Vec<String>),
56    /// Two kept documents share an id or name.
57    #[error("{0}")]
58    Duplicate(String),
59    /// An overlay could not be loaded or applied.
60    #[error("{0}")]
61    Overlay(String),
62    /// Overlays that match no kept document under `stale_overlays: error`.
63    #[error("{}", .0.join("; "))]
64    StaleOverlay(Vec<String>),
65}
66
67fn prefix(ruleset: &Option<String>) -> String {
68    ruleset
69        .as_deref()
70        .map(|name| format!("ruleset '{name}': "))
71        .unwrap_or_default()
72}
73
74impl RulesetError {
75    /// Attach the ruleset name to a variant that does not carry it yet,
76    /// keeping the variant itself.
77    pub(crate) fn named(self, name: &str) -> Self {
78        let label = format!("ruleset '{name}'");
79        let prefixed = |message: String| {
80            if message.starts_with(&label) {
81                message
82            } else {
83                format!("{label}: {message}")
84            }
85        };
86        match self {
87            Self::MissingSource {
88                ruleset: None,
89                path,
90            } => Self::MissingSource {
91                ruleset: Some(name.to_string()),
92                path,
93            },
94            Self::Io {
95                ruleset: None,
96                path,
97                source,
98            } => Self::Io {
99                ruleset: Some(name.to_string()),
100                path,
101                source,
102            },
103            Self::Confinement {
104                ruleset: None,
105                path,
106            } => Self::Confinement {
107                ruleset: Some(name.to_string()),
108                path,
109            },
110            Self::Selector(message) => Self::Selector(prefixed(message)),
111            Self::Duplicate(message) => Self::Duplicate(prefixed(message)),
112            Self::Overlay(message) => Self::Overlay(prefixed(message)),
113            other => other,
114        }
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn named_keeps_the_variant_and_prefixes_once() {
124        let error = RulesetError::MissingSource {
125            ruleset: None,
126            path: PathBuf::from("./nope"),
127        }
128        .named("edge");
129        assert!(
130            matches!(&error, RulesetError::MissingSource { ruleset: Some(name), .. } if name == "edge"),
131            "{error:?}"
132        );
133        let expected = "ruleset 'edge': source path does not exist: ./nope";
134        assert_eq!(error.to_string(), expected);
135        assert_eq!(error.named("edge").to_string(), expected);
136
137        let overlay = RulesetError::Overlay("ruleset 'edge': bad".into()).named("edge");
138        assert_eq!(overlay.to_string(), "ruleset 'edge': bad");
139        let selector = RulesetError::Selector("unknown level 'huge'".into()).named("edge");
140        assert_eq!(selector.to_string(), "ruleset 'edge': unknown level 'huge'");
141    }
142}