Skip to content

Commit

Permalink
feat: support unquoted CSS background-urls, fixes #578, #580
Browse files Browse the repository at this point in the history
  • Loading branch information
a-h committed Mar 3, 2024
1 parent 8d48984 commit f3417e0
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 8 deletions.
2 changes: 1 addition & 1 deletion .version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.2.602
0.2.603
32 changes: 25 additions & 7 deletions safehtml/style.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,17 +62,35 @@ var cssPropertyNameToValueSanitizer = map[string]func(string) string{
"z-index": sanitizeRegular,
}

var validURLPrefixes = []string{
`url("`,
`url('`,
`url(`,
}

var validURLSuffixes = []string{
`")`,
`')`,
`)`,
}

func sanitizeBackgroundImage(v string) string {
// Check for <> as per https://github.com/google/safehtml/blob/be23134998433fcf0135dda53593fc8f8bf4df7c/style.go#L87C2-L89C3
if strings.ContainsAny(v, "<>") {
return InnocuousPropertyValue
}
for _, u := range strings.Split(v, ",") {
u = strings.TrimSpace(u)
if !strings.HasPrefix(u, `url("`) {
return InnocuousPropertyValue
}
if !strings.HasSuffix(u, `")`) {
return InnocuousPropertyValue
var found bool
for i, prefix := range validURLPrefixes {
if strings.HasPrefix(u, prefix) && strings.HasSuffix(u, validURLSuffixes[i]) {
found = true
u = strings.TrimPrefix(u, validURLPrefixes[i])
u = strings.TrimSuffix(u, validURLSuffixes[i])
break
}
}
u := u[5 : len(u)-2]
if !urlIsSafe(u) {
if !found || !urlIsSafe(u) {
return InnocuousPropertyValue
}
}
Expand Down
14 changes: 14 additions & 0 deletions safehtml/style_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,13 @@ func TestSanitizeCSS(t *testing.T) {
inputValue: `url(/img?name=O'Reilly Animal(1)<2>.png)`,
expectedValue: InnocuousPropertyValue,
},
{
name: "angle brackets in quoted property value",
inputProperty: "background-image",
expectedProperty: "background-image",
inputValue: `url("/img?name=O'Reilly Animal(1)<2>.png")`,
expectedValue: InnocuousPropertyValue,
},
{
name: "background",
inputProperty: "background",
Expand Down Expand Up @@ -178,6 +185,13 @@ func TestSanitizeCSS(t *testing.T) {
inputValue: `url("/img.png")`,
expectedValue: `url("/img.png")`,
},
{
name: "background-image safe URL - two slashes",
inputProperty: "background-image",
expectedProperty: "background-image",
inputValue: `url("//img.png")`,
expectedValue: `url("//img.png")`,
},
{
name: "background-image safe HTTP URL",
inputProperty: "background-image",
Expand Down

0 comments on commit f3417e0

Please sign in to comment.