Skip to main content

Crate safehtml

Crate safehtml 

Source
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:

  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 Derefs 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

FeatureDefaultDescription
allocyesHeap-allocated wrapper types and String-returning convenience functions.
serdenoSerialize/Deserialize implementations for the wrapper types.
simdnocore::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;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

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;alloc
pub use types::SafeHtml;alloc
pub use types::SafeHtmlProto;alloc
pub use types::SafeScript;alloc
pub use types::SafeScriptProto;alloc
pub use types::SafeStyle;alloc
pub use types::SafeStyleProto;alloc
pub use types::SafeStyleSheet;alloc
pub use types::SafeStyleSheetProto;alloc
pub use types::SafeUrl;alloc
pub use types::SafeUrlProto;alloc
pub use types::TrustedResourceUrl;alloc
pub use types::TrustedResourceUrlProto;alloc

Modules§

typesalloc
Heap-allocated safe-type wrappers (SafeHtml, SafeUrl, SafeScript, TrustedResourceUrl, SafeStyle, SafeStyleSheet) and their proto replicas. Requires the alloc feature.

Macros§

safe_html_catalloc
Concatenates multiple values (both SafeHtml and raw values that will be HTML-escaped) into a single SafeHtml.
safe_html_formatalloc
Builds a SafeHtml from a trusted template literal with escaped interpolations, or appends the same to a SafeHtmlBuilder.
safe_html_format_to
Streams a trusted template literal with escaped interpolations into any core::fmt::Write — the no_std, zero-allocation sibling of safe_html_format!.
safe_html_write
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!.

Structs§

CapacityError
Error returned when a fixed-size buffer is too small for the output.
DisplayEscaped
A SafeHtmlPart adapter that HTML-escapes the Display output of a wrapped value on the fly. Created by disp.
EncodeSet
A const-buildable set of ASCII bytes allowed to pass through percent-encoding unchanged; every other byte is encoded as %XX.
HtmlEscaped
A zero-allocation core::fmt::Display adapter that HTML-escapes the wrapped string as it is formatted.
IdentifierStr
A borrowed, validated HTML identifier ([A-Za-z][A-Za-z0-9_-]*), safe to interpolate into id/name/class attributes and CSS selectors without escaping. The no_std counterpart of Identifier, mirroring Go safehtml’s Identifier.
JsStringEscaped
A zero-allocation core::fmt::Display adapter that JS-string-escapes the wrapped text as it is formatted (see escape_js_string_to).
PercentDecode
A zero-allocation iterator over the bytes of a percent-decoded string.
SafeHtmlBuilderalloc
An incremental builder for SafeHtml, holding one growable buffer for an entire render.
SafeHtmlStr
A borrowed string slice that is safe to use in HTML contexts, the no_std-friendly counterpart of SafeHtml.
SafeScriptStr
A borrowed string slice of trusted JavaScript, the no_std-friendly counterpart of SafeScript.
SafeStyleSheetStr
A borrowed safe CSS style sheet, the no_std-friendly counterpart of SafeStyleSheet.
SafeStyleStr
A borrowed sequence of safe CSS declarations, the no_std-friendly counterpart of SafeStyle.
SafeUrlStr
A borrowed string slice that is safe to use as a hyperlink URL, the no_std-friendly counterpart of SafeUrl.
SliceWriter
A core::fmt::Write implementation over a caller-provided byte buffer.
TrustedResourceUrlStr
A borrowed URL of a trusted, developer-controlled resource, the no_std-friendly counterpart of TrustedResourceUrl.

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’s zSafez convention.
INNOCUOUS_URL
The innocuous URL returned by sanitizers when validation fails.

Traits§

SafeHtmlPart
A piece that can be written into a safe HTML output.

Functions§

coerce_bytes_to_interchange_validalloc
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 Display value as a SafeHtmlPart whose formatted output is HTML-escaped as it streams — no intermediate String.
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_bytesalloc
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_attributealloc
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_stringalloc
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_scriptalloc
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 text in an HtmlEscaped display 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 SafeStyleSheet style 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 text in a JsStringEscaped display adapter.
percent_decode
Percent-decodes input, returning a byte iterator.
percent_decode_bytesalloc
Percent-decodes input into a byte vector.
percent_decode_utf8_lossyalloc
Percent-decodes input into a String, replacing invalid UTF-8 sequences with U+FFFD.
percent_encodealloc
Allocating convenience form of percent_encode_to.
percent_encode_to
Percent-encodes text against a caller-chosen EncodeSet, writing to w. Zero-allocation core of percent_encode.
percent_escape_css_urlalloc
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_componentalloc
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).