contextual output encoding for XSS defense and safe literal embedding. the web encoders' rules, context model and security caveats are derived from the OWASP Java Encoder.
contextual-encoder is an independent Rust crate for contextual output encoding.
its API and security model are derived from the OWASP Java Encoder (see
THIRD_PARTY_NOTICES.md).
this project is not affiliated with, endorsed by, or maintained by the OWASP
Foundation.
a zero-dependency Rust library that encodes untrusted strings for safe embedding in web output contexts (HTML, JavaScript, CSS, URI, XML) and source literal contexts (JSON, Rust, SQL). each function targets a specific output context so that only the necessary characters are encoded.
use contextual_encoder::for_html;
// pick the encoder for the sink; the input is always untrusted
let safe = for_html("<script>alert('xss')</script>");
assert_eq!(safe, "<script>alert('xss')</script>");see examples for the other contexts, or run
cargo run --example contexts.
- not a sanitizer. encoding
<script>as<script>makes it display safely — it does not remove it. if you need to allow a subset of HTML, use a dedicated sanitizer. - not a validator. tag names, attribute names, event handler names, and URL schemes must be validated separately. encoding cannot make arbitrary names safe.
- not a URL validator.
for_uri_componentencodes a URI component, not a full URL. to embed an untrusted URL, validate its scheme and structure first, then encode for the final sink (for example, an HTML attribute).
| function | safe for | notes |
|---|---|---|
for_html |
text content + quoted attributes | most conservative — safe default |
for_html_content |
text content only | does not encode quotes |
for_html_attribute |
quoted attributes only | does not encode > |
for_html_unquoted_attribute |
unquoted attribute values | most aggressive |
| function | safe for | notes |
|---|---|---|
for_xml |
XML content + quoted attributes | alias for for_html |
for_xml_content |
XML content only | alias for for_html_content |
for_xml_attribute |
quoted XML attributes | alias for for_html_attribute |
for_xml_comment |
XML comment content | every - → ~ |
for_cdata |
CDATA section content | splits the section at every ] and > (up to 13× longer) |
| function | safe for | notes |
|---|---|---|
for_xml11 |
XML 1.1 content + quoted attributes | restricted chars, NEL and U+2028 → hex character references |
for_xml11_content |
XML 1.1 content only | does not encode quotes |
for_xml11_attribute |
quoted XML 1.1 attributes | does not encode > |
| function | safe for | notes |
|---|---|---|
for_javascript |
general JS string contexts | caller supplies quotes; hex-encodes quotes for HTML safety |
for_javascript_attribute |
HTML event attributes | does not escape < or / |
for_javascript_block |
<script> blocks |
uses backslash quote escapes |
for_javascript_source |
standalone .js files | minimal encoding; not valid JSON — use for_json |
for_js_template |
ES6 template literal content | escapes `, ${, a trailing $, and a leading { |
the <script>-block encoders (for_javascript, for_javascript_block,
for_js_template) escape < as \x3c as well as / as \/. escaping /
alone stops a literal </script>, but not <!--<script>, which walks the
HTML tokenizer into script-data-double-escaped state — where the block's real
</script> no longer closes it.
they also escape & as \x26. in an HTML5 document <script> content is raw
text and character references are not decoded, so this matters only when the
page is parsed as XML (application/xhtml+xml, XSLT output) — there the parser
resolves them before JavaScript sees the text, so untrusted input containing
the literal ` would arrive as a backtick that closes a template literal,
and ${ as a ${ that opens an interpolation.
all five escape the bidi formatting controls (U+202A-U+202E, U+2066-U+2069)
as \uHHHH. a direction override left raw in the generated JavaScript reorders
how the surrounding source reads, hiding code from review while the engine runs
it unchanged — the same Trojan Source hazard the Rust literal encoders close.
| function | safe for | notes |
|---|---|---|
for_css_string |
quoted CSS string values | hex escapes with separator spaces, including at the end; escapes the bidi formatting controls |
for_css_url |
CSS url() values, quoted or unquoted |
like for_css_string plus space — output is always one url-token |
| function | safe for | notes |
|---|---|---|
for_uri_component |
query params, path segments | RFC 3986 percent-encoding |
for_uri_path |
URI paths (preserves /) |
RFC 3986 section 3.3 |
for_form_urlencoded |
form field values | WHATWG URL Standard, space → + |
these encoders are not part of the OWASP Java Encoder's scope. they encode untrusted strings for safe embedding in source code literals.
| function | safe for | notes |
|---|---|---|
for_json |
JSON string values | \uHHHH escapes (no \xHH), escapes <, / and U+2028/U+2029 for <script> safety |
| function | safe for | notes |
|---|---|---|
for_rust_string |
Rust string literals ("...") |
\xHH for controls, \u{HHHH} for the bidi controls rustc rejects raw and for unicode non-characters, other non-ASCII passes through |
for_rust_char |
Rust char literals ('...') |
escapes ' instead of "; input must be exactly one character |
for_rust_char_checked |
Rust char literals ('...') |
as for_rust_char, but returns None unless the input is exactly one character |
for_rust_byte_string |
Rust byte string literals (b"...") |
non-ASCII → \xHH per UTF-8 byte |
| function | safe for | notes |
|---|---|---|
for_sql |
standard SQL string literals ('...') |
doubles ' to '', removes NUL; backslash passes through |
for_sql_backslash |
MySQL/MariaDB string literals ('...') |
C-style backslash escaping (\', \\, \n, etc.) |
the following contexts are intentionally not supported because encoding cannot make them safe:
- raw tag names — validate against a whitelist
- raw attribute names — validate against a whitelist
- event handler names — validate against a whitelist
- raw JavaScript expressions — no encoder can make
eval()safe - raw CSS selectors / properties — validate structure separately
- dynamic SQL identifiers (table / column names) —
for_sqlencodes a string literal ('...'), not an identifier ("..."or`...`); validate against a whitelist - HTML comments — vendor-specific extensions (e.g., IE conditional comments) make safe encoding impractical
- full untrusted URLs —
for_uri_componentencodes a component, not a full URL. to embed an untrusted URL, validate its scheme and structure first, then encode for the final sink
use contextual_encoder::{for_html, for_javascript, for_css_string, for_uri_component};
let user_input = "<script>alert('xss')</script>";
// HTML text content or quoted attribute
let safe = for_html(user_input);
assert_eq!(safe, "<script>alert('xss')</script>");
// JavaScript string literal
let safe = for_javascript(user_input);
// quotes are hex-encoded, < and / are escaped to keep </script> closing
assert!(safe.contains(r"\x3c\/script>"));
// CSS string value
let safe = for_css_string(user_input);
assert!(safe.contains(r"\3c"));
// URI component
let safe = for_uri_component(user_input);
assert!(safe.contains("%3C"));every for_* function except for_rust_char_checked has a write_*
counterpart that writes to any std::fmt::Write implementor:
use contextual_encoder::write_html;
let mut buf = String::new();
write_html(&mut buf, "safe & sound").unwrap();
assert_eq!(buf, "safe & sound");each write_* function also has a display_* counterpart that returns a
Display wrapper, for encoding inline in format! or write! without an
intermediate String:
use contextual_encoder::display_html;
let page = format!("<p>{}</p>", display_html("1 < 2"));
assert_eq!(page, "<p>1 < 2</p>");width, fill and precision apply to the encoded output, as they do to the
String a for_* function returns; with either set, the wrapper buffers the
output in one String. precision counts characters of the encoded output, so
it can cut an escape in half: {:.4} turns a<b into a<, which an
HTML parser reads back as a<. truncate the input before encoding it, never
the output.
this is a contextual output encoder, not a sanitizer. it prevents cross-site scripting by encoding output for specific contexts.
grave accent (`): unpatched internet explorer treats the grave
accent as an attribute delimiter. for_html_unquoted_attribute encodes it
as `, but numeric character references decode back to the original
character, so this is not a complete fix. the safest mitigation is to avoid
unquoted attributes entirely.
template literals: the string literal JavaScript encoders (for_javascript,
for_javascript_attribute, etc.) do not encode backticks. to embed
untrusted data directly inside an ES6 template literal, use for_js_template:
// WRONG — vulnerable:
// `Hello ${unsafeInput}`
// RIGHT — use the template literal encoder:
`Hello ${for_js_template(unsafeInput)}`
// ALSO RIGHT — encode into a variable first:
var x = '<contextual_encoder::for_javascript output>';
`Hello ${x}`full URLs: for_uri_component encodes a URI component, not a full URL.
to embed an untrusted URL, validate its scheme and structure first, then
encode for the final sink (for example, an HTML attribute).
HTML comments: no HTML comment encoder is provided. HTML comments have
vendor-specific extensions (e.g., <!--[if IE]>) that make safe encoding
impractical. never embed untrusted data in HTML comments. for_xml_comment
is for XML comments only — it is not safe for HTML comments.
the web output encoders (HTML, JavaScript, CSS, URI, XML) are derived from
the OWASP Java Encoder. for_js_template and the literal encoders (JSON,
Rust, SQL) are additions specific to this crate.
- encoding rules for
for_html,for_html_content,for_html_attribute,for_xml_comment,for_cdata(apart from NEL, below),for_html_unquoted_attribute - JavaScript encoding rules for
for_javascript,for_javascript_attribute,for_javascript_blockandfor_javascript_source, apart from<and the bidirectional formatting characters (below) - CSS hex escape format with a trailing space separator between escapes and the characters that follow (including C1 controls), apart from the separator at the end of the output and the bidirectional formatting characters (below)
- URI component percent-encoding of UTF-8 bytes
- security caveats (grave accent, template literals, HTML comments, full URLs)
- surrogate handling: Java's
char[]can contain invalid surrogate pairs which the Java encoder replaces with space or dash. Ruststris guaranteed valid UTF-8, so surrogates cannot appear. supplementary plane characters (U+10000+) are valid and pass through or are encoded normally. - NEL (U+0085) in
for_html,for_html_content,for_html_attribute, their XML 1.0 aliases,for_xml_commentandfor_cdatais replaced with a space, like the other C1 controls. the Java encoder passes it through unchanged in these contexts. for_htmluses"and'for quote encoding rather than"— both are valid HTML and the numeric form is shorter.<in JavaScript:for_javascriptandfor_javascript_blockescape<as\x3c, so the encoded string cannot spell</script>or<!--.- bidirectional formatting characters (U+202A-U+202E, U+2066-U+2069) are
escaped by every JavaScript encoder (
\uHHHH) and both CSS encoders (as a hex escape), so a direction override in the data cannot reorder how the surrounding source reads. - CSS separator at the end of the output: the CSS encoders append the separator space after a hex escape that ends the output too, so it cannot run into whatever the caller writes next.
-(hyphen) in JavaScript: the Java encoder may escape-as\-in some JavaScript contexts to prevent-->sequences. this crate does not encode-in JavaScript. the-->sequence inside a JS string literal is harmless because the HTML parser does not scan string literal contents.
the differential harness tests encoded output with independent parsers using fixed adversarial inputs and seeded random inputs. run it from a repository checkout:
cargo test --manifest-path differential/Cargo.toml --release --lockedthe harness is a separate, unpublished package. its parser dependencies are isolated from this crate. see its readme for coverage and limitations.
MIT