Skip to content

Commit a455634

Browse files
Add tests.
1 parent 71fef65 commit a455634

File tree

2 files changed

+851
-16
lines changed

2 files changed

+851
-16
lines changed

modifiers.go

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -283,13 +283,19 @@ func getAttr(attrList []html.Attribute, key string) (html.Attribute, bool) {
283283
}
284284

285285
func (csp *CSPContentNonceModifier) applyNonceToNodes(node *html.Node, nonce string) {
286+
for child := node.FirstChild; child != nil; child = child.NextSibling {
287+
csp.applyNonceToNodes(child, nonce)
288+
}
289+
if node.Type != html.ElementNode {
290+
return
291+
}
286292
canHaveNonce := node.Data == "script" || node.Data == "style" || (node.Data == "link" && attrListHas(node.Attr, "rel", "stylesheet"))
287293
styleAttr, hasStyleAttr := getAttr(node.Attr, "style")
288294
if canHaveNonce || hasStyleAttr {
289295
if csp.nonceElementDecider != nil && !csp.nonceElementDecider.ShouldModify(node) {
290296
return
291297
}
292-
switch true {
298+
switch {
293299
case canHaveNonce:
294300
node.Attr = append(node.Attr, html.Attribute{
295301
Key: "nonce",
@@ -325,25 +331,24 @@ func (csp *CSPContentNonceModifier) applyNonceToNodes(node *html.Node, nonce str
325331
parent.InsertBefore(styleNode, node)
326332

327333
classAttr, hasClassAttr := getAttr(node.Attr, "class")
334+
newClassAttr := className
328335
if hasClassAttr {
329-
newAttrs := make([]html.Attribute, 0, len(node.Attr))
330-
for _, attr := range node.Attr {
331-
if attr.Key == "class" {
332-
attr.Val = classAttr.Val + " " + className
333-
}
336+
newClassAttr = classAttr.Val + " " + className
337+
}
338+
var newAttrs []html.Attribute
339+
for _, attr := range node.Attr {
340+
if attr.Key == "class" && hasClassAttr {
341+
attr.Val = classAttr.Val + " " + className
342+
}
343+
if attr.Key != "style" && attr.Key != "class" {
334344
newAttrs = append(newAttrs, attr)
335345
}
336-
} else {
337-
node.Attr = append(node.Attr, html.Attribute{
338-
Key: "class",
339-
Val: className,
340-
})
341346
}
347+
node.Attr = append(newAttrs, html.Attribute{
348+
Key: "class",
349+
Val: newClassAttr,
350+
})
342351
}
343-
return
344-
}
345-
for child := node.FirstChild; child != nil; child = child.NextSibling {
346-
csp.applyNonceToNodes(child, nonce)
347352
}
348353
}
349354

@@ -356,7 +361,7 @@ func makeNonce(length int) (string, error) {
356361
return hex.EncodeToString(randomBytes), nil
357362
}
358363

359-
const defaultNonceLength = 32
364+
const defaultNonceLength = 10
360365

361366
func (csp *CSPContentNonceModifier) ModifyContent(context FileModifierContext, content []byte) ([]byte, error) {
362367
doc, err := html.Parse(bytes.NewReader(content))

0 commit comments

Comments
 (0)