headers.go
34 lines1
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
package security
import (
"fmt"
"net/http"
)
// headers is the internal middleware that sets security response headers.
func headers(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nonce := NonceFrom(r.Context())
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
if nonce != "" {
csp := fmt.Sprintf(
"default-src 'self'; "+
"script-src 'nonce-%s' 'strict-dynamic' 'unsafe-inline' https:; "+
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com https://fonts.gstatic.com; "+
"img-src 'self' data: https:; "+
"font-src 'self' https://fonts.gstatic.com; "+
"connect-src 'self'; "+
"frame-ancestors 'none'; object-src 'none'; base-uri 'self'",
nonce,
)
w.Header().Set("Content-Security-Policy", csp)
}
next.ServeHTTP(w, r)
})
}