Skip to main content

apparmor_policy/
error.rs

1//! Error types for parsing and validating AppArmor policy text.
2//!
3//! The parser is intentionally *fault tolerant*: unknown rule types and
4//! unrecognized syntax degrade to [`crate::ast::RawRule`] nodes instead of
5//! failing the whole parse. Errors are therefore reserved for *structural*
6//! failures that make the remainder of the input unreadable (unterminated
7//! strings, unbalanced braces, malformed variable names, …).
8//!
9//! Every error carries a 1-based `line`/`col` position plus the offending
10//! source line as `context`, so tooling (e.g. an `aa-logprof`-style editor)
11//! can point at the exact spot that needs repair.
12
13use std::fmt;
14use std::path::Path;
15
16/// A structured parse error with position information.
17///
18/// `line` and `col` are 1-based. `context` is the full source line the error
19/// occurred on (without the trailing newline), which is what makes errors
20/// actionable for incremental-repair tooling.
21///
22/// # Examples
23///
24/// ```
25/// use apparmor_policy::parse_str;
26///
27/// let err = parse_str("profile foo {\n  capability setuid,\n").unwrap_err();
28/// assert_eq!(err.line, 3);
29/// assert!(err.message.contains("unclosed"));
30/// assert_eq!(err.context, "");
31/// ```
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct ParseError {
34    /// 1-based line number of the offending token.
35    pub line: usize,
36    /// 1-based column number of the offending token.
37    pub col: usize,
38    /// Human-readable description of what went wrong (what was expected vs
39    /// what was found).
40    pub message: String,
41    /// The full source line containing the error (for display in editors).
42    pub context: String,
43}
44
45impl ParseError {
46    /// Build a new error from a 0-based byte offset and the full source.
47    ///
48    /// Offsets are translated into 1-based line/column numbers and the
49    /// offending line is extracted as `context`.
50    pub(crate) fn at(source: &str, offset: usize, message: impl Into<String>) -> Self {
51        let (line, col) = line_col(source, offset);
52        let context = source_line(source, line).to_string();
53        ParseError {
54            line,
55            col,
56            message: message.into(),
57            context,
58        }
59    }
60
61    /// Build an error that is not tied to a specific source location
62    /// (e.g. an I/O failure while reading a policy file).
63    pub(crate) fn detached(message: impl Into<String>) -> Self {
64        ParseError {
65            line: 0,
66            col: 0,
67            message: message.into(),
68            context: String::new(),
69        }
70    }
71}
72
73impl fmt::Display for ParseError {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        if self.line == 0 {
76            write!(f, "{}", self.message)
77        } else {
78            write!(f, "{}:{}: {}", self.line, self.col, self.message)
79        }
80    }
81}
82
83impl std::error::Error for ParseError {}
84
85/// The error type returned by [`crate::parse_file`] and [`crate::parse_str`].
86///
87/// Parsing failures are reported as [`ParseError`]. Reading a policy file
88/// from disk can additionally fail with an I/O error, which is reported as
89/// the [`Error::Io`] variant carrying the offending path.
90///
91/// # Examples
92///
93/// ```
94/// use apparmor_policy::Error;
95///
96/// let e = Error::detached("boom");
97/// assert!(e.to_string().contains("boom"));
98/// ```
99#[derive(Debug)]
100pub enum Error {
101    /// The policy text is structurally invalid.
102    Parse(ParseError),
103    /// The policy file could not be read from disk.
104    Io {
105        /// The path that could not be read.
106        path: std::path::PathBuf,
107        /// The underlying I/O error.
108        source: std::io::Error,
109    },
110}
111
112impl Error {
113    /// Build an [`Error::Parse`] from a [`ParseError`].
114    pub(crate) fn parse(e: ParseError) -> Self {
115        Error::Parse(e)
116    }
117
118    /// Build an [`Error::Io`] from a path and an I/O error.
119    pub(crate) fn io(path: &Path, source: std::io::Error) -> Self {
120        Error::Io {
121            path: path.to_path_buf(),
122            source,
123        }
124    }
125
126    /// Build an [`Error::Parse`] that is not tied to a specific source
127    /// location (useful for tooling that constructs errors programmatically).
128    ///
129    /// # Examples
130    ///
131    /// ```
132    /// use apparmor_policy::Error;
133    ///
134    /// let e = Error::detached("boom");
135    /// assert_eq!(e.to_string(), "boom");
136    /// ```
137    pub fn detached(msg: impl Into<String>) -> Self {
138        Error::Parse(ParseError::detached(msg))
139    }
140
141    /// Returns the underlying [`ParseError`] if this is a parsing failure.
142    ///
143    /// # Examples
144    ///
145    /// ```
146    /// use apparmor_policy::{Error, parse_str};
147    ///
148    /// let e = Error::from(parse_str("profile foo {").unwrap_err());
149    /// assert!(e.as_parse().is_some());
150    /// ```
151    pub fn as_parse(&self) -> Option<&ParseError> {
152        match self {
153            Error::Parse(e) => Some(e),
154            Error::Io { .. } => None,
155        }
156    }
157}
158
159impl fmt::Display for Error {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        match self {
162            Error::Parse(e) => write!(f, "{}", e),
163            Error::Io { path, source } => {
164                write!(f, "failed to read {}: {}", path.display(), source)
165            }
166        }
167    }
168}
169
170impl std::error::Error for Error {
171    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
172        match self {
173            Error::Parse(e) => Some(e),
174            Error::Io { source, .. } => Some(source),
175        }
176    }
177}
178
179impl From<ParseError> for Error {
180    fn from(e: ParseError) -> Self {
181        Error::Parse(e)
182    }
183}
184
185/// Compute 1-based (line, col) for a 0-based byte offset.
186pub(crate) fn line_col(source: &str, offset: usize) -> (usize, usize) {
187    let offset = offset.min(source.len());
188    let before = &source[..offset];
189    let line = before.bytes().filter(|&b| b == b'\n').count() + 1;
190    let line_start = before.rfind('\n').map(|i| i + 1).unwrap_or(0);
191    let col = before[line_start..].chars().count() + 1;
192    (line, col)
193}
194
195/// Extract the 1-based `line`-th source line (without trailing newline).
196pub(crate) fn source_line(source: &str, line: usize) -> &str {
197    source.lines().nth(line.saturating_sub(1)).unwrap_or("")
198}