| 1 | package markdown |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "os" |
| 6 | "path" |
| 7 | "path/filepath" |
| 8 | "runtime" |
| 9 | "sort" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | // resolve is a resolver that takes every relative path under /r/. |
| 16 | func resolve(dest string) (string, bool) { |
| 17 | if strings.HasPrefix(dest, "#") { |
| 18 | return dest, true |
| 19 | } |
| 20 | return "/r/" + strings.TrimPrefix(dest, "/"), true |
| 21 | } |
| 22 | |
| 23 | func render(t *testing.T, src string) string { |
| 24 | t.Helper() |
| 25 | d, err := Render(context.Background(), []byte(src), Options{Resolve: resolve}) |
| 26 | if err != nil { |
| 27 | t.Fatalf("Render(%q): %v", src, err) |
| 28 | } |
| 29 | return string(d.HTML) |
| 30 | } |
| 31 | |
| 32 | // Examples from the CommonMark and GFM specifications, for the constructs |
| 33 | // the renderer supports, with the output in the renderer's own spacing. |
| 34 | func TestConstructs(t *testing.T) { |
| 35 | for _, c := range []struct{ in, want string }{ |
| 36 | {"# foo\n## foo\n###### foo", `<h1 id="foo">foo <a class="anchor" href="#foo">#</a></h1>` + "\n" + |
| 37 | `<h2 id="foo-1">foo <a class="anchor" href="#foo-1">#</a></h2>` + "\n" + |
| 38 | `<h6 id="foo-2">foo <a class="anchor" href="#foo-2">#</a></h6>` + "\n"}, |
| 39 | {"####### foo", "<p>####### foo</p>\n"}, |
| 40 | {"#5 bolt\n\n#hashtag", "<p>#5 bolt</p>\n<p>#hashtag</p>\n"}, |
| 41 | {"## foo ##\n# foo#", `<h2 id="foo">foo <a class="anchor" href="#foo">#</a></h2>` + "\n" + `<h1 id="foo-1">foo# <a class="anchor" href="#foo-1">#</a></h1>` + "\n"}, |
| 42 | {"Foo *bar*\n=========", `<h1 id="foo-bar">Foo <em>bar</em> <a class="anchor" href="#foo-bar">#</a></h1>` + "\n"}, |
| 43 | {"Foo\nbar\n---", `<h2 id="foo-bar">Foo` + "\n" + `bar <a class="anchor" href="#foo-bar">#</a></h2>` + "\n"}, |
| 44 | {"aaa\n\nbbb", "<p>aaa</p>\n<p>bbb</p>\n"}, |
| 45 | {"foo \nbar\\\nbaz", "<p>foo<br>\nbar<br>\nbaz</p>\n"}, |
| 46 | {"*foo bar*", "<p><em>foo bar</em></p>\n"}, |
| 47 | {"a * foo bar*", "<p>a * foo bar*</p>\n"}, |
| 48 | {"foo*bar*", "<p>foo<em>bar</em></p>\n"}, |
| 49 | {"_foo_bar", "<p>_foo_bar</p>\n"}, |
| 50 | {"**foo*bar**", "<p><strong>foo*bar</strong></p>\n"}, |
| 51 | {"*foo**bar**baz*", "<p><em>foo<strong>bar</strong>baz</em></p>\n"}, |
| 52 | {"***strong emph***", "<p><em><strong>strong emph</strong></em></p>\n"}, |
| 53 | {"*foo**bar*", "<p><em>foo**bar</em></p>\n"}, |
| 54 | {"~~Hi~~ Hello, ~there~ world!", "<p><del>Hi</del> Hello, <del>there</del> world!</p>\n"}, |
| 55 | {"This ~~~is no~~~ strikethrough", "<p>This ~~~is no~~~ strikethrough</p>\n"}, |
| 56 | {"`` foo ` bar ``", "<p><code>foo ` bar</code></p>\n"}, |
| 57 | {"`foo\\`bar`", "<p><code>foo\\</code>bar`</p>\n"}, |
| 58 | {"```foo``", "<p>```foo``</p>\n"}, |
| 59 | {"```\n<\n >\n```", "<pre><code><\n >\n</code></pre>\n"}, |
| 60 | {"~~~ruby startline=3\ndef\n~~~~", `<pre><code class="language-ruby">def` + "\n</code></pre>\n"}, |
| 61 | {"```\naaa\n~~~\n```", "<pre><code>aaa\n~~~\n</code></pre>\n"}, |
| 62 | {" a simple\n indented code block", "<pre><code>a simple\n indented code block\n</code></pre>\n"}, |
| 63 | {"> # Foo\n> bar\nbaz", "<blockquote>\n" + `<h1 id="foo">Foo <a class="anchor" href="#foo">#</a></h1>` + "\n<p>bar\nbaz</p>\n</blockquote>\n"}, |
| 64 | {"> > > foo\nbar", "<blockquote>\n<blockquote>\n<blockquote>\n<p>foo\nbar</p>\n</blockquote>\n</blockquote>\n</blockquote>\n"}, |
| 65 | {"- foo\n- bar\n+ baz", "<ul>\n<li>foo</li>\n<li>bar</li>\n</ul>\n<ul>\n<li>baz</li>\n</ul>\n"}, |
| 66 | {"1. foo\n2. bar\n3) baz", "<ol>\n<li>foo</li>\n<li>bar</li>\n</ol>\n<ol start=\"3\">\n<li>baz</li>\n</ol>\n"}, |
| 67 | {"- foo\n\n- bar", "<ul>\n<li>\n<p>foo</p>\n</li>\n<li>\n<p>bar</p>\n</li>\n</ul>\n"}, |
| 68 | {"- foo\n - bar\n - baz", "<ul>\n<li>foo<ul>\n<li>bar<ul>\n<li>baz</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n"}, |
| 69 | {"The number of windows in my house is\n14. The number of doors is 6.", "<p>The number of windows in my house is\n14. The number of doors is 6.</p>\n"}, |
| 70 | {"- [ ] foo\n- [x] bar", "<ul>\n<li>☐ foo</li>\n<li>☑ bar</li>\n</ul>\n"}, |
| 71 | {"| foo | bar |\n| --- | :-: |\n| baz | bim |", "<table>\n<thead>\n<tr><th>foo</th><th class=\"center\">bar</th></tr>\n</thead>\n<tbody>\n<tr><td>baz</td><td class=\"center\">bim</td></tr>\n</tbody>\n</table>\n"}, |
| 72 | {"| f\\|oo |\n| ------ |\n| `b\\|az` |", "<table>\n<thead>\n<tr><th>f|oo</th></tr>\n</thead>\n<tbody>\n<tr><td><code>b|az</code></td></tr>\n</tbody>\n</table>\n"}, |
| 73 | {"***\n---\n___", "<hr>\n<hr>\n<hr>\n"}, |
| 74 | {"[link](/uri \"title\")", `<p><a href="/r/uri" title="title">link</a></p>` + "\n"}, |
| 75 | {"[link](<foo bar>)", `<p><a href="/r/foo bar">link</a></p>` + "\n"}, |
| 76 | {"[foo]: /url \"title\"\n\n[foo] [Foo][] [x][FOO]", `<p><a href="/r/url" title="title">foo</a> <a href="/r/url" title="title">Foo</a> <a href="/r/url" title="title">x</a></p>` + "\n"}, |
| 77 | {"[link [foo [bar]]](/uri)", `<p><a href="/r/uri">link [foo [bar]]</a></p>` + "\n"}, |
| 78 | {"[foo [bar](/uri)](/uri)", `<p>[foo <a href="/r/uri">bar</a>](/uri)</p>` + "\n"}, |
| 79 | {"<https://foo.bar.baz/test?q=hello&id=22&boolean>", `<p><a href="https://foo.bar.baz/test?q=hello&id=22&boolean">https://foo.bar.baz/test?q=hello&id=22&boolean</a></p>` + "\n"}, |
| 80 | {"<foo@bar.example.com>", `<p><a href="mailto:foo@bar.example.com">foo@bar.example.com</a></p>` + "\n"}, |
| 81 | {"Visit https://www.example.org/a_(b)) now.", `<p>Visit <a href="https://www.example.org/a_(b)">https://www.example.org/a_(b)</a>) now.</p>` + "\n"}, |
| 82 | {"", `<p><a href="/r/train.jpg" title="t">foo bar</a></p>` + "\n"}, |
| 83 | {"\\*not emphasized* \\[not a link](/foo)", "<p>*not emphasized* [not a link](/foo)</p>\n"}, |
| 84 | {" © # " � &ThisIsNotDefined; &x;", "<p> © # " � &ThisIsNotDefined; &ampx;</p>\n"}, |
| 85 | {"[a](#frag)", `<p><a href="#frag">a</a></p>` + "\n"}, |
| 86 | {"# !!!\n\n## a", "<h1>!!!</h1>\n" + `<h2 id="a">a <a class="anchor" href="#a">#</a></h2>` + "\n"}, |
| 87 | {"| a |\n| - |\n| b | c |\n|", "<table>\n<thead>\n<tr><th>a</th></tr>\n</thead>\n<tbody>\n<tr><td>b</td></tr>\n<tr><td></td></tr>\n</tbody>\n</table>\n"}, |
| 88 | } { |
| 89 | if got := render(t, c.in); got != c.want { |
| 90 | t.Errorf("Render(%q)\n got: %q\nwant: %q", c.in, got, c.want) |
| 91 | } |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | // Raw HTML, hostile schemes and attribute values arrive as text. |
| 96 | func TestHostileInputIsInert(t *testing.T) { |
| 97 | for _, c := range []struct{ in, want string }{ |
| 98 | {"<script>alert(1)</script>", "<p><script>alert(1)</script></p>\n"}, |
| 99 | {"<div onclick=\"x()\">\n\n*hi*\n\n</div>", "<p><div onclick="x()"></p>\n<p><em>hi</em></p>\n<p></div></p>\n"}, |
| 100 | {"a <img src=x onerror=alert(1)> b", "<p>a <img src=x onerror=alert(1)> b</p>\n"}, |
| 101 | {"<svg><script>x</script></svg>", "<p><svg><script>x</script></svg></p>\n"}, |
| 102 | {"[x](javascript:alert(1))", "<p>x</p>\n"}, |
| 103 | {"[x](JaVaScRiPt:alert(1))", "<p>x</p>\n"}, |
| 104 | {"[x](javascript:alert(1))", "<p>x</p>\n"}, |
| 105 | {"[x](java	script:alert(1))", "<p>x</p>\n"}, |
| 106 | {"[x](data:text/html;base64,PHNjcmlwdD4=)", "<p>x</p>\n"}, |
| 107 | {"[x](vbscript:msgbox)", "<p>x</p>\n"}, |
| 108 | {"<javascript:alert(1)>", "<p>javascript:alert(1)</p>\n"}, |
| 109 | {"", "<p>x</p>\n"}, |
| 110 | {"[x](\\javascript:alert(1))", "<p>x</p>\n"}, |
| 111 | {`[x](http\z/../../target)`, "<p>x</p>\n"}, |
| 112 | {`[x](https:\\evil.org/)`, "<p>x</p>\n"}, |
| 113 | {"[x](http:../../target) [y](HTTPS:x)", "<p>x y</p>\n"}, |
| 114 | {"[x](a\\b/c) [y](1a:b) [z](a b:c)", "<p>x y [z](a b:c)</p>\n"}, |
| 115 | {`[x](http://a.org/b\c) [y](/a\b) [z](#a\b) [w](mailto:a\b@c.org)`, "<p>x y z w</p>\n"}, |
| 116 | {`[x](http://a.org/\\b) [y](a\b) [z](<a\b>)`, "<p>x y z</p>\n"}, |
| 117 | {"[x](https://) [y](http://) [z](https:///a) [w](http://:80/) [v](https://a@/) <https://>", "<p>x y z w v https://</p>\n"}, |
| 118 | {"[x](https://a.org) [y](http://[::1]:80/)", `<p><a href="https://a.org">x</a> <a href="http://[::1]:80/">y</a></p>` + "\n"}, |
| 119 | {"[x](http://alice@[2001:db8::1]:8080/a[b]?c) <https://[::ffff:192.0.2.1]>", `<p><a href="http://alice@[2001:db8::1]:8080/a%5Bb%5D?c">x</a> <a href="https://[::ffff:192.0.2.1]">https://[::ffff:192.0.2.1]</a></p>` + "\n"}, |
| 120 | {"[x](http://[::1) [y](http://[]/) [z](http://[::1]a/) [w](http://[::g]/) [v](http://[a\"b]/) [u](http://[a]/) [t](http://[::1]:x/) [s](http://[::1]:123456/)", "<p>x y z w v u t s</p>\n"}, |
| 121 | {`[x](http://a.org/"onmouseover="alert(1) "a\"><b>")`, `<p><a href="http://a.org/%22onmouseover=%22alert(1)" title="a"><b>">x</a></p>` + "\n"}, |
| 122 | {"[x](<http://a.org/<>)", "<p>[x](<http://a.org/<>)</p>\n"}, |
| 123 | {"```\"><script>alert(1)</script>\nx\n```", `<pre><code class="language-"><script>alert(1)</script>">x` + "\n</code></pre>\n"}, |
| 124 | {"# <b onclick=x>", `<h1 id="b-onclickx"><b onclick=x> <a class="anchor" href="#b-onclickx">#</a></h1>` + "\n"}, |
| 125 | } { |
| 126 | if got := render(t, c.in); got != c.want { |
| 127 | t.Errorf("Render(%q)\n got: %q\nwant: %q", c.in, got, c.want) |
| 128 | } |
| 129 | checkHTML(t, c.in, render(t, c.in)) |
| 130 | } |
| 131 | if d, err := Render(context.Background(), []byte("[a](b.md)"), Options{}); err != nil || string(d.HTML) != "<p>a</p>\n" { |
| 132 | t.Errorf("with no resolver, a relative link renders %q", d.HTML) |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | // GitHub's ids for real headings of docs/. |
| 137 | func TestSlug(t *testing.T) { |
| 138 | for _, c := range []struct{ in, want string }{ |
| 139 | {"web-export (the-valley/web-export/v2)", "web-export-the-valleyweb-exportv2"}, |
| 140 | {"Purpose and principles", "purpose-and-principles"}, |
| 141 | {"`valley plan`", "valley-plan"}, |
| 142 | {"Ownership: who owns what", "ownership-who-owns-what"}, |
| 143 | {"CLI commands", "cli-commands"}, |
| 144 | {"valley-web, the read side", "valley-web-the-read-side"}, |
| 145 | {"snake_case and spaces", "snake_case-and---spaces"}, |
| 146 | {"Ünïcode Wörds 2", "ünïcode-wörds-2"}, |
| 147 | {"?!", ""}, |
| 148 | } { |
| 149 | if got := Slug(c.in); got != c.want { |
| 150 | t.Errorf("Slug(%q) = %q, want %q", c.in, got, c.want) |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | // adversarial is inputs of about size bytes, each built to take a naive |
| 156 | // renderer quadratic time or memory, or to nest without end. |
| 157 | func adversarial(size int) map[string]string { |
| 158 | fill := func(unit string) string { return strings.Repeat(unit, size/len(unit)) } |
| 159 | // table is a table of cols columns, whose header and delimiter row |
| 160 | // are followed by empty rows to fill size. |
| 161 | table := func(cols int) string { |
| 162 | head := strings.Repeat("|", cols+1) + "\n" + strings.Repeat("|-", cols) + "|\n" |
| 163 | return head + strings.Repeat("|\n", max(0, size-len(head))/2) |
| 164 | } |
| 165 | // nest is n openers of a delimiter, then n closers, as many as size |
| 166 | // holds and as MaxInlineNodes parses. |
| 167 | nest := func(d string) string { |
| 168 | n := min(size/(2*len(d)+4), MaxInlineNodes/8) |
| 169 | return strings.Repeat(d+"a ", n) + strings.Repeat(" a"+d, n) |
| 170 | } |
| 171 | // refs is a definition whose destination takes half of size, used |
| 172 | // as often as the other half holds use and as MaxInlineNodes parses. |
| 173 | refs := func(use string) string { |
| 174 | def := "[a]: http://example.org/" + strings.Repeat("x", size/2) + "\n\n" |
| 175 | return def + strings.Repeat(use, min((size-len(def))/len(use), MaxInlineNodes/8)) |
| 176 | } |
| 177 | links := min(size/12, MaxInlineNodes/8) |
| 178 | // heavy is the content that allocates most: a paragraph past |
| 179 | // MaxInlineNodes, then empty headings past MaxBlocks. |
| 180 | heavy := strings.Repeat("*_~", MaxInlineNodes/3+1) + "\n\n" + fill("#\n") |
| 181 | // padded is s, built to stay under MaxInlineNodes, followed by |
| 182 | // heavy to fill size. |
| 183 | padded := func(s string) string { |
| 184 | return s + "\n\n" + heavy[:max(0, size-len(s)-2)] |
| 185 | } |
| 186 | // labels is a run of brackets around a, each ] of which ends a |
| 187 | // candidate label: 500 of them, from 1 byte to 999. |
| 188 | labels := fill(strings.Repeat("[", 500) + "a" + strings.Repeat("]", 500)) |
| 189 | inputs := map[string]string{ |
| 190 | "stars": fill("*a"), |
| 191 | "underscores": fill("_a "), |
| 192 | "mixed": fill("*_~"), |
| 193 | "brackets": fill("["), |
| 194 | "closers": fill("]"), |
| 195 | "links": fill("[]("), |
| 196 | "titles": fill("[](x \"[](x '"), |
| 197 | "parens": strings.Repeat("[](", size/1000) + fill("()")[3*(size/1000):], |
| 198 | "backticks": fill("`a``b```c````"), |
| 199 | "ticks": func() string { |
| 200 | var b strings.Builder |
| 201 | for i := 1; b.Len()+i%1400+2 <= size; i++ { |
| 202 | b.WriteString(strings.Repeat("`", i%1400+1) + "x") |
| 203 | } |
| 204 | return b.String() |
| 205 | }(), |
| 206 | "autolinks": fill("<a"), |
| 207 | "emails": fill("<a@"), |
| 208 | "bare": fill("(http://a"), |
| 209 | "entities": fill("&#"), |
| 210 | "quotes": fill(">"), |
| 211 | "lists": fill("- "), |
| 212 | "nested": fill("- > 1. "), |
| 213 | "definitions": fill("[a]: b\n") + "[a]", |
| 214 | "refs": fill("[a] [b][c] "), |
| 215 | "table": "|a|\n|-|\n" + fill("|")[8:], |
| 216 | "headings": fill("# a\n"), |
| 217 | "lines": fill("a \n"), |
| 218 | "fences": fill("```\n"), |
| 219 | "setext": fill("a\n=\n"), |
| 220 | "paragraphs": fill("a\n\n"), |
| 221 | // A block for every two bytes, and then for every byte. |
| 222 | "empty headings": fill("#\n"), |
| 223 | "items": fill("- - a\n"), |
| 224 | "deep items": fill(strings.Repeat("- ", MaxDepth) + "a\n"), |
| 225 | // A paragraph past MaxInlineNodes, then blocks past MaxBlocks. |
| 226 | "both caps": heavy[:size], |
| 227 | // A header with a column for every ten bytes, and short rows. |
| 228 | "wide table": table(size / 10), |
| 229 | // A table as wide as one may be, with short rows. |
| 230 | "narrow table": table(MaxTableColumns), |
| 231 | // A bare link followed by a ) for each byte. |
| 232 | "trailing parens": "(http://a" + fill(")")[9:], |
| 233 | // A long destination used in one paragraph, and in many. |
| 234 | "expansion": refs("[a] "), |
| 235 | "expansions": refs("[a]\n\n"), |
| 236 | "backslash": fill(`[x](http\z/../../target) `), |
| 237 | "hosts": fill(`[x](https://) `), |
| 238 | "emphasis": nest("*"), |
| 239 | "strong": nest("**"), |
| 240 | "strike": nest("~~"), |
| 241 | "links in emphasis": strings.Repeat("*a [", links) + strings.Repeat("](b) a*", links), |
| 242 | // Candidate labels with no definition, and with one. |
| 243 | "labels": labels, |
| 244 | "labels, defined": "[x]: y\n\n" + labels[:len(labels)-9], |
| 245 | } |
| 246 | // Those that stay under MaxInlineNodes, padded to full size. |
| 247 | for _, name := range []string{"emphasis", "strong", "strike", "links in emphasis", "expansion", "expansions"} { |
| 248 | inputs[name+" padded"] = padded(inputs[name]) |
| 249 | } |
| 250 | return inputs |
| 251 | } |
| 252 | |
| 253 | func TestBounds(t *testing.T) { |
| 254 | ctx := context.Background() |
| 255 | if _, err := Render(ctx, make([]byte, MaxInput+1), Options{}); err != ErrTooLong { |
| 256 | t.Errorf("an input past MaxInput gave %v", err) |
| 257 | } |
| 258 | deep := strings.Repeat("> ", 100) + "x" |
| 259 | got := render(t, deep) |
| 260 | if n := strings.Count(got, "<blockquote>"); n != MaxDepth { |
| 261 | t.Errorf("100 quotes nested %d deep", n) |
| 262 | } |
| 263 | // Adversarial inputs of MaxInput bytes each render in time |
| 264 | // near-linear in their size, within the output bound the server |
| 265 | // gives, and as whole HTML however they are cut. |
| 266 | const maxOutput = 2 << 20 |
| 267 | out := map[string]Doc{} |
| 268 | for name, src := range adversarial(MaxInput) { |
| 269 | start := time.Now() |
| 270 | d, err := Render(ctx, []byte(src), Options{Resolve: resolve, MaxOutput: maxOutput}) |
| 271 | if err != nil { |
| 272 | t.Errorf("%s: %v", name, err) |
| 273 | } |
| 274 | if took := time.Since(start); took > 3*time.Second { |
| 275 | t.Errorf("%s took %v", name, took) |
| 276 | } |
| 277 | if len(d.HTML) > maxOutput { |
| 278 | t.Errorf("%s rendered %d bytes, past MaxOutput", name, len(d.HTML)) |
| 279 | } |
| 280 | checkHTML(t, name, string(d.HTML)) |
| 281 | out[name] = d |
| 282 | } |
| 283 | html := func(name string) string { return string(out[name].HTML) } |
| 284 | if strings.Contains(html("wide table"), "<table") { |
| 285 | t.Errorf("a header of %d columns made a table", MaxInput/10) |
| 286 | } |
| 287 | cells := strings.Count(html("narrow table"), "<td") + strings.Count(html("narrow table"), "<th") |
| 288 | if cells > MaxTableCells || cells <= MaxTableCells-MaxTableColumns { |
| 289 | t.Errorf("the tables hold %d cells, want at most %d", cells, MaxTableCells) |
| 290 | } |
| 291 | if n := strings.Count(html("trailing parens"), `<a href="http://a">`); n != 1 { |
| 292 | t.Errorf("a bare link before a run of ) rendered %d links", n) |
| 293 | } |
| 294 | for _, name := range []string{"expansion", "expansions"} { |
| 295 | if !out[name].Truncated { |
| 296 | t.Errorf("%s: a destination of %d bytes used over and over fit in %d bytes", name, MaxInput/2, maxOutput) |
| 297 | } |
| 298 | } |
| 299 | for _, name := range []string{"backslash", "hosts"} { |
| 300 | if strings.Contains(html(name), "<a") { |
| 301 | t.Errorf("%s: a destination with a backslash, or with no host, is a link", name) |
| 302 | } |
| 303 | } |
| 304 | for name, tag := range map[string]string{"emphasis": "<em>", "strong": "<strong>", "strike": "<del>", "links in emphasis": "<em>"} { |
| 305 | for _, name := range []string{name, name + " padded"} { |
| 306 | if n := strings.Count(html(name), tag); n != MaxDepth { |
| 307 | t.Errorf("%s nested %d deep, want %d", name, n, MaxDepth) |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | // The caps on brackets, inline nodes and blocks each turn what passes |
| 314 | // them into text. |
| 315 | func TestCaps(t *testing.T) { |
| 316 | ctx := context.Background() |
| 317 | opt := Options{Resolve: resolve} |
| 318 | // Each element nests MaxDepth deep, and a link, an image or an |
| 319 | // autolink within them all is its text. |
| 320 | for _, link := range []string{"[x](b)", "", "<http://a.org>", "http://a.org"} { |
| 321 | src := strings.Repeat("*a ", MaxDepth+8) + link + strings.Repeat(" a*", MaxDepth+8) |
| 322 | got := render(t, src) |
| 323 | if n := strings.Count(got, "<em>"); n != MaxDepth { |
| 324 | t.Errorf("%s nested in emphasis: %d deep, want %d", link, n, MaxDepth) |
| 325 | } |
| 326 | if strings.Contains(got, "<a") { |
| 327 | t.Errorf("%s past MaxDepth is a link: %q", link, got) |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | // The [ past maxBrackets open is text, and the last one open closes. |
| 332 | src := strings.Repeat("[", maxBrackets+10) + "a](b)" |
| 333 | d, u, err := renderDoc(ctx, []byte(src), opt) |
| 334 | if err != nil { |
| 335 | t.Fatal(err) |
| 336 | } |
| 337 | want := "<p>" + strings.Repeat("[", maxBrackets-1) + `<a href="/r/b">` + strings.Repeat("[", 10) + "a</a></p>\n" |
| 338 | if string(d.HTML) != want || u.brackets != maxBrackets { |
| 339 | t.Errorf("%d brackets open at most, and gave %.80q…", u.brackets, d.HTML) |
| 340 | } |
| 341 | |
| 342 | // The block that passes MaxInlineNodes, and each block after it, is |
| 343 | // its text. |
| 344 | src = "*a*\n\n" + strings.Repeat("[", MaxInlineNodes) + "\n\n*b* [c](d)\n\n# *e*" |
| 345 | d, u, err = renderDoc(ctx, []byte(src), opt) |
| 346 | if err != nil { |
| 347 | t.Fatal(err) |
| 348 | } |
| 349 | got := string(d.HTML) |
| 350 | if u.nodes <= MaxInlineNodes || !strings.HasPrefix(got, "<p><em>a</em></p>\n<p>[[[") || |
| 351 | !strings.HasSuffix(got, "[[[</p>\n<p>*b* [c](d)</p>\n"+`<h1 id="e">*e* <a class="anchor" href="#e">#</a></h1>`+"\n") { |
| 352 | t.Errorf("past %d inline nodes, gave %.40q…%q", u.nodes, got, got[max(0, len(got)-120):]) |
| 353 | } |
| 354 | |
| 355 | // The line that would pass MaxBlocks, less the one block kept for |
| 356 | // it, is with the input after it one block of preformatted text. It |
| 357 | // takes back the containers it opened, and a table's header stays |
| 358 | // in its paragraph. |
| 359 | heads := func(n int) string { return strings.Repeat("#\n", n) } |
| 360 | for _, c := range []struct { |
| 361 | src, end string |
| 362 | blocks int |
| 363 | }{ |
| 364 | {heads(MaxBlocks-1) + "# a\n<b>\n\n", "</h1>\n<pre><code># a\n<b>\n</code></pre>\n", MaxBlocks}, |
| 365 | {heads(MaxBlocks-3) + "> - > a\nb", "</h1>\n<pre><code>> - > a\nb\n</code></pre>\n", MaxBlocks - 2}, |
| 366 | {heads(MaxBlocks-2) + "| a |\n| - |\n| b |", "</h1>\n<p>| a |</p>\n<pre><code>| - |\n| b |\n</code></pre>\n", MaxBlocks}, |
| 367 | } { |
| 368 | d, u, err = renderDoc(ctx, []byte(c.src), opt) |
| 369 | if err != nil { |
| 370 | t.Fatal(err) |
| 371 | } |
| 372 | got = string(d.HTML) |
| 373 | if u.blocks != c.blocks || strings.Contains(got, "<blockquote>") || !strings.HasSuffix(got, c.end) { |
| 374 | t.Errorf("%d blocks, want %d, ending %q", u.blocks, c.blocks, got[max(0, len(got)-80):]) |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | // A label holds at most 999 characters, however many bytes they take. |
| 379 | for _, c := range []struct { |
| 380 | chars int |
| 381 | link bool |
| 382 | }{{maxLabel, true}, {maxLabel + 1, false}} { |
| 383 | src = "[" + strings.Repeat("é", c.chars) + "]: /x\n\n[" + strings.Repeat("É", c.chars) + "]" |
| 384 | if got := render(t, src); strings.Contains(got, "<a") != c.link { |
| 385 | t.Errorf("a label of %d characters gave %.40q", c.chars, got) |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | // Past maxLabelBytes of labels looked up, a reference is text. With |
| 390 | // no definition, none is looked up. |
| 391 | unit := strings.Repeat("[", 500) + "b" + strings.Repeat("]", 500) |
| 392 | for _, def := range []string{"", "[a]: /x\n\n"} { |
| 393 | src = def + "[a] " + strings.Repeat(unit, 40) + " [a]" |
| 394 | d, u, err = renderDoc(ctx, []byte(src), opt) |
| 395 | if err != nil { |
| 396 | t.Fatal(err) |
| 397 | } |
| 398 | got = string(d.HTML) |
| 399 | first, labels := "[a] [[[", 0 |
| 400 | if def != "" { |
| 401 | first, labels = `<a href="/r/x">a</a> [[[`, maxLabelBytes |
| 402 | } |
| 403 | if u.labels != labels || !strings.HasPrefix(got, "<p>"+first) || !strings.HasSuffix(got, "]]] [a]</p>\n") { |
| 404 | t.Errorf("%q: %d bytes of labels looked up, giving %.40q…%q", def, u.labels, got, got[max(0, len(got)-20):]) |
| 405 | } |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | // maxAlloc bounds what one render of a MaxInput document allocates. |
| 410 | const maxAlloc = 128 << 20 |
| 411 | |
| 412 | // Every adversarial input renders within maxAlloc: the bytes it allocates |
| 413 | // in all, and so the most its heap grows at once, which is measured too. |
| 414 | // Each is MaxInput bytes, or has a version padded to MaxInput, and holds |
| 415 | // at most MaxBlocks blocks. |
| 416 | func TestAllocation(t *testing.T) { |
| 417 | inputs := adversarial(MaxInput) |
| 418 | names := make([]string, 0, len(inputs)) |
| 419 | for name := range inputs { |
| 420 | names = append(names, name) |
| 421 | } |
| 422 | sort.Strings(names) |
| 423 | var worst string |
| 424 | var most uint64 |
| 425 | for _, name := range names { |
| 426 | src := []byte(inputs[name]) |
| 427 | if _, full := inputs[name+" padded"]; len(src) < MaxInput-MaxInput/100 && !full { |
| 428 | t.Errorf("%s is %d bytes, short of MaxInput, with no padded version", name, len(src)) |
| 429 | } |
| 430 | var u usage |
| 431 | total, peak := allocation(func() { |
| 432 | var err error |
| 433 | if _, u, err = renderDoc(context.Background(), src, Options{Resolve: resolve, MaxOutput: 2 << 20}); err != nil { |
| 434 | t.Fatal(err) |
| 435 | } |
| 436 | }) |
| 437 | t.Logf("%-24s %4d KiB: allocated %5.1f MiB, heap peak %5.1f MiB", name, len(src)>>10, mib(total), mib(peak)) |
| 438 | if u.blocks > MaxBlocks { |
| 439 | t.Errorf("%s holds %d blocks, past MaxBlocks", name, u.blocks) |
| 440 | } |
| 441 | if total > maxAlloc || peak > maxAlloc { |
| 442 | t.Errorf("%s allocated %.1f MiB, with a heap peak of %.1f MiB, past %d MiB", name, mib(total), mib(peak), maxAlloc>>20) |
| 443 | } |
| 444 | if total > most { |
| 445 | worst, most = name, total |
| 446 | } |
| 447 | } |
| 448 | t.Logf("the most allocated is %.1f MiB, by %s", mib(most), worst) |
| 449 | } |
| 450 | |
| 451 | func mib(n uint64) float64 { return float64(n) / (1 << 20) } |
| 452 | |
| 453 | // allocation runs f, and gives the bytes it allocated and the most the |
| 454 | // heap grew while it ran, sampled each millisecond. |
| 455 | func allocation(f func()) (total, peak uint64) { |
| 456 | runtime.GC() |
| 457 | var before, after runtime.MemStats |
| 458 | runtime.ReadMemStats(&before) |
| 459 | stop, sampled := make(chan struct{}), make(chan uint64) |
| 460 | go func() { |
| 461 | var m runtime.MemStats |
| 462 | var high uint64 |
| 463 | tick := time.NewTicker(time.Millisecond) |
| 464 | defer tick.Stop() |
| 465 | for { |
| 466 | runtime.ReadMemStats(&m) |
| 467 | high = max(high, m.HeapAlloc) |
| 468 | select { |
| 469 | case <-stop: |
| 470 | sampled <- high |
| 471 | return |
| 472 | case <-tick.C: |
| 473 | } |
| 474 | } |
| 475 | }() |
| 476 | f() |
| 477 | runtime.ReadMemStats(&after) |
| 478 | close(stop) |
| 479 | high := max(<-sampled, after.HeapAlloc) |
| 480 | return after.TotalAlloc - before.TotalAlloc, high - min(high, before.HeapAlloc) |
| 481 | } |
| 482 | |
| 483 | // A document past MaxOutput is cut after its last whole block, with the |
| 484 | // blocks that hold it closed. |
| 485 | func TestTruncation(t *testing.T) { |
| 486 | src := "# Title\n\n> - one\n>\n> two\n> - " + strings.Repeat("three ", 100) + "\n\nafter" |
| 487 | for max := 1; max < 1000; max++ { |
| 488 | d, err := Render(context.Background(), []byte(src), Options{MaxOutput: max}) |
| 489 | if err != nil { |
| 490 | t.Fatal(err) |
| 491 | } |
| 492 | got := string(d.HTML) |
| 493 | if len(got) > max { |
| 494 | t.Fatalf("MaxOutput %d: %d bytes", max, len(got)) |
| 495 | } |
| 496 | checkHTML(t, src, got) |
| 497 | if d.Truncated != !strings.Contains(got, "after") { |
| 498 | t.Fatalf("MaxOutput %d: Truncated is %v for %q", max, d.Truncated, got) |
| 499 | } |
| 500 | if (len(d.Headings) == 1) != strings.Contains(got, "<h1") { |
| 501 | t.Fatalf("MaxOutput %d: %d headings for %q", max, len(d.Headings), got) |
| 502 | } |
| 503 | } |
| 504 | d, _ := Render(context.Background(), []byte(src), Options{MaxOutput: 200}) |
| 505 | if want := "<blockquote>\n<ul>\n<li>\n<p>one</p>\n<p>two</p>\n</li>\n</ul>\n</blockquote>\n"; !strings.HasSuffix(string(d.HTML), want) { |
| 506 | t.Errorf("a cut inside a list in a quote gave %q", d.HTML) |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | // Rendering stops once its context is done. |
| 511 | func TestContext(t *testing.T) { |
| 512 | ctx, cancel := context.WithCancel(context.Background()) |
| 513 | cancel() |
| 514 | for name, src := range adversarial(MaxInput) { |
| 515 | if _, err := Render(ctx, []byte(src), Options{Resolve: resolve}); err != context.Canceled { |
| 516 | t.Errorf("%s: with its context done, Render gave %v", name, err) |
| 517 | } |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | // The renderer's output holds only its own elements and attributes, every |
| 522 | // href is allowed or resolved, and nothing active appears. |
| 523 | func FuzzRender(f *testing.F) { |
| 524 | for _, seed := range []string{ |
| 525 | "# h\n\n*a* **b** ~~c~~ `d` [e](f \"g\") <http://h.org> \n", |
| 526 | "<script>alert(1)</script>", "[x](javascript:alert(1))", "[x](javascript:1)", |
| 527 | "```\"><svg onload=x>\ny\n```", "> - [ ] a\n> b\n\n| a | b |\n|:-|-:|\n| <c> | d |\n", |
| 528 | "[a]: <b\"c> 'd\"e'\n[a]", "<a href=\"x\" style=\"y\">", "http://a.org/<b>?\"'", "<script>", |
| 529 | "*a _b *c_ d* e_", "1. a\n\n b\n2) c", " code\n\tmore", "[](c)", "<foo@bar.org>", |
| 530 | `[x](http\z/../../target)`, `[x](https:\\evil.org/)`, "[x](http:../../target)", "# !!!", |
| 531 | `[x](http://a.org/b\c)`, `[x](a\b)`, "[x](https://)", "<https://>", "[x](https://a@:1/)", |
| 532 | } { |
| 533 | f.Add(seed) |
| 534 | } |
| 535 | // Each adversarial input, small. |
| 536 | for _, seed := range adversarial(2048) { |
| 537 | f.Add(seed) |
| 538 | } |
| 539 | f.Fuzz(func(t *testing.T, src string) { |
| 540 | d, err := Render(context.Background(), []byte(src), Options{Resolve: resolve}) |
| 541 | if err != nil { |
| 542 | t.Fatal(err) |
| 543 | } |
| 544 | checkHTML(t, src, string(d.HTML)) |
| 545 | }) |
| 546 | } |
| 547 | |
| 548 | // allowed is every element the renderer writes, with its attributes. |
| 549 | var allowed = map[string]map[string]bool{ |
| 550 | "h1": {"id": true}, "h2": {"id": true}, "h3": {"id": true}, "h4": {"id": true}, "h5": {"id": true}, "h6": {"id": true}, |
| 551 | "p": {}, "br": {}, "em": {}, "strong": {}, "del": {}, "code": {"class": true}, "pre": {}, "blockquote": {}, |
| 552 | "ul": {}, "ol": {"start": true}, "li": {}, "hr": {}, "table": {}, "thead": {}, "tbody": {}, "tr": {}, |
| 553 | "th": {"class": true}, "td": {"class": true}, "a": {"href": true, "title": true, "class": true}, |
| 554 | } |
| 555 | |
| 556 | var void = map[string]bool{"br": true, "hr": true} |
| 557 | |
| 558 | // checkHTML tokenizes out and fails unless it is well formed, with only |
| 559 | // allowed elements and attributes, quoted values that hold no raw <, > |
| 560 | // or quote, and hrefs that are http, https, mailto or resolved. |
| 561 | func checkHTML(t *testing.T, src, out string) { |
| 562 | t.Helper() |
| 563 | fail := func(why string) { t.Helper(); t.Fatalf("Render(%q) = %q: %s", src, out, why) } |
| 564 | low := strings.ToLower(out) |
| 565 | for _, active := range []string{"<script", "<img", "<svg", "<iframe", "<input", "<form"} { |
| 566 | if strings.Contains(low, active) { |
| 567 | fail("holds " + active) |
| 568 | } |
| 569 | } |
| 570 | var open []string |
| 571 | for i := 0; i < len(out); { |
| 572 | switch out[i] { |
| 573 | case '>', '"': |
| 574 | fail("a raw > or quote in text") |
| 575 | case '&': |
| 576 | j := strings.IndexByte(out[i:], ';') |
| 577 | if j < 2 || j > 8 { |
| 578 | fail("a bare &") |
| 579 | } |
| 580 | i += j + 1 |
| 581 | continue |
| 582 | case '<': |
| 583 | default: |
| 584 | i++ |
| 585 | continue |
| 586 | } |
| 587 | end := strings.IndexByte(out[i:], '>') |
| 588 | if end < 0 { |
| 589 | fail("an unclosed tag") |
| 590 | } |
| 591 | tag := out[i+1 : i+end] |
| 592 | i += end + 1 |
| 593 | if strings.HasPrefix(tag, "/") { |
| 594 | if len(open) == 0 || open[len(open)-1] != tag[1:] { |
| 595 | fail("a mismatched </" + tag[1:] + ">") |
| 596 | } |
| 597 | open = open[:len(open)-1] |
| 598 | continue |
| 599 | } |
| 600 | if strings.Contains(tag, "style=") || strings.Contains(tag, " on") { |
| 601 | fail("a tag with a style or an event handler") |
| 602 | } |
| 603 | name, attrs, _ := strings.Cut(tag, " ") |
| 604 | allow, ok := allowed[name] |
| 605 | if !ok { |
| 606 | fail("an element " + name) |
| 607 | } |
| 608 | for attrs != "" { |
| 609 | key, rest, ok := strings.Cut(attrs, `="`) |
| 610 | value, more, ok2 := strings.Cut(rest, `"`) |
| 611 | if !ok || !ok2 || !allow[key] || strings.ContainsAny(value, "<>'") { |
| 612 | fail("an attribute " + attrs) |
| 613 | } |
| 614 | scheme, _, _ := strings.Cut(strings.ToLower(value), ":") |
| 615 | if key == "href" && !(scheme == "http" || scheme == "https" || scheme == "mailto" || strings.HasPrefix(value, "/r/") || strings.HasPrefix(value, "#")) { |
| 616 | fail("an href " + value) |
| 617 | } |
| 618 | attrs = strings.TrimPrefix(more, " ") |
| 619 | } |
| 620 | if name == "a" { |
| 621 | for _, o := range open { |
| 622 | if o == "a" { |
| 623 | fail("a link inside a link") |
| 624 | } |
| 625 | } |
| 626 | } |
| 627 | if !void[name] { |
| 628 | open = append(open, name) |
| 629 | } |
| 630 | } |
| 631 | if len(open) > 0 { |
| 632 | fail("unclosed " + strings.Join(open, ", ")) |
| 633 | } |
| 634 | } |
| 635 | |
| 636 | // The repository's own documents render with every relative link naming |
| 637 | // a file of the tree, and every fragment a heading of its target. The |
| 638 | // targets that are not documents are checked where the whole tree is |
| 639 | // present: in a checkout, and in the prose-format check. |
| 640 | func TestRepositoryDocs(t *testing.T) { |
| 641 | root := filepath.Join("..", "..") |
| 642 | docs, _ := filepath.Glob(filepath.Join(root, "docs", "*.md")) |
| 643 | docs = append(docs, filepath.Join(root, "README.md")) |
| 644 | _, err := os.Stat(filepath.Join(root, "flake.nix")) |
| 645 | whole := err == nil |
| 646 | ids := map[string]map[string]bool{} |
| 647 | type ref struct{ from, target, frag string } |
| 648 | var refs []ref |
| 649 | for _, doc := range docs { |
| 650 | rel, _ := filepath.Rel(root, doc) |
| 651 | rel = filepath.ToSlash(rel) |
| 652 | src, err := os.ReadFile(doc) |
| 653 | if err != nil { |
| 654 | t.Fatal(err) |
| 655 | } |
| 656 | d, u, err := renderDoc(context.Background(), src, Options{MaxOutput: 2 << 20, Resolve: func(dest string) (string, bool) { |
| 657 | p, frag, _ := strings.Cut(dest, "#") |
| 658 | target := rel |
| 659 | if p != "" { |
| 660 | target = path.Join(path.Dir(rel), p) |
| 661 | } |
| 662 | refs = append(refs, ref{rel, target, frag}) |
| 663 | return "/r/" + target, true |
| 664 | }}) |
| 665 | if err != nil { |
| 666 | t.Fatal(err) |
| 667 | } |
| 668 | // Each renders whole, far from every cap. |
| 669 | t.Logf("%s: %d KiB, %d blocks, %d inline nodes, %d brackets open at most, %d bytes of labels", rel, len(src)>>10, u.blocks, u.nodes, u.brackets, u.labels) |
| 670 | if d.Truncated || u.blocks > MaxBlocks/4 || u.nodes > MaxInlineNodes/4 || u.brackets > maxBrackets/4 || u.labels > maxLabelBytes/4 { |
| 671 | t.Errorf("%s: truncated %v, with %d blocks, %d inline nodes, %d brackets open and %d bytes of labels; a cap is too near", rel, d.Truncated, u.blocks, u.nodes, u.brackets, u.labels) |
| 672 | } |
| 673 | ids[rel] = map[string]bool{} |
| 674 | for _, h := range d.Headings { |
| 675 | ids[rel][h.ID] = true |
| 676 | } |
| 677 | } |
| 678 | for _, doc := range []string{"docs/reference.md", "docs/architecture.md"} { |
| 679 | if ids[doc] == nil { |
| 680 | t.Errorf("%s was not rendered", doc) |
| 681 | } |
| 682 | } |
| 683 | if len(ids) < 5 || len(refs) < 100 { |
| 684 | t.Fatalf("read %d documents with %d links; the tree's docs are not where the test looks", len(ids), len(refs)) |
| 685 | } |
| 686 | for _, r := range refs { |
| 687 | headings, isDoc := ids[r.target] |
| 688 | switch { |
| 689 | case isDoc && r.frag != "" && !headings[r.frag]: |
| 690 | t.Errorf("%s links %s#%s, which names no heading", r.from, r.target, r.frag) |
| 691 | case !isDoc && strings.HasPrefix(r.target, "../"): |
| 692 | t.Errorf("%s links %s, above the tree", r.from, r.target) |
| 693 | case !isDoc && whole: |
| 694 | if _, err := os.Stat(filepath.Join(root, filepath.FromSlash(r.target))); err != nil { |
| 695 | t.Errorf("%s links %s, which does not exist", r.from, r.target) |
| 696 | } |
| 697 | } |
| 698 | } |
| 699 | } |