safehtml 0.1.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
Documentation
#![deny(unsafe_op_in_unsafe_fn)]
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(feature = "simd", feature(portable_simd))]

//! # Safehtml
//!
//! A pure Rust, 2024 edition, `no_std`-compatible library that implements
//! safety contracts and validation for strings used in security-sensitive web
//! contexts (HTML, CSS, JavaScript, and URLs).
//!
//! The design is a Rust implementation of Google's
//! [safe-html-types](https://github.com/google/safe-html-types) contracts (as
//! seen in the C++ and Go `safehtml` libraries), covering all six contract
//! types: [`SafeHtml`], [`SafeScript`], [`SafeStyle`], [`SafeStyleSheet`],
//! [`SafeUrl`], and [`TrustedResourceUrl`]. It is engineered specifically to
//! prevent Cross-Site Scripting (XSS) and code-injection vulnerabilities by
//! construction.
//!
//! ## Embedded & `no_std` Suitability
//!
//! This crate is highly optimized for embedded and resource-constrained
//! environments:
//! 1. **Zero-Allocation Core**: All validation and escaping logic operates
//!    directly on `&str` and writes to implementations of [`core::fmt::Write`].
//!    This allows formatting directly into stack-allocated buffers (e.g.,
//!    `heapless::String` or direct peripheral I/O) without any dynamic memory
//!    allocations.
//! 2. **No Regular Expressions**: Unlike Go and C++ libraries which depend on
//!    heavy, runtime-compiled regex engines, this library implements fast,
//!    deterministic, table-driven linear scans accelerated by a portable SWAR
//!    word scanner (or `core::simd` with the nightly-only `simd` feature).
//!    This minimizes code size and CPU usage; the default build works on
//!    stable Rust with no nightly features.
//! 3. **Borrowed Safe Types Everywhere**: The `#[repr(transparent)]` borrowed
//!    types ([`SafeHtmlStr`], [`SafeUrlStr`], [`SafeScriptStr`],
//!    [`SafeStyleStr`], [`SafeStyleSheetStr`], [`TrustedResourceUrlStr`])
//!    carry the safety contracts without any allocation, so type-driven
//!    security works even without `alloc`. Their `from_constant` constructors
//!    are `const` and usable in `static` items.
//! 4. **Optional `alloc` Feature**: The high-level owned types ([`SafeHtml`],
//!    [`SafeUrl`], [`SafeScript`], [`SafeStyle`], [`SafeStyleSheet`],
//!    [`TrustedResourceUrl`]) which enforce safety boundaries via type-safety
//!    are gated under the `alloc` feature (enabled by default). They store
//!    `Cow<'static, str>`, so `from_constant`/`empty` are `const` and
//!    allocation-free; each owned type [`Deref`](core::ops::Deref)s to its
//!    borrowed counterpart. Disable default features
//!    (`default-features = false`) to compile in a pure, alloc-free
//!    environment.
//! 5. **Optional `serde` Feature**: Provides optional
//!    serialization/deserialization with built-in validation checks.
//!
//! ## Feature Flags
//!
//! | Feature | Default | Description |
//! |---------|---------|-------------|
//! | `alloc` | yes     | Heap-allocated wrapper types and `String`-returning convenience functions. |
//! | `serde` | no      | `Serialize`/`Deserialize` implementations for the wrapper types. |
//! | `simd`  | no      | `core::simd` scanners (16 bytes/step); requires a nightly toolchain. |
//!
//! ## Security Model
//!
//! Each wrapper type carries a contract: holding an instance means its string
//! value is safe to use in the corresponding sink without further escaping.
//! Instances are created through validating/escaping constructors; the
//! `unsafe fn from_string_unchecked` escape hatches place the burden of proof
//! on the caller and are greppable by design.
//!
//! **Serde caveat**: deserializing [`SafeUrl`] re-validates the value and
//! fails on unsafe input, but deserializing [`SafeHtml`], [`SafeScript`], and
//! [`TrustedResourceUrl`] trusts the input (there is no cheap way to verify
//! "already-safe HTML"). Only deserialize these types from trusted storage or
//! internal services — never directly from user-controlled request bodies.
//!
//! ## Example: Embedded/Alloc-Free Usage
//!
//! ```rust
//! use safehtml::{escape_html_and_coerce_to, is_safe_url_restrictive};
//!
//! // Write HTML directly into a custom buffer (which implements core::fmt::Write)
//! struct SimpleBuffer {
//!     storage: [u8; 128],
//!     len: usize,
//! }
//!
//! impl core::fmt::Write for SimpleBuffer {
//!     fn write_str(&mut self, s: &str) -> core::fmt::Result {
//!         let bytes = s.as_bytes();
//!         if self.len + bytes.len() > self.storage.len() {
//!             return Err(core::fmt::Error);
//!         }
//!         self.storage[self.len..self.len + bytes.len()].copy_from_slice(bytes);
//!         self.len += bytes.len();
//!         Ok(())
//!     }
//! }
//!
//! let mut buf = SimpleBuffer { storage: [0; 128], len: 0 };
//! escape_html_and_coerce_to("Hello <World>", &mut buf).unwrap();
//!
//! // Validate a URL safely without dynamic allocation:
//! let untrusted_url = "https://example.com/api";
//! if is_safe_url_restrictive(untrusted_url) {
//!     // URL is safe to use in href contexts
//! }
//! ```

#[cfg(feature = "alloc")]
pub extern crate alloc;

// Compile the README examples as doctests so the documentation cannot drift
// out of sync with the API.
#[cfg(all(doctest, feature = "alloc"))]
#[doc = include_str!("../README.md")]
pub struct ReadmeDoctests;

mod css;
mod escape;
mod ident;
mod parts;
mod percent;
mod str_types;
mod url;
mod writer;

pub use css::*;
pub use escape::*;
pub use ident::*;
pub use parts::*;
pub use percent::*;
pub use str_types::*;
pub use url::*;
pub use writer::*;

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub mod types;

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub use types::{
    Identifier, SafeHtml, SafeHtmlProto, SafeScript, SafeScriptProto, SafeStyle, SafeStyleProto,
    SafeStyleSheet, SafeStyleSheetProto, SafeUrl, SafeUrlProto, TrustedResourceUrl,
    TrustedResourceUrlProto,
};

/// Concatenates multiple values (both `SafeHtml` and raw values that will be
/// HTML-escaped) into a single `SafeHtml`.
///
/// Automatically escapes standard types and keeps safe types unescaped.
#[cfg(feature = "alloc")]
#[macro_export]
macro_rules! safe_html_cat {
    () => {
        $crate::SafeHtml::empty()
    };
    ($($val:expr),+ $(,)?) => {{
        let mut buf = $crate::alloc::string::String::new();
        $(
            // Writing into a `String` cannot fail.
            let _ = $crate::SafeHtmlPart::write_to(&$val, &mut buf);
        )+
        unsafe { $crate::SafeHtml::from_string_unchecked(buf) }
    }};
}

/// Writes multiple values (both safe types and raw values that will be
/// HTML-escaped) into any [`core::fmt::Write`] — the `no_std`,
/// zero-allocation sibling of [`safe_html_cat!`].
///
/// The first argument is the writer; the rest are parts implementing
/// [`SafeHtmlPart`]. Safe types ([`SafeHtml`], [`SafeHtmlStr`],
/// [`Identifier`]) pass through verbatim; strings and characters are
/// escaped; numbers and booleans are formatted. Evaluates to
/// [`core::fmt::Result`], so a full [`SliceWriter`] surfaces as `Err`.
///
/// ```rust
/// use safehtml::{SafeHtmlStr, SliceWriter, safe_html_write};
///
/// let mut buf = [0u8; 64];
/// let mut w = SliceWriter::new(&mut buf);
/// safe_html_write!(w, SafeHtmlStr::from_constant("<b>"), "5 < 6", 42).unwrap();
/// assert_eq!(w.as_str(), "<b>5 &lt; 642");
/// ```
#[macro_export]
macro_rules! safe_html_write {
    ($w:expr $(,)?) => {{
        let _ = &mut $w;
        core::fmt::Result::Ok(())
    }};
    ($w:expr, $($val:expr),+ $(,)?) => {{
        let w = &mut $w;
        'safe_html_write: {
            $(
                if let core::result::Result::Err(e) = $crate::SafeHtmlPart::write_to(&$val, w) {
                    break 'safe_html_write core::fmt::Result::Err(e);
                }
            )+
            core::fmt::Result::Ok(())
        }
    }};
}

#[cfg(all(feature = "serde", feature = "alloc"))]
mod serde_impl;