sanitizer_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package markup_test
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. . "gogs.io/gogs/internal/markup"
  6. )
  7. func Test_Sanitizer(t *testing.T) {
  8. NewSanitizer()
  9. tests := []struct {
  10. input string
  11. expVal string
  12. }{
  13. // Regular
  14. {input: `<a onblur="alert(secret)" href="http://www.google.com">Google</a>`, expVal: `<a href="http://www.google.com" rel="nofollow">Google</a>`},
  15. // Code highlighting class
  16. {input: `<code class="random string"></code>`, expVal: `<code></code>`},
  17. {input: `<code class="language-random ui tab active menu attached animating sidebar following bar center"></code>`, expVal: `<code></code>`},
  18. {input: `<code class="language-go"></code>`, expVal: `<code class="language-go"></code>`},
  19. // Input checkbox
  20. {input: `<input type="hidden">`, expVal: ``},
  21. {input: `<input type="checkbox">`, expVal: `<input type="checkbox">`},
  22. {input: `<input checked disabled autofocus>`, expVal: `<input checked="" disabled="">`},
  23. // Data URIs: safe image types should be allowed
  24. {input: `<img src="data:image/png;base64,abc">`, expVal: `<img src="data:image/png;base64,abc">`},
  25. {input: `<img src="data:image/jpeg;base64,abc">`, expVal: `<img src="data:image/jpeg;base64,abc">`},
  26. {input: `<img src="data:image/gif;base64,abc">`, expVal: `<img src="data:image/gif;base64,abc">`},
  27. {input: `<img src="data:image/webp;base64,abc">`, expVal: `<img src="data:image/webp;base64,abc">`},
  28. // Data URIs: text/html must be stripped to prevent XSS (GHSA-xrcr-gmf5-2r8j)
  29. {input: `<a href="data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4=">Click</a>`, expVal: `Click`},
  30. {input: `<a href="data:text/html,<script>alert(1)</script>">XSS</a>`, expVal: `XSS`},
  31. {input: `<img src="data:text/html;base64,abc">`, expVal: ``},
  32. // Data URIs: SVG must be stripped (can contain embedded JavaScript)
  33. {input: `<img src="data:image/svg+xml;base64,abc">`, expVal: ``},
  34. }
  35. for _, test := range tests {
  36. t.Run(test.input, func(t *testing.T) {
  37. assert.Equal(t, test.expVal, Sanitize(test.input))
  38. assert.Equal(t, test.expVal, string(SanitizeBytes([]byte(test.input))))
  39. })
  40. }
  41. }