steid

@jamesgill /

Rust51.7 KBCode·Blame·History·Raw
1//! Rendering markdown, for READMEs and later for posts.
2//!
3//! **Raw HTML in the source is never passed through.** Today only a repository's owner
4//! can push to it, so a README is trusted content — but Milestone 7 adds other users,
5//! and markdown rendered with HTML passthrough on the same origin as the session
6//! cookie is stored XSS. Turning it off now costs nothing; retrofitting a sanitiser
7//! later is a security migration. Do not "improve" this back on.
8//!
9//! The guarantee is structural rather than a filter: this module walks the parser's
10//! event stream and writes the HTML itself, so the set of tags that can reach a page is
11//! exactly the set spelled out in [`Writer`]. A `<script>` in the source is not
12//! stripped — it arrives as [`Event::Html`] and is written as *text*, so a reader sees
13//! what was written and a browser sees nothing to execute.
14//!
15//! Writing the HTML by hand rather than calling `pulldown_cmark::html::push_html` is
16//! also forced: `pulldown-cmark` is depended on with `default-features = false`, which
17//! turns its `html` module off. Escaping is not hand-rolled — it goes through
18//! [`HtmlContext`], the same escaper the `view!` macro writes every dynamic value
19//! through.
20//!
21//! The output is [`Unescaped`], which is how it reaches a `view!`: everything in a view
22//! is escaped by default, and this is the deliberate hatch. That hatch is exactly why
23//! raw HTML in the source has to be off — the two decisions are one decision.
24
25use std::collections::{HashMap, VecDeque};
26
27use pulldown_cmark::{Alignment, CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd};
28use topcoat::view::{Formatter, HtmlContext, Unescaped};
29
30use crate::{domain::IssueNumber, infrastructure::highlight};
31
32use super::{commit::commit_url, issues::issue_url};
33
34/// URL schemes a link or image may use.
35///
36/// An allowlist, not a `javascript:` denylist: a denylist has to anticipate every
37/// scripting scheme (`vbscript:`, `data:text/html`, whatever a browser adds next),
38/// while an allowlist only has to name the ones that are useful in prose.
39const ALLOWED_SCHEMES: &[&str] = &["http", "https", "mailto", "ftp", "ftps", "tel"];
40
41/// The repository a body's cross-references belong to.
42///
43/// `#12` and a bare object id only mean something relative to a repository, so a body
44/// rendered without one — a post, a test — simply keeps them as text.
45///
46/// `origin` is what the reference is made absolute against, and is `None` for a page:
47/// a link inside the site should stay relative so it survives a hostname change. A feed
48/// must set it — its content is read somewhere else entirely, where a path with no host
49/// resolves against whatever the reader happened to fetch, if it resolves at all.
50#[derive(Debug, Clone, Copy)]
51pub struct Crossref<'a> {
52 pub handle: &'a str,
53 pub name: &'a str,
54 pub origin: Option<&'a str>,
55}
56
57impl Crossref<'_> {
58 /// A reference URL, prefixed with the origin when there is one.
59 fn absolute(&self, path: String) -> String {
60 match self.origin {
61 Some(origin) => format!("{origin}{path}"),
62 None => path,
63 }
64 }
65}
66
67/// Renders markdown to HTML, leaving relative links exactly as written.
68pub fn render(source: &str, cross: Option<Crossref<'_>>) -> Unescaped<String> {
69 render_with_links(source, cross, |_| None)
70}
71
72/// What a relative destination was written for.
73///
74/// The two resolve differently wherever markdown sits inside a repository: a link to
75/// another file means the page that shows it, and an image means the file's own bytes.
76/// A resolver that could not tell them apart would have to send an image to a page,
77/// which renders a broken image rather than a picture.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum Relative {
80 Link,
81 Image,
82}
83
84/// Renders markdown, giving `resolve` a chance to rewrite relative links.
85///
86/// `resolve` is called only for a destination that is relative — no scheme, and not
87/// starting with `/` or `#` — and returning `None` leaves it untouched. It is a
88/// parameter rather than something this module knows how to do because what a relative
89/// link means depends on where the markdown came from: inside a repository it is
90/// another file in the tree, and in a post it will be something else.
91///
92/// Resolution happens *before* the scheme check, so a resolver cannot hand back a
93/// `javascript:` URL and have it reach the page.
94pub fn render_with_links(
95 source: &str,
96 cross: Option<Crossref<'_>>,
97 resolve: impl Fn(&str) -> Option<String>,
98) -> Unescaped<String> {
99 // An image is never offered to a link-only resolver, which is what keeps a
100 // relative image in a README exactly as written: rewriting one to a page URL
101 // trades a 404 for a broken image.
102 render_with_targets(source, cross, |kind, destination| match kind {
103 Relative::Link => resolve(destination),
104 Relative::Image => None,
105 })
106}
107
108/// Renders markdown, giving `resolve` a chance to rewrite every relative destination,
109/// links and images alike, told apart by [`Relative`].
110///
111/// What a file inside a repository wants: its links point at other files' pages and its
112/// images at their bytes, both resolved against the directory the file itself is in.
113pub fn render_with_targets(
114 source: &str,
115 cross: Option<Crossref<'_>>,
116 resolve: impl Fn(Relative, &str) -> Option<String>,
117) -> Unescaped<String> {
118 let mut buf = String::with_capacity(source.len());
119 // Read ahead for the headings, so each one can be written with the id a `#fragment`
120 // link lands on. A second parse rather than buffering the heading's markup as it is
121 // written: the id has to be in the opening tag, and the text that makes it does not
122 // arrive until after that tag would have been emitted. Parsing is cheap next to
123 // highlighting a fence, and the slugs come out of one pure, tested function.
124 let mut ids = heading_ids(source);
125 let mut writer = Writer::new(&mut buf, cross, resolve);
126
127 for event in Parser::new_ext(source, options()) {
128 if let Event::Start(Tag::Heading { .. }) = &event {
129 writer.heading_id = ids.pop_front().flatten();
130 }
131
132 writer.event(event);
133 }
134
135 Unescaped::new_unchecked(buf)
136}
137
138/// One entry per heading, in document order: the id it should carry, or `None` for a
139/// heading whose text slugs to nothing at all (a heading that is only an image).
140///
141/// Deduplicated the way every anchor scheme has to be — a README with two `## Usage`
142/// sections is ordinary — by suffixing `-1`, `-2` and so on to the later ones. First
143/// mention keeps the bare slug, so a link written against a document that later grows a
144/// second section of the same name still lands where it did.
145fn heading_ids(source: &str) -> VecDeque<Option<String>> {
146 let mut ids = VecDeque::new();
147 let mut taken: HashMap<String, usize> = HashMap::new();
148 let mut text: Option<String> = None;
149
150 for event in Parser::new_ext(source, options()) {
151 match event {
152 Event::Start(Tag::Heading { .. }) => text = Some(String::new()),
153 Event::End(TagEnd::Heading(_)) => {
154 let Some(collected) = text.take() else {
155 continue;
156 };
157
158 ids.push_back(match slugify(&collected) {
159 slug if slug.is_empty() => None,
160 slug => {
161 let seen = taken.entry(slug.clone()).or_insert(0);
162 *seen += 1;
163
164 Some(match *seen {
165 1 => slug,
166 n => format!("{slug}-{}", n - 1),
167 })
168 }
169 });
170 }
171 // Code spans count, and so does an image's alt text: both are words a
172 // reader sees in the heading. HTML in the source is text here as everywhere
173 // else, which is why it is collected rather than skipped.
174 Event::Text(value)
175 | Event::Code(value)
176 | Event::Html(value)
177 | Event::InlineHtml(value) => {
178 if let Some(text) = text.as_mut() {
179 text.push_str(&value);
180 }
181 }
182 Event::SoftBreak | Event::HardBreak => {
183 if let Some(text) = text.as_mut() {
184 text.push(' ');
185 }
186 }
187 _ => {}
188 }
189 }
190
191 ids
192}
193
194/// A heading's text as a fragment.
195///
196/// Lowercased; letters, digits and hyphens kept; whitespace turned into a single
197/// hyphen; everything else dropped. Non-ASCII letters are kept as they are — a heading
198/// in another script should still be linkable, and percent-encoding happens in the URL
199/// rather than in the id.
200fn slugify(text: &str) -> String {
201 let mut slug = String::with_capacity(text.len());
202 let mut pending_gap = false;
203
204 for ch in text.chars() {
205 if ch.is_whitespace() || ch == '-' || ch == '_' {
206 // A run of spaces, or a space beside a hyphen, is one hyphen — and a
207 // trailing one is never written, because the gap is only emitted once
208 // something follows it.
209 pending_gap = !slug.is_empty();
210 continue;
211 }
212
213 if !(ch.is_alphanumeric()) {
214 continue;
215 }
216
217 if pending_gap {
218 slug.push('-');
219 pending_gap = false;
220 }
221
222 slug.extend(ch.to_lowercase());
223 }
224
225 slug
226}
227
228/// The dialect Steid understands.
229///
230/// Tables, strikethrough, task lists and footnotes are the parts of GitHub-flavoured
231/// markdown a README actually uses. Smart punctuation is deliberately *off*: it turns
232/// `--flag` into an en dash, which silently corrupts command-line flags written in
233/// prose — the exact thing a README is full of.
234fn options() -> Options {
235 Options::ENABLE_TABLES
236 | Options::ENABLE_STRIKETHROUGH
237 | Options::ENABLE_TASKLISTS
238 | Options::ENABLE_FOOTNOTES
239}
240
241/// What a link destination turned out to be.
242enum Destination {
243 /// Safe to put in an `href` or `src`.
244 Allowed(String),
245 /// A scheme that is not in [`ALLOWED_SCHEMES`]. The attribute is dropped entirely.
246 Refused,
247}
248
249/// Decides whether a destination may appear in an attribute, and in what form.
250///
251/// `kind` is passed straight to the resolver, which is the only thing that knows what a
252/// relative destination means where this markdown came from. A resolver that wants
253/// nothing to do with one answers `None` and it is left exactly as written.
254fn destination(
255 raw: &str,
256 kind: Relative,
257 resolve: &impl Fn(Relative, &str) -> Option<String>,
258) -> Destination {
259 // Browsers strip ASCII control characters — tab, newline, carriage return among
260 // them — out of a URL before parsing it, so `java&Tab;script:alert(1)` is a
261 // `javascript:` URL by the time it matters. Judge the stripped form *and* emit it,
262 // or the check and the browser would be looking at different strings. Interior
263 // spaces are left alone: they are legal in a `<...>` destination and are not a way
264 // to hide a scheme, since a scheme cannot contain one.
265 let cleaned: String = raw
266 .trim()
267 .chars()
268 .filter(|c| !c.is_ascii_control())
269 .collect();
270
271 let resolved = match scheme_of(&cleaned) {
272 Some(_) => cleaned,
273 // No scheme. An absolute path and a fragment already point at this origin; only
274 // a genuinely relative destination is the caller's to reinterpret.
275 None if cleaned.starts_with('/') || cleaned.starts_with('#') || cleaned.is_empty() => {
276 cleaned
277 }
278 None => resolve(kind, &cleaned).unwrap_or(cleaned),
279 };
280
281 match scheme_of(&resolved) {
282 Some(scheme) if !ALLOWED_SCHEMES.contains(&scheme.as_str()) => Destination::Refused,
283 _ => Destination::Allowed(resolved),
284 }
285}
286
287/// The URL's scheme, lowercased, or `None` when it has none.
288///
289/// A colon only introduces a scheme when it comes before any `/`, `?` or `#` and what
290/// precedes it is a legal scheme name — otherwise `docs/a:b.md` and `#a:b` would read
291/// as schemes and be refused.
292fn scheme_of(url: &str) -> Option<String> {
293 let end = url.find([':', '/', '?', '#'])?;
294
295 if url.as_bytes()[end] != b':' {
296 return None;
297 }
298
299 let scheme = &url[..end];
300 let mut chars = scheme.chars();
301
302 if !chars.next()?.is_ascii_alphabetic() {
303 return None;
304 }
305 if !chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) {
306 return None;
307 }
308
309 Some(scheme.to_ascii_lowercase())
310}
311
312// --- Cross-references ---------------------------------------------------------------
313
314/// The shortest object id a bare word may be, matching `git`'s own abbreviation.
315const SHA_MIN: usize = 7;
316
317/// A full object id. Anything longer is a word that happens to start with hex.
318const SHA_MAX: usize = 40;
319
320/// How many characters of a linked object id are shown.
321const SHA_SHOWN: usize = 7;
322
323/// A reference found in prose.
324#[derive(Debug, PartialEq, Eq)]
325enum Reference<'a> {
326 /// `#12`, whether or not issue 12 exists — see [`references`].
327 Issue(IssueNumber),
328 /// A bare object id, by *shape* only. Never checked against the repository.
329 Commit(&'a str),
330}
331
332/// The references in a text node, in order, each with the byte range it occupies.
333///
334/// Pure and shape-only: an issue number is not checked for existence and an object id
335/// is not checked against git. Both would cost a query or a fork per reference on every
336/// render, and the pages they point at already answer 404 for something that is not
337/// there.
338///
339/// A reference has to stand on its own. The character before it may not be one a path,
340/// a version or a URL is made of, which is what keeps `src/deadbeef1`, `v1.0-abcdef1`
341/// and `https://example.com/x#12` as text. After it, a letter, digit, `_` or `-`
342/// likewise disqualifies it, so `#12a` is not issue 12 — but a full stop or a comma is
343/// ordinary sentence punctuation and ends the reference rather than spoiling it.
344fn references(text: &str) -> Vec<(std::ops::Range<usize>, Reference<'_>)> {
345 let bytes = text.as_bytes();
346 let mut found = Vec::new();
347 let mut index = 0;
348
349 while index < bytes.len() {
350 if !starts_a_reference(text, index) {
351 index += 1;
352 continue;
353 }
354
355 let rest = &text[index..];
356
357 // `#12`. The digits are taken greedily, so `#12a` is rejected below rather
358 // than silently becoming issue 12.
359 if let Some(digits) = rest.strip_prefix('#') {
360 let end = digits
361 .find(|c: char| !c.is_ascii_digit())
362 .unwrap_or(digits.len());
363
364 let number = (end > 0 && ends_a_reference(text, index + 1 + end))
365 .then(|| digits[..end].parse::<u64>().ok())
366 .flatten()
367 // `new` rather than `from_trusted`: `#0` is prose, not a link.
368 .and_then(|value| IssueNumber::new(value).ok());
369
370 if let Some(number) = number {
371 found.push((index..index + 1 + end, Reference::Issue(number)));
372 index += 1 + end;
373 continue;
374 }
375
376 index += 1;
377 continue;
378 }
379
380 // A bare object id. Lowercase only, which is what `git` prints; an uppercase
381 // one would take `DEADBEEF` out of prose for no gain.
382 let end = rest
383 .find(|c: char| !matches!(c, '0'..='9' | 'a'..='f'))
384 .unwrap_or(rest.len());
385
386 if (SHA_MIN..=SHA_MAX).contains(&end) && ends_a_reference(text, index + end) {
387 found.push((index..index + end, Reference::Commit(&rest[..end])));
388 index += end;
389 continue;
390 }
391
392 // Skip the whole word, so a reference can never begin inside one.
393 index += rest
394 .find(|c: char| !is_word(c))
395 .unwrap_or(rest.len())
396 .max(1);
397 }
398
399 found
400}
401
402/// Whether a reference may begin at `index`.
403fn starts_a_reference(text: &str, index: usize) -> bool {
404 if !text.is_char_boundary(index) {
405 return false;
406 }
407
408 text[..index]
409 .chars()
410 .next_back()
411 .is_none_or(|c| !is_word(c))
412}
413
414/// Whether a reference may end at `index`.
415fn ends_a_reference(text: &str, index: usize) -> bool {
416 text[index..]
417 .chars()
418 .next()
419 .is_none_or(|c| !(c.is_alphanumeric() || matches!(c, '_' | '-')))
420}
421
422/// Whether a character is one a reference cannot start immediately after.
423///
424/// Wider than "alphanumeric" on purpose: `-`, `.`, `_` and `/` are what file paths,
425/// version strings and URLs are made of, and a link sprouting inside one of those is
426/// worse than a missing link.
427fn is_word(c: char) -> bool {
428 c.is_alphanumeric() || matches!(c, '-' | '_' | '.' | '/')
429}
430
431/// An image being assembled.
432///
433/// An image's alt text arrives as the events *between* its start and end tags, so it
434/// has to be collected before the `<img>` can be written at all.
435struct Image {
436 destination: Destination,
437 title: String,
438 alt: String,
439}
440
441/// A code block being collected.
442///
443/// Highlighting needs the whole block — a string can open on one line and close on
444/// another — so its text is buffered rather than written as it arrives.
445struct Fence {
446 language: String,
447 text: String,
448}
449
450impl Fence {
451 /// The language is the info string's first word: ` ```rust,ignore ` and
452 /// ` ```rust no_run ` both mean Rust, and an indented block names nothing.
453 fn new(kind: CodeBlockKind<'_>) -> Self {
454 let language = match kind {
455 CodeBlockKind::Fenced(info) => info
456 .split([' ', '\t', ','])
457 .next()
458 .unwrap_or_default()
459 .to_owned(),
460 CodeBlockKind::Indented => String::new(),
461 };
462
463 Self {
464 language,
465 text: String::new(),
466 }
467 }
468}
469
470/// Writes an event stream out as HTML.
471///
472/// Every tag this can emit is written literally below, which is what makes "raw HTML
473/// cannot reach the page" a property of the code rather than of a filter that has to be
474/// kept correct. The classes are Tailwind utilities in theme tokens only — a hardcoded
475/// colour would follow neither a palette change nor the colour scheme — and they live
476/// here as literals so Tailwind's scan of `./src/**/*.rs` finds them.
477struct Writer<'a, F> {
478 out: Formatter<'a>,
479 cross: Option<Crossref<'a>>,
480 resolve: F,
481 image: Option<Image>,
482 fence: Option<Fence>,
483 alignments: Vec<Alignment>,
484 column: usize,
485 in_head: bool,
486 in_link: bool,
487 /// The id the next heading opens with, taken from the read-ahead in
488 /// [`render_with_targets`]. Consumed as the tag is written.
489 heading_id: Option<String>,
490}
491
492impl<'a, F: Fn(Relative, &str) -> Option<String>> Writer<'a, F> {
493 fn new(buf: &'a mut String, cross: Option<Crossref<'a>>, resolve: F) -> Self {
494 Self {
495 out: Formatter::new(buf),
496 cross,
497 resolve,
498 image: None,
499 fence: None,
500 alignments: Vec::new(),
501 column: 0,
502 in_head: false,
503 in_link: false,
504 heading_id: None,
505 }
506 }
507
508 /// Markup this module chose. Never anything derived from the source.
509 ///
510 /// The one thing passed through that is *shaped* by the source is a highlighted
511 /// code line, and that is markup [`highlight`] wrote around text it escaped — the
512 /// same fragments the blob view emits.
513 fn raw(&mut self, markup: &str) {
514 self.out.write_str(markup);
515 }
516
517 /// Content from the source, as a text node — or as alt text while inside an image,
518 /// or as a line of the code block being collected.
519 fn text(&mut self, value: &str) {
520 if let Some(fence) = self.fence.as_mut() {
521 fence.text.push_str(value);
522 return;
523 }
524 if let Some(image) = self.image.as_mut() {
525 image.alt.push_str(value);
526 return;
527 }
528
529 self.prose(value);
530 }
531
532 /// Content from the source, escaped and nothing more.
533 fn escaped(&mut self, value: &str) {
534 HtmlContext::Text.writer(&mut self.out).write_str(value);
535 }
536
537 /// Prose, with `#12` and bare object ids turned into links.
538 ///
539 /// Only prose: a code span and a code block never reach here, because a `#12` in a
540 /// command line is the shell's comment character and not an issue. Neither does the
541 /// text of a link, which would otherwise nest one `<a>` inside another.
542 fn prose(&mut self, value: &str) {
543 let Some(cross) = self.cross.filter(|_| !self.in_link) else {
544 return self.escaped(value);
545 };
546
547 let mut written = 0;
548
549 for (range, reference) in references(value) {
550 self.escaped(&value[written..range.start]);
551 written = range.end;
552
553 match reference {
554 Reference::Issue(number) => {
555 self.raw("<a class=\"text-primary hover:underline\"");
556 self.attribute(
557 "href",
558 &cross.absolute(issue_url(cross.handle, cross.name, number)),
559 );
560 self.raw(">");
561 self.escaped(&value[range]);
562 self.raw("</a>");
563 }
564 Reference::Commit(sha) => {
565 self.raw("<a class=\"font-mono text-primary hover:underline\"");
566 self.attribute(
567 "href",
568 &cross.absolute(commit_url(cross.handle, cross.name, sha)),
569 );
570 self.attribute("title", sha);
571 self.raw(">");
572 // Shown abbreviated, like every other sha on a Steid page; the
573 // link and the tooltip keep the id that was written.
574 self.escaped(&sha[..SHA_SHOWN]);
575 self.raw("</a>");
576 }
577 }
578 }
579
580 self.escaped(&value[written..]);
581 }
582
583 /// Content from the source, inside a double-quoted attribute value.
584 fn attribute(&mut self, name: &str, value: &str) {
585 self.out.write_str(" ");
586 self.out.write_str(name);
587 self.out.write_str("=\"");
588 HtmlContext::AttributeValue
589 .writer(&mut self.out)
590 .write_str(value);
591 self.out.write_str("\"");
592 }
593
594 fn event(&mut self, event: Event<'_>) {
595 match event {
596 Event::Start(tag) => self.start(tag),
597 Event::End(tag) => self.end(tag),
598 Event::Text(text) => self.text(&text),
599 Event::Code(code) => {
600 self.raw(
601 "<code class=\"rounded border border-border bg-surface px-1 py-0.5 font-mono text-[0.85em]\">",
602 );
603 // `escaped`, not `text`: a reference inside backticks is being quoted,
604 // not made.
605 self.escaped(&code);
606 self.raw("</code>");
607 }
608 // The security-critical case, and the reason this module exists in this
609 // shape. HTML in the source is written as text: visible, inert, and
610 // honest about what the author wrote.
611 Event::Html(html) | Event::InlineHtml(html) => self.text(&html),
612 Event::SoftBreak => self.raw("\n"),
613 Event::HardBreak => self.raw("<br />"),
614 Event::Rule => self.raw("<hr class=\"my-6 border-t border-border\" />"),
615 Event::FootnoteReference(label) => {
616 self.raw("<sup><a class=\"text-primary hover:underline\"");
617 self.attribute("href", &format!("#fn-{label}"));
618 self.raw(">");
619 self.text(&label);
620 self.raw("</a></sup>");
621 }
622 Event::TaskListMarker(checked) => {
623 self.raw("<input type=\"checkbox\" disabled class=\"mr-2 align-middle\"");
624 if checked {
625 self.raw(" checked");
626 }
627 self.raw(" />");
628 }
629 // Only reachable with options this module does not enable.
630 Event::InlineMath(value) | Event::DisplayMath(value) => self.text(&value),
631 }
632 }
633
634 fn start(&mut self, tag: Tag<'_>) {
635 match tag {
636 Tag::Paragraph => self.raw("<p class=\"my-3 leading-relaxed\">"),
637 Tag::Heading { level, .. } => {
638 let (tag, classes) = heading_parts(level);
639
640 self.raw("<");
641 self.raw(tag);
642 self.raw(" class=\"");
643 self.raw(classes);
644 self.raw("\"");
645
646 // Ids are this module's own, derived from the heading's text — nothing
647 // from the source reaches an attribute unescaped, and `attribute`
648 // escapes it regardless.
649 if let Some(id) = self.heading_id.take() {
650 self.attribute("id", &id);
651 }
652
653 self.raw(">");
654 }
655 Tag::BlockQuote(_) => self.raw(
656 "<blockquote class=\"my-4 border-l-2 border-border pl-4 text-muted-foreground\">",
657 ),
658 // Nothing is written yet: the block's text has to be complete before it
659 // can be highlighted, and a fence with no usable info string falls back to
660 // exactly the plain output this wrote before.
661 Tag::CodeBlock(kind) => self.fence = Some(Fence::new(kind)),
662 // The block itself is nothing; its lines arrive as `Event::Html` and are
663 // written as text, so they need somewhere to sit.
664 Tag::HtmlBlock => self.raw("<p class=\"my-3 leading-relaxed\">"),
665 Tag::List(None) => self.raw("<ul class=\"my-3 list-disc space-y-1 pl-6\">"),
666 Tag::List(Some(first)) => {
667 self.raw("<ol class=\"my-3 list-decimal space-y-1 pl-6\"");
668 if first != 1 {
669 self.attribute("start", &first.to_string());
670 }
671 self.raw(">");
672 }
673 Tag::Item => self.raw("<li>"),
674 Tag::FootnoteDefinition(label) => {
675 self.raw("<div class=\"mt-2 text-xs text-muted-foreground\"");
676 self.attribute("id", &format!("fn-{label}"));
677 self.raw("><span class=\"mr-2 font-mono\">");
678 self.text(&label);
679 self.raw("</span>");
680 }
681 Tag::Table(alignments) => {
682 self.alignments = alignments;
683 self.raw(
684 "<div class=\"my-4 overflow-x-auto\"><table class=\"w-full border-collapse text-sm\">",
685 );
686 }
687 Tag::TableHead => {
688 self.in_head = true;
689 self.column = 0;
690 self.raw("<thead><tr>");
691 }
692 Tag::TableRow => {
693 self.column = 0;
694 self.raw("<tr>");
695 }
696 Tag::TableCell => {
697 let alignment = self.alignments.get(self.column).copied();
698
699 if self.in_head {
700 // A header with no stated alignment is left-aligned rather than
701 // left to the browser, which centres `<th>` by default and makes a
702 // plain markdown table look deliberately centred when it is not.
703 self.raw("<th class=\"border-b border-border px-3 py-2 font-medium ");
704 self.raw(align_class(alignment).unwrap_or("text-left"));
705 } else {
706 self.raw("<td class=\"border-b border-border px-3 py-2 ");
707 self.raw(align_class(alignment).unwrap_or(""));
708 }
709
710 self.raw("\">");
711 }
712 Tag::Emphasis => self.raw("<em>"),
713 Tag::Strong => self.raw("<strong class=\"font-semibold\">"),
714 Tag::Strikethrough => self.raw("<del>"),
715 Tag::Superscript => self.raw("<sup>"),
716 Tag::Subscript => self.raw("<sub>"),
717 Tag::Link {
718 dest_url, title, ..
719 } => {
720 self.in_link = true;
721 self.raw("<a");
722
723 // A refused destination keeps its text but loses its `href` — and its
724 // link styling with it, so it does not read as a link that silently
725 // does nothing. Dropping the element entirely would swallow what the
726 // author wrote.
727 if let Destination::Allowed(url) =
728 destination(&dest_url, Relative::Link, &self.resolve)
729 {
730 self.raw(" class=\"text-primary hover:underline\"");
731 self.attribute("href", &url);
732 }
733 if !title.is_empty() {
734 self.attribute("title", &title);
735 }
736
737 self.raw(">");
738 }
739 Tag::Image {
740 dest_url, title, ..
741 } => {
742 self.image = Some(Image {
743 destination: destination(&dest_url, Relative::Image, &self.resolve),
744 title: title.into_string(),
745 alt: String::new(),
746 });
747 }
748 // Only reachable with options this module does not enable.
749 Tag::DefinitionList
750 | Tag::DefinitionListTitle
751 | Tag::DefinitionListDefinition
752 | Tag::MetadataBlock(_) => {}
753 }
754 }
755
756 fn end(&mut self, tag: TagEnd) {
757 match tag {
758 TagEnd::Paragraph | TagEnd::HtmlBlock => self.raw("</p>"),
759 TagEnd::Heading(level) => self.raw(heading_close(level)),
760 TagEnd::BlockQuote(_) => self.raw("</blockquote>"),
761 TagEnd::CodeBlock => self.code_block(),
762 TagEnd::List(true) => self.raw("</ol>"),
763 TagEnd::List(false) => self.raw("</ul>"),
764 TagEnd::Item => self.raw("</li>"),
765 TagEnd::FootnoteDefinition => self.raw("</div>"),
766 TagEnd::Table => self.raw("</table></div>"),
767 TagEnd::TableHead => {
768 self.in_head = false;
769 self.raw("</tr></thead><tbody>");
770 }
771 TagEnd::TableRow => self.raw("</tr>"),
772 TagEnd::TableCell => {
773 self.column += 1;
774 if self.in_head {
775 self.raw("</th>");
776 } else {
777 self.raw("</td>");
778 }
779 }
780 TagEnd::Emphasis => self.raw("</em>"),
781 TagEnd::Strong => self.raw("</strong>"),
782 TagEnd::Strikethrough => self.raw("</del>"),
783 TagEnd::Superscript => self.raw("</sup>"),
784 TagEnd::Subscript => self.raw("</sub>"),
785 TagEnd::Link => {
786 self.in_link = false;
787 self.raw("</a>");
788 }
789 TagEnd::Image => self.image(),
790 TagEnd::DefinitionList
791 | TagEnd::DefinitionListTitle
792 | TagEnd::DefinitionListDefinition
793 | TagEnd::MetadataBlock(_) => {}
794 }
795 }
796
797 /// Writes the code block whose lines have just finished arriving.
798 ///
799 /// Highlighted when the info string names a grammar and the block is inside the
800 /// blob view's caps, and plain otherwise — the fallbacks are
801 /// [`highlight::fenced_lines`]'s, and every one of them lands on the text as
802 /// written.
803 fn code_block(&mut self) {
804 let Some(fence) = self.fence.take() else {
805 return;
806 };
807
808 self.raw(
809 "<pre class=\"my-4 overflow-x-auto rounded-lg border border-border bg-surface px-4 py-3 font-mono text-xs leading-relaxed\"><code>",
810 );
811
812 // Through the process's one highlight cache — the same one the blob and blame
813 // views reach through app context. A README is re-rendered on every visit to a
814 // repository's front page and its fences never change between them.
815 match highlight::cache()
816 .fenced_lines(&fence.language, &fence.text)
817 .as_ref()
818 {
819 Some(lines) => {
820 for line in lines {
821 self.raw(line);
822 // The fragments carry no line ending, exactly as the blob view's
823 // cells do not — inside a `<pre>` the newline is what makes the
824 // line, so it is put back here.
825 self.raw("\n");
826 }
827 }
828 None => self.escaped(&fence.text),
829 }
830
831 self.raw("</code></pre>");
832 }
833
834 /// Writes the image whose alt text has just finished arriving.
835 ///
836 /// A refused source is not rendered as a broken image: the alt text is written on
837 /// its own, which is the same thing a reader with images off would get.
838 fn image(&mut self) {
839 let Some(image) = self.image.take() else {
840 return;
841 };
842
843 let Destination::Allowed(url) = image.destination else {
844 self.text(&image.alt);
845 return;
846 };
847
848 self.raw("<img class=\"my-4 max-w-full rounded-lg border border-border\"");
849 self.attribute("src", &url);
850 self.attribute("alt", &image.alt);
851 if !image.title.is_empty() {
852 self.attribute("title", &image.title);
853 }
854 self.raw(" />");
855 }
856}
857
858/// The class for a column's stated alignment, or `None` when it stated none.
859fn align_class(alignment: Option<Alignment>) -> Option<&'static str> {
860 match alignment? {
861 Alignment::Center => Some("text-center"),
862 Alignment::Right => Some("text-right"),
863 Alignment::Left => Some("text-left"),
864 Alignment::None => None,
865 }
866}
867
868/// Headings step down in weight as well as size, so a README's `##` sections read as
869/// sections rather than as six sizes of the same thing.
870/// The element and the classes, apart, because an `id` goes between them.
871fn heading_parts(level: HeadingLevel) -> (&'static str, &'static str) {
872 match level {
873 HeadingLevel::H1 => ("h1", "mt-8 mb-3 text-2xl font-semibold tracking-tight"),
874 HeadingLevel::H2 => (
875 "h2",
876 "mt-8 mb-3 border-b border-border pb-2 text-xl font-semibold tracking-tight",
877 ),
878 HeadingLevel::H3 => ("h3", "mt-6 mb-2 text-lg font-semibold"),
879 HeadingLevel::H4 => ("h4", "mt-6 mb-2 text-base font-semibold"),
880 HeadingLevel::H5 => ("h5", "mt-4 mb-2 text-sm font-semibold"),
881 HeadingLevel::H6 => (
882 "h6",
883 "mt-4 mb-2 text-sm font-semibold text-muted-foreground",
884 ),
885 }
886}
887
888fn heading_close(level: HeadingLevel) -> &'static str {
889 match level {
890 HeadingLevel::H1 => "</h1>",
891 HeadingLevel::H2 => "</h2>",
892 HeadingLevel::H3 => "</h3>",
893 HeadingLevel::H4 => "</h4>",
894 HeadingLevel::H5 => "</h5>",
895 HeadingLevel::H6 => "</h6>",
896 }
897}
898
899#[cfg(test)]
900mod tests {
901 use super::*;
902
903 /// The repository the cross-reference tests render against.
904 const REPO: Crossref<'static> = Crossref {
905 handle: "ada",
906 name: "steid",
907 origin: None,
908 };
909
910 /// The rendered HTML, for a test to look inside. No repository, so no
911 /// cross-references — those have their own tests.
912 fn html(source: &str) -> String {
913 render(source, None).as_str().to_owned()
914 }
915
916 /// The same, rendered inside a repository.
917 fn html_in_repo(source: &str) -> String {
918 render(source, Some(REPO)).as_str().to_owned()
919 }
920
921 /// The same, with a resolver for relative links.
922 fn html_with(source: &str, resolve: impl Fn(&str) -> Option<String>) -> String {
923 render_with_links(source, None, resolve).as_str().to_owned()
924 }
925
926 #[test]
927 fn headings_become_headings() {
928 assert!(html("# Steid").contains("<h1 class=\""));
929 assert!(html("# Steid").contains(">Steid</h1>"));
930 assert!(html("### Deeper").contains(">Deeper</h3>"));
931 }
932
933 #[test]
934 fn a_heading_carries_the_id_a_fragment_link_lands_on() {
935 let rendered = html("## Getting started\n");
936
937 assert!(
938 rendered.contains("id=\"getting-started\""),
939 "got {rendered}"
940 );
941 }
942
943 #[test]
944 fn punctuation_and_code_spans_are_slugged_the_way_a_reader_would_write_them() {
945 assert_eq!(slugify("Getting started"), "getting-started");
946 assert_eq!(slugify("What's `new`?"), "whats-new");
947 assert_eq!(slugify(" Spaced out "), "spaced-out");
948 // A hyphen already there is a gap, not a doubled one.
949 assert_eq!(slugify("read-only browsing"), "read-only-browsing");
950 assert_eq!(slugify("!!!"), "");
951 }
952
953 #[test]
954 fn two_headings_with_one_name_get_different_ids() {
955 // A README with two "Usage" sections is ordinary, and two identical ids would
956 // send both links to the first.
957 let rendered = html("## Usage\n\n## Usage\n\n## Usage\n");
958
959 assert!(rendered.contains("id=\"usage\""), "got {rendered}");
960 assert!(rendered.contains("id=\"usage-1\""), "got {rendered}");
961 assert!(rendered.contains("id=\"usage-2\""), "got {rendered}");
962 }
963
964 #[test]
965 fn a_heading_that_slugs_to_nothing_gets_no_id_rather_than_an_empty_one() {
966 let rendered = html("# ***\n");
967
968 assert!(rendered.contains("<h1 class=\""), "got {rendered}");
969 assert!(!rendered.contains("id=\"\""), "got {rendered}");
970 }
971
972 #[test]
973 fn a_heading_id_is_escaped_like_every_other_attribute() {
974 // Nothing from the source can reach an attribute unescaped. The slug drops the
975 // quote and the bracket long before this, and the escaping is the backstop.
976 let rendered = html("## a\"b<c\n");
977
978 assert!(!rendered.contains("id=\"a\"b"), "got {rendered}");
979 assert!(rendered.contains("id=\"abc\""), "got {rendered}");
980 }
981
982 #[test]
983 fn lists_keep_their_kind() {
984 let bullets = html("- one\n- two\n");
985 assert!(bullets.contains("<ul class="));
986 assert!(bullets.contains("<li>one</li>"));
987
988 let numbers = html("3. three\n4. four\n");
989 assert!(numbers.contains("<ol class="));
990 assert!(numbers.contains("start=\"3\""));
991 }
992
993 #[test]
994 fn a_fenced_code_block_is_a_pre_and_its_contents_are_text() {
995 // No info string, so no highlighting — the escaping is the point here.
996 let rendered = html("```\nlet x = 1 < 2;\n```\n");
997
998 assert!(rendered.contains("<pre class="));
999 assert!(rendered.contains("<code>let x = 1 &lt; 2;\n</code></pre>"));
1000 }
1001
1002 #[test]
1003 fn inline_code_is_a_code_element() {
1004 assert!(html("use `cargo test`").contains("<code class=\"rounded"));
1005 }
1006
1007 #[test]
1008 fn a_table_renders_as_a_table_with_alignment() {
1009 let rendered = html("| a | b |\n|:-:|--:|\n| 1 | 2 |\n");
1010
1011 assert!(rendered.contains("<table class="));
1012 assert!(
1013 rendered.contains(
1014 "<th class=\"border-b border-border px-3 py-2 font-medium text-center\">"
1015 )
1016 );
1017 assert!(rendered.contains("text-right"));
1018 assert!(rendered.contains("<tbody><tr><td"));
1019 }
1020
1021 #[test]
1022 fn a_header_with_no_stated_alignment_is_left_aligned() {
1023 // A browser centres `<th>` on its own, which reads as a deliberate choice.
1024 let rendered = html("| a |\n|---|\n| 1 |\n");
1025
1026 assert!(rendered.contains("font-medium text-left\">"), "{rendered}");
1027 }
1028
1029 #[test]
1030 fn task_lists_render_as_disabled_checkboxes() {
1031 let rendered = html("- [x] done\n- [ ] not\n");
1032
1033 assert!(rendered.contains("type=\"checkbox\" disabled"));
1034 assert!(rendered.contains(" checked />"));
1035 }
1036
1037 // --- Safety ---------------------------------------------------------------------
1038
1039 #[test]
1040 fn a_script_tag_in_the_source_is_text_and_not_a_tag() {
1041 let rendered = html("<script>alert(1)</script>\n");
1042
1043 assert!(
1044 !rendered.contains("<script"),
1045 "a script tag reached the page: {rendered}"
1046 );
1047 assert!(rendered.contains("&lt;script&gt;alert(1)&lt;/script&gt;"));
1048 }
1049
1050 #[test]
1051 fn a_reference_is_made_absolute_when_an_origin_is_given() {
1052 // What a feed needs: its content is read outside the site, so `/ada/...` there
1053 // resolves against the reader rather than against us. The page keeps the
1054 // relative form, which is what `REPO` renders everywhere else in these tests.
1055 let cross = Crossref {
1056 origin: Some("https://steid.example"),
1057 ..REPO
1058 };
1059 let rendered = render("fixes #12 in deadbeef1", Some(cross)).to_string();
1060
1061 assert!(
1062 rendered.contains("href=\"https://steid.example/ada/repos/steid/issues/12\""),
1063 "{rendered}"
1064 );
1065 assert!(
1066 rendered.contains("href=\"https://steid.example/ada/repos/steid/commits/deadbeef1\""),
1067 "{rendered}"
1068 );
1069 }
1070
1071 #[test]
1072 fn an_inline_event_handler_is_text_and_not_a_tag() {
1073 let rendered = html("Look: <img src=x onerror=\"alert(1)\"> at that.\n");
1074
1075 // The words are still there — they are *text* now. What matters is that no
1076 // element was created for the handler to hang off.
1077 assert!(
1078 !rendered.contains("<img"),
1079 "an image tag reached the page: {rendered}"
1080 );
1081 assert!(rendered.contains("&lt;img src=x onerror="));
1082 }
1083
1084 #[test]
1085 fn an_html_comment_cannot_hide_markup() {
1086 let rendered = html("<!-- <script>alert(1)</script> -->\n");
1087
1088 assert!(!rendered.contains("<script"), "{rendered}");
1089 assert!(!rendered.contains("<!--"), "{rendered}");
1090 }
1091
1092 #[test]
1093 fn a_javascript_link_loses_its_href() {
1094 let rendered = html("[click](javascript:alert(1))");
1095
1096 assert!(!rendered.contains("javascript"), "{rendered}");
1097 assert!(rendered.contains("<a>click</a>"), "{rendered}");
1098 }
1099
1100 #[test]
1101 fn a_javascript_url_split_by_a_control_character_still_loses_its_href() {
1102 // A browser strips the tab before parsing the URL, so the check has to as well.
1103 let rendered = html("[click](<java&#9;script:alert(1)>)");
1104
1105 assert!(!rendered.contains("href"), "{rendered}");
1106 }
1107
1108 #[test]
1109 fn an_uppercase_scheme_is_still_refused() {
1110 assert!(!html("[click](JaVaScRiPt:alert(1))").contains("href"));
1111 }
1112
1113 #[test]
1114 fn a_data_url_image_is_refused_and_leaves_its_alt_text() {
1115 let rendered = html("![a logo](data:text/html;base64,PHNjcmlwdD4=)");
1116
1117 assert!(!rendered.contains("<img"), "{rendered}");
1118 assert!(rendered.contains("a logo"));
1119 }
1120
1121 #[test]
1122 fn ordinary_links_and_images_survive() {
1123 assert!(
1124 html("[home](https://example.com/a?b=1)")
1125 .contains("href=\"https://example.com/a?b=1\"")
1126 );
1127 assert!(html("[mail](mailto:ada@example.com)").contains("href=\"mailto:ada@example.com\""));
1128 assert!(
1129 html("![logo](https://example.com/l.png)")
1130 .contains("src=\"https://example.com/l.png\"")
1131 );
1132 assert!(html("[anchor](#usage)").contains("href=\"#usage\""));
1133 }
1134
1135 #[test]
1136 fn text_that_needs_escaping_is_escaped() {
1137 let rendered = html("5 < 6 & \"quoted\" > 4\n");
1138
1139 assert!(rendered.contains("5 &lt; 6 &amp; \"quoted\" &gt; 4"));
1140 }
1141
1142 #[test]
1143 fn a_title_cannot_break_out_of_its_attribute() {
1144 let rendered = html("[x](https://example.com \"a \\\" onmouseover=alert(1)\")");
1145
1146 assert!(rendered.contains("&quot;"), "{rendered}");
1147 assert!(!rendered.contains("\" onmouseover"), "{rendered}");
1148 }
1149
1150 // --- Relative links -------------------------------------------------------------
1151
1152 #[test]
1153 fn a_relative_link_is_handed_to_the_resolver() {
1154 let rendered = html_with("[c](./CONTRIBUTING.md)", |dest| {
1155 Some(format!("/tree/{dest}"))
1156 });
1157
1158 assert!(
1159 rendered.contains("href=\"/tree/./CONTRIBUTING.md\""),
1160 "{rendered}"
1161 );
1162 }
1163
1164 #[test]
1165 fn absolute_paths_anchors_and_urls_are_not_resolved() {
1166 let resolve = |_: &str| Some("/rewritten".to_owned());
1167
1168 for source in ["[a](/already)", "[a](#anchor)", "[a](https://example.com/)"] {
1169 let rendered = html_with(source, resolve);
1170 assert!(!rendered.contains("/rewritten"), "{source}: {rendered}");
1171 }
1172 }
1173
1174 #[test]
1175 fn a_resolver_cannot_smuggle_in_a_dangerous_url() {
1176 // The scheme check runs after resolution, on purpose.
1177 let rendered = html_with("[a](whatever.md)", |_| {
1178 Some("javascript:alert(1)".to_owned())
1179 });
1180
1181 assert!(!rendered.contains("href"), "{rendered}");
1182 }
1183
1184 #[test]
1185 fn a_relative_image_is_never_resolved() {
1186 // A tree URL serves a *page*, so rewriting an image source to one would swap a
1187 // 404 for a broken image. The resolver is for links only.
1188 let rendered = html_with("![l](logo.png)", |_| Some("/rewritten".to_owned()));
1189
1190 assert!(rendered.contains("src=\"logo.png\""), "{rendered}");
1191 }
1192
1193 #[test]
1194 fn a_resolver_that_wants_images_is_offered_them_separately() {
1195 // What a file inside a repository needs: its links point at pages and its
1196 // images at bytes, and one resolver has to be able to tell them apart.
1197 let rendered = render_with_targets(
1198 "[a](docs/a.md) ![alt](img/logo.png)\n",
1199 None,
1200 |kind, destination| {
1201 Some(match kind {
1202 Relative::Link => format!("/tree/{destination}"),
1203 Relative::Image => format!("/raw/{destination}"),
1204 })
1205 },
1206 );
1207 let html = rendered.as_str();
1208
1209 assert!(html.contains("href=\"/tree/docs/a.md\""), "{html}");
1210 assert!(html.contains("src=\"/raw/img/logo.png\""), "{html}");
1211 }
1212
1213 #[test]
1214 fn a_resolver_cannot_smuggle_a_dangerous_url_into_an_image_either() {
1215 // Resolution happens before the scheme check, which is what makes this hold
1216 // for the destination a resolver invented as well as for one that was written.
1217 let rendered = render_with_targets("![alt](logo.png)\n", None, |_, _| {
1218 Some("javascript:alert(1)".to_owned())
1219 });
1220
1221 assert!(!rendered.as_str().contains("javascript"));
1222 assert!(rendered.as_str().contains("alt"));
1223 }
1224
1225 #[test]
1226 fn without_a_resolver_a_relative_link_is_left_alone() {
1227 assert!(html("[c](./CONTRIBUTING.md)").contains("href=\"./CONTRIBUTING.md\""));
1228 }
1229
1230 #[test]
1231 fn a_colon_in_a_path_is_not_a_scheme() {
1232 assert!(scheme_of("docs/a:b.md").is_none());
1233 assert!(scheme_of("#a:b").is_none());
1234 assert!(scheme_of("./a.md").is_none());
1235 assert_eq!(scheme_of("HTTPS://example.com").as_deref(), Some("https"));
1236 }
1237
1238 // --- Cross-references -----------------------------------------------------------
1239
1240 #[test]
1241 fn an_issue_reference_in_a_sentence_becomes_a_link() {
1242 let rendered = html_in_repo("Fixed by #12 yesterday.\n");
1243
1244 assert!(
1245 rendered.contains("href=\"/ada/repos/steid/issues/12\">#12</a>"),
1246 "{rendered}"
1247 );
1248 assert!(rendered.contains("Fixed by <a"), "{rendered}");
1249 assert!(rendered.contains("</a> yesterday."), "{rendered}");
1250 }
1251
1252 #[test]
1253 fn an_issue_reference_at_the_start_of_a_line_becomes_a_link() {
1254 assert!(html_in_repo("#12 is the one.\n").contains("issues/12"));
1255 }
1256
1257 #[test]
1258 fn trailing_punctuation_is_not_part_of_a_reference() {
1259 let rendered = html_in_repo("See #12, then #13.\n");
1260
1261 assert!(rendered.contains(">#12</a>,"), "{rendered}");
1262 assert!(rendered.contains(">#13</a>."), "{rendered}");
1263 }
1264
1265 #[test]
1266 fn a_reference_inside_backticks_is_left_alone() {
1267 let rendered = html_in_repo("run `git log #12` and `deadbeef1`\n");
1268
1269 assert!(!rendered.contains("<a"), "{rendered}");
1270 assert!(rendered.contains("git log #12"), "{rendered}");
1271 }
1272
1273 #[test]
1274 fn a_reference_inside_a_fenced_block_is_left_alone() {
1275 let rendered = html_in_repo("```\n# a comment #12 deadbeef1\n```\n");
1276
1277 assert!(!rendered.contains("<a"), "{rendered}");
1278 }
1279
1280 #[test]
1281 fn a_reference_is_not_taken_out_of_a_longer_word() {
1282 for source in [
1283 "issue x#12 here",
1284 "issue #12a here",
1285 "path src/deadbeef1 here",
1286 "tag v1.0-abcdef1 here",
1287 "url https://example.com/x#12 here",
1288 ] {
1289 assert!(!html_in_repo(source).contains("<a"), "{source}");
1290 }
1291 }
1292
1293 #[test]
1294 fn an_object_id_shaped_word_becomes_a_shortened_commit_link() {
1295 let rendered = html_in_repo("Broken since 1a2b3c4d5e6f7 for a while.\n");
1296
1297 assert!(
1298 rendered.contains("href=\"/ada/repos/steid/commits/1a2b3c4d5e6f7\""),
1299 "{rendered}"
1300 );
1301 assert!(rendered.contains(">1a2b3c4</a>"), "{rendered}");
1302 assert!(rendered.contains("font-mono"), "{rendered}");
1303 }
1304
1305 #[test]
1306 fn a_real_english_word_that_is_also_hex_links() {
1307 // `deadbeef` is eight hex characters, so it is an object id by shape and this
1308 // links it. Accepted knowingly: the alternative is a word list, and the words
1309 // that qualify are the ones people write *because* they look like shas.
1310 assert!(html_in_repo("the deadbeef case").contains("commits/deadbeef"));
1311 }
1312
1313 #[test]
1314 fn a_word_that_is_not_object_id_shaped_is_left_alone() {
1315 let too_long = format!("and {} here", "a".repeat(SHA_MAX + 1));
1316
1317 for source in [
1318 "only abcdef here", // six, too short
1319 &too_long, // forty-one
1320 "and DEADBEEF here", // uppercase
1321 "and deadbeefg here", // not hex
1322 ] {
1323 assert!(!html_in_repo(source).contains("<a"), "{source}");
1324 }
1325 }
1326
1327 #[test]
1328 fn a_reference_inside_a_link_stays_text() {
1329 // Nesting one `<a>` inside another is not markup a browser can make sense of.
1330 let rendered = html_in_repo("[see #12](https://example.com/)");
1331
1332 assert_eq!(rendered.matches("<a").count(), 1, "{rendered}");
1333 assert!(rendered.contains(">see #12</a>"), "{rendered}");
1334 }
1335
1336 #[test]
1337 fn without_a_repository_a_reference_is_text() {
1338 let rendered = html("Fixed by #12 in deadbeef1.\n");
1339
1340 assert!(!rendered.contains("<a"), "{rendered}");
1341 }
1342
1343 #[test]
1344 fn issue_zero_is_not_a_reference() {
1345 assert!(!html_in_repo("puzzle #0 solved").contains("<a"));
1346 }
1347
1348 #[test]
1349 fn references_are_found_by_shape_alone() {
1350 assert_eq!(
1351 references("closes #7 with deadbeef1"),
1352 vec![
1353 (7..9, Reference::Issue(IssueNumber::from_trusted(7))),
1354 (15..24, Reference::Commit("deadbeef1")),
1355 ]
1356 );
1357 }
1358
1359 // --- Highlighted fences ---------------------------------------------------------
1360
1361 #[test]
1362 fn a_rust_fence_is_highlighted() {
1363 let rendered = html("```rust\nfn main() {}\n```\n");
1364
1365 assert!(rendered.contains("class=\"hl-"), "{rendered}");
1366 assert!(rendered.contains("hl-storage"), "{rendered}");
1367 assert!(rendered.contains("<pre class="), "{rendered}");
1368 }
1369
1370 #[test]
1371 fn a_fence_with_no_info_string_is_plain() {
1372 let rendered = html("```\nfn main() {}\n```\n");
1373
1374 assert!(!rendered.contains("hl-"), "{rendered}");
1375 assert!(
1376 rendered.contains("<code>fn main() {}\n</code></pre>"),
1377 "{rendered}"
1378 );
1379 }
1380
1381 #[test]
1382 fn an_unknown_language_is_plain_and_still_escaped() {
1383 let rendered = html("```nosuchlang\nlet x = 1 < 2;\n```\n");
1384
1385 assert!(!rendered.contains("hl-"), "{rendered}");
1386 assert!(rendered.contains("let x = 1 &lt; 2;"), "{rendered}");
1387 }
1388
1389 #[test]
1390 fn a_fence_past_the_cap_is_plain() {
1391 let long = "let x = 1;\n".repeat(highlight::MAX_LINES + 1);
1392 let rendered = html(&format!("```rust\n{long}```\n"));
1393
1394 assert!(!rendered.contains("hl-"), "{rendered}");
1395 }
1396
1397 #[test]
1398 fn an_info_string_with_extra_words_still_names_the_language() {
1399 assert!(html("```rust,ignore\nfn main() {}\n```\n").contains("hl-storage"));
1400 }
1401
1402 #[test]
1403 fn empty_input_renders_nothing() {
1404 assert!(html("").is_empty());
1405 assert!(html(" \n\n ").is_empty());
1406 }
1407}