gitea源码

sanitizer.go 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Copyright 2017 The Gogs Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package markup
  5. import (
  6. "regexp"
  7. "sync"
  8. "github.com/microcosm-cc/bluemonday"
  9. )
  10. // Sanitizer is a protection wrapper of *bluemonday.Policy which does not allow
  11. // any modification to the underlying policies once it's been created.
  12. type Sanitizer struct {
  13. defaultPolicy *bluemonday.Policy
  14. descriptionPolicy *bluemonday.Policy
  15. rendererPolicies map[string]*bluemonday.Policy
  16. allowAllRegex *regexp.Regexp
  17. }
  18. var (
  19. defaultSanitizer *Sanitizer
  20. defaultSanitizerOnce sync.Once
  21. )
  22. func GetDefaultSanitizer() *Sanitizer {
  23. defaultSanitizerOnce.Do(func() {
  24. defaultSanitizer = &Sanitizer{
  25. rendererPolicies: map[string]*bluemonday.Policy{},
  26. allowAllRegex: regexp.MustCompile(".+"),
  27. }
  28. for name, renderer := range renderers {
  29. sanitizerRules := renderer.SanitizerRules()
  30. if len(sanitizerRules) > 0 {
  31. policy := defaultSanitizer.createDefaultPolicy()
  32. defaultSanitizer.addSanitizerRules(policy, sanitizerRules)
  33. defaultSanitizer.rendererPolicies[name] = policy
  34. }
  35. }
  36. defaultSanitizer.defaultPolicy = defaultSanitizer.createDefaultPolicy()
  37. defaultSanitizer.descriptionPolicy = defaultSanitizer.createRepoDescriptionPolicy()
  38. })
  39. return defaultSanitizer
  40. }
  41. func ResetDefaultSanitizerForTesting() {
  42. defaultSanitizer = nil
  43. defaultSanitizerOnce = sync.Once{}
  44. }