safehtml 0.2.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.
//!
//! ## Migration Hazard: Double Escaping
//!
//! `String`/`&str` values interpolated as parts (in [`safe_html_cat!`],
//! [`safe_html_write!`], [`safe_html_format!`], [`safe_html_format_to!`],
//! and [`SafeHtmlBuilder::push`]) are **always HTML-escaped** — that is the
//! right default, because a bare string carries no safety contract.
//!
//! During incremental migration of an existing codebase, however, helper
//! functions often still return *already-escaped* `String`s (e.g. a legacy
//! `money()` or `select()` helper built on `format!`). Passing such a value
//! as a part escapes it **again**: it compiles cleanly and only shows up at
//! runtime as visible `&amp;amp;` / `&amp;lt;` artifacts. The type system
//! cannot catch this, precisely because `String` must stay "untrusted".
//!
//! The fix is to move the trust boundary into the helper: have it return
//! [`SafeHtml`] (built with [`safe_html_format!`]/[`safe_html_cat!`], or —
//! after an audit — `unsafe { SafeHtml::from_string_unchecked(..) }`)
//! instead of `String`. Until a helper is converted, do **not** pass its
//! output as a part. Rule of thumb: any `String` crossing a part boundary
//! must be raw, unescaped text.
//!
//! **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;

#[cfg(feature = "alloc")]
mod builder;
mod css;
mod escape;
mod format;
mod ident;
mod parts;
mod percent;
mod str_types;
mod url;
mod writer;

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub use builder::SafeHtmlBuilder;
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::*;

/// Implementation details of the crate macros ([`safe_html_cat!`],
/// [`safe_html_format!`], [`safe_html_format_to!`]).
///
/// Not public API: there are no semver guarantees, and calling these
/// directly can mint safe-type values without their contracts being
/// upheld. The `unsafe` needed by the macro expansions lives here (and in
/// [`SafeHtmlBuilder`]) so that consumer crates with
/// `#![forbid(unsafe_code)]` can use the macros.
#[doc(hidden)]
pub mod __private {
    pub use crate::format::{
        check_named_format, check_positional_format, format_named_to, format_positional_to,
        has_brace, unit,
    };
    #[cfg(feature = "alloc")]
    pub use crate::format::{format_named, format_positional};
    pub use crate::parts::DynPart;
    #[cfg(feature = "alloc")]
    pub use crate::parts::cat_from_parts;

    /// Wraps macro-built output as [`SafeHtml`](crate::SafeHtml).
    #[cfg(feature = "alloc")]
    pub fn finish_safe_html(html: crate::alloc::string::String) -> crate::SafeHtml {
        // SAFETY: only called from this crate's macro expansions, which
        // route every part through `SafeHtmlPart` (already-safe types
        // verbatim, untrusted text escaped) and treat only string literals
        // as trusted markup.
        unsafe { crate::SafeHtml::from_string_unchecked(html) }
    }
}

#[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.
/// Strings are *always* escaped — never pass a pre-escaped `String` (see
/// "Migration Hazard: Double Escaping" in the crate docs). For
/// template-shaped construction prefer
/// [`safe_html_format!`](crate::safe_html_format).
#[cfg(feature = "alloc")]
#[macro_export]
macro_rules! safe_html_cat {
    () => {
        $crate::SafeHtml::empty()
    };
    ($($val:expr),+ $(,)?) => {
        $crate::__private::cat_from_parts(&[$(&$val as &dyn $crate::__private::DynPart),+])
    };
}

/// 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;