forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.2 MiBbcaef90Tahinli1 month ago164 commits

markdown.rs1081 lines, 36.2 KiBHistoryRawDownload
1//! comrak + ammonia markdown rendering.
2//!
3//! Pipeline: parse with comrak (GFM extensions, raw HTML passed through),
4//! optionally rewrite link and image URLs in the AST, render to HTML, then
5//! sanitize the whole output with a strict ammonia allowlist. Nothing that
6//! comrak emits reaches the page without going through ammonia.
7
8use std::borrow::Cow;
9use std::collections::{HashMap, HashSet};
10use std::ops::Range;
11
12use ammonia::{Builder, UrlRelative};
13use comrak::nodes::{Ast, AstNode, NodeLink, NodeValue};
14use comrak::{Arena, Options, format_html, parse_document};
15use forge_core::issue_refs;
16
17use crate::render::emoji::emojify;
18
19/// Prefix applied to heading ids (and to in-page `#anchor` links that target them).
20const ID_PREFIX: &str = "user-content-";
21
22/// Longest username an `@mention` can name.
23const MAX_MENTION_LEN: usize = 39;
24
25/// comrak cannot put a `class` on a link, so links made for issue refs and mentions carry one of
26/// these sentinel titles, which `apply_link_classes` turns into the class before sanitizing.
27const ISSUE_REF_TITLE: &str = "forge-issue-ref";
28const USER_MENTION_TITLE: &str = "forge-user-mention";
29
30/// `rel` added to every link, internal or external. The sanitizer sets it, so raw HTML links
31/// cannot skip it.
32const EXTERNAL_REL: &str = "nofollow noopener noreferrer";
33
34/// Base URLs used to resolve relative links in a rendered file.
35///
36/// Each base ends at the directory that contains the file being rendered,
37/// with no trailing slash, e.g. `https://host/o/r/blob/main/docs`.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct LinkContext {
40 pub tree_base: String,
41 pub blob_base: String,
42 pub raw_base: String,
43 /// Issues page of the repo, e.g. `/Tahinli/forge/issues`. When set, `#N` and `@user` in text
44 /// are linked. `None` leaves them as plain text.
45 pub issues_base: Option<String>,
46}
47
48/// Renders markdown to sanitized HTML.
49///
50/// With `ctx = None` no link rewriting happens: links and images keep their
51/// source URLs, and `#anchor` links are left alone.
52pub fn render_markdown(src: &str, ctx: Option<&LinkContext>) -> String {
53 let options = markdown_options();
54 let arena = Arena::new();
55 let root = parse_document(&arena, src, &options);
56
57 emojify_text(root);
58 if let Some(ctx) = ctx {
59 rewrite_links(root, &Resolver::new(ctx));
60 if let Some(issues_base) = &ctx.issues_base {
61 link_refs(&arena, root, issues_base);
62 }
63 }
64
65 let mut html = String::new();
66 if format_html(root, &options, &mut html).is_err() {
67 return String::new();
68 }
69 sanitizer().clean(&apply_link_classes(&html)).to_string()
70}
71
72fn markdown_options() -> Options<'static> {
73 let mut options = Options::default();
74 options.extension.table = true;
75 options.extension.tasklist = true;
76 options.extension.strikethrough = true;
77 options.extension.autolink = true;
78 options.extension.footnotes = true;
79 options.extension.alerts = true;
80 options.extension.math_dollars = true;
81 options.extension.header_id_prefix = Some(ID_PREFIX.to_string());
82 // Raw HTML is passed through to ammonia, which removes anything not allowlisted.
83 options.render.r#unsafe = true;
84 options
85}
86
87/// Resolves relative URLs against the repo.
88///
89/// The bases in a [`LinkContext`] all carry the directory of the rendered
90/// file after the ref, e.g. `.../blob/main/docs/guide`. The directory is the
91/// part after the ref segment, so `dir` is `["docs", "guide"]` here, and the
92/// repo root for each kind is the base with those trailing segments removed.
93///
94/// Root-relative links (`/x`) resolve from the repo root, not from `dir`.
95/// Relative links (`x`, `../x`) resolve from `dir`. Both kinds clamp `..` at
96/// the root, so a link can never point above the repo.
97///
98/// Limitation: the ref is assumed to be a single path segment. A branch name
99/// with a `/` in it makes the directory split wrong.
100struct Resolver {
101 tree_root: String,
102 blob_root: String,
103 raw_root: String,
104 dir: Vec<String>,
105}
106
107impl Resolver {
108 fn new(ctx: &LinkContext) -> Self {
109 let blob = ctx.blob_base.trim_end_matches('/');
110 let depth = dir_depth(blob);
111 let dir = blob
112 .split('/')
113 .rev()
114 .take(depth)
115 .filter(|seg| !seg.is_empty())
116 .map(str::to_string)
117 .collect::<Vec<_>>()
118 .into_iter()
119 .rev()
120 .collect();
121 Self {
122 tree_root: strip_segments(&ctx.tree_base, depth),
123 blob_root: strip_segments(&ctx.blob_base, depth),
124 raw_root: strip_segments(&ctx.raw_base, depth),
125 dir,
126 }
127 }
128
129 /// Returns the rewritten URL, or `None` to keep the original.
130 fn rewrite(&self, url: &str, image: bool) -> Option<String> {
131 // Attachment URLs are site-absolute and independent of the rendered file's location.
132 if url.is_empty()
133 || url.starts_with("//")
134 || has_scheme(url)
135 || url.starts_with("/attachments/")
136 {
137 return None;
138 }
139 if let Some(fragment) = url.strip_prefix('#') {
140 if fragment.is_empty() {
141 return None;
142 }
143 return Some(format!("#{ID_PREFIX}{fragment}"));
144 }
145
146 let split = url.find(['?', '#']).unwrap_or(url.len());
147 let (path, suffix) = url.split_at(split);
148 let start: &[String] = if path.starts_with('/') {
149 &[]
150 } else {
151 &self.dir
152 };
153 let segments = normalize(start, path);
154
155 if image {
156 return Some(join(&self.raw_root, &segments, suffix));
157 }
158 if segments.is_empty() || path.ends_with('/') {
159 Some(join(&self.tree_root, &segments, suffix))
160 } else {
161 Some(join(&self.blob_root, &segments, suffix))
162 }
163 }
164}
165
166/// Number of path segments after the ref in a blob/tree base, or 0 if there is none.
167///
168/// The marker is searched from index 3 on so the scheme, host, owner and repo
169/// are skipped.
170fn dir_depth(base: &str) -> usize {
171 let segments: Vec<&str> = base.split('/').collect();
172 segments
173 .iter()
174 .enumerate()
175 .skip(3)
176 .find(|(i, seg)| (**seg == "blob" || **seg == "tree") && i + 1 < segments.len())
177 .map_or(0, |(i, _)| segments.len() - (i + 2))
178}
179
180/// Removes `n` trailing path segments from a base URL.
181fn strip_segments(base: &str, n: usize) -> String {
182 let mut out = base.trim_end_matches('/');
183 for _ in 0..n {
184 match out.rfind('/') {
185 Some(i) => out = &out[..i],
186 None => break,
187 }
188 }
189 out.to_string()
190}
191
192/// Applies `path` to `start`, resolving `.` and `..`. `..` past the root is dropped.
193fn normalize(start: &[String], path: &str) -> Vec<String> {
194 let mut out = start.to_vec();
195 for seg in path.split('/') {
196 match seg {
197 "" | "." => {}
198 ".." => {
199 out.pop();
200 }
201 other => out.push(other.to_string()),
202 }
203 }
204 out
205}
206
207fn join(root: &str, segments: &[String], suffix: &str) -> String {
208 if segments.is_empty() {
209 format!("{root}{suffix}")
210 } else {
211 format!("{root}/{}{suffix}", segments.join("/"))
212 }
213}
214
215/// True for `scheme:` prefixes such as `https:`, `mailto:` or `javascript:`.
216fn has_scheme(url: &str) -> bool {
217 match url.find(':') {
218 Some(i) if i > 0 => {
219 let scheme = &url[..i];
220 scheme.starts_with(|c: char| c.is_ascii_alphabetic())
221 && scheme
222 .chars()
223 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
224 }
225 _ => false,
226 }
227}
228
229/// Replaces `:shortcode:` in text nodes. Code spans and blocks keep their literals in their own
230/// node values, so they are never `Text`. Text inside a link (such as an autolink, whose
231/// visible text must match its href) is left alone.
232fn emojify_text<'a>(root: &'a AstNode<'a>) {
233 for node in root.descendants() {
234 let in_link = node
235 .parent()
236 .is_some_and(|parent| matches!(parent.data.borrow().value, NodeValue::Link(_)));
237 if in_link {
238 continue;
239 }
240 let mut ast = node.data.borrow_mut();
241 if let NodeValue::Text(text) = &mut ast.value {
242 let replaced = match emojify(text.as_ref()) {
243 Cow::Owned(s) => Some(s),
244 Cow::Borrowed(_) => None,
245 };
246 if let Some(s) = replaced {
247 *text = s.into();
248 }
249 }
250 }
251}
252
253fn rewrite_links<'a>(root: &'a AstNode<'a>, resolver: &Resolver) {
254 for node in root.descendants() {
255 let mut ast = node.data.borrow_mut();
256 match &mut ast.value {
257 NodeValue::Link(link) => {
258 if let Some(url) = resolver.rewrite(&link.url, false) {
259 link.url = url;
260 }
261 }
262 NodeValue::Image(link) => {
263 if let Some(url) = resolver.rewrite(&link.url, true) {
264 link.url = url;
265 }
266 }
267 _ => {}
268 }
269 }
270}
271
272/// Replaces the sentinel titles of issue-ref and mention links with their classes. `rel` is not
273/// handled here: the sanitizer adds it to every link. Text quotes are escaped by comrak, so the
274/// patterns can only occur in a tag.
275fn apply_link_classes(html: &str) -> String {
276 html.replace(
277 &format!("title=\"{ISSUE_REF_TITLE}\""),
278 "class=\"issue-ref\"",
279 )
280 .replace(
281 &format!("title=\"{USER_MENTION_TITLE}\""),
282 "class=\"user-mention\"",
283 )
284}
285
286/// Turns `#N` and `@user` in text nodes into link nodes. Text inside links and images is skipped.
287/// Code spans and blocks are not text nodes, so they are skipped too. Raw HTML blocks are split
288/// so that their plain text (outside tags, code, links and raw-text elements) is linked as well.
289fn link_refs<'a>(arena: &'a Arena<'a>, root: &'a AstNode<'a>, issues_base: &str) {
290 let targets: Vec<&'a AstNode<'a>> = root
291 .descendants()
292 .filter(|node| {
293 matches!(
294 node.data.borrow().value,
295 NodeValue::Text(_) | NodeValue::HtmlBlock(_)
296 ) && !node.ancestors().skip(1).any(|ancestor| {
297 matches!(
298 ancestor.data.borrow().value,
299 NodeValue::Link(_) | NodeValue::Image(_)
300 )
301 })
302 })
303 .collect();
304
305 for node in targets {
306 let (sourcepos, value) = {
307 let ast = node.data.borrow();
308 (ast.sourcepos, ast.value.clone())
309 };
310 match value {
311 NodeValue::Text(text) => {
312 if let Some(nodes) = text_with_links(arena, sourcepos, &text, issues_base) {
313 for new in nodes {
314 node.insert_before(new);
315 }
316 node.detach();
317 }
318 }
319 NodeValue::HtmlBlock(block) => {
320 let literal = block.literal.trim_end_matches('\n').to_string();
321 let mut children = Vec::new();
322 let mut linked = false;
323 for piece in split_html(&literal) {
324 match piece {
325 HtmlPiece::Html(html) => {
326 children.push(new_node(arena, sourcepos, NodeValue::HtmlInline(html)))
327 }
328 HtmlPiece::Text(raw) => {
329 // Raw text may hold entities; comrak escapes Text nodes again, so decode
330 // them first.
331 let text = decode_entities(&raw);
332 match text_with_links(arena, sourcepos, &text, issues_base) {
333 Some(nodes) => {
334 linked = true;
335 children.extend(nodes);
336 }
337 None => children.push(new_node(
338 arena,
339 sourcepos,
340 NodeValue::Text(text.into()),
341 )),
342 }
343 }
344 }
345 }
346 // Only rewrite the block when something was actually linked.
347 if linked {
348 node.data.borrow_mut().value = NodeValue::Paragraph;
349 for child in children {
350 node.append(child);
351 }
352 }
353 }
354 _ => {}
355 }
356 }
357}
358
359/// Splits `text` into link and text nodes for every `#N` and `@user` in it. Returns `None` when
360/// there is nothing to link.
361fn text_with_links<'a>(
362 arena: &'a Arena<'a>,
363 sourcepos: comrak::nodes::Sourcepos,
364 text: &str,
365 issues_base: &str,
366) -> Option<Vec<&'a AstNode<'a>>> {
367 let mut spans: Vec<(Range<usize>, Option<i64>)> = issue_refs::issue_ref_spans(text)
368 .into_iter()
369 .map(|(range, n)| (range, Some(n)))
370 .chain(mention_spans(text).into_iter().map(|range| (range, None)))
371 .collect();
372 if spans.is_empty() {
373 return None;
374 }
375 spans.sort_by_key(|(range, _)| range.start);
376
377 let mut out = Vec::new();
378 let mut cursor = 0;
379 for (range, issue) in spans {
380 if range.start > cursor {
381 out.push(new_node(
382 arena,
383 sourcepos,
384 NodeValue::Text(text[cursor..range.start].to_string().into()),
385 ));
386 }
387 let label = &text[range.clone()];
388 let link = match issue {
389 Some(n) => new_node(
390 arena,
391 sourcepos,
392 NodeValue::Link(Box::new(NodeLink {
393 url: format!("{issues_base}/{n}"),
394 title: ISSUE_REF_TITLE.to_string(),
395 })),
396 ),
397 None => new_node(
398 arena,
399 sourcepos,
400 NodeValue::Link(Box::new(NodeLink {
401 url: format!("/{}", &label[1..]),
402 title: USER_MENTION_TITLE.to_string(),
403 })),
404 ),
405 };
406 link.append(new_node(
407 arena,
408 sourcepos,
409 NodeValue::Text(label.to_string().into()),
410 ));
411 out.push(link);
412 cursor = range.end;
413 }
414 if cursor < text.len() {
415 out.push(new_node(
416 arena,
417 sourcepos,
418 NodeValue::Text(text[cursor..].to_string().into()),
419 ));
420 }
421 Some(out)
422}
423
424/// A piece of a raw HTML block: markup that must stay as written, or plain text that may be linked.
425#[derive(Debug, PartialEq, Eq)]
426enum HtmlPiece {
427 Html(String),
428 Text(String),
429}
430
431/// Tags whose content is raw text (not markup) and is removed by the sanitizer.
432const RAW_TEXT_TAGS: &[&str] = &["script", "style", "textarea", "title"];
433
434/// Tags inside which nothing may be linked.
435const NO_LINK_TAGS: &[&str] = &["a", "code", "pre"];
436
437/// Splits raw HTML into markup and text. Text outside tags is `Text`, unless it sits inside a
438/// link, code or pre element, in which case it is `Html`. Raw-text elements are kept whole as `Html`.
439fn split_html(src: &str) -> Vec<HtmlPiece> {
440 let lower = src.to_ascii_lowercase();
441 let mut segments: Vec<(bool, Range<usize>)> = Vec::new();
442 let mut prev = 0;
443 let mut depth = 0usize;
444 let mut i = 0;
445 while let Some(off) = src[i..].find('<') {
446 let lt = i + off;
447 let end = if src[lt..].starts_with("<!--") {
448 src[lt..].find("-->").map_or(src.len(), |p| lt + p + 3)
449 } else {
450 match src[lt..].find('>') {
451 Some(p) => lt + p + 1,
452 None => break,
453 }
454 };
455 let inner = src[lt + 1..end].trim_end_matches('>');
456 let closing = inner.starts_with('/');
457 let name: String = inner
458 .trim_start_matches('/')
459 .chars()
460 .take_while(|c| c.is_ascii_alphanumeric())
461 .collect::<String>()
462 .to_ascii_lowercase();
463
464 if lt > prev {
465 segments.push((depth == 0, prev..lt));
466 }
467 let mut tag_end = end;
468 if !closing && RAW_TEXT_TAGS.contains(&name.as_str()) {
469 let close = format!("</{name}");
470 if let Some(p) = lower[end..].find(&close) {
471 let close_start = end + p;
472 tag_end = lower[close_start..]
473 .find('>')
474 .map_or(src.len(), |g| close_start + g + 1);
475 }
476 }
477 segments.push((false, lt..tag_end));
478 if NO_LINK_TAGS.contains(&name.as_str()) {
479 if closing {
480 depth = depth.saturating_sub(1);
481 } else {
482 depth += 1;
483 }
484 }
485 prev = tag_end;
486 i = tag_end;
487 }
488 if prev < src.len() {
489 segments.push((depth == 0, prev..src.len()));
490 }
491
492 let mut out: Vec<HtmlPiece> = Vec::new();
493 for (is_text, range) in segments {
494 let piece = &src[range];
495 let next = if is_text {
496 HtmlPiece::Text(piece.to_string())
497 } else {
498 HtmlPiece::Html(piece.to_string())
499 };
500 match (out.last_mut(), next) {
501 (Some(HtmlPiece::Html(prev_html)), HtmlPiece::Html(html)) => prev_html.push_str(&html),
502 (Some(HtmlPiece::Text(prev_text)), HtmlPiece::Text(text)) => prev_text.push_str(&text),
503 (_, next) => out.push(next),
504 }
505 }
506 out
507}
508
509/// Decodes the character references that raw HTML text may contain: the named entities `&amp;`,
510/// `&lt;`, `&gt;`, `&quot;`, `&apos;`, `&nbsp;` and numeric `&#NN;` / `&#xHH;`. Anything else is
511/// kept literally.
512fn decode_entities(text: &str) -> String {
513 let mut out = String::with_capacity(text.len());
514 let mut rest = text;
515 while let Some(amp) = rest.find('&') {
516 out.push_str(&rest[..amp]);
517 let from_amp = &rest[amp..];
518 match decode_entity(from_amp) {
519 Some((ch, len)) => {
520 out.push(ch);
521 rest = &from_amp[len..];
522 }
523 None => {
524 out.push('&');
525 rest = &from_amp[1..];
526 }
527 }
528 }
529 out.push_str(rest);
530 out
531}
532
533/// Decodes the entity at the start of `s` (which begins with `&`). Returns the character and the
534/// number of bytes the entity spans.
535fn decode_entity(s: &str) -> Option<(char, usize)> {
536 let end = s.find(';')?;
537 if end > 12 {
538 return None;
539 }
540 let body = &s[1..end];
541 let ch = if let Some(hex) = body.strip_prefix("#x").or_else(|| body.strip_prefix("#X")) {
542 if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
543 return None;
544 }
545 char::from_u32(u32::from_str_radix(hex, 16).ok()?)?
546 } else if let Some(dec) = body.strip_prefix('#') {
547 if dec.is_empty() || !dec.bytes().all(|b| b.is_ascii_digit()) {
548 return None;
549 }
550 char::from_u32(dec.parse().ok()?)?
551 } else {
552 match body {
553 "amp" => '&',
554 "lt" => '<',
555 "gt" => '>',
556 "quot" => '"',
557 "apos" => '\'',
558 "nbsp" => '\u{a0}',
559 _ => return None,
560 }
561 };
562 Some((ch, end + 1))
563}
564
565fn new_node<'a>(
566 arena: &'a Arena<'a>,
567 sourcepos: comrak::nodes::Sourcepos,
568 value: NodeValue,
569) -> &'a AstNode<'a> {
570 arena.alloc(comrak::arena_tree::Node::new(std::cell::RefCell::new(
571 Ast::new_with_sourcepos(value, sourcepos),
572 )))
573}
574
575/// Byte ranges of `@username` mentions. The `@` must start the text or follow whitespace, and the
576/// name uses `[A-Za-z0-9._-]`, at most 39 chars, without trailing dots.
577fn mention_spans(text: &str) -> Vec<Range<usize>> {
578 let bytes = text.as_bytes();
579 let mut out = Vec::new();
580 for (at, _) in text.match_indices('@') {
581 if text[..at]
582 .chars()
583 .next_back()
584 .is_some_and(|c| !c.is_whitespace())
585 {
586 continue;
587 }
588 let run = bytes[at + 1..]
589 .iter()
590 .take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
591 .count();
592 let name = text[at + 1..at + 1 + run].trim_end_matches('.');
593 if name.is_empty() || name.len() > MAX_MENTION_LEN {
594 continue;
595 }
596 out.push(at..at + 1 + name.len());
597 }
598 out
599}
600
601/// Usernames `@mention`ed in markdown `text`, lowercased and deduplicated in first-seen order.
602///
603/// Parses with the same options as [`render_markdown`] and walks the text nodes that the `@user`
604/// linking would touch: code spans and blocks, and text inside links and images, are skipped.
605/// Raw HTML blocks are split the same way the linker splits them.
606pub fn mentioned_usernames(text: &str) -> Vec<String> {
607 let options = markdown_options();
608 let arena = Arena::new();
609 let root = parse_document(&arena, text, &options);
610
611 let mut found: Vec<String> = Vec::new();
612 for node in root.descendants() {
613 let ast = node.data.borrow();
614 let inside_link = node.ancestors().skip(1).any(|ancestor| {
615 matches!(
616 ancestor.data.borrow().value,
617 NodeValue::Link(_) | NodeValue::Image(_)
618 )
619 });
620 if inside_link {
621 continue;
622 }
623 match &ast.value {
624 NodeValue::Text(literal) => collect_mentions(literal, &mut found),
625 NodeValue::HtmlBlock(block) => {
626 let literal = block.literal.trim_end_matches('\n');
627 for piece in split_html(literal) {
628 if let HtmlPiece::Text(raw) = piece {
629 collect_mentions(&decode_entities(&raw), &mut found);
630 }
631 }
632 }
633 _ => {}
634 }
635 }
636 found
637}
638
639/// The task items of `src` in document order, as `(byte offset of the mark, checked)`. The mark is
640/// the character between the brackets. Tasks inside code blocks are not task items, so they are
641/// not listed.
642fn task_marks(src: &str) -> Vec<(usize, bool)> {
643 let options = markdown_options();
644 let arena = Arena::new();
645 let root = parse_document(&arena, src, &options);
646 let mut line_starts = vec![0usize];
647 for (i, b) in src.bytes().enumerate() {
648 if b == b'\n' {
649 line_starts.push(i + 1);
650 }
651 }
652 let mut out = Vec::new();
653 for node in root.descendants() {
654 if let NodeValue::TaskItem(item) = &node.data.borrow().value {
655 let pos = item.symbol_sourcepos.start;
656 let Some(line) = line_starts.get(pos.line.wrapping_sub(1)) else {
657 continue;
658 };
659 let at = line + pos.column.saturating_sub(1);
660 if at < src.len() && src.is_char_boundary(at) {
661 out.push((at, item.symbol.is_some()));
662 }
663 }
664 }
665 out
666}
667
668/// `(done, total)` task items in markdown `src`.
669pub fn task_progress(src: &str) -> (usize, usize) {
670 let marks = task_marks(src);
671 (marks.iter().filter(|(_, done)| *done).count(), marks.len())
672}
673
674/// Sets the `index`th task item (document order) to `checked`. `None` when there is no such task.
675pub fn set_task(src: &str, index: usize, checked: bool) -> Option<String> {
676 let (at, _) = *task_marks(src).get(index)?;
677 let mark = src[at..].chars().next()?;
678 let before = src[..at].chars().next_back()?;
679 if before != '[' || !(mark == ' ' || mark == 'x' || mark == 'X') {
680 return None;
681 }
682 let mut out = String::with_capacity(src.len());
683 out.push_str(&src[..at]);
684 out.push(if checked { 'x' } else { ' ' });
685 out.push_str(&src[at + mark.len_utf8()..]);
686 Some(out)
687}
688
689/// Adds the lowercased names of the `@mention`s in one text run to `found`, skipping duplicates.
690fn collect_mentions(text: &str, found: &mut Vec<String>) {
691 for range in mention_spans(text) {
692 let name = text[range.start + 1..range.end].to_ascii_lowercase();
693 if !found.contains(&name) {
694 found.push(name);
695 }
696 }
697}
698
699const TAGS: &[&str] = &[
700 "h1",
701 "h2",
702 "h3",
703 "h4",
704 "h5",
705 "h6",
706 "p",
707 "a",
708 "img",
709 "ul",
710 "ol",
711 "li",
712 "input",
713 "table",
714 "thead",
715 "tbody",
716 "tr",
717 "th",
718 "td",
719 "pre",
720 "code",
721 "blockquote",
722 "hr",
723 "br",
724 "em",
725 "strong",
726 "del",
727 "sup",
728 "sub",
729 "details",
730 "summary",
731 "kbd",
732 "div",
733 "span",
734 "section",
735];
736
737const CLASSES: &[&str] = &[
738 "markdown-alert",
739 "markdown-alert-note",
740 "markdown-alert-tip",
741 "markdown-alert-important",
742 "markdown-alert-warning",
743 "markdown-alert-caution",
744 "markdown-alert-title",
745 "footnote-ref",
746 "footnote-backref",
747 "footnotes",
748 "task-list-item",
749 "sr-only",
750 "anchor",
751 "issue-ref",
752 "user-mention",
753];
754
755const SCRIPT_LIKE: &[&str] = &[
756 "script", "style", "iframe", "object", "embed", "noscript", "template", "textarea", "title",
757 "svg", "math", "form",
758];
759
760/// The strict allowlist. Anything not listed here is removed, and so are all `style`
761/// and `on*` attributes, because they are not in any attribute list.
762fn sanitizer() -> Builder<'static> {
763 let tags: HashSet<&'static str> = TAGS.iter().copied().collect();
764 let clean_content: HashSet<&'static str> = SCRIPT_LIKE.iter().copied().collect();
765 let classes: HashSet<&'static str> = CLASSES.iter().copied().collect();
766 let allowed_classes: HashMap<&'static str, HashSet<&'static str>> =
767 TAGS.iter().map(|tag| (*tag, classes.clone())).collect();
768
769 let attrs: HashMap<&'static str, HashSet<&'static str>> = [
770 ("h1", &["id"][..]),
771 ("h2", &["id"]),
772 ("h3", &["id"]),
773 ("h4", &["id"]),
774 ("h5", &["id"]),
775 ("h6", &["id"]),
776 (
777 "a",
778 &[
779 "href",
780 "title",
781 "id",
782 "data-footnote-ref",
783 "data-footnote-backref",
784 ],
785 ),
786 ("img", &["src", "alt", "title", "width", "height"]),
787 ("ol", &["start"]),
788 ("li", &["id"]),
789 ("sup", &["id"]),
790 ("section", &["id", "data-footnotes"]),
791 ("pre", &["lang"]),
792 ("td", &["align"]),
793 ("th", &["align"]),
794 ("input", &["type", "checked", "disabled"]),
795 ("details", &["open"]),
796 ("span", &["data-math-style"]),
797 ]
798 .into_iter()
799 .map(|(tag, names)| (tag, names.iter().copied().collect()))
800 .collect();
801
802 let mut builder = Builder::empty();
803 builder
804 .tags(tags)
805 .clean_content_tags(clean_content)
806 .tag_attributes(attrs)
807 .generic_attributes(HashSet::from([
808 "aria-label",
809 "aria-describedby",
810 "aria-hidden",
811 ]))
812 .allowed_classes(allowed_classes)
813 .url_schemes(HashSet::from(["http", "https", "mailto"]))
814 .url_relative(UrlRelative::PassThrough)
815 .link_rel(Some(EXTERNAL_REL))
816 .set_tag_attribute_value("input", "type", "checkbox");
817 builder
818}
819
820#[cfg(test)]
821mod tests {
822 use super::*;
823
824 fn ctx() -> LinkContext {
825 LinkContext {
826 tree_base: "https://forge.test/o/r/tree/main/guide".to_string(),
827 blob_base: "https://forge.test/o/r/blob/main/guide".to_string(),
828 raw_base: "https://raw.test/o/r/main/guide".to_string(),
829 issues_base: None,
830 }
831 }
832
833 fn issue_ctx() -> LinkContext {
834 LinkContext {
835 issues_base: Some("/o/r/issues".to_string()),
836 ..ctx()
837 }
838 }
839
840 /// `(markdown, with_ctx, fragments that must appear in the rendered HTML)`.
841 const CONTAINS_CASES: &[(&str, bool, &[&str])] = &[
842 (
843 "$x^2$ and ![a](/attachments/abc/a.png)",
844 true,
845 &[
846 "data-math-style=\"inline\"",
847 "src=\"/attachments/abc/a.png\"",
848 ],
849 ),
850 (
851 "| a | b |\n|:-|-:|\n| 1 | 2 |\n\n- [x] done\n- [ ] todo\n",
852 false,
853 &["<table>", "<td", "type=\"checkbox\"", "checked"],
854 ),
855 (
856 "<details><summary>More</summary>\n\nHidden text\n\n</details>\n",
857 false,
858 &["<details>", "<summary>More</summary>"],
859 ),
860 ("# Hello World", false, &["id=\"user-content-hello-world\""]),
861 (
862 "[t](#hello-world)",
863 true,
864 &["href=\"#user-content-hello-world\""],
865 ),
866 (
867 "[x](docs/a.md)",
868 true,
869 &["href=\"https://forge.test/o/r/blob/main/guide/docs/a.md\""],
870 ),
871 (
872 "[d](../sub/)\n\n[e](../../../../x.md)",
873 true,
874 &[
875 "href=\"https://forge.test/o/r/tree/main/sub\"",
876 "href=\"https://forge.test/o/r/blob/main/x.md\"",
877 ],
878 ),
879 (
880 "![i](../img.png)",
881 true,
882 &["src=\"https://raw.test/o/r/main/img.png\""],
883 ),
884 // The fragment belongs to the target file (e.g. #L12 on code), so it is left as is.
885 (
886 "[r](/README.md#top) [s](/a/../b.md)",
887 true,
888 &[
889 "href=\"https://forge.test/o/r/blob/main/README.md#top\"",
890 "href=\"https://forge.test/o/r/blob/main/b.md\"",
891 ],
892 ),
893 (
894 "[g](https://example.com/a?b=1)",
895 true,
896 &[
897 "href=\"https://example.com/a?b=1\"",
898 "rel=\"nofollow noopener noreferrer\"",
899 ],
900 ),
901 ("[x](docs/a.md)", false, &["href=\"docs/a.md\""]),
902 ];
903
904 #[test]
905 fn rendered_html_contains_expected_fragments() {
906 for (src, with_ctx, needles) in CONTAINS_CASES {
907 let lc = ctx();
908 let html = render_markdown(src, with_ctx.then_some(&lc));
909 for needle in needles.iter() {
910 assert!(
911 html.contains(needle),
912 "case {src:?} missing {needle:?}: {html}"
913 );
914 }
915 }
916 }
917
918 #[test]
919 fn tasks_are_counted_and_toggled() {
920 let src = "- [ ] one\n- [x] two\n - [ ] nested\n\n```\n- [ ] code\n```\n";
921 assert_eq!(task_progress(src), (1, 3));
922 let on = set_task(src, 0, true).unwrap();
923 assert!(on.starts_with("- [x] one\n"), "{on}");
924 let off = set_task(&on, 1, false).unwrap();
925 assert!(off.contains("- [ ] two"), "{off}");
926 assert_eq!(set_task(src, 2, true).unwrap().matches("[x]").count(), 2);
927 assert!(set_task(src, 3, true).is_none());
928 assert!(set_task("no tasks", 0, true).is_none());
929 }
930
931 #[test]
932 fn issue_refs_and_mentions_are_linked() {
933 let html = render_markdown("fixes #12, see @tahinli.\n\n- #3", Some(&issue_ctx()));
934 assert!(html.contains("href=\"/o/r/issues/12\""), "{html}");
935 assert!(html.contains("class=\"issue-ref\""), "{html}");
936 assert!(html.contains(">#12</a>"), "{html}");
937 assert!(html.contains("href=\"/o/r/issues/3\""), "{html}");
938 assert!(html.contains(">#3</a>"), "{html}");
939 assert!(html.contains("href=\"/tahinli\""), "{html}");
940 assert!(html.contains("class=\"user-mention\""), "{html}");
941 assert!(html.contains(">@tahinli</a>."), "{html}");
942 assert!(!html.contains("title="), "{html}");
943 }
944
945 /// Every `<a` start tag in `html` must carry the external `rel`.
946 fn assert_all_links_have_rel(html: &str) {
947 let mut count = 0;
948 for (at, _) in html.match_indices("<a") {
949 if !matches!(html[at + 2..].chars().next(), Some(' ' | '>')) {
950 continue;
951 }
952 count += 1;
953 let tag_end = html[at..].find('>').expect("unclosed tag");
954 let tag = &html[at..at + tag_end];
955 assert!(
956 tag.contains("rel=\"nofollow noopener noreferrer\""),
957 "{html}"
958 );
959 }
960 assert!(count > 0, "{html}");
961 }
962
963 #[test]
964 fn raw_html_links_always_get_rel() {
965 let html = render_markdown(
966 "<a title=\"x\" href='https://spam.example'>s</a>\n\n\
967 <a href=\"https://x.example\">x</a>\n\n<a href=\"/internal\">i</a>\n",
968 Some(&ctx()),
969 );
970 assert_all_links_have_rel(&html);
971 assert!(html.contains("href=\"https://spam.example\""), "{html}");
972 assert_all_links_have_rel(&render_markdown(
973 "<a title=\"x\" href='https://spam.example'>s</a>\n\n<a href=\"https://x.example\">x</a>",
974 None,
975 ));
976 }
977
978 #[test]
979 fn html_block_entities_are_not_double_escaped() {
980 let html = render_markdown("<div>Tom &amp; Jerry #3</div>\n", Some(&issue_ctx()));
981 assert!(html.contains("Tom &amp; Jerry"), "{html}");
982 assert!(!html.contains("&amp;amp;"), "{html}");
983 assert!(html.contains("class=\"issue-ref\""), "{html}");
984 assert!(html.contains(">#3</a>"), "{html}");
985 }
986
987 #[test]
988 fn decode_entities_handles_known_and_unknown() {
989 assert_eq!(
990 decode_entities("a &amp; b &lt;&#39;&#x41;&gt;"),
991 "a & b <'A>"
992 );
993 assert_eq!(decode_entities("&nbsp;&quot;&apos;"), "\u{a0}\"'");
994 assert_eq!(
995 decode_entities("&bogus; & &#; &#xZZ; &"),
996 "&bogus; & &#; &#xZZ; &"
997 );
998 assert_eq!(decode_entities("&#0;"), "\0");
999 }
1000
1001 #[test]
1002 fn refs_in_code_are_not_linked() {
1003 let html = render_markdown(
1004 "`#12` and @bob\n\n```\n#13 @carol\n```\n",
1005 Some(&issue_ctx()),
1006 );
1007 // `@bob` is plain text and is linked; the refs inside code are not.
1008 assert!(!html.contains("issue-ref"), "{html}");
1009 assert_eq!(html.matches("user-mention").count(), 1, "{html}");
1010 assert!(html.contains(">@bob</a>"), "{html}");
1011 assert!(!html.contains("@carol</a>"), "{html}");
1012 assert!(html.contains("<code>#12</code>"), "{html}");
1013 }
1014
1015 #[test]
1016 fn refs_inside_existing_links_are_not_doubled() {
1017 let html = render_markdown("[see #5 and @dan](https://example.com)", Some(&issue_ctx()));
1018 assert!(!html.contains("issue-ref"), "{html}");
1019 assert!(!html.contains("user-mention"), "{html}");
1020 assert_eq!(html.matches("<a ").count(), 1, "{html}");
1021 }
1022
1023 #[test]
1024 fn script_is_still_stripped_with_linking_on() {
1025 let html = render_markdown("<script>alert(1)</script> #7", Some(&issue_ctx()));
1026 assert!(!html.contains("script"), "{html}");
1027 assert!(html.contains("class=\"issue-ref\""), "{html}");
1028 assert!(html.contains(">#7</a>"), "{html}");
1029 }
1030
1031 #[test]
1032 fn no_issues_base_means_no_linking() {
1033 let html = render_markdown("#12 @tahinli", Some(&ctx()));
1034 assert!(!html.contains("issue-ref"), "{html}");
1035 assert!(!html.contains("user-mention"), "{html}");
1036 assert!(html.contains("#12 @tahinli"), "{html}");
1037 }
1038
1039 #[test]
1040 fn email_is_not_a_mention() {
1041 let html = render_markdown("write to a@b.com or @ alone", Some(&issue_ctx()));
1042 assert!(!html.contains("user-mention"), "{html}");
1043 assert!(html.contains("a@b.com"), "{html}");
1044 }
1045
1046 #[test]
1047 fn mention_names_follow_the_rules() {
1048 assert_eq!(mention_spans("@bob."), vec![0..4]);
1049 assert!(mention_spans(&format!("@{}", "a".repeat(40))).is_empty());
1050 assert_eq!(mention_spans(&format!("@{}", "a".repeat(39))), vec![0..40]);
1051 assert!(mention_spans("@.").is_empty());
1052 assert_eq!(mention_spans("x @a, @b_c-d"), vec![2..4, 6..12]);
1053 }
1054
1055 #[test]
1056 fn dangerous_markup_is_stripped() {
1057 let html = render_markdown(
1058 "<script>alert(1)</script>\n\n[x](javascript:alert(1))\n\n\
1059 <img src=x onerror=alert(1)>\n\n<span style=\"color:red\">s</span>\n",
1060 None,
1061 );
1062 assert!(!html.contains("script"), "{html}");
1063 assert!(!html.contains("javascript:"), "{html}");
1064 assert!(!html.contains("onerror"), "{html}");
1065 assert!(!html.contains("style"), "{html}");
1066 assert!(html.contains(">x</a>"), "{html}");
1067 }
1068
1069 #[test]
1070 fn emoji_shortcodes_convert_outside_code() {
1071 let html = render_markdown(
1072 "party :tada: and `:tada:` and\n\n```\n:tada:\n```\n\n:spark:\n",
1073 None,
1074 );
1075 assert!(html.contains("party 🎉 and"), "{html}");
1076 assert!(html.contains("<code>:tada:</code>"), "{html}");
1077 assert!(html.contains("<pre"), "{html}");
1078 assert!(html.contains(":spark:"), "{html}");
1079 assert!(!html.contains("<code>🎉</code>"), "{html}");
1080 }
1081}