safehtml/lib.rs
1#![deny(unsafe_op_in_unsafe_fn)]
2#![no_std]
3#![cfg_attr(docsrs, feature(doc_cfg))]
4#![cfg_attr(feature = "simd", feature(portable_simd))]
5
6//! # Safehtml
7//!
8//! A pure Rust, 2024 edition, `no_std`-compatible library that implements
9//! safety contracts and validation for strings used in security-sensitive web
10//! contexts (HTML, CSS, JavaScript, and URLs).
11//!
12//! The design is a Rust implementation of Google's
13//! [safe-html-types](https://github.com/google/safe-html-types) contracts (as
14//! seen in the C++ and Go `safehtml` libraries), covering all six contract
15//! types: [`SafeHtml`], [`SafeScript`], [`SafeStyle`], [`SafeStyleSheet`],
16//! [`SafeUrl`], and [`TrustedResourceUrl`]. It is engineered specifically to
17//! prevent Cross-Site Scripting (XSS) and code-injection vulnerabilities by
18//! construction.
19//!
20//! ## Embedded & `no_std` Suitability
21//!
22//! This crate is highly optimized for embedded and resource-constrained
23//! environments:
24//! 1. **Zero-Allocation Core**: All validation and escaping logic operates
25//! directly on `&str` and writes to implementations of [`core::fmt::Write`].
26//! This allows formatting directly into stack-allocated buffers (e.g.,
27//! `heapless::String` or direct peripheral I/O) without any dynamic memory
28//! allocations.
29//! 2. **No Regular Expressions**: Unlike Go and C++ libraries which depend on
30//! heavy, runtime-compiled regex engines, this library implements fast,
31//! deterministic, table-driven linear scans accelerated by a portable SWAR
32//! word scanner (or `core::simd` with the nightly-only `simd` feature).
33//! This minimizes code size and CPU usage; the default build works on
34//! stable Rust with no nightly features.
35//! 3. **Borrowed Safe Types Everywhere**: The `#[repr(transparent)]` borrowed
36//! types ([`SafeHtmlStr`], [`SafeUrlStr`], [`SafeScriptStr`],
37//! [`SafeStyleStr`], [`SafeStyleSheetStr`], [`TrustedResourceUrlStr`])
38//! carry the safety contracts without any allocation, so type-driven
39//! security works even without `alloc`. Their `from_constant` constructors
40//! are `const` and usable in `static` items.
41//! 4. **Optional `alloc` Feature**: The high-level owned types ([`SafeHtml`],
42//! [`SafeUrl`], [`SafeScript`], [`SafeStyle`], [`SafeStyleSheet`],
43//! [`TrustedResourceUrl`]) which enforce safety boundaries via type-safety
44//! are gated under the `alloc` feature (enabled by default). They store
45//! `Cow<'static, str>`, so `from_constant`/`empty` are `const` and
46//! allocation-free; each owned type [`Deref`](core::ops::Deref)s to its
47//! borrowed counterpart. Disable default features
48//! (`default-features = false`) to compile in a pure, alloc-free
49//! environment.
50//! 5. **Optional `serde` Feature**: Provides optional
51//! serialization/deserialization with built-in validation checks.
52//!
53//! ## Feature Flags
54//!
55//! | Feature | Default | Description |
56//! |---------|---------|-------------|
57//! | `alloc` | yes | Heap-allocated wrapper types and `String`-returning convenience functions. |
58//! | `serde` | no | `Serialize`/`Deserialize` implementations for the wrapper types. |
59//! | `simd` | no | `core::simd` scanners (16 bytes/step); requires a nightly toolchain. |
60//!
61//! ## Security Model
62//!
63//! Each wrapper type carries a contract: holding an instance means its string
64//! value is safe to use in the corresponding sink without further escaping.
65//! Instances are created through validating/escaping constructors; the
66//! `unsafe fn from_string_unchecked` escape hatches place the burden of proof
67//! on the caller and are greppable by design.
68//!
69//! ## Migration Hazard: Double Escaping
70//!
71//! `String`/`&str` values interpolated as parts (in [`safe_html_cat!`],
72//! [`safe_html_write!`], [`safe_html_format!`], [`safe_html_format_to!`],
73//! and [`SafeHtmlBuilder::push`]) are **always HTML-escaped** — that is the
74//! right default, because a bare string carries no safety contract.
75//!
76//! During incremental migration of an existing codebase, however, helper
77//! functions often still return *already-escaped* `String`s (e.g. a legacy
78//! `money()` or `select()` helper built on `format!`). Passing such a value
79//! as a part escapes it **again**: it compiles cleanly and only shows up at
80//! runtime as visible `&amp;` / `&lt;` artifacts. The type system
81//! cannot catch this, precisely because `String` must stay "untrusted".
82//!
83//! The fix is to move the trust boundary into the helper: have it return
84//! [`SafeHtml`] (built with [`safe_html_format!`]/[`safe_html_cat!`], or —
85//! after an audit — `unsafe { SafeHtml::from_string_unchecked(..) }`)
86//! instead of `String`. Until a helper is converted, do **not** pass its
87//! output as a part. Rule of thumb: any `String` crossing a part boundary
88//! must be raw, unescaped text.
89//!
90//! **Serde caveat**: deserializing [`SafeUrl`] re-validates the value and
91//! fails on unsafe input, but deserializing [`SafeHtml`], [`SafeScript`], and
92//! [`TrustedResourceUrl`] trusts the input (there is no cheap way to verify
93//! "already-safe HTML"). Only deserialize these types from trusted storage or
94//! internal services — never directly from user-controlled request bodies.
95//!
96//! ## Example: Embedded/Alloc-Free Usage
97//!
98//! ```rust
99//! use safehtml::{escape_html_and_coerce_to, is_safe_url_restrictive};
100//!
101//! // Write HTML directly into a custom buffer (which implements core::fmt::Write)
102//! struct SimpleBuffer {
103//! storage: [u8; 128],
104//! len: usize,
105//! }
106//!
107//! impl core::fmt::Write for SimpleBuffer {
108//! fn write_str(&mut self, s: &str) -> core::fmt::Result {
109//! let bytes = s.as_bytes();
110//! if self.len + bytes.len() > self.storage.len() {
111//! return Err(core::fmt::Error);
112//! }
113//! self.storage[self.len..self.len + bytes.len()].copy_from_slice(bytes);
114//! self.len += bytes.len();
115//! Ok(())
116//! }
117//! }
118//!
119//! let mut buf = SimpleBuffer { storage: [0; 128], len: 0 };
120//! escape_html_and_coerce_to("Hello <World>", &mut buf).unwrap();
121//!
122//! // Validate a URL safely without dynamic allocation:
123//! let untrusted_url = "https://example.com/api";
124//! if is_safe_url_restrictive(untrusted_url) {
125//! // URL is safe to use in href contexts
126//! }
127//! ```
128
129#[cfg(feature = "alloc")]
130pub extern crate alloc;
131
132// Compile the README examples as doctests so the documentation cannot drift
133// out of sync with the API.
134#[cfg(all(doctest, feature = "alloc"))]
135#[doc = include_str!("../README.md")]
136pub struct ReadmeDoctests;
137
138#[cfg(feature = "alloc")]
139mod builder;
140mod css;
141mod escape;
142mod format;
143mod ident;
144mod parts;
145mod percent;
146mod str_types;
147mod url;
148mod writer;
149
150#[cfg(feature = "alloc")]
151#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
152pub use builder::SafeHtmlBuilder;
153pub use css::*;
154pub use escape::*;
155pub use ident::*;
156pub use parts::*;
157pub use percent::*;
158pub use str_types::*;
159pub use url::*;
160pub use writer::*;
161
162/// Implementation details of the crate macros ([`safe_html_cat!`],
163/// [`safe_html_format!`], [`safe_html_format_to!`]).
164///
165/// Not public API: there are no semver guarantees, and calling these
166/// directly can mint safe-type values without their contracts being
167/// upheld. The `unsafe` needed by the macro expansions lives here (and in
168/// [`SafeHtmlBuilder`]) so that consumer crates with
169/// `#![forbid(unsafe_code)]` can use the macros.
170#[doc(hidden)]
171pub mod __private {
172 pub use crate::format::{
173 check_named_format, check_positional_format, format_named_to, format_positional_to,
174 has_brace, unit,
175 };
176 #[cfg(feature = "alloc")]
177 pub use crate::format::{format_named, format_positional};
178 pub use crate::parts::DynPart;
179 #[cfg(feature = "alloc")]
180 pub use crate::parts::cat_from_parts;
181
182 /// Wraps macro-built output as [`SafeHtml`](crate::SafeHtml).
183 #[cfg(feature = "alloc")]
184 pub fn finish_safe_html(html: crate::alloc::string::String) -> crate::SafeHtml {
185 // SAFETY: only called from this crate's macro expansions, which
186 // route every part through `SafeHtmlPart` (already-safe types
187 // verbatim, untrusted text escaped) and treat only string literals
188 // as trusted markup.
189 unsafe { crate::SafeHtml::from_string_unchecked(html) }
190 }
191}
192
193#[cfg(feature = "alloc")]
194#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
195pub mod types;
196
197#[cfg(feature = "alloc")]
198#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
199pub use types::{
200 Identifier, SafeHtml, SafeHtmlProto, SafeScript, SafeScriptProto, SafeStyle, SafeStyleProto,
201 SafeStyleSheet, SafeStyleSheetProto, SafeUrl, SafeUrlProto, TrustedResourceUrl,
202 TrustedResourceUrlProto,
203};
204
205/// Concatenates multiple values (both `SafeHtml` and raw values that will be
206/// HTML-escaped) into a single `SafeHtml`.
207///
208/// Automatically escapes standard types and keeps safe types unescaped.
209/// Strings are *always* escaped — never pass a pre-escaped `String` (see
210/// "Migration Hazard: Double Escaping" in the crate docs). For
211/// template-shaped construction prefer
212/// [`safe_html_format!`](crate::safe_html_format).
213#[cfg(feature = "alloc")]
214#[macro_export]
215macro_rules! safe_html_cat {
216 () => {
217 $crate::SafeHtml::empty()
218 };
219 ($($val:expr),+ $(,)?) => {
220 $crate::__private::cat_from_parts(&[$(&$val as &dyn $crate::__private::DynPart),+])
221 };
222}
223
224/// Writes multiple values (both safe types and raw values that will be
225/// HTML-escaped) into any [`core::fmt::Write`] — the `no_std`,
226/// zero-allocation sibling of [`safe_html_cat!`].
227///
228/// The first argument is the writer; the rest are parts implementing
229/// [`SafeHtmlPart`]. Safe types ([`SafeHtml`], [`SafeHtmlStr`],
230/// [`Identifier`]) pass through verbatim; strings and characters are
231/// escaped; numbers and booleans are formatted. Evaluates to
232/// [`core::fmt::Result`], so a full [`SliceWriter`] surfaces as `Err`.
233///
234/// ```rust
235/// use safehtml::{SafeHtmlStr, SliceWriter, safe_html_write};
236///
237/// let mut buf = [0u8; 64];
238/// let mut w = SliceWriter::new(&mut buf);
239/// safe_html_write!(w, SafeHtmlStr::from_constant("<b>"), "5 < 6", 42).unwrap();
240/// assert_eq!(w.as_str(), "<b>5 < 642");
241/// ```
242#[macro_export]
243macro_rules! safe_html_write {
244 ($w:expr $(,)?) => {{
245 let _ = &mut $w;
246 core::fmt::Result::Ok(())
247 }};
248 ($w:expr, $($val:expr),+ $(,)?) => {{
249 let w = &mut $w;
250 'safe_html_write: {
251 $(
252 if let core::result::Result::Err(e) = $crate::SafeHtmlPart::write_to(&$val, w) {
253 break 'safe_html_write core::fmt::Result::Err(e);
254 }
255 )+
256 core::fmt::Result::Ok(())
257 }
258 }};
259}
260
261#[cfg(all(feature = "serde", feature = "alloc"))]
262mod serde_impl;