safehtml 0.1.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
Documentation
//! Strict RFC 3986 percent-encoding for URL components and CSS `url(...)`
//! contexts (zero-allocation core).

/// Builds a 256-entry table of bytes allowed to pass through percent-encoding
/// unchanged: ASCII alphanumerics, the RFC 3986 unreserved characters, plus
/// any bytes in `extra`.
const fn build_allowed_table(extra: &[u8]) -> [bool; 256] {
    let mut table = [false; 256];
    let mut b = 0usize;
    while b < 256 {
        let c = b as u8;
        table[b] = c.is_ascii_alphanumeric() || matches!(c, b'-' | b'.' | b'_' | b'~');
        b += 1;
    }
    let mut i = 0;
    while i < extra.len() {
        table[extra[i] as usize] = true;
        i += 1;
    }
    table
}

static URL_COMPONENT_ALLOWED: [bool; 256] = build_allowed_table(&[]);
static CSS_URL_ALLOWED: [bool; 256] = build_allowed_table(b"/:?#[]@!$&*+=%");

const HEX_UPPER: &[u8; 16] = b"0123456789ABCDEF";

/// Writes `%XX` for a single byte without invoking the `core::fmt` formatting
/// machinery (much cheaper than `write!(w, "%{:02X}", b)`).
#[inline]
fn write_pct_encoded<W: core::fmt::Write>(w: &mut W, b: u8) -> core::fmt::Result {
    w.write_char('%')?;
    w.write_char(HEX_UPPER[(b >> 4) as usize] as char)?;
    w.write_char(HEX_UPPER[(b & 0x0F) as usize] as char)
}

/// Shared percent-encoding loop: passes through bytes flagged in `table`,
/// `%XX`-encodes everything else, writing allowed runs in bulk.
///
/// All allowed bytes are ASCII and every byte of a multi-byte UTF-8 character
/// is escaped individually, so the bulk slices always fall on character
/// boundaries.
fn percent_encode_with_table<W: core::fmt::Write>(
    text: &str,
    table: &[bool; 256],
    mut w: W,
) -> core::fmt::Result {
    let bytes = text.as_bytes();
    let mut last = 0;
    for (idx, &b) in bytes.iter().enumerate() {
        if !table[b as usize] {
            if idx > last {
                w.write_str(text.get(last..idx).unwrap_or(""))?;
            }
            write_pct_encoded(&mut w, b)?;
            last = idx + 1;
        }
    }
    if last < bytes.len() {
        w.write_str(text.get(last..).unwrap_or(""))?;
    }
    Ok(())
}

/// Percent-escapes characters in a URL for safe embedding in CSS contexts (like
/// `url(...)`).
///
/// **Allowed characters (passed through unchanged)**:
/// - ASCII alphanumerics `[0-9a-zA-Z]`
/// - RFC 3986 unreserved characters: `-`, `.`, `_`, `~`
/// - RFC 3986 reserved characters (excluding quotes/parens/commas): `/`, `:`,
///   `?`, `#`, `[`, `]`, `@`, `!`, `$`, `&`, `*`, `+`, `=`, `%`
///
/// **Escaped characters**:
/// All other bytes are percent-encoded to `%XX`. Note that `%` itself is
/// allowed through, so already-encoded input is not double-encoded.
///
/// Optimized to write safe ASCII substrings in bulk with zero allocations.
pub fn percent_escape_css_url_to<W: core::fmt::Write>(url: &str, w: W) -> core::fmt::Result {
    percent_encode_with_table(url, &CSS_URL_ALLOWED, w)
}

/// Percent-encodes a string for safe use as a URL component (e.g., a query
/// parameter value).
///
/// **Allowed characters (passed through unchanged)**:
/// - ASCII alphanumerics `[0-9a-zA-Z]`
/// - RFC 3986 unreserved characters: `-`, `.`, `_`, `~`
///
/// **Escaped characters**:
/// All other bytes, including reserved characters like `&`, `=`, `?`, and `/`,
/// are percent-encoded to `%XX`. This prevents query parameter injection (e.g.,
/// when embedding user input in `?q=USER_INPUT`).
pub fn url_encode_component_to<W: core::fmt::Write>(text: &str, w: W) -> core::fmt::Result {
    percent_encode_with_table(text, &URL_COMPONENT_ALLOWED, w)
}

/// Percent-encodes a string for safe use as a URL component (e.g. query
/// parameter value).
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn url_encode_component(text: &str) -> alloc::string::String {
    let mut s = alloc::string::String::with_capacity(text.len());
    let _ = url_encode_component_to(text, &mut s);
    s
}

/// Percent-escapes characters in a URL for safe embedding in CSS contexts.
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn percent_escape_css_url(url: &str) -> alloc::string::String {
    let mut s = alloc::string::String::with_capacity(url.len());
    let _ = percent_escape_css_url_to(url, &mut s);
    s
}

// -----------------------------------------------------------------------------
// Public encode-set API and percent-decoding
// -----------------------------------------------------------------------------

/// A `const`-buildable set of ASCII bytes allowed to pass through
/// percent-encoding unchanged; every other byte is encoded as `%XX`.
///
/// Start from a base set and refine it with [`allow`](EncodeSet::allow) /
/// [`disallow`](EncodeSet::disallow) in `const` context:
///
/// ```rust
/// use safehtml::{EncodeSet, percent_encode_to};
///
/// // Path segments: unreserved characters plus a few sub-delimiters.
/// const PATH_SEGMENT: EncodeSet = EncodeSet::UNRESERVED.allow_all(b"!$&'()*+,;=:@");
///
/// let mut out = String::new();
/// percent_encode_to("a b:c/d", &PATH_SEGMENT, &mut out).unwrap();
/// assert_eq!(out, "a%20b:c%2Fd");
/// ```
#[derive(Clone, Copy)]
pub struct EncodeSet {
    table: [bool; 256],
}

impl EncodeSet {
    /// Only the RFC 3986 unreserved characters pass through: ASCII
    /// alphanumerics and `-`, `.`, `_`, `~`. The strictest base set, used by
    /// [`url_encode_component_to`].
    pub const UNRESERVED: EncodeSet = EncodeSet {
        table: build_allowed_table(&[]),
    };

    /// The set used by [`percent_escape_css_url_to`]: unreserved plus the
    /// RFC 3986 reserved characters that are safe inside CSS `url("...")`.
    pub const CSS_URL: EncodeSet = EncodeSet {
        table: build_allowed_table(b"/:?#[]@!$&*+=%"),
    };

    /// Returns a copy of the set that additionally passes `b` through.
    ///
    /// # Panics
    ///
    /// Panics (at compile time in `const` context) if `b` is not ASCII:
    /// allowing a non-ASCII byte through could split multi-byte UTF-8
    /// characters in the output.
    #[must_use]
    pub const fn allow(mut self, b: u8) -> EncodeSet {
        assert!(b.is_ascii(), "EncodeSet may only allow ASCII bytes");
        self.table[b as usize] = true;
        self
    }

    /// Returns a copy of the set that additionally passes every byte in
    /// `bytes` through. Panics like [`allow`](EncodeSet::allow) on
    /// non-ASCII bytes.
    #[must_use]
    pub const fn allow_all(mut self, bytes: &[u8]) -> EncodeSet {
        let mut i = 0;
        while i < bytes.len() {
            assert!(bytes[i].is_ascii(), "EncodeSet may only allow ASCII bytes");
            self.table[bytes[i] as usize] = true;
            i += 1;
        }
        self
    }

    /// Returns a copy of the set that percent-encodes `b`.
    #[must_use]
    pub const fn disallow(mut self, b: u8) -> EncodeSet {
        self.table[b as usize] = false;
        self
    }

    /// True if `b` passes through this set unencoded.
    pub const fn is_allowed(&self, b: u8) -> bool {
        self.table[b as usize]
    }
}

/// Percent-encodes `text` against a caller-chosen [`EncodeSet`], writing to
/// `w`. Zero-allocation core of [`percent_encode`].
pub fn percent_encode_to<W: core::fmt::Write>(
    text: &str,
    set: &EncodeSet,
    w: W,
) -> core::fmt::Result {
    percent_encode_with_table(text, &set.table, w)
}

/// Allocating convenience form of [`percent_encode_to`].
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn percent_encode(text: &str, set: &EncodeSet) -> alloc::string::String {
    let mut s = alloc::string::String::with_capacity(text.len());
    let _ = percent_encode_to(text, set, &mut s);
    s
}

/// A zero-allocation iterator over the bytes of a percent-decoded string.
///
/// Produced by [`percent_decode`]. Well-formed `%XX` sequences (upper- or
/// lowercase hex) decode to their byte; malformed sequences (`%`, `%z`, a
/// truncated `%4`) pass through literally, matching the behavior of the
/// `percent-encoding` crate. The output is raw bytes: decoded data is not
/// guaranteed to be valid UTF-8.
#[derive(Debug, Clone)]
pub struct PercentDecode<'a> {
    bytes: &'a [u8],
}

/// Percent-decodes `input`, returning a byte iterator.
///
/// ```rust
/// use safehtml::percent_decode;
///
/// let decoded: Vec<u8> = percent_decode("a%20b%2fc%").collect();
/// assert_eq!(decoded, b"a b/c%");
/// ```
pub fn percent_decode(input: &str) -> PercentDecode<'_> {
    PercentDecode {
        bytes: input.as_bytes(),
    }
}

#[inline]
const fn hex_value(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

impl Iterator for PercentDecode<'_> {
    type Item = u8;

    fn next(&mut self) -> Option<u8> {
        let (&first, rest) = self.bytes.split_first()?;
        if first == b'%'
            && let (Some(&h), Some(&l)) = (rest.first(), rest.get(1))
            && let (Some(hi), Some(lo)) = (hex_value(h), hex_value(l))
        {
            self.bytes = rest.get(2..).unwrap_or(&[]);
            return Some(hi << 4 | lo);
        }
        self.bytes = rest;
        Some(first)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.bytes.len().div_ceil(3), Some(self.bytes.len()))
    }
}

/// Percent-decodes `input` into a byte vector.
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn percent_decode_bytes(input: &str) -> alloc::vec::Vec<u8> {
    percent_decode(input).collect()
}

/// Percent-decodes `input` into a `String`, replacing invalid UTF-8
/// sequences with U+FFFD.
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn percent_decode_utf8_lossy(input: &str) -> alloc::string::String {
    let bytes = percent_decode_bytes(input);
    match alloc::string::String::from_utf8_lossy(&bytes) {
        alloc::borrow::Cow::Borrowed(_) => {
            alloc::string::String::from_utf8(bytes).unwrap_or_default()
        }
        alloc::borrow::Cow::Owned(s) => s,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Rebuilding the allowed tables at runtime must reproduce the
    /// compile-time statics, and the base table must match the RFC 3986
    /// unreserved set exactly.
    #[test]
    fn allowed_tables_rebuild_and_match_spec() {
        assert_eq!(build_allowed_table(&[]), URL_COMPONENT_ALLOWED);
        assert_eq!(build_allowed_table(b"/:?#[]@!$&*+=%"), CSS_URL_ALLOWED);

        for b in 0..=0xFFu8 {
            let unreserved = b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~');
            assert_eq!(
                URL_COMPONENT_ALLOWED[b as usize], unreserved,
                "url-component table disagrees at {b:#04x}"
            );
            let css_extra = b"/:?#[]@!$&*+=%".contains(&b);
            assert_eq!(
                CSS_URL_ALLOWED[b as usize],
                unreserved || css_extra,
                "css-url table disagrees at {b:#04x}"
            );
        }
    }
}