Skip to content

Commit

Permalink
HTML: fix attribute quoting bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
tdewolff committed May 22, 2022
1 parent 184bfb2 commit 893ef0d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
7 changes: 5 additions & 2 deletions html/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ func EscapeAttrVal(buf *[]byte, b []byte, origQuote byte, mustQuote, isXML bool)
}
if unquoted && (!mustQuote || origQuote == 0) && !isXML {
return b
} else if singles == 0 && origQuote == '\'' || doubles == 0 && origQuote == '"' {
} else if singles == 0 && origQuote == '\'' && !isXML || doubles == 0 && origQuote == '"' {
if len(b)+2 > cap(*buf) {
*buf = make([]byte, 0, len(b)+2)
}
t := (*buf)[:len(b)+2]
t[0] = origQuote
copy(t[1:], b)
Expand All @@ -37,7 +40,7 @@ func EscapeAttrVal(buf *[]byte, b []byte, origQuote byte, mustQuote, isXML bool)
n += doubles * 4
quote = '"'
escapedQuote = doubleQuoteEntityBytes
if singles == doubles && origQuote == '\'' {
if singles == doubles && origQuote == '\'' && !isXML {
quote = '\''
escapedQuote = singleQuoteEntityBytes
}
Expand Down
16 changes: 12 additions & 4 deletions html/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,14 @@ func TestEscapeAttrVal(t *testing.T) {
for _, tt := range escapeAttrValTests {
t.Run(tt.attrVal, func(t *testing.T) {
b := []byte(tt.attrVal)
orig := b
var quote byte
if 0 < len(b) && (b[0] == '\'' || b[0] == '"') {
quote = b[0]
}
if len(b) > 1 && (b[0] == '"' || b[0] == '\'') && b[0] == b[len(b)-1] {
b = b[1 : len(b)-1]
}
val := EscapeAttrVal(&buf, orig, b, false)
val := EscapeAttrVal(&buf, b, quote, false, false)
test.String(t, string(val), tt.expected)
})
}
Expand All @@ -44,18 +47,23 @@ func TestEscapeAttrValXML(t *testing.T) {
attrVal string
expected string
}{
{`"xyz"`, `"xyz"`},
{`xyz`, `"xyz"`},
{`'xyz'`, `"xyz"`},
{``, `""`},
}
var buf []byte
for _, tt := range escapeAttrValTests {
t.Run(tt.attrVal, func(t *testing.T) {
b := []byte(tt.attrVal)
orig := b
var quote byte
if 0 < len(b) && (b[0] == '\'' || b[0] == '"') {
quote = b[0]
}
if len(b) > 1 && (b[0] == '"' || b[0] == '\'') && b[0] == b[len(b)-1] {
b = b[1 : len(b)-1]
}
val := EscapeAttrVal(&buf, orig, b, true)
val := EscapeAttrVal(&buf, b, quote, false, true)
test.String(t, string(val), tt.expected)
})
}
Expand Down

0 comments on commit 893ef0d

Please sign in to comment.