fix(api): give every filename that leaves Gotenberg a portable form

This commit is contained in:
Julien Neuhart
2026-11-22 10:18:54 +01:00
parent 61ec7e14c0
commit a0ce256c56
6 changed files with 300 additions and 37 deletions

View File

@@ -21,6 +21,7 @@ import (
"sync"
"sync/atomic"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
@@ -929,13 +930,7 @@ func (ctx *Context) BuildOutputFile() (string, error) {
return ctx.outputPaths[0], nil
}
filesInfo, err := archives.FilesFromDisk(ctx.Context, nil, func() map[string]string {
f := make(map[string]string)
for _, outputPath := range ctx.outputPaths {
f[outputPath] = ctx.OriginalFilename(outputPath)
}
return f
}())
filesInfo, err := archives.FilesFromDisk(ctx.Context, nil, ctx.archiveEntryNames())
if err != nil {
return "", fmt.Errorf("create files info: %w", err)
}
@@ -975,11 +970,13 @@ func (ctx *Context) OutputFilename(outputPath string) string {
}
// ContentDisposition returns the Content-Disposition header value of an
// attachment named filename. A name with non-ASCII characters also travels in
// the "filename*" parameter, percent-encoded in UTF-8, beside an ASCII
// "filename" fallback for the clients that read only that one. See RFC 6266,
// section 4.3, and RFC 8187, section 3.2.
// attachment named filename, through [PortableFilename]. A name with non-ASCII
// characters also travels in the "filename*" parameter, percent-encoded in
// UTF-8, beside an ASCII "filename" fallback for the clients that read only
// that one. See RFC 6266, section 4.3, and RFC 8187, section 3.2.
func ContentDisposition(filename string) string {
filename = PortableFilename(filename)
var fallback strings.Builder
ascii := true
for _, r := range filename {
@@ -1082,9 +1079,9 @@ func (ctx *Context) trackFileOrder(path, base string) {
// SanitizeFilename strips path separators (including backslashes, which
// [filepath.Base] ignores on Linux) and control characters from a
// caller-supplied filename, then NFC-normalizes the result. This prevents a
// Windows-side Zip Slip when an output zip is extracted by a permissive
// extractor that interprets '\' as a path separator.
// caller-supplied filename, then NFC-normalizes the result. Gotenberg keys
// uploads by that name, so stages and HTML assets can still refer to them. A
// name that leaves Gotenberg goes through [PortableFilename] as well.
func SanitizeFilename(name string) string {
if i := strings.LastIndexAny(name, `/\`); i >= 0 {
name = name[i+1:]
@@ -1097,3 +1094,95 @@ func SanitizeFilename(name string) string {
}, name)
return norm.NFC.String(name)
}
// portableASCII lists the ASCII punctuation every common file system and
// extractor takes as part of a file name.
const portableASCII = " !#$%&'()+,-.;=@[]^_`{}~"
// PortableFilename returns name as a file name that every common operating
// system and extractor takes as one file in the folder it extracts to. It
// keeps the last path segment of name, then builds the result from an allow
// list rather than filtering a deny list: letters, marks and digits in any
// script, and the ASCII punctuation of [portableASCII]. Every other character
// becomes '_': separators and ':', which Windows reads as a drive or an
// alternate data stream, the characters Windows refuses, control and format
// characters, such as a right-to-left override, and the punctuation and
// symbols Windows best-fit conversions map to a separator, such as '/' or '¥'.
// It then trims leading spaces and trailing dots and spaces, which Windows
// drops, and prefixes '_' to a Windows device name, such as "CON.pdf". An
// empty result becomes "file".
func PortableFilename(name string) string {
var b strings.Builder
for _, r := range SanitizeFilename(name) {
switch {
case unicode.IsLetter(r), unicode.IsMark(r), unicode.IsDigit(r):
b.WriteRune(r)
case r < utf8.RuneSelf && strings.ContainsRune(portableASCII, r):
b.WriteRune(r)
default:
b.WriteByte('_')
}
}
portable := strings.TrimRight(strings.TrimLeft(b.String(), " "), ". ")
if portable == "" {
return "file"
}
if isWindowsDeviceName(portable) {
return "_" + portable
}
return portable
}
// isWindowsDeviceName reports whether Windows opens a device instead of a file
// named name: the part before the first dot, trailing spaces aside, is CON,
// PRN, AUX, NUL, COM0 to COM9, LPT0 to LPT9, CONIN$ or CONOUT$, in any case.
// The superscript digits Windows also accepts after COM and LPT never reach
// here, as [PortableFilename] replaces them.
func isWindowsDeviceName(name string) bool {
stem, _, _ := strings.Cut(name, ".")
stem = strings.ToUpper(strings.TrimRight(stem, " "))
switch stem {
case "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$":
return true
}
return len(stem) == 4 && (strings.HasPrefix(stem, "COM") || strings.HasPrefix(stem, "LPT")) && stem[3] >= '0' && stem[3] <= '9'
}
// archiveEntryNames returns the name each output path takes in the archive:
// its original filename through [PortableFilename], numbered when an earlier
// entry already took the same name, whatever its case, as Windows and macOS
// compare names: "doc.pdf", then "Doc (2).pdf".
func (ctx *Context) archiveEntryNames() map[string]string {
names := make(map[string]string, len(ctx.outputPaths))
taken := make(map[string]bool, len(ctx.outputPaths))
nextSuffix := make(map[string]int)
for _, outputPath := range ctx.outputPaths {
name := PortableFilename(ctx.OriginalFilename(outputPath))
key := strings.ToLower(name)
if taken[key] {
ext := filepath.Ext(name)
stem := strings.TrimSuffix(name, ext)
for i := max(nextSuffix[key], 2); ; i++ {
candidate := fmt.Sprintf("%s (%d)%s", stem, i, ext)
if !taken[strings.ToLower(candidate)] {
nextSuffix[key] = i + 1
name = candidate
break
}
}
}
taken[strings.ToLower(name)] = true
names[outputPath] = name
}
return names
}

View File

@@ -1,6 +1,7 @@
package api
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
@@ -23,6 +24,8 @@ import (
"sync/atomic"
"testing"
"time"
"unicode"
"unicode/utf8"
"github.com/dlclark/regexp2/v2"
"github.com/labstack/echo/v5"
@@ -1428,14 +1431,18 @@ func TestContentDisposition(t *testing.T) {
name string
filename string
want string
// parsed is the name a client reads back, the filename through
// PortableFilename.
parsed string
}{
{name: "ASCII", filename: "foo.pdf", want: `attachment; filename="foo.pdf"`},
{name: "space", filename: "my report.pdf", want: `attachment; filename="my report.pdf"`},
{name: "quote", filename: `quo"te.pdf`, want: `attachment; filename="quo\"te.pdf"`},
{name: "backslash", filename: `a\b.pdf`, want: `attachment; filename="a\\b.pdf"`},
{name: "extension kept", filename: "report.pdf.pdf", want: `attachment; filename="report.pdf.pdf"`},
{name: "non-ASCII", filename: "é日本.pdf", want: `attachment; filename="___.pdf"; filename*=UTF-8''%C3%A9%E6%97%A5%E6%9C%AC.pdf`},
{name: "non-ASCII with a quote and a semicolon", filename: `é";a=b.pdf`, want: `attachment; filename="_\";a=b.pdf"; filename*=UTF-8''%C3%A9%22%3Ba%3Db.pdf`},
{name: "ASCII", filename: "foo.pdf", want: `attachment; filename="foo.pdf"`, parsed: "foo.pdf"},
{name: "space", filename: "my report.pdf", want: `attachment; filename="my report.pdf"`, parsed: "my report.pdf"},
{name: "quote", filename: `quo"te.pdf`, want: `attachment; filename="quo_te.pdf"`, parsed: "quo_te.pdf"},
{name: "backslash", filename: `a\b.pdf`, want: `attachment; filename="b.pdf"`, parsed: "b.pdf"},
{name: "drive", filename: `C:evil.pdf`, want: `attachment; filename="C_evil.pdf"`, parsed: "C_evil.pdf"},
{name: "extension kept", filename: "report.pdf.pdf", want: `attachment; filename="report.pdf.pdf"`, parsed: "report.pdf.pdf"},
{name: "non-ASCII", filename: "é日本.pdf", want: `attachment; filename="___.pdf"; filename*=UTF-8''%C3%A9%E6%97%A5%E6%9C%AC.pdf`, parsed: "é日本.pdf"},
{name: "non-ASCII with a quote and a semicolon", filename: `é";a=b.pdf`, want: `attachment; filename="__;a=b.pdf"; filename*=UTF-8''%C3%A9_%3Ba%3Db.pdf`, parsed: "é_;a=b.pdf"},
} {
t.Run(tc.name, func(t *testing.T) {
got := ContentDisposition(tc.filename)
@@ -1448,13 +1455,102 @@ func TestContentDisposition(t *testing.T) {
if err != nil {
t.Fatalf("parse media type: %v", err)
}
if params["filename"] != tc.filename {
t.Errorf("parsed filename = %q, want %q", params["filename"], tc.filename)
if params["filename"] != tc.parsed {
t.Errorf("parsed filename = %q, want %q", params["filename"], tc.parsed)
}
})
}
}
func TestPortableFilename(t *testing.T) {
for _, tc := range []struct {
name string
want string
}{
{name: "report.pdf", want: "report.pdf"},
{name: "résumé (final).pdf", want: "résumé (final).pdf"},
{name: "cafe\u0301.pdf", want: "café.pdf"},
{name: "日本語.pdf", want: "日本語.pdf"},
{name: "Привет.pdf", want: "Привет.pdf"},
{name: "हिन्दी.pdf", want: "हिन्दी.pdf"},
{name: "عربي.pdf", want: "عربي.pdf"},
{name: ".hidden", want: ".hidden"},
{name: "../../evil.png", want: "evil.png"},
{name: `..\..\evil.png`, want: "evil.png"},
{name: `\\server\share\x.pdf`, want: "x.pdf"},
{name: `\\?\C:`, want: "C_"},
{name: "C:evil.pdf", want: "C_evil.pdf"},
{name: "x.pdf:stream", want: "x.pdf_stream"},
{name: "x::$DATA", want: "x__$DATA"},
{name: `a*b?c"d<e>f|g.pdf`, want: "a_b_c_d_e_f_g.pdf"},
{name: "a\x00b\x1fc.pdf", want: "abc.pdf"},
{name: "invoice\u202efdp.exe", want: "invoice_fdp.exe"},
{name: "zero\u200bwidth.pdf", want: "zero_width.pdf"},
{name: "a/b\c:d.pdf", want: "a_b_c_d.pdf"},
{name: "a¥b₩c∕d.pdf", want: "a_b_c_d.pdf"},
{name: "invalid\xff.pdf", want: "invalid_.pdf"},
{name: "€ “quoted” 🙂.pdf", want: "_ _quoted_ _.pdf"},
{name: "evil.pdf.", want: "evil.pdf"},
{name: "evil.pdf ", want: "evil.pdf"},
{name: " evil.pdf", want: "evil.pdf"},
{name: "CON", want: "_CON"},
{name: "con.pdf", want: "_con.pdf"},
{name: "CON .pdf", want: "_CON .pdf"},
{name: "nul.tar.gz", want: "_nul.tar.gz"},
{name: "COM1", want: "_COM1"},
{name: "LPT9.txt", want: "_LPT9.txt"},
{name: "CONIN$", want: "_CONIN$"},
{name: "COM¹.pdf", want: "COM_.pdf"},
{name: "CONSOLE.pdf", want: "CONSOLE.pdf"},
{name: "COM10.pdf", want: "COM10.pdf"},
{name: "", want: "file"},
{name: ".", want: "file"},
{name: "..", want: "file"},
{name: "...", want: "file"},
{name: "dir/", want: "file"},
} {
if got := PortableFilename(tc.name); got != tc.want {
t.Errorf("PortableFilename(%q) = %q, want %q", tc.name, got, tc.want)
}
}
}
// FuzzPortableFilename checks what every name PortableFilename returns holds,
// whatever it gets.
func FuzzPortableFilename(f *testing.F) {
for _, seed := range []string{"report.pdf", "C:evil.pdf", "../..", "CON.pdf", "a\u202eb", "/\:", ""} {
f.Add(seed)
}
f.Fuzz(func(t *testing.T, name string) {
got := PortableFilename(name)
if got == "" {
t.Fatalf("PortableFilename(%q) is empty", name)
}
if !utf8.ValidString(got) {
t.Fatalf("PortableFilename(%q) = %q, not valid UTF-8", name, got)
}
if strings.ContainsAny(got, `<>:"/\|?*`) {
t.Fatalf("PortableFilename(%q) = %q, holds a character Windows refuses", name, got)
}
for _, r := range got {
if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) {
t.Fatalf("PortableFilename(%q) = %q, holds %U", name, got, r)
}
}
if strings.HasSuffix(got, ".") || strings.HasSuffix(got, " ") || strings.HasPrefix(got, " ") {
t.Fatalf("PortableFilename(%q) = %q, starts with a space or ends with a dot or a space", name, got)
}
if isWindowsDeviceName(got) {
t.Fatalf("PortableFilename(%q) = %q, a Windows device name", name, got)
}
if again := PortableFilename(got); again != got {
t.Fatalf("PortableFilename(%q) = %q, but PortableFilename(%q) = %q", name, got, got, again)
}
})
}
// A download that fails answers 400 with a message the client can act on: it
// uses the prefix of the other form field errors, tells what a response must
// carry, and names no address the container resolved.
@@ -1615,6 +1711,48 @@ func TestDownloadFilename(t *testing.T) {
}
}
// An archive names each entry through PortableFilename, and tells apart the
// names Windows and macOS would take for one.
func TestContext_BuildOutputFile_EntryNames(t *testing.T) {
dir := t.TempDir()
ctx := &Context{Context: context.Background(), dirPath: dir, logger: slog.New(slog.DiscardHandler)}
originals := []string{"C:evil.rtf.pdf", "Doc.pdf", "doc.pdf", "a:b.pdf", "a_b.pdf", "CON.pdf"}
for _, original := range originals {
path := ctx.GeneratePathFromFilename(original)
err := os.WriteFile(path, []byte(original), 0o600)
if err != nil {
t.Fatalf("write %q: %v", original, err)
}
err = ctx.AddOutputPaths(path)
if err != nil {
t.Fatalf("add output path: %v", err)
}
}
archivePath, err := ctx.BuildOutputFile()
if err != nil {
t.Fatalf("BuildOutputFile: %v", err)
}
r, err := zip.OpenReader(archivePath)
if err != nil {
t.Fatalf("open archive: %v", err)
}
defer r.Close()
var got []string
for _, f := range r.File {
got = append(got, f.Name)
}
slices.Sort(got)
want := []string{"C_evil.rtf.pdf", "Doc.pdf", "_CON.pdf", "a_b (2).pdf", "a_b.pdf", "doc (2).pdf"}
if !slices.Equal(got, want) {
t.Fatalf("entries = %q, want %q", got, want)
}
}
func TestContext_GeneratePath(t *testing.T) {
ctx := &Context{dirPath: "/tmp/req"}

View File

@@ -5,11 +5,12 @@ import (
"context"
"errors"
"fmt"
"path/filepath"
"slices"
"strings"
litho "github.com/gotenberg/litho/pkg/pdf"
"github.com/gotenberg/gotenberg/v9/pkg/modules/api"
)
func (s *deleteStage) edit(_ context.Context, w *litho.Writer, env *runEnv) error {
@@ -268,10 +269,13 @@ func (s *attachStage) edit(_ context.Context, w *litho.Writer, env *runEnv) erro
return err
}
// The name travels inside the PDF, and a viewer or extractor writes the
// file under it, so it gets the rule of every name that leaves Gotenberg.
name := s.Name
if name == "" {
name = filepath.Base(s.File)
name = s.File
}
name = api.PortableFilename(name)
mimeType := s.MimeType
if mimeType == "" {

View File

@@ -131,16 +131,10 @@ func selectAttachments(files []models.EmbeddedFile, name string) ([]models.Embed
// attachmentFilename returns the name an attachment comes back under: the
// document's base name, then the attachment's. The attachment's name comes
// from the PDF, so it loses any directory and control character, which would
// otherwise reach the ZIP as a path.
// from the PDF as it holds it, so it goes through [api.PortableFilename]
// first: a directory in it would otherwise drop the base name.
func attachmentFilename(base, name string) string {
name = api.SanitizeFilename(name)
if name == "" || name == "." || name == ".." {
// litho names a file specification without a name the same way.
name = "embedded"
}
return base + "_" + name
return base + "_" + api.PortableFilename(name)
}
// uniqueName returns name, or a numbered variant of it, invoice_factur-x_2.xml

View File

@@ -113,6 +113,28 @@ func TestExtractAttachments(t *testing.T) {
}
}
// The attach stage writes the name a viewer extracts the file under, so it
// writes it through api.PortableFilename: no directory, no drive.
func TestAttachWritesAPortableName(t *testing.T) {
processor := testProcessor()
ctx, paths := testContext(t, "page_1.pdf", "embed_1.xml")
files := map[string]string{"embed_1.xml": paths["embed_1.xml"]}
attached, err := processor.Run(ctx, mustStages(t, `[{"op":"attach","file":"embed_1.xml","name":"../../C:evil.xml"}]`), []string{paths["page_1.pdf"]}, files)
if err != nil {
t.Fatal(err)
}
outputs, err := processor.Run(ctx, mustStages(t, `[{"op":"extract-attachments","name":"C_evil.xml"}]`), attached, files)
if err != nil {
t.Fatalf("extract the attachment by its portable name: %v", err)
}
if got := ctx.OriginalFilename(outputs[len(outputs)-1]); got != "page_1_C_evil.xml" {
t.Fatalf("extracted %q, want %q", got, "page_1_C_evil.xml")
}
}
func TestAttachmentFilename(t *testing.T) {
for _, tc := range []struct {
name string
@@ -122,9 +144,11 @@ func TestAttachmentFilename(t *testing.T) {
{name: "../../etc/passwd", want: "invoice_passwd"},
{name: `C:\temp\data.xml`, want: "invoice_data.xml"},
{name: "da\x00ta\x1f.xml", want: "invoice_data.xml"},
{name: "", want: "invoice_embedded"},
{name: "..", want: "invoice_embedded"},
{name: "dir/", want: "invoice_embedded"},
{name: "C:payload.exe", want: "invoice_C_payload.exe"},
{name: "embedded", want: "invoice_embedded"},
{name: "", want: "invoice_file"},
{name: "..", want: "invoice_file"},
{name: "dir/", want: "invoice_file"},
} {
if got := attachmentFilename("invoice", tc.name); got != tc.want {
t.Errorf("attachmentFilename(%q) = %q, want %q", tc.name, got, tc.want)

View File

@@ -1185,6 +1185,20 @@ Feature: /forms/libreoffice/convert
Then the file request header "X-Foo" should be "bar"
Then the response header "Content-Type" should be "application/pdf"
# A name that leaves Gotenberg is one file name on every system: a drive
# prefix or a Windows device name never reaches the extractor as such.
@download-from
Scenario: POST /forms/libreoffice/convert (Download From With Hostile Filenames)
Given I have a default Gotenberg container
Given I have a static server
When I make a "POST" request to Gotenberg at the "/forms/libreoffice/convert" endpoint with the following form data and header(s):
| downloadFrom | [{"url":"{helper}/static/testdata/page_1.docx","filename":"C:evil.docx"},{"url":"{helper}/static/testdata/page_2.docx","filename":"CON.docx"}] | field |
Then the response status code should be 200
Then the response header "Content-Type" should be "application/zip"
Then there should be the following file(s) in the response:
| C_evil.docx.pdf |
| _CON.docx.pdf |
# The outbound filter refuses a download URL the deny-list names, even when
# the allow-list matches every URL. A refusal stays generic for the client.
@download-from