safehtml 0.2.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](https://github.com/google/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 `EncodeSet`s 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 `Deref`s to it, and `ToOwned`/`From` convert back.

## Example Usage

```rust
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");

// 7. Template formatting: the literal is trusted markup, arguments are
// parts (escaped or already safe). Placeholders are checked at compile
// time — a {placeholder} without a matching `name = value` argument does
// not compile, so locals can never sneak in unescaped.
use safehtml::safe_html_format;
let html = safe_html_format!(
    r#"<input name="date" value="{date}" title="{t}">"#,
    date = "2026-07-18",
    t = "Bob & Alice",
);
assert_eq!(
    html.as_str(),
    r#"<input name="date" value="2026-07-18" title="Bob &amp; Alice">"#
);

// 8. Incremental rendering: one buffer for a whole screen.
use safehtml::SafeHtmlBuilder;
let mut b = SafeHtmlBuilder::with_capacity(256);
b.push(SafeHtml::from_constant("<ul>"));
for name in ["a<b", "c&d"] {
    safe_html_format!(b, "<li>{name}</li>", name = name);
}
b.push(SafeHtml::from_constant("</ul>"));
assert_eq!(b.finish().as_str(), "<ul><li>a&lt;b</li><li>c&amp;d</li></ul>");

// 9. Foreign Display types interpolate through `disp`, which escapes
// their output as it streams (no intermediate String).
use safehtml::disp;
struct Money(i64);
impl core::fmt::Display for Money {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "${}.{:02}", self.0 / 100, self.0 % 100)
    }
}
let cell = safe_html_format!("<td>{m}</td>", m = disp(Money(1234)));
assert_eq!(cell.as_str(), "<td>$12.34</td>");
```

> **Migration note — double escaping**: string parts are *always* escaped.
> A legacy helper that still returns an already-escaped `String` will be
> escaped again (`&amp;amp;`) if passed as a part; convert such helpers to
> return `SafeHtml` instead. See the "Migration Hazard: Double Escaping"
> section in the crate docs.

## Embedded / Zero-Allocation Usage

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

```rust
use safehtml::{SafeHtmlStr, SafeUrlStr, SliceWriter, safe_html_format_to, 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>");

// The template form of the same, still zero-allocation:
let mut out2 = [0u8; 64];
let mut w2 = SliceWriter::new(&mut out2);
safe_html_format_to!(w2, "<b>{v}</b>", v = "5 < 6").unwrap();
assert_eq!(w2.as_str(), "<b>5 &lt; 6</b>");

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

```sh
./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](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE).