apparmor-policy 0.1.0

Typed, lossless parser and serializer for the AppArmor policy language.
Documentation
//! Error types for parsing and validating AppArmor policy text.
//!
//! The parser is intentionally *fault tolerant*: unknown rule types and
//! unrecognized syntax degrade to [`crate::ast::RawRule`] nodes instead of
//! failing the whole parse. Errors are therefore reserved for *structural*
//! failures that make the remainder of the input unreadable (unterminated
//! strings, unbalanced braces, malformed variable names, …).
//!
//! Every error carries a 1-based `line`/`col` position plus the offending
//! source line as `context`, so tooling (e.g. an `aa-logprof`-style editor)
//! can point at the exact spot that needs repair.

use std::fmt;
use std::path::Path;

/// A structured parse error with position information.
///
/// `line` and `col` are 1-based. `context` is the full source line the error
/// occurred on (without the trailing newline), which is what makes errors
/// actionable for incremental-repair tooling.
///
/// # Examples
///
/// ```
/// use apparmor_policy::parse_str;
///
/// let err = parse_str("profile foo {\n  capability setuid,\n").unwrap_err();
/// assert_eq!(err.line, 3);
/// assert!(err.message.contains("unclosed"));
/// assert_eq!(err.context, "");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
    /// 1-based line number of the offending token.
    pub line: usize,
    /// 1-based column number of the offending token.
    pub col: usize,
    /// Human-readable description of what went wrong (what was expected vs
    /// what was found).
    pub message: String,
    /// The full source line containing the error (for display in editors).
    pub context: String,
}

impl ParseError {
    /// Build a new error from a 0-based byte offset and the full source.
    ///
    /// Offsets are translated into 1-based line/column numbers and the
    /// offending line is extracted as `context`.
    pub(crate) fn at(source: &str, offset: usize, message: impl Into<String>) -> Self {
        let (line, col) = line_col(source, offset);
        let context = source_line(source, line).to_string();
        ParseError {
            line,
            col,
            message: message.into(),
            context,
        }
    }

    /// Build an error that is not tied to a specific source location
    /// (e.g. an I/O failure while reading a policy file).
    pub(crate) fn detached(message: impl Into<String>) -> Self {
        ParseError {
            line: 0,
            col: 0,
            message: message.into(),
            context: String::new(),
        }
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.line == 0 {
            write!(f, "{}", self.message)
        } else {
            write!(f, "{}:{}: {}", self.line, self.col, self.message)
        }
    }
}

impl std::error::Error for ParseError {}

/// The error type returned by [`crate::parse_file`] and [`crate::parse_str`].
///
/// Parsing failures are reported as [`ParseError`]. Reading a policy file
/// from disk can additionally fail with an I/O error, which is reported as
/// the [`Error::Io`] variant carrying the offending path.
///
/// # Examples
///
/// ```
/// use apparmor_policy::Error;
///
/// let e = Error::detached("boom");
/// assert!(e.to_string().contains("boom"));
/// ```
#[derive(Debug)]
pub enum Error {
    /// The policy text is structurally invalid.
    Parse(ParseError),
    /// The policy file could not be read from disk.
    Io {
        /// The path that could not be read.
        path: std::path::PathBuf,
        /// The underlying I/O error.
        source: std::io::Error,
    },
}

impl Error {
    /// Build an [`Error::Parse`] from a [`ParseError`].
    pub(crate) fn parse(e: ParseError) -> Self {
        Error::Parse(e)
    }

    /// Build an [`Error::Io`] from a path and an I/O error.
    pub(crate) fn io(path: &Path, source: std::io::Error) -> Self {
        Error::Io {
            path: path.to_path_buf(),
            source,
        }
    }

    /// Build an [`Error::Parse`] that is not tied to a specific source
    /// location (useful for tooling that constructs errors programmatically).
    ///
    /// # Examples
    ///
    /// ```
    /// use apparmor_policy::Error;
    ///
    /// let e = Error::detached("boom");
    /// assert_eq!(e.to_string(), "boom");
    /// ```
    pub fn detached(msg: impl Into<String>) -> Self {
        Error::Parse(ParseError::detached(msg))
    }

    /// Returns the underlying [`ParseError`] if this is a parsing failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use apparmor_policy::{Error, parse_str};
    ///
    /// let e = Error::from(parse_str("profile foo {").unwrap_err());
    /// assert!(e.as_parse().is_some());
    /// ```
    pub fn as_parse(&self) -> Option<&ParseError> {
        match self {
            Error::Parse(e) => Some(e),
            Error::Io { .. } => None,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Parse(e) => write!(f, "{}", e),
            Error::Io { path, source } => {
                write!(f, "failed to read {}: {}", path.display(), source)
            }
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Parse(e) => Some(e),
            Error::Io { source, .. } => Some(source),
        }
    }
}

impl From<ParseError> for Error {
    fn from(e: ParseError) -> Self {
        Error::Parse(e)
    }
}

/// Compute 1-based (line, col) for a 0-based byte offset.
pub(crate) fn line_col(source: &str, offset: usize) -> (usize, usize) {
    let offset = offset.min(source.len());
    let before = &source[..offset];
    let line = before.bytes().filter(|&b| b == b'\n').count() + 1;
    let line_start = before.rfind('\n').map(|i| i + 1).unwrap_or(0);
    let col = before[line_start..].chars().count() + 1;
    (line, col)
}

/// Extract the 1-based `line`-th source line (without trailing newline).
pub(crate) fn source_line(source: &str, line: usize) -> &str {
    source.lines().nth(line.saturating_sub(1)).unwrap_or("")
}