-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathx-xss-protection.go
92 lines (75 loc) · 2.43 KB
/
x-xss-protection.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
package helmet
import (
"fmt"
"net/http"
"strings"
)
// HeaderXXSSProtection is the X-XSS-Protection HTTP security header.
const HeaderXXSSProtection = "X-XSS-Protection"
// DirectiveModeBlock is the X-XSS-Protection mode=block directive.
const DirectiveModeBlock XXSSProtectionDirective = "mode=block"
// XXSSProtectionDirectiveXSSFiltering is the X-XSS-Protection XSSFiltering directive.
func XXSSProtectionDirectiveXSSFiltering(xssFiltering bool) XXSSProtectionDirective {
if xssFiltering {
return "1"
}
return "0"
}
// XXSSProtectionDirectiveReportURI is the X-XSS-Protection ReportURI directive.
func XXSSProtectionDirectiveReportURI(reportURI string) XXSSProtectionDirective {
if reportURI == "" {
return ""
}
return XXSSProtectionDirective(fmt.Sprintf(`report=%s`, reportURI))
}
type (
// XXSSProtectionDirective represents an X-XSS-Protection directive.
XXSSProtectionDirective string
// XXSSProtection represents the X-XSS-Protection HTTP security header.
XXSSProtection struct {
XSSFiltering bool
Mode XXSSProtectionDirective
ReportURI string
cache string
}
)
// NewXXSSProtection creates a new X-XSS-Protection.
func NewXXSSProtection(xssFiltering bool, mode XXSSProtectionDirective, reportURI string) *XXSSProtection {
return &XXSSProtection{
XSSFiltering: xssFiltering,
Mode: mode,
ReportURI: reportURI,
}
}
// EmptyXXSSProtection creates a blank slate X-XSS-Protection.
func EmptyXXSSProtection() *XXSSProtection {
return NewXXSSProtection(false, "", "")
}
func (xssp *XXSSProtection) String() string {
if len(xssp.cache) != 0 {
return xssp.cache
}
builder := []string{
string(XXSSProtectionDirectiveXSSFiltering(xssp.XSSFiltering)),
}
if xssp.Mode != "" {
builder = append(builder, string(DirectiveModeBlock))
}
if xssp.ReportURI != "" {
builder = append(builder, string(XXSSProtectionDirectiveReportURI(xssp.ReportURI)))
}
xssp.cache = strings.Join(builder, "; ")
return xssp.cache
}
// Empty returns whether the X-XSS-Protection is empty.
func (xssp *XXSSProtection) Empty() bool {
// no matter what, the only required info (XSS Filtering) will always be present
// true and false are the only options, and they are both valid
return false
}
// Header adds the X-XSS-Protection HTTP security header to the given http.ResponseWriter.
func (xssp *XXSSProtection) Header(w http.ResponseWriter) {
if !xssp.Empty() {
w.Header().Set(HeaderXXSSProtection, xssp.String())
}
}