pub fn sanitize(html: &str) -> StringExpand description
Cleans user-supplied HTML down to SANITIZE_TAGS and SANITIZE_ATTRIBUTES (Rails’ sanitize).
The output is rebuilt, not filtered: kept tags are written back with
quoted, escaped attributes; other tags are removed but their text kept;
<script>, <style>, <iframe>, <svg> and similar are removed with
their content; comments are removed; href/src with a scheme other
than http, https, mailto or tel (e.g. javascript:) are removed;
text is escaped; unclosed tags are closed. The result is safe to insert
with askama’s |safe: {{ comment.body_html|safe }}.
Sanitize when saving (store the clean HTML) rather than on every render: it costs CPU proportional to the input, about 1 ms per 100 KB.
§Examples
use ocre::security::sanitize;
assert_eq!(
sanitize(r#"<p onclick="steal()">Hi <b>there</b><script>alert(1)</script></p>"#),
"<p>Hi <b>there</b></p>"
);
assert_eq!(sanitize(r#"<a href="javascript:alert(1)">x</a>"#), "<a>x</a>");
assert_eq!(sanitize(r#"<a href="https://example.com" target="_blank">x</a>"#), r#"<a href="https://example.com">x</a>"#);
assert_eq!(sanitize("<em>unclosed"), "<em>unclosed</em>");
assert_eq!(sanitize("1 < 2 & 3"), "1 < 2 & 3");