Skip to content
Merged
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
8 changes: 5 additions & 3 deletions crates/markkit/src/render/escape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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&colon;`).
//! - Fences are one backtick longer than the longest backtick run in the code.
Expand Down Expand Up @@ -254,6 +254,7 @@ pub(crate) fn safe_destination(url: &str, kind: UrlKind) -> Option<String> {
'<' => 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];
Expand Down Expand Up @@ -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);
}
Expand Down
5 changes: 3 additions & 2 deletions crates/markkit/src/render/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions crates/markkit/tests/fixtures/html/table_link_title.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<table><tr><th>Link</th><th>Code</th></tr><tr><td><a href="https://example.com/a`b" title="a|b`c">Open</a></td><td><code>&lt;table&gt;</code></td></tr></table>
3 changes: 3 additions & 0 deletions crates/markkit/tests/fixtures/html/table_link_title.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
| Link | Code |
| --- | --- |
| [Open](https://example.com/a%60b "a\|b\`c") | `<table>` |
123 changes: 123 additions & 0 deletions crates/markkit/tests/fixtures/ir/footnote-link-code.json
Original file line number Diff line number Diff line change
@@ -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": "<!t",
"language": null
}
}
]
},
{
"checked": true,
"children": [
{
"FootnoteDefinition": {
"children": [
{
"List": {
"items": [
{
"checked": true,
"children": [
{
"Image": {
"alt": "",
"src": ""
}
}
]
}
],
"ordered": false,
"start": null
}
}
],
"label": ""
}
}
]
}
],
"ordered": true,
"start": null
}
}
]
}
]
}
}
],
"level": 5
}
}
]
}
]
}
}
]
}
5 changes: 5 additions & 0 deletions crates/markkit/tests/html_fixtures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,8 @@ fn fixture_news_page_main_content() {
let actual = m.extract_html_sync(&html).unwrap();
assert_eq!(actual, expected, "\n--- Actual ---\n{actual}");
}

#[test]
fn fixture_table_link_title() {
fixture_test("table_link_title");
}
143 changes: 136 additions & 7 deletions crates/markkit/tests/output_safety.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,42 @@ fn assert_safe(md: &str) {
for ev in events(md) {
match ev {
Event::Html(h) | Event::InlineHtml(h) => 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::<String>()
.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();
Expand Down Expand Up @@ -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("<table>".into()),
])],
rows: vec![],
}]);
assert_safe(&md);
assert!(
events(&md)
.iter()
.any(|e| matches!(e, Event::Code(c) if c.as_ref() == "<table>")),
"{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("<!".into()),
Node::InlineCode("<!t".into()),
])]);
assert_safe(&md);
let codes: Vec<_> = events(&md)
.into_iter()
.filter_map(|e| match e {
Event::Code(c) => Some(c.into_string()),
_ => None,
})
.collect();
assert_eq!(codes, vec!["<!", "<!t"], "{md}");
assert!(md.contains("%60"), "{md}");
}

#[test]
fn ir_fuzz_footnote_link_code_regression() {
let doc: Document =
serde_json::from_str(include_str!("fixtures/ir/footnote-link-code.json")).unwrap();
assert_safe(&MarkdownRenderer::new().render(&doc));
}
2 changes: 2 additions & 0 deletions knowledge/log.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## 2026-11-25

- [Threat Model](security/threat-model.md) T1/S17: separate footnote references from following colons, escape table-title pipes/backticks and encode destination backticks. Three nightly crash seeds and deterministic regressions cover unintended reference links and raw HTML; see [Fuzzing](security/fuzzing.md).

- [Threat Model](security/threat-model.md): require `url` 2.5.9 for RUSTSEC-2026-0592; shipping audit rejects the prior locked version.

- [Format Support](formats/format-support.md): bounded decoded email clean/full views with conservative omission spans; no model or network. [Threat Model](security/threat-model.md) records plain-text rendering responsibility and limit checks on forwarded/empty bodies; runnable example covers the new Rust API.
Expand Down
4 changes: 3 additions & 1 deletion knowledge/security/fuzzing.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ long nightly runs that find what generators miss. See
| `render_ir` | Arbitrary IR tree (`arbitrary`) | Renderer on trees no parser emits yet |

Seeds: `fuzz/seeds/<target>/` (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

Expand Down
7 changes: 4 additions & 3 deletions knowledge/security/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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` |
Expand Down
Loading