Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

### Fixed

- Refuse to render Markdown whose markup nests deeper than 256 levels, which
cost the sanitizer minutes of CPU per request.
- Reject off-origin and scheme-relative `Referer` values when redirecting back
after a theme change, closing an open-redirect bypass via `//`-prefixed paths.
- Unlink Unix domain socket after shutdown.
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions crates/wastebin_highlight/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ publish = false

[dependencies]
ammonia = "4"
# The version ammonia parses with: the nesting check has to build the tree the sanitizer does.
html5ever = "0.40"
pulldown-cmark = { version = "0.13", default-features = false, features = ["html"] }
syntect = { workspace = true }
thiserror = { workspace = true }
Expand Down
2 changes: 2 additions & 0 deletions crates/wastebin_highlight/src/highlight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ pub enum Error {
SyntaxParsing(#[from] syntect::parsing::ParsingError),
#[error("failed to escaped")]
Escape,
#[error("markup nested deeper than {0} levels")]
TooDeeplyNested(usize),
}

const HIGHLIGHT_LINE_LENGTH_CUTOFF: usize = 2048;
Expand Down
57 changes: 57 additions & 0 deletions crates/wastebin_highlight/src/markdown.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
mod nesting;

use std::sync::OnceLock;

use ammonia::Builder;
use pulldown_cmark::{BlockQuoteKind, CodeBlockKind, CowStr, Event, Options, Parser, Tag, html};

use crate::highlight::Error;
use crate::{Highlighter, Html};
use nesting::nesting_depth;

/// Deepest markup nesting handed to the sanitizer.
///
/// Building the DOM is quadratic in nesting depth, and raw HTML in a paste reaches it verbatim:
/// a megabyte of `<div>` is a quarter million levels deep and costs minutes of CPU. Prose does not
/// come close to this bound — deeply nested lists sit around a dozen levels.
const MAX_NESTING_DEPTH: usize = 256;

/// Render CommonMark `text` to HTML. Fenced code blocks with a known language are syntax
/// highlighted via `highlighter`; unknown languages fall back to plain text.
///
/// Raw HTML embedded in the source is passed through the parser and then sanitized by
/// [`ammonia`], so tags like `<details>` or `<kbd>` survive while `<script>`, inline event
/// handlers, `javascript:` URLs and other XSS vectors are stripped.
///
/// Markup nested deeper than [`MAX_NESTING_DEPTH`] is rejected instead of sanitized.
pub fn render(text: &str, highlighter: &Highlighter) -> Result<Html, Error> {
let options = Options::ENABLE_TABLES
| Options::ENABLE_STRIKETHROUGH
Expand All @@ -25,6 +37,11 @@ pub fn render(text: &str, highlighter: &Highlighter) -> Result<Html, Error> {
let mut raw = String::with_capacity(text.len());
html::push_html(&mut raw, events.into_iter());

let depth = nesting_depth(&raw);
if depth > MAX_NESTING_DEPTH {
return Err(Error::TooDeeplyNested(MAX_NESTING_DEPTH));
}

Ok(Html::new(sanitizer().clean(&raw).to_string()))
}

Expand Down Expand Up @@ -96,6 +113,46 @@ mod tests {
render(text, highlighter).map(Html::into_inner)
}

#[test]
fn deeply_nested_markup_is_rejected() {
let md = "<div>".repeat(MAX_NESTING_DEPTH + 10);
let result = render(&md, &Highlighter::default());
assert!(matches!(result, Err(Error::TooDeeplyNested(_))));
}

#[test]
fn nesting_hidden_behind_unmatched_close_tags_is_rejected() {
let md = "<div></span>".repeat(MAX_NESTING_DEPTH + 10);
let result = render(&md, &Highlighter::default());
assert!(matches!(result, Err(Error::TooDeeplyNested(_))));
}

/// HTML5 ignores a trailing slash on anything but a void element, so `<div/>` opens a level
/// just like `<div>`.
#[test]
fn a_slash_does_not_close_a_non_void_element() {
let md = "<div/>".repeat(MAX_NESTING_DEPTH + 10);
let result = render(&md, &Highlighter::default());
assert!(matches!(result, Err(Error::TooDeeplyNested(_))));
}

#[test]
fn nesting_within_the_limit_still_renders() -> Result<(), Box<dyn std::error::Error>> {
let md = "<div>".repeat(32);
let html = render_string(&md, &Highlighter::default())?;
assert!(html.contains("<div>"), "got: {html}");
Ok(())
}

#[test]
fn flat_markup_is_not_mistaken_for_nesting() -> Result<(), Box<dyn std::error::Error>> {
// Siblings and void elements open no levels, so a long flat document must render.
let md = format!("{}\n\n{}", "<div>x</div>".repeat(500), "<br>".repeat(500));
let html = render_string(&md, &Highlighter::default())?;
assert!(html.contains("<div>"), "got: {html}");
Ok(())
}

#[test]
fn heading() -> Result<(), Box<dyn std::error::Error>> {
let html = render_string("# Hello", &Highlighter::default())?;
Expand Down
Loading
Loading