├── .github └── workflows │ ├── lint.yaml │ └── test.yaml ├── .gitignore ├── .golangci.yaml ├── LICENSE ├── Makefile ├── README.md ├── csp.go ├── csp_test.go ├── cspbuilder ├── builder.go ├── builder_test.go ├── directive_builder.go └── directive_builder_test.go ├── doc.go ├── go.mod ├── go.sum ├── secure.go └── secure_test.go /.github/workflows/lint.yaml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - master 5 | - v1 6 | pull_request: 7 | branches: 8 | - "**" 9 | name: Linter 10 | jobs: 11 | golangci: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | with: 16 | path: src/github.com/unrolled/secure 17 | - uses: golangci/golangci-lint-action@v6 18 | with: 19 | working-directory: src/github.com/unrolled/secure 20 | -------------------------------------------------------------------------------- /.github/workflows/test.yaml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - master 5 | - v1 6 | pull_request: 7 | branches: 8 | - "**" 9 | name: Tests 10 | jobs: 11 | tests: 12 | strategy: 13 | matrix: 14 | go-version: [1.18.x, 1.19.x, 1.20.x, 1.21.x, 1.22.x, 1.23.x] 15 | os: [ubuntu-latest] 16 | runs-on: ${{ matrix.os }} 17 | steps: 18 | - uses: actions/checkout@v4 19 | - uses: actions/setup-go@v5 20 | with: 21 | go-version: ${{ matrix.go-version }} 22 | - run: make ci 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | 25 | *.pem 26 | .DS_Store 27 | *.swp 28 | -------------------------------------------------------------------------------- /.golangci.yaml: -------------------------------------------------------------------------------- 1 | run: 2 | timeout: 10m 3 | modules-download-mode: readonly 4 | allow-parallel-runners: true 5 | 6 | linters: 7 | enable-all: true 8 | disable: 9 | - paralleltest 10 | - gochecknoglobals 11 | - exhaustruct 12 | - wrapcheck 13 | - tagliatelle 14 | - depguard 15 | - ireturn 16 | - funlen 17 | - varnamelen 18 | - gomnd 19 | - execinquery 20 | - copyloopvar 21 | - intrange 22 | - gocognit 23 | - lll 24 | - cyclop 25 | - gocyclo 26 | - testpackage 27 | - err113 28 | - nestif 29 | - maintidx 30 | - contextcheck 31 | - perfsprint 32 | - exportloopref 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Cory Jacobsen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: help test ci 2 | .DEFAULT_GOAL := help 3 | 4 | help: ## Displays this help message. 5 | @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST) 6 | 7 | test: ## Runs the tests, vetting, and golangci linter. 8 | golangci-lint run ./... 9 | go test -v -cover -race -count=1 ./... 10 | go vet . 11 | 12 | ci: ## Runs on the tests and vetting checks (specific for CI). 13 | go test -cover -race -count=1 ./... 14 | go vet ./... 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Secure [![GoDoc](https://pkg.go.dev/badge/github.com/unrolled/secure)](http://godoc.org/github.com/unrolled/secure) [![Test](https://github.com/unrolled/secure/actions/workflows/test.yaml/badge.svg)](https://github.com/unrolled/secure/actions) 2 | 3 | Secure is an HTTP middleware for Go that facilitates some quick security wins. It's a standard net/http [Handler](http://golang.org/pkg/net/http/#Handler), and can be used with many [frameworks](#integration-examples) or directly with Go's net/http package. 4 | 5 | ## Usage 6 | 7 | ~~~ go 8 | // main.go 9 | package main 10 | 11 | import ( 12 | "net/http" 13 | 14 | "github.com/unrolled/secure" 15 | ) 16 | 17 | var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 18 | w.Write([]byte("hello world")) 19 | }) 20 | 21 | func main() { 22 | secureMiddleware := secure.New(secure.Options{ 23 | AllowedHosts: []string{"example\\.com", ".*\\.example\\.com"}, 24 | AllowedHostsAreRegex: true, 25 | HostsProxyHeaders: []string{"X-Forwarded-Host"}, 26 | SSLRedirect: true, 27 | SSLHost: "ssl.example.com", 28 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 29 | STSSeconds: 31536000, 30 | STSIncludeSubdomains: true, 31 | STSPreload: true, 32 | FrameDeny: true, 33 | ContentTypeNosniff: true, 34 | BrowserXssFilter: true, 35 | ContentSecurityPolicy: "script-src $NONCE", 36 | }) 37 | 38 | app := secureMiddleware.Handler(myHandler) 39 | http.ListenAndServe("127.0.0.1:3000", app) 40 | } 41 | ~~~ 42 | 43 | Be sure to include the Secure middleware as close to the top (beginning) as possible (but after logging and recovery). It's best to do the allowed hosts and SSL check before anything else. 44 | 45 | The above example will only allow requests with a host name of 'example.com', or 'ssl.example.com'. Also if the request is not HTTPS, it will be redirected to HTTPS with the host name of 'ssl.example.com'. 46 | Once those requirements are satisfied, it will add the following headers: 47 | ~~~ go 48 | Strict-Transport-Security: 31536000; includeSubdomains; preload 49 | X-Frame-Options: DENY 50 | X-Content-Type-Options: nosniff 51 | X-XSS-Protection: 1; mode=block 52 | Content-Security-Policy: script-src 'nonce-a2ZobGFoZg==' 53 | ~~~ 54 | 55 | ### Set the `IsDevelopment` option to `true` when developing! 56 | When `IsDevelopment` is true, the AllowedHosts, SSLRedirect, and STS header will not be in effect. This allows you to work in development/test mode and not have any annoying redirects to HTTPS (ie. development can happen on HTTP), or block `localhost` has a bad host. 57 | 58 | ### Available options 59 | Secure comes with a variety of configuration options (Note: these are not the default option values. See the defaults below.): 60 | 61 | ~~~ go 62 | // ... 63 | s := secure.New(secure.Options{ 64 | AllowedHosts: []string{"ssl.example.com"}, // AllowedHosts is a list of fully qualified domain names that are allowed. Default is empty list, which allows any and all host names. 65 | AllowedHostsAreRegex: false, // AllowedHostsAreRegex determines, if the provided AllowedHosts slice contains valid regular expressions. Default is false. 66 | AllowRequestFunc: nil, // AllowRequestFunc is a custom function type that allows you to determine if the request should proceed or not based on your own custom logic. Default is nil. 67 | HostsProxyHeaders: []string{"X-Forwarded-Hosts"}, // HostsProxyHeaders is a set of header keys that may hold a proxied hostname value for the request. 68 | SSLRedirect: true, // If SSLRedirect is set to true, then only allow HTTPS requests. Default is false. 69 | SSLTemporaryRedirect: false, // If SSLTemporaryRedirect is true, then a 307 will be used while redirecting. Default is false (301). 70 | SSLHost: "ssl.example.com", // SSLHost is the host name that is used to redirect HTTP requests to HTTPS. Default is "", which indicates to use the same host. 71 | SSLHostFunc: nil, // SSLHostFunc is a function pointer, the return value of the function is the host name that has same functionality as `SSHost`. Default is nil. If SSLHostFunc is nil, the `SSLHost` option will be used. 72 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, // SSLProxyHeaders is set of header keys with associated values that would indicate a valid HTTPS request. Useful when using Nginx: `map[string]string{"X-Forwarded-Proto": "https"}`. Default is blank map. 73 | STSSeconds: 31536000, // STSSeconds is the max-age of the Strict-Transport-Security header. Default is 0, which would NOT include the header. 74 | STSIncludeSubdomains: true, // If STSIncludeSubdomains is set to true, the `includeSubdomains` will be appended to the Strict-Transport-Security header. Default is false. 75 | STSPreload: true, // If STSPreload is set to true, the `preload` flag will be appended to the Strict-Transport-Security header. Default is false. 76 | ForceSTSHeader: false, // STS header is only included when the connection is HTTPS. If you want to force it to always be added, set to true. `IsDevelopment` still overrides this. Default is false. 77 | FrameDeny: true, // If FrameDeny is set to true, adds the X-Frame-Options header with the value of `DENY`. Default is false. 78 | CustomFrameOptionsValue: "SAMEORIGIN", // CustomFrameOptionsValue allows the X-Frame-Options header value to be set with a custom value. This overrides the FrameDeny option. Default is "". 79 | ContentTypeNosniff: true, // If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value `nosniff`. Default is false. 80 | BrowserXssFilter: true, // If BrowserXssFilter is true, adds the X-XSS-Protection header with the value `1; mode=block`. Default is false. 81 | CustomBrowserXssValue: "1; report=https://example.com/xss-report", // CustomBrowserXssValue allows the X-XSS-Protection header value to be set with a custom value. This overrides the BrowserXssFilter option. Default is "". 82 | ContentSecurityPolicy: "default-src 'self'", // ContentSecurityPolicy allows the Content-Security-Policy header value to be set with a custom value. Default is "". Passing a template string will replace `$NONCE` with a dynamic nonce value of 16 bytes for each request which can be later retrieved using the Nonce function. 83 | ReferrerPolicy: "same-origin", // ReferrerPolicy allows the Referrer-Policy header with the value to be set with a custom value. Default is "". 84 | FeaturePolicy: "vibrate 'none';", // Deprecated: this header has been renamed to PermissionsPolicy. FeaturePolicy allows the Feature-Policy header with the value to be set with a custom value. Default is "". 85 | PermissionsPolicy: "fullscreen=(), geolocation=()", // PermissionsPolicy allows the Permissions-Policy header with the value to be set with a custom value. Default is "". 86 | CrossOriginOpenerPolicy: "same-origin", // CrossOriginOpenerPolicy allows the Cross-Origin-Opener-Policy header with the value to be set with a custom value. Default is "". 87 | CrossOriginEmbedderPolicy: "require-corp", // CrossOriginEmbedderPolicy allows the Cross-Origin-Embedder-Policy header with the value to be set with a custom value. Default is "". 88 | CrossOriginResourcePolicy: "same-origin", // CrossOriginResourcePolicy allows the Cross-Origin-Resource-Policy header with the value to be set with a custom value. Default is "". 89 | XDNSPrefetchControl: "on", // XDNSPrefetchControl allows the X-DNS-Prefetch-Control header to be set via "on" or "off" keyword. Default is "". 90 | XPermittedCrossDomainPolicies: "none", // XPermittedCrossDomainPolicies allows the X-Permitted-Cross-Domain-Policies to be set with a custom value. Default is "". 91 | IsDevelopment: true, // This will cause the AllowedHosts, SSLRedirect, and STSSeconds/STSIncludeSubdomains options to be ignored during development. When deploying to production, be sure to set this to false. 92 | }) 93 | // ... 94 | ~~~ 95 | 96 | ### Default options 97 | These are the preset options for Secure: 98 | 99 | ~~~ go 100 | s := secure.New() 101 | 102 | // Is the same as the default configuration options: 103 | 104 | l := secure.New(secure.Options{ 105 | AllowedHosts: []string, 106 | AllowedHostsAreRegex: false, 107 | AllowRequestFunc: nil, 108 | HostsProxyHeaders: []string, 109 | SSLRedirect: false, 110 | SSLTemporaryRedirect: false, 111 | SSLHost: "", 112 | SSLProxyHeaders: map[string]string{}, 113 | STSSeconds: 0, 114 | STSIncludeSubdomains: false, 115 | STSPreload: false, 116 | ForceSTSHeader: false, 117 | FrameDeny: false, 118 | CustomFrameOptionsValue: "", 119 | ContentTypeNosniff: false, 120 | BrowserXssFilter: false, 121 | ContentSecurityPolicy: "", 122 | PublicKey: "", 123 | ReferrerPolicy: "", 124 | FeaturePolicy: "", 125 | PermissionsPolicy: "", 126 | CrossOriginOpenerPolicy: "", 127 | CrossOriginEmbedderPolicy: "", 128 | CrossOriginResourcePolicy: "", 129 | XDNSPrefetchControl: "", 130 | XPermittedCrossDomainPolicies: "", 131 | IsDevelopment: false, 132 | }) 133 | ~~~ 134 | The default bad host handler returns the following error: 135 | ~~~ go 136 | http.Error(w, "Bad Host", http.StatusInternalServerError) 137 | ~~~ 138 | Call `secure.SetBadHostHandler` to set your own custom handler. 139 | 140 | The default bad request handler returns the following error: 141 | ~~~ go 142 | http.Error(w, "Bad Request", http.StatusBadRequest) 143 | ~~~ 144 | Call `secure.SetBadRequestHandler` to set your own custom handler. 145 | 146 | ### Allow Request Function 147 | Secure allows you to set a custom function (`func(r *http.Request) bool`) for the `AllowRequestFunc` option. You can use this function as a custom filter to allow the request to continue or simply reject it. This can be handy if you need to do any dynamic filtering on any of the request properties. It should be noted that this function will be called on every request, so be sure to make your checks quick and not relying on time consuming external calls (or you will be slowing down all requests). See above on how to set a custom handler for the rejected requests. 148 | 149 | ### Redirecting HTTP to HTTPS 150 | If you want to redirect all HTTP requests to HTTPS, you can use the following example. 151 | 152 | ~~~ go 153 | // main.go 154 | package main 155 | 156 | import ( 157 | "log" 158 | "net/http" 159 | 160 | "github.com/unrolled/secure" 161 | ) 162 | 163 | var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 164 | w.Write([]byte("hello world")) 165 | }) 166 | 167 | func main() { 168 | secureMiddleware := secure.New(secure.Options{ 169 | SSLRedirect: true, 170 | SSLHost: "localhost:8443", // This is optional in production. The default behavior is to just redirect the request to the HTTPS protocol. Example: http://github.com/some_page would be redirected to https://github.com/some_page. 171 | }) 172 | 173 | app := secureMiddleware.Handler(myHandler) 174 | 175 | // HTTP 176 | go func() { 177 | log.Fatal(http.ListenAndServe(":8080", app)) 178 | }() 179 | 180 | // HTTPS 181 | // To generate a development cert and key, run the following from your *nix terminal: 182 | // go run $GOROOT/src/crypto/tls/generate_cert.go --host="localhost" 183 | log.Fatal(http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", app)) 184 | } 185 | ~~~ 186 | 187 | ### Strict Transport Security 188 | The STS header will only be sent on verified HTTPS connections (and when `IsDevelopment` is false). Be sure to set the `SSLProxyHeaders` option if your application is behind a proxy to ensure the proper behavior. If you need the STS header for all HTTP and HTTPS requests (which you [shouldn't](http://tools.ietf.org/html/rfc6797#section-7.2)), you can use the `ForceSTSHeader` option. Note that if `IsDevelopment` is true, it will still disable this header even when `ForceSTSHeader` is set to true. 189 | 190 | * The `preload` flag is required for domain inclusion in Chrome's [preload](https://hstspreload.appspot.com/) list. 191 | 192 | ### Content Security Policy 193 | You can utilize the CSP Builder to create your policies: 194 | 195 | ~~~ go 196 | import ( 197 | "github.com/unrolled/secure" 198 | "github.com/unrolled/secure/cspbuilder" 199 | ) 200 | 201 | cspBuilder := cspbuilder.Builder{ 202 | Directives: map[string][]string{ 203 | cspbuilder.DefaultSrc: {"self"}, 204 | cspbuilder.ScriptSrc: {"self", "www.google-analytics.com"}, 205 | cspbuilder.ImgSrc: {"*"}, 206 | }, 207 | } 208 | 209 | opt := secure.Options{ 210 | ContentSecurityPolicy: cspBuilder.MustBuild(), 211 | } 212 | ~~~ 213 | 214 | ## Integration examples 215 | 216 | ### [chi](https://github.com/pressly/chi) 217 | ~~~ go 218 | // main.go 219 | package main 220 | 221 | import ( 222 | "net/http" 223 | 224 | "github.com/pressly/chi" 225 | "github.com/unrolled/secure" 226 | ) 227 | 228 | func main() { 229 | secureMiddleware := secure.New(secure.Options{ 230 | FrameDeny: true, 231 | }) 232 | 233 | r := chi.NewRouter() 234 | r.Use(secureMiddleware.Handler) 235 | 236 | r.Get("/", func(w http.ResponseWriter, r *http.Request) { 237 | w.Write([]byte("X-Frame-Options header is now `DENY`.")) 238 | }) 239 | 240 | http.ListenAndServe("127.0.0.1:3000", r) 241 | } 242 | ~~~ 243 | 244 | ### [Echo](https://github.com/labstack/echo) 245 | ~~~ go 246 | // main.go 247 | package main 248 | 249 | import ( 250 | "net/http" 251 | 252 | "github.com/labstack/echo" 253 | "github.com/unrolled/secure" 254 | ) 255 | 256 | func main() { 257 | secureMiddleware := secure.New(secure.Options{ 258 | FrameDeny: true, 259 | }) 260 | 261 | e := echo.New() 262 | e.GET("/", func(c echo.Context) error { 263 | return c.String(http.StatusOK, "X-Frame-Options header is now `DENY`.") 264 | }) 265 | 266 | e.Use(echo.WrapMiddleware(secureMiddleware.Handler)) 267 | e.Logger.Fatal(e.Start("127.0.0.1:3000")) 268 | } 269 | ~~~ 270 | 271 | ### [Gin](https://github.com/gin-gonic/gin) 272 | ~~~ go 273 | // main.go 274 | package main 275 | 276 | import ( 277 | "github.com/gin-gonic/gin" 278 | "github.com/unrolled/secure" 279 | ) 280 | 281 | func main() { 282 | secureMiddleware := secure.New(secure.Options{ 283 | FrameDeny: true, 284 | }) 285 | secureFunc := func() gin.HandlerFunc { 286 | return func(c *gin.Context) { 287 | err := secureMiddleware.Process(c.Writer, c.Request) 288 | 289 | // If there was an error, do not continue. 290 | if err != nil { 291 | c.Abort() 292 | return 293 | } 294 | 295 | // Avoid header rewrite if response is a redirection. 296 | if status := c.Writer.Status(); status > 300 && status < 399 { 297 | c.Abort() 298 | } 299 | } 300 | }() 301 | 302 | router := gin.Default() 303 | router.Use(secureFunc) 304 | 305 | router.GET("/", func(c *gin.Context) { 306 | c.String(200, "X-Frame-Options header is now `DENY`.") 307 | }) 308 | 309 | router.Run("127.0.0.1:3000") 310 | } 311 | ~~~ 312 | 313 | ### [Goji](https://github.com/zenazn/goji) 314 | ~~~ go 315 | // main.go 316 | package main 317 | 318 | import ( 319 | "net/http" 320 | 321 | "github.com/unrolled/secure" 322 | "github.com/zenazn/goji" 323 | "github.com/zenazn/goji/web" 324 | ) 325 | 326 | func main() { 327 | secureMiddleware := secure.New(secure.Options{ 328 | FrameDeny: true, 329 | }) 330 | 331 | goji.Get("/", func(c web.C, w http.ResponseWriter, req *http.Request) { 332 | w.Write([]byte("X-Frame-Options header is now `DENY`.")) 333 | }) 334 | goji.Use(secureMiddleware.Handler) 335 | goji.Serve() // Defaults to ":8000". 336 | } 337 | ~~~ 338 | 339 | ### [Iris](https://github.com/kataras/iris) 340 | ~~~ go 341 | //main.go 342 | package main 343 | 344 | import ( 345 | "github.com/kataras/iris/v12" 346 | "github.com/unrolled/secure" 347 | ) 348 | 349 | func main() { 350 | app := iris.New() 351 | 352 | secureMiddleware := secure.New(secure.Options{ 353 | FrameDeny: true, 354 | }) 355 | 356 | app.Use(iris.FromStd(secureMiddleware.HandlerFuncWithNext)) 357 | // Identical to: 358 | // app.Use(func(ctx iris.Context) { 359 | // err := secureMiddleware.Process(ctx.ResponseWriter(), ctx.Request()) 360 | // 361 | // // If there was an error, do not continue. 362 | // if err != nil { 363 | // return 364 | // } 365 | // 366 | // ctx.Next() 367 | // }) 368 | 369 | app.Get("/home", func(ctx iris.Context) { 370 | ctx.Writef("X-Frame-Options header is now `%s`.", "DENY") 371 | }) 372 | 373 | app.Listen(":8080") 374 | } 375 | ~~~ 376 | 377 | ### [Mux](https://github.com/gorilla/mux) 378 | ~~~ go 379 | //main.go 380 | package main 381 | 382 | import ( 383 | "log" 384 | "net/http" 385 | 386 | "github.com/gorilla/mux" 387 | "github.com/unrolled/secure" 388 | ) 389 | 390 | func main() { 391 | secureMiddleware := secure.New(secure.Options{ 392 | FrameDeny: true, 393 | }) 394 | 395 | r := mux.NewRouter() 396 | r.Use(secureMiddleware.Handler) 397 | http.Handle("/", r) 398 | log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", 8080), nil)) 399 | } 400 | ~~~ 401 | 402 | ### [Negroni](https://github.com/urfave/negroni) 403 | Note this implementation has a special helper function called `HandlerFuncWithNext`. 404 | ~~~ go 405 | // main.go 406 | package main 407 | 408 | import ( 409 | "net/http" 410 | 411 | "github.com/urfave/negroni" 412 | "github.com/unrolled/secure" 413 | ) 414 | 415 | func main() { 416 | mux := http.NewServeMux() 417 | mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { 418 | w.Write([]byte("X-Frame-Options header is now `DENY`.")) 419 | }) 420 | 421 | secureMiddleware := secure.New(secure.Options{ 422 | FrameDeny: true, 423 | }) 424 | 425 | n := negroni.Classic() 426 | n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext)) 427 | n.UseHandler(mux) 428 | 429 | n.Run("127.0.0.1:3000") 430 | } 431 | ~~~ 432 | -------------------------------------------------------------------------------- /csp.go: -------------------------------------------------------------------------------- 1 | package secure 2 | 3 | import ( 4 | "context" 5 | "crypto/rand" 6 | "encoding/base64" 7 | "io" 8 | "net/http" 9 | ) 10 | 11 | type key int 12 | 13 | const cspNonceKey key = iota 14 | 15 | // CSPNonce returns the nonce value associated with the present request. 16 | // If no nonce has been generated it returns an empty string. 17 | func CSPNonce(c context.Context) string { 18 | if val, ok := c.Value(cspNonceKey).(string); ok { 19 | return val 20 | } 21 | 22 | return "" 23 | } 24 | 25 | // WithCSPNonce returns a context derived from ctx containing the given nonce as a value. 26 | // 27 | // This is intended for testing or more advanced use-cases; 28 | // For ordinary HTTP handlers, clients can rely on this package's middleware to populate the CSP nonce in the context. 29 | func WithCSPNonce(ctx context.Context, nonce string) context.Context { 30 | return context.WithValue(ctx, cspNonceKey, nonce) 31 | } 32 | 33 | func withCSPNonce(r *http.Request, nonce string) *http.Request { 34 | return r.WithContext(WithCSPNonce(r.Context(), nonce)) 35 | } 36 | 37 | func cspRandNonce() string { 38 | var buf [cspNonceSize]byte 39 | 40 | _, err := io.ReadFull(rand.Reader, buf[:]) 41 | if err != nil { 42 | panic("CSP Nonce rand.Reader failed" + err.Error()) 43 | } 44 | 45 | return base64.RawStdEncoding.EncodeToString(buf[:]) 46 | } 47 | -------------------------------------------------------------------------------- /csp_test.go: -------------------------------------------------------------------------------- 1 | package secure 2 | 3 | import ( 4 | "context" 5 | "encoding/base64" 6 | "fmt" 7 | "net/http" 8 | "net/http/httptest" 9 | "strings" 10 | "testing" 11 | ) 12 | 13 | //nolint:gochecknoglobals 14 | var cspHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 15 | _, _ = w.Write([]byte(CSPNonce(r.Context()))) 16 | }) 17 | 18 | func TestCSPNonce(t *testing.T) { 19 | csp := "default-src 'self' $NONCE; script-src 'strict-dynamic' $NONCE" 20 | cases := []struct { 21 | options Options 22 | headers []string 23 | }{ 24 | {Options{ContentSecurityPolicy: csp}, []string{"Content-Security-Policy"}}, 25 | {Options{ContentSecurityPolicyReportOnly: csp}, []string{"Content-Security-Policy-Report-Only"}}, 26 | { 27 | Options{ContentSecurityPolicy: csp, ContentSecurityPolicyReportOnly: csp}, 28 | []string{"Content-Security-Policy", "Content-Security-Policy-Report-Only"}, 29 | }, 30 | } 31 | 32 | for _, c := range cases { 33 | s := New(c.options) 34 | 35 | res := httptest.NewRecorder() 36 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 37 | 38 | s.Handler(cspHandler).ServeHTTP(res, req) 39 | 40 | expect(t, res.Code, http.StatusOK) 41 | 42 | for _, header := range c.headers { 43 | csp := res.Header().Get(header) 44 | expect(t, strings.Count(csp, "'nonce-"), 2) 45 | 46 | nonce := strings.Split(strings.Split(csp, "'")[3], "-")[1] 47 | // Test that the context has the CSP nonce, but only during the request. 48 | expect(t, res.Body.String(), nonce) 49 | expect(t, CSPNonce(req.Context()), "") 50 | 51 | _, err := base64.RawStdEncoding.DecodeString(nonce) 52 | expect(t, err, nil) 53 | 54 | expect(t, csp, fmt.Sprintf("default-src 'self' 'nonce-%[1]s'; script-src 'strict-dynamic' 'nonce-%[1]s'", nonce)) 55 | } 56 | } 57 | } 58 | 59 | func TestWithCSPNonce(t *testing.T) { 60 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 61 | 62 | nonce := "jdgKGHkbnd+/" 63 | 64 | expect(t, CSPNonce(withCSPNonce(req, nonce).Context()), nonce) 65 | } 66 | -------------------------------------------------------------------------------- /cspbuilder/builder.go: -------------------------------------------------------------------------------- 1 | package cspbuilder 2 | 3 | import ( 4 | "sort" 5 | "strings" 6 | ) 7 | 8 | const ( 9 | // Fetch Directives. 10 | ChildSrc = "child-src" 11 | ConnectSrc = "connect-src" 12 | DefaultSrc = "default-src" 13 | FontSrc = "font-src" 14 | FrameSrc = "frame-src" 15 | ImgSrc = "img-src" 16 | ManifestSrc = "manifest-src" 17 | MediaSrc = "media-src" 18 | ObjectSrc = "object-src" 19 | PrefetchSrc = "prefetch-src" 20 | ScriptSrc = "script-src" 21 | ScriptSrcAttr = "script-src-attr" 22 | ScriptSrcElem = "script-src-elem" 23 | StyleSrc = "style-src" 24 | StyleSrcAttr = "style-src-attr" 25 | StyleSrcElem = "style-src-elem" 26 | WorkerSrc = "worker-src" 27 | 28 | // Document Directives. 29 | BaseURI = "base-uri" 30 | Sandbox = "sandbox" 31 | 32 | // Navigation directives. 33 | FormAction = "form-action" 34 | FrameAncestors = "frame-ancestors" 35 | NavigateTo = "navigate-to" 36 | 37 | // Reporting directives. 38 | ReportURI = "report-uri" 39 | ReportTo = "report-to" 40 | 41 | // Other directives. 42 | RequireTrustedTypesFor = "require-trusted-types-for" 43 | TrustedTypes = "trusted-types" 44 | UpgradeInsecureRequests = "upgrade-insecure-requests" 45 | ) 46 | 47 | type Builder struct { 48 | Directives map[string]([]string) 49 | } 50 | 51 | // MustBuild is like Build but panics if an error occurs. 52 | func (builder *Builder) MustBuild() string { 53 | policy, err := builder.Build() 54 | if err != nil { 55 | panic(err) 56 | } 57 | 58 | return policy 59 | } 60 | 61 | // Build creates a content security policy string from the specified directives. 62 | // If any directive contains invalid values, an error is returned instead. 63 | func (builder *Builder) Build() (string, error) { 64 | var sb strings.Builder 65 | 66 | // Pull the directive keys out. 67 | directiveKeys := []string{} 68 | for key := range builder.Directives { 69 | directiveKeys = append(directiveKeys, key) 70 | } 71 | 72 | // Sort the policies: https://www.w3.org/TR/CSP3/#framework-policy 73 | sort.Strings(directiveKeys) 74 | 75 | for _, directive := range directiveKeys { 76 | if sb.Len() > 0 { 77 | sb.WriteString("; ") 78 | } 79 | 80 | switch directive { 81 | case Sandbox: 82 | err := buildDirectiveSandbox(&sb, builder.Directives[directive]) 83 | if err != nil { 84 | return "", err 85 | } 86 | case FrameAncestors: 87 | err := buildDirectiveFrameAncestors(&sb, builder.Directives[directive]) 88 | if err != nil { 89 | return "", err 90 | } 91 | case ReportTo: 92 | err := buildDirectiveReportTo(&sb, builder.Directives[directive]) 93 | if err != nil { 94 | return "", err 95 | } 96 | case RequireTrustedTypesFor: 97 | err := buildDirectiveRequireTrustedTypesFor(&sb, builder.Directives[directive]) 98 | if err != nil { 99 | return "", err 100 | } 101 | case TrustedTypes: 102 | err := buildDirectiveTrustedTypes(&sb, builder.Directives[directive]) 103 | if err != nil { 104 | return "", err 105 | } 106 | case UpgradeInsecureRequests: 107 | err := buildDirectiveUpgradeInsecureRequests(&sb, builder.Directives[directive]) 108 | if err != nil { 109 | return "", err 110 | } 111 | default: 112 | // no special handling of directive values needed 113 | err := buildDirectiveDefault(&sb, directive, builder.Directives[directive]) 114 | if err != nil { 115 | return "", err 116 | } 117 | } 118 | } 119 | 120 | return sb.String(), nil 121 | } 122 | -------------------------------------------------------------------------------- /cspbuilder/builder_test.go: -------------------------------------------------------------------------------- 1 | package cspbuilder 2 | 3 | import ( 4 | "reflect" 5 | "sort" 6 | "strings" 7 | "testing" 8 | ) 9 | 10 | func TestContentSecurityPolicyBuilder_Build_SingleDirective(t *testing.T) { 11 | tests := []struct { 12 | name string 13 | directiveName string 14 | directiveValues []string 15 | want string 16 | wantErr bool 17 | }{ 18 | { 19 | name: "empty default-src", 20 | directiveName: DefaultSrc, 21 | directiveValues: nil, 22 | want: "", 23 | wantErr: true, 24 | }, 25 | { 26 | name: "single default-src", 27 | directiveName: DefaultSrc, 28 | directiveValues: []string{"'self'"}, 29 | want: "default-src 'self'", 30 | }, 31 | { 32 | name: "multiple default-src", 33 | directiveName: DefaultSrc, 34 | directiveValues: []string{"'self'", "example.com", "*.example.com"}, 35 | want: "default-src 'self' example.com *.example.com", 36 | }, 37 | } 38 | for _, tt := range tests { 39 | t.Run(tt.name, func(t *testing.T) { 40 | builder := &Builder{ 41 | Directives: map[string][]string{ 42 | tt.directiveName: tt.directiveValues, 43 | }, 44 | } 45 | 46 | got, err := builder.Build() 47 | if (err != nil) != tt.wantErr { 48 | t.Errorf("ContentSecurityPolicyBuilder.Build() error = %v, wantErr %v", err, tt.wantErr) 49 | 50 | return 51 | } 52 | 53 | if got != tt.want { 54 | t.Errorf("ContentSecurityPolicyBuilder.Build() = '%v', want '%v'", got, tt.want) 55 | } 56 | }) 57 | } 58 | } 59 | 60 | func TestContentSecurityPolicyBuilder_Build_MultipleDirectives(t *testing.T) { 61 | tests := []struct { 62 | name string 63 | directives map[string]([]string) 64 | builder Builder 65 | wantParts []string 66 | wantFull string 67 | wantErr bool 68 | }{ 69 | { 70 | name: "multiple valid directives", 71 | directives: map[string]([]string){ 72 | "default-src": {"'self'", "example.com", "*.example.com"}, 73 | "sandbox": {"allow-scripts"}, 74 | "frame-ancestors": {"'self'", "http://*.example.com"}, 75 | "report-to": {"group1"}, 76 | "require-trusted-types-for": {"'script'"}, 77 | "trusted-types": {"policy-1", "policy-#=_/@.%", "'allow-duplicates'"}, 78 | "upgrade-insecure-requests": nil, 79 | }, 80 | 81 | wantParts: []string{ 82 | "default-src 'self' example.com *.example.com", 83 | "sandbox allow-scripts", 84 | "frame-ancestors 'self' http://*.example.com", 85 | "report-to group1", 86 | "require-trusted-types-for 'script'", 87 | "trusted-types policy-1 policy-#=_/@.% 'allow-duplicates'", 88 | "upgrade-insecure-requests", 89 | }, 90 | 91 | wantFull: "default-src 'self' example.com *.example.com; frame-ancestors 'self' http://*.example.com; report-to group1; require-trusted-types-for 'script'; sandbox allow-scripts; trusted-types policy-1 policy-#=_/@.% 'allow-duplicates'; upgrade-insecure-requests", 92 | }, 93 | } 94 | for _, tt := range tests { 95 | t.Run(tt.name, func(t *testing.T) { 96 | builder := &Builder{ 97 | Directives: tt.directives, 98 | } 99 | 100 | got, err := builder.Build() 101 | if (err != nil) != tt.wantErr { 102 | t.Errorf("ContentSecurityPolicyBuilder.Build() error = %v, wantErr %v", err, tt.wantErr) 103 | 104 | return 105 | } 106 | 107 | if got != tt.wantFull { 108 | t.Errorf("ContentSecurityPolicyBuilder.Build() full = %v, but wanted %v", got, tt.wantFull) 109 | } 110 | 111 | { 112 | startsWithDirective := false 113 | 114 | for directive := range tt.directives { 115 | if strings.HasPrefix(got, directive) { 116 | startsWithDirective = true 117 | 118 | break 119 | } 120 | } 121 | 122 | if !startsWithDirective { 123 | t.Errorf("ContentSecurityPolicyBuilder.Build() = '%v', does not start with directive name", got) 124 | } 125 | } 126 | 127 | if strings.HasSuffix(got, " ") { 128 | t.Errorf("ContentSecurityPolicyBuilder.Build() = '%v', ends on whitespace", got) 129 | } 130 | 131 | if strings.HasSuffix(got, ";") { 132 | t.Errorf("ContentSecurityPolicyBuilder.Build() = '%v', ends on semi-colon", got) 133 | } 134 | 135 | // order of directives in created string is not guaranteed 136 | // check output contains all expected parts 137 | { 138 | gotParts := strings.Split(got, "; ") 139 | if len(gotParts) != len(tt.wantParts) { 140 | t.Errorf("Got %d parts, want %d", len(gotParts), len(tt.wantParts)) 141 | } 142 | 143 | sort.Slice(gotParts, func(i, j int) bool { 144 | return gotParts[i] < gotParts[j] 145 | }) 146 | sort.Slice(tt.wantParts, func(i, j int) bool { 147 | return tt.wantParts[i] < tt.wantParts[j] 148 | }) 149 | 150 | if !reflect.DeepEqual(gotParts, tt.wantParts) { 151 | t.Errorf("ContentSecurityPolicyBuilder.Build() = '%v', expected following parts %v", got, gotParts) 152 | } 153 | } 154 | }) 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /cspbuilder/directive_builder.go: -------------------------------------------------------------------------------- 1 | package cspbuilder 2 | 3 | import ( 4 | "fmt" 5 | "regexp" 6 | "strings" 7 | ) 8 | 9 | func buildDirectiveSandbox(sb *strings.Builder, values []string) error { 10 | if len(values) == 0 { 11 | sb.WriteString(Sandbox) 12 | 13 | return nil 14 | } 15 | 16 | if len(values) > 1 { 17 | return fmt.Errorf("too many values set for directive %s", Sandbox) 18 | } 19 | 20 | sandboxVal := values[0] 21 | 22 | switch sandboxVal { 23 | case "allow-downloads-without-user-activation": 24 | case "allow-downloads": 25 | case "allow-forms": 26 | case "allow-modals": 27 | case "allow-orientation-lock": 28 | case "allow-pointer-lock": 29 | case "allow-popups-to-escape-sandbox": 30 | case "allow-popups": 31 | case "allow-presentation": 32 | case "allow-same-origin": 33 | case "allow-scripts": 34 | case "allow-storage-access-by-user-activation": 35 | case "allow-top-navigation-by-user-activation": 36 | case "allow-top-navigation-to-custom-protocols": 37 | case "allow-top-navigation": 38 | default: 39 | return fmt.Errorf("unallowed value %s for directive %s", sandboxVal, Sandbox) 40 | } 41 | 42 | sb.WriteString(Sandbox) 43 | sb.WriteString(" ") 44 | sb.WriteString(sandboxVal) 45 | 46 | return nil 47 | } 48 | 49 | func buildDirectiveFrameAncestors(sb *strings.Builder, values []string) error { 50 | if len(values) == 0 { 51 | return fmt.Errorf("no values set for directive %s", FrameAncestors) 52 | } 53 | 54 | sb.WriteString(FrameAncestors) 55 | 56 | for _, val := range values { 57 | if strings.HasPrefix(val, "'") && strings.HasSuffix(val, "'") { 58 | switch val { 59 | case "'self'": 60 | case "'none'": 61 | default: 62 | return fmt.Errorf("unallowed value %s for directive %s", val, FrameAncestors) 63 | } 64 | } 65 | 66 | sb.WriteString(" ") 67 | sb.WriteString(val) 68 | } 69 | 70 | return nil 71 | } 72 | 73 | func buildDirectiveReportTo(sb *strings.Builder, values []string) error { 74 | if len(values) == 0 { 75 | return fmt.Errorf("no values set for directive %s", ReportTo) 76 | } 77 | 78 | if len(values) > 1 { 79 | return fmt.Errorf("too many values set for directive %s", ReportTo) 80 | } 81 | 82 | sb.WriteString(ReportTo) 83 | sb.WriteString(" ") 84 | sb.WriteString(values[0]) 85 | 86 | return nil 87 | } 88 | 89 | func buildDirectiveRequireTrustedTypesFor(sb *strings.Builder, values []string) error { 90 | const allowedValue = "'script'" 91 | if len(values) != 1 || values[0] != allowedValue { 92 | return fmt.Errorf("value for directive %s must be %s", RequireTrustedTypesFor, allowedValue) 93 | } 94 | 95 | sb.WriteString(RequireTrustedTypesFor) 96 | sb.WriteString(" ") 97 | sb.WriteString(values[0]) 98 | 99 | return nil 100 | } 101 | 102 | func buildDirectiveTrustedTypes(sb *strings.Builder, values []string) error { 103 | sb.WriteString(TrustedTypes) 104 | 105 | for _, val := range values { 106 | sb.WriteString(" ") 107 | 108 | switch val { 109 | case "'none'": 110 | if len(values) != 1 { 111 | return fmt.Errorf("'none' must be only value for directive %s", TrustedTypes) 112 | } 113 | case "'allow-duplicates'": 114 | // nothing to do 115 | case "*": 116 | // nothing to do 117 | default: 118 | // value is policy name 119 | regex := regexp.MustCompile(`^[A-Za-z0-9\-#=_/@\.%]*$`) 120 | if !regex.MatchString(val) { 121 | return fmt.Errorf("unallowed value %s for directive %s", val, TrustedTypes) 122 | } 123 | } 124 | 125 | sb.WriteString(val) 126 | } 127 | 128 | return nil 129 | } 130 | 131 | func buildDirectiveUpgradeInsecureRequests(sb *strings.Builder, values []string) error { 132 | if len(values) != 0 { 133 | return fmt.Errorf("directive %s must not contain values", UpgradeInsecureRequests) 134 | } 135 | 136 | sb.WriteString(UpgradeInsecureRequests) 137 | 138 | return nil 139 | } 140 | 141 | func buildDirectiveDefault(sb *strings.Builder, directive string, values []string) error { 142 | if len(values) == 0 { 143 | return fmt.Errorf("no values set for directive %s", directive) 144 | } 145 | 146 | sb.WriteString(directive) 147 | 148 | for i := range values { 149 | sb.WriteString(" ") 150 | sb.WriteString(values[i]) 151 | } 152 | 153 | return nil 154 | } 155 | -------------------------------------------------------------------------------- /cspbuilder/directive_builder_test.go: -------------------------------------------------------------------------------- 1 | package cspbuilder 2 | 3 | import ( 4 | "strings" 5 | "testing" 6 | ) 7 | 8 | func TestBuildDirectiveSandbox(t *testing.T) { 9 | tests := []struct { 10 | name string 11 | values []string 12 | wantErr bool 13 | want string 14 | }{ 15 | { 16 | name: "empty", 17 | values: nil, 18 | want: "sandbox", 19 | }, 20 | { 21 | name: "allowed value", 22 | values: []string{"allow-scripts"}, 23 | want: "sandbox allow-scripts", 24 | }, 25 | { 26 | name: "unallowed value", 27 | values: []string{"invalid-sandbox-value"}, 28 | wantErr: true, 29 | }, 30 | { 31 | name: "too many values", 32 | values: []string{"allow-forms", "allow-modals"}, 33 | wantErr: true, 34 | }, 35 | } 36 | for _, tt := range tests { 37 | t.Run(tt.name, func(t *testing.T) { 38 | sb := &strings.Builder{} 39 | 40 | err := buildDirectiveSandbox(sb, tt.values) 41 | if tt.wantErr && err != nil { 42 | return 43 | } 44 | 45 | if (err != nil) != tt.wantErr { 46 | t.Errorf("buildDirectiveSandbox() error = %v, wantErr %v", err, tt.wantErr) 47 | } 48 | 49 | if got := sb.String(); got != tt.want { 50 | t.Errorf("buildDirectiveSandbox() result = '%v', want '%v'", got, tt.want) 51 | } 52 | }) 53 | } 54 | } 55 | 56 | func TestBuildDirectiveFrameAncestors(t *testing.T) { 57 | tests := []struct { 58 | name string 59 | values []string 60 | wantErr bool 61 | want string 62 | }{ 63 | { 64 | name: "empty", 65 | values: nil, 66 | wantErr: true, 67 | }, 68 | { 69 | name: "allowed value", 70 | values: []string{"'self'"}, 71 | want: "frame-ancestors 'self'", 72 | }, 73 | { 74 | name: "unallowed value", 75 | values: []string{"'invalid-frame-ancestors-value'"}, 76 | wantErr: true, 77 | }, 78 | } 79 | for _, tt := range tests { 80 | t.Run(tt.name, func(t *testing.T) { 81 | sb := &strings.Builder{} 82 | 83 | err := buildDirectiveFrameAncestors(sb, tt.values) 84 | if tt.wantErr && err != nil { 85 | return 86 | } 87 | 88 | if (err != nil) != tt.wantErr { 89 | t.Errorf("buildDirectiveFrameAncestors() error = %v, wantErr %v", err, tt.wantErr) 90 | } 91 | 92 | if got := sb.String(); got != tt.want { 93 | t.Errorf("buildDirectiveFrameAncestors() result = '%v', want '%v'", got, tt.want) 94 | } 95 | }) 96 | } 97 | } 98 | 99 | func TestBuildDirectiveReportTo(t *testing.T) { 100 | tests := []struct { 101 | name string 102 | values []string 103 | wantErr bool 104 | want string 105 | }{ 106 | { 107 | name: "empty", 108 | values: nil, 109 | wantErr: true, 110 | }, 111 | { 112 | name: "single value", 113 | values: []string{"group1"}, 114 | want: "report-to group1", 115 | }, 116 | { 117 | name: "too many values", 118 | values: []string{"group1", "group2"}, 119 | wantErr: true, 120 | }, 121 | } 122 | for _, tt := range tests { 123 | t.Run(tt.name, func(t *testing.T) { 124 | sb := &strings.Builder{} 125 | 126 | err := buildDirectiveReportTo(sb, tt.values) 127 | if tt.wantErr && err != nil { 128 | return 129 | } 130 | 131 | if (err != nil) != tt.wantErr { 132 | t.Errorf("buildDirectiveReportTo() error = %v, wantErr %v", err, tt.wantErr) 133 | } 134 | 135 | if got := sb.String(); got != tt.want { 136 | t.Errorf("buildDirectiveReportTo() result = '%v', want '%v'", got, tt.want) 137 | } 138 | }) 139 | } 140 | } 141 | 142 | func TestBuildDirectiveRequireTrustedTypesFor(t *testing.T) { 143 | tests := []struct { 144 | name string 145 | values []string 146 | wantErr bool 147 | want string 148 | }{ 149 | { 150 | name: "empty", 151 | values: nil, 152 | wantErr: true, 153 | }, 154 | { 155 | name: "allowed value", 156 | values: []string{"'script'"}, 157 | want: "require-trusted-types-for 'script'", 158 | }, 159 | { 160 | name: "unallowed value", 161 | values: []string{"*"}, 162 | wantErr: true, 163 | }, 164 | { 165 | name: "too many values", 166 | values: []string{"'script'", "*"}, 167 | wantErr: true, 168 | }, 169 | } 170 | for _, tt := range tests { 171 | t.Run(tt.name, func(t *testing.T) { 172 | sb := &strings.Builder{} 173 | 174 | err := buildDirectiveRequireTrustedTypesFor(sb, tt.values) 175 | if tt.wantErr && err != nil { 176 | return 177 | } 178 | 179 | if (err != nil) != tt.wantErr { 180 | t.Errorf("buildDirectiveRequireTrustedTypesFor() error = %v, wantErr %v", err, tt.wantErr) 181 | } 182 | 183 | if got := sb.String(); got != tt.want { 184 | t.Errorf("buildDirectiveRequireTrustedTypesFor() result = '%v', want '%v'", got, tt.want) 185 | } 186 | }) 187 | } 188 | } 189 | 190 | func TestBuildDirectiveTrustedTypes(t *testing.T) { 191 | tests := []struct { 192 | name string 193 | values []string 194 | wantErr bool 195 | want string 196 | }{ 197 | { 198 | name: "empty", 199 | values: nil, 200 | want: "trusted-types", 201 | }, 202 | { 203 | name: "none", 204 | values: []string{"'none'"}, 205 | want: "trusted-types 'none'", 206 | }, 207 | { 208 | name: "allowed value", 209 | values: []string{"policy-#=_/@.%"}, 210 | want: "trusted-types policy-#=_/@.%", 211 | }, 212 | { 213 | name: "unallowed value", 214 | values: []string{"unallowed-char-!"}, 215 | wantErr: true, 216 | }, 217 | { 218 | name: "multiple values", 219 | values: []string{"policy-1", "policy-#=_/@.%", "'allow-duplicates'"}, 220 | want: "trusted-types policy-1 policy-#=_/@.% 'allow-duplicates'", 221 | }, 222 | } 223 | for _, tt := range tests { 224 | t.Run(tt.name, func(t *testing.T) { 225 | sb := &strings.Builder{} 226 | 227 | err := buildDirectiveTrustedTypes(sb, tt.values) 228 | if tt.wantErr && err != nil { 229 | return 230 | } 231 | 232 | if (err != nil) != tt.wantErr { 233 | t.Errorf("buildDirectiveTrustedTypes() error = %v, wantErr %v", err, tt.wantErr) 234 | } 235 | 236 | if got := sb.String(); got != tt.want { 237 | t.Errorf("buildDirectiveTrustedTypes() result = '%v', want '%v'", got, tt.want) 238 | } 239 | }) 240 | } 241 | } 242 | 243 | func TestBuildDirectiveUpgradeInsecureRequests(t *testing.T) { 244 | tests := []struct { 245 | name string 246 | values []string 247 | wantErr bool 248 | want string 249 | }{ 250 | { 251 | name: "empty", 252 | values: nil, 253 | want: "upgrade-insecure-requests", 254 | }, 255 | { 256 | name: "value", 257 | values: []string{"upgrade-insecure-requests"}, 258 | wantErr: true, 259 | }, 260 | } 261 | for _, tt := range tests { 262 | t.Run(tt.name, func(t *testing.T) { 263 | sb := &strings.Builder{} 264 | 265 | err := buildDirectiveUpgradeInsecureRequests(sb, tt.values) 266 | if tt.wantErr && err != nil { 267 | return 268 | } 269 | 270 | if (err != nil) != tt.wantErr { 271 | t.Errorf("buildDirectiveUpgradeInsecureRequests() error = %v, wantErr %v", err, tt.wantErr) 272 | } 273 | 274 | if got := sb.String(); got != tt.want { 275 | t.Errorf("buildDirectiveUpgradeInsecureRequests() result = '%v', want '%v'", got, tt.want) 276 | } 277 | }) 278 | } 279 | } 280 | 281 | func TestBuildDirectiveDefault(t *testing.T) { 282 | tests := []struct { 283 | name string 284 | directive string 285 | values []string 286 | want string 287 | wantErr bool 288 | }{ 289 | { 290 | name: "empty", 291 | directive: DefaultSrc, 292 | values: nil, 293 | wantErr: true, 294 | }, 295 | { 296 | name: "single value", 297 | directive: DefaultSrc, 298 | values: []string{"value1"}, 299 | want: "default-src value1", 300 | }, 301 | { 302 | name: "multiple values", 303 | directive: DefaultSrc, 304 | values: []string{"value1", "value2"}, 305 | want: "default-src value1 value2", 306 | }, 307 | } 308 | for _, tt := range tests { 309 | t.Run(tt.name, func(t *testing.T) { 310 | sb := &strings.Builder{} 311 | 312 | err := buildDirectiveDefault(sb, tt.directive, tt.values) 313 | if tt.wantErr && err != nil { 314 | return 315 | } 316 | 317 | if (err != nil) != tt.wantErr { 318 | t.Errorf("buildDirectiveDefault() error = %v, wantErr %v", err, tt.wantErr) 319 | } 320 | 321 | if got := sb.String(); got != tt.want { 322 | t.Errorf("buildDirectiveDefault() result = '%v', want '%v'", got, tt.want) 323 | } 324 | }) 325 | } 326 | } 327 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package secure is an HTTP middleware for Go that facilitates some quick security wins. 3 | 4 | package main 5 | 6 | import ( 7 | "net/http" 8 | 9 | "github.com/unrolled/secure" 10 | ) 11 | 12 | var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 13 | w.Write([]byte("hello world")) 14 | }) 15 | 16 | func main() { 17 | secureMiddleware := secure.New(secure.Options{ 18 | AllowedHosts: []string{"www.example.com", "sub.example.com"}, 19 | SSLRedirect: true, 20 | }) 21 | 22 | app := secureMiddleware.Handler(myHandler) 23 | http.ListenAndServe("127.0.0.1:3000", app) 24 | } 25 | */ 26 | package secure 27 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/unrolled/secure 2 | 3 | go 1.13 4 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/unrolled/secure/ba42bc3377183ef4987b3f718ae3786938f457d6/go.sum -------------------------------------------------------------------------------- /secure.go: -------------------------------------------------------------------------------- 1 | package secure 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/http" 7 | "regexp" 8 | "strings" 9 | ) 10 | 11 | type secureCtxKey string 12 | 13 | const ( 14 | stsHeader = "Strict-Transport-Security" 15 | stsSubdomainString = "; includeSubDomains" 16 | stsPreloadString = "; preload" 17 | frameOptionsHeader = "X-Frame-Options" 18 | frameOptionsValue = "DENY" 19 | contentTypeHeader = "X-Content-Type-Options" 20 | contentTypeValue = "nosniff" 21 | xssProtectionHeader = "X-XSS-Protection" 22 | xssProtectionValue = "1; mode=block" 23 | cspHeader = "Content-Security-Policy" 24 | cspReportOnlyHeader = "Content-Security-Policy-Report-Only" 25 | hpkpHeader = "Public-Key-Pins" 26 | referrerPolicyHeader = "Referrer-Policy" 27 | featurePolicyHeader = "Feature-Policy" 28 | permissionsPolicyHeader = "Permissions-Policy" 29 | coopHeader = "Cross-Origin-Opener-Policy" 30 | coepHeader = "Cross-Origin-Embedder-Policy" 31 | corpHeader = "Cross-Origin-Resource-Policy" 32 | dnsPreFetchControlHeader = "X-DNS-Prefetch-Control" 33 | permittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies" 34 | ctxDefaultSecureHeaderKey = secureCtxKey("SecureResponseHeader") 35 | cspNonceSize = 16 36 | ) 37 | 38 | // SSLHostFunc is a custom function type that can be used to dynamically set the SSL host of a request. 39 | type SSLHostFunc func(host string) (newHost string) 40 | 41 | // AllowRequestFunc is a custom function type that can be used to dynamically determine if a request should proceed or not. 42 | type AllowRequestFunc func(r *http.Request) bool 43 | 44 | func defaultBadHostHandler(w http.ResponseWriter, _ *http.Request) { 45 | http.Error(w, "Bad Host", http.StatusInternalServerError) 46 | } 47 | 48 | func defaultBadRequestHandler(w http.ResponseWriter, _ *http.Request) { 49 | http.Error(w, "Bad Request", http.StatusBadRequest) 50 | } 51 | 52 | // Options is a struct for specifying configuration options for the secure.Secure middleware. 53 | type Options struct { 54 | // If BrowserXssFilter is true, adds the X-XSS-Protection header with the value `1; mode=block`. Default is false. 55 | BrowserXssFilter bool //nolint:stylecheck,revive 56 | // If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value `nosniff`. Default is false. 57 | ContentTypeNosniff bool 58 | // If ForceSTSHeader is set to true, the STS header will be added even when the connection is HTTP. Default is false. 59 | ForceSTSHeader bool 60 | // If FrameDeny is set to true, adds the X-Frame-Options header with the value of `DENY`. Default is false. 61 | FrameDeny bool 62 | // When developing, the AllowedHosts, SSL, and STS options can cause some unwanted effects. Usually testing happens on http, not https, and on localhost, not your production domain... so set this to true for dev environment. 63 | // If you would like your development environment to mimic production with complete Host blocking, SSL redirects, and STS headers, leave this as false. Default if false. 64 | IsDevelopment bool 65 | // nonceEnabled is used internally for dynamic nouces. 66 | nonceEnabled bool 67 | // If SSLRedirect is set to true, then only allow https requests. Default is false. 68 | SSLRedirect bool 69 | // If SSLForceHost is true and SSLHost is set, requests will be forced to use SSLHost even the ones that are already using SSL. Default is false. 70 | SSLForceHost bool 71 | // If SSLTemporaryRedirect is true, then a 307 will be used while redirecting. Default is false (301). 72 | SSLTemporaryRedirect bool 73 | // If STSIncludeSubdomains is set to true, the `includeSubdomains` will be appended to the Strict-Transport-Security header. Default is false. 74 | STSIncludeSubdomains bool 75 | // If STSPreload is set to true, the `preload` flag will be appended to the Strict-Transport-Security header. Default is false. 76 | STSPreload bool 77 | // ContentSecurityPolicy allows the Content-Security-Policy header value to be set with a custom value. Default is "". 78 | ContentSecurityPolicy string 79 | // ContentSecurityPolicyReportOnly allows the Content-Security-Policy-Report-Only header value to be set with a custom value. Default is "". 80 | ContentSecurityPolicyReportOnly string 81 | // CustomBrowserXssValue allows the X-XSS-Protection header value to be set with a custom value. This overrides the BrowserXssFilter option. Default is "". 82 | CustomBrowserXssValue string //nolint:stylecheck,revive 83 | // Passing a template string will replace `$NONCE` with a dynamic nonce value of 16 bytes for each request which can be later retrieved using the Nonce function. 84 | // Eg: script-src $NONCE -> script-src 'nonce-a2ZobGFoZg==' 85 | // CustomFrameOptionsValue allows the X-Frame-Options header value to be set with a custom value. This overrides the FrameDeny option. Default is "". 86 | CustomFrameOptionsValue string 87 | // ReferrerPolicy allows sites to control when browsers will pass the Referer header to other sites. Default is "". 88 | ReferrerPolicy string 89 | // FeaturePolicy allows to selectively enable and disable use of various browser features and APIs. Default is "". 90 | // Deprecated: This header has been renamed to Permissions-Policy. 91 | FeaturePolicy string 92 | // PermissionsPolicy allows to selectively enable and disable use of various browser features and APIs. Default is "". 93 | PermissionsPolicy string 94 | // CrossOriginOpenerPolicy allows you to ensure a top-level document does not share a browsing context group with cross-origin documents. Default is "". 95 | // Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy 96 | CrossOriginOpenerPolicy string 97 | // CrossOriginResourcePolicy header blocks others from loading your resources cross-origin in some cases. 98 | // Reference https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy 99 | CrossOriginResourcePolicy string 100 | // CrossOriginEmbedderPolicy header helps control what resources can be loaded cross-origin. 101 | // Reference https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy 102 | CrossOriginEmbedderPolicy string 103 | // XDNSPrefetchControl header helps control DNS prefetching, which can improve user privacy at the expense of performance. 104 | // Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control 105 | XDNSPrefetchControl string 106 | // XPermittedCrossDomainPolicies header tells some clients (mostly Adobe products) your domain's policy for loading cross-domain content. 107 | // Reference: https://owasp.org/www-project-secure-headers/ 108 | XPermittedCrossDomainPolicies string 109 | // SSLHost is the host name that is used to redirect http requests to https. Default is "", which indicates to use the same host. 110 | SSLHost string 111 | // AllowedHosts is a slice of fully qualified domain names that are allowed. Default is an empty slice, which allows any and all host names. 112 | AllowedHosts []string 113 | // AllowedHostsAreRegex determines, if the provided `AllowedHosts` slice contains valid regular expressions. If this flag is set to true, every request's host will be checked against these expressions. Default is false. 114 | AllowedHostsAreRegex bool 115 | // AllowRequestFunc is a custom function that allows you to determine if the request should proceed or not based on your own custom logic. Default is nil. 116 | AllowRequestFunc AllowRequestFunc `json:"-" toml:"-" yaml:"-"` 117 | // HostsProxyHeaders is a set of header keys that may hold a proxied hostname value for the request. 118 | HostsProxyHeaders []string 119 | // SSLHostFunc is a function pointer, the return value of the function is the host name that has same functionality as `SSHost`. Default is nil. 120 | // If SSLHostFunc is nil, the `SSLHost` option will be used. 121 | SSLHostFunc *SSLHostFunc `json:"-" toml:"-" yaml:"-"` 122 | // SSLProxyHeaders is set of header keys with associated values that would indicate a valid https request. Useful when using Nginx: `map[string]string{"X-Forwarded-Proto": "https"}`. Default is blank map. 123 | SSLProxyHeaders map[string]string 124 | // STSSeconds is the max-age of the Strict-Transport-Security header. Default is 0, which would NOT include the header. 125 | STSSeconds int64 126 | // SecureContextKey allows a custom key to be specified for context storage. 127 | SecureContextKey string 128 | } 129 | 130 | // Secure is a middleware that helps setup a few basic security features. A single secure.Options struct can be 131 | // provided to configure which features should be enabled, and the ability to override a few of the default values. 132 | type Secure struct { 133 | // Customize Secure with an Options struct. 134 | opt Options 135 | 136 | // badHostHandler is the handler used when an incorrect host is passed in. 137 | badHostHandler http.Handler 138 | 139 | // badRequestHandler is the handler used when the AllowRequestFunc rejects a request. 140 | badRequestHandler http.Handler 141 | 142 | // cRegexAllowedHosts saves the compiled regular expressions of the AllowedHosts 143 | // option for subsequent use in processRequest 144 | cRegexAllowedHosts []*regexp.Regexp 145 | 146 | // ctxSecureHeaderKey is the key used for context storage for request modification. 147 | ctxSecureHeaderKey secureCtxKey 148 | } 149 | 150 | // New constructs a new Secure instance with the supplied options. 151 | func New(options ...Options) *Secure { 152 | var o Options 153 | if len(options) == 0 { 154 | o = Options{} 155 | } else { 156 | o = options[0] 157 | } 158 | 159 | o.ContentSecurityPolicy = strings.ReplaceAll(o.ContentSecurityPolicy, "$NONCE", "'nonce-%[1]s'") 160 | o.ContentSecurityPolicyReportOnly = strings.ReplaceAll(o.ContentSecurityPolicyReportOnly, "$NONCE", "'nonce-%[1]s'") 161 | 162 | o.nonceEnabled = strings.Contains(o.ContentSecurityPolicy, "%[1]s") || strings.Contains(o.ContentSecurityPolicyReportOnly, "%[1]s") 163 | 164 | s := &Secure{ 165 | opt: o, 166 | badHostHandler: http.HandlerFunc(defaultBadHostHandler), 167 | badRequestHandler: http.HandlerFunc(defaultBadRequestHandler), 168 | } 169 | 170 | if s.opt.AllowedHostsAreRegex { 171 | // Test for invalid regular expressions in AllowedHosts 172 | for _, allowedHost := range o.AllowedHosts { 173 | regex, err := regexp.Compile(fmt.Sprintf("^%s$", allowedHost)) 174 | if err != nil { 175 | panic(fmt.Sprintf("Error parsing AllowedHost: %s", err)) 176 | } 177 | 178 | s.cRegexAllowedHosts = append(s.cRegexAllowedHosts, regex) 179 | } 180 | } 181 | 182 | s.ctxSecureHeaderKey = ctxDefaultSecureHeaderKey 183 | if len(s.opt.SecureContextKey) > 0 { 184 | s.ctxSecureHeaderKey = secureCtxKey(s.opt.SecureContextKey) 185 | } 186 | 187 | return s 188 | } 189 | 190 | // SetBadHostHandler sets the handler to call when secure rejects the host name. 191 | func (s *Secure) SetBadHostHandler(handler http.Handler) { 192 | s.badHostHandler = handler 193 | } 194 | 195 | // SetBadRequestHandler sets the handler to call when the AllowRequestFunc rejects a request. 196 | func (s *Secure) SetBadRequestHandler(handler http.Handler) { 197 | s.badRequestHandler = handler 198 | } 199 | 200 | // Handler implements the http.HandlerFunc for integration with the standard net/http lib. 201 | func (s *Secure) Handler(h http.Handler) http.Handler { 202 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 203 | // Let secure process the request. If it returns an error, 204 | // that indicates the request should not continue. 205 | responseHeader, r, err := s.processRequest(w, r) 206 | addResponseHeaders(responseHeader, w) 207 | 208 | // If there was an error, do not continue. 209 | if err != nil { 210 | return 211 | } 212 | 213 | h.ServeHTTP(w, r) 214 | }) 215 | } 216 | 217 | // HandlerForRequestOnly implements the http.HandlerFunc for integration with the standard net/http lib. 218 | // Note that this is for requests only and will not write any headers. 219 | func (s *Secure) HandlerForRequestOnly(h http.Handler) http.Handler { 220 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 221 | // Let secure process the request. If it returns an error, 222 | // that indicates the request should not continue. 223 | responseHeader, r, err := s.processRequest(w, r) 224 | if err != nil { 225 | return 226 | } 227 | 228 | // Save response headers in the request context. 229 | ctx := context.WithValue(r.Context(), s.ctxSecureHeaderKey, responseHeader) 230 | 231 | // No headers will be written to the ResponseWriter. 232 | h.ServeHTTP(w, r.WithContext(ctx)) 233 | }) 234 | } 235 | 236 | // HandlerFuncWithNext is a special implementation for Negroni, but could be used elsewhere. 237 | func (s *Secure) HandlerFuncWithNext(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { 238 | // Let secure process the request. If it returns an error, 239 | // that indicates the request should not continue. 240 | responseHeader, r, err := s.processRequest(w, r) 241 | addResponseHeaders(responseHeader, w) 242 | 243 | // If there was an error, do not call next. 244 | if err == nil && next != nil { 245 | next(w, r) 246 | } 247 | } 248 | 249 | // HandlerFuncWithNextForRequestOnly is a special implementation for Negroni, but could be used elsewhere. 250 | // Note that this is for requests only and will not write any headers. 251 | func (s *Secure) HandlerFuncWithNextForRequestOnly(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { 252 | // Let secure process the request. If it returns an error, 253 | // that indicates the request should not continue. 254 | responseHeader, r, err := s.processRequest(w, r) 255 | 256 | // If there was an error, do not call next. 257 | if err == nil && next != nil { 258 | // Save response headers in the request context 259 | ctx := context.WithValue(r.Context(), s.ctxSecureHeaderKey, responseHeader) 260 | 261 | // No headers will be written to the ResponseWriter. 262 | next(w, r.WithContext(ctx)) 263 | } 264 | } 265 | 266 | // addResponseHeaders Adds the headers from 'responseHeader' to the response. 267 | func addResponseHeaders(responseHeader http.Header, w http.ResponseWriter) { 268 | for key, values := range responseHeader { 269 | for _, value := range values { 270 | w.Header().Set(key, value) 271 | } 272 | } 273 | } 274 | 275 | // Process runs the actual checks and writes the headers in the ResponseWriter. 276 | func (s *Secure) Process(w http.ResponseWriter, r *http.Request) error { 277 | responseHeader, _, err := s.processRequest(w, r) 278 | addResponseHeaders(responseHeader, w) 279 | 280 | return err 281 | } 282 | 283 | // ProcessAndReturnNonce runs the actual checks and writes the headers in the ResponseWriter. 284 | // In addition, the generated nonce for the request is returned as well as the error value. 285 | func (s *Secure) ProcessAndReturnNonce(w http.ResponseWriter, r *http.Request) (string, error) { 286 | responseHeader, newR, err := s.processRequest(w, r) 287 | if err != nil { 288 | return "", err 289 | } 290 | 291 | addResponseHeaders(responseHeader, w) 292 | 293 | return CSPNonce(newR.Context()), err 294 | } 295 | 296 | // ProcessNoModifyRequest runs the actual checks but does not write the headers in the ResponseWriter. 297 | func (s *Secure) ProcessNoModifyRequest(w http.ResponseWriter, r *http.Request) (http.Header, *http.Request, error) { 298 | return s.processRequest(w, r) 299 | } 300 | 301 | // processRequest runs the actual checks on the request and returns an error if the middleware chain should stop. 302 | func (s *Secure) processRequest(w http.ResponseWriter, r *http.Request) (http.Header, *http.Request, error) { 303 | // Setup nonce if required. 304 | if s.opt.nonceEnabled { 305 | r = withCSPNonce(r, cspRandNonce()) 306 | } 307 | 308 | // Resolve the host for the request, using proxy headers if present. 309 | host := r.Host 310 | 311 | for _, header := range s.opt.HostsProxyHeaders { 312 | if h := r.Header.Get(header); h != "" { 313 | host = h 314 | 315 | break 316 | } 317 | } 318 | 319 | // Allowed hosts check. 320 | if len(s.opt.AllowedHosts) > 0 && !s.opt.IsDevelopment { 321 | isGoodHost := false 322 | 323 | if s.opt.AllowedHostsAreRegex { 324 | for _, allowedHost := range s.cRegexAllowedHosts { 325 | if match := allowedHost.MatchString(host); match { 326 | isGoodHost = true 327 | 328 | break 329 | } 330 | } 331 | } else { 332 | for _, allowedHost := range s.opt.AllowedHosts { 333 | if strings.EqualFold(allowedHost, host) { 334 | isGoodHost = true 335 | 336 | break 337 | } 338 | } 339 | } 340 | 341 | if !isGoodHost { 342 | s.badHostHandler.ServeHTTP(w, r) 343 | 344 | return nil, nil, fmt.Errorf("bad host name: %s", host) 345 | } 346 | } 347 | 348 | // Determine if we are on HTTPS. 349 | ssl := s.isSSL(r) 350 | 351 | // SSL check. 352 | if s.opt.SSLRedirect && !ssl && !s.opt.IsDevelopment { 353 | url := r.URL 354 | url.Scheme = "https" 355 | url.Host = host 356 | 357 | if s.opt.SSLHostFunc != nil { 358 | if h := (*s.opt.SSLHostFunc)(host); len(h) > 0 { 359 | url.Host = h 360 | } 361 | } else if len(s.opt.SSLHost) > 0 { 362 | url.Host = s.opt.SSLHost 363 | } 364 | 365 | status := http.StatusMovedPermanently 366 | if s.opt.SSLTemporaryRedirect { 367 | status = http.StatusTemporaryRedirect 368 | } 369 | 370 | http.Redirect(w, r, url.String(), status) 371 | 372 | return nil, nil, fmt.Errorf("redirecting to HTTPS") 373 | } 374 | 375 | if s.opt.SSLForceHost { 376 | tempSSLHost := host 377 | 378 | if s.opt.SSLHostFunc != nil { 379 | if h := (*s.opt.SSLHostFunc)(host); len(h) > 0 { 380 | tempSSLHost = h 381 | } 382 | } else if len(s.opt.SSLHost) > 0 { 383 | tempSSLHost = s.opt.SSLHost 384 | } 385 | 386 | if tempSSLHost != host { 387 | url := r.URL 388 | url.Scheme = "https" 389 | url.Host = tempSSLHost 390 | 391 | status := http.StatusMovedPermanently 392 | if s.opt.SSLTemporaryRedirect { 393 | status = http.StatusTemporaryRedirect 394 | } 395 | 396 | http.Redirect(w, r, url.String(), status) 397 | 398 | return nil, nil, fmt.Errorf("redirecting to HTTPS") 399 | } 400 | } 401 | 402 | // If the AllowRequestFunc is set, call it and exit early if needed. 403 | if s.opt.AllowRequestFunc != nil && !s.opt.AllowRequestFunc(r) { 404 | s.badRequestHandler.ServeHTTP(w, r) 405 | 406 | return nil, nil, fmt.Errorf("request not allowed") 407 | } 408 | 409 | // Create our header container. 410 | responseHeader := make(http.Header) 411 | 412 | // Strict Transport Security header. Only add header when we know it's an SSL connection. 413 | // See https://tools.ietf.org/html/rfc6797#section-7.2 for details. 414 | if s.opt.STSSeconds != 0 && (ssl || s.opt.ForceSTSHeader) && !s.opt.IsDevelopment { 415 | stsSub := "" 416 | if s.opt.STSIncludeSubdomains { 417 | stsSub = stsSubdomainString 418 | } 419 | 420 | if s.opt.STSPreload { 421 | stsSub += stsPreloadString 422 | } 423 | 424 | responseHeader.Set(stsHeader, fmt.Sprintf("max-age=%d%s", s.opt.STSSeconds, stsSub)) 425 | } 426 | 427 | // Frame Options header. 428 | if len(s.opt.CustomFrameOptionsValue) > 0 { 429 | responseHeader.Set(frameOptionsHeader, s.opt.CustomFrameOptionsValue) 430 | } else if s.opt.FrameDeny { 431 | responseHeader.Set(frameOptionsHeader, frameOptionsValue) 432 | } 433 | 434 | // Content Type Options header. 435 | if s.opt.ContentTypeNosniff { 436 | responseHeader.Set(contentTypeHeader, contentTypeValue) 437 | } 438 | 439 | // XSS Protection header. 440 | if len(s.opt.CustomBrowserXssValue) > 0 { 441 | responseHeader.Set(xssProtectionHeader, s.opt.CustomBrowserXssValue) 442 | } else if s.opt.BrowserXssFilter { 443 | responseHeader.Set(xssProtectionHeader, xssProtectionValue) 444 | } 445 | 446 | // Content Security Policy header. 447 | if len(s.opt.ContentSecurityPolicy) > 0 { 448 | if s.opt.nonceEnabled { 449 | responseHeader.Set(cspHeader, fmt.Sprintf(s.opt.ContentSecurityPolicy, CSPNonce(r.Context()))) 450 | } else { 451 | responseHeader.Set(cspHeader, s.opt.ContentSecurityPolicy) 452 | } 453 | } 454 | 455 | // Content Security Policy Report Only header. 456 | if len(s.opt.ContentSecurityPolicyReportOnly) > 0 { 457 | if s.opt.nonceEnabled { 458 | responseHeader.Set(cspReportOnlyHeader, fmt.Sprintf(s.opt.ContentSecurityPolicyReportOnly, CSPNonce(r.Context()))) 459 | } else { 460 | responseHeader.Set(cspReportOnlyHeader, s.opt.ContentSecurityPolicyReportOnly) 461 | } 462 | } 463 | 464 | // Referrer Policy header. 465 | if len(s.opt.ReferrerPolicy) > 0 { 466 | responseHeader.Set(referrerPolicyHeader, s.opt.ReferrerPolicy) 467 | } 468 | 469 | // Feature Policy header. 470 | if len(s.opt.FeaturePolicy) > 0 { 471 | responseHeader.Set(featurePolicyHeader, s.opt.FeaturePolicy) 472 | } 473 | 474 | // Permissions Policy header. 475 | if len(s.opt.PermissionsPolicy) > 0 { 476 | responseHeader.Set(permissionsPolicyHeader, s.opt.PermissionsPolicy) 477 | } 478 | 479 | // Cross Origin Opener Policy header. 480 | if len(s.opt.CrossOriginOpenerPolicy) > 0 { 481 | responseHeader.Set(coopHeader, s.opt.CrossOriginOpenerPolicy) 482 | } 483 | 484 | // Cross Origin Resource Policy header. 485 | if len(s.opt.CrossOriginResourcePolicy) > 0 { 486 | responseHeader.Set(corpHeader, s.opt.CrossOriginResourcePolicy) 487 | } 488 | 489 | // Cross-Origin-Embedder-Policy header. 490 | if len(s.opt.CrossOriginEmbedderPolicy) > 0 { 491 | responseHeader.Set(coepHeader, s.opt.CrossOriginEmbedderPolicy) 492 | } 493 | 494 | // X-DNS-Prefetch-Control header. 495 | switch strings.ToLower(s.opt.XDNSPrefetchControl) { 496 | case "on": 497 | responseHeader.Set(dnsPreFetchControlHeader, "on") 498 | case "off": 499 | responseHeader.Set(dnsPreFetchControlHeader, "off") 500 | } 501 | 502 | // X-Permitted-Cross-Domain-Policies header. 503 | if len(s.opt.XPermittedCrossDomainPolicies) > 0 { 504 | responseHeader.Set(permittedCrossDomainPolicies, s.opt.XPermittedCrossDomainPolicies) 505 | } 506 | 507 | return responseHeader, r, nil 508 | } 509 | 510 | // isSSL determine if we are on HTTPS. 511 | func (s *Secure) isSSL(r *http.Request) bool { 512 | ssl := strings.EqualFold(r.URL.Scheme, "https") || r.TLS != nil 513 | if !ssl { 514 | for k, v := range s.opt.SSLProxyHeaders { 515 | if r.Header.Get(k) == v { 516 | ssl = true 517 | 518 | break 519 | } 520 | } 521 | } 522 | 523 | return ssl 524 | } 525 | 526 | // ModifyResponseHeaders modifies the Response. 527 | // Used by http.ReverseProxy. 528 | func (s *Secure) ModifyResponseHeaders(res *http.Response) error { 529 | if res != nil && res.Request != nil { 530 | // Fix Location response header http to https: 531 | // When SSL is enabled, 532 | // And SSLHost is defined, 533 | // And the response location header includes the SSLHost as the domain with a trailing slash, 534 | // Or an exact match to the SSLHost. 535 | location := res.Header.Get("Location") 536 | if s.isSSL(res.Request) && 537 | len(s.opt.SSLHost) > 0 && 538 | (strings.HasPrefix(location, fmt.Sprintf("http://%s/", s.opt.SSLHost)) || location == fmt.Sprintf("http://%s", s.opt.SSLHost)) { 539 | location = strings.Replace(location, "http:", "https:", 1) 540 | res.Header.Set("Location", location) 541 | } 542 | 543 | responseHeader := res.Request.Context().Value(s.ctxSecureHeaderKey) 544 | if responseHeader != nil { 545 | headers, _ := responseHeader.(http.Header) 546 | for header, values := range headers { 547 | if len(values) > 0 { 548 | res.Header.Set(header, strings.Join(values, ",")) 549 | } 550 | } 551 | } 552 | } 553 | 554 | return nil 555 | } 556 | -------------------------------------------------------------------------------- /secure_test.go: -------------------------------------------------------------------------------- 1 | package secure 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "encoding/json" 7 | "net/http" 8 | "net/http/httptest" 9 | "reflect" 10 | "strings" 11 | "testing" 12 | ) 13 | 14 | const ( 15 | httpSchema = "http" 16 | httpsSchema = "https" 17 | exampleHost = "www.example.com" 18 | ) 19 | 20 | //nolint:gochecknoglobals 21 | var myHandler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { 22 | _, _ = w.Write([]byte("bar")) 23 | }) 24 | 25 | func TestNoConfigOnlyOneHeader(t *testing.T) { 26 | s := New() 27 | 28 | res := httptest.NewRecorder() 29 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://example.com/foo", nil) 30 | 31 | s.Handler(myHandler).ServeHTTP(res, req) 32 | 33 | expect(t, len(res.Header()), 1) 34 | expect(t, strings.Contains(res.Header().Get("Content-Type"), "text/plain"), true) 35 | } 36 | 37 | func TestNoConfig(t *testing.T) { 38 | s := New() 39 | 40 | res := httptest.NewRecorder() 41 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://example.com/foo", nil) 42 | 43 | s.Handler(myHandler).ServeHTTP(res, req) 44 | 45 | expect(t, res.Code, http.StatusOK) 46 | expect(t, res.Body.String(), "bar") 47 | } 48 | 49 | func TestNoAllowHosts(t *testing.T) { 50 | s := New(Options{ 51 | AllowedHosts: []string{}, 52 | }) 53 | 54 | res := httptest.NewRecorder() 55 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 56 | req.Host = exampleHost 57 | 58 | s.Handler(myHandler).ServeHTTP(res, req) 59 | 60 | expect(t, res.Code, http.StatusOK) 61 | expect(t, res.Body.String(), `bar`) 62 | } 63 | 64 | func TestGoodSingleAllowHosts(t *testing.T) { 65 | s := New(Options{ 66 | AllowedHosts: []string{"www.example.com"}, 67 | }) 68 | 69 | res := httptest.NewRecorder() 70 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 71 | req.Host = exampleHost 72 | 73 | s.Handler(myHandler).ServeHTTP(res, req) 74 | 75 | expect(t, res.Code, http.StatusOK) 76 | expect(t, res.Body.String(), `bar`) 77 | } 78 | 79 | func TestBadSingleAllowHosts(t *testing.T) { 80 | s := New(Options{ 81 | AllowedHosts: []string{"sub.example.com"}, 82 | }) 83 | 84 | res := httptest.NewRecorder() 85 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 86 | req.Host = exampleHost 87 | 88 | s.Handler(myHandler).ServeHTTP(res, req) 89 | 90 | expect(t, res.Code, http.StatusInternalServerError) 91 | } 92 | 93 | func TestRegexSingleAllowHosts(t *testing.T) { 94 | s := New(Options{ 95 | AllowedHosts: []string{"*\\.example\\.com"}, 96 | AllowedHostsAreRegex: true, 97 | }) 98 | 99 | res := httptest.NewRecorder() 100 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 101 | req.Host = exampleHost 102 | 103 | s.Handler(myHandler).ServeHTTP(res, req) 104 | 105 | expect(t, res.Code, http.StatusOK) 106 | expect(t, res.Body.String(), `bar`) 107 | } 108 | 109 | func TestRegexMultipleAllowHosts(t *testing.T) { 110 | s := New(Options{ 111 | AllowedHosts: []string{".+\\.example\\.com", ".*sub\\..+-awesome-example\\.com"}, 112 | AllowedHostsAreRegex: true, 113 | }) 114 | 115 | res := httptest.NewRecorder() 116 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 117 | req.Host = "sub.first-awesome-example.com" 118 | 119 | s.Handler(myHandler).ServeHTTP(res, req) 120 | 121 | expect(t, res.Code, http.StatusOK) 122 | expect(t, res.Body.String(), `bar`) 123 | 124 | res = httptest.NewRecorder() 125 | req, _ = http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 126 | req.Host = "test.sub.second-awesome-example.com" 127 | 128 | s.Handler(myHandler).ServeHTTP(res, req) 129 | 130 | expect(t, res.Code, http.StatusOK) 131 | expect(t, res.Body.String(), `bar`) 132 | 133 | res = httptest.NewRecorder() 134 | req, _ = http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 135 | req.Host = "test.sub.second-example.com" 136 | 137 | s.Handler(myHandler).ServeHTTP(res, req) 138 | 139 | expect(t, res.Code, http.StatusInternalServerError) 140 | } 141 | 142 | func TestInvalidRegexAllowHosts(t *testing.T) { 143 | defer func() { 144 | if r := recover(); r == nil { 145 | t.Errorf("The code did not panic") 146 | } 147 | }() 148 | New(Options{ 149 | AllowedHosts: []string{"[*.e"}, 150 | AllowedHostsAreRegex: true, 151 | }) 152 | } 153 | 154 | func TestGoodSingleAllowHostsProxyHeaders(t *testing.T) { 155 | s := New(Options{ 156 | AllowedHosts: []string{"www.example.com"}, 157 | HostsProxyHeaders: []string{"X-Proxy-Host"}, 158 | }) 159 | 160 | res := httptest.NewRecorder() 161 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 162 | req.Host = "example-internal-3" 163 | req.Header.Set("X-Proxy-Host", "www.example.com") 164 | 165 | s.Handler(myHandler).ServeHTTP(res, req) 166 | 167 | expect(t, res.Code, http.StatusOK) 168 | expect(t, res.Body.String(), `bar`) 169 | } 170 | 171 | func TestBadSingleAllowHostsProxyHeaders(t *testing.T) { 172 | s := New(Options{ 173 | AllowedHosts: []string{"sub.example.com"}, 174 | HostsProxyHeaders: []string{"X-Proxy-Host"}, 175 | }) 176 | 177 | res := httptest.NewRecorder() 178 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 179 | req.Host = "example-internal" 180 | req.Header.Set("X-Proxy-Host", "www.example.com") 181 | 182 | s.Handler(myHandler).ServeHTTP(res, req) 183 | 184 | expect(t, res.Code, http.StatusInternalServerError) 185 | } 186 | 187 | func TestGoodMultipleAllowHosts(t *testing.T) { 188 | s := New(Options{ 189 | AllowedHosts: []string{"www.example.com", "sub.example.com"}, 190 | }) 191 | 192 | res := httptest.NewRecorder() 193 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 194 | req.Host = exampleHost 195 | 196 | s.Handler(myHandler).ServeHTTP(res, req) 197 | 198 | expect(t, res.Code, http.StatusOK) 199 | expect(t, res.Body.String(), `bar`) 200 | } 201 | 202 | func TestBadMultipleAllowHosts(t *testing.T) { 203 | s := New(Options{ 204 | AllowedHosts: []string{"www.example.com", "sub.example.com"}, 205 | }) 206 | 207 | res := httptest.NewRecorder() 208 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 209 | req.Host = "www3.example.com" 210 | 211 | s.Handler(myHandler).ServeHTTP(res, req) 212 | 213 | expect(t, res.Code, http.StatusInternalServerError) 214 | } 215 | 216 | func TestAllowHostsInDevMode(t *testing.T) { 217 | s := New(Options{ 218 | AllowedHosts: []string{"www.example.com", "sub.example.com"}, 219 | IsDevelopment: true, 220 | }) 221 | 222 | res := httptest.NewRecorder() 223 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 224 | req.Host = exampleHost 225 | 226 | s.Handler(myHandler).ServeHTTP(res, req) 227 | 228 | expect(t, res.Code, http.StatusOK) 229 | } 230 | 231 | func TestBadHostHandler(t *testing.T) { 232 | s := New(Options{ 233 | AllowedHosts: []string{"www.example.com", "sub.example.com"}, 234 | }) 235 | 236 | badHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { 237 | http.Error(w, "BadHost", http.StatusInternalServerError) 238 | }) 239 | 240 | s.SetBadHostHandler(badHandler) 241 | 242 | res := httptest.NewRecorder() 243 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 244 | req.Host = "www3.example.com" 245 | 246 | s.Handler(myHandler).ServeHTTP(res, req) 247 | 248 | expect(t, res.Code, http.StatusInternalServerError) 249 | 250 | // http.Error outputs a new line character with the response. 251 | expect(t, res.Body.String(), "BadHost\n") 252 | } 253 | 254 | func TestSSL(t *testing.T) { 255 | s := New(Options{ 256 | SSLRedirect: true, 257 | }) 258 | 259 | res := httptest.NewRecorder() 260 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 261 | req.Host = exampleHost 262 | req.URL.Scheme = httpsSchema 263 | 264 | s.Handler(myHandler).ServeHTTP(res, req) 265 | 266 | expect(t, res.Code, http.StatusOK) 267 | } 268 | 269 | func TestSSLInDevMode(t *testing.T) { 270 | s := New(Options{ 271 | SSLRedirect: true, 272 | IsDevelopment: true, 273 | }) 274 | 275 | res := httptest.NewRecorder() 276 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 277 | req.Host = exampleHost 278 | req.URL.Scheme = httpSchema 279 | 280 | s.Handler(myHandler).ServeHTTP(res, req) 281 | 282 | expect(t, res.Code, http.StatusOK) 283 | } 284 | 285 | func TestBasicSSL(t *testing.T) { 286 | s := New(Options{ 287 | SSLRedirect: true, 288 | }) 289 | 290 | res := httptest.NewRecorder() 291 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 292 | req.Host = exampleHost 293 | req.URL.Scheme = httpSchema 294 | 295 | s.Handler(myHandler).ServeHTTP(res, req) 296 | 297 | expect(t, res.Code, http.StatusMovedPermanently) 298 | expect(t, res.Header().Get("Location"), "https://www.example.com/foo") 299 | } 300 | 301 | func TestBasicSSLWithHost(t *testing.T) { 302 | s := New(Options{ 303 | SSLRedirect: true, 304 | SSLHost: "secure.example.com", 305 | }) 306 | 307 | res := httptest.NewRecorder() 308 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 309 | req.Host = exampleHost 310 | req.URL.Scheme = httpSchema 311 | 312 | s.Handler(myHandler).ServeHTTP(res, req) 313 | 314 | expect(t, res.Code, http.StatusMovedPermanently) 315 | expect(t, res.Header().Get("Location"), "https://secure.example.com/foo") 316 | } 317 | 318 | func TestBasicSSLWithHostFunc(t *testing.T) { 319 | sslHostFunc := (func() SSLHostFunc { 320 | return func(host string) string { 321 | newHost := "" 322 | if host == exampleHost { 323 | newHost = "secure.example.com:8443" 324 | } else if host == "www.example.org" { 325 | newHost = "secure.example.org" 326 | } 327 | 328 | return newHost 329 | } 330 | })() 331 | s := New(Options{ 332 | SSLRedirect: true, 333 | SSLHostFunc: &sslHostFunc, 334 | }) 335 | 336 | // test www.example.com 337 | res := httptest.NewRecorder() 338 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 339 | req.Host = exampleHost 340 | req.URL.Scheme = httpSchema 341 | 342 | s.Handler(myHandler).ServeHTTP(res, req) 343 | 344 | expect(t, res.Code, http.StatusMovedPermanently) 345 | expect(t, res.Header().Get("Location"), "https://secure.example.com:8443/foo") 346 | 347 | // test www.example.org 348 | res = httptest.NewRecorder() 349 | req, _ = http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 350 | req.Host = "www.example.org" 351 | req.URL.Scheme = httpSchema 352 | 353 | s.Handler(myHandler).ServeHTTP(res, req) 354 | 355 | expect(t, res.Code, http.StatusMovedPermanently) 356 | expect(t, res.Header().Get("Location"), "https://secure.example.org/foo") 357 | 358 | // test other 359 | res = httptest.NewRecorder() 360 | req, _ = http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 361 | req.Host = "www.other.com" 362 | req.URL.Scheme = httpSchema 363 | 364 | s.Handler(myHandler).ServeHTTP(res, req) 365 | 366 | expect(t, res.Code, http.StatusMovedPermanently) 367 | expect(t, res.Header().Get("Location"), "https://www.other.com/foo") 368 | } 369 | 370 | func TestBadProxySSL(t *testing.T) { 371 | s := New(Options{ 372 | SSLRedirect: true, 373 | }) 374 | 375 | res := httptest.NewRecorder() 376 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 377 | req.Host = exampleHost 378 | req.URL.Scheme = httpSchema 379 | req.Header.Add("X-Forwarded-Proto", "https") 380 | 381 | s.Handler(myHandler).ServeHTTP(res, req) 382 | 383 | expect(t, res.Code, http.StatusMovedPermanently) 384 | expect(t, res.Header().Get("Location"), "https://www.example.com/foo") 385 | } 386 | 387 | func TestCustomProxySSL(t *testing.T) { 388 | s := New(Options{ 389 | SSLRedirect: true, 390 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 391 | }) 392 | 393 | res := httptest.NewRecorder() 394 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 395 | req.Host = exampleHost 396 | req.URL.Scheme = httpSchema 397 | req.Header.Add("X-Forwarded-Proto", "https") 398 | 399 | s.Handler(myHandler).ServeHTTP(res, req) 400 | 401 | expect(t, res.Code, http.StatusOK) 402 | } 403 | 404 | func TestCustomProxySSLInDevMode(t *testing.T) { 405 | s := New(Options{ 406 | SSLRedirect: true, 407 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 408 | IsDevelopment: true, 409 | }) 410 | 411 | res := httptest.NewRecorder() 412 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 413 | req.Host = exampleHost 414 | req.URL.Scheme = httpSchema 415 | req.Header.Add("X-Forwarded-Proto", "http") 416 | 417 | s.Handler(myHandler).ServeHTTP(res, req) 418 | 419 | expect(t, res.Code, http.StatusOK) 420 | } 421 | 422 | func TestCustomProxyAndHostProxyHeadersWithRedirect(t *testing.T) { 423 | s := New(Options{ 424 | HostsProxyHeaders: []string{"X-Forwarded-Host"}, 425 | SSLRedirect: true, 426 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "http"}, 427 | }) 428 | 429 | res := httptest.NewRecorder() 430 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 431 | req.Host = "example-internal" 432 | req.URL.Scheme = httpSchema 433 | req.Header.Add("X-Forwarded-Proto", "https") 434 | req.Header.Add("X-Forwarded-Host", "www.example.com") 435 | 436 | s.Handler(myHandler).ServeHTTP(res, req) 437 | 438 | expect(t, res.Code, http.StatusMovedPermanently) 439 | expect(t, res.Header().Get("Location"), "https://www.example.com/foo") 440 | } 441 | 442 | func TestCustomProxyAndHostSSL(t *testing.T) { 443 | s := New(Options{ 444 | SSLRedirect: true, 445 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 446 | SSLHost: "secure.example.com", 447 | }) 448 | 449 | res := httptest.NewRecorder() 450 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 451 | req.Host = exampleHost 452 | req.URL.Scheme = httpSchema 453 | req.Header.Add("X-Forwarded-Proto", "https") 454 | 455 | s.Handler(myHandler).ServeHTTP(res, req) 456 | 457 | expect(t, res.Code, http.StatusOK) 458 | } 459 | 460 | func TestCustomBadProxyAndHostSSL(t *testing.T) { 461 | s := New(Options{ 462 | SSLRedirect: true, 463 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "superman"}, 464 | SSLHost: "secure.example.com", 465 | }) 466 | 467 | res := httptest.NewRecorder() 468 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 469 | req.Host = exampleHost 470 | req.URL.Scheme = httpSchema 471 | req.Header.Add("X-Forwarded-Proto", "https") 472 | 473 | s.Handler(myHandler).ServeHTTP(res, req) 474 | 475 | expect(t, res.Code, http.StatusMovedPermanently) 476 | expect(t, res.Header().Get("Location"), "https://secure.example.com/foo") 477 | } 478 | 479 | func TestCustomBadProxyAndHostSSLWithTempRedirect(t *testing.T) { 480 | s := New(Options{ 481 | SSLRedirect: true, 482 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "superman"}, 483 | SSLHost: "secure.example.com", 484 | SSLTemporaryRedirect: true, 485 | }) 486 | 487 | res := httptest.NewRecorder() 488 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 489 | req.Host = exampleHost 490 | req.URL.Scheme = httpSchema 491 | req.Header.Add("X-Forwarded-Proto", "https") 492 | 493 | s.Handler(myHandler).ServeHTTP(res, req) 494 | 495 | expect(t, res.Code, http.StatusTemporaryRedirect) 496 | expect(t, res.Header().Get("Location"), "https://secure.example.com/foo") 497 | } 498 | 499 | func TestStsHeaderWithNoSSL(t *testing.T) { 500 | s := New(Options{ 501 | STSSeconds: 315360000, 502 | }) 503 | 504 | res := httptest.NewRecorder() 505 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 506 | 507 | s.Handler(myHandler).ServeHTTP(res, req) 508 | 509 | expect(t, res.Code, http.StatusOK) 510 | expect(t, res.Header().Get("Strict-Transport-Security"), "") 511 | } 512 | 513 | func TestStsHeaderWithNoSSLButWithForce(t *testing.T) { 514 | s := New(Options{ 515 | STSSeconds: 315360000, 516 | ForceSTSHeader: true, 517 | }) 518 | 519 | res := httptest.NewRecorder() 520 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 521 | 522 | s.Handler(myHandler).ServeHTTP(res, req) 523 | 524 | expect(t, res.Code, http.StatusOK) 525 | expect(t, res.Header().Get("Strict-Transport-Security"), "max-age=315360000") 526 | } 527 | 528 | func TestStsHeaderWithNoSSLButWithForceForRequestOnly(t *testing.T) { 529 | s := New(Options{ 530 | STSSeconds: 315360000, 531 | ForceSTSHeader: true, 532 | }) 533 | 534 | res := httptest.NewRecorder() 535 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 536 | 537 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 538 | 539 | expect(t, res.Code, http.StatusOK) 540 | expect(t, res.Header().Get("Strict-Transport-Security"), "") 541 | } 542 | 543 | func TestStsHeaderWithNoSSLButWithForceAndIsDev(t *testing.T) { 544 | s := New(Options{ 545 | STSSeconds: 315360000, 546 | ForceSTSHeader: true, 547 | IsDevelopment: true, 548 | }) 549 | 550 | res := httptest.NewRecorder() 551 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 552 | 553 | s.Handler(myHandler).ServeHTTP(res, req) 554 | 555 | expect(t, res.Code, http.StatusOK) 556 | expect(t, res.Header().Get("Strict-Transport-Security"), "") 557 | } 558 | 559 | func TestStsHeaderWithSSL(t *testing.T) { 560 | s := New(Options{ 561 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 562 | STSSeconds: 315360000, 563 | }) 564 | 565 | res := httptest.NewRecorder() 566 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 567 | req.URL.Scheme = httpSchema 568 | req.Header.Add("X-Forwarded-Proto", "https") 569 | 570 | s.Handler(myHandler).ServeHTTP(res, req) 571 | 572 | expect(t, res.Code, http.StatusOK) 573 | expect(t, res.Header().Get("Strict-Transport-Security"), "max-age=315360000") 574 | } 575 | 576 | func TestStsHeaderWithSSLForRequestOnly(t *testing.T) { 577 | s := New(Options{ 578 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 579 | STSSeconds: 315360000, 580 | }) 581 | 582 | res := httptest.NewRecorder() 583 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 584 | req.URL.Scheme = httpSchema 585 | req.Header.Add("X-Forwarded-Proto", "https") 586 | 587 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 588 | 589 | expect(t, res.Code, http.StatusOK) 590 | expect(t, res.Header().Get("Strict-Transport-Security"), "") 591 | } 592 | 593 | func TestStsHeaderInDevMode(t *testing.T) { 594 | s := New(Options{ 595 | STSSeconds: 315360000, 596 | IsDevelopment: true, 597 | }) 598 | 599 | res := httptest.NewRecorder() 600 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 601 | req.URL.Scheme = httpsSchema 602 | 603 | s.Handler(myHandler).ServeHTTP(res, req) 604 | 605 | expect(t, res.Code, http.StatusOK) 606 | expect(t, res.Header().Get("Strict-Transport-Security"), "") 607 | } 608 | 609 | func TestStsHeaderWithSubdomains(t *testing.T) { 610 | s := New(Options{ 611 | STSSeconds: 315360000, 612 | STSIncludeSubdomains: true, 613 | }) 614 | 615 | res := httptest.NewRecorder() 616 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 617 | req.URL.Scheme = httpsSchema 618 | 619 | s.Handler(myHandler).ServeHTTP(res, req) 620 | 621 | expect(t, res.Code, http.StatusOK) 622 | expect(t, res.Header().Get("Strict-Transport-Security"), "max-age=315360000; includeSubDomains") 623 | } 624 | 625 | func TestStsHeaderWithSubdomainsForRequestOnly(t *testing.T) { 626 | s := New(Options{ 627 | STSSeconds: 315360000, 628 | STSIncludeSubdomains: true, 629 | }) 630 | 631 | res := httptest.NewRecorder() 632 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 633 | req.URL.Scheme = httpsSchema 634 | 635 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 636 | 637 | expect(t, res.Code, http.StatusOK) 638 | expect(t, res.Header().Get("Strict-Transport-Security"), "") 639 | } 640 | 641 | func TestStsHeaderWithPreload(t *testing.T) { 642 | s := New(Options{ 643 | STSSeconds: 315360000, 644 | STSPreload: true, 645 | }) 646 | 647 | res := httptest.NewRecorder() 648 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 649 | req.URL.Scheme = httpsSchema 650 | 651 | s.Handler(myHandler).ServeHTTP(res, req) 652 | 653 | expect(t, res.Code, http.StatusOK) 654 | expect(t, res.Header().Get("Strict-Transport-Security"), "max-age=315360000; preload") 655 | } 656 | 657 | func TestStsHeaderWithPreloadForRequest(t *testing.T) { 658 | s := New(Options{ 659 | STSSeconds: 315360000, 660 | STSPreload: true, 661 | }) 662 | 663 | res := httptest.NewRecorder() 664 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 665 | req.URL.Scheme = httpsSchema 666 | 667 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 668 | 669 | expect(t, res.Code, http.StatusOK) 670 | expect(t, res.Header().Get("Strict-Transport-Security"), "") 671 | } 672 | 673 | func TestStsHeaderWithSubdomainsWithPreload(t *testing.T) { 674 | s := New(Options{ 675 | STSSeconds: 315360000, 676 | STSIncludeSubdomains: true, 677 | STSPreload: true, 678 | }) 679 | 680 | res := httptest.NewRecorder() 681 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 682 | req.URL.Scheme = httpsSchema 683 | 684 | s.Handler(myHandler).ServeHTTP(res, req) 685 | 686 | expect(t, res.Code, http.StatusOK) 687 | expect(t, res.Header().Get("Strict-Transport-Security"), "max-age=315360000; includeSubDomains; preload") 688 | } 689 | 690 | func TestStsHeaderWithSubdomainsWithPreloadForRequestOnly(t *testing.T) { 691 | s := New(Options{ 692 | STSSeconds: 315360000, 693 | STSIncludeSubdomains: true, 694 | STSPreload: true, 695 | }) 696 | 697 | res := httptest.NewRecorder() 698 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 699 | req.URL.Scheme = httpsSchema 700 | 701 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 702 | 703 | expect(t, res.Code, http.StatusOK) 704 | expect(t, res.Header().Get("Strict-Transport-Security"), "") 705 | } 706 | 707 | func TestFrameDeny(t *testing.T) { 708 | s := New(Options{ 709 | FrameDeny: true, 710 | }) 711 | 712 | res := httptest.NewRecorder() 713 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 714 | 715 | s.Handler(myHandler).ServeHTTP(res, req) 716 | 717 | expect(t, res.Code, http.StatusOK) 718 | expect(t, res.Header().Get("X-Frame-Options"), "DENY") 719 | } 720 | 721 | func TestFrameDenyForRequestOnly(t *testing.T) { 722 | s := New(Options{ 723 | FrameDeny: true, 724 | }) 725 | 726 | res := httptest.NewRecorder() 727 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 728 | 729 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 730 | 731 | expect(t, res.Code, http.StatusOK) 732 | expect(t, res.Header().Get("X-Frame-Options"), "") 733 | } 734 | 735 | func TestCustomFrameValue(t *testing.T) { 736 | s := New(Options{ 737 | CustomFrameOptionsValue: "SAMEORIGIN", 738 | }) 739 | 740 | res := httptest.NewRecorder() 741 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 742 | 743 | s.Handler(myHandler).ServeHTTP(res, req) 744 | 745 | expect(t, res.Code, http.StatusOK) 746 | expect(t, res.Header().Get("X-Frame-Options"), "SAMEORIGIN") 747 | } 748 | 749 | func TestCustomFrameValueWithDeny(t *testing.T) { 750 | s := New(Options{ 751 | FrameDeny: true, 752 | CustomFrameOptionsValue: "SAMEORIGIN", 753 | }) 754 | 755 | res := httptest.NewRecorder() 756 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 757 | 758 | s.Handler(myHandler).ServeHTTP(res, req) 759 | 760 | expect(t, res.Code, http.StatusOK) 761 | expect(t, res.Header().Get("X-Frame-Options"), "SAMEORIGIN") 762 | } 763 | 764 | func TestCustomFrameValueWithDenyForRequestOnly(t *testing.T) { 765 | s := New(Options{ 766 | FrameDeny: true, 767 | CustomFrameOptionsValue: "SAMEORIGIN", 768 | }) 769 | 770 | res := httptest.NewRecorder() 771 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 772 | 773 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 774 | 775 | expect(t, res.Code, http.StatusOK) 776 | expect(t, res.Header().Get("X-Frame-Options"), "") 777 | } 778 | 779 | func TestContentNosniff(t *testing.T) { 780 | s := New(Options{ 781 | ContentTypeNosniff: true, 782 | }) 783 | 784 | res := httptest.NewRecorder() 785 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 786 | 787 | s.Handler(myHandler).ServeHTTP(res, req) 788 | 789 | expect(t, res.Code, http.StatusOK) 790 | expect(t, res.Header().Get("X-Content-Type-Options"), "nosniff") 791 | } 792 | 793 | func TestContentNosniffForRequestOnly(t *testing.T) { 794 | s := New(Options{ 795 | ContentTypeNosniff: true, 796 | }) 797 | 798 | res := httptest.NewRecorder() 799 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 800 | 801 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 802 | 803 | expect(t, res.Code, http.StatusOK) 804 | expect(t, res.Header().Get("X-Content-Type-Options"), "") 805 | } 806 | 807 | func TestXSSProtection(t *testing.T) { 808 | s := New(Options{ 809 | BrowserXssFilter: true, 810 | }) 811 | 812 | res := httptest.NewRecorder() 813 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 814 | 815 | s.Handler(myHandler).ServeHTTP(res, req) 816 | 817 | expect(t, res.Code, http.StatusOK) 818 | expect(t, res.Header().Get("X-XSS-Protection"), "1; mode=block") 819 | } 820 | 821 | func TestXSSProtectionForRequestOnly(t *testing.T) { 822 | s := New(Options{ 823 | BrowserXssFilter: true, 824 | }) 825 | 826 | res := httptest.NewRecorder() 827 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 828 | 829 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 830 | 831 | expect(t, res.Code, http.StatusOK) 832 | expect(t, res.Header().Get("X-XSS-Protection"), "") 833 | } 834 | 835 | func TestCustomXSSProtection(t *testing.T) { 836 | xssVal := "1; report=https://example.com" 837 | s := New(Options{ 838 | CustomBrowserXssValue: xssVal, 839 | }) 840 | 841 | res := httptest.NewRecorder() 842 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 843 | 844 | s.Handler(myHandler).ServeHTTP(res, req) 845 | 846 | expect(t, res.Code, http.StatusOK) 847 | expect(t, res.Header().Get("X-XSS-Protection"), xssVal) 848 | } 849 | 850 | func TestCustomXSSProtectionForRequestOnly(t *testing.T) { 851 | xssVal := "1; report=https://example.com" 852 | s := New(Options{ 853 | CustomBrowserXssValue: xssVal, 854 | }) 855 | 856 | res := httptest.NewRecorder() 857 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 858 | 859 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 860 | 861 | expect(t, res.Code, http.StatusOK) 862 | expect(t, res.Header().Get("X-XSS-Protection"), "") 863 | } 864 | 865 | func TestBothXSSProtection(t *testing.T) { 866 | xssVal := "0" 867 | s := New(Options{ 868 | BrowserXssFilter: true, 869 | CustomBrowserXssValue: xssVal, 870 | }) 871 | 872 | res := httptest.NewRecorder() 873 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 874 | 875 | s.Handler(myHandler).ServeHTTP(res, req) 876 | 877 | expect(t, res.Code, http.StatusOK) 878 | expect(t, res.Header().Get("X-XSS-Protection"), xssVal) 879 | } 880 | 881 | func TestBothXSSProtectionForRequestOnly(t *testing.T) { 882 | xssVal := "0" 883 | s := New(Options{ 884 | BrowserXssFilter: true, 885 | CustomBrowserXssValue: xssVal, 886 | }) 887 | 888 | res := httptest.NewRecorder() 889 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 890 | 891 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 892 | 893 | expect(t, res.Code, http.StatusOK) 894 | expect(t, res.Header().Get("X-XSS-Protection"), "") 895 | } 896 | 897 | func TestCsp(t *testing.T) { 898 | s := New(Options{ 899 | ContentSecurityPolicy: "default-src 'self'", 900 | }) 901 | 902 | res := httptest.NewRecorder() 903 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 904 | 905 | s.Handler(myHandler).ServeHTTP(res, req) 906 | 907 | expect(t, res.Code, http.StatusOK) 908 | expect(t, res.Header().Get("Content-Security-Policy"), "default-src 'self'") 909 | } 910 | 911 | func TestCspForRequestOnly(t *testing.T) { 912 | s := New(Options{ 913 | ContentSecurityPolicy: "default-src 'self'", 914 | }) 915 | 916 | res := httptest.NewRecorder() 917 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 918 | 919 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 920 | 921 | expect(t, res.Code, http.StatusOK) 922 | expect(t, res.Header().Get("Content-Security-Policy"), "") 923 | } 924 | 925 | func TestCspReportOnly(t *testing.T) { 926 | s := New(Options{ 927 | ContentSecurityPolicyReportOnly: "default-src 'self'", 928 | }) 929 | 930 | res := httptest.NewRecorder() 931 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 932 | 933 | s.Handler(myHandler).ServeHTTP(res, req) 934 | 935 | expect(t, res.Code, http.StatusOK) 936 | expect(t, res.Header().Get("Content-Security-Policy-Report-Only"), "default-src 'self'") 937 | } 938 | 939 | func TestCspReportOnlyForRequestOnly(t *testing.T) { 940 | s := New(Options{ 941 | ContentSecurityPolicyReportOnly: "default-src 'self'", 942 | }) 943 | 944 | res := httptest.NewRecorder() 945 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 946 | 947 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 948 | 949 | expect(t, res.Code, http.StatusOK) 950 | expect(t, res.Header().Get("Content-Security-Policy-Report-Only"), "") 951 | } 952 | 953 | func TestInlineSecure(t *testing.T) { 954 | s := New(Options{ 955 | FrameDeny: true, 956 | }) 957 | 958 | res := httptest.NewRecorder() 959 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 960 | 961 | handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 962 | s.HandlerFuncWithNext(w, r, nil) 963 | _, _ = w.Write([]byte("bar")) 964 | }) 965 | 966 | handler.ServeHTTP(res, req) 967 | 968 | expect(t, res.Code, http.StatusOK) 969 | expect(t, res.Header().Get("X-Frame-Options"), "DENY") 970 | } 971 | 972 | func TestInlineSecureForRequestOnly(t *testing.T) { 973 | s := New(Options{ 974 | FrameDeny: true, 975 | }) 976 | 977 | res := httptest.NewRecorder() 978 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 979 | 980 | handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 981 | s.HandlerFuncWithNextForRequestOnly(w, r, nil) 982 | _, _ = w.Write([]byte("bar")) 983 | }) 984 | 985 | handler.ServeHTTP(res, req) 986 | 987 | expect(t, res.Code, http.StatusOK) 988 | expect(t, res.Header().Get("X-Frame-Options"), "") 989 | } 990 | 991 | func TestReferrer(t *testing.T) { 992 | s := New(Options{ 993 | ReferrerPolicy: "same-origin", 994 | }) 995 | 996 | res := httptest.NewRecorder() 997 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 998 | 999 | s.Handler(myHandler).ServeHTTP(res, req) 1000 | 1001 | expect(t, res.Code, http.StatusOK) 1002 | expect(t, res.Header().Get("Referrer-Policy"), "same-origin") 1003 | } 1004 | 1005 | func TestReferrerForRequestOnly(t *testing.T) { 1006 | s := New(Options{ 1007 | ReferrerPolicy: "same-origin", 1008 | }) 1009 | 1010 | res := httptest.NewRecorder() 1011 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1012 | 1013 | s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) 1014 | 1015 | expect(t, res.Code, http.StatusOK) 1016 | expect(t, res.Header().Get("Referrer-Policy"), "") 1017 | } 1018 | 1019 | func TestFeaturePolicy(t *testing.T) { 1020 | s := New(Options{ 1021 | FeaturePolicy: "vibrate 'none';", 1022 | }) 1023 | 1024 | res := httptest.NewRecorder() 1025 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1026 | 1027 | s.Handler(myHandler).ServeHTTP(res, req) 1028 | 1029 | expect(t, res.Code, http.StatusOK) 1030 | expect(t, res.Header().Get("Feature-Policy"), "vibrate 'none';") 1031 | } 1032 | 1033 | func TestPermissionsPolicy(t *testing.T) { 1034 | s := New(Options{ 1035 | PermissionsPolicy: "geolocation=(self)", 1036 | }) 1037 | 1038 | res := httptest.NewRecorder() 1039 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1040 | 1041 | s.Handler(myHandler).ServeHTTP(res, req) 1042 | 1043 | expect(t, res.Code, http.StatusOK) 1044 | expect(t, res.Header().Get("Permissions-Policy"), "geolocation=(self)") 1045 | } 1046 | 1047 | func TestCrossOriginOpenerPolicy(t *testing.T) { 1048 | s := New(Options{ 1049 | CrossOriginOpenerPolicy: "same-origin", 1050 | }) 1051 | 1052 | res := httptest.NewRecorder() 1053 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1054 | 1055 | s.Handler(myHandler).ServeHTTP(res, req) 1056 | 1057 | expect(t, res.Code, http.StatusOK) 1058 | expect(t, res.Header().Get("Cross-Origin-Opener-Policy"), "same-origin") 1059 | } 1060 | 1061 | func TestCrossOriginEmbedderPolicy(t *testing.T) { 1062 | s := New(Options{ 1063 | CrossOriginEmbedderPolicy: "require-corp", 1064 | }) 1065 | 1066 | res := httptest.NewRecorder() 1067 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1068 | 1069 | s.Handler(myHandler).ServeHTTP(res, req) 1070 | 1071 | expect(t, res.Code, http.StatusOK) 1072 | expect(t, res.Header().Get("Cross-Origin-Embedder-Policy"), "require-corp") 1073 | } 1074 | 1075 | func TestCrossOriginResourcePolicy(t *testing.T) { 1076 | s := New(Options{ 1077 | CrossOriginResourcePolicy: "same-origin", 1078 | }) 1079 | 1080 | res := httptest.NewRecorder() 1081 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1082 | 1083 | s.Handler(myHandler).ServeHTTP(res, req) 1084 | 1085 | expect(t, res.Code, http.StatusOK) 1086 | expect(t, res.Header().Get("Cross-Origin-Resource-Policy"), "same-origin") 1087 | } 1088 | 1089 | func TestXDNSPreFetchControl(t *testing.T) { 1090 | s := New(Options{ 1091 | XDNSPrefetchControl: "on", 1092 | }) 1093 | 1094 | res := httptest.NewRecorder() 1095 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1096 | 1097 | s.Handler(myHandler).ServeHTTP(res, req) 1098 | 1099 | expect(t, res.Code, http.StatusOK) 1100 | expect(t, res.Header().Get("X-DNS-Prefetch-Control"), "on") 1101 | 1102 | k := New(Options{ 1103 | XDNSPrefetchControl: "off", 1104 | }) 1105 | 1106 | res = httptest.NewRecorder() 1107 | req, _ = http.NewRequestWithContext(context.Background(), http.MethodGet, "/bar", nil) 1108 | 1109 | k.Handler(myHandler).ServeHTTP(res, req) 1110 | 1111 | expect(t, res.Code, http.StatusOK) 1112 | expect(t, res.Header().Get("X-DNS-Prefetch-Control"), "off") 1113 | } 1114 | 1115 | func TestXPermittedCrossDomainPolicies(t *testing.T) { 1116 | s := New(Options{ 1117 | XPermittedCrossDomainPolicies: "none", 1118 | }) 1119 | 1120 | res := httptest.NewRecorder() 1121 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1122 | 1123 | s.Handler(myHandler).ServeHTTP(res, req) 1124 | 1125 | expect(t, res.Code, http.StatusOK) 1126 | expect(t, res.Header().Get("X-Permitted-Cross-Domain-Policies"), "none") 1127 | } 1128 | 1129 | func TestIsSSL(t *testing.T) { 1130 | s := New(Options{ 1131 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 1132 | }) 1133 | 1134 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1135 | expect(t, s.isSSL(req), false) 1136 | 1137 | req, _ = http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1138 | req.TLS = &tls.ConnectionState{ 1139 | CipherSuite: 16, 1140 | } 1141 | expect(t, s.isSSL(req), true) 1142 | 1143 | req, _ = http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1144 | req.URL.Scheme = httpsSchema 1145 | expect(t, s.isSSL(req), true) 1146 | 1147 | req, _ = http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1148 | req.Header.Add("X-Forwarded-Proto", "https") 1149 | expect(t, s.isSSL(req), true) 1150 | } 1151 | 1152 | func TestSSLForceHostWithHTTPS(t *testing.T) { 1153 | s := New(Options{ 1154 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 1155 | SSLHost: "secure.example.com", 1156 | SSLForceHost: true, 1157 | }) 1158 | 1159 | res := httptest.NewRecorder() 1160 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1161 | req.Host = exampleHost 1162 | req.URL.Scheme = httpsSchema 1163 | req.Header.Add("X-Forwarded-Proto", "https") 1164 | 1165 | s.Handler(myHandler).ServeHTTP(res, req) 1166 | 1167 | expect(t, res.Code, http.StatusMovedPermanently) 1168 | } 1169 | 1170 | func TestSSLForceHostWithHTTP(t *testing.T) { 1171 | s := New(Options{ 1172 | SSLHost: "secure.example.com", 1173 | SSLForceHost: true, 1174 | }) 1175 | 1176 | res := httptest.NewRecorder() 1177 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1178 | req.Host = exampleHost 1179 | req.URL.Scheme = httpSchema 1180 | req.Header.Add("X-Forwarded-Proto", "http") 1181 | 1182 | s.Handler(myHandler).ServeHTTP(res, req) 1183 | 1184 | expect(t, res.Code, http.StatusMovedPermanently) 1185 | } 1186 | 1187 | func TestSSLForceHostWithSSLRedirect(t *testing.T) { 1188 | s := New(Options{ 1189 | SSLRedirect: true, 1190 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 1191 | SSLHost: "secure.example.com", 1192 | SSLForceHost: true, 1193 | }) 1194 | 1195 | res := httptest.NewRecorder() 1196 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1197 | req.Host = exampleHost 1198 | req.URL.Scheme = httpsSchema 1199 | req.Header.Add("X-Forwarded-Proto", "https") 1200 | 1201 | s.Handler(myHandler).ServeHTTP(res, req) 1202 | 1203 | expect(t, res.Code, http.StatusMovedPermanently) 1204 | } 1205 | 1206 | func TestSSLForceHostTemporaryRedirect(t *testing.T) { 1207 | s := New(Options{ 1208 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 1209 | SSLHost: "secure.example.com", 1210 | SSLForceHost: true, 1211 | SSLTemporaryRedirect: true, 1212 | }) 1213 | 1214 | res := httptest.NewRecorder() 1215 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1216 | req.Host = exampleHost 1217 | req.URL.Scheme = httpsSchema 1218 | req.Header.Add("X-Forwarded-Proto", "https") 1219 | 1220 | s.Handler(myHandler).ServeHTTP(res, req) 1221 | 1222 | expect(t, res.Code, http.StatusTemporaryRedirect) 1223 | } 1224 | 1225 | func TestModifyResponseHeadersNoSSL(t *testing.T) { 1226 | s := New(Options{ 1227 | SSLRedirect: false, 1228 | }) 1229 | 1230 | res := &http.Response{} 1231 | res.Header = http.Header{"Location": []string{"http://example.com"}} 1232 | 1233 | err := s.ModifyResponseHeaders(res) 1234 | expect(t, err, nil) 1235 | 1236 | expect(t, res.Header.Get("Location"), "http://example.com") 1237 | } 1238 | 1239 | func TestModifyResponseHeadersWithSSLAndDifferentSSLHost(t *testing.T) { 1240 | s := New(Options{ 1241 | SSLRedirect: true, 1242 | SSLHost: "secure.example.com", 1243 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 1244 | }) 1245 | 1246 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1247 | req.Host = exampleHost 1248 | req.URL.Scheme = httpSchema 1249 | req.Header.Add("X-Forwarded-Proto", "https") 1250 | 1251 | res := &http.Response{} 1252 | res.Header = http.Header{"Location": []string{"http://example.com"}} 1253 | res.Request = req 1254 | 1255 | expect(t, res.Header.Get("Location"), "http://example.com") 1256 | 1257 | err := s.ModifyResponseHeaders(res) 1258 | expect(t, err, nil) 1259 | 1260 | expect(t, res.Header.Get("Location"), "http://example.com") 1261 | } 1262 | 1263 | func TestModifyResponseHeadersWithSSLAndNoSSLHost(t *testing.T) { 1264 | s := New(Options{ 1265 | SSLRedirect: true, 1266 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 1267 | }) 1268 | 1269 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1270 | req.Host = exampleHost 1271 | req.URL.Scheme = httpSchema 1272 | req.Header.Add("X-Forwarded-Proto", "https") 1273 | 1274 | res := &http.Response{} 1275 | res.Header = http.Header{"Location": []string{"http://example.com"}} 1276 | res.Request = req 1277 | 1278 | expect(t, res.Header.Get("Location"), "http://example.com") 1279 | 1280 | err := s.ModifyResponseHeaders(res) 1281 | expect(t, err, nil) 1282 | 1283 | expect(t, res.Header.Get("Location"), "http://example.com") 1284 | } 1285 | 1286 | func TestModifyResponseHeadersWithSSLAndMatchingSSLHost(t *testing.T) { 1287 | s := New(Options{ 1288 | SSLRedirect: true, 1289 | SSLHost: "secure.example.com", 1290 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 1291 | }) 1292 | 1293 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1294 | req.Host = exampleHost 1295 | req.URL.Scheme = httpSchema 1296 | req.Header.Add("X-Forwarded-Proto", "https") 1297 | 1298 | res := &http.Response{} 1299 | res.Header = http.Header{"Location": []string{"http://secure.example.com"}} 1300 | res.Request = req 1301 | 1302 | expect(t, res.Header.Get("Location"), "http://secure.example.com") 1303 | 1304 | err := s.ModifyResponseHeaders(res) 1305 | expect(t, err, nil) 1306 | 1307 | expect(t, res.Header.Get("Location"), "https://secure.example.com") 1308 | } 1309 | 1310 | func TestModifyResponseHeadersWithSSLAndPortInLocationResponse(t *testing.T) { 1311 | s := New(Options{ 1312 | SSLRedirect: true, 1313 | SSLHost: "secure.example.com", 1314 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 1315 | }) 1316 | 1317 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1318 | req.Host = exampleHost 1319 | req.URL.Scheme = httpSchema 1320 | req.Header.Add("X-Forwarded-Proto", "https") 1321 | 1322 | res := &http.Response{} 1323 | res.Header = http.Header{"Location": []string{"http://secure.example.com:877"}} 1324 | res.Request = req 1325 | 1326 | expect(t, res.Header.Get("Location"), "http://secure.example.com:877") 1327 | 1328 | err := s.ModifyResponseHeaders(res) 1329 | expect(t, err, nil) 1330 | 1331 | expect(t, res.Header.Get("Location"), "http://secure.example.com:877") 1332 | } 1333 | 1334 | func TestModifyResponseHeadersWithSSLAndPathInLocationResponse(t *testing.T) { 1335 | s := New(Options{ 1336 | SSLRedirect: true, 1337 | SSLHost: "secure.example.com", 1338 | SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, 1339 | }) 1340 | 1341 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1342 | req.Host = exampleHost 1343 | req.URL.Scheme = httpSchema 1344 | req.Header.Add("X-Forwarded-Proto", "https") 1345 | 1346 | res := &http.Response{} 1347 | res.Header = http.Header{"Location": []string{"http://secure.example.com/admin/login"}} 1348 | res.Request = req 1349 | 1350 | expect(t, res.Header.Get("Location"), "http://secure.example.com/admin/login") 1351 | 1352 | err := s.ModifyResponseHeaders(res) 1353 | expect(t, err, nil) 1354 | 1355 | expect(t, res.Header.Get("Location"), "https://secure.example.com/admin/login") 1356 | } 1357 | 1358 | func TestCustomSecureContextKey(t *testing.T) { 1359 | s1 := New(Options{ 1360 | BrowserXssFilter: true, 1361 | CustomBrowserXssValue: "0", 1362 | SecureContextKey: "totallySecureContextKey", 1363 | }) 1364 | 1365 | res := httptest.NewRecorder() 1366 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1367 | 1368 | var actual *http.Request 1369 | 1370 | hf := func(_ http.ResponseWriter, r *http.Request) { 1371 | actual = r 1372 | } 1373 | 1374 | s1.HandlerFuncWithNextForRequestOnly(res, req, hf) 1375 | contextHeaders, _ := actual.Context().Value(s1.ctxSecureHeaderKey).(http.Header) 1376 | expect(t, contextHeaders.Get(xssProtectionHeader), s1.opt.CustomBrowserXssValue) 1377 | } 1378 | 1379 | func TestMultipleCustomSecureContextKeys(t *testing.T) { 1380 | s1 := New(Options{ 1381 | BrowserXssFilter: true, 1382 | CustomBrowserXssValue: "0", 1383 | SecureContextKey: "totallySecureContextKey", 1384 | }) 1385 | 1386 | s2 := New(Options{ 1387 | FeaturePolicy: "test", 1388 | SecureContextKey: "anotherSecureContextKey", 1389 | }) 1390 | 1391 | res := httptest.NewRecorder() 1392 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1393 | 1394 | var actual *http.Request 1395 | 1396 | hf := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { 1397 | actual = r 1398 | }) 1399 | 1400 | next := s1.HandlerForRequestOnly(hf) 1401 | s2.HandlerFuncWithNextForRequestOnly(res, req, next.ServeHTTP) 1402 | 1403 | s1Headers, _ := actual.Context().Value(s1.ctxSecureHeaderKey).(http.Header) 1404 | s2Headers, _ := actual.Context().Value(s2.ctxSecureHeaderKey).(http.Header) 1405 | 1406 | expect(t, s1Headers.Get(xssProtectionHeader), s1.opt.CustomBrowserXssValue) 1407 | expect(t, s2Headers.Get(featurePolicyHeader), s2.opt.FeaturePolicy) 1408 | } 1409 | 1410 | func TestAllowRequestFuncTrue(t *testing.T) { 1411 | s := New(Options{ 1412 | AllowRequestFunc: func(_ *http.Request) bool { return true }, 1413 | }) 1414 | 1415 | res := httptest.NewRecorder() 1416 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1417 | req.Host = "www.allow-request.com" 1418 | 1419 | s.Handler(myHandler).ServeHTTP(res, req) 1420 | 1421 | expect(t, res.Code, http.StatusOK) 1422 | expect(t, res.Body.String(), `bar`) 1423 | } 1424 | 1425 | func TestAllowRequestFuncFalse(t *testing.T) { 1426 | s := New(Options{ 1427 | AllowRequestFunc: func(_ *http.Request) bool { return false }, 1428 | }) 1429 | 1430 | res := httptest.NewRecorder() 1431 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1432 | req.Host = "www.deny-request.com" 1433 | 1434 | s.Handler(myHandler).ServeHTTP(res, req) 1435 | 1436 | expect(t, res.Code, http.StatusBadRequest) 1437 | } 1438 | 1439 | func TestBadRequestHandler(t *testing.T) { 1440 | s := New(Options{ 1441 | AllowRequestFunc: func(_ *http.Request) bool { return false }, 1442 | }) 1443 | badRequestFunc := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { 1444 | http.Error(w, "custom error", http.StatusConflict) 1445 | }) 1446 | s.SetBadRequestHandler(badRequestFunc) 1447 | 1448 | res := httptest.NewRecorder() 1449 | req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "/foo", nil) 1450 | req.Host = "www.deny-request.com" 1451 | 1452 | s.Handler(myHandler).ServeHTTP(res, req) 1453 | 1454 | expect(t, res.Code, http.StatusConflict) 1455 | expect(t, strings.TrimSpace(res.Body.String()), `custom error`) 1456 | } 1457 | 1458 | func TestMarshal(t *testing.T) { 1459 | // Options has struct field tags to omit func fields 1460 | var o1 Options 1461 | 1462 | b, err := json.Marshal(o1) //nolint:musttag 1463 | if err != nil { 1464 | t.Errorf("unexpected error marshal: %v", err) 1465 | } 1466 | 1467 | err = json.Unmarshal(b, &o1) //nolint:musttag 1468 | if err != nil { 1469 | t.Errorf("unexpected error unmarshal: %v", err) 1470 | } 1471 | } 1472 | 1473 | // Test Helper. 1474 | func expect(t *testing.T, a interface{}, b interface{}) { 1475 | t.Helper() 1476 | 1477 | if a != b { 1478 | t.Errorf("Expected [%v] (type %v) - Got [%v] (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) 1479 | } 1480 | } 1481 | --------------------------------------------------------------------------------