Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_text/src/doc/policy.rs

25.8 KiB, 17 runs

created by r1870400018:16344, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! Bringing an untrusted document within what a site will publish.
2//!
3//! The tree a reader's comment parses to is the same tree an author's essay parses to, and the
4//! renderer treats them alike. It should not: an author is trusted with a link's destination and a
5//! stranger is not.
6//!
7//! # Why this is not a sanitiser
8//!
9//! A sanitiser is what a pipeline needs when author-written HTML passes through it: the markup is
10//! opaque, so the dangerous parts must be named and stripped, and anything the list failed to name
11//! survives. **This tree cannot carry HTML at all.** There is no `Block::Html` and no `Inline::Html`
12//; every node is a named construct, and [`html::render`](crate::doc::html) writes tags itself and
13//! escapes every run of text and every attribute value on the way out. A `<script>` in a comment is
14//! therefore already only ever the *words* `<script>`.
15//!
16//! What is left is not markup injection but the handful of places where a string the author wrote
17//! reaches somewhere with meaning:
18//!
19//! - **A link's destination and an image's source.** `escape_attr` stops a destination breaking out
20//! of its quotes, and stops nothing about what the destination *is*: `javascript:` in an `href` is
21//! a script that runs on click. This is the one real hole, and the module documentation of the
22//! renderer has named it as such since it was written.
23//! - **An image's source, again, for a different reason.** A remote image is a request the reader's
24//! browser makes to a third party, carrying their address and the page they are on. A commenter who
25//! can embed one can log every reader of the thread. That is tracking, whoever is doing it.
26//! - **Attributes.** An `id` or a `class` a stranger chose lands in the site's own document, where it
27//! can collide with the page's ids or borrow the site's styling to dress a comment as something it
28//! is not.
29//!
30//! So this is an allowlist over a *tree*, not over text: it walks a document and returns one that
31//! holds only what the policy permits. It is testable on the tree -- the assertion is that no
32//! `javascript:` link is present afterwards, not that some string was rewritten -- and every
33//! renderer, not only the HTML one, is protected by it.
34//!
35//! # Depth
36//!
37//! The walk is recursive on the same terms as the renderer's, and a policy additionally *bounds* the
38//! depth: [`Policy::max_depth`] truncates a tree deeper than a caller will accept, so a document
39//! built to overflow a stack is refused rather than walked.
40
41use crate::doc::{
42 Block,
43 Cell,
44 Doc,
45 Inline,
46 Row,
47};
48
49
50/// The URL schemes a link may use where a caller names none of its own.
51///
52/// The three a person writing prose actually reaches for. `javascript:` is the attack, and `data:`
53/// is one too -- a `data:text/html` destination is a document of the sender's choosing served from
54/// the site's own origin.
55pub const SAFE_SCHEMES: &[&str] = &["http", "https", "mailto"];
56
57/// What a document from an untrusted author may contain.
58///
59/// The defaults are a comment's: prose, emphasis, links to the ordinary schemes, quotes, lists and
60/// code, and nothing that reaches outside the page. Loosen deliberately, field by field, rather than
61/// by starting from everything and removing.
62#[derive(Clone, Debug)]
63pub struct Policy {
64 /// The URL schemes a link may use. A destination with no scheme is governed by
65 /// [`allow_relative`](Policy::allow_relative).
66 pub schemes: Vec<String>,
67 /// Whether a link may point within the site, with no scheme of its own.
68 pub allow_relative: bool,
69 /// Whether images survive. Off by default: an image is a request to wherever it points, made by
70 /// the reader's browser, and a commenter who can place one can count the thread's readers.
71 pub allow_images: bool,
72 /// Whether headings survive, and above which level they are demoted rather than dropped. A
73 /// comment inside a page has no business opening an `h1`.
74 pub heading_floor: Option<u8>,
75 /// Whether tables survive.
76 pub allow_tables: bool,
77 /// Whether a division or span keeps the attributes that name it. Off by default: an id or a class
78 /// a stranger chose lands in the site's own document.
79 pub allow_attrs: bool,
80 /// How deep the tree may nest before the walk stops and drops what is below.
81 pub max_depth: usize,
82}
83
84impl Default for Policy {
85
86 /// The policy for a comment: prose and links, nothing that reaches out of the page.
87 fn default() -> Self {
88 Self {
89 schemes: SAFE_SCHEMES.iter().map(|s| s.to_string()).collect(),
90 allow_relative: true,
91 allow_images: false,
92 heading_floor: Some(3),
93 allow_tables: true,
94 allow_attrs: false,
95 max_depth: 16,
96 }
97 }
98}
99
100impl Policy {
101
102 /// A policy that permits everything, for prose whose author is trusted.
103 ///
104 /// Applying this is a no-op in effect and is offered so a caller can hold one type for both cases
105 /// rather than branching around whether to apply a policy at all.
106 pub fn trusting() -> Self {
107 Self {
108 schemes: Vec::new(), // empty means every scheme, with `allow_relative` moot
109 allow_relative: true,
110 allow_images: true,
111 heading_floor: None,
112 allow_tables: true,
113 allow_attrs: true,
114 max_depth: usize::MAX,
115 }
116 }
117
118 /// Whether this policy permits every scheme, which is what an empty allowlist means.
119 fn permits_every_scheme(&self) -> bool {
120 self.schemes.is_empty()
121 }
122
123 /// Whether a destination is one this policy will write.
124 ///
125 /// The scheme is what stands before the first `:`, where that colon comes before any `/`, `?` or
126 /// `#` -- so `mailto:a@b` has one, `/posts/a:b` does not, and neither does `a.html`. Compared
127 /// without regard to case, because `JavaScript:` is the same scheme as `javascript:` to a browser
128 /// and a different string to a comparison that forgot.
129 ///
130 /// Leading whitespace and control characters are stripped before the test: `\tjavascript:` and
131 /// `java\0script:` are destinations browsers have historically honoured, and a check that looked
132 /// only at the string as given would pass them.
133 ///
134 /// A backslash is read as a separator, because that is what a browser reads it as. The URL
135 /// standard's relative states treat `\` as `/` for every special scheme, so `\\host/x` resolves
136 /// against an `http` or `https` page exactly as `//host/x` does and goes straight off-site. A
137 /// check that looked only for `//` would let the same destination through under a different
138 /// spelling, which is the whole of what an allowlist is for.
139 pub fn permits_url(&self, url: &str) -> bool {
140 if self.permits_every_scheme() {
141 return true;
142 }
143 // Control characters and whitespace anywhere in the scheme portion are removed rather than
144 // merely trimmed: a browser ignores them, so a comparison must too. A backslash becomes the
145 // separator a browser reads it as, for the reason given above; this is the string the test
146 // is made against and never the string that is written out.
147 let cleaned: String = url
148 .chars()
149 .filter(|c| !c.is_whitespace() && !c.is_control())
150 .map(|c| if c == '\\' { '/' } else { c })
151 .collect();
152 let scheme_end = cleaned.find(':');
153 let scheme = match scheme_end {
154 Some(i) => {
155 // A colon that comes after a path separator is part of the path, not a scheme.
156 let before = &cleaned[..i];
157 if before.contains('/') || before.contains('?') || before.contains('#') {
158 return self.allow_relative && !cleaned.starts_with("//");
159 }
160 before
161 }
162 // No colon at all: a relative destination -- unless it opens `//`, which is not
163 // relative at all. `//evil.example/x` inherits the page's scheme and goes straight
164 // off-site, and reading it as "relative" is how a link allowlist is walked past.
165 None => return self.allow_relative && !cleaned.starts_with("//"),
166 };
167 if scheme.is_empty() {
168 // A destination beginning `:` names no scheme and is nonsense; refuse it rather than
169 // guess what a browser will make of it.
170 return false;
171 }
172 let scheme = scheme.to_ascii_lowercase();
173 self.schemes.iter().any(|s| s.eq_ignore_ascii_case(&scheme))
174 }
175}
176
177/// Brings a document within a policy, returning what survives.
178///
179/// Nothing is rejected wholesale: a document is *reduced* to what is permitted, because a comment
180/// that says something worth reading and one disallowed thing should lose the one thing rather than
181/// the whole comment. A link whose destination is refused keeps its words and loses its link -- the
182/// reader still reads the sentence, and follows nothing.
183pub fn apply(doc: &Doc, policy: &Policy) -> Doc {
184 Doc { blocks: blocks(&doc.blocks, policy, 0) }
185}
186
187/// Returns the document with every destination rewritten by the caller.
188///
189/// The companion to [`apply`], and the other half of publishing prose somebody else wrote. A policy
190/// decides *whether* a destination may be written; this decides *what* is written instead. The two
191/// are separate because they answer to different things: the allowlist is a property of the site's
192/// safety, and the rewriting is a property of where the prose is being shown.
193///
194/// # Why a caller wants this rather than the destination as written
195///
196/// A relative destination in an untrusted document is resolved by the browser against the address of
197/// the page that carries it, which is almost never the place the author meant. A README written to be
198/// read beside its own files says `[the parser](src/parse.rs)`, and a site that drops that string into
199/// a page at `/thing/files` sends the reader to `/thing/src/parse.rs`. Worse, a destination is free to
200/// climb: `../../elsewhere` reaches whatever the site keeps at that address, so a document can point
201/// at parts of the site nobody offered it. Mapping every destination through a function the site owns
202/// puts both under the site's control in one place.
203///
204/// `map` returns the destination to write, or nothing to drop the link and keep its words -- which is
205/// exactly what [`apply`] does with a destination its policy refuses, so a reader meets one behaviour
206/// however a link came to be dropped.
207///
208/// Order does not matter and applying both is the ordinary case: run this and then [`apply`], or the
209/// reverse, and the surviving set is the same, since neither invents a destination the other has not
210/// seen.
211pub fn retarget<F>(doc: &Doc, map: F) -> Doc
212where
213 F: Fn(&str) -> Option<String>,
214{
215 Doc { blocks: retarget_blocks(&doc.blocks, &map) }
216}
217
218/// The blocks, their destinations rewritten.
219fn retarget_blocks<F>(items: &[Block], map: &F) -> Vec<Block>
220where
221 F: Fn(&str) -> Option<String>,
222{
223 let mut out = Vec::with_capacity(items.len());
224 for item in items {
225 out.push(match item {
226 Block::Heading { level, content } => Block::Heading {
227 level: *level,
228 content: retarget_inlines(content, map),
229 },
230 Block::Para(content) => Block::Para(retarget_inlines(content, map)),
231 Block::List { ordered, items } => Block::List {
232 ordered: *ordered,
233 items: items.iter().map(|it| retarget_blocks(it, map)).collect(),
234 },
235 Block::Quote(inner) => Block::Quote(retarget_blocks(inner, map)),
236 Block::Table { head, rows, cols } => Block::Table {
237 head: head.as_ref().map(|h| retarget_row(h, map)),
238 rows: rows.iter().map(|r| retarget_row(r, map)).collect(),
239 cols: cols.clone(),
240 },
241 Block::Div { attrs, content } => Block::Div {
242 attrs: attrs.clone(),
243 content: retarget_blocks(content, map),
244 },
245 // A code block and a rule hold no destination, so there is nothing here to rewrite.
246 Block::Code { .. } | Block::Rule => item.clone(),
247 });
248 }
249 out
250}
251
252/// A row, its cells' destinations rewritten.
253fn retarget_row<F>(r: &Row, map: &F) -> Row
254where
255 F: Fn(&str) -> Option<String>,
256{
257 Row(r.0.iter().map(|c| Cell(retarget_inlines(&c.0, map))).collect())
258}
259
260/// The inlines, their destinations rewritten.
261fn retarget_inlines<F>(items: &[Inline], map: &F) -> Vec<Inline>
262where
263 F: Fn(&str) -> Option<String>,
264{
265 let mut out = Vec::with_capacity(items.len());
266 for item in items {
267 match item {
268 Inline::Link { to, content } => {
269 let kept = retarget_inlines(content, map);
270 match map(to) {
271 Some(there) => out.push(Inline::Link { to: there, content: kept }),
272 // The words stay and the destination goes, which is what a refused
273 // destination already does. See [`retarget`].
274 None => out.extend(kept),
275 }
276 }
277 Inline::Image { src, alt } => match map(src) {
278 Some(there) => out.push(Inline::Image { src: there, alt: alt.clone() }),
279 None if !alt.trim().is_empty() => out.push(Inline::Text(alt.clone())),
280 None => {},
281 },
282 Inline::Emph { strong, content } => out.push(Inline::Emph {
283 strong: *strong,
284 content: retarget_inlines(content, map),
285 }),
286 Inline::Span { attrs, content } => out.push(Inline::Span {
287 attrs: attrs.clone(),
288 content: retarget_inlines(content, map),
289 }),
290 Inline::Text(_) | Inline::Code(_) | Inline::Break => out.push(item.clone()),
291 }
292 }
293 out
294}
295
296
297/// The blocks that survive, at a given depth.
298fn blocks(items: &[Block], policy: &Policy, depth: usize) -> Vec<Block> {
299 if depth >= policy.max_depth {
300 return Vec::new();
301 }
302 let mut out = Vec::new();
303 for item in items {
304 match item {
305 Block::Heading { level, content } => {
306 let floor = match policy.heading_floor {
307 Some(f) => f,
308 // No floor means headings are not permitted at all: the words become a
309 // paragraph, since what was said still stands.
310 None => {
311 out.push(Block::Para(inlines(content, policy, depth)));
312 continue;
313 }
314 };
315 // Demoted rather than dropped: the author meant a heading, and the only thing wrong
316 // with it is how loudly it would speak inside somebody else's page.
317 out.push(Block::Heading {
318 level: (*level).max(floor).min(6),
319 content: inlines(content, policy, depth),
320 });
321 }
322 Block::Para(content) => out.push(Block::Para(inlines(content, policy, depth))),
323 Block::List { ordered, items } => {
324 let kept: Vec<Vec<Block>> = items.iter()
325 .map(|it| blocks(it, policy, depth + 1))
326 .filter(|it| !it.is_empty())
327 .collect();
328 if !kept.is_empty() {
329 out.push(Block::List { ordered: *ordered, items: kept });
330 }
331 }
332 // Code is text and nothing else. The renderer escapes it, so it is safe as written, and
333 // the language name reaches a class attribute -- which is why it is passed through the
334 // same attribute rule as everything else.
335 Block::Code { lang, text } => out.push(Block::Code {
336 lang: if policy.allow_attrs { lang.clone() } else { lang.as_ref()
337 .filter(|l| l.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'))
338 .cloned() },
339 text: text.clone(),
340 }),
341 Block::Quote(inner) => {
342 let kept = blocks(inner, policy, depth + 1);
343 if !kept.is_empty() {
344 out.push(Block::Quote(kept));
345 }
346 }
347 Block::Table { head, rows, cols } => {
348 if !policy.allow_tables {
349 // A table that is not permitted still said something; its cells become
350 // paragraphs rather than vanishing.
351 if let Some(h) = head {
352 out.extend(row_as_paras(h, policy, depth));
353 }
354 for r in rows {
355 out.extend(row_as_paras(r, policy, depth));
356 }
357 continue;
358 }
359 out.push(Block::Table {
360 head: head.as_ref().map(|h| row(h, policy, depth)),
361 rows: rows.iter().map(|r| row(r, policy, depth)).collect(),
362 cols: cols.clone(),
363 });
364 }
365 Block::Rule => out.push(Block::Rule),
366 Block::Div { attrs, content } => {
367 let kept = blocks(content, policy, depth + 1);
368 if kept.is_empty() {
369 continue;
370 }
371 if policy.allow_attrs {
372 out.push(Block::Div { attrs: attrs.clone(), content: kept });
373 } else {
374 // The division's content is kept and its naming is not: the words were the
375 // author's to write and the site's markup was not theirs to join.
376 out.extend(kept);
377 }
378 }
379 }
380 }
381 out
382}
383
384/// A row, its cells brought within the policy.
385fn row(r: &Row, policy: &Policy, depth: usize) -> Row {
386 Row(r.0.iter().map(|c| Cell(inlines(&c.0, policy, depth))).collect())
387}
388
389/// A row's cells as paragraphs, for a table a policy will not keep.
390fn row_as_paras(r: &Row, policy: &Policy, depth: usize) -> Vec<Block> {
391 r.0.iter()
392 .map(|c| Block::Para(inlines(&c.0, policy, depth)))
393 .filter(|b| match b { Block::Para(c) => !c.is_empty(), _ => true })
394 .collect()
395}
396
397/// The inlines that survive.
398fn inlines(items: &[Inline], policy: &Policy, depth: usize) -> Vec<Inline> {
399 if depth >= policy.max_depth {
400 return Vec::new();
401 }
402 let mut out = Vec::new();
403 for item in items {
404 match item {
405 Inline::Text(t) => out.push(Inline::Text(t.clone())),
406 Inline::Code(c) => out.push(Inline::Code(c.clone())),
407 Inline::Break => out.push(Inline::Break),
408 Inline::Emph { strong, content } => out.push(Inline::Emph {
409 strong: *strong,
410 content: inlines(content, policy, depth + 1),
411 }),
412 Inline::Link { to, content } => {
413 let kept = inlines(content, policy, depth + 1);
414 if policy.permits_url(to) {
415 out.push(Inline::Link { to: to.clone(), content: kept });
416 } else {
417 // The words stay and the destination goes. A reader still reads the sentence
418 // and follows nothing.
419 out.extend(kept);
420 }
421 }
422 Inline::Image { src, alt } => {
423 if policy.allow_images && policy.permits_url(src) {
424 out.push(Inline::Image { src: src.clone(), alt: alt.clone() });
425 } else if !alt.trim().is_empty() {
426 // What the image stood for is what the author said it stood for.
427 out.push(Inline::Text(alt.clone()));
428 }
429 }
430 Inline::Span { attrs, content } => {
431 let kept = inlines(content, policy, depth + 1);
432 if policy.allow_attrs {
433 out.push(Inline::Span { attrs: attrs.clone(), content: kept });
434 } else {
435 out.extend(kept);
436 }
437 }
438 }
439 }
440 out
441}
442
443
444#[cfg(test)]
445mod tests {
446 use super::*;
447 use crate::doc::{Attrs, html};
448 use oxedyne_fe2o3_core::prelude::*;
449
450 fn para(inl: Vec<Inline>) -> Doc {
451 Doc { blocks: vec![Block::Para(inl)] }
452 }
453 fn link(to: &str) -> Doc {
454 para(vec![Inline::Link { to: fmt!("{}", to), content: vec![Inline::Text(fmt!("here"))] }])
455 }
456
457 /// The whole point: a script destination does not survive, and the words around it do.
458 #[test]
459 fn test_a_script_destination_does_not_survive_00() -> Outcome<()> {
460 let p = Policy::default();
461 for bad in [
462 "javascript:alert(1)",
463 "JavaScript:alert(1)",
464 "JAVASCRIPT:alert(1)",
465 " javascript:alert(1)",
466 "java\tscript:alert(1)",
467 "java\nscript:alert(1)",
468 "data:text/html;base64,PHNjcmlwdD4=",
469 "vbscript:msgbox(1)",
470 "file:///etc/passwd",
471 ":nonsense",
472 ] {
473 let out = apply(&link(bad), &p);
474 let html = html::render(&out);
475 assert!(!html.contains("<a "), "'{}' kept its link: {}", bad, html);
476 assert!(html.contains("here"), "'{}' lost the words too: {}", bad, html);
477 }
478 Ok(())
479 }
480
481 /// An ordinary destination is untouched.
482 #[test]
483 fn test_an_ordinary_destination_survives_01() -> Outcome<()> {
484 let p = Policy::default();
485 for good in [
486 "https://example.com/a",
487 "http://example.com",
488 "mailto:someone@example.com",
489 "/posts/a-post",
490 "a-post.html",
491 "#section",
492 "?tag=rust",
493 ] {
494 let html = html::render(&apply(&link(good), &p));
495 assert!(html.contains("<a href="), "'{}' lost its link: {}", good, html);
496 }
497 Ok(())
498 }
499
500 /// A backslash is a separator to a browser, so a destination that spells `//` with one does not
501 /// pass as relative.
502 ///
503 /// The URL standard's relative states treat `\` as `/` for every special scheme, so each of
504 /// these resolves off-site from an `https` page exactly as `//host/x` does. The check read
505 /// them as relative and permitted every one, which walked past the allowlist by spelling.
506 #[test]
507 fn test_a_backslash_does_not_smuggle_a_host_09() -> Outcome<()> {
508 let p = Policy::default();
509 for bad in [
510 "\\\\evil.example/x",
511 "\\/evil.example/x",
512 "/\\evil.example/x",
513 "\\\\evil.example",
514 "\t\\\\evil.example/x",
515 ] {
516 assert!(!p.permits_url(bad), "'{}' passed as a relative destination", bad);
517 let html = html::render(&apply(&link(bad), &p));
518 assert!(!html.contains("<a "), "'{}' kept its link: {}", bad, html);
519 assert!(html.contains("here"), "'{}' lost the words too: {}", bad, html);
520 }
521 // A backslash that is not a separator is still not a way to a scheme: a Windows path
522 // names `c:` and `c` is not on the list.
523 assert!(!p.permits_url("C:\\Windows\\System32"));
524 // And an ordinary relative destination is unaffected.
525 assert!(p.permits_url("src/parse.rs"));
526 assert!(p.permits_url("/posts/a"));
527 Ok(())
528 }
529
530 /// A destination the caller rewrites is written as the caller wrote it, and one the caller
531 /// declines to rewrite loses its link and keeps its words.
532 ///
533 /// This is the containment a site publishing somebody else's prose needs: a relative
534 /// destination resolves against the *page*, not against wherever the document came from, and
535 /// one that climbs reaches whatever the site keeps up there. Mapping every destination through
536 /// the site's own function is what stops both.
537 #[test]
538 fn test_a_destination_can_be_rewritten_10() -> Outcome<()> {
539 let doc = Doc { blocks: vec![Block::Para(vec![
540 Inline::Link {
541 to: fmt!("src/parse.rs"),
542 content: vec![Inline::Text(fmt!("the parser"))],
543 },
544 Inline::Link {
545 to: fmt!("../../elsewhere"),
546 content: vec![Inline::Text(fmt!("up and out"))],
547 },
548 Inline::Image { src: fmt!("logo.png"), alt: fmt!("a logo") },
549 ])] };
550 let out = retarget(&doc, |to: &str| {
551 if to.starts_with("..") {
552 return None;
553 }
554 Some(fmt!("/repo/files/{}", to))
555 });
556 let html = html::render(&out);
557 assert!(html.contains("href=\"/repo/files/src/parse.rs\""),
558 "the destination was not rewritten: {}", html);
559 assert!(html.contains("src=\"/repo/files/logo.png\""),
560 "an image's source was not rewritten: {}", html);
561 assert!(!html.contains("elsewhere"),
562 "a destination the caller declined survived: {}", html);
563 assert!(html.contains("up and out"),
564 "and it took its words with it: {}", html);
565 // A code block holds no destination and comes through as it was.
566 let code = Doc { blocks: vec![Block::Code {
567 lang: Some(fmt!("rust")),
568 text: fmt!("let a = 1;"),
569 }] };
570 assert_eq!(retarget(&code, |to: &str| Some(fmt!("{}", to))), code);
571 Ok(())
572 }
573
574 /// A relative destination can be refused on its own, without opening every scheme.
575 #[test]
576 fn test_relative_can_be_refused_02() -> Outcome<()> {
577 let mut p = Policy::default();
578 p.allow_relative = false;
579 assert!(!p.permits_url("/posts/a"));
580 assert!(!p.permits_url("a.html"));
581 assert!(p.permits_url("https://example.com"));
582 Ok(())
583 }
584
585 /// An image is a request to a third party, so a comment does not make one; its alt text stands.
586 #[test]
587 fn test_an_image_does_not_survive_by_default_03() -> Outcome<()> {
588 let d = para(vec![Inline::Image {
589 src: fmt!("https://tracker.example/pixel.gif"),
590 alt: fmt!("a picture of a cat"),
591 }]);
592 let html = html::render(&apply(&d, &Policy::default()));
593 assert!(!html.contains("<img"), "an image survived: {}", html);
594 assert!(!html.contains("tracker.example"), "the tracker's address survived: {}", html);
595 assert!(html.contains("a picture of a cat"), "the alt text was lost: {}", html);
596
597 // A caller that wants images says so, and then gets them.
598 let mut p = Policy::default();
599 p.allow_images = true;
600 let html = html::render(&apply(&d, &p));
601 assert!(html.contains("<img"), "an allowed image was still dropped: {}", html);
602 Ok(())
603 }
604
605 /// A stranger does not get to name things in the site's own document.
606 #[test]
607 fn test_attributes_are_dropped_but_content_is_kept_04() -> Outcome<()> {
608 let mut attrs = Attrs::default();
609 attrs.id = Some(fmt!("main"));
610 attrs.classes = vec![fmt!("site-banner")];
611 let d = Doc { blocks: vec![Block::Div {
612 attrs: attrs.clone(),
613 content: vec![Block::Para(vec![Inline::Text(fmt!("the words"))])],
614 }] };
615 let html = html::render(&apply(&d, &Policy::default()));
616 assert!(!html.contains("main"), "an id was borrowed: {}", html);
617 assert!(!html.contains("site-banner"), "a class was borrowed: {}", html);
618 assert!(html.contains("the words"), "the content was lost: {}", html);
619 Ok(())
620 }
621
622 /// A heading is demoted rather than dropped: it should not outrank the page it sits in.
623 #[test]
624 fn test_a_heading_is_demoted_05() -> Outcome<()> {
625 let d = Doc { blocks: vec![Block::Heading {
626 level: 1, content: vec![Inline::Text(fmt!("shouting"))],
627 }] };
628 let html = html::render(&apply(&d, &Policy::default()));
629 assert!(!html.contains("<h1"), "an h1 survived inside a page: {}", html);
630 assert!(html.contains("<h3"), "the heading was not demoted to the floor: {}", html);
631 assert!(html.contains("shouting"));
632 Ok(())
633 }
634
635 /// A tree deeper than the policy allows is truncated rather than walked.
636 #[test]
637 fn test_depth_is_bounded_06() -> Outcome<()> {
638 let mut inner = vec![Block::Para(vec![Inline::Text(fmt!("bottom"))])];
639 for _ in 0..64 {
640 inner = vec![Block::Quote(inner)];
641 }
642 let mut p = Policy::default();
643 p.max_depth = 8;
644 let out = apply(&Doc { blocks: inner }, &p);
645 let html = html::render(&out);
646 assert!(!html.contains("bottom"), "the bottom of a too-deep tree survived");
647 // Counting the quotes that did survive proves it stopped where it was told to.
648 assert!(html.matches("<blockquote>").count() <= 8, "it went deeper than told: {}", html);
649 Ok(())
650 }
651
652 /// The trusting policy leaves a document as it was, so one code path serves both cases.
653 #[test]
654 fn test_the_trusting_policy_changes_nothing_07() -> Outcome<()> {
655 let p = Policy::trusting();
656 assert!(p.permits_url("javascript:alert(1)"), "the trusting policy refused a scheme");
657 let d = para(vec![Inline::Image { src: fmt!("a.png"), alt: fmt!("alt") }]);
658 let html = html::render(&apply(&d, &p));
659 assert!(html.contains("<img"), "the trusting policy dropped an image: {}", html);
660 Ok(())
661 }
662
663 /// Text is never markup, whatever it says, and the policy does not change that.
664 #[test]
665 fn test_words_that_look_like_markup_stay_words_08() -> Outcome<()> {
666 let d = para(vec![Inline::Text(fmt!("<script>steal()</script> & <img onerror=x>"))]);
667 let html = html::render(&apply(&d, &Policy::default()));
668 assert!(!html.contains("<script>"), "a script tag was written: {}", html);
669 assert!(!html.contains("<img"), "an img tag was written: {}", html);
670 assert!(html.contains("&lt;script&gt;"), "the words were lost: {}", html);
671 Ok(())
672 }
673}