safehtml 0.2.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
Documentation
//! URL validation: regex-free, zero-allocation scheme and content checks.

/// The innocuous URL returned by sanitizers when validation fails.
///
/// Under standard browser behavior, `about:invalid` acts as a safe,
/// non-resolvable URL placeholder that avoids side-effects or untrusted script
/// execution.
pub const INNOCUOUS_URL: &str = "about:invalid#zSafez";

/// Helper function to perform case-insensitive scheme matching.
///
/// Normalizes underscores `_` in the target scheme configuration to dashes `-`
/// (which is standard for URL protocols, but helpful if working with protobuf
/// enum schemes).
fn starts_with_scheme_ignore_case(url: &str, scheme: &str) -> bool {
    if scheme.is_empty() {
        return false;
    }
    let mut url_chars = url.chars();
    for s_char in scheme.chars() {
        let u_char = match url_chars.next() {
            Some(c) => c,
            None => return false,
        };
        // Normalize underscores in the defined scheme names to hyphens
        let s_target = if s_char == '_' { '-' } else { s_char };
        if !u_char
            .to_ascii_lowercase()
            .eq(&s_target.to_ascii_lowercase())
        {
            return false;
        }
    }
    url_chars.next() == Some(':')
}

/// Checks if a MIME type matches one of the allowlisted media MIME types for
/// safe data URLs.
///
/// Allowed MIME types:
/// - `text/plain`
/// - `image/`: bmp, gif, jpeg, jpg, png, tiff, webp, x-icon
/// - `audio/`: 3gpp2, 3gpp, aac, midi, mp3, mp4, mpeg, oga, ogg, opus, x-m4a,
///   x-matroska, x-wav, wav, webm
/// - `video/`: mpeg, mp4, ogg, webm, x-matroska
///
/// HTML (`text/html`) and SVG (`image/svg+xml`) are explicitly excluded because
/// they can contain execution scripts. Panic-hardened: validates UTF-8 index
/// boundaries before slicing.
fn is_safe_mime_type(mime: &str) -> bool {
    if mime.eq_ignore_ascii_case("text/plain") {
        return true;
    }
    if mime.len() > 6 && mime.is_char_boundary(6) {
        if mime[..6].eq_ignore_ascii_case("audio/") {
            let sub = &mime[6..];
            return eq_any_ignore_case(
                sub,
                &[
                    "3gpp2",
                    "3gpp",
                    "aac",
                    "midi",
                    "mp3",
                    "mp4",
                    "mpeg",
                    "oga",
                    "ogg",
                    "opus",
                    "x-m4a",
                    "x-matroska",
                    "x-wav",
                    "wav",
                    "webm",
                ],
            );
        }
        if mime[..6].eq_ignore_ascii_case("image/") {
            let sub = &mime[6..];
            return eq_any_ignore_case(
                sub,
                &["bmp", "gif", "jpeg", "jpg", "png", "tiff", "webp", "x-icon"],
            );
        }
        if mime[..6].eq_ignore_ascii_case("video/") {
            let sub = &mime[6..];
            return eq_any_ignore_case(sub, &["mpeg", "mp4", "ogg", "webm", "x-matroska"]);
        }
    }
    false
}

/// Helper to match string against candidates case-insensitively.
fn eq_any_ignore_case(s: &str, candidates: &[&str]) -> bool {
    candidates.iter().any(|c| s.eq_ignore_ascii_case(c))
}

/// Validates that a string is a safe base64-encoded data URL.
///
/// Layout format: `data:<mime-type>;base64,<base64-data>`
/// Validates both the MIME type and the structural base64 alphabet
/// (`[a-zA-Z0-9+/]=*`).
fn is_safe_data_url(url: &str) -> bool {
    // Prefix check
    if !url
        .get(..5)
        .is_some_and(|s| s.eq_ignore_ascii_case("data:"))
    {
        return false;
    }
    let rest = &url[5..];
    let semi_idx = match rest.find(';') {
        Some(idx) => idx,
        None => return false,
    };
    let mime = &rest[..semi_idx];
    let after_semi = &rest[semi_idx..];
    if !after_semi
        .get(..8)
        .is_some_and(|s| s.eq_ignore_ascii_case(";base64,"))
    {
        return false;
    }
    let b64_data = &after_semi[8..];
    if !is_safe_mime_type(mime) {
        return false;
    }
    if b64_data.is_empty() {
        return false;
    }

    // Validate base64 structure: must only contain [a-zA-Z0-9+/] and optional '='
    // padding at the end.
    let mut chars = b64_data.chars();
    while let Some(c) = chars.next() {
        if c.is_ascii_alphanumeric() || c == '+' || c == '/' {
            continue;
        } else if c == '=' {
            // Once '=' is seen, all remaining chars must be '=' padding.
            for p in chars {
                if p != '=' {
                    return false;
                }
            }
            break;
        } else {
            return false;
        }
    }
    true
}

/// Validates that a URL starts with a well-formed scheme that is not
/// `javascript:`, or contains no scheme (relative URL).
///
/// This implements the `SanitizeBlockOnlyJavaScript` logic. It permits all
/// schemeless paths (e.g. `/foo/bar`, `path/to:file`) and all explicit
/// non-javascript schemes (like `http:`, `https:`, `foo:` — including `data:`
/// and `vbscript:`; use [`is_safe_url_restrictive`] for an allowlist).
///
/// Protocol-relative URLs (`//host/path`) are treated as relative and
/// accepted: they cannot change the scheme, though they do change the origin.
///
/// ### Security Mechanism
/// To prevent entity-bypass attacks where the browser interprets HTML-encoded
/// entities like `javascript&colon;` as a protocol separator, any incidence of
/// `&` or `:` *before* a path separator (`/`, `?`, or `#`) is analyzed.
/// If an ampersand `&` is encountered before any slash/query/hash, it is
/// rejected. Panic-hardened: utilizes boundary-safe `.get` when extracting
/// scheme prefixes.
pub fn is_safe_url_block_javascript(url: &str) -> bool {
    for (idx, c) in url.char_indices() {
        if c == '/' || c == '?' || c == '#' {
            // Path separator encountered first; this is a schemeless relative URL.
            return true;
        }
        if c == ':' || c == '&' {
            if c == '&' {
                // Ampersand before path separator could lead to HTML entity bypasses. Block it.
                return false;
            }
            // Colon found. The text preceding the colon is the scheme.
            let scheme = match url.get(..idx) {
                Some(s) => s,
                None => return false,
            };
            if scheme.is_empty() {
                return false;
            }
            // Scheme must consist only of ASCII alphanumerics, '+', '-', '.'
            for sc in scheme.chars() {
                if !sc.is_ascii_alphanumeric() && sc != '+' && sc != '-' && sc != '.' {
                    return false;
                }
            }
            // Reject javascript:
            return !scheme.eq_ignore_ascii_case("javascript");
        }
    }
    true
}

/// Validates that a URL is safe using the default allowed schemes or is
/// relative.
///
/// Default allowed schemes: `http`, `https`, `mailto`, `ftp`, or safe base64
/// media data URLs. Other custom/unvetted schemes are rejected.
///
/// Protocol-relative URLs (`//host/path`) are treated as relative and
/// accepted: they cannot change the scheme, though they do change the origin.
pub fn is_safe_url_restrictive(url: &str) -> bool {
    is_safe_url_restrictive_with_schemes(url, &[] as &[&str])
}

/// Validates that a URL is safe, additionally permitting the specified custom
/// schemes.
///
/// Performs the restrictive check but allows overriding with a list of custom
/// schemes (e.g. `["git", "ssh"]`).
///
/// # Security
///
/// The extra schemes are trusted verbatim — passing `"javascript"` re-allows
/// `javascript:` URLs. Only pass compile-time constant scheme lists.
pub fn is_safe_url_restrictive_with_schemes<S: AsRef<str>>(url: &str, extra_schemes: &[S]) -> bool {
    // Check if it starts with any of the custom schemes.
    for scheme in extra_schemes {
        if starts_with_scheme_ignore_case(url, scheme.as_ref()) {
            return true;
        }
    }

    // Default schemes check
    if starts_with_scheme_ignore_case(url, "http")
        || starts_with_scheme_ignore_case(url, "https")
        || starts_with_scheme_ignore_case(url, "mailto")
        || starts_with_scheme_ignore_case(url, "ftp")
    {
        return true;
    }

    // Data URL check
    if is_safe_data_url(url) {
        return true;
    }

    // Relative URL check: ensure there is no colon or entity bypass character
    // before a path separator.
    for c in url.chars() {
        if c == '/' || c == '?' || c == '#' {
            return true;
        }
        if c == ':' || c == '&' {
            return false;
        }
    }
    true
}