pax_global_header00006660000000000000000000000064135467714360014532gustar00rootroot0000000000000052 comment=4b50158aba1b9683db9b198ddc61436713e778f8 csrf-1.6.2/000077500000000000000000000000001354677143600124755ustar00rootroot00000000000000csrf-1.6.2/.circleci/000077500000000000000000000000001354677143600143305ustar00rootroot00000000000000csrf-1.6.2/.circleci/config.yml000066400000000000000000000023301354677143600163160ustar00rootroot00000000000000version: 2.0 jobs: # Base test configuration for Go library tests Each distinct version should # inherit this base, and override (at least) the container image used. "test": &test docker: - image: circleci/golang:latest environment: GO111MODULE: "on" working_directory: /go/src/github.com/gorilla/csrf steps: &steps - checkout - run: go version - run: go get -t -v ./... - run: diff -u <(echo -n) <(gofmt -d .) - run: if [[ "$LATEST" = true ]]; then go vet -v ./...; fi - run: go test -v -race ./... "latest": <<: *test environment: LATEST: "true" GO111MODULE: "on" "1.12": <<: *test docker: - image: circleci/golang:1.12 "1.11": <<: *test docker: - image: circleci/golang:1.11 "1.10": <<: *test docker: - image: circleci/golang:1.10 "1.9": <<: *test docker: - image: circleci/golang:1.9 "1.8": <<: *test docker: - image: circleci/golang:1.8 "1.7": <<: *test docker: - image: circleci/golang:1.7 workflows: version: 2 build: jobs: - "latest" - "1.12" - "1.11" - "1.10" - "1.9" - "1.8" - "1.7" csrf-1.6.2/.github/000077500000000000000000000000001354677143600140355ustar00rootroot00000000000000csrf-1.6.2/.github/release-drafter.yml000066400000000000000000000002001354677143600176150ustar00rootroot00000000000000# Config for https://github.com/apps/release-drafter template: | ## CHANGELOG $CHANGES csrf-1.6.2/.github/stale.yml000066400000000000000000000005271354677143600156740ustar00rootroot00000000000000daysUntilStale: 60 daysUntilClose: 7 # Issues with these labels will never be considered stale exemptLabels: - v2 - needs-review - work-required staleLabel: stale markComment: > This issue has been automatically marked as stale because it hasn't seen a recent update. It'll be automatically closed in a few days. closeComment: false csrf-1.6.2/AUTHORS000066400000000000000000000013551354677143600135510ustar00rootroot00000000000000# This is the official list of gorilla/csrf authors for copyright purposes. # Please keep the list sorted. adiabatic Google LLC (https://opensource.google.com) jamesgroat Joshua Carp Kamil Kisiel Kevin Burke Kévin Dunglas Kristoffer Berdal Martin Angers Matt Silverlock Philip I. Thomas Richard Musiol Seth Hoenig Stefano Vettorazzi Wayne Ashley Berry 田浩浩 陈东海 csrf-1.6.2/Gopkg.lock000066400000000000000000000013261354677143600144200ustar00rootroot00000000000000# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. [[projects]] name = "github.com/gorilla/context" packages = ["."] revision = "1ea25387ff6f684839d82767c1733ff4d4d15d0a" version = "v1.1" [[projects]] name = "github.com/gorilla/securecookie" packages = ["."] revision = "667fe4e3466a040b780561fe9b51a83a3753eefc" version = "v1.1" [[projects]] name = "github.com/pkg/errors" packages = ["."] revision = "645ef00459ed84a119197bfb8d8205042c6df63d" version = "v0.8.0" [solve-meta] analyzer-name = "dep" analyzer-version = 1 inputs-digest = "1695686bc8fa0eb76df9fe8c5ca473686071ddcf795a0595a9465a03e8ac9bef" solver-name = "gps-cdcl" solver-version = 1 csrf-1.6.2/Gopkg.toml000066400000000000000000000013651354677143600144460ustar00rootroot00000000000000 # Gopkg.toml example # # Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md # for detailed Gopkg.toml documentation. # # required = ["github.com/user/thing/cmd/thing"] # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] # # [[constraint]] # name = "github.com/user/project" # version = "1.0.0" # # [[constraint]] # name = "github.com/user/project2" # branch = "dev" # source = "github.com/myfork/project2" # # [[override]] # name = "github.com/x/y" # version = "2.4.0" [[constraint]] name = "github.com/gorilla/context" version = "1.1.0" [[constraint]] name = "github.com/gorilla/securecookie" version = "1.1.0" [[constraint]] name = "github.com/pkg/errors" version = "0.8.0" csrf-1.6.2/LICENSE000066400000000000000000000027301354677143600135040ustar00rootroot00000000000000Copyright (c) 2015-2018, The Gorilla Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. csrf-1.6.2/README.md000066400000000000000000000307061354677143600137620ustar00rootroot00000000000000# gorilla/csrf [![GoDoc](https://godoc.org/github.com/gorilla/csrf?status.svg)](https://godoc.org/github.com/gorilla/csrf) [![Sourcegraph](https://sourcegraph.com/github.com/gorilla/csrf/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/csrf?badge) [![Reviewed by Hound](https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg)](https://houndci.com) [![CircleCI](https://circleci.com/gh/gorilla/csrf.svg?style=svg)](https://circleci.com/gh/gorilla/csrf) gorilla/csrf is a HTTP middleware library that provides [cross-site request forgery](http://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/) (CSRF) protection. It includes: - The `csrf.Protect` middleware/handler provides CSRF protection on routes attached to a router or a sub-router. - A `csrf.Token` function that provides the token to pass into your response, whether that be a HTML form or a JSON response body. - ... and a `csrf.TemplateField` helper that you can pass into your `html/template` templates to replace a `{{ .csrfField }}` template tag with a hidden input field. gorilla/csrf is designed to work with any Go web framework, including: - The [Gorilla](https://www.gorillatoolkit.org/) toolkit - Go's built-in [net/http](http://golang.org/pkg/net/http/) package - [Goji](https://goji.io) - see the [tailored fork](https://github.com/goji/csrf) - [Gin](https://github.com/gin-gonic/gin) - [Echo](https://github.com/labstack/echo) - ... and any other router/framework that rallies around Go's `http.Handler` interface. gorilla/csrf is also compatible with middleware 'helper' libraries like [Alice](https://github.com/justinas/alice) and [Negroni](https://github.com/codegangsta/negroni). ## Install With a properly configured Go toolchain: ```sh go get github.com/gorilla/csrf ``` ## Examples - [HTML Forms](#html-forms) - [JavaScript Apps](#javascript-applications) - [Google App Engine](#google-app-engine) - [Setting SameSite](#setting-samesite) - [Setting Options](#setting-options) gorilla/csrf is easy to use: add the middleware to your router with the below: ```go CSRF := csrf.Protect([]byte("32-byte-long-auth-key")) http.ListenAndServe(":8000", CSRF(r)) ``` ...and then collect the token with `csrf.Token(r)` in your handlers before passing it to the template, JSON body or HTTP header (see below). Note that the authentication key passed to `csrf.Protect([]byte(key))` should be 32-bytes long and persist across application restarts. Generating a random key won't allow you to authenticate existing cookies and will break your CSRF validation. gorilla/csrf inspects the HTTP headers (first) and form body (second) on subsequent POST/PUT/PATCH/DELETE/etc. requests for the token. ### HTML Forms Here's the common use-case: HTML forms you want to provide CSRF protection for, in order to protect malicious POST requests being made: ```go package main import ( "net/http" "github.com/gorilla/csrf" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() r.HandleFunc("/signup", ShowSignupForm) // All POST requests without a valid token will return HTTP 403 Forbidden. // We should also ensure that our mutating (non-idempotent) handler only // matches on POST requests. We can check that here, at the router level, or // within the handler itself via r.Method. r.HandleFunc("/signup/post", SubmitSignupForm).Methods("POST") // Add the middleware to your router by wrapping it. http.ListenAndServe(":8000", csrf.Protect([]byte("32-byte-long-auth-key"))(r)) // PS: Don't forget to pass csrf.Secure(false) if you're developing locally // over plain HTTP (just don't leave it on in production). } func ShowSignupForm(w http.ResponseWriter, r *http.Request) { // signup_form.tmpl just needs a {{ .csrfField }} template tag for // csrf.TemplateField to inject the CSRF token into. Easy! t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{ csrf.TemplateTag: csrf.TemplateField(r), }) // We could also retrieve the token directly from csrf.Token(r) and // set it in the request header - w.Header.Set("X-CSRF-Token", token) // This is useful if you're sending JSON to clients or a front-end JavaScript // framework. } func SubmitSignupForm(w http.ResponseWriter, r *http.Request) { // We can trust that requests making it this far have satisfied // our CSRF protection requirements. } ``` Note that the CSRF middleware will (by necessity) consume the request body if the token is passed via POST form values. If you need to consume this in your handler, insert your own middleware earlier in the chain to capture the request body. ### JavaScript Applications This approach is useful if you're using a front-end JavaScript framework like React, Ember or Angular, and are providing a JSON API. Specifically, we need to provide a way for our front-end fetch/AJAX calls to pass the token on each fetch (AJAX/XMLHttpRequest) request. We achieve this by: - Parsing the token from the `` field generated by the `csrf.TemplateField(r)` helper, or passing it back in a response header. - Sending this token back on every request - Ensuring our cookie is attached to the request so that the form/header value can be compared to the cookie value. We'll also look at applying selective CSRF protection using [gorilla/mux's](https://www.gorillatoolkit.org/pkg/mux) sub-routers, as we don't handle any POST/PUT/DELETE requests with our top-level router. ```go package main import ( "github.com/gorilla/csrf" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key")) api := r.PathPrefix("/api").Subrouter() api.Use(csrfMiddleware) api.HandleFunc("/user/{id}", GetUser).Methods("GET") http.ListenAndServe(":8000", r) } func GetUser(w http.ResponseWriter, r *http.Request) { // Authenticate the request, get the id from the route params, // and fetch the user from the DB, etc. // Get the token and pass it in the CSRF header. Our JSON-speaking client // or JavaScript framework can now read the header and return the token in // in its own "X-CSRF-Token" request header on the subsequent POST. w.Header().Set("X-CSRF-Token", csrf.Token(r)) b, err := json.Marshal(user) if err != nil { http.Error(w, err.Error(), 500) return } w.Write(b) } ``` In our JavaScript application, we should read the token from the response headers and pass it in a request header for all requests. Here's what that looks like when using [Axios](https://github.com/axios/axios), a popular JavaScript HTTP client library: ```js // You can alternatively parse the response header for the X-CSRF-Token, and // store that instead, if you followed the steps above to write the token to a // response header. let csrfToken = document.getElementsByName("gorilla.csrf.Token")[0].value // via https://github.com/axios/axios#creating-an-instance const instance = axios.create({ baseURL: "https://example.com/api/", timeout: 1000, headers: { "X-CSRF-Token": csrfToken } }) // Now, any HTTP request you make will include the csrfToken from the page, // provided you update the csrfToken variable for each render. try { let resp = await instance.post(endpoint, formData) // Do something with resp } catch (err) { // Handle the exception } ``` If you plan to host your JavaScript application on another domain, you can use the Trusted Origins feature to allow the host of your JavaScript application to make requests to your Go application. Observe the example below: ```go package main import ( "github.com/gorilla/csrf" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key"), csrf.TrustedOrigin([]string{"ui.domain.com"})) api := r.PathPrefix("/api").Subrouter() api.Use(csrfMiddleware) api.HandleFunc("/user/{id}", GetUser).Methods("GET") http.ListenAndServe(":8000", r) } func GetUser(w http.ResponseWriter, r *http.Request) { // Authenticate the request, get the id from the route params, // and fetch the user from the DB, etc. // Get the token and pass it in the CSRF header. Our JSON-speaking client // or JavaScript framework can now read the header and return the token in // in its own "X-CSRF-Token" request header on the subsequent POST. w.Header().Set("X-CSRF-Token", csrf.Token(r)) b, err := json.Marshal(user) if err != nil { http.Error(w, err.Error(), 500) return } w.Write(b) } ``` On the example above, you're authorizing requests from `ui.domain.com` to make valid CSRF requests to your application, so you can have your API server on another domain without problems. ### Google App Engine If you're using [Google App Engine](https://cloud.google.com/appengine/docs/go/how-requests-are-handled#Go_Requests_and_HTTP), (first-generation) which doesn't allow you to hook into the default `http.ServeMux` directly, you can still use gorilla/csrf (and gorilla/mux): ```go package app // Remember: appengine has its own package main func init() { r := mux.NewRouter() r.HandleFunc("/", IndexHandler) // ... // We pass our CSRF-protected router to the DefaultServeMux http.Handle("/", csrf.Protect([]byte(your-key))(r)) } ``` Note: You can ignore this if you're using the [second-generation](https://cloud.google.com/appengine/docs/go/) Go runtime on App Engine (Go 1.11 and above). ### Setting SameSite Go 1.11 introduced the option to set the SameSite attribute in cookies. This is valuable if a developer wants to instruct a browser to not include cookies during a cross site request. SameSiteStrictMode prevents all cross site requests from including the cookie. SameSiteLaxMode prevents CSRF prone requests (POST) from including the cookie but allows the cookie to be included in GET requests to support external linking. ```go func main() { CSRF := csrf.Protect( []byte("a-32-byte-long-key-goes-here"), // instruct the browser to never send cookies during cross site requests csrf.SameSite(csrf.SameSiteStrictMode), ) r := mux.NewRouter() r.HandleFunc("/signup", GetSignupForm) r.HandleFunc("/signup/post", PostSignupForm) http.ListenAndServe(":8000", CSRF(r)) } ``` ### Setting Options What about providing your own error handler and changing the HTTP header the package inspects on requests? (i.e. an existing API you're porting to Go). Well, gorilla/csrf provides options for changing these as you see fit: ```go func main() { CSRF := csrf.Protect( []byte("a-32-byte-long-key-goes-here"), csrf.RequestHeader("Authenticity-Token"), csrf.FieldName("authenticity_token"), csrf.ErrorHandler(http.HandlerFunc(serverError(403))), ) r := mux.NewRouter() r.HandleFunc("/signup", GetSignupForm) r.HandleFunc("/signup/post", PostSignupForm) http.ListenAndServe(":8000", CSRF(r)) } ``` Not too bad, right? If there's something you're confused about or a feature you would like to see added, open an issue. ## Design Notes Getting CSRF protection right is important, so here's some background: - This library generates unique-per-request (masked) tokens as a mitigation against the [BREACH attack](http://breachattack.com/). - The 'base' (unmasked) token is stored in the session, which means that multiple browser tabs won't cause a user problems as their per-request token is compared with the base token. - Operates on a "whitelist only" approach where safe (non-mutating) HTTP methods (GET, HEAD, OPTIONS, TRACE) are the _only_ methods where token validation is not enforced. - The design is based on the battle-tested [Django](https://docs.djangoproject.com/en/1.8/ref/csrf/) and [Ruby on Rails](http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html) approaches. - Cookies are authenticated and based on the [securecookie](https://github.com/gorilla/securecookie) library. They're also Secure (issued over HTTPS only) and are HttpOnly by default, because sane defaults are important. - Cookie SameSite attribute (prevents cookies from being sent by a browser during cross site requests) are not set by default to maintain backwards compatibility for legacy systems. The SameSite attribute can be set with the SameSite option. - Go's `crypto/rand` library is used to generate the 32 byte (256 bit) tokens and the one-time-pad used for masking them. This library does not seek to be adventurous. ## License BSD licensed. See the LICENSE file for details. csrf-1.6.2/context.go000066400000000000000000000010331354677143600145050ustar00rootroot00000000000000// +build go1.7 package csrf import ( "context" "net/http" "github.com/pkg/errors" ) func contextGet(r *http.Request, key string) (interface{}, error) { val := r.Context().Value(key) if val == nil { return nil, errors.Errorf("no value exists in the context for key %q", key) } return val, nil } func contextSave(r *http.Request, key string, val interface{}) *http.Request { ctx := r.Context() ctx = context.WithValue(ctx, key, val) return r.WithContext(ctx) } func contextClear(r *http.Request) { // no-op for go1.7+ } csrf-1.6.2/csrf.go000066400000000000000000000220561354677143600137660ustar00rootroot00000000000000package csrf import ( "fmt" "net/http" "net/url" "github.com/pkg/errors" "github.com/gorilla/securecookie" ) // CSRF token length in bytes. const tokenLength = 32 // Context/session keys & prefixes const ( tokenKey string = "gorilla.csrf.Token" formKey string = "gorilla.csrf.Form" errorKey string = "gorilla.csrf.Error" skipCheckKey string = "gorilla.csrf.Skip" cookieName string = "_gorilla_csrf" errorPrefix string = "gorilla/csrf: " ) var ( // The name value used in form fields. fieldName = tokenKey // defaultAge sets the default MaxAge for cookies. defaultAge = 3600 * 12 // The default HTTP request header to inspect headerName = "X-CSRF-Token" // Idempotent (safe) methods as defined by RFC7231 section 4.2.2. safeMethods = []string{"GET", "HEAD", "OPTIONS", "TRACE"} ) // TemplateTag provides a default template tag - e.g. {{ .csrfField }} - for use // with the TemplateField function. var TemplateTag = "csrfField" var ( // ErrNoReferer is returned when a HTTPS request provides an empty Referer // header. ErrNoReferer = errors.New("referer not supplied") // ErrBadReferer is returned when the scheme & host in the URL do not match // the supplied Referer header. ErrBadReferer = errors.New("referer invalid") // ErrNoToken is returned if no CSRF token is supplied in the request. ErrNoToken = errors.New("CSRF token not found in request") // ErrBadToken is returned if the CSRF token in the request does not match // the token in the session, or is otherwise malformed. ErrBadToken = errors.New("CSRF token invalid") ) // SameSiteMode allows a server to define a cookie attribute making it impossible for // the browser to send this cookie along with cross-site requests. The main // goal is to mitigate the risk of cross-origin information leakage, and provide // some protection against cross-site request forgery attacks. // // See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details. type SameSiteMode int // SameSite options const ( SameSiteDefaultMode SameSiteMode = iota + 1 SameSiteLaxMode SameSiteStrictMode SameSiteNoneMode ) type csrf struct { h http.Handler sc *securecookie.SecureCookie st store opts options } // options contains the optional settings for the CSRF middleware. type options struct { MaxAge int Domain string Path string // Note that the function and field names match the case of the associated // http.Cookie field instead of the "correct" HTTPOnly name that golint suggests. HttpOnly bool Secure bool SameSite SameSiteMode RequestHeader string FieldName string ErrorHandler http.Handler CookieName string TrustedOrigins []string } // Protect is HTTP middleware that provides Cross-Site Request Forgery // protection. // // It securely generates a masked (unique-per-request) token that // can be embedded in the HTTP response (e.g. form field or HTTP header). // The original (unmasked) token is stored in the session, which is inaccessible // by an attacker (provided you are using HTTPS). Subsequent requests are // expected to include this token, which is compared against the session token. // Requests that do not provide a matching token are served with a HTTP 403 // 'Forbidden' error response. // // Example: // package main // // import ( // "html/template" // // "github.com/gorilla/csrf" // "github.com/gorilla/mux" // ) // // var t = template.Must(template.New("signup_form.tmpl").Parse(form)) // // func main() { // r := mux.NewRouter() // // r.HandleFunc("/signup", GetSignupForm) // // POST requests without a valid token will return a HTTP 403 Forbidden. // r.HandleFunc("/signup/post", PostSignupForm) // // // Add the middleware to your router. // http.ListenAndServe(":8000", // // Note that the authentication key provided should be 32 bytes // // long and persist across application restarts. // csrf.Protect([]byte("32-byte-long-auth-key"))(r)) // } // // func GetSignupForm(w http.ResponseWriter, r *http.Request) { // // signup_form.tmpl just needs a {{ .csrfField }} template tag for // // csrf.TemplateField to inject the CSRF token into. Easy! // t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{ // csrf.TemplateTag: csrf.TemplateField(r), // }) // // We could also retrieve the token directly from csrf.Token(r) and // // set it in the request header - w.Header.Set("X-CSRF-Token", token) // // This is useful if you're sending JSON to clients or a front-end JavaScript // // framework. // } // func Protect(authKey []byte, opts ...Option) func(http.Handler) http.Handler { return func(h http.Handler) http.Handler { cs := parseOptions(h, opts...) // Set the defaults if no options have been specified if cs.opts.ErrorHandler == nil { cs.opts.ErrorHandler = http.HandlerFunc(unauthorizedHandler) } if cs.opts.MaxAge < 0 { // Default of 12 hours cs.opts.MaxAge = defaultAge } if cs.opts.FieldName == "" { cs.opts.FieldName = fieldName } if cs.opts.CookieName == "" { cs.opts.CookieName = cookieName } if cs.opts.RequestHeader == "" { cs.opts.RequestHeader = headerName } // Create an authenticated securecookie instance. if cs.sc == nil { cs.sc = securecookie.New(authKey, nil) // Use JSON serialization (faster than one-off gob encoding) cs.sc.SetSerializer(securecookie.JSONEncoder{}) // Set the MaxAge of the underlying securecookie. cs.sc.MaxAge(cs.opts.MaxAge) } if cs.st == nil { // Default to the cookieStore cs.st = &cookieStore{ name: cs.opts.CookieName, maxAge: cs.opts.MaxAge, secure: cs.opts.Secure, httpOnly: cs.opts.HttpOnly, sameSite: cs.opts.SameSite, path: cs.opts.Path, domain: cs.opts.Domain, sc: cs.sc, } } return cs } } // Implements http.Handler for the csrf type. func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Skip the check if directed to. This should always be a bool. if val, err := contextGet(r, skipCheckKey); err == nil { if skip, ok := val.(bool); ok { if skip { cs.h.ServeHTTP(w, r) return } } } // Retrieve the token from the session. // An error represents either a cookie that failed HMAC validation // or that doesn't exist. realToken, err := cs.st.Get(r) if err != nil || len(realToken) != tokenLength { // If there was an error retrieving the token, the token doesn't exist // yet, or it's the wrong length, generate a new token. // Note that the new token will (correctly) fail validation downstream // as it will no longer match the request token. realToken, err = generateRandomBytes(tokenLength) if err != nil { r = envError(r, err) cs.opts.ErrorHandler.ServeHTTP(w, r) return } // Save the new (real) token in the session store. err = cs.st.Save(realToken, w) if err != nil { r = envError(r, err) cs.opts.ErrorHandler.ServeHTTP(w, r) return } } // Save the masked token to the request context r = contextSave(r, tokenKey, mask(realToken, r)) // Save the field name to the request context r = contextSave(r, formKey, cs.opts.FieldName) // HTTP methods not defined as idempotent ("safe") under RFC7231 require // inspection. if !contains(safeMethods, r.Method) { // Enforce an origin check for HTTPS connections. As per the Django CSRF // implementation (https://goo.gl/vKA7GE) the Referer header is almost // always present for same-domain HTTP requests. if r.URL.Scheme == "https" { // Fetch the Referer value. Call the error handler if it's empty or // otherwise fails to parse. referer, err := url.Parse(r.Referer()) if err != nil || referer.String() == "" { r = envError(r, ErrNoReferer) cs.opts.ErrorHandler.ServeHTTP(w, r) return } valid := sameOrigin(r.URL, referer) if !valid { for _, trustedOrigin := range cs.opts.TrustedOrigins { if referer.Host == trustedOrigin { valid = true break } } } if valid == false { r = envError(r, ErrBadReferer) cs.opts.ErrorHandler.ServeHTTP(w, r) return } } // If the token returned from the session store is nil for non-idempotent // ("unsafe") methods, call the error handler. if realToken == nil { r = envError(r, ErrNoToken) cs.opts.ErrorHandler.ServeHTTP(w, r) return } // Retrieve the combined token (pad + masked) token and unmask it. requestToken := unmask(cs.requestToken(r)) // Compare the request token against the real token if !compareTokens(requestToken, realToken) { r = envError(r, ErrBadToken) cs.opts.ErrorHandler.ServeHTTP(w, r) return } } // Set the Vary: Cookie header to protect clients from caching the response. w.Header().Add("Vary", "Cookie") // Call the wrapped handler/router on success. cs.h.ServeHTTP(w, r) // Clear the request context after the handler has completed. contextClear(r) } // unauthorizedhandler sets a HTTP 403 Forbidden status and writes the // CSRF failure reason to the response. func unauthorizedHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, fmt.Sprintf("%s - %s", http.StatusText(http.StatusForbidden), FailureReason(r)), http.StatusForbidden) return } csrf-1.6.2/csrf_test.go000066400000000000000000000240111354677143600150160ustar00rootroot00000000000000package csrf import ( "net/http" "net/http/httptest" "strings" "testing" ) var testKey = []byte("keep-it-secret-keep-it-safe-----") var testHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) // TestProtect is a high-level test to make sure the middleware returns the // wrapped handler with a 200 OK status. func TestProtect(t *testing.T) { s := http.NewServeMux() s.HandleFunc("/", testHandler) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p := Protect(testKey)(s) p.ServeHTTP(rr, r) if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } if rr.Header().Get("Set-Cookie") == "" { t.Fatalf("cookie not set: got %q", rr.Header().Get("Set-Cookie")) } cookie := rr.Header().Get("Set-Cookie") if !strings.Contains(cookie, "HttpOnly") || !strings.Contains(cookie, "Secure") { t.Fatalf("cookie does not default to Secure & HttpOnly: got %v", cookie) } } // TestCookieOptions is a test to make sure the middleware correctly sets cookie options func TestCookieOptions(t *testing.T) { s := http.NewServeMux() s.HandleFunc("/", testHandler) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p := Protect(testKey, CookieName("nameoverride"), Secure(false), HttpOnly(false), Path("/pathoverride"), Domain("domainoverride"), MaxAge(173))(s) p.ServeHTTP(rr, r) if rr.Header().Get("Set-Cookie") == "" { t.Fatalf("cookie not set: got %q", rr.Header().Get("Set-Cookie")) } cookie := rr.Header().Get("Set-Cookie") if strings.Contains(cookie, "HttpOnly") { t.Fatalf("cookie does not respect HttpOnly option: got %v do not want HttpOnly", cookie) } if strings.Contains(cookie, "Secure") { t.Fatalf("cookie does not respect Secure option: got %v do not want Secure", cookie) } if !strings.Contains(cookie, "nameoverride=") { t.Fatalf("cookie does not respect CookieName option: got %v want %v", cookie, "nameoverride=") } if !strings.Contains(cookie, "Domain=domainoverride") { t.Fatalf("cookie does not respect Domain option: got %v want %v", cookie, "Domain=domainoverride") } if !strings.Contains(cookie, "Max-Age=173") { t.Fatalf("cookie does not respect MaxAge option: got %v want %v", cookie, "Max-Age=173") } } // Test that idempotent methods return a 200 OK status and that non-idempotent // methods return a 403 Forbidden status when a CSRF cookie is not present. func TestMethods(t *testing.T) { s := http.NewServeMux() s.HandleFunc("/", testHandler) p := Protect(testKey)(s) // Test idempontent ("safe") methods for _, method := range safeMethods { r, err := http.NewRequest(method, "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p.ServeHTTP(rr, r) if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } if rr.Header().Get("Set-Cookie") == "" { t.Fatalf("cookie not set: got %q", rr.Header().Get("Set-Cookie")) } } // Test non-idempotent methods (should return a 403 without a cookie set) nonIdempotent := []string{"POST", "PUT", "DELETE", "PATCH"} for _, method := range nonIdempotent { r, err := http.NewRequest(method, "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p.ServeHTTP(rr, r) if rr.Code != http.StatusForbidden { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } if rr.Header().Get("Set-Cookie") == "" { t.Fatalf("cookie not set: got %q", rr.Header().Get("Set-Cookie")) } } } // Tests for failure if the cookie containing the session does not exist on a // POST request. func TestNoCookie(t *testing.T) { s := http.NewServeMux() p := Protect(testKey)(s) // POST the token back in the header. r, err := http.NewRequest("POST", "http://www.gorillatoolkit.org/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p.ServeHTTP(rr, r) if rr.Code != http.StatusForbidden { t.Fatalf("middleware failed to reject a non-existent cookie: got %v want %v", rr.Code, http.StatusForbidden) } } // TestBadCookie tests for failure when a cookie header is modified (malformed). func TestBadCookie(t *testing.T) { s := http.NewServeMux() p := Protect(testKey)(s) var token string s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token = Token(r) })) // Obtain a CSRF cookie via a GET request. r, err := http.NewRequest("GET", "http://www.gorillatoolkit.org/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p.ServeHTTP(rr, r) // POST the token back in the header. r, err = http.NewRequest("POST", "http://www.gorillatoolkit.org/", nil) if err != nil { t.Fatal(err) } // Replace the cookie prefix badHeader := strings.Replace(cookieName+"=", rr.Header().Get("Set-Cookie"), "_badCookie", -1) r.Header.Set("Cookie", badHeader) r.Header.Set("X-CSRF-Token", token) r.Header.Set("Referer", "http://www.gorillatoolkit.org/") rr = httptest.NewRecorder() p.ServeHTTP(rr, r) if rr.Code != http.StatusForbidden { t.Fatalf("middleware failed to reject a bad cookie: got %v want %v", rr.Code, http.StatusForbidden) } } // Responses should set a "Vary: Cookie" header to protect client/proxy caching. func TestVaryHeader(t *testing.T) { s := http.NewServeMux() s.HandleFunc("/", testHandler) p := Protect(testKey)(s) r, err := http.NewRequest("HEAD", "https://www.golang.org/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p.ServeHTTP(rr, r) if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } if rr.Header().Get("Vary") != "Cookie" { t.Fatalf("vary header not set: got %q want %q", rr.Header().Get("Vary"), "Cookie") } } // Requests with no Referer header should fail. func TestNoReferer(t *testing.T) { s := http.NewServeMux() s.HandleFunc("/", testHandler) p := Protect(testKey)(s) r, err := http.NewRequest("POST", "https://golang.org/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p.ServeHTTP(rr, r) if rr.Code != http.StatusForbidden { t.Fatalf("middleware failed reject an empty Referer header: got %v want %v", rr.Code, http.StatusForbidden) } } // TestBadReferer checks that HTTPS requests with a Referer that does not // match the request URL correctly fail CSRF validation. func TestBadReferer(t *testing.T) { s := http.NewServeMux() p := Protect(testKey)(s) var token string s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token = Token(r) })) // Obtain a CSRF cookie via a GET request. r, err := http.NewRequest("GET", "https://www.gorillatoolkit.org/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p.ServeHTTP(rr, r) // POST the token back in the header. r, err = http.NewRequest("POST", "https://www.gorillatoolkit.org/", nil) if err != nil { t.Fatal(err) } setCookie(rr, r) r.Header.Set("X-CSRF-Token", token) // Set a non-matching Referer header. r.Header.Set("Referer", "http://golang.org/") rr = httptest.NewRecorder() p.ServeHTTP(rr, r) if rr.Code != http.StatusForbidden { t.Fatalf("middleware failed reject a non-matching Referer header: got %v want %v", rr.Code, http.StatusForbidden) } } // TestTrustedReferer checks that HTTPS requests with a Referer that does not // match the request URL correctly but is a trusted origin pass CSRF validation. func TestTrustedReferer(t *testing.T) { testTable := []struct { trustedOrigin []string shouldPass bool }{ {[]string{"golang.org"}, true}, {[]string{"api.example.com", "golang.org"}, true}, {[]string{"http://golang.org"}, false}, {[]string{"https://golang.org"}, false}, {[]string{"http://example.com"}, false}, {[]string{"example.com"}, false}, } for _, item := range testTable { s := http.NewServeMux() p := Protect(testKey, TrustedOrigins(item.trustedOrigin))(s) var token string s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token = Token(r) })) // Obtain a CSRF cookie via a GET request. r, err := http.NewRequest("GET", "https://www.gorillatoolkit.org/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p.ServeHTTP(rr, r) // POST the token back in the header. r, err = http.NewRequest("POST", "https://www.gorillatoolkit.org/", nil) if err != nil { t.Fatal(err) } setCookie(rr, r) r.Header.Set("X-CSRF-Token", token) // Set a non-matching Referer header. r.Header.Set("Referer", "http://golang.org/") rr = httptest.NewRecorder() p.ServeHTTP(rr, r) if item.shouldPass { if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } } else { if rr.Code != http.StatusForbidden { t.Fatalf("middleware failed reject a non-matching Referer header: got %v want %v", rr.Code, http.StatusForbidden) } } } } // Requests with a valid Referer should pass. func TestWithReferer(t *testing.T) { s := http.NewServeMux() p := Protect(testKey)(s) var token string s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token = Token(r) })) // Obtain a CSRF cookie via a GET request. r, err := http.NewRequest("GET", "http://www.gorillatoolkit.org/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p.ServeHTTP(rr, r) // POST the token back in the header. r, err = http.NewRequest("POST", "http://www.gorillatoolkit.org/", nil) if err != nil { t.Fatal(err) } setCookie(rr, r) r.Header.Set("X-CSRF-Token", token) r.Header.Set("Referer", "http://www.gorillatoolkit.org/") rr = httptest.NewRecorder() p.ServeHTTP(rr, r) if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } } func setCookie(rr *httptest.ResponseRecorder, r *http.Request) { r.Header.Set("Cookie", rr.Header().Get("Set-Cookie")) } csrf-1.6.2/doc.go000066400000000000000000000136141354677143600135760ustar00rootroot00000000000000/* Package csrf (gorilla/csrf) provides Cross Site Request Forgery (CSRF) prevention middleware for Go web applications & services. It includes: * The `csrf.Protect` middleware/handler provides CSRF protection on routes attached to a router or a sub-router. * A `csrf.Token` function that provides the token to pass into your response, whether that be a HTML form or a JSON response body. * ... and a `csrf.TemplateField` helper that you can pass into your `html/template` templates to replace a `{{ .csrfField }}` template tag with a hidden input field. gorilla/csrf is easy to use: add the middleware to individual handlers with the below: CSRF := csrf.Protect([]byte("32-byte-long-auth-key")) http.HandlerFunc("/route", CSRF(YourHandler)) ... and then collect the token with `csrf.Token(r)` before passing it to the template, JSON body or HTTP header (you pick!). gorilla/csrf inspects the form body (first) and HTTP headers (second) on subsequent POST/PUT/PATCH/DELETE/etc. requests for the token. Note that the authentication key passed to `csrf.Protect([]byte(key))` should be 32-bytes long and persist across application restarts. Generating a random key won't allow you to authenticate existing cookies and will break your CSRF validation. Here's the common use-case: HTML forms you want to provide CSRF protection for, in order to protect malicious POST requests being made: package main import ( "fmt" "html/template" "net/http" "github.com/gorilla/csrf" "github.com/gorilla/mux" ) var form = ` Sign Up!
{{ .csrfField }}
` var t = template.Must(template.New("signup_form.tmpl").Parse(form)) func main() { r := mux.NewRouter() r.HandleFunc("/signup", ShowSignupForm) // All POST requests without a valid token will return HTTP 403 Forbidden. // We should also ensure that our mutating (non-idempotent) handler only // matches on POST requests. We can check that here, at the router level, or // within the handler itself via r.Method. r.HandleFunc("/signup/post", SubmitSignupForm).Methods("POST") // Add the middleware to your router by wrapping it. http.ListenAndServe(":8000", csrf.Protect([]byte("32-byte-long-auth-key"))(r)) // PS: Don't forget to pass csrf.Secure(false) if you're developing locally // over plain HTTP (just don't leave it on in production). } func ShowSignupForm(w http.ResponseWriter, r *http.Request) { // signup_form.tmpl just needs a {{ .csrfField }} template tag for // csrf.TemplateField to inject the CSRF token into. Easy! t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{ csrf.TemplateTag: csrf.TemplateField(r), }) } func SubmitSignupForm(w http.ResponseWriter, r *http.Request) { // We can trust that requests making it this far have satisfied // our CSRF protection requirements. fmt.Fprintf(w, "%v\n", r.PostForm) } Note that the CSRF middleware will (by necessity) consume the request body if the token is passed via POST form values. If you need to consume this in your handler, insert your own middleware earlier in the chain to capture the request body. You can also send the CSRF token in the response header. This approach is useful if you're using a front-end JavaScript framework like Ember or Angular, or are providing a JSON API: package main import ( "github.com/gorilla/csrf" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() api := r.PathPrefix("/api").Subrouter() api.HandleFunc("/user/:id", GetUser).Methods("GET") http.ListenAndServe(":8000", csrf.Protect([]byte("32-byte-long-auth-key"))(r)) } func GetUser(w http.ResponseWriter, r *http.Request) { // Authenticate the request, get the id from the route params, // and fetch the user from the DB, etc. // Get the token and pass it in the CSRF header. Our JSON-speaking client // or JavaScript framework can now read the header and return the token in // in its own "X-CSRF-Token" request header on the subsequent POST. w.Header().Set("X-CSRF-Token", csrf.Token(r)) b, err := json.Marshal(user) if err != nil { http.Error(w, err.Error(), 500) return } w.Write(b) } If you're writing a client that's supposed to mimic browser behavior, make sure to send back the CSRF cookie (the default name is _gorilla_csrf, but this can be changed with the CookieName Option) along with either the X-CSRF-Token header or the gorilla.csrf.Token form field. In addition: getting CSRF protection right is important, so here's some background: * This library generates unique-per-request (masked) tokens as a mitigation against the BREACH attack (http://breachattack.com/). * The 'base' (unmasked) token is stored in the session, which means that multiple browser tabs won't cause a user problems as their per-request token is compared with the base token. * Operates on a "whitelist only" approach where safe (non-mutating) HTTP methods (GET, HEAD, OPTIONS, TRACE) are the *only* methods where token validation is not enforced. * The design is based on the battle-tested Django (https://docs.djangoproject.com/en/1.8/ref/csrf/) and Ruby on Rails (http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html) approaches. * Cookies are authenticated and based on the securecookie (https://github.com/gorilla/securecookie) library. They're also Secure (issued over HTTPS only) and are HttpOnly by default, because sane defaults are important. * Go's `crypto/rand` library is used to generate the 32 byte (256 bit) tokens and the one-time-pad used for masking them. This library does not seek to be adventurous. */ package csrf csrf-1.6.2/go.mod000066400000000000000000000001621354677143600136020ustar00rootroot00000000000000module github.com/gorilla/csrf require ( github.com/gorilla/securecookie v1.1.1 github.com/pkg/errors v0.8.0 ) csrf-1.6.2/go.sum000066400000000000000000000005261354677143600136330ustar00rootroot00000000000000github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= csrf-1.6.2/helpers.go000066400000000000000000000132721354677143600144730ustar00rootroot00000000000000package csrf import ( "crypto/rand" "crypto/subtle" "encoding/base64" "fmt" "html/template" "net/http" "net/url" ) // Token returns a masked CSRF token ready for passing into HTML template or // a JSON response body. An empty token will be returned if the middleware // has not been applied (which will fail subsequent validation). func Token(r *http.Request) string { if val, err := contextGet(r, tokenKey); err == nil { if maskedToken, ok := val.(string); ok { return maskedToken } } return "" } // FailureReason makes CSRF validation errors available in the request context. // This is useful when you want to log the cause of the error or report it to // client. func FailureReason(r *http.Request) error { if val, err := contextGet(r, errorKey); err == nil { if err, ok := val.(error); ok { return err } } return nil } // UnsafeSkipCheck will skip the CSRF check for any requests. This must be // called before the CSRF middleware. // // Note: You should not set this without otherwise securing the request from // CSRF attacks. The primary use-case for this function is to turn off CSRF // checks for non-browser clients using authorization tokens against your API. func UnsafeSkipCheck(r *http.Request) *http.Request { return contextSave(r, skipCheckKey, true) } // TemplateField is a template helper for html/template that provides an field // populated with a CSRF token. // // Example: // // // The following tag in our form.tmpl template: // {{ .csrfField }} // // // ... becomes: // // func TemplateField(r *http.Request) template.HTML { if name, err := contextGet(r, formKey); err == nil { fragment := fmt.Sprintf(``, name, Token(r)) return template.HTML(fragment) } return template.HTML("") } // mask returns a unique-per-request token to mitigate the BREACH attack // as per http://breachattack.com/#mitigations // // The token is generated by XOR'ing a one-time-pad and the base (session) CSRF // token and returning them together as a 64-byte slice. This effectively // randomises the token on a per-request basis without breaking multiple browser // tabs/windows. func mask(realToken []byte, r *http.Request) string { otp, err := generateRandomBytes(tokenLength) if err != nil { return "" } // XOR the OTP with the real token to generate a masked token. Append the // OTP to the front of the masked token to allow unmasking in the subsequent // request. return base64.StdEncoding.EncodeToString(append(otp, xorToken(otp, realToken)...)) } // unmask splits the issued token (one-time-pad + masked token) and returns the // unmasked request token for comparison. func unmask(issued []byte) []byte { // Issued tokens are always masked and combined with the pad. if len(issued) != tokenLength*2 { return nil } // We now know the length of the byte slice. otp := issued[tokenLength:] masked := issued[:tokenLength] // Unmask the token by XOR'ing it against the OTP used to mask it. return xorToken(otp, masked) } // requestToken returns the issued token (pad + masked token) from the HTTP POST // body or HTTP header. It will return nil if the token fails to decode. func (cs *csrf) requestToken(r *http.Request) []byte { // 1. Check the HTTP header first. issued := r.Header.Get(cs.opts.RequestHeader) // 2. Fall back to the POST (form) value. if issued == "" { issued = r.PostFormValue(cs.opts.FieldName) } // 3. Finally, fall back to the multipart form (if set). if issued == "" && r.MultipartForm != nil { vals := r.MultipartForm.Value[cs.opts.FieldName] if len(vals) > 0 { issued = vals[0] } } // Decode the "issued" (pad + masked) token sent in the request. Return a // nil byte slice on a decoding error (this will fail upstream). decoded, err := base64.StdEncoding.DecodeString(issued) if err != nil { return nil } return decoded } // generateRandomBytes returns securely generated random bytes. // It will return an error if the system's secure random number generator // fails to function correctly. func generateRandomBytes(n int) ([]byte, error) { b := make([]byte, n) _, err := rand.Read(b) // err == nil only if len(b) == n if err != nil { return nil, err } return b, nil } // sameOrigin returns true if URLs a and b share the same origin. The same // origin is defined as host (which includes the port) and scheme. func sameOrigin(a, b *url.URL) bool { return (a.Scheme == b.Scheme && a.Host == b.Host) } // compare securely (constant-time) compares the unmasked token from the request // against the real token from the session. func compareTokens(a, b []byte) bool { // This is required as subtle.ConstantTimeCompare does not check for equal // lengths in Go versions prior to 1.3. if len(a) != len(b) { return false } return subtle.ConstantTimeCompare(a, b) == 1 } // xorToken XORs tokens ([]byte) to provide unique-per-request CSRF tokens. It // will return a masked token if the base token is XOR'ed with a one-time-pad. // An unmasked token will be returned if a masked token is XOR'ed with the // one-time-pad used to mask it. func xorToken(a, b []byte) []byte { n := len(a) if len(b) < n { n = len(b) } res := make([]byte, n) for i := 0; i < n; i++ { res[i] = a[i] ^ b[i] } return res } // contains is a helper function to check if a string exists in a slice - e.g. // whether a HTTP method exists in a list of safe methods. func contains(vals []string, s string) bool { for _, v := range vals { if v == s { return true } } return false } // envError stores a CSRF error in the request context. func envError(r *http.Request, err error) *http.Request { return contextSave(r, errorKey, err) } csrf-1.6.2/helpers_test.go000066400000000000000000000167331354677143600155370ustar00rootroot00000000000000package csrf import ( "bytes" "crypto/rand" "encoding/base64" "fmt" "io" "mime/multipart" "net/http" "net/http/httptest" "net/url" "strings" "testing" "text/template" ) var testTemplate = `
{{ .csrfField }}
` // Test that our form helpers correctly inject a token into the response body. func TestFormToken(t *testing.T) { s := http.NewServeMux() // Make the token available outside of the handler for comparison. var token string s.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token = Token(r) t := template.Must((template.New("base").Parse(testTemplate))) t.Execute(w, map[string]interface{}{ TemplateTag: TemplateField(r), }) })) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p := Protect(testKey)(s) p.ServeHTTP(rr, r) if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } if len(token) != base64.StdEncoding.EncodedLen(tokenLength*2) { t.Fatalf("token length invalid: got %v want %v", len(token), base64.StdEncoding.EncodedLen(tokenLength*2)) } if !strings.Contains(rr.Body.String(), token) { t.Fatalf("token not in response body: got %v want %v", rr.Body.String(), token) } } // Test that we can extract a CSRF token from a multipart form. func TestMultipartFormToken(t *testing.T) { s := http.NewServeMux() // Make the token available outside of the handler for comparison. var token string s.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token = Token(r) t := template.Must((template.New("base").Parse(testTemplate))) t.Execute(w, map[string]interface{}{ TemplateTag: TemplateField(r), }) })) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p := Protect(testKey)(s) p.ServeHTTP(rr, r) // Set up our multipart form var b bytes.Buffer mp := multipart.NewWriter(&b) wr, err := mp.CreateFormField(fieldName) if err != nil { t.Fatal(err) } wr.Write([]byte(token)) mp.Close() r, err = http.NewRequest("POST", "http://www.gorillatoolkit.org/", &b) if err != nil { t.Fatal(err) } // Add the multipart header. r.Header.Set("Content-Type", mp.FormDataContentType()) // Send back the issued cookie. setCookie(rr, r) rr = httptest.NewRecorder() p.ServeHTTP(rr, r) if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } if body := rr.Body.String(); !strings.Contains(body, token) { t.Fatalf("token not in response body: got %v want %v", body, token) } } // TestMaskUnmaskTokens tests that a token traversing the mask -> unmask process // is correctly unmasked to the original 'real' token. func TestMaskUnmaskTokens(t *testing.T) { realToken, err := generateRandomBytes(tokenLength) if err != nil { t.Fatal(err) } issued := mask(realToken, nil) decoded, err := base64.StdEncoding.DecodeString(issued) if err != nil { t.Fatal(err) } unmasked := unmask(decoded) if !compareTokens(unmasked, realToken) { t.Fatalf("tokens do not match: got %x want %x", unmasked, realToken) } } // Tests domains that should (or should not) return true for a // same-origin check. func TestSameOrigin(t *testing.T) { var originTests = []struct { o1 string o2 string expected bool }{ {"https://gorillatoolkit.org/", "https://gorillatoolkit.org", true}, {"http://golang.org/", "http://golang.org/pkg/net/http", true}, {"https://gorillatoolkit.org/", "http://gorillatoolkit.org", false}, {"https://gorillatoolkit.org:3333/", "http://gorillatoolkit.org:4444", false}, } for _, origins := range originTests { a, err := url.Parse(origins.o1) if err != nil { t.Fatal(err) } b, err := url.Parse(origins.o2) if err != nil { t.Fatal(err) } if sameOrigin(a, b) != origins.expected { t.Fatalf("origin checking failed: %v and %v, expected %v", origins.o1, origins.o2, origins.expected) } } } func TestXOR(t *testing.T) { testTokens := []struct { a []byte b []byte expected []byte }{ {[]byte("goodbye"), []byte("hello"), []byte{15, 10, 3, 8, 13}}, {[]byte("gophers"), []byte("clojure"), []byte{4, 3, 31, 2, 16, 0, 22}}, {nil, []byte("requestToken"), nil}, } for _, token := range testTokens { if res := xorToken(token.a, token.b); res != nil { if bytes.Compare(res, token.expected) != 0 { t.Fatalf("xorBytes failed to return the expected result: got %v want %v", res, token.expected) } } } } // shortReader provides a broken implementation of io.Reader for testing. type shortReader struct{} func (sr shortReader) Read(p []byte) (int, error) { return len(p) % 2, io.ErrUnexpectedEOF } // TestGenerateRandomBytes tests the (extremely rare) case that crypto/rand does // not return the expected number of bytes. func TestGenerateRandomBytes(t *testing.T) { // Pioneered from https://github.com/justinas/nosurf original := rand.Reader rand.Reader = shortReader{} defer func() { rand.Reader = original }() b, err := generateRandomBytes(tokenLength) if err == nil { t.Fatalf("generateRandomBytes did not report a short read: only read %d bytes", len(b)) } } func TestTemplateField(t *testing.T) { s := http.NewServeMux() // Make the token & template field available outside of the handler. var token string var templateField string s.HandleFunc("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token = Token(r) templateField = string(TemplateField(r)) t := template.Must((template.New("base").Parse(testTemplate))) t.Execute(w, map[string]interface{}{ TemplateTag: TemplateField(r), }) })) testFieldName := "custom_field_name" r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p := Protect(testKey, FieldName(testFieldName))(s) p.ServeHTTP(rr, r) expectedField := fmt.Sprintf(``, testFieldName, token) if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } if templateField != expectedField { t.Fatalf("custom FieldName was not set correctly: got %v want %v", templateField, expectedField) } } func TestCompareTokens(t *testing.T) { // Go's subtle.ConstantTimeCompare prior to 1.3 did not check for matching // lengths. a := []byte("") b := []byte("an-actual-token") if v := compareTokens(a, b); v == true { t.Fatalf("compareTokens failed on different tokens: got %v want %v", v, !v) } } func TestUnsafeSkipCSRFCheck(t *testing.T) { s := http.NewServeMux() skipCheck := func(h http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { r = UnsafeSkipCheck(r) h.ServeHTTP(w, r) } return http.HandlerFunc(fn) } var teapot = 418 // Issue a POST request without a CSRF token in the request. s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Set a non-200 header to make the test explicit. w.WriteHeader(teapot) })) r, err := http.NewRequest("POST", "/", nil) if err != nil { t.Fatal(err) } // Must be used prior to the CSRF handler being invoked. p := skipCheck(Protect(testKey)(s)) rr := httptest.NewRecorder() p.ServeHTTP(rr, r) if status := rr.Code; status != teapot { t.Fatalf("middleware failed to skip this request: got %v want %v", status, teapot) } } csrf-1.6.2/options.go000066400000000000000000000130051354677143600145160ustar00rootroot00000000000000package csrf import ( "net/http" ) // Option describes a functional option for configuring the CSRF handler. type Option func(*csrf) // MaxAge sets the maximum age (in seconds) of a CSRF token's underlying cookie. // Defaults to 12 hours. Call csrf.MaxAge(0) to explicitly set session-only // cookies. func MaxAge(age int) Option { return func(cs *csrf) { cs.opts.MaxAge = age } } // Domain sets the cookie domain. Defaults to the current domain of the request // only (recommended). // // This should be a hostname and not a URL. If set, the domain is treated as // being prefixed with a '.' - e.g. "example.com" becomes ".example.com" and // matches "www.example.com" and "secure.example.com". func Domain(domain string) Option { return func(cs *csrf) { cs.opts.Domain = domain } } // Path sets the cookie path. Defaults to the path the cookie was issued from // (recommended). // // This instructs clients to only respond with cookie for that path and its // subpaths - i.e. a cookie issued from "/register" would be included in requests // to "/register/step2" and "/register/submit". func Path(p string) Option { return func(cs *csrf) { cs.opts.Path = p } } // Secure sets the 'Secure' flag on the cookie. Defaults to true (recommended). // Set this to 'false' in your development environment otherwise the cookie won't // be sent over an insecure channel. Setting this via the presence of a 'DEV' // environmental variable is a good way of making sure this won't make it to a // production environment. func Secure(s bool) Option { return func(cs *csrf) { cs.opts.Secure = s } } // HttpOnly sets the 'HttpOnly' flag on the cookie. Defaults to true (recommended). func HttpOnly(h bool) Option { return func(cs *csrf) { // Note that the function and field names match the case of the // related http.Cookie field instead of the "correct" HTTPOnly name // that golint suggests. cs.opts.HttpOnly = h } } // SameSite sets the cookie SameSite attribute. Defaults to blank to maintain // backwards compatibility, however, Strict is recommended. // // SameSite(SameSiteStrictMode) will prevent the cookie from being sent by the // browser to the target site in all cross-site browsing context, even when // following a regular link (GET request). // // SameSite(SameSiteLaxMode) provides a reasonable balance between security and // usability for websites that want to maintain user's logged-in session after // the user arrives from an external link. The session cookie would be allowed // when following a regular link from an external website while blocking it in // CSRF-prone request methods (e.g. POST). // // This option is only available for go 1.11+. func SameSite(s SameSiteMode) Option { return func(cs *csrf) { cs.opts.SameSite = s } } // ErrorHandler allows you to change the handler called when CSRF request // processing encounters an invalid token or request. A typical use would be to // provide a handler that returns a static HTML file with a HTTP 403 status. By // default a HTTP 403 status and a plain text CSRF failure reason are served. // // Note that a custom error handler can also access the csrf.FailureReason(r) // function to retrieve the CSRF validation reason from the request context. func ErrorHandler(h http.Handler) Option { return func(cs *csrf) { cs.opts.ErrorHandler = h } } // RequestHeader allows you to change the request header the CSRF middleware // inspects. The default is X-CSRF-Token. func RequestHeader(header string) Option { return func(cs *csrf) { cs.opts.RequestHeader = header } } // FieldName allows you to change the name attribute of the hidden field // inspected by this package. The default is 'gorilla.csrf.Token'. func FieldName(name string) Option { return func(cs *csrf) { cs.opts.FieldName = name } } // CookieName changes the name of the CSRF cookie issued to clients. // // Note that cookie names should not contain whitespace, commas, semicolons, // backslashes or control characters as per RFC6265. func CookieName(name string) Option { return func(cs *csrf) { cs.opts.CookieName = name } } // TrustedOrigins configures a set of origins (Referers) that are considered as trusted. // This will allow cross-domain CSRF use-cases - e.g. where the front-end is served // from a different domain than the API server - to correctly pass a CSRF check. // // You should only provide origins you own or have full control over. func TrustedOrigins(origins []string) Option { return func(cs *csrf) { cs.opts.TrustedOrigins = origins } } // setStore sets the store used by the CSRF middleware. // Note: this is private (for now) to allow for internal API changes. func setStore(s store) Option { return func(cs *csrf) { cs.st = s } } // parseOptions parses the supplied options functions and returns a configured // csrf handler. func parseOptions(h http.Handler, opts ...Option) *csrf { // Set the handler to call after processing. cs := &csrf{ h: h, } // Default to true. See Secure & HttpOnly function comments for rationale. // Set here to allow package users to override the default. cs.opts.Secure = true cs.opts.HttpOnly = true // Default to blank to maintain backwards compatibility cs.opts.SameSite = SameSiteDefaultMode // Default; only override this if the package user explicitly calls MaxAge(0) cs.opts.MaxAge = defaultAge // Range over each options function and apply it // to our csrf type to configure it. Options functions are // applied in order, with any conflicting options overriding // earlier calls. for _, option := range opts { option(cs) } return cs } csrf-1.6.2/options_test.go000066400000000000000000000051151354677143600155600ustar00rootroot00000000000000package csrf import ( "net/http" "reflect" "testing" ) // Tests that options functions are applied to the middleware. func TestOptions(t *testing.T) { var h http.Handler age := 86400 domain := "gorillatoolkit.org" path := "/forms/" header := "X-AUTH-TOKEN" field := "authenticity_token" errorHandler := unauthorizedHandler name := "_chimpanzee_csrf" testOpts := []Option{ MaxAge(age), Domain(domain), Path(path), HttpOnly(false), Secure(false), SameSite(SameSiteStrictMode), RequestHeader(header), FieldName(field), ErrorHandler(http.HandlerFunc(errorHandler)), CookieName(name), } // Parse our test options and check that they set the related struct fields. cs := parseOptions(h, testOpts...) if cs.opts.MaxAge != age { t.Errorf("MaxAge not set correctly: got %v want %v", cs.opts.MaxAge, age) } if cs.opts.Domain != domain { t.Errorf("Domain not set correctly: got %v want %v", cs.opts.Domain, domain) } if cs.opts.Path != path { t.Errorf("Path not set correctly: got %v want %v", cs.opts.Path, path) } if cs.opts.HttpOnly != false { t.Errorf("HttpOnly not set correctly: got %v want %v", cs.opts.HttpOnly, false) } if cs.opts.Secure != false { t.Errorf("Secure not set correctly: got %v want %v", cs.opts.Secure, false) } if cs.opts.SameSite != SameSiteStrictMode { t.Errorf("SameSite not set correctly: got %v want %v", cs.opts.SameSite, SameSiteStrictMode) } if cs.opts.RequestHeader != header { t.Errorf("RequestHeader not set correctly: got %v want %v", cs.opts.RequestHeader, header) } if cs.opts.FieldName != field { t.Errorf("FieldName not set correctly: got %v want %v", cs.opts.FieldName, field) } if !reflect.ValueOf(cs.opts.ErrorHandler).IsValid() { t.Errorf("ErrorHandler not set correctly: got %v want %v", reflect.ValueOf(cs.opts.ErrorHandler).IsValid(), reflect.ValueOf(errorHandler).IsValid()) } if cs.opts.CookieName != name { t.Errorf("CookieName not set correctly: got %v want %v", cs.opts.CookieName, name) } } func TestMaxAge(t *testing.T) { t.Run("Ensure the default MaxAge is applied", func(t *testing.T) { handler := Protect(testKey)(nil) csrf := handler.(*csrf) cs := csrf.st.(*cookieStore) if cs.maxAge != defaultAge { t.Fatalf("default maxAge not applied: got %d (want %d)", cs.maxAge, defaultAge) } }) t.Run("Support an explicit MaxAge of 0 (session-only)", func(t *testing.T) { handler := Protect(testKey, MaxAge(0))(nil) csrf := handler.(*csrf) cs := csrf.st.(*cookieStore) if cs.maxAge != 0 { t.Fatalf("zero (0) maxAge not applied: got %d (want %d)", cs.maxAge, 0) } }) } csrf-1.6.2/store.go000066400000000000000000000043201354677143600141570ustar00rootroot00000000000000// +build go1.11 package csrf import ( "net/http" "time" "github.com/gorilla/securecookie" ) // store represents the session storage used for CSRF tokens. type store interface { // Get returns the real CSRF token from the store. Get(*http.Request) ([]byte, error) // Save stores the real CSRF token in the store and writes a // cookie to the http.ResponseWriter. // For non-cookie stores, the cookie should contain a unique (256 bit) ID // or key that references the token in the backend store. // csrf.GenerateRandomBytes is a helper function for generating secure IDs. Save(token []byte, w http.ResponseWriter) error } // cookieStore is a signed cookie session store for CSRF tokens. type cookieStore struct { name string maxAge int secure bool httpOnly bool path string domain string sc *securecookie.SecureCookie sameSite SameSiteMode } // Get retrieves a CSRF token from the session cookie. It returns an empty token // if decoding fails (e.g. HMAC validation fails or the named cookie doesn't exist). func (cs *cookieStore) Get(r *http.Request) ([]byte, error) { // Retrieve the cookie from the request cookie, err := r.Cookie(cs.name) if err != nil { return nil, err } token := make([]byte, tokenLength) // Decode the HMAC authenticated cookie. err = cs.sc.Decode(cs.name, cookie.Value, &token) if err != nil { return nil, err } return token, nil } // Save stores the CSRF token in the session cookie. func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error { // Generate an encoded cookie value with the CSRF token. encoded, err := cs.sc.Encode(cs.name, token) if err != nil { return err } cookie := &http.Cookie{ Name: cs.name, Value: encoded, MaxAge: cs.maxAge, HttpOnly: cs.httpOnly, Secure: cs.secure, SameSite: http.SameSite(cs.sameSite), Path: cs.path, Domain: cs.domain, } // Set the Expires field on the cookie based on the MaxAge // If MaxAge <= 0, we don't set the Expires attribute, making the cookie // session-only. if cs.maxAge > 0 { cookie.Expires = time.Now().Add( time.Duration(cs.maxAge) * time.Second) } // Write the authenticated cookie to the response. http.SetCookie(w, cookie) return nil } csrf-1.6.2/store_legacy.go000066400000000000000000000043421354677143600155070ustar00rootroot00000000000000// +build !go1.11 // file for compatibility with go versions prior to 1.11 package csrf import ( "net/http" "time" "github.com/gorilla/securecookie" ) // store represents the session storage used for CSRF tokens. type store interface { // Get returns the real CSRF token from the store. Get(*http.Request) ([]byte, error) // Save stores the real CSRF token in the store and writes a // cookie to the http.ResponseWriter. // For non-cookie stores, the cookie should contain a unique (256 bit) ID // or key that references the token in the backend store. // csrf.GenerateRandomBytes is a helper function for generating secure IDs. Save(token []byte, w http.ResponseWriter) error } // cookieStore is a signed cookie session store for CSRF tokens. type cookieStore struct { name string maxAge int secure bool httpOnly bool path string domain string sc *securecookie.SecureCookie sameSite SameSiteMode } // Get retrieves a CSRF token from the session cookie. It returns an empty token // if decoding fails (e.g. HMAC validation fails or the named cookie doesn't exist). func (cs *cookieStore) Get(r *http.Request) ([]byte, error) { // Retrieve the cookie from the request cookie, err := r.Cookie(cs.name) if err != nil { return nil, err } token := make([]byte, tokenLength) // Decode the HMAC authenticated cookie. err = cs.sc.Decode(cs.name, cookie.Value, &token) if err != nil { return nil, err } return token, nil } // Save stores the CSRF token in the session cookie. func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error { // Generate an encoded cookie value with the CSRF token. encoded, err := cs.sc.Encode(cs.name, token) if err != nil { return err } cookie := &http.Cookie{ Name: cs.name, Value: encoded, MaxAge: cs.maxAge, HttpOnly: cs.httpOnly, Secure: cs.secure, Path: cs.path, Domain: cs.domain, } // Set the Expires field on the cookie based on the MaxAge // If MaxAge <= 0, we don't set the Expires attribute, making the cookie // session-only. if cs.maxAge > 0 { cookie.Expires = time.Now().Add( time.Duration(cs.maxAge) * time.Second) } // Write the authenticated cookie to the response. http.SetCookie(w, cookie) return nil } csrf-1.6.2/store_legacy_test.go000066400000000000000000000077071354677143600165560ustar00rootroot00000000000000// +build !go1.11 // file for compatibility with go versions prior to 1.11 package csrf import ( "fmt" "net/http" "net/http/httptest" "strings" "testing" "github.com/pkg/errors" "github.com/gorilla/securecookie" ) // Check store implementations var _ store = &cookieStore{} // brokenSaveStore is a CSRF store that cannot, well, save. type brokenSaveStore struct { store } func (bs *brokenSaveStore) Get(*http.Request) ([]byte, error) { // Generate an invalid token so we can progress to our Save method return generateRandomBytes(24) } func (bs *brokenSaveStore) Save(realToken []byte, w http.ResponseWriter) error { return errors.New("test error") } // Tests for failure if the middleware can't save to the Store. func TestStoreCannotSave(t *testing.T) { s := http.NewServeMux() bs := &brokenSaveStore{} s.HandleFunc("/", testHandler) p := Protect(testKey, setStore(bs))(s) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p.ServeHTTP(rr, r) if rr.Code != http.StatusForbidden { t.Fatalf("broken store did not set an error status: got %v want %v", rr.Code, http.StatusForbidden) } if c := rr.Header().Get("Set-Cookie"); c != "" { t.Fatalf("broken store incorrectly set a cookie: got %v want %v", c, "") } } // TestCookieDecode tests that an invalid cookie store returns a decoding error. func TestCookieDecode(t *testing.T) { r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } var age = 3600 // Test with a nil hash key sc := securecookie.New(nil, nil) sc.MaxAge(age) st := &cookieStore{cookieName, age, true, true, "", "", sc, SameSiteDefaultMode} // Set a fake cookie value so r.Cookie passes. r.Header.Set("Cookie", fmt.Sprintf("%s=%s", cookieName, "notacookie")) _, err = st.Get(r) if err == nil { t.Fatal("cookiestore did not report an invalid hashkey on decode") } } // TestCookieEncode tests that an invalid cookie store returns an encoding error. func TestCookieEncode(t *testing.T) { var age = 3600 // Test with a nil hash key sc := securecookie.New(nil, nil) sc.MaxAge(age) st := &cookieStore{cookieName, age, true, true, "", "", sc, SameSiteDefaultMode} rr := httptest.NewRecorder() err := st.Save(nil, rr) if err == nil { t.Fatal("cookiestore did not report an invalid hashkey on encode") } } // TestMaxAgeZero tests that setting MaxAge(0) does not set the Expires // attribute on the cookie. func TestMaxAgeZero(t *testing.T) { var age = 0 s := http.NewServeMux() s.HandleFunc("/", testHandler) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p := Protect(testKey, MaxAge(age))(s) p.ServeHTTP(rr, r) if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } if rr.Header().Get("Set-Cookie") == "" { t.Fatalf("cookie not set: got %q", rr.Header().Get("Set-Cookie")) } cookie := rr.Header().Get("Set-Cookie") if !strings.Contains(cookie, "HttpOnly") || strings.Contains(cookie, "Expires") { t.Fatalf("cookie incorrectly has the Expires attribute set: got %q", cookie) } } // TestSameSizeSet tests that setting SameSite Option does not set the SameSite // attribute on the cookie in legacy systems. func TestSameSizeSet(t *testing.T) { s := http.NewServeMux() s.HandleFunc("/", testHandler) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p := Protect(testKey, SameSite(SameSiteStrictMode))(s) p.ServeHTTP(rr, r) if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } if rr.Header().Get("Set-Cookie") == "" { t.Fatalf("cookie not set: got %q", rr.Header().Get("Set-Cookie")) } cookie := rr.Header().Get("Set-Cookie") if strings.Contains(cookie, "SameSite") { t.Fatalf("cookie incorrectly has the SameSite attribute set: got %q", cookie) } } csrf-1.6.2/store_test.go000066400000000000000000000076251354677143600152310ustar00rootroot00000000000000// +build go1.11 package csrf import ( "fmt" "net/http" "net/http/httptest" "strings" "testing" "github.com/pkg/errors" "github.com/gorilla/securecookie" ) // Check store implementations var _ store = &cookieStore{} // brokenSaveStore is a CSRF store that cannot, well, save. type brokenSaveStore struct { store } func (bs *brokenSaveStore) Get(*http.Request) ([]byte, error) { // Generate an invalid token so we can progress to our Save method return generateRandomBytes(24) } func (bs *brokenSaveStore) Save(realToken []byte, w http.ResponseWriter) error { return errors.New("test error") } // Tests for failure if the middleware can't save to the Store. func TestStoreCannotSave(t *testing.T) { s := http.NewServeMux() bs := &brokenSaveStore{} s.HandleFunc("/", testHandler) p := Protect(testKey, setStore(bs))(s) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p.ServeHTTP(rr, r) if rr.Code != http.StatusForbidden { t.Fatalf("broken store did not set an error status: got %v want %v", rr.Code, http.StatusForbidden) } if c := rr.Header().Get("Set-Cookie"); c != "" { t.Fatalf("broken store incorrectly set a cookie: got %v want %v", c, "") } } // TestCookieDecode tests that an invalid cookie store returns a decoding error. func TestCookieDecode(t *testing.T) { r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } var age = 3600 // Test with a nil hash key sc := securecookie.New(nil, nil) sc.MaxAge(age) st := &cookieStore{cookieName, age, true, true, "", "", sc, SameSiteDefaultMode} // Set a fake cookie value so r.Cookie passes. r.Header.Set("Cookie", fmt.Sprintf("%s=%s", cookieName, "notacookie")) _, err = st.Get(r) if err == nil { t.Fatal("cookiestore did not report an invalid hashkey on decode") } } // TestCookieEncode tests that an invalid cookie store returns an encoding error. func TestCookieEncode(t *testing.T) { var age = 3600 // Test with a nil hash key sc := securecookie.New(nil, nil) sc.MaxAge(age) st := &cookieStore{cookieName, age, true, true, "", "", sc, SameSiteDefaultMode} rr := httptest.NewRecorder() err := st.Save(nil, rr) if err == nil { t.Fatal("cookiestore did not report an invalid hashkey on encode") } } // TestMaxAgeZero tests that setting MaxAge(0) does not set the Expires // attribute on the cookie. func TestMaxAgeZero(t *testing.T) { var age = 0 s := http.NewServeMux() s.HandleFunc("/", testHandler) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p := Protect(testKey, MaxAge(age))(s) p.ServeHTTP(rr, r) if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } if rr.Header().Get("Set-Cookie") == "" { t.Fatalf("cookie not set: got %q", rr.Header().Get("Set-Cookie")) } cookie := rr.Header().Get("Set-Cookie") if !strings.Contains(cookie, "HttpOnly") || strings.Contains(cookie, "Expires") { t.Fatalf("cookie incorrectly has the Expires attribute set: got %q", cookie) } } // TestSameSizeSet tests that setting SameSite Option sets the SameSite // attribute on the cookie in post go1.11 systems. func TestSameSizeSet(t *testing.T) { s := http.NewServeMux() s.HandleFunc("/", testHandler) r, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() p := Protect(testKey, SameSite(SameSiteStrictMode))(s) p.ServeHTTP(rr, r) if rr.Code != http.StatusOK { t.Fatalf("middleware failed to pass to the next handler: got %v want %v", rr.Code, http.StatusOK) } if rr.Header().Get("Set-Cookie") == "" { t.Fatalf("cookie not set: got %q", rr.Header().Get("Set-Cookie")) } cookie := rr.Header().Get("Set-Cookie") if !strings.Contains(cookie, "SameSite") { t.Fatalf("cookie incorrectly does not have the SameSite attribute set: got %q", cookie) } }