safehtml 0.1.0

A high-performance, no_std Rust library for Type-Driven Security (XSS and injection prevention).
Documentation

safehtml

safehtml is a high-performance, no_std Rust library designed to prevent Cross-Site Scripting (XSS) vulnerabilities through Type-Driven Security (validation by construction). It is a Rust implementation of Google's safe-html-types contracts, as seen in the open-source Go safehtml package.

By utilizing strongly-typed wrapper structures (SafeHtml, SafeUrl, SafeScript, SafeStyle, SafeStyleSheet, TrustedResourceUrl, Identifier), this library ensures that security contracts are enforced at compile-time. If a function requires a SafeHtml argument, it is impossible for a developer to accidentally pass an unescaped, untrusted string into it.

Features

  • XSS Prevention by Construction: Enforce strict security contracts at compile time.
  • no_std First: Designed for embedded systems and core libraries. The core escaping and validation functions require zero allocations, and the borrowed safe types carry the full contracts without alloc.
  • Panic-Free & DoS Resilient: Core parsing paths are entirely panic-free and do not use regular expressions, preventing ReDoS attacks.
  • High Performance: O(N) table-driven linear scanning with a portable SWAR word scanner and bulk slice-writing, on stable Rust (optional core::simd acceleration on nightly). Clean-input HTML escaping runs at multiple GiB/s.
  • Borrowed Safe Types: #[repr(transparent)] borrowed twins (SafeHtmlStr, SafeUrlStr, ...) carry the contracts without allocation, with const construction for static items.
  • Allocation-Free Constants: The owned types store Cow<'static, str>, so SafeHtml::from_constant("...") and empty() are const and never allocate. Identifier::from_constant even validates at compile time.
  • Context-Aware Escapers: Beyond HTML text/quoted attributes: unquoted attribute values, JavaScript string literals, JSON in <script> blocks, CSS url(...), and strict RFC 3986 percent-encoding with custom EncodeSets and round-trip percent_decode.
  • Ecosystem Integration: Optional support for alloc (for ergonomic string wrappers) and serde (for API serialization).
  • Heavily Verified: Differential test suites against naive reference implementations, six libFuzzer targets with differential and invariant oracles, and ~99% line coverage with 100% function coverage.

Feature Flags

Feature Default Description
alloc yes Heap-allocated wrapper types and String-returning convenience functions.
serde no Serialize/Deserialize for the wrapper types. Note: only SafeUrl and Identifier re-validate on deserialize; the other types trust their input — see the crate docs' Security Model section.
simd no core::simd escape scanners (16 bytes/step, ~2x on clean input). Requires a nightly toolchain.

Core Types

All six contract types from Google's safe-html-types are implemented, plus Identifier:

  • SafeHtml: A string guaranteed to be safe for interpolation into an HTML document. Malicious input must be escaped (SafeHtml::escape) or constructed from vetted sources (SafeHtml::from_constant).
  • SafeUrl: A URL guaranteed not to execute malicious scripts (i.e., blocks javascript: and data: with script payloads) when embedded in href or src attributes.
  • TrustedResourceUrl: A URL vetted by the developer to be completely safe to load external resources from (e.g., <script src="...">).
  • SafeScript: A string containing JavaScript code that is safe to evaluate. Includes utilities to safely escape JSON for inline <script> tags without breaking out of the context.
  • SafeStyle: A sequence of complete CSS declarations (name:value;), built with validated property names and sanitized values (SafeStyle::from_properties), safe for style attributes.
  • SafeStyleSheet: A complete CSS style sheet, built from validated selectors and SafeStyle rules (SafeStyleSheet::from_style_rule), safe for <style> elements.
  • Identifier: A validated HTML identifier ([A-Za-z][A-Za-z0-9_-]*) for id/name/class attributes, HTML- and CSS-selector-inert by construction.

Every owned type has a borrowed, no_std twin (SafeHtmlStr, SafeUrlStr, SafeScriptStr, TrustedResourceUrlStr, SafeStyleStr, SafeStyleSheetStr, IdentifierStr), related the way String relates to str: the owned type Derefs to it, and ToOwned/From convert back.

Example Usage

use safehtml::{SafeHtml, SafeUrl};

// 1. Escaping untrusted user input
let untrusted_input = "<script>alert(1)</script>";
let safe_html = SafeHtml::escape(untrusted_input);

// The output safely escapes HTML sensitive characters
assert_eq!(safe_html.as_str(), "&lt;script&gt;alert(1)&lt;/script&gt;");

// 2. Safely concatenating HTML
let mut template = SafeHtml::from_constant("<div>");
template += &safe_html;
template += &SafeHtml::from_constant("</div>");

assert_eq!(template.as_str(), "<div>&lt;script&gt;alert(1)&lt;/script&gt;</div>");

// 3. Sanitizing untrusted URLs
let dangerous_url = "javascript:alert(1)";
let safe_url = SafeUrl::sanitize(dangerous_url);

// Dangerous URLs are neutralized to a safe placeholder
assert_eq!(safe_url.as_str(), "about:invalid#zSafez");

// 4. Appending untrusted query parameters safely
let mut search = SafeUrl::sanitize("https://example.com/search");
search.push_query_param("q", "a&b=c");
assert_eq!(search.as_str(), "https://example.com/search?q=a%26b%3Dc");

// 5. Building CSS safely
use safehtml::{SafeStyle, SafeStyleSheet};
let style = SafeStyle::from_properties(&[("width", "1em"), ("color", "#f00")]);
let sheet = SafeStyleSheet::from_style_rule("p.note", &style).unwrap();
assert_eq!(sheet.as_str(), "p.note{width:1em;color:#f00;}");

// 6. Part-based interpolation: safe types pass through, raw values escape
use safehtml::{Identifier, safe_html_cat};
let id = Identifier::from_constant("user-name"); // validated at compile time
let gt = SafeHtml::from_constant(">");
let row = safe_html_cat!(SafeHtml::from_constant("<td id="), id, gt, "Bob & Alice");
assert_eq!(row.as_str(), "<td id=user-name>Bob &amp; Alice");

Embedded / Zero-Allocation Usage

Everything works without a heap. Escaping writes into caller-provided buffers, sanitizers borrow their input, and safe_html_write! streams into any core::fmt::Write:

use safehtml::{SafeHtmlStr, SafeUrlStr, SliceWriter, safe_html_write};

// Escape into a stack buffer; the safe-type wrap needs no `unsafe`.
let mut buf = [0u8; 64];
let name = SafeHtmlStr::escape_into("<Bob>", &mut buf).unwrap();
assert_eq!(name.as_str(), "&lt;Bob&gt;");

// URL sanitizing is allocation-free: the input is borrowed verbatim,
// or the static innocuous placeholder is returned.
let url = SafeUrlStr::sanitize("https://example.com");
assert_eq!(url.as_str(), "https://example.com");

// Stream a mix of safe fragments and escaped values into a fixed buffer.
let mut out = [0u8; 128];
let mut w = SliceWriter::new(&mut out);
safe_html_write!(
    w,
    SafeHtmlStr::from_constant("<a href=\""),
    url,
    SafeHtmlStr::from_constant("\">"),
    "5 < 6",
    SafeHtmlStr::from_constant("</a>")
)
.unwrap();
assert_eq!(w.as_str(), "<a href=\"https://example.com\">5 &lt; 6</a>");

// Constants live in statics, validated where possible.
use safehtml::IdentifierStr;
static MENU_ID: &IdentifierStr = IdentifierStr::from_constant("nav-menu");
assert_eq!(MENU_ID.as_str(), "nav-menu");

Advanced Operations

The library provides zero-allocation primitive functions for custom writers (e.g. core::fmt::Write), as well as escaping logic for specific contexts:

  • url_encode_component: Safely encode user input as a URL query parameter (RFC 3986). EncodeSet builds custom const allowed-sets, and percent_decode round-trips.
  • percent_escape_css_url: Safely embed dynamic URLs inside CSS url(...) declarations.
  • escape_json_for_script: Convert valid JSON into a format strictly safe for embedding inside an HTML <script> block (also escapes the U+2028/U+2029 line separators).
  • escape_js_string: Escape untrusted text for JavaScript string literals (quote-agnostic, </script>-breakout-proof).
  • escape_html_unquoted_attribute: Escape values for unquoted HTML attributes, where whitespace, =, and backtick also need encoding.
  • html_escaped / js_string_escaped: Zero-allocation Display adapters — format!("<p>{}</p>", html_escaped(user_input)) escapes inline with no intermediate String.

Development

./build.sh                  # fmt, clippy, tests (stable + nightly simd), no_std build, fuzzing
cargo test --features alloc,serde
cargo bench                 # Criterion benchmarks
cargo llvm-cov --features alloc,serde   # coverage
cargo +nightly fuzz list    # six libFuzzer targets under fuzz/

License

Dual-licensed under MIT or Apache-2.0.