Expand description
§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 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:
- Zero-Allocation Core: All validation and escaping logic operates
directly on
&strand writes to implementations ofcore::fmt::Write. This allows formatting directly into stack-allocated buffers (e.g.,heapless::Stringor direct peripheral I/O) without any dynamic memory allocations. - 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::simdwith the nightly-onlysimdfeature). This minimizes code size and CPU usage; the default build works on stable Rust with no nightly features. - 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 withoutalloc. Theirfrom_constantconstructors areconstand usable instaticitems. - Optional
allocFeature: The high-level owned types (SafeHtml,SafeUrl,SafeScript,SafeStyle,SafeStyleSheet,TrustedResourceUrl) which enforce safety boundaries via type-safety are gated under theallocfeature (enabled by default). They storeCow<'static, str>, sofrom_constant/emptyareconstand allocation-free; each owned typeDerefs to its borrowed counterpart. Disable default features (default-features = false) to compile in a pure, alloc-free environment. - Optional
serdeFeature: 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 Strings (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; / &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
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
}Re-exports§
pub extern crate alloc;
Re-exports§
pub use types::Identifier;allocpub use types::SafeHtml;allocpub use types::SafeHtmlProto;allocpub use types::SafeScript;allocpub use types::SafeScriptProto;allocpub use types::SafeStyle;allocpub use types::SafeStyleProto;allocpub use types::SafeStyleSheet;allocpub use types::SafeStyleSheetProto;allocpub use types::SafeUrl;allocpub use types::SafeUrlProto;allocpub use types::TrustedResourceUrl;allocpub use types::TrustedResourceUrlProto;alloc
Modules§
- types
alloc - Heap-allocated safe-type wrappers (
SafeHtml,SafeUrl,SafeScript,TrustedResourceUrl,SafeStyle,SafeStyleSheet) and their proto replicas. Requires theallocfeature.
Macros§
- safe_
html_ cat alloc - Concatenates multiple values (both
SafeHtmland raw values that will be HTML-escaped) into a singleSafeHtml. - safe_
html_ format alloc - Builds a
SafeHtmlfrom a trusted template literal with escaped interpolations, or appends the same to aSafeHtmlBuilder. - safe_
html_ format_ to - Streams a trusted template literal with escaped interpolations into any
core::fmt::Write— theno_std, zero-allocation sibling ofsafe_html_format!. - safe_
html_ write - Writes multiple values (both safe types and raw values that will be
HTML-escaped) into any
core::fmt::Write— theno_std, zero-allocation sibling ofsafe_html_cat!.
Structs§
- Capacity
Error - Error returned when a fixed-size buffer is too small for the output.
- Display
Escaped - A
SafeHtmlPartadapter that HTML-escapes theDisplayoutput of a wrapped value on the fly. Created bydisp. - Encode
Set - A
const-buildable set of ASCII bytes allowed to pass through percent-encoding unchanged; every other byte is encoded as%XX. - Html
Escaped - A zero-allocation
core::fmt::Displayadapter that HTML-escapes the wrapped string as it is formatted. - Identifier
Str - A borrowed, validated HTML identifier (
[A-Za-z][A-Za-z0-9_-]*), safe to interpolate intoid/name/classattributes and CSS selectors without escaping. Theno_stdcounterpart ofIdentifier, mirroring Go safehtml’sIdentifier. - JsString
Escaped - A zero-allocation
core::fmt::Displayadapter that JS-string-escapes the wrapped text as it is formatted (seeescape_js_string_to). - Percent
Decode - A zero-allocation iterator over the bytes of a percent-decoded string.
- Safe
Html Builder alloc - An incremental builder for
SafeHtml, holding one growable buffer for an entire render. - Safe
Html Str - A borrowed string slice that is safe to use in HTML contexts, the
no_std-friendly counterpart ofSafeHtml. - Safe
Script Str - A borrowed string slice of trusted JavaScript, the
no_std-friendly counterpart ofSafeScript. - Safe
Style Sheet Str - A borrowed safe CSS style sheet, the
no_std-friendly counterpart ofSafeStyleSheet. - Safe
Style Str - A borrowed sequence of safe CSS declarations, the
no_std-friendly counterpart ofSafeStyle. - Safe
UrlStr - A borrowed string slice that is safe to use as a hyperlink URL, the
no_std-friendly counterpart ofSafeUrl. - Slice
Writer - A
core::fmt::Writeimplementation over a caller-provided byte buffer. - Trusted
Resource UrlStr - A borrowed URL of a trusted, developer-controlled resource, the
no_std-friendly counterpart ofTrustedResourceUrl.
Constants§
- INNOCUOUS_
PROPERTY_ VALUE - The innocuous value substituted for CSS property values that fail
validation, mirroring Go safehtml’s
InnocuousPropertyValue(zGoSafezInvalidPropertyValue); the prefix is adjusted to this crate’szSafezconvention. - INNOCUOUS_
URL - The innocuous URL returned by sanitizers when validation fails.
Traits§
- Safe
Html Part - A piece that can be written into a safe HTML output.
Functions§
- coerce_
bytes_ to_ interchange_ valid alloc - Coerces raw bytes to interchange-valid UTF-8.
- coerce_
bytes_ to_ interchange_ valid_ to - Coerces raw bytes (which may contain invalid UTF-8 sequences) to interchange-valid UTF-8, writing the result to a writer.
- coerce_
to_ interchange_ valid_ to - Coerces a string to interchange-valid UTF-8, replacing invalid characters.
- disp
- Wraps any
Displayvalue as aSafeHtmlPartwhose formatted output is HTML-escaped as it streams — no intermediateString. - escape_
allow_ character_ references_ to - Escapes a string to be HTML-safe while preserving existing valid character references.
- escape_
html_ and_ coerce_ to - Coerces a string to interchange-valid UTF-8 and HTML-escapes security-sensitive characters.
- escape_
html_ bytes alloc - Coerces raw bytes to interchange-valid UTF-8 and escapes security-sensitive HTML characters.
- escape_
html_ bytes_ and_ coerce_ to - Coerces raw bytes (which may contain invalid UTF-8 sequences) to interchange-valid UTF-8, escaping security-sensitive HTML characters, writing the result to a writer.
- escape_
html_ unquoted_ attribute alloc - Allocating convenience form of
escape_html_unquoted_attribute_to. - escape_
html_ unquoted_ attribute_ to - Escapes text for use as an unquoted HTML attribute value, coercing interchange-invalid characters in the same pass.
- escape_
js_ string alloc - Allocating convenience form of
escape_js_string_to. - escape_
js_ string_ to - Escapes untrusted text for embedding inside a JavaScript string literal
(single-quoted, double-quoted, or template literal) in an inline
<script>block. - escape_
json_ for_ script alloc - Escapes a JSON string to be safely embedded within an inline
<script>HTML tag. - escape_
json_ for_ script_ to - Escapes a JSON string to be safely embedded within an inline
<script>HTML tag. - html_
escaped - Wraps
textin anHtmlEscapeddisplay adapter; formatting it produces the HTML-escaped, interchange-coerced representation. - is_
interchange_ invalid - Checks if a character is “interchange-invalid” according to Unicode and HTML preprocessing specs.
- is_
safe_ css_ selector - Validates a CSS selector for use in a
SafeStyleSheetstyle rule. - is_
safe_ identifier - Validates an HTML identifier: one ASCII letter followed by any number of
ASCII alphanumerics,
-, or_. - is_
safe_ style_ property_ name - Validates a CSS property name: one or more ASCII letters or hyphens
(e.g.
background-color). - is_
safe_ style_ property_ value - Validates a CSS property value against the safe regular-property pattern
used by Go safehtml (
^(?:[*/]?(?:[0-9a-zA-Z+-.!#%_ \t]|$))*$), implemented as a linear scan. - is_
safe_ url_ block_ javascript - Validates that a URL starts with a well-formed scheme that is not
javascript:, or contains no scheme (relative URL). - is_
safe_ url_ restrictive - Validates that a URL is safe using the default allowed schemes or is relative.
- is_
safe_ url_ restrictive_ with_ schemes - Validates that a URL is safe, additionally permitting the specified custom schemes.
- js_
string_ escaped - Wraps
textin aJsStringEscapeddisplay adapter. - percent_
decode - Percent-decodes
input, returning a byte iterator. - percent_
decode_ bytes alloc - Percent-decodes
inputinto a byte vector. - percent_
decode_ utf8_ lossy alloc - Percent-decodes
inputinto aString, replacing invalid UTF-8 sequences with U+FFFD. - percent_
encode alloc - Allocating convenience form of
percent_encode_to. - percent_
encode_ to - Percent-encodes
textagainst a caller-chosenEncodeSet, writing tow. Zero-allocation core ofpercent_encode. - percent_
escape_ css_ url alloc - Percent-escapes characters in a URL for safe embedding in CSS contexts.
- percent_
escape_ css_ url_ to - Percent-escapes characters in a URL for safe embedding in CSS contexts (like
url(...)). - url_
encode_ component alloc - Percent-encodes a string for safe use as a URL component (e.g. query parameter value).
- url_
encode_ component_ to - Percent-encodes a string for safe use as a URL component (e.g., a query parameter value).