From d85908e3dee90a86713658d19b79e3fca4b0b126 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Guillot?= Date: Sun, 3 Jul 2022 17:36:27 -0700 Subject: [PATCH] Allow width and height attributes for img tags --- reader/sanitizer/sanitizer.go | 13 ++++++++++++- reader/sanitizer/sanitizer_test.go | 22 +++++++++++++++++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/reader/sanitizer/sanitizer.go b/reader/sanitizer/sanitizer.go index 0af6c197..92ae869e 100644 --- a/reader/sanitizer/sanitizer.go +++ b/reader/sanitizer/sanitizer.go @@ -113,6 +113,10 @@ func sanitizeAttributes(baseURL, tagName string, attributes []html.Attribute) ([ value = sanitizeSrcsetAttr(baseURL, value) } + if tagName == "img" && (attribute.Key == "width" || attribute.Key == "height") && !isPositiveInteger(value) { + continue + } + if isExternalResourceAttribute(attribute.Key) { if tagName == "iframe" { if isValidIframeSource(baseURL, attribute.Val) { @@ -350,7 +354,7 @@ func isValidIframeSource(baseURL, src string) bool { func getTagAllowList() map[string][]string { whitelist := make(map[string][]string) - whitelist["img"] = []string{"alt", "title", "src", "srcset", "sizes"} + whitelist["img"] = []string{"alt", "title", "src", "srcset", "sizes", "width", "height"} whitelist["picture"] = []string{} whitelist["audio"] = []string{"src"} whitelist["video"] = []string{"poster", "height", "width", "src"} @@ -511,3 +515,10 @@ func isValidDataAttribute(value string) bool { } return false } + +func isPositiveInteger(value string) bool { + if number, err := strconv.Atoi(value); err == nil { + return number > 0 + } + return false +} diff --git a/reader/sanitizer/sanitizer_test.go b/reader/sanitizer/sanitizer_test.go index fedb98ee..aee7ba4e 100644 --- a/reader/sanitizer/sanitizer_test.go +++ b/reader/sanitizer/sanitizer_test.go @@ -15,6 +15,26 @@ func TestValidInput(t *testing.T) { } } +func TestImgWithWidthAndHeightAttribute(t *testing.T) { + input := `` + expected := `` + output := Sanitize("http://example.org/", input) + + if output != expected { + t.Errorf(`Wrong output: %s`, output) + } +} + +func TestImgWithIncorrectWidthAndHeightAttribute(t *testing.T) { + input := `` + expected := `` + output := Sanitize("http://example.org/", input) + + if output != expected { + t.Errorf(`Wrong output: %s`, output) + } +} + func TestImgWithTextDataURL(t *testing.T) { input := `Example` expected := `` @@ -57,7 +77,7 @@ func TestSourceWithSrcsetAndMedia(t *testing.T) { func TestMediumImgWithSrcset(t *testing.T) { input := `Image for post` - expected := `Image for post` + expected := `Image for post` output := Sanitize("http://example.org/", input) if output != expected {