You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.1 KiB

  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Copyright 2017 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package markup
  6. import (
  7. "regexp"
  8. "sync"
  9. "code.gitea.io/gitea/modules/setting"
  10. "github.com/microcosm-cc/bluemonday"
  11. )
  12. // Sanitizer is a protection wrapper of *bluemonday.Policy which does not allow
  13. // any modification to the underlying policies once it's been created.
  14. type Sanitizer struct {
  15. policy *bluemonday.Policy
  16. init sync.Once
  17. }
  18. var sanitizer = &Sanitizer{}
  19. // NewSanitizer initializes sanitizer with allowed attributes based on settings.
  20. // Multiple calls to this function will only create one instance of Sanitizer during
  21. // entire application lifecycle.
  22. func NewSanitizer() {
  23. sanitizer.init.Do(func() {
  24. ReplaceSanitizer()
  25. })
  26. }
  27. // ReplaceSanitizer replaces the current sanitizer to account for changes in settings
  28. func ReplaceSanitizer() {
  29. sanitizer = &Sanitizer{}
  30. sanitizer.policy = bluemonday.UGCPolicy()
  31. // We only want to allow HighlightJS specific classes for code blocks
  32. sanitizer.policy.AllowAttrs("class").Matching(regexp.MustCompile(`^language-\w+$`)).OnElements("code")
  33. // Checkboxes
  34. sanitizer.policy.AllowAttrs("type").Matching(regexp.MustCompile(`^checkbox$`)).OnElements("input")
  35. sanitizer.policy.AllowAttrs("checked", "disabled").OnElements("input")
  36. // Custom URL-Schemes
  37. sanitizer.policy.AllowURLSchemes(setting.Markdown.CustomURLSchemes...)
  38. // Allow keyword markup
  39. sanitizer.policy.AllowAttrs("class").Matching(regexp.MustCompile(`^` + keywordClass + `$`)).OnElements("span")
  40. }
  41. // Sanitize takes a string that contains a HTML fragment or document and applies policy whitelist.
  42. func Sanitize(s string) string {
  43. NewSanitizer()
  44. return sanitizer.policy.Sanitize(s)
  45. }
  46. // SanitizeBytes takes a []byte slice that contains a HTML fragment or document and applies policy whitelist.
  47. func SanitizeBytes(b []byte) []byte {
  48. if len(b) == 0 {
  49. // nothing to sanitize
  50. return b
  51. }
  52. NewSanitizer()
  53. return sanitizer.policy.SanitizeBytes(b)
  54. }