safehtml 0.1.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
Documentation
//! CSS style validation: property names, property values, and selectors
//! (zero-allocation, regex-free).

/// The innocuous value substituted for CSS property values that fail
/// validation, mirroring Go safehtml's `InnocuousPropertyValue`
/// (`zGoSafezInvalidPropertyValue`); the prefix is adjusted to this crate's
/// `zSafez` convention.
pub const INNOCUOUS_PROPERTY_VALUE: &str = "zSafezInvalidPropertyValue";

/// Validates a CSS property *name*: one or more ASCII letters or hyphens
/// (e.g. `background-color`).
pub fn is_safe_style_property_name(name: &str) -> bool {
    !name.is_empty() && name.chars().all(|c| c.is_ascii_alphabetic() || c == '-')
}

/// Validates a CSS property *value* against the safe regular-property pattern
/// used by Go safehtml (`^(?:[*/]?(?:[0-9a-zA-Z+-.!#%_ \t]|$))*$`), implemented
/// as a linear scan.
///
/// Allowed: ASCII alphanumerics and `+`, `-`, `.`, `!`, `#`, `%`, `_`, space,
/// and tab. The characters `*` and `/` are permitted only when not adjacent to
/// another `*` or `/`, which blocks CSS comment markers (`/*`, `*/`, `//`).
/// Everything else — parentheses, quotes, commas, colons, semicolons, `@`,
/// angle brackets — is rejected, preventing function calls (`url(...)`,
/// `expression(...)`), string breakouts, and declaration injection.
pub fn is_safe_style_property_value(value: &str) -> bool {
    let mut prev_was_star_or_slash = false;
    for c in value.chars() {
        if c.is_ascii_alphanumeric()
            || matches!(c, '+' | '-' | '.' | '!' | '#' | '%' | '_' | ' ' | '\t')
        {
            prev_was_star_or_slash = false;
        } else if c == '*' || c == '/' {
            if prev_was_star_or_slash {
                return false;
            }
            prev_was_star_or_slash = true;
        } else {
            return false;
        }
    }
    true
}

/// Validates a CSS selector for use in a [`SafeStyleSheet`](crate::SafeStyleSheet)
/// style rule.
///
/// Allows the characters used by standard selectors (element names, classes,
/// IDs, pseudo-classes, combinators, attribute selectors with quoted values)
/// while rejecting everything that could escape the selector context:
/// braces, backslashes, `<`, `/` (comments), `;`, and `@`. Parentheses,
/// brackets, and quotes must be balanced.
pub fn is_safe_css_selector(selector: &str) -> bool {
    if selector.is_empty() {
        return false;
    }
    let mut paren_depth: u32 = 0;
    let mut bracket_depth: u32 = 0;
    let mut in_quote: Option<char> = None;
    for c in selector.chars() {
        if let Some(q) = in_quote {
            if c == q {
                in_quote = None;
            } else if matches!(c, '<' | '>' | '{' | '}' | '\\') {
                return false;
            }
            continue;
        }
        match c {
            '"' | '\'' => in_quote = Some(c),
            '(' => paren_depth += 1,
            ')' => {
                if paren_depth == 0 {
                    return false;
                }
                paren_depth -= 1;
            }
            '[' => bracket_depth += 1,
            ']' => {
                if bracket_depth == 0 {
                    return false;
                }
                bracket_depth -= 1;
            }
            c if c.is_ascii_alphanumeric() => {}
            '-' | '_' | '#' | '.' | ':' | '*' | ' ' | '\t' | '\n' | '\r' | ',' | '>' | '+'
            | '~' | '=' | '^' | '$' | '|' => {}
            _ => return false,
        }
    }
    paren_depth == 0 && bracket_depth == 0 && in_quote.is_none()
}