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//!
91//! ## additional literal contexts
92//!
93//! these encoders are not part of the OWASP Java Encoder's scope. they encode
94//! untrusted strings for safe embedding in source code literals.
95//!
96//! | function | safe for |
97//! |----------|----------|
98//! | [`for_json`] | JSON string values |
99//! | [`for_rust_string`] | Rust string literals (`"..."`) |
100//! | [`for_rust_char`] | Rust char literals (`'...'`) |
101//! | [`for_rust_byte_string`] | Rust byte string literals (`b"..."`) |
102//! | [`for_sql`] | Standard SQL string literals (`'...'`) |
103//! | [`for_sql_backslash`] | MySQL/MariaDB string literals with backslash escaping (`'...'`) |
104//!
105//! # security model
106//!
107//! this is a **contextual output encoder**, not a sanitizer. it prevents
108//! cross-site scripting by encoding output for specific contexts, but it
109//! does not validate or sanitize input.
110//!
111//! **important caveats:**
112//!
113//! - **encoding is not sanitization.** encoding `<script>` as `<script>`
114//! makes it display safely in HTML, but does not remove it. if you need to
115//! allow a subset of HTML, use a dedicated sanitizer.
116//! - **context matters.** using the wrong encoder for a context can leave
117//! you vulnerable. `for_html_content` output is not safe in attributes.
118//! - **tag and attribute names cannot be encoded.** never pass untrusted data
119//! as a tag name, attribute name, or event handler name. validate these
120//! against a whitelist.
121//! - **full URLs must be validated separately.** `for_uri_component` encodes
122//! a component, not a full URL. to embed an untrusted URL, validate its
123//! scheme and structure first, then encode for the final sink.
124//! - **template literals.** the string literal JavaScript encoders do not
125//! encode backticks. use [`for_js_template`] to embed data directly in
126//! ES2015+ template literals.
127//! - **grave accent.** unpatched Internet Explorer treats `` ` `` as an
128//! attribute delimiter. `for_html_unquoted_attribute` encodes it, but
129//! numeric entities decode back to the original character, so this is
130//! not a complete fix. avoid unquoted attributes.
131//! - **HTML comments.** no HTML comment encoder is provided because HTML
132//! comments have vendor-specific extensions (e.g., conditional comments)
133//! that make safe encoding impractical. [`for_xml_comment`] is for XML
134//! comments only.
135//!
136//! # writer-based API
137//!
138//! every `for_*` function has a corresponding `write_*` function that writes
139//! to any `std::fmt::Write` implementor, avoiding allocation when writing to
140//! an existing buffer:
141//!
142//! ```
143//! use contextual_encoder::write_html;
144//!
145//! let mut buf = String::new();
146//! write_html(&mut buf, "safe & sound").unwrap();
147//! assert_eq!(buf, "safe & sound");
148//! ```
149//!
150//! # display wrappers
151//!
152//! every `for_*` function also has a corresponding `display_*` function that
153//! returns a zero-allocation [`Display`](std::fmt::Display) wrapper. use these
154//! when embedding encoded output inline in `format!` or `write!`:
155//!
156//! ```
157//! use contextual_encoder::display_html;
158//!
159//! let user_input = "<script>alert('xss')</script>";
160//! // one allocation (the final String), zero intermediate allocations
161//! let safe = format!("<p>{}</p>", display_html(user_input));
162//! assert!(safe.contains("<script>"));
163//! ```
164
165pub mod css;
166pub mod display;
167pub mod html;
168pub mod javascript;
169pub mod json;
170pub mod rust;
171pub mod sql;
172pub mod uri;
173pub mod xml;
174
175mod engine;
176
177// convenience re-exports — users can `use contextual_encoder::for_html` directly
178pub use css::{for_css_string, for_css_url, write_css_string, write_css_url};
179pub use display::{
180 display_cdata, display_css_string, display_css_url, display_html, display_html_attribute,
181 display_html_content, display_html_unquoted_attribute, display_javascript,
182 display_javascript_attribute, display_javascript_block, display_javascript_source,
183 display_js_template, display_json, display_rust_byte_string, display_rust_char,
184 display_rust_string, display_sql, display_sql_backslash, display_uri_component,
185 display_uri_path, display_xml, display_xml11, display_xml11_attribute, display_xml11_content,
186 display_xml_attribute, display_xml_comment, display_xml_content,
187};
188pub use html::{
189 for_html, for_html_attribute, for_html_content, for_html_unquoted_attribute, write_html,
190 write_html_attribute, write_html_content, write_html_unquoted_attribute,
191};
192pub use javascript::{
193 for_javascript, for_javascript_attribute, for_javascript_block, for_javascript_source,
194 for_js_template, write_javascript, write_javascript_attribute, write_javascript_block,
195 write_javascript_source, write_js_template,
196};
197pub use json::{for_json, write_json};
198pub use rust::{
199 for_rust_byte_string, for_rust_char, for_rust_string, write_rust_byte_string, write_rust_char,
200 write_rust_string,
201};
202pub use sql::{for_sql, for_sql_backslash, write_sql, write_sql_backslash};
203pub use uri::{for_uri_component, for_uri_path, write_uri_component, write_uri_path};
204pub use xml::{
205 for_cdata, for_xml, for_xml11, for_xml11_attribute, for_xml11_content, for_xml_attribute,
206 for_xml_comment, for_xml_content, write_cdata, write_xml, write_xml11, write_xml11_attribute,
207 write_xml11_content, write_xml_attribute, write_xml_comment, write_xml_content,
208};
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213
214 #[test]
215 fn empty_string_returns_empty() {
216 assert_eq!(for_html(""), "");
217 assert_eq!(for_html_content(""), "");
218 assert_eq!(for_html_attribute(""), "");
219 assert_eq!(for_html_unquoted_attribute(""), "");
220 assert_eq!(for_javascript(""), "");
221 assert_eq!(for_javascript_attribute(""), "");
222 assert_eq!(for_javascript_block(""), "");
223 assert_eq!(for_javascript_source(""), "");
224 assert_eq!(for_css_string(""), "");
225 assert_eq!(for_css_url(""), "");
226 assert_eq!(for_uri_component(""), "");
227 assert_eq!(for_uri_path(""), "");
228 assert_eq!(for_xml(""), "");
229 assert_eq!(for_xml_content(""), "");
230 assert_eq!(for_xml_attribute(""), "");
231 assert_eq!(for_xml_comment(""), "");
232 assert_eq!(for_cdata(""), "");
233 assert_eq!(for_xml11(""), "");
234 assert_eq!(for_xml11_content(""), "");
235 assert_eq!(for_xml11_attribute(""), "");
236 assert_eq!(for_json(""), "");
237 assert_eq!(for_rust_string(""), "");
238 assert_eq!(for_rust_char(""), "");
239 assert_eq!(for_rust_byte_string(""), "");
240 assert_eq!(for_js_template(""), "");
241 assert_eq!(for_sql(""), "");
242 assert_eq!(for_sql_backslash(""), "");
243 }
244
245 #[test]
246 fn empty_string_writer_variants() {
247 let mut buf = String::new();
248 write_html(&mut buf, "").unwrap();
249 assert_eq!(buf, "");
250
251 buf.clear();
252 write_javascript(&mut buf, "").unwrap();
253 assert_eq!(buf, "");
254
255 buf.clear();
256 write_css_string(&mut buf, "").unwrap();
257 assert_eq!(buf, "");
258
259 buf.clear();
260 write_uri_component(&mut buf, "").unwrap();
261 assert_eq!(buf, "");
262
263 buf.clear();
264 write_uri_path(&mut buf, "").unwrap();
265 assert_eq!(buf, "");
266 }
267
268 // two-byte: é (U+00E9), ñ (U+00F1)
269 // three-byte: 世 (U+4E16), € (U+20AC)
270 // four-byte: 😀 (U+1F600), 𐍈 (U+10348)
271
272 #[test]
273 fn multibyte_utf8_html() {
274 assert_eq!(for_html("café"), "café");
275 assert_eq!(for_html("世界"), "世界");
276 assert_eq!(for_html("😀"), "😀");
277 assert_eq!(for_html("é<世>&😀"), "é<世>&😀");
278 }
279
280 #[test]
281 fn multibyte_utf8_javascript() {
282 assert_eq!(for_javascript("café"), "café");
283 assert_eq!(for_javascript("世界"), "世界");
284 assert_eq!(for_javascript("😀"), "😀");
285 }
286
287 #[test]
288 fn multibyte_utf8_css_string() {
289 assert_eq!(for_css_string("café"), "café");
290 assert_eq!(for_css_string("世界"), "世界");
291 assert_eq!(for_css_string("😀"), "😀");
292 }
293
294 #[test]
295 fn multibyte_utf8_uri_component() {
296 assert_eq!(for_uri_component("é"), "%C3%A9");
297 assert_eq!(for_uri_component("世"), "%E4%B8%96");
298 assert_eq!(for_uri_component("😀"), "%F0%9F%98%80");
299 assert_eq!(for_uri_component("café"), "caf%C3%A9");
300 }
301
302 #[test]
303 fn multibyte_utf8_uri_path() {
304 assert_eq!(for_uri_path("é"), "%C3%A9");
305 assert_eq!(for_uri_path("世"), "%E4%B8%96");
306 assert_eq!(for_uri_path("😀"), "%F0%9F%98%80");
307 assert_eq!(for_uri_path("/café"), "/caf%C3%A9");
308 }
309
310 #[test]
311 fn multibyte_utf8_rust_byte_string() {
312 assert_eq!(for_rust_byte_string("é"), r"\xc3\xa9");
313 assert_eq!(for_rust_byte_string("世"), r"\xe4\xb8\x96");
314 assert_eq!(for_rust_byte_string("😀"), r"\xf0\x9f\x98\x80");
315 }
316
317 #[test]
318 fn multibyte_utf8_rust_string_passthrough() {
319 assert_eq!(for_rust_string("café"), "café");
320 assert_eq!(for_rust_string("世界"), "世界");
321 assert_eq!(for_rust_string("😀"), "😀");
322 }
323
324 #[test]
325 fn multibyte_utf8_json() {
326 assert_eq!(for_json("café"), "café");
327 assert_eq!(for_json("世界"), "世界");
328 assert_eq!(for_json("😀"), "😀");
329 }
330
331 #[test]
332 fn multibyte_utf8_sql() {
333 assert_eq!(for_sql("café"), "café");
334 assert_eq!(for_sql("世界"), "世界");
335 assert_eq!(for_sql("😀"), "😀");
336 }
337
338 #[test]
339 fn multibyte_utf8_sql_backslash() {
340 assert_eq!(for_sql_backslash("café"), "café");
341 assert_eq!(for_sql_backslash("世界"), "世界");
342 assert_eq!(for_sql_backslash("😀"), "😀");
343 }
344
345 #[test]
346 fn multibyte_utf8_xml() {
347 assert_eq!(for_xml("café"), "café");
348 assert_eq!(for_xml("世界"), "世界");
349 assert_eq!(for_xml("😀"), "😀");
350 }
351}