Skip to main content

rustango_cms/
markdown.rs

1//! Server-side Markdown → HTML rendering for page bodies.
2//!
3//! Authors write markdown in the admin (via the extension-field
4//! editor). At render time, `pulldown-cmark` converts to HTML; the
5//! result is then run through `ammonia` so any embedded `<script>`,
6//! event handlers, `javascript:` hrefs, or other XSS vectors are
7//! stripped before reaching the browser.
8//!
9//! Exposed as the Tera filter `markdown`. Use it like:
10//!
11//! ```tera
12//! {{ extension.body_markdown | markdown | safe }}
13//! ```
14//!
15//! The `| safe` is required — the filter returns trusted HTML, and
16//! without `safe` Tera would re-escape the angle brackets.
17
18use pulldown_cmark::{html, Options, Parser};
19
20/// Convert a markdown source string to sanitized HTML.
21///
22/// Enables the common GFM extensions (tables, strikethrough, task
23/// lists, autolinks, footnotes) so authors get the syntax they expect
24/// from GitHub / Notion / Obsidian. The post-pass through ammonia
25/// keeps it XSS-safe: only a curated tag/attribute allowlist
26/// survives.
27#[must_use]
28pub fn render(src: &str) -> String {
29    let mut opts = Options::empty();
30    opts.insert(Options::ENABLE_TABLES);
31    opts.insert(Options::ENABLE_STRIKETHROUGH);
32    opts.insert(Options::ENABLE_TASKLISTS);
33    opts.insert(Options::ENABLE_FOOTNOTES);
34    let parser = Parser::new_ext(src, opts);
35    let mut html_out = String::with_capacity(src.len() + src.len() / 4);
36    html::push_html(&mut html_out, parser);
37    base_sanitizer().clean(&html_out).to_string()
38}
39
40/// The shared ammonia allow-list: the default policy PLUS `class` on
41/// `<code>` / `<pre>` so fenced code blocks keep their `language-…`
42/// hint (`pulldown-cmark` emits `<code class="language-rust">` for a
43/// ```rust fence) for client-side highlighters. A class is
44/// inert — no script / URL vector — so allowing it is XSS-safe.
45fn base_sanitizer() -> ammonia::Builder<'static> {
46    let mut b = ammonia::Builder::default();
47    b.add_tag_attributes("code", ["class"]);
48    b.add_tag_attributes("pre", ["class"]);
49    b
50}
51
52/// Sanitize an HTML string for richtext storage / preview. Uses the same
53/// ammonia allow-list as the markdown renderer, PLUS the move-safe
54/// internal-link attributes `<a linktype="page|media" id="N">` that
55/// the `| richtext` filter resolves to real URLs at render time. Ammonia's
56/// default policy strips unknown `<a>` attributes, which would drop the
57/// `linktype`/`id` pair and turn move-safe links into broken ones the next
58/// time a page is moved — so they're explicitly allow-listed here. Both are
59/// inert (no script/URL vector), so allowing them is XSS-safe. Used by the
60/// richtext on-save sanitizer (`sanitized_extension_form`) and the
61/// preview pane.
62#[must_use]
63pub fn sanitize_html(src: &str) -> String {
64    let mut builder = base_sanitizer();
65    builder.add_tag_attributes("a", ["linktype", "id"]);
66    builder.clean(src).to_string()
67}
68
69/// Register the `markdown` filter on a Tera instance. Host apps
70/// already calling `crate::translation::register_tera_filter` should
71/// call this too so `{{ … | markdown }}` resolves.
72pub fn register_tera_filter(tera: &mut tera::Tera) {
73    tera.register_filter("markdown", markdown_filter);
74}
75
76fn markdown_filter(
77    value: &tera::Value,
78    _args: &std::collections::HashMap<String, tera::Value>,
79) -> tera::Result<tera::Value> {
80    let Some(src) = value.as_str() else {
81        return Ok(value.clone());
82    };
83    if src.is_empty() {
84        return Ok(tera::Value::String(String::new()));
85    }
86    Ok(tera::Value::String(render(src)))
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92
93    #[test]
94    fn renders_basic_markdown() {
95        let html = render("# Hello\n\nA *world* of [links](https://example.com).");
96        assert!(html.contains("<h1>Hello</h1>"));
97        assert!(html.contains("<em>world</em>"));
98        assert!(html.contains(r#"<a href="https://example.com""#));
99    }
100
101    #[test]
102    fn strips_inline_script() {
103        let html = render("Hello <script>alert(1)</script> world");
104        assert!(!html.contains("<script>"));
105        assert!(!html.contains("alert"));
106    }
107
108    #[test]
109    fn strips_javascript_href() {
110        let html = render("[click](javascript:alert(1))");
111        // ammonia rewrites unsafe schemes to nothing-or-text — what
112        // matters is the JS doesn't survive.
113        assert!(!html.contains("javascript:"));
114    }
115
116    #[test]
117    fn supports_tables() {
118        let html = render("| a | b |\n|---|---|\n| 1 | 2 |");
119        assert!(html.contains("<table>"));
120        assert!(html.contains("<th>a</th>"));
121    }
122
123    #[test]
124    fn empty_input_empty_output() {
125        assert_eq!(render(""), "");
126    }
127
128    // `sanitize_html` cleans stored richtext; pin the same XSS
129    // guarantees the markdown path gets: no script tags, no
130    // javascript: hrefs.
131    #[test]
132    fn sanitize_html_strips_script_tags() {
133        let out = sanitize_html("<p>Hi <script>alert(1)</script></p>");
134        assert!(!out.contains("<script>"), "got `{out}`");
135        assert!(!out.contains("alert(1)"), "got `{out}`");
136        assert!(out.contains("<p>"), "got `{out}`");
137    }
138
139    #[test]
140    fn sanitize_html_keeps_safe_richtext_shape() {
141        let out = sanitize_html(r#"<h2>Title</h2><p>Body <a href="/about">link</a></p>"#);
142        assert!(out.contains("<h2>Title</h2>"));
143        assert!(out.contains(r#"<a href="/about""#));
144    }
145
146    #[test]
147    fn sanitize_html_rejects_javascript_href() {
148        let out = sanitize_html(r#"<a href="javascript:alert(1)">x</a>"#);
149        assert!(!out.contains("javascript:"), "got `{out}`");
150    }
151
152    #[test]
153    fn sanitize_html_empty_input_empty_output() {
154        assert_eq!(sanitize_html(""), "");
155    }
156
157    // #403 — fenced code blocks must keep their `language-…` class so
158    // client-side highlighters (Prism / highlight.js) can colour them.
159    #[test]
160    fn fenced_code_keeps_language_class() {
161        let html = render("```rust\nfn main() {}\n```");
162        assert!(
163            html.contains(r#"class="language-rust""#),
164            "language hint must survive the sanitizer; got `{html}`"
165        );
166        // The body is still escaped (no live markup from code content).
167        let escaped = render("```html\n<script>x</script>\n```");
168        assert!(!escaped.contains("<script>"), "got `{escaped}`");
169        assert!(escaped.contains("&lt;script&gt;"), "got `{escaped}`");
170    }
171
172    #[test]
173    fn sanitize_html_keeps_code_language_class() {
174        let out = sanitize_html(r#"<pre><code class="language-python">x = 1</code></pre>"#);
175        assert!(
176            out.contains(r#"class="language-python""#),
177            "richtext code class must survive; got `{out}`"
178        );
179    }
180
181    #[test]
182    fn sanitize_html_still_strips_event_handlers_on_code() {
183        // Allowing `class` on code must not open the door to other
184        // attributes — onclick etc. still go.
185        let out = sanitize_html(r#"<code class="language-x" onclick="alert(1)">x</code>"#);
186        assert!(out.contains(r#"class="language-x""#), "got `{out}`");
187        assert!(!out.contains("onclick"), "got `{out}`");
188    }
189
190    #[test]
191    fn sanitize_html_keeps_mailto_and_anchor_links() {
192        // #399 — email + in-page anchor links must survive on-save
193        // sanitization (mailto is a default-allowed scheme; `#frag` is a
194        // relative URL, passed through like `/about`).
195        let mail = sanitize_html(r#"<a href="mailto:hi@example.com">mail</a>"#);
196        assert!(
197            mail.contains(r#"href="mailto:hi@example.com""#),
198            "got `{mail}`"
199        );
200        let anchor = sanitize_html(r##"<a href="#section-2">jump</a>"##);
201        assert!(anchor.contains(r##"href="#section-2""##), "got `{anchor}`");
202    }
203
204    #[test]
205    fn sanitize_html_preserves_move_safe_linktype_anchors() {
206        // #294 — the `<a linktype="page|media" id="N">` storage shape the
207        // `| richtext` filter resolves must survive on-save sanitization.
208        let out = sanitize_html(r#"<a linktype="page" id="42">Team</a>"#);
209        assert!(out.contains(r#"linktype="page""#), "got `{out}`");
210        assert!(out.contains(r#"id="42""#), "got `{out}`");
211        let media = sanitize_html(r#"<a linktype="media" id="7">Doc</a>"#);
212        assert!(
213            media.contains(r#"linktype="media""#) && media.contains(r#"id="7""#),
214            "got `{media}`"
215        );
216    }
217
218    #[test]
219    fn sanitize_html_preserves_richtext_tables_and_images() {
220        // #294 (C) — the TipTap editor emits tables + images; both must
221        // survive on-save sanitization (ammonia's default allow-list
222        // covers table/thead/tbody/tr/th/td + img).
223        // The real editor emits colgroup + per-cell colspan/rowspan + a
224        // cosmetic `style` (which ammonia drops — harmless). The table
225        // STRUCTURE + cell content + colspan must survive.
226        let table = sanitize_html(
227            r#"<table style="min-width:50px"><colgroup><col style="min-width:25px"></colgroup><tbody><tr><th colspan="1" rowspan="1"><p>A</p></th></tr><tr><td colspan="1" rowspan="1"><p>1</p></td></tr></tbody></table>"#,
228        );
229        assert!(
230            table.contains("<table")
231                && table.contains("<th")
232                && table.contains("<td")
233                && table.contains(r#"colspan="1""#)
234                && table.contains("A")
235                && table.contains("1"),
236            "table structure stripped: `{table}`"
237        );
238        // Media serve URLs are id-stable, so a plain <img src> is move-safe.
239        let img = sanitize_html(r#"<p><img src="/media/serve/9/x.png" alt="pic"></p>"#);
240        assert!(
241            img.contains(r#"src="/media/serve/9/x.png""#) && img.contains(r#"alt="pic""#),
242            "img stripped: `{img}`"
243        );
244    }
245
246    #[test]
247    fn sanitize_html_still_strips_dangerous_attrs_on_linktype_anchor() {
248        // allow-listing linktype/id must NOT open an XSS hole on <a>.
249        let out = sanitize_html(
250            r#"<a linktype="page" id="1" onclick="alert(1)" href="javascript:alert(2)">x</a>"#,
251        );
252        assert!(out.contains(r#"linktype="page""#), "got `{out}`");
253        assert!(!out.contains("onclick"), "got `{out}`");
254        assert!(!out.contains("javascript:"), "got `{out}`");
255    }
256}