navidrome/utils/str/content_disposition_test.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

120 lines
4.5 KiB
Go
Raw Permalink Normal View History

sec(server): sanitize user-controlled filenames in Content-Disposition (#5895) * sec(server): sanitize user-controlled filenames in Content-Disposition Playlist export, Subsonic download and public share download built the Content-Disposition header by interpolating a user-controlled name into a quoted-string with fmt.Sprintf. A name containing a double quote closes the string early and the rest is parsed as additional parameters, so a playlist named `party"; filename="evil.html` yielded attachment; filename="party"; filename="evil.html.m3u" letting whoever chose the name decide what the browser saves the download as. The names come from playlists, album/artist names and media file tags. Go's net/http already rewrites CR and LF in header values to spaces, so response splitting was not reachable; parameter injection was. Add str.ContentDispositionAttachment, which emits a sanitized ASCII-only quoted `filename` plus an RFC 5987 `filename*` carrying the original UTF-8 name, and use it at all four call sites. The `filename*` parameter also fixes non-ASCII names, which previously went out raw or were mangled by sanitizing. Signed-off-by: zapisanchez <zapisanchez@gmail.com> * fix(server): keep download names intact and sanitize filename* Rework ContentDispositionAttachment after review. Names with no ASCII letters now fall back to download.<ext> instead of a bare extension (東京.mp3 gave filename="mp3"). filename* is built from the same sanitized name as the ASCII fallback, so path separators, reserved characters, control and bidi characters, and invalid UTF-8 no longer reach it. The ASCII fallback transliterates accents and typographic punctuation (Legião -> Legiao, She’s -> She's) through the existing sanitize.Accents and str.Clear helpers, keeps leading dots, and only trims trailing ones. Names are capped at 255 bytes, keeping the extension. Pure ASCII names now get only the quoted filename parameter, so the header for them matches the previous output byte for byte. filename* is encoded with mime.FormatMediaType instead of a hand-written RFC 5987 encoder. Adds tests for the M3U export and Subsonic download headers. * fix(server): handle dot-only names and long fake extensions A name made only of dots trimmed down to an empty filename. It now falls back to download, like an empty stem does. path.Ext treats anything after the last dot as the extension, so a long suffix with no real extension was kept whole and replaced the stem with download, going past the 255-byte cap. Suffixes longer than 16 bytes are now treated as part of the stem and truncated with it. Neither case is reachable from the current call sites, which always append a short extension. --------- Signed-off-by: zapisanchez <zapisanchez@gmail.com> Co-authored-by: Deluan <deluan@navidrome.org>
2026-09-23 15:47:16 +02:00
package str_test
import (
"mime"
"regexp"
"strings"
"github.com/navidrome/navidrome/utils/str"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var asciiFilenameRe = regexp.MustCompile(`(?:^|; )filename="([^"]*)"`)
// asciiName returns the quoted filename parameter, the one used by clients that ignore filename*.
func asciiName(filename string) string {
m := asciiFilenameRe.FindAllStringSubmatch(str.ContentDispositionAttachment(filename), -1)
ExpectWithOffset(1, m).To(HaveLen(1), "expected exactly one quoted filename parameter")
return m[0][1]
}
// decodedName returns the name an RFC 6266 client picks, preferring filename* when present.
func decodedName(filename string) string {
disp, params, err := mime.ParseMediaType(str.ContentDispositionAttachment(filename))
ExpectWithOffset(1, err).ToNot(HaveOccurred())
ExpectWithOffset(1, disp).To(Equal("attachment"))
return params["filename"]
}
var _ = Describe("ContentDispositionAttachment", func() {
Describe("parameter injection", func() {
const attack = `party"; filename="evil.html.m3u`
It("does not let a quote in the name open a second parameter", func() {
Expect(str.ContentDispositionAttachment(attack)).To(Equal(`attachment; filename="party_; filename=_evil.html.m3u"`))
})
It("keeps the header parseable", func() {
Expect(decodedName(attack)).To(Equal("party_; filename=_evil.html.m3u"))
})
It("does not let a quote in a non-ASCII name inject either", func() {
const utf8Attack = `東京"; filename="evil.html.m3u`
header := str.ContentDispositionAttachment(utf8Attack)
Expect(strings.Count(header, `"`)).To(Equal(2))
Expect(decodedName(utf8Attack)).To(Equal("東京_; filename=_evil.html.m3u"))
})
})
Describe("ASCII names", func() {
It("sends only the quoted filename, unchanged", func() {
Expect(str.ContentDispositionAttachment("My Playlist.m3u")).To(Equal(`attachment; filename="My Playlist.m3u"`))
})
It("keeps leading dots", func() {
Expect(asciiName("...And Justice for All.zip")).To(Equal("...And Justice for All.zip"))
})
It("trims surrounding spaces and trailing dots", func() {
Expect(asciiName(" Greatest Hits .zip")).To(Equal("Greatest Hits.zip"))
Expect(asciiName("Loose End. ")).To(Equal("Loose End"))
})
It("falls back to a placeholder when only dots are left", func() {
Expect(str.ContentDispositionAttachment("...")).To(Equal(`attachment; filename="download"`))
})
It("caps a long name whose last dot is not an extension", func() {
name := asciiName("a." + strings.Repeat("x", 300))
Expect(len(name)).To(BeNumerically("<=", 255))
Expect(name).To(HavePrefix("a.xxx"))
})
It("replaces path separators and reserved characters", func() {
Expect(asciiName("AC/DC: Live, 1979?.zip")).To(Equal("AC_DC_ Live_ 1979_.zip"))
})
It("drops control characters", func() {
Expect(asciiName("line\r\nbreak\x00\t.mp3")).To(Equal("linebreak.mp3"))
})
})
Describe("non-ASCII names", func() {
It("transliterates accents in the ASCII fallback", func() {
Expect(asciiName("Legião Urbana.zip")).To(Equal("Legiao Urbana.zip"))
})
It("converts typographic punctuation in the ASCII fallback", func() {
Expect(asciiName("She’s a Woman — Live.mp3")).To(Equal("She's a Woman - Live.mp3"))
Expect(asciiName("“Heroes”.mp3")).To(Equal("_Heroes_.mp3"))
Expect(decodedName("She’s a Woman.mp3")).To(Equal("She’s a Woman.mp3"))
})
It("keeps the extension when no ASCII letters survive", func() {
Expect(asciiName("東京.mp3")).To(Equal("download.mp3"))
Expect(asciiName("Кино.m3u")).To(Equal("download.m3u"))
Expect(asciiName("東京")).To(Equal("download"))
})
DescribeTable("filename* carries the sanitized UTF-8 name",
func(filename, expected string) {
Expect(decodedName(filename)).To(Equal(expected))
},
Entry("accented", "Legião Urbana.zip", "Legião Urbana.zip"),
Entry("CJK", "東京.zip", "東京.zip"),
Entry("emoji", "🎵 mix.zip", "🎵 mix.zip"),
Entry("comma and percent", "Sigur Rós, 100%.zip", "Sigur Rós, 100%.zip"),
Entry("path separators", "Sigur Rós/Live: Heima.zip", "Sigur Rós_Live_ Heima.zip"),
Entry("control characters", "Sigur Rós\r\n\x00.zip", "Sigur Rós.zip"),
Entry("bidi override", "Björk\u202Eexe.mp3", "Björkexe.mp3"),
Entry("invalid UTF-8", "Bj\xf6rk Café.mp3", "Bj_rk Café.mp3"),
)
It("caps the name length and keeps the extension", func() {
name := decodedName(strings.Repeat("東", 300) + ".zip")
Expect(len(name)).To(BeNumerically("<=", 255))
Expect(name).To(HaveSuffix("東.zip"))
})
})
})