contextual_encoder/lib.rs
1#![forbid(unsafe_code)]
2
3//! contextual output encoding for XSS defense and safe literal embedding.
4//!
5//! this crate provides context-aware encoding functions inspired by the
6//! [OWASP Java Encoder](https://owasp.org/owasp-java-encoder/). each function
7//! encodes input for safe embedding in a specific output context — web contexts
8//! (HTML, XML, JavaScript, CSS, URI) and source literal contexts (Rust).
9//!
10//! **disclaimer:** contextual-encoder is an independent Rust crate. its API and security model
11//! are inspired by the OWASP Java Encoder, but this project is not affiliated with,
12//! endorsed by, or maintained by the OWASP Foundation.
13//!
14//! # quick start
15//!
16//! ```
17//! use contextual_encoder::{for_html, for_javascript, for_css_string, for_uri_component};
18//!
19//! let user_input = "<script>alert('xss')</script>";
20//!
21//! // safe for HTML text content and quoted attributes
22//! let html_safe = for_html(user_input);
23//! assert!(html_safe.contains("<script>"));
24//!
25//! // safe for javascript string literals (universal)
26//! let js_safe = for_javascript(user_input);
27//! assert!(js_safe.contains(r"<\/script>"));
28//!
29//! // safe for quoted CSS string values
30//! let css_safe = for_css_string(user_input);
31//! assert!(css_safe.contains(r"\3c"));
32//!
33//! // safe as a URI query parameter value
34//! let uri_safe = for_uri_component(user_input);
35//! assert!(uri_safe.contains("%3C"));
36//! ```
37//!
38//! # available contexts
39//!
40//! ## HTML
41//!
42//! | function | safe for |
43//! |----------|----------|
44//! | [`for_html`] | text content + quoted attributes |
45//! | [`for_html_content`] | text content only |
46//! | [`for_html_attribute`] | quoted attributes only |
47//! | [`for_html_unquoted_attribute`] | unquoted attribute values |
48//!
49//! ## XML
50//!
51//! | function | safe for |
52//! |----------|----------|
53//! | [`for_xml`] | XML text content + quoted attributes (alias for `for_html`) |
54//! | [`for_xml_content`] | XML text content only (alias for `for_html_content`) |
55//! | [`for_xml_attribute`] | quoted XML attributes only (alias for `for_html_attribute`) |
56//! | [`for_xml_comment`] | XML comment content |
57//! | [`for_cdata`] | CDATA section content |
58//!
59//! ## XML 1.1
60//!
61//! | function | safe for |
62//! |----------|----------|
63//! | [`for_xml11`] | XML 1.1 content + quoted attributes |
64//! | [`for_xml11_content`] | XML 1.1 content only |
65//! | [`for_xml11_attribute`] | XML 1.1 quoted attributes only |
66//!
67//! ## JavaScript
68//!
69//! | function | safe for |
70//! |----------|----------|
71//! | [`for_javascript`] | general JS string contexts |
72//! | [`for_javascript_attribute`] | HTML event attributes |
73//! | [`for_javascript_block`] | `<script>` blocks |
74//! | [`for_javascript_source`] | standalone .js files |
75//! | [`for_js_template`] | ES6 template literal content (`` `...` ``) |
76//!
77//! ## CSS
78//!
79//! | function | safe for |
80//! |----------|----------|
81//! | [`for_css_string`] | quoted CSS string values |
82//! | [`for_css_url`] | CSS `url()` values |
83//!
84//! ## URI
85//!
86//! | function | safe for |
87//! |----------|----------|
88//! | [`for_uri_component`] | URI components (query params, path segments) |
89//! | [`for_uri_path`] | URI paths (preserves `/` separators) |
90//! | [`for_form_urlencoded`] | `application/x-www-form-urlencoded` values |
91//!
92//! ## additional literal contexts
93//!
94//! these encoders are not part of the OWASP Java Encoder's scope. they encode
95//! untrusted strings for safe embedding in source code literals.
96//!
97//! | function | safe for |
98//! |----------|----------|
99//! | [`for_json`] | JSON string values |
100//! | [`for_rust_string`] | Rust string literals (`"..."`) |
101//! | [`for_rust_char`] | Rust char literals (`'...'`) |
102//! | [`for_rust_byte_string`] | Rust byte string literals (`b"..."`) |
103//! | [`for_sql`] | Standard SQL string literals (`'...'`) |
104//! | [`for_sql_backslash`] | MySQL/MariaDB string literals with backslash escaping (`'...'`) |
105//!
106//! # security model
107//!
108//! this is a **contextual output encoder**, not a sanitizer. it prevents
109//! cross-site scripting by encoding output for specific contexts, but it
110//! does not validate or sanitize input.
111//!
112//! **important caveats:**
113//!
114//! - **encoding is not sanitization.** encoding `<script>` as `<script>`
115//! makes it display safely in HTML, but does not remove it. if you need to
116//! allow a subset of HTML, use a dedicated sanitizer.
117//! - **context matters.** using the wrong encoder for a context can leave
118//! you vulnerable. `for_html_content` output is not safe in attributes.
119//! - **tag and attribute names cannot be encoded.** never pass untrusted data
120//! as a tag name, attribute name, or event handler name. validate these
121//! against a whitelist.
122//! - **full URLs must be validated separately.** `for_uri_component` encodes
123//! a component, not a full URL. to embed an untrusted URL, validate its
124//! scheme and structure first, then encode for the final sink.
125//! - **template literals.** the string literal JavaScript encoders do not
126//! encode backticks. use [`for_js_template`] to embed data directly in
127//! ES2015+ template literals.
128//! - **grave accent.** unpatched Internet Explorer treats `` ` `` as an
129//! attribute delimiter. `for_html_unquoted_attribute` encodes it, but
130//! numeric entities decode back to the original character, so this is
131//! not a complete fix. avoid unquoted attributes.
132//! - **HTML comments.** no HTML comment encoder is provided because HTML
133//! comments have vendor-specific extensions (e.g., conditional comments)
134//! that make safe encoding impractical. [`for_xml_comment`] is for XML
135//! comments only.
136//!
137//! # writer-based API
138//!
139//! every `for_*` function has a corresponding `write_*` function that writes
140//! to any `std::fmt::Write` implementor, avoiding allocation when writing to
141//! an existing buffer:
142//!
143//! ```
144//! use contextual_encoder::write_html;
145//!
146//! let mut buf = String::new();
147//! write_html(&mut buf, "safe & sound").unwrap();
148//! assert_eq!(buf, "safe & sound");
149//! ```
150//!
151//! # display wrappers
152//!
153//! every `for_*` function also has a corresponding `display_*` function that
154//! returns a zero-allocation [`Display`](std::fmt::Display) wrapper. use these
155//! when embedding encoded output inline in `format!` or `write!`:
156//!
157//! ```
158//! use contextual_encoder::display_html;
159//!
160//! let user_input = "<script>alert('xss')</script>";
161//! // one allocation (the final String), zero intermediate allocations
162//! let safe = format!("<p>{}</p>", display_html(user_input));
163//! assert!(safe.contains("<script>"));
164//! ```
165
166pub mod css;
167pub mod display;
168pub mod html;
169pub mod javascript;
170pub mod json;
171pub mod rust;
172pub mod sql;
173pub mod uri;
174pub mod xml;
175
176mod engine;
177
178// convenience re-exports — users can `use contextual_encoder::for_html` directly
179pub use css::{for_css_string, for_css_url, write_css_string, write_css_url};
180pub use display::{
181 display_cdata, display_css_string, display_css_url, display_form_urlencoded, display_html,
182 display_html_attribute, display_html_content, display_html_unquoted_attribute,
183 display_javascript, display_javascript_attribute, display_javascript_block,
184 display_javascript_source, display_js_template, display_json, display_rust_byte_string,
185 display_rust_char, display_rust_string, display_sql, display_sql_backslash,
186 display_uri_component, display_uri_path, display_xml, display_xml11, display_xml11_attribute,
187 display_xml11_content, display_xml_attribute, display_xml_comment, display_xml_content,
188};
189pub use html::{
190 for_html, for_html_attribute, for_html_content, for_html_unquoted_attribute, write_html,
191 write_html_attribute, write_html_content, write_html_unquoted_attribute,
192};
193pub use javascript::{
194 for_javascript, for_javascript_attribute, for_javascript_block, for_javascript_source,
195 for_js_template, write_javascript, write_javascript_attribute, write_javascript_block,
196 write_javascript_source, write_js_template,
197};
198pub use json::{for_json, write_json};
199pub use rust::{
200 for_rust_byte_string, for_rust_char, for_rust_string, write_rust_byte_string, write_rust_char,
201 write_rust_string,
202};
203pub use sql::{for_sql, for_sql_backslash, write_sql, write_sql_backslash};
204pub use uri::{
205 for_form_urlencoded, for_uri_component, for_uri_path, write_form_urlencoded,
206 write_uri_component, write_uri_path,
207};
208pub use xml::{
209 for_cdata, for_xml, for_xml11, for_xml11_attribute, for_xml11_content, for_xml_attribute,
210 for_xml_comment, for_xml_content, write_cdata, write_xml, write_xml11, write_xml11_attribute,
211 write_xml11_content, write_xml_attribute, write_xml_comment, write_xml_content,
212};
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217
218 #[test]
219 fn empty_string_returns_empty() {
220 assert_eq!(for_html(""), "");
221 assert_eq!(for_html_content(""), "");
222 assert_eq!(for_html_attribute(""), "");
223 assert_eq!(for_html_unquoted_attribute(""), "");
224 assert_eq!(for_javascript(""), "");
225 assert_eq!(for_javascript_attribute(""), "");
226 assert_eq!(for_javascript_block(""), "");
227 assert_eq!(for_javascript_source(""), "");
228 assert_eq!(for_css_string(""), "");
229 assert_eq!(for_css_url(""), "");
230 assert_eq!(for_uri_component(""), "");
231 assert_eq!(for_uri_path(""), "");
232 assert_eq!(for_xml(""), "");
233 assert_eq!(for_xml_content(""), "");
234 assert_eq!(for_xml_attribute(""), "");
235 assert_eq!(for_xml_comment(""), "");
236 assert_eq!(for_cdata(""), "");
237 assert_eq!(for_xml11(""), "");
238 assert_eq!(for_xml11_content(""), "");
239 assert_eq!(for_xml11_attribute(""), "");
240 assert_eq!(for_json(""), "");
241 assert_eq!(for_rust_string(""), "");
242 assert_eq!(for_rust_char(""), "");
243 assert_eq!(for_rust_byte_string(""), "");
244 assert_eq!(for_js_template(""), "");
245 assert_eq!(for_sql(""), "");
246 assert_eq!(for_sql_backslash(""), "");
247 assert_eq!(for_form_urlencoded(""), "");
248 }
249
250 #[test]
251 fn empty_string_writer_variants() {
252 let mut buf = String::new();
253 write_html(&mut buf, "").unwrap();
254 assert_eq!(buf, "");
255
256 buf.clear();
257 write_javascript(&mut buf, "").unwrap();
258 assert_eq!(buf, "");
259
260 buf.clear();
261 write_css_string(&mut buf, "").unwrap();
262 assert_eq!(buf, "");
263
264 buf.clear();
265 write_uri_component(&mut buf, "").unwrap();
266 assert_eq!(buf, "");
267
268 buf.clear();
269 write_uri_path(&mut buf, "").unwrap();
270 assert_eq!(buf, "");
271
272 buf.clear();
273 write_form_urlencoded(&mut buf, "").unwrap();
274 assert_eq!(buf, "");
275 }
276
277 // two-byte: é (U+00E9), ñ (U+00F1)
278 // three-byte: 世 (U+4E16), € (U+20AC)
279 // four-byte: 😀 (U+1F600), 𐍈 (U+10348)
280
281 #[test]
282 fn multibyte_utf8_html() {
283 assert_eq!(for_html("café"), "café");
284 assert_eq!(for_html("世界"), "世界");
285 assert_eq!(for_html("😀"), "😀");
286 assert_eq!(for_html("é<世>&😀"), "é<世>&😀");
287 }
288
289 #[test]
290 fn multibyte_utf8_javascript() {
291 assert_eq!(for_javascript("café"), "café");
292 assert_eq!(for_javascript("世界"), "世界");
293 assert_eq!(for_javascript("😀"), "😀");
294 }
295
296 #[test]
297 fn multibyte_utf8_css_string() {
298 assert_eq!(for_css_string("café"), "café");
299 assert_eq!(for_css_string("世界"), "世界");
300 assert_eq!(for_css_string("😀"), "😀");
301 }
302
303 #[test]
304 fn multibyte_utf8_uri_component() {
305 assert_eq!(for_uri_component("é"), "%C3%A9");
306 assert_eq!(for_uri_component("世"), "%E4%B8%96");
307 assert_eq!(for_uri_component("😀"), "%F0%9F%98%80");
308 assert_eq!(for_uri_component("café"), "caf%C3%A9");
309 }
310
311 #[test]
312 fn multibyte_utf8_uri_path() {
313 assert_eq!(for_uri_path("é"), "%C3%A9");
314 assert_eq!(for_uri_path("世"), "%E4%B8%96");
315 assert_eq!(for_uri_path("😀"), "%F0%9F%98%80");
316 assert_eq!(for_uri_path("/café"), "/caf%C3%A9");
317 }
318
319 #[test]
320 fn multibyte_utf8_form_urlencoded() {
321 assert_eq!(for_form_urlencoded("é"), "%C3%A9");
322 assert_eq!(for_form_urlencoded("世"), "%E4%B8%96");
323 assert_eq!(for_form_urlencoded("😀"), "%F0%9F%98%80");
324 assert_eq!(for_form_urlencoded("café"), "caf%C3%A9");
325 }
326
327 #[test]
328 fn multibyte_utf8_rust_byte_string() {
329 assert_eq!(for_rust_byte_string("é"), r"\xc3\xa9");
330 assert_eq!(for_rust_byte_string("世"), r"\xe4\xb8\x96");
331 assert_eq!(for_rust_byte_string("😀"), r"\xf0\x9f\x98\x80");
332 }
333
334 #[test]
335 fn multibyte_utf8_rust_string_passthrough() {
336 assert_eq!(for_rust_string("café"), "café");
337 assert_eq!(for_rust_string("世界"), "世界");
338 assert_eq!(for_rust_string("😀"), "😀");
339 }
340
341 #[test]
342 fn multibyte_utf8_json() {
343 assert_eq!(for_json("café"), "café");
344 assert_eq!(for_json("世界"), "世界");
345 assert_eq!(for_json("😀"), "😀");
346 }
347
348 #[test]
349 fn multibyte_utf8_sql() {
350 assert_eq!(for_sql("café"), "café");
351 assert_eq!(for_sql("世界"), "世界");
352 assert_eq!(for_sql("😀"), "😀");
353 }
354
355 #[test]
356 fn multibyte_utf8_sql_backslash() {
357 assert_eq!(for_sql_backslash("café"), "café");
358 assert_eq!(for_sql_backslash("世界"), "世界");
359 assert_eq!(for_sql_backslash("😀"), "😀");
360 }
361
362 #[test]
363 fn multibyte_utf8_xml() {
364 assert_eq!(for_xml("café"), "café");
365 assert_eq!(for_xml("世界"), "世界");
366 assert_eq!(for_xml("😀"), "😀");
367 }
368}