pax_global_header00006660000000000000000000000064140415415650014517gustar00rootroot0000000000000052 comment=d9ab0ac5b2ce84de5ceb163f1b31fc674e22ed59 secure-1.0.9/000077500000000000000000000000001404154156500130145ustar00rootroot00000000000000secure-1.0.9/.github/000077500000000000000000000000001404154156500143545ustar00rootroot00000000000000secure-1.0.9/.github/workflows/000077500000000000000000000000001404154156500164115ustar00rootroot00000000000000secure-1.0.9/.github/workflows/test.yaml000066400000000000000000000011741404154156500202570ustar00rootroot00000000000000on: push: branches: - master - v1 pull_request: branches: - "**" name: Test jobs: test: strategy: matrix: go-version: [1.14.x, 1.15.x, 1.16.x] os: [ubuntu-latest] runs-on: ${{ matrix.os }} steps: - name: Install Go uses: actions/setup-go@v2 with: go-version: ${{ matrix.go-version }} - name: Checkout code uses: actions/checkout@v2 - name: Dependencies run: go get -u honnef.co/go/tools/cmd/staticcheck env: GO111MODULE: off - name: Test run: go test -v -race -tags=integration secure-1.0.9/.gitignore000066400000000000000000000004321404154156500150030ustar00rootroot00000000000000# Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe *.test *.pem .DS_Store *.swp secure-1.0.9/LICENSE000066400000000000000000000020701404154156500140200ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2014 Cory Jacobsen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. secure-1.0.9/README.md000066400000000000000000000347421404154156500143050ustar00rootroot00000000000000# Secure [![GoDoc](https://godoc.org/github.com/unrolled/secure?status.svg)](http://godoc.org/github.com/unrolled/secure) [![Test](https://github.com/unrolled/secure/workflows/Test/badge.svg?branch=v1)](https://github.com/unrolled/secure/actions) 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. ## Usage ~~~ go // main.go package main import ( "net/http" "github.com/unrolled/secure" // or "gopkg.in/unrolled/secure.v1" ) var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello world")) }) func main() { secureMiddleware := secure.New(secure.Options{ AllowedHosts: []string{"example\\.com", ".*\\.example\\.com"}, AllowedHostsAreRegex: true, HostsProxyHeaders: []string{"X-Forwarded-Host"}, SSLRedirect: true, SSLHost: "ssl.example.com", SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, STSSeconds: 31536000, STSIncludeSubdomains: true, STSPreload: true, FrameDeny: true, ContentTypeNosniff: true, BrowserXssFilter: true, ContentSecurityPolicy: "script-src $NONCE", }) app := secureMiddleware.Handler(myHandler) http.ListenAndServe("127.0.0.1:3000", app) } ~~~ 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. 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'. Once those requirements are satisfied, it will add the following headers: ~~~ go Strict-Transport-Security: 31536000; includeSubdomains; preload X-Frame-Options: DENY X-Content-Type-Options: nosniff X-XSS-Protection: 1; mode=block Content-Security-Policy: script-src 'nonce-a2ZobGFoZg==' ~~~ ### Set the `IsDevelopment` option to `true` when developing! When `IsDevelopment` is true, the AllowedHosts, SSLRedirect, STS header, and HPKP 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. ### Available options Secure comes with a variety of configuration options (Note: these are not the default option values. See the defaults below.): ~~~ go // ... s := secure.New(secure.Options{ 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. AllowedHostsAreRegex: false, // AllowedHostsAreRegex determines, if the provided AllowedHosts slice contains valid regular expressions. Default is false. HostsProxyHeaders: []string{"X-Forwarded-Hosts"}, // HostsProxyHeaders is a set of header keys that may hold a proxied hostname value for the request. SSLRedirect: true, // If SSLRedirect is set to true, then only allow HTTPS requests. Default is false. SSLTemporaryRedirect: false, // If SSLTemporaryRedirect is true, the a 302 will be used while redirecting. Default is false (301). 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. 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. 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. STSSeconds: 31536000, // STSSeconds is the max-age of the Strict-Transport-Security header. Default is 0, which would NOT include the header. STSIncludeSubdomains: true, // If STSIncludeSubdomains is set to true, the `includeSubdomains` will be appended to the Strict-Transport-Security header. Default is false. STSPreload: true, // If STSPreload is set to true, the `preload` flag will be appended to the Strict-Transport-Security header. Default is false. 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. FrameDeny: true, // If FrameDeny is set to true, adds the X-Frame-Options header with the value of `DENY`. Default is false. CustomFrameOptionsValue: "SAMEORIGIN", // CustomFrameOptionsValue allows the X-Frame-Options header value to be set with a custom value. This overrides the FrameDeny option. Default is "". ContentTypeNosniff: true, // If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value `nosniff`. Default is false. BrowserXssFilter: true, // If BrowserXssFilter is true, adds the X-XSS-Protection header with the value `1; mode=block`. Default is false. 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 "". 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. PublicKey: `pin-sha256="base64+primary=="; pin-sha256="base64+backup=="; max-age=5184000; includeSubdomains; report-uri="https://www.example.com/hpkp-report"`, // Deprecated: This feature is no longer recommended. PublicKey implements HPKP to prevent MITM attacks with forged certificates. Default is "". ReferrerPolicy: "same-origin", // ReferrerPolicy allows the Referrer-Policy header with the value to be set with a custom value. Default is "". 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 "". PermissionsPolicy: "fullscreen=(), geolocation=()", // PermissionsPolicy allows the Permissions-Policy header with the value to be set with a custom value. Default is "". ExpectCTHeader: `enforce, max-age=30, report-uri="https://www.example.com/ct-report"`, 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. }) // ... ~~~ ### Default options These are the preset options for Secure: ~~~ go s := secure.New() // Is the same as the default configuration options: l := secure.New(secure.Options{ AllowedHosts: []string, AllowedHostsAreRegex: false, HostsProxyHeaders: []string, SSLRedirect: false, SSLTemporaryRedirect: false, SSLHost: "", SSLProxyHeaders: map[string]string{}, STSSeconds: 0, STSIncludeSubdomains: false, STSPreload: false, ForceSTSHeader: false, FrameDeny: false, CustomFrameOptionsValue: "", ContentTypeNosniff: false, BrowserXssFilter: false, ContentSecurityPolicy: "", PublicKey: "", ReferrerPolicy: "", FeaturePolicy: "", PermissionsPolicy: "", ExpectCTHeader: "", IsDevelopment: false, }) ~~~ Also note the default bad host handler returns an error: ~~~ go http.Error(w, "Bad Host", http.StatusInternalServerError) ~~~ Call `secure.SetBadHostHandler` to change the bad host handler. ### Redirecting HTTP to HTTPS If you want to redirect all HTTP requests to HTTPS, you can use the following example. ~~~ go // main.go package main import ( "log" "net/http" "github.com/unrolled/secure" // or "gopkg.in/unrolled/secure.v1" ) var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello world")) }) func main() { secureMiddleware := secure.New(secure.Options{ SSLRedirect: true, 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. }) app := secureMiddleware.Handler(myHandler) // HTTP go func() { log.Fatal(http.ListenAndServe(":8080", app)) }() // HTTPS // To generate a development cert and key, run the following from your *nix terminal: // go run $GOROOT/src/crypto/tls/generate_cert.go --host="localhost" log.Fatal(http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", app)) } ~~~ ### Strict Transport Security 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. * The `preload` flag is required for domain inclusion in Chrome's [preload](https://hstspreload.appspot.com/) list. ### Content Security Policy If you need dynamic support for CSP while using Websockets, check out this other middleware [awakenetworks/csp](https://github.com/awakenetworks/csp). ## Integration examples ### [chi](https://github.com/pressly/chi) ~~~ go // main.go package main import ( "net/http" "github.com/pressly/chi" "github.com/unrolled/secure" // or "gopkg.in/unrolled/secure.v1" ) func main() { secureMiddleware := secure.New(secure.Options{ FrameDeny: true, }) r := chi.NewRouter() r.Use(secureMiddleware.Handler) r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("X-Frame-Options header is now `DENY`.")) }) http.ListenAndServe("127.0.0.1:3000", r) } ~~~ ### [Echo](https://github.com/labstack/echo) ~~~ go // main.go package main import ( "net/http" "github.com/labstack/echo" "github.com/unrolled/secure" // or "gopkg.in/unrolled/secure.v1" ) func main() { secureMiddleware := secure.New(secure.Options{ FrameDeny: true, }) e := echo.New() e.GET("/", func(c echo.Context) error { return c.String(http.StatusOK, "X-Frame-Options header is now `DENY`.") }) e.Use(echo.WrapMiddleware(secureMiddleware.Handler)) e.Logger.Fatal(e.Start("127.0.0.1:3000")) } ~~~ ### [Gin](https://github.com/gin-gonic/gin) ~~~ go // main.go package main import ( "github.com/gin-gonic/gin" "github.com/unrolled/secure" // or "gopkg.in/unrolled/secure.v1" ) func main() { secureMiddleware := secure.New(secure.Options{ FrameDeny: true, }) secureFunc := func() gin.HandlerFunc { return func(c *gin.Context) { err := secureMiddleware.Process(c.Writer, c.Request) // If there was an error, do not continue. if err != nil { c.Abort() return } // Avoid header rewrite if response is a redirection. if status := c.Writer.Status(); status > 300 && status < 399 { c.Abort() } } }() router := gin.Default() router.Use(secureFunc) router.GET("/", func(c *gin.Context) { c.String(200, "X-Frame-Options header is now `DENY`.") }) router.Run("127.0.0.1:3000") } ~~~ ### [Goji](https://github.com/zenazn/goji) ~~~ go // main.go package main import ( "net/http" "github.com/unrolled/secure" // or "gopkg.in/unrolled/secure.v1" "github.com/zenazn/goji" "github.com/zenazn/goji/web" ) func main() { secureMiddleware := secure.New(secure.Options{ FrameDeny: true, }) goji.Get("/", func(c web.C, w http.ResponseWriter, req *http.Request) { w.Write([]byte("X-Frame-Options header is now `DENY`.")) }) goji.Use(secureMiddleware.Handler) goji.Serve() // Defaults to ":8000". } ~~~ ### [Iris](https://github.com/kataras/iris) ~~~ go //main.go package main import ( "github.com/kataras/iris/v12" "github.com/unrolled/secure" // or "gopkg.in/unrolled/secure.v1" ) func main() { app := iris.New() secureMiddleware := secure.New(secure.Options{ FrameDeny: true, }) app.Use(iris.FromStd(secureMiddleware.HandlerFuncWithNext)) // Identical to: // app.Use(func(ctx iris.Context) { // err := secureMiddleware.Process(ctx.ResponseWriter(), ctx.Request()) // // // If there was an error, do not continue. // if err != nil { // return // } // // ctx.Next() // }) app.Get("/home", func(ctx iris.Context) { ctx.Writef("X-Frame-Options header is now `%s`.", "DENY") }) app.Listen(":8080") } ~~~ ### [Mux](https://github.com/gorilla/mux) ~~~ go //main.go package main import ( "log" "net/http" "github.com/gorilla/mux" "github.com/unrolled/secure" // or "gopkg.in/unrolled/secure.v1" ) func main() { secureMiddleware := secure.New(secure.Options{ FrameDeny: true, }) r := mux.NewRouter() r.Use(secureMiddleware.Handler) http.Handle("/", r) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", 8080), nil)) } ~~~ ### [Negroni](https://github.com/urfave/negroni) Note this implementation has a special helper function called `HandlerFuncWithNext`. ~~~ go // main.go package main import ( "net/http" "github.com/urfave/negroni" "github.com/unrolled/secure" // or "gopkg.in/unrolled/secure.v1" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { w.Write([]byte("X-Frame-Options header is now `DENY`.")) }) secureMiddleware := secure.New(secure.Options{ FrameDeny: true, }) n := negroni.Classic() n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext)) n.UseHandler(mux) n.Run("127.0.0.1:3000") } ~~~ secure-1.0.9/csp.go000066400000000000000000000021671404154156500141360ustar00rootroot00000000000000package secure import ( "context" "crypto/rand" "encoding/base64" "io" "net/http" ) type key int const cspNonceKey key = iota // CSPNonce returns the nonce value associated with the present request. If no nonce has been generated it returns an empty string. func CSPNonce(c context.Context) string { if val, ok := c.Value(cspNonceKey).(string); ok { return val } return "" } // WithCSPNonce returns a context derived from ctx containing the given nonce as a value. // // This is intended for testing or more advanced use-cases; // For ordinary HTTP handlers, clients can rely on this package's middleware to populate the CSP nonce in the context. func WithCSPNonce(ctx context.Context, nonce string) context.Context { return context.WithValue(ctx, cspNonceKey, nonce) } func withCSPNonce(r *http.Request, nonce string) *http.Request { return r.WithContext(WithCSPNonce(r.Context(), nonce)) } func cspRandNonce() string { var buf [cspNonceSize]byte _, err := io.ReadFull(rand.Reader, buf[:]) if err != nil { panic("CSP Nonce rand.Reader failed" + err.Error()) } return base64.RawStdEncoding.EncodeToString(buf[:]) } secure-1.0.9/csp_test.go000066400000000000000000000033111404154156500151650ustar00rootroot00000000000000package secure import ( "encoding/base64" "fmt" "net/http" "net/http/httptest" "strings" "testing" ) // cspHandler writes the nonce out as the response body. var cspHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(CSPNonce(r.Context()))) }) func TestCSPNonce(t *testing.T) { csp := "default-src 'self' $NONCE; script-src 'strict-dynamic' $NONCE" cases := []struct { options Options headers []string }{ {Options{ContentSecurityPolicy: csp}, []string{"Content-Security-Policy"}}, {Options{ContentSecurityPolicyReportOnly: csp}, []string{"Content-Security-Policy-Report-Only"}}, {Options{ContentSecurityPolicy: csp, ContentSecurityPolicyReportOnly: csp}, []string{"Content-Security-Policy", "Content-Security-Policy-Report-Only"}}, } for _, c := range cases { s := New(c.options) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(cspHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) for _, header := range c.headers { csp := res.Header().Get(header) expect(t, strings.Count(csp, "'nonce-"), 2) nonce := strings.Split(strings.Split(csp, "'")[3], "-")[1] // Test that the context has the CSP nonce, but only during the request. expect(t, res.Body.String(), nonce) expect(t, CSPNonce(req.Context()), "") _, err := base64.RawStdEncoding.DecodeString(nonce) expect(t, err, nil) expect(t, csp, fmt.Sprintf("default-src 'self' 'nonce-%[1]s'; script-src 'strict-dynamic' 'nonce-%[1]s'", nonce)) } } } func TestWithCSPNonce(t *testing.T) { req, _ := http.NewRequest("GET", "/foo", nil) nonce := "jdgKGHkbnd+/" expect(t, CSPNonce(withCSPNonce(req, nonce).Context()), nonce) } secure-1.0.9/doc.go000066400000000000000000000011761404154156500141150ustar00rootroot00000000000000/*Package secure is an HTTP middleware for Go that facilitates some quick security wins. package main import ( "net/http" "github.com/unrolled/secure" // or "gopkg.in/unrolled/secure.v1" ) var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello world")) }) func main() { secureMiddleware := secure.New(secure.Options{ AllowedHosts: []string{"www.example.com", "sub.example.com"}, SSLRedirect: true, }) app := secureMiddleware.Handler(myHandler) http.ListenAndServe("127.0.0.1:3000", app) } */ package secure secure-1.0.9/go.mod000066400000000000000000000001251404154156500141200ustar00rootroot00000000000000module github.com/unrolled/secure go 1.13 require github.com/urfave/negroni v1.0.0 secure-1.0.9/go.sum000066400000000000000000000002511404154156500141450ustar00rootroot00000000000000github.com/urfave/negroni v1.0.0 h1:kIimOitoypq34K7TG7DUaJ9kq/N4Ofuwi1sjz0KipXc= github.com/urfave/negroni v1.0.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4= secure-1.0.9/secure.go000066400000000000000000000437251404154156500146440ustar00rootroot00000000000000package secure import ( "context" "fmt" "net/http" "regexp" "strings" ) type secureCtxKey string const ( stsHeader = "Strict-Transport-Security" stsSubdomainString = "; includeSubDomains" stsPreloadString = "; preload" frameOptionsHeader = "X-Frame-Options" frameOptionsValue = "DENY" contentTypeHeader = "X-Content-Type-Options" contentTypeValue = "nosniff" xssProtectionHeader = "X-XSS-Protection" xssProtectionValue = "1; mode=block" cspHeader = "Content-Security-Policy" cspReportOnlyHeader = "Content-Security-Policy-Report-Only" hpkpHeader = "Public-Key-Pins" referrerPolicyHeader = "Referrer-Policy" featurePolicyHeader = "Feature-Policy" permissionsPolicyHeader = "Permissions-Policy" expectCTHeader = "Expect-CT" ctxDefaultSecureHeaderKey = secureCtxKey("SecureResponseHeader") cspNonceSize = 16 ) // SSLHostFunc a type whose pointer is the type of field `SSLHostFunc` of `Options` struct type SSLHostFunc func(host string) (newHost string) func defaultBadHostHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, "Bad Host", http.StatusInternalServerError) } // Options is a struct for specifying configuration options for the secure.Secure middleware. type Options struct { // If BrowserXssFilter is true, adds the X-XSS-Protection header with the value `1; mode=block`. Default is false. BrowserXssFilter bool // nolint: golint // If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value `nosniff`. Default is false. ContentTypeNosniff bool // If ForceSTSHeader is set to true, the STS header will be added even when the connection is HTTP. Default is false. ForceSTSHeader bool // If FrameDeny is set to true, adds the X-Frame-Options header with the value of `DENY`. Default is false. FrameDeny bool // 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. // 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. IsDevelopment bool // nonceEnabled is used internally for dynamic nouces. nonceEnabled bool // If SSLRedirect is set to true, then only allow https requests. Default is false. SSLRedirect bool // 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. SSLForceHost bool // If SSLTemporaryRedirect is true, the a 302 will be used while redirecting. Default is false (301). SSLTemporaryRedirect bool // If STSIncludeSubdomains is set to true, the `includeSubdomains` will be appended to the Strict-Transport-Security header. Default is false. STSIncludeSubdomains bool // If STSPreload is set to true, the `preload` flag will be appended to the Strict-Transport-Security header. Default is false. STSPreload bool // ContentSecurityPolicy allows the Content-Security-Policy header value to be set with a custom value. Default is "". ContentSecurityPolicy string // ContentSecurityPolicyReportOnly allows the Content-Security-Policy-Report-Only header value to be set with a custom value. Default is "". ContentSecurityPolicyReportOnly string // CustomBrowserXssValue allows the X-XSS-Protection header value to be set with a custom value. This overrides the BrowserXssFilter option. Default is "". CustomBrowserXssValue string // nolint: golint // 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. // Eg: script-src $NONCE -> script-src 'nonce-a2ZobGFoZg==' // CustomFrameOptionsValue allows the X-Frame-Options header value to be set with a custom value. This overrides the FrameDeny option. Default is "". CustomFrameOptionsValue string // PublicKey implements HPKP to prevent MITM attacks with forged certificates. Default is "". // Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible. PublicKey string // ReferrerPolicy allows sites to control when browsers will pass the Referer header to other sites. Default is "". ReferrerPolicy string // FeaturePolicy allows to selectively enable and disable use of various browser features and APIs. Default is "". // Deprecated: This header has been renamed to Permissions-Policy. FeaturePolicy string // PermissionsPolicy allows to selectively enable and disable use of various browser features and APIs. Default is "". PermissionsPolicy string // SSLHost is the host name that is used to redirect http requests to https. Default is "", which indicates to use the same host. SSLHost string // AllowedHosts is a list of fully qualified domain names that are allowed. Default is empty list, which allows any and all host names. AllowedHosts []string // AllowedHostsAreRegex determines, if the provided 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 for backwards compatibility. AllowedHostsAreRegex bool // HostsProxyHeaders is a set of header keys that may hold a proxied hostname value for the request. HostsProxyHeaders []string // 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. SSLHostFunc *SSLHostFunc // 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. SSLProxyHeaders map[string]string // STSSeconds is the max-age of the Strict-Transport-Security header. Default is 0, which would NOT include the header. STSSeconds int64 // ExpectCTHeader allows the Expect-CT header value to be set with a custom value. Default is "". ExpectCTHeader string // SecureContextKey allows a custom key to be specified for context storage. SecureContextKey string } // Secure is a middleware that helps setup a few basic security features. A single secure.Options struct can be // provided to configure which features should be enabled, and the ability to override a few of the default values. type Secure struct { // Customize Secure with an Options struct. opt Options // badHostHandler is the handler used when an incorrect host is passed in. badHostHandler http.Handler // cRegexAllowedHosts saves the compiled regular expressions of the AllowedHosts // option for subsequent use in processRequest cRegexAllowedHosts []*regexp.Regexp // ctxSecureHeaderKey is the key used for context storage for request modification. ctxSecureHeaderKey secureCtxKey } // New constructs a new Secure instance with the supplied options. func New(options ...Options) *Secure { var o Options if len(options) == 0 { o = Options{} } else { o = options[0] } o.ContentSecurityPolicy = strings.Replace(o.ContentSecurityPolicy, "$NONCE", "'nonce-%[1]s'", -1) o.ContentSecurityPolicyReportOnly = strings.Replace(o.ContentSecurityPolicyReportOnly, "$NONCE", "'nonce-%[1]s'", -1) o.nonceEnabled = strings.Contains(o.ContentSecurityPolicy, "%[1]s") || strings.Contains(o.ContentSecurityPolicyReportOnly, "%[1]s") s := &Secure{ opt: o, badHostHandler: http.HandlerFunc(defaultBadHostHandler), } if s.opt.AllowedHostsAreRegex { // Test for invalid regular expressions in AllowedHosts for _, allowedHost := range o.AllowedHosts { regex, err := regexp.Compile(fmt.Sprintf("^%s$", allowedHost)) if err != nil { panic(fmt.Sprintf("Error parsing AllowedHost: %s", err)) } s.cRegexAllowedHosts = append(s.cRegexAllowedHosts, regex) } } s.ctxSecureHeaderKey = ctxDefaultSecureHeaderKey if len(s.opt.SecureContextKey) > 0 { s.ctxSecureHeaderKey = secureCtxKey(s.opt.SecureContextKey) } return s } // SetBadHostHandler sets the handler to call when secure rejects the host name. func (s *Secure) SetBadHostHandler(handler http.Handler) { s.badHostHandler = handler } // Handler implements the http.HandlerFunc for integration with the standard net/http lib. func (s *Secure) Handler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Let secure process the request. If it returns an error, // that indicates the request should not continue. responseHeader, r, err := s.processRequest(w, r) addResponseHeaders(responseHeader, w) // If there was an error, do not continue. if err != nil { return } h.ServeHTTP(w, r) }) } // HandlerForRequestOnly implements the http.HandlerFunc for integration with the standard net/http lib. // Note that this is for requests only and will not write any headers. func (s *Secure) HandlerForRequestOnly(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Let secure process the request. If it returns an error, // that indicates the request should not continue. responseHeader, r, err := s.processRequest(w, r) // If there was an error, do not continue. if err != nil { return } // Save response headers in the request context. ctx := context.WithValue(r.Context(), s.ctxSecureHeaderKey, responseHeader) // No headers will be written to the ResponseWriter. h.ServeHTTP(w, r.WithContext(ctx)) }) } // HandlerFuncWithNext is a special implementation for Negroni, but could be used elsewhere. func (s *Secure) HandlerFuncWithNext(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { // Let secure process the request. If it returns an error, // that indicates the request should not continue. responseHeader, r, err := s.processRequest(w, r) addResponseHeaders(responseHeader, w) // If there was an error, do not call next. if err == nil && next != nil { next(w, r) } } // HandlerFuncWithNextForRequestOnly is a special implementation for Negroni, but could be used elsewhere. // Note that this is for requests only and will not write any headers. func (s *Secure) HandlerFuncWithNextForRequestOnly(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { // Let secure process the request. If it returns an error, // that indicates the request should not continue. responseHeader, r, err := s.processRequest(w, r) // If there was an error, do not call next. if err == nil && next != nil { // Save response headers in the request context ctx := context.WithValue(r.Context(), s.ctxSecureHeaderKey, responseHeader) // No headers will be written to the ResponseWriter. next(w, r.WithContext(ctx)) } } // addResponseHeaders Adds the headers from 'responseHeader' to the response. func addResponseHeaders(responseHeader http.Header, w http.ResponseWriter) { for key, values := range responseHeader { for _, value := range values { w.Header().Set(key, value) } } } // Process runs the actual checks and writes the headers in the ResponseWriter. func (s *Secure) Process(w http.ResponseWriter, r *http.Request) error { responseHeader, _, err := s.processRequest(w, r) addResponseHeaders(responseHeader, w) return err } // ProcessAndReturnNonce runs the actual checks and writes the headers in the ResponseWriter. // In addition, the generated nonce for the request is returned as well as the error value. func (s *Secure) ProcessAndReturnNonce(w http.ResponseWriter, r *http.Request) (string, error) { responseHeader, newR, err := s.processRequest(w, r) if err != nil { return "", err } addResponseHeaders(responseHeader, w) return CSPNonce(newR.Context()), err } // ProcessNoModifyRequest runs the actual checks but does not write the headers in the ResponseWriter. func (s *Secure) ProcessNoModifyRequest(w http.ResponseWriter, r *http.Request) (http.Header, *http.Request, error) { return s.processRequest(w, r) } // processRequest runs the actual checks on the request and returns an error if the middleware chain should stop. func (s *Secure) processRequest(w http.ResponseWriter, r *http.Request) (http.Header, *http.Request, error) { // Setup nonce if required. if s.opt.nonceEnabled { r = withCSPNonce(r, cspRandNonce()) } // Resolve the host for the request, using proxy headers if present. host := r.Host for _, header := range s.opt.HostsProxyHeaders { if h := r.Header.Get(header); h != "" { host = h break } } // Allowed hosts check. if len(s.opt.AllowedHosts) > 0 && !s.opt.IsDevelopment { isGoodHost := false if s.opt.AllowedHostsAreRegex { for _, allowedHost := range s.cRegexAllowedHosts { if match := allowedHost.MatchString(host); match { isGoodHost = true break } } } else { for _, allowedHost := range s.opt.AllowedHosts { if strings.EqualFold(allowedHost, host) { isGoodHost = true break } } } if !isGoodHost { s.badHostHandler.ServeHTTP(w, r) return nil, nil, fmt.Errorf("bad host name: %s", host) } } // Determine if we are on HTTPS. ssl := s.isSSL(r) // SSL check. if s.opt.SSLRedirect && !ssl && !s.opt.IsDevelopment { url := r.URL url.Scheme = "https" url.Host = host if s.opt.SSLHostFunc != nil { if h := (*s.opt.SSLHostFunc)(host); len(h) > 0 { url.Host = h } } else if len(s.opt.SSLHost) > 0 { url.Host = s.opt.SSLHost } status := http.StatusMovedPermanently if s.opt.SSLTemporaryRedirect { status = http.StatusTemporaryRedirect } http.Redirect(w, r, url.String(), status) return nil, nil, fmt.Errorf("redirecting to HTTPS") } if s.opt.SSLForceHost { var SSLHost = host if s.opt.SSLHostFunc != nil { if h := (*s.opt.SSLHostFunc)(host); len(h) > 0 { SSLHost = h } } else if len(s.opt.SSLHost) > 0 { SSLHost = s.opt.SSLHost } if SSLHost != host { url := r.URL url.Scheme = "https" url.Host = SSLHost status := http.StatusMovedPermanently if s.opt.SSLTemporaryRedirect { status = http.StatusTemporaryRedirect } http.Redirect(w, r, url.String(), status) return nil, nil, fmt.Errorf("redirecting to HTTPS") } } // Create our header container. responseHeader := make(http.Header) // Strict Transport Security header. Only add header when we know it's an SSL connection. // See https://tools.ietf.org/html/rfc6797#section-7.2 for details. if s.opt.STSSeconds != 0 && (ssl || s.opt.ForceSTSHeader) && !s.opt.IsDevelopment { stsSub := "" if s.opt.STSIncludeSubdomains { stsSub = stsSubdomainString } if s.opt.STSPreload { stsSub += stsPreloadString } responseHeader.Set(stsHeader, fmt.Sprintf("max-age=%d%s", s.opt.STSSeconds, stsSub)) } // Frame Options header. if len(s.opt.CustomFrameOptionsValue) > 0 { responseHeader.Set(frameOptionsHeader, s.opt.CustomFrameOptionsValue) } else if s.opt.FrameDeny { responseHeader.Set(frameOptionsHeader, frameOptionsValue) } // Content Type Options header. if s.opt.ContentTypeNosniff { responseHeader.Set(contentTypeHeader, contentTypeValue) } // XSS Protection header. if len(s.opt.CustomBrowserXssValue) > 0 { responseHeader.Set(xssProtectionHeader, s.opt.CustomBrowserXssValue) } else if s.opt.BrowserXssFilter { responseHeader.Set(xssProtectionHeader, xssProtectionValue) } // HPKP header. if len(s.opt.PublicKey) > 0 && ssl && !s.opt.IsDevelopment { responseHeader.Set(hpkpHeader, s.opt.PublicKey) } // Content Security Policy header. if len(s.opt.ContentSecurityPolicy) > 0 { if s.opt.nonceEnabled { responseHeader.Set(cspHeader, fmt.Sprintf(s.opt.ContentSecurityPolicy, CSPNonce(r.Context()))) } else { responseHeader.Set(cspHeader, s.opt.ContentSecurityPolicy) } } // Content Security Policy Report Only header. if len(s.opt.ContentSecurityPolicyReportOnly) > 0 { if s.opt.nonceEnabled { responseHeader.Set(cspReportOnlyHeader, fmt.Sprintf(s.opt.ContentSecurityPolicyReportOnly, CSPNonce(r.Context()))) } else { responseHeader.Set(cspReportOnlyHeader, s.opt.ContentSecurityPolicyReportOnly) } } // Referrer Policy header. if len(s.opt.ReferrerPolicy) > 0 { responseHeader.Set(referrerPolicyHeader, s.opt.ReferrerPolicy) } // Feature Policy header. if len(s.opt.FeaturePolicy) > 0 { responseHeader.Set(featurePolicyHeader, s.opt.FeaturePolicy) } // Permissions Policy header. if len(s.opt.PermissionsPolicy) > 0 { responseHeader.Set(permissionsPolicyHeader, s.opt.PermissionsPolicy) } // Expect-CT header. if len(s.opt.ExpectCTHeader) > 0 { responseHeader.Set(expectCTHeader, s.opt.ExpectCTHeader) } return responseHeader, r, nil } // isSSL determine if we are on HTTPS. func (s *Secure) isSSL(r *http.Request) bool { ssl := strings.EqualFold(r.URL.Scheme, "https") || r.TLS != nil if !ssl { for k, v := range s.opt.SSLProxyHeaders { if r.Header.Get(k) == v { ssl = true break } } } return ssl } // ModifyResponseHeaders modifies the Response. // Used by http.ReverseProxy. func (s *Secure) ModifyResponseHeaders(res *http.Response) error { if res != nil && res.Request != nil { // Fix Location response header http to https: // When SSL is enabled, // And SSLHost is defined, // And the response location header includes the SSLHost as the domain with a trailing slash, // Or an exact match to the SSLHost. location := res.Header.Get("Location") if s.isSSL(res.Request) && len(s.opt.SSLHost) > 0 && (strings.HasPrefix(location, fmt.Sprintf("http://%s/", s.opt.SSLHost)) || location == fmt.Sprintf("http://%s", s.opt.SSLHost)) { location = strings.Replace(location, "http:", "https:", 1) res.Header.Set("Location", location) } responseHeader := res.Request.Context().Value(s.ctxSecureHeaderKey) if responseHeader != nil { for header, values := range responseHeader.(http.Header) { if len(values) > 0 { res.Header.Set(header, strings.Join(values, ",")) } } } } return nil } secure-1.0.9/secure_integration_test.go000066400000000000000000000042011404154156500202700ustar00rootroot00000000000000// +build integration package secure import ( "fmt" "net/http" "net/http/httptest" "testing" "github.com/urfave/negroni" ) // go test -tags=integration func TestIntegration(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "bar") }) secureMiddleware := New(Options{ ContentTypeNosniff: true, FrameDeny: true, }) n := negroni.New() n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext)) n.UseHandler(mux) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "http://example.com/foo", nil) n.ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Body.String(), "bar") expect(t, res.Header().Get("X-Frame-Options"), "DENY") expect(t, res.Header().Get("X-Content-Type-Options"), "nosniff") } func TestIntegrationWithError(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "bar") }) secureMiddleware := New(Options{ ContentTypeNosniff: true, FrameDeny: true, AllowedHosts: []string{"www.example.com", "sub.example.com"}, }) n := negroni.New() n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext)) n.UseHandler(mux) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www3.example.com" n.ServeHTTP(res, req) expect(t, res.Code, http.StatusInternalServerError) } func TestIntegrationForRequestOnly(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "bar") }) secureMiddleware := New(Options{ ContentTypeNosniff: true, FrameDeny: true, }) n := negroni.New() n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNextForRequestOnly)) n.UseHandler(mux) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "http://example.com/foo", nil) n.ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Body.String(), "bar") expect(t, res.Header().Get("X-Frame-Options"), "") expect(t, res.Header().Get("X-Content-Type-Options"), "") } secure-1.0.9/secure_test.go000066400000000000000000001075141404154156500157000ustar00rootroot00000000000000package secure import ( "crypto/tls" "net/http" "net/http/httptest" "reflect" "testing" ) var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("bar")) }) func TestNoConfig(t *testing.T) { s := New() res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "http://example.com/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Body.String(), "bar") } func TestNoAllowHosts(t *testing.T) { s := New(Options{ AllowedHosts: []string{}, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Body.String(), `bar`) } func TestGoodSingleAllowHosts(t *testing.T) { s := New(Options{ AllowedHosts: []string{"www.example.com"}, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Body.String(), `bar`) } func TestBadSingleAllowHosts(t *testing.T) { s := New(Options{ AllowedHosts: []string{"sub.example.com"}, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusInternalServerError) } func TestRegexSingleAllowHosts(t *testing.T) { s := New(Options{ AllowedHosts: []string{"*\\.example\\.com"}, AllowedHostsAreRegex: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "sub.example.com" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Body.String(), `bar`) } func TestRegexMultipleAllowHosts(t *testing.T) { s := New(Options{ AllowedHosts: []string{".+\\.example\\.com", ".*sub\\..+-awesome-example\\.com"}, AllowedHostsAreRegex: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "sub.first-awesome-example.com" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Body.String(), `bar`) res = httptest.NewRecorder() req, _ = http.NewRequest("GET", "/foo", nil) req.Host = "test.sub.second-awesome-example.com" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Body.String(), `bar`) res = httptest.NewRecorder() req, _ = http.NewRequest("GET", "/foo", nil) req.Host = "test.sub.second-example.com" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusInternalServerError) } func TestInvalidRegexAllowHosts(t *testing.T) { defer func() { if r := recover(); r == nil { t.Errorf("The code did not panic") } }() New(Options{ AllowedHosts: []string{"[*.e"}, AllowedHostsAreRegex: true, }) } func TestGoodSingleAllowHostsProxyHeaders(t *testing.T) { s := New(Options{ AllowedHosts: []string{"www.example.com"}, HostsProxyHeaders: []string{"X-Proxy-Host"}, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "example-internal" req.Header.Set("X-Proxy-Host", "www.example.com") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Body.String(), `bar`) } func TestBadSingleAllowHostsProxyHeaders(t *testing.T) { s := New(Options{ AllowedHosts: []string{"sub.example.com"}, HostsProxyHeaders: []string{"X-Proxy-Host"}, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "example-internal" req.Header.Set("X-Proxy-Host", "www.example.com") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusInternalServerError) } func TestGoodMultipleAllowHosts(t *testing.T) { s := New(Options{ AllowedHosts: []string{"www.example.com", "sub.example.com"}, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "sub.example.com" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Body.String(), `bar`) } func TestBadMultipleAllowHosts(t *testing.T) { s := New(Options{ AllowedHosts: []string{"www.example.com", "sub.example.com"}, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www3.example.com" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusInternalServerError) } func TestAllowHostsInDevMode(t *testing.T) { s := New(Options{ AllowedHosts: []string{"www.example.com", "sub.example.com"}, IsDevelopment: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www3.example.com" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) } func TestBadHostHandler(t *testing.T) { s := New(Options{ AllowedHosts: []string{"www.example.com", "sub.example.com"}, }) badHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "BadHost", http.StatusInternalServerError) }) s.SetBadHostHandler(badHandler) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www3.example.com" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusInternalServerError) // http.Error outputs a new line character with the response. expect(t, res.Body.String(), "BadHost\n") } func TestSSL(t *testing.T) { s := New(Options{ SSLRedirect: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "https" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) } func TestSSLInDevMode(t *testing.T) { s := New(Options{ SSLRedirect: true, IsDevelopment: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) } func TestBasicSSL(t *testing.T) { s := New(Options{ SSLRedirect: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusMovedPermanently) expect(t, res.Header().Get("Location"), "https://www.example.com/foo") } func TestBasicSSLWithHost(t *testing.T) { s := New(Options{ SSLRedirect: true, SSLHost: "secure.example.com", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusMovedPermanently) expect(t, res.Header().Get("Location"), "https://secure.example.com/foo") } func TestBasicSSLWithHostFunc(t *testing.T) { sslHostFunc := (func() SSLHostFunc { isServerDown := false return func(host string) (newHost string) { if isServerDown { newHost = "404.example.com" return } if host == "www.example.com" { newHost = "secure.example.com:8443" } else if host == "www.example.org" { newHost = "secure.example.org" } return } })() s := New(Options{ SSLRedirect: true, SSLHostFunc: &sslHostFunc, }) // test www.example.com res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusMovedPermanently) expect(t, res.Header().Get("Location"), "https://secure.example.com:8443/foo") // test www.example.org res = httptest.NewRecorder() req, _ = http.NewRequest("GET", "/foo", nil) req.Host = "www.example.org" req.URL.Scheme = "http" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusMovedPermanently) expect(t, res.Header().Get("Location"), "https://secure.example.org/foo") // test other res = httptest.NewRecorder() req, _ = http.NewRequest("GET", "/foo", nil) req.Host = "www.other.com" req.URL.Scheme = "http" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusMovedPermanently) expect(t, res.Header().Get("Location"), "https://www.other.com/foo") } func TestBadProxySSL(t *testing.T) { s := New(Options{ SSLRedirect: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "https") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusMovedPermanently) expect(t, res.Header().Get("Location"), "https://www.example.com/foo") } func TestCustomProxySSL(t *testing.T) { s := New(Options{ SSLRedirect: true, SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "https") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) } func TestCustomProxySSLInDevMode(t *testing.T) { s := New(Options{ SSLRedirect: true, SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, IsDevelopment: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "http") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) } func TestCustomProxyAndHostProxyHeadersWithRedirect(t *testing.T) { s := New(Options{ HostsProxyHeaders: []string{"X-Forwarded-Host"}, SSLRedirect: true, SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "http"}, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "example-internal" req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "https") req.Header.Add("X-Forwarded-Host", "www.example.com") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusMovedPermanently) expect(t, res.Header().Get("Location"), "https://www.example.com/foo") } func TestCustomProxyAndHostSSL(t *testing.T) { s := New(Options{ SSLRedirect: true, SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, SSLHost: "secure.example.com", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "https") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) } func TestCustomBadProxyAndHostSSL(t *testing.T) { s := New(Options{ SSLRedirect: true, SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "superman"}, SSLHost: "secure.example.com", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "https") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusMovedPermanently) expect(t, res.Header().Get("Location"), "https://secure.example.com/foo") } func TestCustomBadProxyAndHostSSLWithTempRedirect(t *testing.T) { s := New(Options{ SSLRedirect: true, SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "superman"}, SSLHost: "secure.example.com", SSLTemporaryRedirect: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "https") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusTemporaryRedirect) expect(t, res.Header().Get("Location"), "https://secure.example.com/foo") } func TestStsHeaderWithNoSSL(t *testing.T) { s := New(Options{ STSSeconds: 315360000, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Strict-Transport-Security"), "") } func TestStsHeaderWithNoSSLButWithForce(t *testing.T) { s := New(Options{ STSSeconds: 315360000, ForceSTSHeader: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Strict-Transport-Security"), "max-age=315360000") } func TestStsHeaderWithNoSSLButWithForceForRequestOnly(t *testing.T) { s := New(Options{ STSSeconds: 315360000, ForceSTSHeader: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Strict-Transport-Security"), "") } func TestStsHeaderWithNoSSLButWithForceAndIsDev(t *testing.T) { s := New(Options{ STSSeconds: 315360000, ForceSTSHeader: true, IsDevelopment: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Strict-Transport-Security"), "") } func TestStsHeaderWithSSL(t *testing.T) { s := New(Options{ SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, STSSeconds: 315360000, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "https") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Strict-Transport-Security"), "max-age=315360000") } func TestStsHeaderWithSSLForRequestOnly(t *testing.T) { s := New(Options{ SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, STSSeconds: 315360000, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "https") s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Strict-Transport-Security"), "") } func TestStsHeaderInDevMode(t *testing.T) { s := New(Options{ STSSeconds: 315360000, IsDevelopment: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.URL.Scheme = "https" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Strict-Transport-Security"), "") } func TestStsHeaderWithSubdomains(t *testing.T) { s := New(Options{ STSSeconds: 315360000, STSIncludeSubdomains: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.URL.Scheme = "https" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Strict-Transport-Security"), "max-age=315360000; includeSubDomains") } func TestStsHeaderWithSubdomainsForRequestOnly(t *testing.T) { s := New(Options{ STSSeconds: 315360000, STSIncludeSubdomains: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.URL.Scheme = "https" s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Strict-Transport-Security"), "") } func TestStsHeaderWithPreload(t *testing.T) { s := New(Options{ STSSeconds: 315360000, STSPreload: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.URL.Scheme = "https" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Strict-Transport-Security"), "max-age=315360000; preload") } func TestStsHeaderWithPreloadForRequest(t *testing.T) { s := New(Options{ STSSeconds: 315360000, STSPreload: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.URL.Scheme = "https" s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Strict-Transport-Security"), "") } func TestStsHeaderWithSubdomainsWithPreload(t *testing.T) { s := New(Options{ STSSeconds: 315360000, STSIncludeSubdomains: true, STSPreload: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.URL.Scheme = "https" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Strict-Transport-Security"), "max-age=315360000; includeSubDomains; preload") } func TestStsHeaderWithSubdomainsWithPreloadForRequestOnly(t *testing.T) { s := New(Options{ STSSeconds: 315360000, STSIncludeSubdomains: true, STSPreload: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.URL.Scheme = "https" s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Strict-Transport-Security"), "") } func TestFrameDeny(t *testing.T) { s := New(Options{ FrameDeny: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-Frame-Options"), "DENY") } func TestFrameDenyForRequestOnly(t *testing.T) { s := New(Options{ FrameDeny: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-Frame-Options"), "") } func TestCustomFrameValue(t *testing.T) { s := New(Options{ CustomFrameOptionsValue: "SAMEORIGIN", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-Frame-Options"), "SAMEORIGIN") } func TestCustomFrameValueWithDeny(t *testing.T) { s := New(Options{ FrameDeny: true, CustomFrameOptionsValue: "SAMEORIGIN", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-Frame-Options"), "SAMEORIGIN") } func TestCustomFrameValueWithDenyForRequestOnly(t *testing.T) { s := New(Options{ FrameDeny: true, CustomFrameOptionsValue: "SAMEORIGIN", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-Frame-Options"), "") } func TestContentNosniff(t *testing.T) { s := New(Options{ ContentTypeNosniff: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-Content-Type-Options"), "nosniff") } func TestContentNosniffForRequestOnly(t *testing.T) { s := New(Options{ ContentTypeNosniff: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-Content-Type-Options"), "") } func TestXSSProtection(t *testing.T) { s := New(Options{ BrowserXssFilter: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-XSS-Protection"), "1; mode=block") } func TestXSSProtectionForRequestOnly(t *testing.T) { s := New(Options{ BrowserXssFilter: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-XSS-Protection"), "") } func TestCustomXSSProtection(t *testing.T) { xssVal := "1; report=https://example.com" s := New(Options{ CustomBrowserXssValue: xssVal, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-XSS-Protection"), xssVal) } func TestCustomXSSProtectionForRequestOnly(t *testing.T) { xssVal := "1; report=https://example.com" s := New(Options{ CustomBrowserXssValue: xssVal, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-XSS-Protection"), "") } func TestBothXSSProtection(t *testing.T) { xssVal := "0" s := New(Options{ BrowserXssFilter: true, CustomBrowserXssValue: xssVal, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-XSS-Protection"), xssVal) } func TestBothXSSProtectionForRequestOnly(t *testing.T) { xssVal := "0" s := New(Options{ BrowserXssFilter: true, CustomBrowserXssValue: xssVal, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-XSS-Protection"), "") } func TestCsp(t *testing.T) { s := New(Options{ ContentSecurityPolicy: "default-src 'self'", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Content-Security-Policy"), "default-src 'self'") } func TestCspForRequestOnly(t *testing.T) { s := New(Options{ ContentSecurityPolicy: "default-src 'self'", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Content-Security-Policy"), "") } func TestCspReportOnly(t *testing.T) { s := New(Options{ ContentSecurityPolicyReportOnly: "default-src 'self'", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Content-Security-Policy-Report-Only"), "default-src 'self'") } func TestCspReportOnlyForRequestOnly(t *testing.T) { s := New(Options{ ContentSecurityPolicyReportOnly: "default-src 'self'", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Content-Security-Policy-Report-Only"), "") } func TestInlineSecure(t *testing.T) { s := New(Options{ FrameDeny: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s.HandlerFuncWithNext(w, r, nil) w.Write([]byte("bar")) }) handler.ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-Frame-Options"), "DENY") } func TestInlineSecureForRequestOnly(t *testing.T) { s := New(Options{ FrameDeny: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s.HandlerFuncWithNextForRequestOnly(w, r, nil) w.Write([]byte("bar")) }) handler.ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("X-Frame-Options"), "") } // https://developer.mozilla.org/en-US/docs/Web/Security/Public_Key_Pinning const hpkp = `pin-sha256="cUPcTAZWKaASuYWhhneDttWpY3oBAkE3h2+soZS7sWs="; pin-sha256="M8HztCzM3elUxkcjR2S5P4hhyBNf6lHkmjAHKhpGPWE="; max-age=5184000; includeSubdomains; report-uri="https://www.example.net/hpkp-report"` func TestHPKP(t *testing.T) { s := New(Options{ PublicKey: hpkp, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.URL.Scheme = "https" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Public-Key-Pins"), hpkp) } func TestHPKPForRequestOnly(t *testing.T) { s := New(Options{ PublicKey: hpkp, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.URL.Scheme = "https" s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Public-Key-Pins"), "") } func TestHPKPNotSet(t *testing.T) { s := New() res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Public-Key-Pins"), "") } func TestHPKPNotSetForRequestOnly(t *testing.T) { s := New() res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Public-Key-Pins"), "") } func TestHPKPInDevMode(t *testing.T) { s := New(Options{ PublicKey: hpkp, IsDevelopment: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Public-Key-Pins"), "") } func TestHPKPInDevModeForRequestOnly(t *testing.T) { s := New(Options{ PublicKey: hpkp, IsDevelopment: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Public-Key-Pins"), "") } func TestHPKPNonSSL(t *testing.T) { s := New(Options{ PublicKey: hpkp, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Public-Key-Pins"), "") } func TestHPKPNonSSLForRequestOnly(t *testing.T) { s := New(Options{ PublicKey: hpkp, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Public-Key-Pins"), "") } func TestReferrer(t *testing.T) { s := New(Options{ ReferrerPolicy: "same-origin", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Referrer-Policy"), "same-origin") } func TestReferrerForRequestOnly(t *testing.T) { s := New(Options{ ReferrerPolicy: "same-origin", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.HandlerForRequestOnly(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Referrer-Policy"), "") } func TestFeaturePolicy(t *testing.T) { s := New(Options{ FeaturePolicy: "vibrate 'none';", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Feature-Policy"), "vibrate 'none';") } func TestPermissionsPolicy(t *testing.T) { s := New(Options{ PermissionsPolicy: "geolocation=(self)", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Permissions-Policy"), "geolocation=(self)") } func TestExpectCT(t *testing.T) { s := New(Options{ ExpectCTHeader: `enforce, max-age=30, report-uri="https://www.example.com/ct-report"`, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusOK) expect(t, res.Header().Get("Expect-CT"), `enforce, max-age=30, report-uri="https://www.example.com/ct-report"`) } func TestIsSSL(t *testing.T) { s := New(Options{ SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, }) req, _ := http.NewRequest("GET", "/foo", nil) expect(t, s.isSSL(req), false) req, _ = http.NewRequest("GET", "/foo", nil) req.TLS = &tls.ConnectionState{ CipherSuite: 16, } expect(t, s.isSSL(req), true) req, _ = http.NewRequest("GET", "/foo", nil) req.URL.Scheme = "https" expect(t, s.isSSL(req), true) req, _ = http.NewRequest("GET", "/foo", nil) req.Header.Add("X-Forwarded-Proto", "https") expect(t, s.isSSL(req), true) } func TestSSLForceHostWithHTTPS(t *testing.T) { s := New(Options{ SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, SSLHost: "secure.example.com", SSLForceHost: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "https" req.Header.Add("X-Forwarded-Proto", "https") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusMovedPermanently) } func TestSSLForceHostWithHTTP(t *testing.T) { s := New(Options{ SSLHost: "secure.example.com", SSLForceHost: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "http") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusMovedPermanently) } func TestSSLForceHostWithSSLRedirect(t *testing.T) { s := New(Options{ SSLRedirect: true, SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, SSLHost: "secure.example.com", SSLForceHost: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "https" req.Header.Add("X-Forwarded-Proto", "https") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusMovedPermanently) } func TestSSLForceHostTemporaryRedirect(t *testing.T) { s := New(Options{ SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, SSLHost: "secure.example.com", SSLForceHost: true, SSLTemporaryRedirect: true, }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "https" req.Header.Add("X-Forwarded-Proto", "https") s.Handler(myHandler).ServeHTTP(res, req) expect(t, res.Code, http.StatusTemporaryRedirect) } func TestModifyResponseHeadersNoSSL(t *testing.T) { s := New(Options{ SSLRedirect: false, }) res := &http.Response{} res.Header = http.Header{"Location": []string{"http://example.com"}} err := s.ModifyResponseHeaders(res) expect(t, err, nil) expect(t, res.Header.Get("Location"), "http://example.com") } func TestModifyResponseHeadersWithSSLAndDifferentSSLHost(t *testing.T) { s := New(Options{ SSLRedirect: true, SSLHost: "secure.example.com", SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, }) req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "https") res := &http.Response{} res.Header = http.Header{"Location": []string{"http://example.com"}} res.Request = req expect(t, res.Header.Get("Location"), "http://example.com") err := s.ModifyResponseHeaders(res) expect(t, err, nil) expect(t, res.Header.Get("Location"), "http://example.com") } func TestModifyResponseHeadersWithSSLAndNoSSLHost(t *testing.T) { s := New(Options{ SSLRedirect: true, SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, }) req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "https") res := &http.Response{} res.Header = http.Header{"Location": []string{"http://example.com"}} res.Request = req expect(t, res.Header.Get("Location"), "http://example.com") err := s.ModifyResponseHeaders(res) expect(t, err, nil) expect(t, res.Header.Get("Location"), "http://example.com") } func TestModifyResponseHeadersWithSSLAndMatchingSSLHost(t *testing.T) { s := New(Options{ SSLRedirect: true, SSLHost: "secure.example.com", SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, }) req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "https") res := &http.Response{} res.Header = http.Header{"Location": []string{"http://secure.example.com"}} res.Request = req expect(t, res.Header.Get("Location"), "http://secure.example.com") err := s.ModifyResponseHeaders(res) expect(t, err, nil) expect(t, res.Header.Get("Location"), "https://secure.example.com") } func TestModifyResponseHeadersWithSSLAndPortInLocationResponse(t *testing.T) { s := New(Options{ SSLRedirect: true, SSLHost: "secure.example.com", SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, }) req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "https") res := &http.Response{} res.Header = http.Header{"Location": []string{"http://secure.example.com:877"}} res.Request = req expect(t, res.Header.Get("Location"), "http://secure.example.com:877") err := s.ModifyResponseHeaders(res) expect(t, err, nil) expect(t, res.Header.Get("Location"), "http://secure.example.com:877") } func TestModifyResponseHeadersWithSSLAndPathInLocationResponse(t *testing.T) { s := New(Options{ SSLRedirect: true, SSLHost: "secure.example.com", SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, }) req, _ := http.NewRequest("GET", "/foo", nil) req.Host = "www.example.com" req.URL.Scheme = "http" req.Header.Add("X-Forwarded-Proto", "https") res := &http.Response{} res.Header = http.Header{"Location": []string{"http://secure.example.com/admin/login"}} res.Request = req expect(t, res.Header.Get("Location"), "http://secure.example.com/admin/login") err := s.ModifyResponseHeaders(res) expect(t, err, nil) expect(t, res.Header.Get("Location"), "https://secure.example.com/admin/login") } func TestCustomSecureContextKey(t *testing.T) { s1 := New(Options{ BrowserXssFilter: true, CustomBrowserXssValue: "0", SecureContextKey: "totallySecureContextKey", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) var actual *http.Request hf := func(w http.ResponseWriter, r *http.Request) { actual = r } s1.HandlerFuncWithNextForRequestOnly(res, req, hf) contextHeaders := actual.Context().Value(s1.ctxSecureHeaderKey).(http.Header) expect(t, contextHeaders.Get(xssProtectionHeader), s1.opt.CustomBrowserXssValue) } func TestMultipleCustomSecureContextKeys(t *testing.T) { s1 := New(Options{ BrowserXssFilter: true, CustomBrowserXssValue: "0", SecureContextKey: "totallySecureContextKey", }) s2 := New(Options{ FeaturePolicy: "test", SecureContextKey: "anotherSecureContextKey", }) res := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/foo", nil) var actual *http.Request hf := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { actual = r }) next := s1.HandlerForRequestOnly(hf) s2.HandlerFuncWithNextForRequestOnly(res, req, next.ServeHTTP) s1Headers := actual.Context().Value(s1.ctxSecureHeaderKey).(http.Header) s2Headers := actual.Context().Value(s2.ctxSecureHeaderKey).(http.Header) expect(t, s1Headers.Get(xssProtectionHeader), s1.opt.CustomBrowserXssValue) expect(t, s2Headers.Get(featurePolicyHeader), s2.opt.FeaturePolicy) } /* Test Helpers */ func expect(t *testing.T, a interface{}, b interface{}) { if a != b { t.Errorf("Expected [%v] (type %v) - Got [%v] (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) } }