fix(chromium): parse the Markdown page instead of executing it as a template

This commit is contained in:
Julien Neuhart
2026-11-21 19:11:53 +01:00
parent ca4b710673
commit 62003e3a18
6 changed files with 453 additions and 56 deletions

View File

@@ -1,18 +1,17 @@
package chromium
import (
"bytes"
"bufio"
"encoding/json"
"errors"
"fmt"
"html/template"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"text/template/parse"
"time"
"github.com/dlclark/regexp2/v2"
@@ -739,63 +738,121 @@ func screenshotMarkdownRoute(chromium Api) api.Route {
}
}
// markdownPageWant says what the index.html of a Markdown route may hold.
const markdownPageWant = `want text and {{ toHTML "<file>" }} actions`
// markdownPagePart is a piece of the index.html of a Markdown route: either
// text written as is, or a Markdown file rendered to HTML in its place.
type markdownPagePart struct {
text string
markdownPath string
}
// markdownToHtml writes the index.html at inputPath to a new HTML file in the
// request's working directory, with each {{ toHTML "<file>" }} action replaced
// by the sanitized HTML of that Markdown file, and returns the file:// URL of
// the result.
//
// The page is parsed, never executed: it holds text, comments and toHTML
// actions naming one of markdownPaths with a string literal, each file at most
// once. The result is the page's text and each Markdown file rendered once, so
// its size follows the upload's.
func markdownToHtml(ctx *api.Context, inputPath string, markdownPaths []string) (string, error) {
// We have to convert each Markdown file referenced in the HTML
// file to... HTML. Thanks to the "html/template" package, we are
// able to provide the "toHTML" function which the user may call
// directly inside the HTML file.
var markdownFilesNotFoundErr error
tmpl, err := template.
New(filepath.Base(inputPath)).
Funcs(template.FuncMap{
"toHTML": func(filename string) (template.HTML, error) {
var path string
for _, markdownPath := range markdownPaths {
markdownFilename := ctx.OriginalFilename(markdownPath)
if filename == markdownFilename {
path = markdownPath
break
}
}
if path == "" {
markdownFilesNotFoundErr = errors.Join(
markdownFilesNotFoundErr,
fmt.Errorf("'%s'", filename),
)
return "", nil
}
b, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read markdown file '%s': %w", filename, err)
}
unsafe := markdown.ToHTML(b, nil, nil)
sanitized := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
// #nosec
return template.HTML(sanitized), nil
},
}).ParseFiles(inputPath)
parts, err := parseMarkdownPage(ctx, inputPath, markdownPaths)
if err != nil {
return "", fmt.Errorf("parse template file: %w", err)
return "", err
}
var buffer bytes.Buffer
outputPath := ctx.GeneratePath(".html")
err = tmpl.Execute(&buffer, &struct{}{})
err = writeMarkdownPage(ctx, outputPath, parts)
if err != nil {
return "", fmt.Errorf("execute template: %w", err)
return "", fmt.Errorf("write HTML file: %w", err)
}
return fmt.Sprintf("file://%s", outputPath), nil
}
// parseMarkdownPage splits the index.html at inputPath into the parts
// [writeMarkdownPage] writes. It answers 400 for a page holding anything but
// text, comments and {{ toHTML "<file>" }} actions, for a Markdown file named
// twice, and for Markdown files the request lacks.
func parseMarkdownPage(ctx *api.Context, inputPath string, markdownPaths []string) ([]markdownPagePart, error) {
name := ctx.OriginalFilename(inputPath)
b, err := os.ReadFile(inputPath)
if err != nil {
return nil, fmt.Errorf("read '%s': %w", name, err)
}
// Without the builtins, an action calling any function but toHTML fails
// to parse.
tree := parse.New(name)
trees := make(map[string]*parse.Tree)
_, err = tree.Parse(string(b), "{{", "}}", trees, map[string]any{"toHTML": true})
if err != nil {
return nil, invalidMarkdownPage(name, err, strings.TrimPrefix(err.Error(), "template: "))
}
// A define or block action adds a tree, or replaces the page's own when it
// takes its name.
if len(trees) != 1 || trees[name] != tree || tree.Root == nil {
return nil, invalidMarkdownPage(name, errors.New("page defines templates"), "got a define or block action")
}
byFilename := make(map[string]string, len(markdownPaths))
for _, markdownPath := range markdownPaths {
byFilename[ctx.OriginalFilename(markdownPath)] = markdownPath
}
var (
parts []markdownPagePart
seen = make(map[string]bool)
markdownFilesNotFoundErr error
)
for _, node := range tree.Root.Nodes {
switch node := node.(type) {
case *parse.TextNode:
parts = append(parts, markdownPagePart{text: string(node.Text)})
case *parse.CommentNode:
case *parse.ActionNode:
filename, ok := toHTMLArgument(node)
if !ok {
return nil, unsupportedMarkdownPageNode(name, tree, node)
}
if seen[filename] {
location, _ := tree.ErrorContext(node)
return nil, api.WrapError(
fmt.Errorf("markdown file '%s' named twice at %s", filename, location),
api.NewSentinelHttpError(
http.StatusBadRequest,
fmt.Sprintf("Invalid form data: file '%s' is invalid (%s: got toHTML on '%s' a second time, want one toHTML action per Markdown file)", name, location, filename),
),
)
}
seen[filename] = true
markdownPath, ok := byFilename[filename]
if !ok {
markdownFilesNotFoundErr = errors.Join(
markdownFilesNotFoundErr,
fmt.Errorf("'%s'", filename),
)
continue
}
parts = append(parts, markdownPagePart{markdownPath: markdownPath})
default:
return nil, unsupportedMarkdownPageNode(name, tree, node)
}
}
if markdownFilesNotFoundErr != nil {
return "", api.WrapError(
return nil, api.WrapError(
fmt.Errorf("markdown files not found: %w", markdownFilesNotFoundErr),
api.NewSentinelHttpError(
http.StatusBadRequest,
@@ -804,14 +861,119 @@ func markdownToHtml(ctx *api.Context, inputPath string, markdownPaths []string)
)
}
inputPath = ctx.GeneratePath(".html")
return parts, nil
}
err = os.WriteFile(inputPath, buffer.Bytes(), 0o600)
if err != nil {
return "", fmt.Errorf("write template result: %w", err)
// toHTMLArgument returns the filename of an action that is exactly
// {{ toHTML "<file>" }}: one command, no variable, the toHTML function and one
// string literal.
func toHTMLArgument(node *parse.ActionNode) (string, bool) {
pipe := node.Pipe
if pipe == nil || pipe.IsAssign || len(pipe.Decl) != 0 || len(pipe.Cmds) != 1 {
return "", false
}
return fmt.Sprintf("file://%s", inputPath), nil
args := pipe.Cmds[0].Args
if len(args) != 2 {
return "", false
}
identifier, ok := args[0].(*parse.IdentifierNode)
if !ok || identifier.Ident != "toHTML" {
return "", false
}
filename, ok := args[1].(*parse.StringNode)
if !ok {
return "", false
}
return filename.Text, true
}
// unsupportedMarkdownPageNode answers 400 for a node of an index.html other
// than text, a comment or a {{ toHTML "<file>" }} action. The message quotes
// the node's opening action only, as the node may span the page.
func unsupportedMarkdownPageNode(name string, tree *parse.Tree, node parse.Node) error {
location, context := tree.ErrorContext(node)
before, _, found := strings.Cut(context, "}}")
if found {
context = before + "}}"
}
return invalidMarkdownPage(
name,
fmt.Errorf("unsupported node at %s", location),
fmt.Sprintf("%s: got '%s'", location, context),
)
}
// invalidMarkdownPage answers 400 for an index.html holding more than text
// and {{ toHTML "<file>" }} actions.
func invalidMarkdownPage(name string, err error, detail string) error {
return api.WrapError(
fmt.Errorf("parse '%s': %w", name, err),
api.NewSentinelHttpError(
http.StatusBadRequest,
fmt.Sprintf("Invalid form data: file '%s' is invalid (%s, %s)", name, detail, markdownPageWant),
),
)
}
// writeMarkdownPage writes parts to a new file at path, rendering each
// Markdown file with the user-generated content policy of bluemonday. It
// stops between parts once ctx is done.
func writeMarkdownPage(ctx *api.Context, path string, parts []markdownPagePart) (err error) {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return fmt.Errorf("create file: %w", err)
}
defer func() {
errClose := f.Close()
if err == nil && errClose != nil {
err = fmt.Errorf("close file: %w", errClose)
}
}()
w := bufio.NewWriter(f)
policy := bluemonday.UGCPolicy()
for _, part := range parts {
err = ctx.Err()
if err != nil {
return fmt.Errorf("context: %w", err)
}
if part.markdownPath == "" {
_, err = w.WriteString(part.text)
if err != nil {
return fmt.Errorf("write text: %w", err)
}
continue
}
var b []byte
b, err = os.ReadFile(part.markdownPath)
if err != nil {
return fmt.Errorf("read markdown file '%s': %w", ctx.OriginalFilename(part.markdownPath), err)
}
unsafe := markdown.ToHTML(b, nil, nil)
_, err = w.Write(policy.SanitizeBytes(unsafe))
if err != nil {
return fmt.Errorf("write markdown file '%s': %w", ctx.OriginalFilename(part.markdownPath), err)
}
}
err = w.Flush()
if err != nil {
return fmt.Errorf("flush: %w", err)
}
return nil
}
// convertUrl prints url to PDF with Chromium and runs stages on the result.

View File

@@ -7,6 +7,8 @@ import (
"fmt"
"math"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
@@ -484,3 +486,171 @@ func clientMessage(err error) string {
_, message := httpErr.HttpError()
return message
}
// newMarkdownPage writes page as the index.html of a Markdown request, beside
// a.md and b.md, and returns the request context and the paths to pass to
// [markdownToHtml].
func newMarkdownPage(t *testing.T, reqCtx context.Context, page string) (*api.Context, string, []string) {
t.Helper()
dir := t.TempDir()
ctx := &api.Context{Context: reqCtx}
(&api.ContextMock{Context: ctx}).SetDirPath(dir)
write := func(filename, content string) string {
t.Helper()
path := ctx.GeneratePathFromFilename(filename)
err := os.WriteFile(path, []byte(content), 0o600)
if err != nil {
t.Fatalf("write %s: %v", filename, err)
}
return path
}
inputPath := write("index.html", page)
markdownPaths := []string{
write("a.md", "# A\n"),
write("b.md", "*b*\n"),
}
return ctx, inputPath, markdownPaths
}
// TestMarkdownToHtml pins what the index.html of the Markdown routes renders
// to: its text as is, each {{ toHTML "<file>" }} action replaced by the
// sanitized HTML of that Markdown file.
func TestMarkdownToHtml(t *testing.T) {
for _, tc := range []struct {
scenario string
page string
want string
}{
{scenario: "empty page", page: "", want: ""},
{scenario: "plain text", page: "<html><body><p>Hi</p></body></html>", want: "<html><body><p>Hi</p></body></html>"},
{scenario: "single toHTML", page: `<body>{{ toHTML "a.md" }}</body>`, want: "<body><h1>A</h1>\n</body>"},
{scenario: "several toHTML", page: `{{ toHTML "a.md" }}<hr>{{toHTML "b.md"}}`, want: "<h1>A</h1>\n<hr><p><em>b</em></p>\n"},
{scenario: "backtick string literal", page: "{{ toHTML `a.md` }}", want: "<h1>A</h1>\n"},
{scenario: "trim markers", page: "<div>\n {{- toHTML \"a.md\" -}}\n</div>", want: "<div><h1>A</h1>\n</div>"},
{scenario: "template comment", page: "x{{/* note */}}y{{- /* trimmed */ -}} z", want: "xyz"},
{scenario: "HTML comment", page: `<!-- note -->{{ toHTML "b.md" }}`, want: "<!-- note --><p><em>b</em></p>\n"},
} {
t.Run(tc.scenario, func(t *testing.T) {
ctx, inputPath, markdownPaths := newMarkdownPage(t, context.Background(), tc.page)
url, err := markdownToHtml(ctx, inputPath, markdownPaths)
if err != nil {
t.Fatalf("markdownToHtml() error = %v", err)
}
path, ok := strings.CutPrefix(url, "file://")
if !ok || filepath.Dir(path) != ctx.DirPath() {
t.Fatalf("url = %q, want a file:// URL in %s", url, ctx.DirPath())
}
got, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read result: %v", err)
}
if string(got) != tc.want {
t.Errorf("result = %q, want %q", got, tc.want)
}
})
}
}
// TestMarkdownToHtml_Rejects pins that an index.html holding anything but
// text, comments and {{ toHTML "<file>" }} actions, or naming a Markdown file
// twice or one the request lacks, answers 400 without writing a page. The page
// is never executed, so no action can loop, recurse or read data.
func TestMarkdownToHtml_Rejects(t *testing.T) {
for _, tc := range []struct {
scenario string
page string
want string
}{
{scenario: "range over an integer", page: `{{ range 1000000000000000 }}{{ end }}`},
{scenario: "range with toHTML", page: `{{ range 3 }}{{ toHTML "a.md" }}{{ end }}`},
{scenario: "if", page: `{{ if true }}x{{ end }}`},
{scenario: "with", page: `{{ with "a.md" }}{{ toHTML . }}{{ end }}`},
{scenario: "dot", page: `{{ . }}`},
{scenario: "field", page: `{{ .Secret }}`},
{scenario: "variable declaration", page: `{{ $x := toHTML "a.md" }}`},
{scenario: "variable argument", page: `{{ $x := "a.md" }}{{ toHTML $x }}`},
{scenario: "variable assignment", page: `{{ $x := "a.md" }}{{ $x = "b.md" }}`},
{scenario: "pipeline", page: `{{ toHTML "a.md" | toHTML }}`},
{scenario: "parenthesized pipeline", page: `{{ (toHTML "a.md") }}`},
{scenario: "parenthesized argument", page: `{{ toHTML ("a.md") }}`},
{scenario: "no argument", page: `{{ toHTML }}`},
{scenario: "two arguments", page: `{{ toHTML "a.md" "b.md" }}`},
{scenario: "number argument", page: `{{ toHTML 1 }}`},
{scenario: "bare string", page: `{{ "a.md" }}`},
{scenario: "define", page: `{{ define "t" }}x{{ end }}{{ template "t" }}`},
{scenario: "nested define", page: `{{ define "a" }}{{ template "b" }}{{ template "b" }}{{ end }}{{ define "b" }}xx{{ end }}`},
{scenario: "block", page: `{{ block "t" . }}x{{ end }}`},
{scenario: "redefined page", page: `{{ define "index.html" }}{{ template "index.html" }}{{ end }}`},
{scenario: "redefined page holding text", page: `{{ define "index.html" }}x{{ end }}`},
{scenario: "template", page: `{{ template "index.html" }}`},
{scenario: "printf", page: `{{ printf "%s" "a.md" }}`},
{scenario: "len", page: `{{ len "a.md" }}`},
{scenario: "unclosed action", page: `{{ toHTML "a.md"`},
{
scenario: "message",
page: "<p>\n{{ range 3 }}{{ toHTML \"a.md\" }}{{ end }}",
want: `Invalid form data: file 'index.html' is invalid (index.html:2:9: got '{{range 3}}', want text and {{ toHTML "<file>" }} actions)`,
},
{
scenario: "Markdown file named twice",
page: `{{ toHTML "a.md" }}{{ toHTML "b.md" }}{{ toHTML "a.md" }}`,
want: `Invalid form data: file 'index.html' is invalid (index.html:1:41: got toHTML on 'a.md' a second time, want one toHTML action per Markdown file)`,
},
{
scenario: "Markdown files not found",
page: `{{ toHTML "a.md" }}{{ toHTML "c.md" }}{{ toHTML "d.md" }}`,
want: "Markdown file(s) not found: 'c.md'\n'd.md'",
},
} {
t.Run(tc.scenario, func(t *testing.T) {
ctx, inputPath, markdownPaths := newMarkdownPage(t, context.Background(), tc.page)
_, err := markdownToHtml(ctx, inputPath, markdownPaths)
if err == nil {
t.Fatal("markdownToHtml() error = nil, want a 400")
}
status, message := api.ParseError(err)
if status != http.StatusBadRequest {
t.Errorf("status = %d, want %d (error: %v)", status, http.StatusBadRequest, err)
}
if tc.want != "" && message != tc.want {
t.Errorf("message = %q, want %q", message, tc.want)
}
entries, err := os.ReadDir(ctx.DirPath())
if err != nil {
t.Fatalf("read directory: %v", err)
}
if len(entries) != 1+len(markdownPaths) {
t.Errorf("directory holds %d files, want only the %d uploads", len(entries), 1+len(markdownPaths))
}
})
}
}
// TestMarkdownToHtml_Cancelled pins that writing the page stops once the
// request is done.
func TestMarkdownToHtml_Cancelled(t *testing.T) {
reqCtx, cancel := context.WithCancel(context.Background())
cancel()
ctx, inputPath, markdownPaths := newMarkdownPage(t, reqCtx, `{{ toHTML "a.md" }}`)
_, err := markdownToHtml(ctx, inputPath, markdownPaths)
if !errors.Is(err, context.Canceled) {
t.Errorf("markdownToHtml() error = %v, want %v", err, context.Canceled)
}
}

View File

@@ -84,6 +84,29 @@ Feature: /forms/chromium/convert/markdown
Then the response header "Content-Type" should be "application/pdf"
Then there should be 1 PDF(s) in the response
# The page is parsed, never executed: it holds text and one toHTML action per
# Markdown file, so no action can loop or recurse.
Scenario: POST /forms/chromium/convert/markdown (Template Actions)
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/chromium/convert/markdown" endpoint with the following form data and header(s):
| files | testdata/template-actions-markdown/index.html | file |
| files | testdata/page-1-markdown/page_1.md | file |
Then the response status code should be 400
Then the response header "Content-Type" should be "text/plain; charset=UTF-8"
Then the response body should match string:
"""
Invalid form data: file 'index.html' is invalid (index.html:7:13: got '{{range 3}}', want text and {{ toHTML "<file>" }} actions)
"""
When I make a "POST" request to Gotenberg at the "/forms/chromium/convert/markdown" endpoint with the following form data and header(s):
| files | testdata/duplicate-markdown/index.html | file |
| files | testdata/page-1-markdown/page_1.md | file |
Then the response status code should be 400
Then the response header "Content-Type" should be "text/plain; charset=UTF-8"
Then the response body should match string:
"""
Invalid form data: file 'index.html' is invalid (index.html:8:12: got toHTML on 'page_1.md' a second time, want one toHTML action per Markdown file)
"""
Scenario: POST /forms/chromium/convert/markdown (Bad Request)
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/chromium/convert/markdown" endpoint with the following form data and header(s):

View File

@@ -44,6 +44,29 @@ Feature: /forms/chromium/screenshot/markdown
Then the response status code should be 400
Then the response header "Content-Type" should be "text/plain; charset=UTF-8"
# The page is parsed, never executed: it holds text and one toHTML action per
# Markdown file, so no action can loop or recurse.
Scenario: POST /forms/chromium/screenshot/markdown (Template Actions)
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/chromium/screenshot/markdown" endpoint with the following form data and header(s):
| files | testdata/template-actions-markdown/index.html | file |
| files | testdata/page-1-markdown/page_1.md | file |
Then the response status code should be 400
Then the response header "Content-Type" should be "text/plain; charset=UTF-8"
Then the response body should match string:
"""
Invalid form data: file 'index.html' is invalid (index.html:7:13: got '{{range 3}}', want text and {{ toHTML "<file>" }} actions)
"""
When I make a "POST" request to Gotenberg at the "/forms/chromium/screenshot/markdown" endpoint with the following form data and header(s):
| files | testdata/duplicate-markdown/index.html | file |
| files | testdata/page-1-markdown/page_1.md | file |
Then the response status code should be 400
Then the response header "Content-Type" should be "text/plain; charset=UTF-8"
Then the response body should match string:
"""
Invalid form data: file 'index.html' is invalid (index.html:8:12: got toHTML on 'page_1.md' a second time, want one toHTML action per Markdown file)
"""
# A field the route does not read answers 400; screenshots run no stage.
Scenario: POST /forms/chromium/screenshot/markdown (Unknown Form Fields)
Given I have a default Gotenberg container

View File

@@ -0,0 +1,10 @@
<!doctype html>
<html lang="en">
<head>
<title>Page 1</title>
</head>
<body>
<div>{{ toHTML "page_1.md" }}</div>
<div>{{ toHTML "page_1.md" }}</div>
</body>
</html>

View File

@@ -0,0 +1,9 @@
<!doctype html>
<html lang="en">
<head>
<title>Page 1</title>
</head>
<body>
{{ range 3 }}{{ toHTML "page_1.md" }}{{ end }}
</body>
</html>