-
Notifications
You must be signed in to change notification settings - Fork 427
/
Copy pathsecurity_mw.go
68 lines (56 loc) · 1.83 KB
/
security_mw.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
package main
import (
"net/http"
"strings"
"v2.staffjoy.com/environments"
)
// SecurityMiddleware is a negroni middleware that does nice things
// like HSTS and framebusting
type SecurityMiddleware struct {
Config environments.Config
}
// NewSecurityMiddleware returns a new middleware for security
func NewSecurityMiddleware(config environments.Config) *SecurityMiddleware {
return &SecurityMiddleware{
Config: config,
}
}
func (svc *SecurityMiddleware) ServeHTTP(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
// TODO - Determine how to force SSL. Depends on our load balancer config.
if origin := req.Header.Get("Origin"); origin != "" {
res.Header().Set("Access-Control-Allow-Origin", origin)
res.Header().Set("Access-Control-Allow-Credentials", "true")
res.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
res.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Cookie, Accept-Encoding, X-CSRF-Token, Authorization")
}
// Stop here if its Preflighted OPTIONS request
if req.Method == "OPTIONS" {
return
}
if svc.Config.Debug == false {
// Check if SSL
isSSL := strings.EqualFold(req.URL.Scheme, "https") || req.TLS != nil
if !isSSL {
// Check if Cloudflare proxied it
if req.Header.Get("X-Forwarded-Proto") == "https" {
isSSL = true
}
}
// If not SSL, then redirect.
if !isSSL {
url := req.URL
url.Scheme = "https"
url.Host = req.Host
http.Redirect(res, req, url.String(), http.StatusMovedPermanently)
return
}
// HSTS - force SSL
res.Header().Add("Strict-Transport-Security", "max-age=315360000; includeSubDomains; preload")
// No iFrames
res.Header().Add("X-Frame-Options", "DENY")
// Cross-site scripting protection
res.Header().Add("X-XSS-Protection", "1; mode=block")
}
next(res, req)
}