code.gitea.io/gitea@v1.22.3/modules/markup/sanitizer.go (about)

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