diff --git a/CHANGELOG.md b/CHANGELOG.md index a381762..9a46a8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ### Security +- Prevent footnote references from becoming unintended link definitions, and + keep link titles and destinations from exposing raw HTML through code spans. + - Require `url` 2.5.9 or later to avoid nested `blob:` URL origin stack overflow (RUSTSEC-2026-0592). diff --git a/crates/markkit/fuzz/seeds/html/table-link-title-pipe.html b/crates/markkit/fuzz/seeds/html/table-link-title-pipe.html new file mode 100644 index 0000000..7ad1e8a Binary files /dev/null and b/crates/markkit/fuzz/seeds/html/table-link-title-pipe.html differ diff --git a/crates/markkit/fuzz/seeds/markdown/footnote-reference-colon.md b/crates/markkit/fuzz/seeds/markdown/footnote-reference-colon.md new file mode 100644 index 0000000..699865b Binary files /dev/null and b/crates/markkit/fuzz/seeds/markdown/footnote-reference-colon.md differ diff --git a/crates/markkit/fuzz/seeds/render_ir/inline-wrapper-code b/crates/markkit/fuzz/seeds/render_ir/inline-wrapper-code new file mode 100644 index 0000000..63387b5 Binary files /dev/null and b/crates/markkit/fuzz/seeds/render_ir/inline-wrapper-code differ diff --git a/crates/markkit/src/render/escape.rs b/crates/markkit/src/render/escape.rs index 09568a0..f85c05b 100644 --- a/crates/markkit/src/render/escape.rs +++ b/crates/markkit/src/render/escape.rs @@ -12,7 +12,7 @@ //! `http`, `https`, relative and raster `data:image/*` for images. Anything else is //! dropped and its text (link children, image alt) kept. Scheme detection ignores //! ASCII whitespace and control characters anywhere, as browsers do. -//! - Destinations are emitted bare with `( ) < > \ space` percent-encoded and entity-like +//! - Destinations are emitted bare with `( ) < > \ backtick space` percent-encoded and entity-like //! `&` backslash-escaped, so a destination can neither end early nor decode into //! another scheme (`javascript:`). //! - Fences are one backtick longer than the longest backtick run in the code. @@ -254,6 +254,7 @@ pub(crate) fn safe_destination(url: &str, kind: UrlKind) -> Option { '<' => out.push_str("%3C"), '>' => out.push_str("%3E"), '\\' => out.push_str("%5C"), + '`' => out.push_str("%60"), '&' if entity_like(&chars[i..]) => out.push_str("\\&"), c if c.is_whitespace() => { let mut tmp = [0u8; 4]; @@ -320,8 +321,9 @@ pub(crate) fn link_title(t: &str) -> String { for c in t.chars() { match c { // `<` too: if the link ever fails to parse, the title must not - // become raw HTML. - '"' | '\\' | '<' => { + // become raw HTML. Pipes must not split table cells; backticks + // must not capture later code spans when a link fails to parse. + '"' | '\\' | '<' | '`' | '|' => { out.push('\\'); out.push(c); } diff --git a/crates/markkit/src/render/markdown.rs b/crates/markkit/src/render/markdown.rs index 578c855..8e9d312 100644 --- a/crates/markkit/src/render/markdown.rs +++ b/crates/markkit/src/render/markdown.rs @@ -472,8 +472,9 @@ impl MarkdownRenderer { Position::Inline }; // A footnote reference followed by a new text node beginning - // with `(` would combine into an inline link (`[^x](...)`). - if self.buf.ends_with(']') && t.starts_with('(') { + // with `(` or `:` could create an inline link or a reference + // definition in readers without footnote support. + if self.buf.ends_with(']') && t.starts_with(['(', ':']) { self.buf.push('\\'); } self.line_start = escape::push_text(&mut self.buf, t, pos); diff --git a/crates/markkit/tests/fixtures/html/table_link_title.html b/crates/markkit/tests/fixtures/html/table_link_title.html new file mode 100644 index 0000000..246fe7f --- /dev/null +++ b/crates/markkit/tests/fixtures/html/table_link_title.html @@ -0,0 +1 @@ +
LinkCode
Open<table>
diff --git a/crates/markkit/tests/fixtures/html/table_link_title.md b/crates/markkit/tests/fixtures/html/table_link_title.md new file mode 100644 index 0000000..98c7527 --- /dev/null +++ b/crates/markkit/tests/fixtures/html/table_link_title.md @@ -0,0 +1,3 @@ +| Link | Code | +| --- | --- | +| [Open](https://example.com/a%60b "a\|b\`c") | `` | diff --git a/crates/markkit/tests/fixtures/ir/footnote-link-code.json b/crates/markkit/tests/fixtures/ir/footnote-link-code.json new file mode 100644 index 0000000..e7d1503 --- /dev/null +++ b/crates/markkit/tests/fixtures/ir/footnote-link-code.json @@ -0,0 +1,123 @@ +{ + "ir_version": 2, + "nodes": [ + { + "List": { + "items": [ + { + "checked": true, + "children": [ + { + "FootnoteReference": { + "label": "" + } + }, + { + "Text": ":" + }, + { + "FootnoteReference": { + "label": "" + } + } + ] + } + ], + "ordered": true, + "start": 569201 + } + }, + { + "DefinitionList": { + "items": [ + { + "definitions": [], + "term": [ + { + "Heading": { + "children": [ + { + "Link": { + "children": [ + { + "FootnoteReference": { + "label": "" + } + } + ], + "title": "", + "url": "`" + } + }, + { + "DefinitionList": { + "items": [ + { + "definitions": [], + "term": [ + { + "List": { + "items": [ + { + "checked": true, + "children": [ + { + "CodeBlock": { + "code": " panic!("raw HTML {h:?} in {md:?}"), - Event::Start(Tag::Link { dest_url, .. }) - | Event::Start(Tag::Image { dest_url, .. }) => { - let lower = dest_url.to_ascii_lowercase(); - for bad in ["javascript:", "vbscript:", "data:text", "file:"] { - assert!(!lower.contains(bad), "unsafe url {dest_url:?} in {md:?}"); - } - } + Event::Start(Tag::Link { dest_url, .. }) => assert_safe_url(&dest_url, false, md), + Event::Start(Tag::Image { dest_url, .. }) => assert_safe_url(&dest_url, true, md), _ => {} } } } +fn assert_safe_url(url: &str, image: bool, md: &str) { + let probe: String = url + .trim_start_matches(|c: char| c <= ' ') + .chars() + .filter(|c| !c.is_ascii_control()) + .collect::() + .to_ascii_lowercase(); + let Some(i) = probe.find([':', '/', '?', '#']) else { + return; + }; + let scheme = &probe[..i]; + let valid = scheme.starts_with(|c: char| c.is_ascii_alphabetic()) + && scheme + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')); + if probe.as_bytes()[i] != b':' || !valid { + return; + } + let allowed = if image { + matches!(scheme, "http" | "https") || probe.starts_with("data:image/") + } else { + matches!(scheme, "http" | "https" | "mailto" | "tel" | "ftp") + }; + assert!( + allowed && !probe.starts_with("data:image/svg"), + "unsafe url {url:?} in {md:?}" + ); +} + /// Concatenated text events of the rendered Markdown, as a reader would see it. fn visible_text(md: &str) -> String { let mut out = String::new(); @@ -1183,3 +1207,108 @@ fn display_math_in_inline_context_is_flattened() { assert_safe(&md); assert!(md.starts_with("| $`x = 1`$ |"), "{md}"); } + +#[test] +fn footnote_reference_cannot_open_reference_definition() { + let md = render(vec![ + para(vec![ + Node::FootnoteReference { + label: "note".into(), + }, + text(":javascript:alert(1)"), + ]), + para(vec![Node::FootnoteReference { + label: "note".into(), + }]), + ]); + assert_safe(&md); + assert!( + !events(&md) + .iter() + .any(|e| matches!(e, Event::Start(Tag::Link { .. }))) + ); +} + +#[test] +fn link_title_pipe_cannot_split_table_code() { + let md = render(vec![Node::Table { + source: None, + alignments: vec![], + headers: vec![TableCell::new(vec![ + Node::Link { + url: "https://example.com".into(), + title: Some("a|b".into()), + children: vec![text("link")], + }, + Node::InlineCode("
".into()), + ])], + rows: vec![], + }]); + assert_safe(&md); + assert!( + events(&md) + .iter() + .any(|e| matches!(e, Event::Code(c) if c.as_ref() == "
")), + "{md}" + ); +} + +#[cfg(feature = "html")] +#[test] +fn html_fuzz_table_link_title_regression() { + let input = include_bytes!("../fuzz/seeds/html/table-link-title-pipe.html"); + let out = markkit::Markkit::builder() + .build() + .extract_document_sync(input, markkit::DocumentHint::file_name("fuzz.html")) + .unwrap(); + assert_safe(&out.markdown); +} + +#[cfg(feature = "markdown")] +#[test] +fn markdown_fuzz_footnote_reference_regression() { + let input = include_bytes!("../fuzz/seeds/markdown/footnote-reference-colon.md"); + let out = markkit::Markkit::builder() + .build() + .extract_document_sync(input, markkit::DocumentHint::file_name("fuzz.md")) + .unwrap(); + assert_safe(&out.markdown); +} + +#[test] +fn destination_backtick_cannot_capture_following_code() { + let md = render(vec![para(vec![ + Node::Link { + url: "`".into(), + title: Some("".into()), + children: vec![ + Node::FootnoteReference { + label: "note".into(), + }, + Node::Image { + src: "".into(), + alt: "".into(), + }, + ], + }, + Node::InlineCode(" = events(&md) + .into_iter() + .filter_map(|e| match e { + Event::Code(c) => Some(c.into_string()), + _ => None, + }) + .collect(); + assert_eq!(codes, vec!["/` (committed, small) plus `tests/fixtures/html` -for `html`. `fuzz/corpus/` and `fuzz/artifacts/` are git-ignored. +for `html`. November 2026 regressions retain the HTML table-title, Markdown +footnote-colon and direct-IR link/code crash seeds; `output_safety` also checks +the minimized IR fixture deterministically. `fuzz/corpus/` and `fuzz/artifacts/` are git-ignored. ## Running diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index dca9bef..344c21a 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -59,8 +59,9 @@ that renders as headings, links, code fences or tables). are indented by the marker width (`1. ` = 3, `10. ` = 4); a block always starts on its own line after a blank line; hard breaks never produce a blank line; nested links render as text; redundant nested emphasis wrappers render once; - adjacent bracketed nodes and opening parentheses are separated; empty - destinations are written `<>`; link titles escape `"`, `\` and `<`. + adjacent bracketed nodes and opening parentheses or colons are separated; empty + destinations are written `<>`; link titles escape `"`, `\`, `<`, backticks and pipes. Destinations encode + backticks so invalid links cannot capture later code spans. - Task checkboxes occupy their own line before the item body so they cannot turn a leading code fence into paragraph text. Definition lists render as a term paragraph and ordinary GFM list items, keeping nested blocks safe @@ -637,7 +638,7 @@ shared renderer under `max_output_size` (`tests/registry.rs`). | S14 | Returned Markdown never exceeds `max_output_size` | `limits::*output_cap*` | | S15 | No configuration of `max_nesting_depth` can overflow the stack | `limits::*hard_ceiling_survives_small_stack` | | S16 | Extraction stops with `ResourceLimit` once `timeout` passes (checked at least after each non-interruptible third-party step) | `limits::*zero_timeout_rejects`, `limits::tests::*` | -| S17 | Rendered markdown has no raw HTML, no non-allowlisted link/image scheme, and document text cannot create Markdown structure; footnote bodies are separated by a blank line so non-footnote readers cannot interpret them as reference destinations | `output_safety::*`, including `footnote_body_cannot_become_reference_link_destination` (both reader modes), pulldown-cmark oracle + proptests | +| S17 | Rendered markdown has no raw HTML, no non-allowlisted link/image scheme, and document text cannot create Markdown structure; footnote bodies are separated by a blank line so non-footnote readers cannot interpret them as reference destinations | `output_safety::*`, including `footnote_body_cannot_become_reference_link_destination` (both reader modes), `footnote_reference_cannot_open_reference_definition`, exact HTML/Markdown/IR fuzz regressions, pulldown-cmark oracle + proptests | | S18 | Text, Markdown, CSV/TSV, notebook and email output never contains C0 controls (except tab/newline); Markdown raw HTML (blocks, inline tags) is never copied | `text_integration::security_*`, `csv_integration::security_*`, `notebook_integration::security_*`, `email_integration::security_*` | | S19 | No PDF stream is decoded past `max_pdf_stream_size`, by markkit or hayro | `pdf_security::*bomb*`, `pdf_security::chained_filters_are_measured_after_every_stage` | | S20 | Hidden content is not rendered by default (HTML, DOCX, ODT, EPUB) | `hidden_content::*`, `odt_integration::security_hidden_content_skipped_by_default`, `epub_integration::security_hidden_content_skipped_by_default` |