Skip to content

Commit 5b4fcd6

Browse files
committed
Use singleton
1 parent 058c0f3 commit 5b4fcd6

File tree

2 files changed

+34
-10
lines changed

2 files changed

+34
-10
lines changed

pkg/sanitize/sanitize.go

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
package sanitize
22

33
import (
4+
"sync"
5+
46
"github.com/microcosm-cc/bluemonday"
57
)
68

79
var policy *bluemonday.Policy
10+
var policyOnce sync.Once
811

912
func Sanitize(input string) string {
1013
return FilterHTMLTags(FilterInvisibleCharacters(input))
@@ -41,14 +44,30 @@ func FilterHTMLTags(input string) string {
4144
}
4245

4346
func policyInit() {
44-
if policy != nil {
45-
return
46-
}
47-
policy = bluemonday.StrictPolicy()
48-
policy.AllowElements("b", "blockquote", "br", "code", "em", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "i", "li", "ol", "p", "pre", "strong", "sub", "sup", "table", "tbody", "td", "th", "thead", "tr", "ul")
49-
policy.AllowAttrs("img", "a")
50-
policy.AllowURLSchemes("https")
51-
policy.AllowImages()
47+
policyOnce.Do(func() {
48+
p := bluemonday.StrictPolicy()
49+
50+
p.AllowElements(
51+
"b", "blockquote", "br", "code", "em",
52+
"h1", "h2", "h3", "h4", "h5", "h6",
53+
"hr", "i", "li", "ol", "p", "pre",
54+
"strong", "sub", "sup", "table", "tbody",
55+
"td", "th", "thead", "tr", "ul",
56+
"a", "img",
57+
)
58+
59+
p.AllowAttrs("href").OnElements("a")
60+
p.AllowURLSchemes("https")
61+
p.RequireParseableURLs(true)
62+
p.RequireNoFollowOnLinks(true)
63+
p.RequireNoReferrerOnLinks(true)
64+
p.AddTargetBlankToFullyQualifiedLinks(true)
65+
66+
p.AllowImages()
67+
p.AllowAttrs("src", "alt", "title").OnElements("img")
68+
69+
policy = p
70+
})
5271
}
5372

5473
func shouldRemoveRune(r rune) bool {

pkg/sanitize/sanitize_test.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -218,10 +218,15 @@ func TestFilterHtmlTags(t *testing.T) {
218218
input: "<script>alert(1)</script>",
219219
expected: "", // StrictPolicy should drop script element and contents
220220
},
221+
{
222+
name: "allow anchor with https href",
223+
input: "Click <a href=\"https://example.com\">here</a> now",
224+
expected: "Click <a href=\"https://example.com\" rel=\"nofollow noreferrer noopener\" target=\"_blank\">here</a> now",
225+
},
221226
{
222227
name: "anchor removed but inner text kept",
223-
input: "Click <a href='https://example.com'>here</a> now",
224-
expected: "Click here now",
228+
input: "before <a href='https://example.com' onclick='alert(1)' title='foo' alt='bar'>link</a> after",
229+
expected: "before <a href=\"https://example.com\" rel=\"nofollow noreferrer noopener\" target=\"_blank\">link</a> after",
225230
},
226231
{
227232
name: "image removed (no textual fallback)",

0 commit comments

Comments
 (0)