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_stdFirst: 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 withoutalloc.- 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 (optionalcore::simdacceleration 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, withconstconstruction forstaticitems. - Allocation-Free Constants: The owned types store
Cow<'static, str>, soSafeHtml::from_constant("...")andempty()areconstand never allocate.Identifier::from_constanteven validates at compile time. - Context-Aware Escapers: Beyond HTML text/quoted attributes: unquoted attribute values, JavaScript string literals, JSON in
<script>blocks, CSSurl(...), and strict RFC 3986 percent-encoding with customEncodeSets and round-trippercent_decode. - Ecosystem Integration: Optional support for
alloc(for ergonomic string wrappers) andserde(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., blocksjavascript:anddata:with script payloads) when embedded inhreforsrcattributes.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 forstyleattributes.SafeStyleSheet: A complete CSS style sheet, built from validated selectors andSafeStylerules (SafeStyleSheet::from_style_rule), safe for<style>elements.Identifier: A validated HTML identifier ([A-Za-z][A-Za-z0-9_-]*) forid/name/classattributes, 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 ;
// 1. Escaping untrusted user input
let untrusted_input = "<script>alert(1)</script>";
let safe_html = escape;
// The output safely escapes HTML sensitive characters
assert_eq!;
// 2. Safely concatenating HTML
let mut template = from_constant;
template += &safe_html;
template += &from_constant;
assert_eq!;
// 3. Sanitizing untrusted URLs
let dangerous_url = "javascript:alert(1)";
let safe_url = sanitize;
// Dangerous URLs are neutralized to a safe placeholder
assert_eq!;
// 4. Appending untrusted query parameters safely
let mut search = sanitize;
search.push_query_param;
assert_eq!;
// 5. Building CSS safely
use ;
let style = from_properties;
let sheet = from_style_rule.unwrap;
assert_eq!;
// 6. Part-based interpolation: safe types pass through, raw values escape
use ;
let id = from_constant; // validated at compile time
let gt = from_constant;
let row = safe_html_cat!;
assert_eq!;
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 ;
// Escape into a stack buffer; the safe-type wrap needs no `unsafe`.
let mut buf = ;
let name = escape_into.unwrap;
assert_eq!;
// URL sanitizing is allocation-free: the input is borrowed verbatim,
// or the static innocuous placeholder is returned.
let url = sanitize;
assert_eq!;
// Stream a mix of safe fragments and escaped values into a fixed buffer.
let mut out = ;
let mut w = new;
safe_html_write!
.unwrap;
assert_eq!;
// Constants live in statics, validated where possible.
use IdentifierStr;
static MENU_ID: &IdentifierStr = from_constant;
assert_eq!;
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).EncodeSetbuilds customconstallowed-sets, andpercent_decoderound-trips.percent_escape_css_url: Safely embed dynamic URLs inside CSSurl(...)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-allocationDisplayadapters —format!("<p>{}</p>", html_escaped(user_input))escapes inline with no intermediateString.
Development
License
Dual-licensed under MIT or Apache-2.0.