-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcleaner_test.go
429 lines (362 loc) · 14.3 KB
/
cleaner_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
package gsoup
import (
"bytes"
"errors"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
func Test_FailGracefullyOnParseError(t *testing.T) {
_, err := NewEmptyCleaner().Clean(badReader{})
assert.NotNil(t, err, "err should not be nil")
}
func Test_stripInvalidAttributes(t *testing.T) {
// basic passthrough
elem := ele("class")
def := T(atom.P, "class")
stripInvalidAttributes(elem, def)
assert.Equal(t, 1, len(elem.Attr), "tag should have one attribute")
assert.Equal(t, "class", elem.Attr[0].Key, "elem should still contain key 'class'")
// basic strip
def = T(atom.P)
stripInvalidAttributes(elem, def)
assert.Equal(t, 0, len(elem.Attr), "tag should have zero attributes")
// attributes should be found case insensitive and lowercased
def = T(atom.P, "class")
elem = ele("ClAsS", "OnClicK")
stripInvalidAttributes(elem, def)
assert.Equal(t, 1, len(elem.Attr), "tag should have one attribute")
assert.Equal(t, "class", elem.Attr[0].Key, "elem should contain lowercased key 'class'")
}
func Test_shouldPreserveChildren(t *testing.T) {
c := NewBasicCleaner().(*cleaner)
// test 'always preserve' elements
n := ele()
n.Type = html.ElementNode
for a := range preserveChildrenSet {
n.DataAtom = a
assert.True(t, c.shouldPreserveChildren(n), "should preserve atoms in the 'always preserve set'")
}
// test don't preserve children of non-element types
n.Type = html.TextNode
assert.False(t, c.shouldPreserveChildren(n), "should not preserve non-elements")
// test preserveChildren toggle
n.Type = html.ElementNode
n.DataAtom = atom.P
c.preserveChildren = false
assert.False(t, c.shouldPreserveChildren(n), "should not preserve P tag if preserveChildren is false")
c.preserveChildren = true
assert.True(t, c.shouldPreserveChildren(n), "should preserve P tag if preserveChildren is true")
// always delete non-structure nodes
for a := range deleteChildrenSet {
n.DataAtom = a
assert.False(t, c.shouldPreserveChildren(n), "should not preserve atoms in the 'always delete set'")
}
}
func Test_removeElement_WithChildren(t *testing.T) {
p := &html.Node{Type: html.DocumentNode}
n1 := eleWithData(1)
n2 := eleWithData(2)
n3 := eleWithData(3)
c1 := eleWithData(4)
c2 := eleWithData(5)
p.AppendChild(n1)
p.AppendChild(n2)
p.AppendChild(n3)
n2.AppendChild(c1)
n2.AppendChild(c2)
n2.Type = html.ElementNode
n2.DataAtom = atom.P
c := NewBasicCleaner().(*cleaner)
c.preserveChildren = true
result := c.removeElement(n2)
assert.Equal(t, result, c1, "returned node should be first child of removed node if it has children")
assert.Nil(t, n2.Parent, "n2 should have been removed from the graph")
assert.Equal(t, n1, c1.PrevSibling, "c1 should be next sib of n1")
assert.Equal(t, c2, c1.NextSibling, "c2 should be next sib of c1")
assert.Equal(t, n3, c2.NextSibling, "n3 should be next sib of c2")
}
func Test_removeElement_WithoutChildren(t *testing.T) {
p := &html.Node{Type: html.DocumentNode}
n1 := eleWithData(1)
n2 := eleWithData(2)
n3 := eleWithData(3)
p.AppendChild(n1)
p.AppendChild(n2)
p.AppendChild(n3)
n2.Type = html.ElementNode
n2.DataAtom = atom.P
c := NewBasicCleaner().(*cleaner)
c.preserveChildren = true
result := c.removeElement(n2)
assert.Nil(t, n2.Parent, "n2 should have been removed from the graph")
assert.Equal(t, n3, result, "returned node should be next sib. of removed node if removed node has no children")
assert.Equal(t, n3, n1.NextSibling, "n1 and n3 should now be neighbors")
}
func Test_removeElement_AndKillChildren(t *testing.T) {
p := &html.Node{Type: html.DocumentNode}
n1 := eleWithData(1)
n2 := eleWithData(2)
n2.DataAtom = atom.Script // don't preserve children of this element
n3 := eleWithData(3)
c1 := eleWithData(4)
c2 := eleWithData(5)
p.AppendChild(n1)
p.AppendChild(n2)
p.AppendChild(n3)
n2.AppendChild(c1)
n2.AppendChild(c2)
c := NewBasicCleaner().(*cleaner)
result := c.removeElement(n2)
assert.Equal(t, result, n3, "returned node should be next sibling of removed node")
assert.Nil(t, n2.Parent, "n2 should have been removed from the graph")
assert.Equal(t, n1, n3.PrevSibling, "n3 should be next sib of n1")
}
func Test_removeElement_ReturnsNilIfItWasLastChild(t *testing.T) {
p := &html.Node{Type: html.DocumentNode}
n1 := eleWithData(1)
n2 := eleWithData(2)
p.AppendChild(n1)
p.AppendChild(n2)
c := NewBasicCleaner().(*cleaner)
result := c.removeElement(n2)
assert.Nil(t, n2.Parent, "n2 should have been removed from the graph")
assert.Nil(t, result, "returned node should be nil if it was a last child")
assert.Nil(t, n1.NextSibling, "n1 should have no more siblings")
}
func Test_Clean_All(t *testing.T) {
c := NewBasicCleaner().(*cleaner)
for input, expected := range basicWhitelistKillChildren {
doc, err := c.Clean(strings.NewReader(input))
var buf bytes.Buffer
html.Render(&buf, doc)
actual := buf.String()
assert.Nil(t, err, "unexpected error: %v", err)
assert.Equal(t, expected, actual, "expected %s but got %s", expected, actual)
}
c.preserveChildren = true
for input, expected := range basicWhitelistpreserveChildren {
doc, err := c.Clean(strings.NewReader(input))
var buf bytes.Buffer
html.Render(&buf, doc)
actual := buf.String()
assert.Nil(t, err, "unexpected error: %v", err)
assert.Equal(t, expected, actual, "expected %s but got %s", expected, actual)
}
}
func Test_CleanString_All(t *testing.T) {
c := NewBasicCleaner().(*cleaner)
for input, expected := range basicWhitelistKillChildren {
actual, err := c.CleanString(input)
assert.Nil(t, err, "unexpected error: %v", err)
assert.Equal(t, expected, actual, "expected %s but got %s", expected, actual)
}
c.preserveChildren = true
for input, expected := range basicWhitelistpreserveChildren {
actual, err := c.CleanString(input)
assert.Nil(t, err, "unexpected error: %v", err)
assert.Equal(t, expected, actual, "expected %s but got %s", expected, actual)
}
}
func Test_AddTags(t *testing.T) {
c := NewBasicCleaner().(*cleaner)
c.AddTags(
T(atom.Div, "id"),
T(atom.Table),
T(atom.Q, "id"),
)
def, ok := c.w[atom.Div]
assert.True(t, ok, "div tag should now appear in whitelist")
_, ok = def.AllowedAttrs["id"]
assert.True(t, ok, "attribute 'id' should be set for div tag")
def, ok = c.w[atom.Table]
assert.True(t, ok, "table tag should now appear in whitelist")
def, ok = c.w[atom.Q]
assert.True(t, ok, "q tag should still appear in whitelist")
_, ok = def.AllowedAttrs["id"]
assert.True(t, ok, "attribute 'id' should be set for q tag")
_, ok = def.AllowedAttrs["cite"]
assert.False(t, ok, "attribute 'cite' should no longer be set for q tag")
}
func Test_RemoveTags(t *testing.T) {
c := NewBasicCleaner().(*cleaner)
c.RemoveTags(atom.P, atom.Div)
_, ok := c.w[atom.P]
assert.False(t, ok, "p tag should no longer appear in whitelist")
_, ok = c.w[atom.Div]
assert.False(t, ok, "div tag should still not appear in whitelist")
}
func Test_PreserveChildren(t *testing.T) {
c := &cleaner{}
assert.False(t, c.preserveChildren, "default should be false")
c2 := c.PreserveChildren()
assert.True(t, c.preserveChildren, "default should be false")
assert.True(t, c2.(*cleaner).preserveChildren, "default should be false for returned value")
}
func Test_Clean_ShouldOverwriteEnforcedAttribute(t *testing.T) {
c := NewEmptyCleaner().AddTags(T(atom.A, "rel").EnforceAttr("rel", "nofollow"))
input := `<a rel="foobar">hello</a>`
doc, err := c.Clean(strings.NewReader(input))
assert.Nil(t, err, "err should be nil")
var buf bytes.Buffer
html.Render(&buf, doc)
actual := buf.String()
assert.Equal(t, `<a rel="nofollow">hello</a>`, actual, "should overwrite enforced attributes")
}
func Test_AllowedAttrNamesNormalized(t *testing.T) {
c := NewEmptyCleaner().AddTags(T(atom.A, " key/\r\n\t >\"'=nameバナナ \t"))
input := "<a key/\r\n\t >\"'=nameバナナ \t=\"bad\" keynameバナナ=\"good\">hello</a>"
doc, err := c.Clean(strings.NewReader(input))
assert.Nil(t, err, "err should be nil")
var buf bytes.Buffer
html.Render(&buf, doc)
actual := buf.String()
assert.Equal(t, "<a>"'=nameバナナ \t="bad" keynameバナナ="good">hello</a>", actual, "parser should reject certain characters")
}
func Test_Clean_AttrNames(t *testing.T) {
// note: T() will scrub these attr inputs, so we bypass the normalization process here
c := NewEmptyCleaner().AddTags(T(atom.A)).(*cleaner)
c.w[atom.A].AllowedAttrs["s\te"] = struct{}{}
c.w[atom.A].AllowedAttrs["s\re"] = struct{}{}
c.w[atom.A].AllowedAttrs["s\ne"] = struct{}{}
c.w[atom.A].AllowedAttrs["s e"] = struct{}{}
c.w[atom.A].AllowedAttrs["s/e"] = struct{}{}
c.w[atom.A].AllowedAttrs["s=e"] = struct{}{}
c.w[atom.A].AllowedAttrs["s'e"] = struct{}{}
c.w[atom.A].AllowedAttrs["s\"e"] = struct{}{}
c.w[atom.A].AllowedAttrs["s>e"] = struct{}{}
c.w[atom.A].AllowedAttrs["s\u0000e"] = struct{}{}
for input, expected := range attrNames {
doc, err := c.Clean(strings.NewReader(input))
var buf bytes.Buffer
html.Render(&buf, doc)
actual := buf.String()
assert.Nil(t, err, "unexpected error: %v", err)
assert.Equal(t, expected, actual, "expected %s but got %s", expected, actual)
}
}
func Test_Clean_EnforcedAttrValuesProperlyEscaped(t *testing.T) {
c := NewEmptyCleaner().AddTags(T(atom.P).EnforceAttr("foo", "bar\u0000\"&"))
input := `<p>hello</p>`
doc, err := c.Clean(strings.NewReader(input))
var buf bytes.Buffer
html.Render(&buf, doc)
actual := buf.String()
assert.Nil(t, err, "unexpected error: %v", err)
expected := "<p foo=\"bar\x00"&\">hello</p>"
assert.Equal(t, expected, actual, "expected %s but got %s", expected, actual)
}
func ele(attrs ...string) *html.Node {
attributes := []html.Attribute{}
for _, key := range attrs {
attributes = append(attributes, html.Attribute{Key: key})
}
return &html.Node{
Attr: attributes,
}
}
func Test_enforceProtocol_notEnforced(t *testing.T) {
tdef := &Tagdef{}
result, err := enforceProtocol(tdef, "href", "javascript:alert('hi!')")
assert.Nil(t, err)
assert.Equal(t, "javascript:alert('hi!')", result)
tdef.EnforcedProtocols = make(Protomap)
result, err = enforceProtocol(tdef, "href", "javascript:alert('hi!')")
assert.Nil(t, err)
assert.Equal(t, "javascript:alert('hi!')", result)
}
func Test_enforceProtocol_invalidURL(t *testing.T) {
tdef := T(atom.A, "href").EnforceProtocols("href", "http", "https")
_, err := enforceProtocol(tdef, "href", ":alert('hi!')")
assert.NotNil(t, err)
}
func Test_enforceProtocol_relativeLink(t *testing.T) {
tdef := T(atom.A, "href").EnforceProtocols("href", "http", "https")
_, err := enforceProtocol(tdef, "href", "/foo/bar")
assert.NotNil(t, err)
tdef.AllowRelativeLinks()
result, err := enforceProtocol(tdef, "href", "/foo/bar")
assert.Nil(t, err)
assert.Equal(t, "/foo/bar", result)
}
func Test_enforceProtocol_allowed(t *testing.T) {
tdef := T(atom.A, "href").EnforceProtocols("href", "https")
_, err := enforceProtocol(tdef, "href", "HTTP://google.com?q=alan+turing")
assert.NotNil(t, err)
result, err := enforceProtocol(tdef, "href", "HTTPS://google.com?q=alan+turing")
assert.Nil(t, err)
assert.Equal(t, "https://google.com?q=alan+turing", result)
tdef.EnforceProtocols("href", "https", "mailto")
result, err = enforceProtocol(tdef, "href", "MaIlTo:[email protected]")
assert.Nil(t, err)
assert.Equal(t, "mailto:[email protected]", result)
result, err = enforceProtocol(tdef, "href", "javascript:MaIlTo:[email protected]")
assert.NotNil(t, err)
}
func Test_Cleaner_protocolEnforcement(t *testing.T) {
c := NewBasicCleaner()
for raw, expected := range protocolEnforcementTests {
doc, err := c.Clean(strings.NewReader(raw))
var buf bytes.Buffer
html.Render(&buf, doc)
actual := buf.String()
assert.Nil(t, err)
assert.Equal(t, expected, actual)
}
}
func eleWithData(datum int) *html.Node {
return &html.Node{
Data: strconv.Itoa(datum),
}
}
var basicWhitelistpreserveChildren = map[string]string{
`plain text`: `plain text`,
`plain text<!-- comment -->`: `plain text`,
`<p>plain text</p><div>more text</div>`: `<p>plain text</p>more text`,
`<SCRIPT SRC=http://ha.ckers.org/xss.js></SCRIPT>`: ``,
`<IMG SRC="javascript:alert('XSS');">`: ``,
`<IMG """><SCRIPT>alert("XSS")</SCRIPT>">`: `">`,
`<P """><SCRIPT>alert("XSS")</SCRIPT>">`: `<p>"></p>`,
`<p onmouseover="alert('xxs')">`: `<p></p>`,
`<P/XSS SRC="http://ha.ckers.org/xss.js"></SCRIPT>`: `<p></p>`,
`<<SCRIPT>alert("XSS");//<</SCRIPT>`: `<`,
`<BR SIZE="&{alert('XSS')}">`: `<br/>`,
`exp/*<A STYLE='no\xss:noxss("*//*");
xss:ex/*XSS*//*/*/pression(alert("XSS"))'>`: `exp/*<a rel="nofollow"></a>`,
`<!--[if gte IE 4]>
<SCRIPT>alert('XSS');</SCRIPT>
<![endif]-->`: ``,
`<a onmouseover="alert(document.cookie)">xxs link</a>`: `<a rel="nofollow">xxs link</a>`,
`<a onmouseover=alert(document.cookie)>xxs link</a>`: `<a rel="nofollow">xxs link</a>`,
`<a rel="foobar">http://google.com</a>`: `<a rel="nofollow">http://google.com</a>`,
}
var basicWhitelistKillChildren = map[string]string{
`plain text`: `plain text`,
`plain text<!-- comment -->`: `plain text`,
`<p>plain text</p><div>more text</div>`: `<p>plain text</p>`,
}
var attrNames = map[string]string{
"<a s\te=\"foo\">bar</a>": `<a>bar</a>`,
"<a s\re=\"foo\">bar</a>": `<a>bar</a>`,
"<a s\ne=\"foo\">bar</a>": `<a>bar</a>`,
"<a s\"e=\"foo\">bar</a>": `<a>bar</a>`,
"<a s=e=\"foo\">bar</a>": `<a>bar</a>`,
"<a s e=\"foo\">bar</a>": `<a>bar</a>`,
"<a s'e=\"foo\">bar</a>": `<a>bar</a>`,
"<a s/e=\"foo\">bar</a>": `<a>bar</a>`,
"<a s\u0000e=\"foo\">bar</a>": `<a>bar</a>`,
"<a s>e=\"foo\">bar</a>": "<a>e="foo">bar</a>", // > will close the anchor tag
}
var protocolEnforcementTests = map[string]string{
`<a href="http://google.com">link</a>`: `<a href="http://google.com" rel="nofollow">link</a>`,
`<a href="https://google.com">link</a>`: `<a href="https://google.com" rel="nofollow">link</a>`,
`<a href="mailto:[email protected]">link</a>`: `<a href="mailto:[email protected]" rel="nofollow">link</a>`,
`<a href="javascript:alert('hi!')">link</a>`: `<a rel="nofollow">link</a>`,
}
type badReader struct{}
func (br badReader) Read(p []byte) (n int, err error) {
return 0, errors.New("i've made a terrible mistake")
}