From a8abe8abf66db8f4a9750d76ba95b4021a354757 Mon Sep 17 00:00:00 2001 From: Wayne Ashley Berry Date: Thu, 1 Sep 2016 07:58:16 +0200 Subject: [PATCH 01/48] [docs] Mentions passing csrf.Secure(false) in local dev environments. --- doc.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc.go b/doc.go index 612c8d9..e0bf408 100644 --- a/doc.go +++ b/doc.go @@ -74,6 +74,8 @@ in order to protect malicious POST requests being made: // 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) { From 0ff6a2ce414a64d341b00a78fd83afec5baa1146 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E4=B8=9C=E6=B5=B7?= Date: Mon, 26 Sep 2016 23:41:16 +0800 Subject: [PATCH 02/48] [docs] Improve commented code (#46) --- csrf.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/csrf.go b/csrf.go index b4b0439..58ffd5b 100644 --- a/csrf.go +++ b/csrf.go @@ -110,7 +110,7 @@ type options struct { // 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{ +// 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 From bbe668740d1d0d07e117e840a4b704e06e719da7 Mon Sep 17 00:00:00 2001 From: Stefano Vettorazzi Date: Sun, 2 Oct 2016 15:00:12 -0300 Subject: [PATCH 03/48] [docs] Fix syntax typo (#48) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 02e4f42..9bcf3f8 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ func main() { 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{ + 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 From 7f54448f9190a1f217e867373b87ce5c987b1b98 Mon Sep 17 00:00:00 2001 From: "Philip I. Thomas" Date: Fri, 14 Oct 2016 20:28:55 -0700 Subject: [PATCH 04/48] [docs] Fix incorrect function name in docs (#49) --- options.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/options.go b/options.go index c644d49..b50ebd4 100644 --- a/options.go +++ b/options.go @@ -63,7 +63,7 @@ func HttpOnly(h bool) Option { // 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.Failure(r) +// 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) { From fdae182b1882857ae6a246467084c30af79be824 Mon Sep 17 00:00:00 2001 From: Seth Hoenig Date: Sun, 23 Oct 2016 12:09:07 -0500 Subject: [PATCH 05/48] docs: fix minor typo (#50) --- README.md | 2 +- csrf.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9bcf3f8..daa3c87 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ func ShowSignupForm(w http.ResponseWriter, r *http.Request) { }) // 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 your sending JSON to clients or a front-end JavaScript + // This is useful if you're sending JSON to clients or a front-end JavaScript // framework. } diff --git a/csrf.go b/csrf.go index 58ffd5b..926be23 100644 --- a/csrf.go +++ b/csrf.go @@ -115,7 +115,7 @@ type options struct { // }) // // 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 your sending JSON to clients or a front-end JavaScript +// // This is useful if you're sending JSON to clients or a front-end JavaScript // // framework. // } // From 10e8fd1f4e34acff5875a9aed9fd34bbd181e3e7 Mon Sep 17 00:00:00 2001 From: Joshua Carp Date: Tue, 22 Nov 2016 11:43:42 -0500 Subject: [PATCH 06/48] [docs] Fix a few minor typos in examples. (#54) * Fix package import * Explicitly load templates * Fix `HandleFunc` invocation --- csrf.go | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/csrf.go b/csrf.go index 926be23..cc7878f 100644 --- a/csrf.go +++ b/csrf.go @@ -89,21 +89,25 @@ type options struct { // package main // // import ( -// "github.com/elithrar/protect" +// "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 := mux.NewRouter() // -// mux.HandlerFunc("/signup", GetSignupForm) -// // POST requests without a valid token will return a HTTP 403 Forbidden. -// mux.HandlerFunc("/signup/post", PostSignupForm) +// 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. +// // 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)) // } // From 69581736821c33d85bbf378f42f6ad864dbd85de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=94=B0=E6=B5=A9=E6=B5=A9?= Date: Wed, 23 Nov 2016 00:45:00 +0800 Subject: [PATCH 07/48] [doc] Fixed readme mux path prefix (#51) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index daa3c87..8cad716 100644 --- a/README.md +++ b/README.md @@ -130,7 +130,7 @@ func main() { r := mux.NewRouter() api := r.PathPrefix("/api").Subrouter() - api.HandleFunc("/user/:id", GetUser).Methods("GET") + api.HandleFunc("/user/{id}", GetUser).Methods("GET") http.ListenAndServe(":8000", csrf.Protect([]byte("32-byte-long-auth-key"))(r)) From 27774abb29384b09f394ba050d142b4a51bd63e2 Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Mon, 20 Mar 2017 06:15:12 -0700 Subject: [PATCH 08/48] Add Sourcegraph badge. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8cad716..ec3a8ed 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # gorilla/csrf -[![GoDoc](https://godoc.org/github.com/gorilla/csrf?status.svg)](https://godoc.org/github.com/gorilla/csrf) [![Build Status](https://travis-ci.org/gorilla/csrf.svg?branch=master)](https://travis-ci.org/gorilla/csrf) +[![GoDoc](https://godoc.org/github.com/gorilla/csrf?status.svg)](https://godoc.org/github.com/gorilla/csrf) [![Build Status](https://travis-ci.org/gorilla/csrf.svg?branch=master)](https://travis-ci.org/gorilla/csrf) [![Sourcegraph](https://sourcegraph.com/github.com/gorilla/csrf/-/badge.svg)](https://sourcegraph.com/github.com/csrf/securecookie?badge) gorilla/csrf is a HTTP middleware library that provides [cross-site request forgery](http://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/) (CSRF) From 0c47eade21eb80062daba8ecdf418c94ee6588ef Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Mon, 20 Mar 2017 06:16:09 -0700 Subject: [PATCH 09/48] Fix link. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ec3a8ed..75e8525 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # gorilla/csrf -[![GoDoc](https://godoc.org/github.com/gorilla/csrf?status.svg)](https://godoc.org/github.com/gorilla/csrf) [![Build Status](https://travis-ci.org/gorilla/csrf.svg?branch=master)](https://travis-ci.org/gorilla/csrf) [![Sourcegraph](https://sourcegraph.com/github.com/gorilla/csrf/-/badge.svg)](https://sourcegraph.com/github.com/csrf/securecookie?badge) +[![GoDoc](https://godoc.org/github.com/gorilla/csrf?status.svg)](https://godoc.org/github.com/gorilla/csrf) [![Build Status](https://travis-ci.org/gorilla/csrf.svg?branch=master)](https://travis-ci.org/gorilla/csrf) [![Sourcegraph](https://sourcegraph.com/github.com/gorilla/csrf/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/csrf?badge) gorilla/csrf is a HTTP middleware library that provides [cross-site request forgery](http://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/) (CSRF) From 0790a82825913cb077e3eb4f446023f46c3e931d Mon Sep 17 00:00:00 2001 From: adiabatic Date: Fri, 24 Mar 2017 07:11:26 -0700 Subject: [PATCH 10/48] Update doc.go (#59) --- doc.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/doc.go b/doc.go index e0bf408..301abe0 100644 --- a/doc.go +++ b/doc.go @@ -135,6 +135,10 @@ providing a JSON API: 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 From e6dca6753d92320b18aaf5d4682691b96f7b4564 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Dunglas?= Date: Thu, 20 Apr 2017 03:54:30 +0200 Subject: [PATCH 11/48] [docs] doc.go: Fix list rendering (#61) --- doc.go | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/doc.go b/doc.go index 301abe0..c28a373 100644 --- a/doc.go +++ b/doc.go @@ -4,13 +4,13 @@ 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. +* 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: @@ -141,23 +141,23 @@ with the CookieName Option) along with either the X-CSRF-Token header or the gor 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 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. From c5a2560016c225d14b67dadd102650167fc343fc Mon Sep 17 00:00:00 2001 From: Kevin Burke Date: Tue, 6 Jun 2017 16:08:13 -0700 Subject: [PATCH 12/48] [docs] Fix documentation formatting (#63) Godoc treats all indented code as code blocks, and was incorrectly interpreting list items in doc.go as code blocks. In addition, Godoc does not recognize the Markdown URL format, so just put links in parentheses and omit the braces. Finally, the code samples had an extra unnecessary level of indentation on account of using 4 spaces for indentation instead of tabs. Use tabs instead so they appear correctly on the godoc website. --- doc.go | 214 ++++++++++++++++++++++++++++++--------------------------- 1 file changed, 111 insertions(+), 103 deletions(-) diff --git a/doc.go b/doc.go index c28a373..3046cdc 100644 --- a/doc.go +++ b/doc.go @@ -5,12 +5,14 @@ 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. +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. +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. +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: @@ -31,66 +33,66 @@ 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. - r.HandleFunc("/signup/post", SubmitSignupForm) - - // 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) - } + 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. + r.HandleFunc("/signup/post", SubmitSignupForm) + + // 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 @@ -101,39 +103,39 @@ 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 + package main - import ( - "github.com/gorilla/csrf" - "github.com/gorilla/mux" - ) + import ( + "github.com/gorilla/csrf" + "github.com/gorilla/mux" + ) - func main() { - r := mux.NewRouter() + func main() { + r := mux.NewRouter() - api := r.PathPrefix("/api").Subrouter() - api.HandleFunc("/user/:id", GetUser).Methods("GET") + api := r.PathPrefix("/api").Subrouter() + api.HandleFunc("/user/:id", GetUser).Methods("GET") - http.ListenAndServe(":8000", - csrf.Protect([]byte("32-byte-long-auth-key"))(r)) - } + 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. + 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 - } + // 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) - } + 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 @@ -142,22 +144,28 @@ with the CookieName Option) along with either the X-CSRF-Token header or the gor 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/). +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. +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. +(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. +and the one-time-pad used for masking them. This library does not seek to be adventurous. From 8b1b43bb8260c0ce4e4fc503075890fb4b04d921 Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Wed, 9 Aug 2017 11:39:22 -0700 Subject: [PATCH 13/48] [build] Use dep / min Go version 1.3 (#68) --- .travis.yml | 1 - Gopkg.lock | 27 + Gopkg.toml | 34 + vendor/github.com/gorilla/context/.travis.yml | 19 + vendor/github.com/gorilla/context/LICENSE | 27 + vendor/github.com/gorilla/context/README.md | 7 + vendor/github.com/gorilla/context/context.go | 143 ++++ .../gorilla/context/context_test.go | 161 +++++ vendor/github.com/gorilla/context/doc.go | 82 +++ .../gorilla/securecookie/.travis.yml | 18 + .../github.com/gorilla/securecookie/LICENSE | 27 + .../github.com/gorilla/securecookie/README.md | 76 +++ vendor/github.com/gorilla/securecookie/doc.go | 61 ++ .../github.com/gorilla/securecookie/fuzz.go | 25 + .../gorilla/securecookie/fuzz/gencorpus.go | 47 ++ .../gorilla/securecookie/securecookie.go | 646 ++++++++++++++++++ .../gorilla/securecookie/securecookie_test.go | 274 ++++++++ vendor/github.com/pkg/errors/.gitignore | 24 + vendor/github.com/pkg/errors/.travis.yml | 11 + vendor/github.com/pkg/errors/LICENSE | 23 + vendor/github.com/pkg/errors/README.md | 52 ++ vendor/github.com/pkg/errors/appveyor.yml | 32 + vendor/github.com/pkg/errors/bench_test.go | 59 ++ vendor/github.com/pkg/errors/errors.go | 269 ++++++++ vendor/github.com/pkg/errors/errors_test.go | 226 ++++++ vendor/github.com/pkg/errors/example_test.go | 205 ++++++ vendor/github.com/pkg/errors/format_test.go | 535 +++++++++++++++ vendor/github.com/pkg/errors/stack.go | 178 +++++ vendor/github.com/pkg/errors/stack_test.go | 292 ++++++++ 29 files changed, 3580 insertions(+), 1 deletion(-) create mode 100644 Gopkg.lock create mode 100644 Gopkg.toml create mode 100644 vendor/github.com/gorilla/context/.travis.yml create mode 100644 vendor/github.com/gorilla/context/LICENSE create mode 100644 vendor/github.com/gorilla/context/README.md create mode 100644 vendor/github.com/gorilla/context/context.go create mode 100644 vendor/github.com/gorilla/context/context_test.go create mode 100644 vendor/github.com/gorilla/context/doc.go create mode 100644 vendor/github.com/gorilla/securecookie/.travis.yml create mode 100644 vendor/github.com/gorilla/securecookie/LICENSE create mode 100644 vendor/github.com/gorilla/securecookie/README.md create mode 100644 vendor/github.com/gorilla/securecookie/doc.go create mode 100644 vendor/github.com/gorilla/securecookie/fuzz.go create mode 100644 vendor/github.com/gorilla/securecookie/fuzz/gencorpus.go create mode 100644 vendor/github.com/gorilla/securecookie/securecookie.go create mode 100644 vendor/github.com/gorilla/securecookie/securecookie_test.go create mode 100644 vendor/github.com/pkg/errors/.gitignore create mode 100644 vendor/github.com/pkg/errors/.travis.yml create mode 100644 vendor/github.com/pkg/errors/LICENSE create mode 100644 vendor/github.com/pkg/errors/README.md create mode 100644 vendor/github.com/pkg/errors/appveyor.yml create mode 100644 vendor/github.com/pkg/errors/bench_test.go create mode 100644 vendor/github.com/pkg/errors/errors.go create mode 100644 vendor/github.com/pkg/errors/errors_test.go create mode 100644 vendor/github.com/pkg/errors/example_test.go create mode 100644 vendor/github.com/pkg/errors/format_test.go create mode 100644 vendor/github.com/pkg/errors/stack.go create mode 100644 vendor/github.com/pkg/errors/stack_test.go diff --git a/.travis.yml b/.travis.yml index 13b50cd..db5e560 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,7 +3,6 @@ sudo: false matrix: include: - - go: 1.2 - go: 1.3 - go: 1.4 - go: 1.5 diff --git a/Gopkg.lock b/Gopkg.lock new file mode 100644 index 0000000..5db9540 --- /dev/null +++ b/Gopkg.lock @@ -0,0 +1,27 @@ +# 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 diff --git a/Gopkg.toml b/Gopkg.toml new file mode 100644 index 0000000..02837b1 --- /dev/null +++ b/Gopkg.toml @@ -0,0 +1,34 @@ + +# 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" diff --git a/vendor/github.com/gorilla/context/.travis.yml b/vendor/github.com/gorilla/context/.travis.yml new file mode 100644 index 0000000..faca4da --- /dev/null +++ b/vendor/github.com/gorilla/context/.travis.yml @@ -0,0 +1,19 @@ +language: go +sudo: false + +matrix: + include: + - go: 1.3 + - go: 1.4 + - go: 1.5 + - go: 1.6 + - go: tip + +install: + - go get golang.org/x/tools/cmd/vet + +script: + - go get -t -v ./... + - diff -u <(echo -n) <(gofmt -d .) + - go tool vet . + - go test -v -race ./... diff --git a/vendor/github.com/gorilla/context/LICENSE b/vendor/github.com/gorilla/context/LICENSE new file mode 100644 index 0000000..0e5fb87 --- /dev/null +++ b/vendor/github.com/gorilla/context/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012 Rodrigo Moraes. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Google Inc. 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 +OWNER 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. diff --git a/vendor/github.com/gorilla/context/README.md b/vendor/github.com/gorilla/context/README.md new file mode 100644 index 0000000..c60a31b --- /dev/null +++ b/vendor/github.com/gorilla/context/README.md @@ -0,0 +1,7 @@ +context +======= +[![Build Status](https://travis-ci.org/gorilla/context.png?branch=master)](https://travis-ci.org/gorilla/context) + +gorilla/context is a general purpose registry for global request variables. + +Read the full documentation here: http://www.gorillatoolkit.org/pkg/context diff --git a/vendor/github.com/gorilla/context/context.go b/vendor/github.com/gorilla/context/context.go new file mode 100644 index 0000000..81cb128 --- /dev/null +++ b/vendor/github.com/gorilla/context/context.go @@ -0,0 +1,143 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package context + +import ( + "net/http" + "sync" + "time" +) + +var ( + mutex sync.RWMutex + data = make(map[*http.Request]map[interface{}]interface{}) + datat = make(map[*http.Request]int64) +) + +// Set stores a value for a given key in a given request. +func Set(r *http.Request, key, val interface{}) { + mutex.Lock() + if data[r] == nil { + data[r] = make(map[interface{}]interface{}) + datat[r] = time.Now().Unix() + } + data[r][key] = val + mutex.Unlock() +} + +// Get returns a value stored for a given key in a given request. +func Get(r *http.Request, key interface{}) interface{} { + mutex.RLock() + if ctx := data[r]; ctx != nil { + value := ctx[key] + mutex.RUnlock() + return value + } + mutex.RUnlock() + return nil +} + +// GetOk returns stored value and presence state like multi-value return of map access. +func GetOk(r *http.Request, key interface{}) (interface{}, bool) { + mutex.RLock() + if _, ok := data[r]; ok { + value, ok := data[r][key] + mutex.RUnlock() + return value, ok + } + mutex.RUnlock() + return nil, false +} + +// GetAll returns all stored values for the request as a map. Nil is returned for invalid requests. +func GetAll(r *http.Request) map[interface{}]interface{} { + mutex.RLock() + if context, ok := data[r]; ok { + result := make(map[interface{}]interface{}, len(context)) + for k, v := range context { + result[k] = v + } + mutex.RUnlock() + return result + } + mutex.RUnlock() + return nil +} + +// GetAllOk returns all stored values for the request as a map and a boolean value that indicates if +// the request was registered. +func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) { + mutex.RLock() + context, ok := data[r] + result := make(map[interface{}]interface{}, len(context)) + for k, v := range context { + result[k] = v + } + mutex.RUnlock() + return result, ok +} + +// Delete removes a value stored for a given key in a given request. +func Delete(r *http.Request, key interface{}) { + mutex.Lock() + if data[r] != nil { + delete(data[r], key) + } + mutex.Unlock() +} + +// Clear removes all values stored for a given request. +// +// This is usually called by a handler wrapper to clean up request +// variables at the end of a request lifetime. See ClearHandler(). +func Clear(r *http.Request) { + mutex.Lock() + clear(r) + mutex.Unlock() +} + +// clear is Clear without the lock. +func clear(r *http.Request) { + delete(data, r) + delete(datat, r) +} + +// Purge removes request data stored for longer than maxAge, in seconds. +// It returns the amount of requests removed. +// +// If maxAge <= 0, all request data is removed. +// +// This is only used for sanity check: in case context cleaning was not +// properly set some request data can be kept forever, consuming an increasing +// amount of memory. In case this is detected, Purge() must be called +// periodically until the problem is fixed. +func Purge(maxAge int) int { + mutex.Lock() + count := 0 + if maxAge <= 0 { + count = len(data) + data = make(map[*http.Request]map[interface{}]interface{}) + datat = make(map[*http.Request]int64) + } else { + min := time.Now().Unix() - int64(maxAge) + for r := range data { + if datat[r] < min { + clear(r) + count++ + } + } + } + mutex.Unlock() + return count +} + +// ClearHandler wraps an http.Handler and clears request values at the end +// of a request lifetime. +func ClearHandler(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer Clear(r) + h.ServeHTTP(w, r) + }) +} diff --git a/vendor/github.com/gorilla/context/context_test.go b/vendor/github.com/gorilla/context/context_test.go new file mode 100644 index 0000000..9814c50 --- /dev/null +++ b/vendor/github.com/gorilla/context/context_test.go @@ -0,0 +1,161 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package context + +import ( + "net/http" + "testing" +) + +type keyType int + +const ( + key1 keyType = iota + key2 +) + +func TestContext(t *testing.T) { + assertEqual := func(val interface{}, exp interface{}) { + if val != exp { + t.Errorf("Expected %v, got %v.", exp, val) + } + } + + r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) + emptyR, _ := http.NewRequest("GET", "http://localhost:8080/", nil) + + // Get() + assertEqual(Get(r, key1), nil) + + // Set() + Set(r, key1, "1") + assertEqual(Get(r, key1), "1") + assertEqual(len(data[r]), 1) + + Set(r, key2, "2") + assertEqual(Get(r, key2), "2") + assertEqual(len(data[r]), 2) + + //GetOk + value, ok := GetOk(r, key1) + assertEqual(value, "1") + assertEqual(ok, true) + + value, ok = GetOk(r, "not exists") + assertEqual(value, nil) + assertEqual(ok, false) + + Set(r, "nil value", nil) + value, ok = GetOk(r, "nil value") + assertEqual(value, nil) + assertEqual(ok, true) + + // GetAll() + values := GetAll(r) + assertEqual(len(values), 3) + + // GetAll() for empty request + values = GetAll(emptyR) + if values != nil { + t.Error("GetAll didn't return nil value for invalid request") + } + + // GetAllOk() + values, ok = GetAllOk(r) + assertEqual(len(values), 3) + assertEqual(ok, true) + + // GetAllOk() for empty request + values, ok = GetAllOk(emptyR) + assertEqual(value, nil) + assertEqual(ok, false) + + // Delete() + Delete(r, key1) + assertEqual(Get(r, key1), nil) + assertEqual(len(data[r]), 2) + + Delete(r, key2) + assertEqual(Get(r, key2), nil) + assertEqual(len(data[r]), 1) + + // Clear() + Clear(r) + assertEqual(len(data), 0) +} + +func parallelReader(r *http.Request, key string, iterations int, wait, done chan struct{}) { + <-wait + for i := 0; i < iterations; i++ { + Get(r, key) + } + done <- struct{}{} + +} + +func parallelWriter(r *http.Request, key, value string, iterations int, wait, done chan struct{}) { + <-wait + for i := 0; i < iterations; i++ { + Set(r, key, value) + } + done <- struct{}{} + +} + +func benchmarkMutex(b *testing.B, numReaders, numWriters, iterations int) { + + b.StopTimer() + r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) + done := make(chan struct{}) + b.StartTimer() + + for i := 0; i < b.N; i++ { + wait := make(chan struct{}) + + for i := 0; i < numReaders; i++ { + go parallelReader(r, "test", iterations, wait, done) + } + + for i := 0; i < numWriters; i++ { + go parallelWriter(r, "test", "123", iterations, wait, done) + } + + close(wait) + + for i := 0; i < numReaders+numWriters; i++ { + <-done + } + + } + +} + +func BenchmarkMutexSameReadWrite1(b *testing.B) { + benchmarkMutex(b, 1, 1, 32) +} +func BenchmarkMutexSameReadWrite2(b *testing.B) { + benchmarkMutex(b, 2, 2, 32) +} +func BenchmarkMutexSameReadWrite4(b *testing.B) { + benchmarkMutex(b, 4, 4, 32) +} +func BenchmarkMutex1(b *testing.B) { + benchmarkMutex(b, 2, 8, 32) +} +func BenchmarkMutex2(b *testing.B) { + benchmarkMutex(b, 16, 4, 64) +} +func BenchmarkMutex3(b *testing.B) { + benchmarkMutex(b, 1, 2, 128) +} +func BenchmarkMutex4(b *testing.B) { + benchmarkMutex(b, 128, 32, 256) +} +func BenchmarkMutex5(b *testing.B) { + benchmarkMutex(b, 1024, 2048, 64) +} +func BenchmarkMutex6(b *testing.B) { + benchmarkMutex(b, 2048, 1024, 512) +} diff --git a/vendor/github.com/gorilla/context/doc.go b/vendor/github.com/gorilla/context/doc.go new file mode 100644 index 0000000..73c7400 --- /dev/null +++ b/vendor/github.com/gorilla/context/doc.go @@ -0,0 +1,82 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package context stores values shared during a request lifetime. + +For example, a router can set variables extracted from the URL and later +application handlers can access those values, or it can be used to store +sessions values to be saved at the end of a request. There are several +others common uses. + +The idea was posted by Brad Fitzpatrick to the go-nuts mailing list: + + http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53 + +Here's the basic usage: first define the keys that you will need. The key +type is interface{} so a key can be of any type that supports equality. +Here we define a key using a custom int type to avoid name collisions: + + package foo + + import ( + "github.com/gorilla/context" + ) + + type key int + + const MyKey key = 0 + +Then set a variable. Variables are bound to an http.Request object, so you +need a request instance to set a value: + + context.Set(r, MyKey, "bar") + +The application can later access the variable using the same key you provided: + + func MyHandler(w http.ResponseWriter, r *http.Request) { + // val is "bar". + val := context.Get(r, foo.MyKey) + + // returns ("bar", true) + val, ok := context.GetOk(r, foo.MyKey) + // ... + } + +And that's all about the basic usage. We discuss some other ideas below. + +Any type can be stored in the context. To enforce a given type, make the key +private and wrap Get() and Set() to accept and return values of a specific +type: + + type key int + + const mykey key = 0 + + // GetMyKey returns a value for this package from the request values. + func GetMyKey(r *http.Request) SomeType { + if rv := context.Get(r, mykey); rv != nil { + return rv.(SomeType) + } + return nil + } + + // SetMyKey sets a value for this package in the request values. + func SetMyKey(r *http.Request, val SomeType) { + context.Set(r, mykey, val) + } + +Variables must be cleared at the end of a request, to remove all values +that were stored. This can be done in an http.Handler, after a request was +served. Just call Clear() passing the request: + + context.Clear(r) + +...or use ClearHandler(), which conveniently wraps an http.Handler to clear +variables at the end of a request lifetime. + +The Routers from the packages gorilla/mux and gorilla/pat call Clear() +so if you are using either of them you don't need to clear the context manually. +*/ +package context diff --git a/vendor/github.com/gorilla/securecookie/.travis.yml b/vendor/github.com/gorilla/securecookie/.travis.yml new file mode 100644 index 0000000..24882fc --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/.travis.yml @@ -0,0 +1,18 @@ +language: go +sudo: false + +matrix: + include: + - go: 1.3 + - go: 1.4 + - go: 1.5 + - go: 1.6 + - go: tip + allow_failures: + - go: tip + +script: + - go get -t -v ./... + - diff -u <(echo -n) <(gofmt -d .) + - go vet $(go list ./... | grep -v /vendor/) + - go test -v -race ./... diff --git a/vendor/github.com/gorilla/securecookie/LICENSE b/vendor/github.com/gorilla/securecookie/LICENSE new file mode 100644 index 0000000..0e5fb87 --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012 Rodrigo Moraes. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Google Inc. 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 +OWNER 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. diff --git a/vendor/github.com/gorilla/securecookie/README.md b/vendor/github.com/gorilla/securecookie/README.md new file mode 100644 index 0000000..5ed299e --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/README.md @@ -0,0 +1,76 @@ +securecookie +============ +[![GoDoc](https://godoc.org/github.com/gorilla/securecookie?status.svg)](https://godoc.org/github.com/gorilla/securecookie) [![Build Status](https://travis-ci.org/gorilla/securecookie.png?branch=master)](https://travis-ci.org/gorilla/securecookie) + +securecookie encodes and decodes authenticated and optionally encrypted +cookie values. + +Secure cookies can't be forged, because their values are validated using HMAC. +When encrypted, the content is also inaccessible to malicious eyes. It is still +recommended that sensitive data not be stored in cookies, and that HTTPS be used +to prevent cookie [replay attacks](https://en.wikipedia.org/wiki/Replay_attack). + +## Examples + +To use it, first create a new SecureCookie instance: + +```go +// Hash keys should be at least 32 bytes long +var hashKey = []byte("very-secret") +// Block keys should be 16 bytes (AES-128) or 32 bytes (AES-256) long. +// Shorter keys may weaken the encryption used. +var blockKey = []byte("a-lot-secret") +var s = securecookie.New(hashKey, blockKey) +``` + +The hashKey is required, used to authenticate the cookie value using HMAC. +It is recommended to use a key with 32 or 64 bytes. + +The blockKey is optional, used to encrypt the cookie value -- set it to nil +to not use encryption. If set, the length must correspond to the block size +of the encryption algorithm. For AES, used by default, valid lengths are +16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. + +Strong keys can be created using the convenience function GenerateRandomKey(). + +Once a SecureCookie instance is set, use it to encode a cookie value: + +```go +func SetCookieHandler(w http.ResponseWriter, r *http.Request) { + value := map[string]string{ + "foo": "bar", + } + if encoded, err := s.Encode("cookie-name", value); err == nil { + cookie := &http.Cookie{ + Name: "cookie-name", + Value: encoded, + Path: "/", + } + http.SetCookie(w, cookie) + } +} +``` + +Later, use the same SecureCookie instance to decode and validate a cookie +value: + +```go +func ReadCookieHandler(w http.ResponseWriter, r *http.Request) { + if cookie, err := r.Cookie("cookie-name"); err == nil { + value := make(map[string]string) + if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil { + fmt.Fprintf(w, "The value of foo is %q", value["foo"]) + } + } +} +``` + +We stored a map[string]string, but secure cookies can hold any value that +can be encoded using `encoding/gob`. To store custom types, they must be +registered first using gob.Register(). For basic types this is not needed; +it works out of the box. An optional JSON encoder that uses `encoding/json` is +available for types compatible with JSON. + +## License + +BSD licensed. See the LICENSE file for details. diff --git a/vendor/github.com/gorilla/securecookie/doc.go b/vendor/github.com/gorilla/securecookie/doc.go new file mode 100644 index 0000000..ae89408 --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/doc.go @@ -0,0 +1,61 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package securecookie encodes and decodes authenticated and optionally +encrypted cookie values. + +Secure cookies can't be forged, because their values are validated using HMAC. +When encrypted, the content is also inaccessible to malicious eyes. + +To use it, first create a new SecureCookie instance: + + var hashKey = []byte("very-secret") + var blockKey = []byte("a-lot-secret") + var s = securecookie.New(hashKey, blockKey) + +The hashKey is required, used to authenticate the cookie value using HMAC. +It is recommended to use a key with 32 or 64 bytes. + +The blockKey is optional, used to encrypt the cookie value -- set it to nil +to not use encryption. If set, the length must correspond to the block size +of the encryption algorithm. For AES, used by default, valid lengths are +16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. + +Strong keys can be created using the convenience function GenerateRandomKey(). + +Once a SecureCookie instance is set, use it to encode a cookie value: + + func SetCookieHandler(w http.ResponseWriter, r *http.Request) { + value := map[string]string{ + "foo": "bar", + } + if encoded, err := s.Encode("cookie-name", value); err == nil { + cookie := &http.Cookie{ + Name: "cookie-name", + Value: encoded, + Path: "/", + } + http.SetCookie(w, cookie) + } + } + +Later, use the same SecureCookie instance to decode and validate a cookie +value: + + func ReadCookieHandler(w http.ResponseWriter, r *http.Request) { + if cookie, err := r.Cookie("cookie-name"); err == nil { + value := make(map[string]string) + if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil { + fmt.Fprintf(w, "The value of foo is %q", value["foo"]) + } + } + } + +We stored a map[string]string, but secure cookies can hold any value that +can be encoded using encoding/gob. To store custom types, they must be +registered first using gob.Register(). For basic types this is not needed; +it works out of the box. +*/ +package securecookie diff --git a/vendor/github.com/gorilla/securecookie/fuzz.go b/vendor/github.com/gorilla/securecookie/fuzz.go new file mode 100644 index 0000000..e4d0534 --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/fuzz.go @@ -0,0 +1,25 @@ +// +build gofuzz + +package securecookie + +var hashKey = []byte("very-secret12345") +var blockKey = []byte("a-lot-secret1234") +var s = New(hashKey, blockKey) + +type Cookie struct { + B bool + I int + S string +} + +func Fuzz(data []byte) int { + datas := string(data) + var c Cookie + if err := s.Decode("fuzz", datas, &c); err != nil { + return 0 + } + if _, err := s.Encode("fuzz", c); err != nil { + panic(err) + } + return 1 +} diff --git a/vendor/github.com/gorilla/securecookie/fuzz/gencorpus.go b/vendor/github.com/gorilla/securecookie/fuzz/gencorpus.go new file mode 100644 index 0000000..368192b --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/fuzz/gencorpus.go @@ -0,0 +1,47 @@ +package main + +import ( + "fmt" + "io" + "math/rand" + "os" + "reflect" + "testing/quick" + + "github.com/gorilla/securecookie" +) + +var hashKey = []byte("very-secret12345") +var blockKey = []byte("a-lot-secret1234") +var s = securecookie.New(hashKey, blockKey) + +type Cookie struct { + B bool + I int + S string +} + +func main() { + var c Cookie + t := reflect.TypeOf(c) + rnd := rand.New(rand.NewSource(0)) + for i := 0; i < 100; i++ { + v, ok := quick.Value(t, rnd) + if !ok { + panic("couldn't generate value") + } + encoded, err := s.Encode("fuzz", v.Interface()) + if err != nil { + panic(err) + } + f, err := os.Create(fmt.Sprintf("corpus/%d.sc", i)) + if err != nil { + panic(err) + } + _, err = io.WriteString(f, encoded) + if err != nil { + panic(err) + } + f.Close() + } +} diff --git a/vendor/github.com/gorilla/securecookie/securecookie.go b/vendor/github.com/gorilla/securecookie/securecookie.go new file mode 100644 index 0000000..83dd606 --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/securecookie.go @@ -0,0 +1,646 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package securecookie + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/gob" + "encoding/json" + "fmt" + "hash" + "io" + "strconv" + "strings" + "time" +) + +// Error is the interface of all errors returned by functions in this library. +type Error interface { + error + + // IsUsage returns true for errors indicating the client code probably + // uses this library incorrectly. For example, the client may have + // failed to provide a valid hash key, or may have failed to configure + // the Serializer adequately for encoding value. + IsUsage() bool + + // IsDecode returns true for errors indicating that a cookie could not + // be decoded and validated. Since cookies are usually untrusted + // user-provided input, errors of this type should be expected. + // Usually, the proper action is simply to reject the request. + IsDecode() bool + + // IsInternal returns true for unexpected errors occurring in the + // securecookie implementation. + IsInternal() bool + + // Cause, if it returns a non-nil value, indicates that this error was + // propagated from some underlying library. If this method returns nil, + // this error was raised directly by this library. + // + // Cause is provided principally for debugging/logging purposes; it is + // rare that application logic should perform meaningfully different + // logic based on Cause. See, for example, the caveats described on + // (MultiError).Cause(). + Cause() error +} + +// errorType is a bitmask giving the error type(s) of an cookieError value. +type errorType int + +const ( + usageError = errorType(1 << iota) + decodeError + internalError +) + +type cookieError struct { + typ errorType + msg string + cause error +} + +func (e cookieError) IsUsage() bool { return (e.typ & usageError) != 0 } +func (e cookieError) IsDecode() bool { return (e.typ & decodeError) != 0 } +func (e cookieError) IsInternal() bool { return (e.typ & internalError) != 0 } + +func (e cookieError) Cause() error { return e.cause } + +func (e cookieError) Error() string { + parts := []string{"securecookie: "} + if e.msg == "" { + parts = append(parts, "error") + } else { + parts = append(parts, e.msg) + } + if c := e.Cause(); c != nil { + parts = append(parts, " - caused by: ", c.Error()) + } + return strings.Join(parts, "") +} + +var ( + errGeneratingIV = cookieError{typ: internalError, msg: "failed to generate random iv"} + + errNoCodecs = cookieError{typ: usageError, msg: "no codecs provided"} + errHashKeyNotSet = cookieError{typ: usageError, msg: "hash key is not set"} + errBlockKeyNotSet = cookieError{typ: usageError, msg: "block key is not set"} + errEncodedValueTooLong = cookieError{typ: usageError, msg: "the value is too long"} + + errValueToDecodeTooLong = cookieError{typ: decodeError, msg: "the value is too long"} + errTimestampInvalid = cookieError{typ: decodeError, msg: "invalid timestamp"} + errTimestampTooNew = cookieError{typ: decodeError, msg: "timestamp is too new"} + errTimestampExpired = cookieError{typ: decodeError, msg: "expired timestamp"} + errDecryptionFailed = cookieError{typ: decodeError, msg: "the value could not be decrypted"} + errValueNotByte = cookieError{typ: decodeError, msg: "value not a []byte."} + + // ErrMacInvalid indicates that cookie decoding failed because the HMAC + // could not be extracted and verified. Direct use of this error + // variable is deprecated; it is public only for legacy compatibility, + // and may be privatized in the future, as it is rarely useful to + // distinguish between this error and other Error implementations. + ErrMacInvalid = cookieError{typ: decodeError, msg: "the value is not valid"} +) + +// Codec defines an interface to encode and decode cookie values. +type Codec interface { + Encode(name string, value interface{}) (string, error) + Decode(name, value string, dst interface{}) error +} + +// New returns a new SecureCookie. +// +// hashKey is required, used to authenticate values using HMAC. Create it using +// GenerateRandomKey(). It is recommended to use a key with 32 or 64 bytes. +// +// blockKey is optional, used to encrypt values. Create it using +// GenerateRandomKey(). The key length must correspond to the block size +// of the encryption algorithm. For AES, used by default, valid lengths are +// 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. +// The default encoder used for cookie serialization is encoding/gob. +// +// Note that keys created using GenerateRandomKey() are not automatically +// persisted. New keys will be created when the application is restarted, and +// previously issued cookies will not be able to be decoded. +func New(hashKey, blockKey []byte) *SecureCookie { + s := &SecureCookie{ + hashKey: hashKey, + blockKey: blockKey, + hashFunc: sha256.New, + maxAge: 86400 * 30, + maxLength: 4096, + sz: GobEncoder{}, + } + if hashKey == nil { + s.err = errHashKeyNotSet + } + if blockKey != nil { + s.BlockFunc(aes.NewCipher) + } + return s +} + +// SecureCookie encodes and decodes authenticated and optionally encrypted +// cookie values. +type SecureCookie struct { + hashKey []byte + hashFunc func() hash.Hash + blockKey []byte + block cipher.Block + maxLength int + maxAge int64 + minAge int64 + err error + sz Serializer + // For testing purposes, the function that returns the current timestamp. + // If not set, it will use time.Now().UTC().Unix(). + timeFunc func() int64 +} + +// Serializer provides an interface for providing custom serializers for cookie +// values. +type Serializer interface { + Serialize(src interface{}) ([]byte, error) + Deserialize(src []byte, dst interface{}) error +} + +// GobEncoder encodes cookie values using encoding/gob. This is the simplest +// encoder and can handle complex types via gob.Register. +type GobEncoder struct{} + +// JSONEncoder encodes cookie values using encoding/json. Users who wish to +// encode complex types need to satisfy the json.Marshaller and +// json.Unmarshaller interfaces. +type JSONEncoder struct{} + +// NopEncoder does not encode cookie values, and instead simply accepts a []byte +// (as an interface{}) and returns a []byte. This is particularly useful when +// you encoding an object upstream and do not wish to re-encode it. +type NopEncoder struct{} + +// MaxLength restricts the maximum length, in bytes, for the cookie value. +// +// Default is 4096, which is the maximum value accepted by Internet Explorer. +func (s *SecureCookie) MaxLength(value int) *SecureCookie { + s.maxLength = value + return s +} + +// MaxAge restricts the maximum age, in seconds, for the cookie value. +// +// Default is 86400 * 30. Set it to 0 for no restriction. +func (s *SecureCookie) MaxAge(value int) *SecureCookie { + s.maxAge = int64(value) + return s +} + +// MinAge restricts the minimum age, in seconds, for the cookie value. +// +// Default is 0 (no restriction). +func (s *SecureCookie) MinAge(value int) *SecureCookie { + s.minAge = int64(value) + return s +} + +// HashFunc sets the hash function used to create HMAC. +// +// Default is crypto/sha256.New. +func (s *SecureCookie) HashFunc(f func() hash.Hash) *SecureCookie { + s.hashFunc = f + return s +} + +// BlockFunc sets the encryption function used to create a cipher.Block. +// +// Default is crypto/aes.New. +func (s *SecureCookie) BlockFunc(f func([]byte) (cipher.Block, error)) *SecureCookie { + if s.blockKey == nil { + s.err = errBlockKeyNotSet + } else if block, err := f(s.blockKey); err == nil { + s.block = block + } else { + s.err = cookieError{cause: err, typ: usageError} + } + return s +} + +// Encoding sets the encoding/serialization method for cookies. +// +// Default is encoding/gob. To encode special structures using encoding/gob, +// they must be registered first using gob.Register(). +func (s *SecureCookie) SetSerializer(sz Serializer) *SecureCookie { + s.sz = sz + + return s +} + +// Encode encodes a cookie value. +// +// It serializes, optionally encrypts, signs with a message authentication code, +// and finally encodes the value. +// +// The name argument is the cookie name. It is stored with the encoded value. +// The value argument is the value to be encoded. It can be any value that can +// be encoded using the currently selected serializer; see SetSerializer(). +// +// It is the client's responsibility to ensure that value, when encoded using +// the current serialization/encryption settings on s and then base64-encoded, +// is shorter than the maximum permissible length. +func (s *SecureCookie) Encode(name string, value interface{}) (string, error) { + if s.err != nil { + return "", s.err + } + if s.hashKey == nil { + s.err = errHashKeyNotSet + return "", s.err + } + var err error + var b []byte + // 1. Serialize. + if b, err = s.sz.Serialize(value); err != nil { + return "", cookieError{cause: err, typ: usageError} + } + // 2. Encrypt (optional). + if s.block != nil { + if b, err = encrypt(s.block, b); err != nil { + return "", cookieError{cause: err, typ: usageError} + } + } + b = encode(b) + // 3. Create MAC for "name|date|value". Extra pipe to be used later. + b = []byte(fmt.Sprintf("%s|%d|%s|", name, s.timestamp(), b)) + mac := createMac(hmac.New(s.hashFunc, s.hashKey), b[:len(b)-1]) + // Append mac, remove name. + b = append(b, mac...)[len(name)+1:] + // 4. Encode to base64. + b = encode(b) + // 5. Check length. + if s.maxLength != 0 && len(b) > s.maxLength { + return "", errEncodedValueTooLong + } + // Done. + return string(b), nil +} + +// Decode decodes a cookie value. +// +// It decodes, verifies a message authentication code, optionally decrypts and +// finally deserializes the value. +// +// The name argument is the cookie name. It must be the same name used when +// it was stored. The value argument is the encoded cookie value. The dst +// argument is where the cookie will be decoded. It must be a pointer. +func (s *SecureCookie) Decode(name, value string, dst interface{}) error { + if s.err != nil { + return s.err + } + if s.hashKey == nil { + s.err = errHashKeyNotSet + return s.err + } + // 1. Check length. + if s.maxLength != 0 && len(value) > s.maxLength { + return errValueToDecodeTooLong + } + // 2. Decode from base64. + b, err := decode([]byte(value)) + if err != nil { + return err + } + // 3. Verify MAC. Value is "date|value|mac". + parts := bytes.SplitN(b, []byte("|"), 3) + if len(parts) != 3 { + return ErrMacInvalid + } + h := hmac.New(s.hashFunc, s.hashKey) + b = append([]byte(name+"|"), b[:len(b)-len(parts[2])-1]...) + if err = verifyMac(h, b, parts[2]); err != nil { + return err + } + // 4. Verify date ranges. + var t1 int64 + if t1, err = strconv.ParseInt(string(parts[0]), 10, 64); err != nil { + return errTimestampInvalid + } + t2 := s.timestamp() + if s.minAge != 0 && t1 > t2-s.minAge { + return errTimestampTooNew + } + if s.maxAge != 0 && t1 < t2-s.maxAge { + return errTimestampExpired + } + // 5. Decrypt (optional). + b, err = decode(parts[1]) + if err != nil { + return err + } + if s.block != nil { + if b, err = decrypt(s.block, b); err != nil { + return err + } + } + // 6. Deserialize. + if err = s.sz.Deserialize(b, dst); err != nil { + return cookieError{cause: err, typ: decodeError} + } + // Done. + return nil +} + +// timestamp returns the current timestamp, in seconds. +// +// For testing purposes, the function that generates the timestamp can be +// overridden. If not set, it will return time.Now().UTC().Unix(). +func (s *SecureCookie) timestamp() int64 { + if s.timeFunc == nil { + return time.Now().UTC().Unix() + } + return s.timeFunc() +} + +// Authentication ------------------------------------------------------------- + +// createMac creates a message authentication code (MAC). +func createMac(h hash.Hash, value []byte) []byte { + h.Write(value) + return h.Sum(nil) +} + +// verifyMac verifies that a message authentication code (MAC) is valid. +func verifyMac(h hash.Hash, value []byte, mac []byte) error { + mac2 := createMac(h, value) + // Check that both MACs are of equal length, as subtle.ConstantTimeCompare + // does not do this prior to Go 1.4. + if len(mac) == len(mac2) && subtle.ConstantTimeCompare(mac, mac2) == 1 { + return nil + } + return ErrMacInvalid +} + +// Encryption ----------------------------------------------------------------- + +// encrypt encrypts a value using the given block in counter mode. +// +// A random initialization vector (http://goo.gl/zF67k) with the length of the +// block size is prepended to the resulting ciphertext. +func encrypt(block cipher.Block, value []byte) ([]byte, error) { + iv := GenerateRandomKey(block.BlockSize()) + if iv == nil { + return nil, errGeneratingIV + } + // Encrypt it. + stream := cipher.NewCTR(block, iv) + stream.XORKeyStream(value, value) + // Return iv + ciphertext. + return append(iv, value...), nil +} + +// decrypt decrypts a value using the given block in counter mode. +// +// The value to be decrypted must be prepended by a initialization vector +// (http://goo.gl/zF67k) with the length of the block size. +func decrypt(block cipher.Block, value []byte) ([]byte, error) { + size := block.BlockSize() + if len(value) > size { + // Extract iv. + iv := value[:size] + // Extract ciphertext. + value = value[size:] + // Decrypt it. + stream := cipher.NewCTR(block, iv) + stream.XORKeyStream(value, value) + return value, nil + } + return nil, errDecryptionFailed +} + +// Serialization -------------------------------------------------------------- + +// Serialize encodes a value using gob. +func (e GobEncoder) Serialize(src interface{}) ([]byte, error) { + buf := new(bytes.Buffer) + enc := gob.NewEncoder(buf) + if err := enc.Encode(src); err != nil { + return nil, cookieError{cause: err, typ: usageError} + } + return buf.Bytes(), nil +} + +// Deserialize decodes a value using gob. +func (e GobEncoder) Deserialize(src []byte, dst interface{}) error { + dec := gob.NewDecoder(bytes.NewBuffer(src)) + if err := dec.Decode(dst); err != nil { + return cookieError{cause: err, typ: decodeError} + } + return nil +} + +// Serialize encodes a value using encoding/json. +func (e JSONEncoder) Serialize(src interface{}) ([]byte, error) { + buf := new(bytes.Buffer) + enc := json.NewEncoder(buf) + if err := enc.Encode(src); err != nil { + return nil, cookieError{cause: err, typ: usageError} + } + return buf.Bytes(), nil +} + +// Deserialize decodes a value using encoding/json. +func (e JSONEncoder) Deserialize(src []byte, dst interface{}) error { + dec := json.NewDecoder(bytes.NewReader(src)) + if err := dec.Decode(dst); err != nil { + return cookieError{cause: err, typ: decodeError} + } + return nil +} + +// Serialize passes a []byte through as-is. +func (e NopEncoder) Serialize(src interface{}) ([]byte, error) { + if b, ok := src.([]byte); ok { + return b, nil + } + + return nil, errValueNotByte +} + +// Deserialize passes a []byte through as-is. +func (e NopEncoder) Deserialize(src []byte, dst interface{}) error { + if _, ok := dst.([]byte); ok { + dst = src + return nil + } + + return errValueNotByte +} + +// Encoding ------------------------------------------------------------------- + +// encode encodes a value using base64. +func encode(value []byte) []byte { + encoded := make([]byte, base64.URLEncoding.EncodedLen(len(value))) + base64.URLEncoding.Encode(encoded, value) + return encoded +} + +// decode decodes a cookie using base64. +func decode(value []byte) ([]byte, error) { + decoded := make([]byte, base64.URLEncoding.DecodedLen(len(value))) + b, err := base64.URLEncoding.Decode(decoded, value) + if err != nil { + return nil, cookieError{cause: err, typ: decodeError, msg: "base64 decode failed"} + } + return decoded[:b], nil +} + +// Helpers -------------------------------------------------------------------- + +// GenerateRandomKey creates a random key with the given length in bytes. +// On failure, returns nil. +// +// Callers should explicitly check for the possibility of a nil return, treat +// it as a failure of the system random number generator, and not continue. +func GenerateRandomKey(length int) []byte { + k := make([]byte, length) + if _, err := io.ReadFull(rand.Reader, k); err != nil { + return nil + } + return k +} + +// CodecsFromPairs returns a slice of SecureCookie instances. +// +// It is a convenience function to create a list of codecs for key rotation. Note +// that the generated Codecs will have the default options applied: callers +// should iterate over each Codec and type-assert the underlying *SecureCookie to +// change these. +// +// Example: +// +// codecs := securecookie.CodecsFromPairs( +// []byte("new-hash-key"), +// []byte("new-block-key"), +// []byte("old-hash-key"), +// []byte("old-block-key"), +// ) +// +// // Modify each instance. +// for _, s := range codecs { +// if cookie, ok := s.(*securecookie.SecureCookie); ok { +// cookie.MaxAge(86400 * 7) +// cookie.SetSerializer(securecookie.JSONEncoder{}) +// cookie.HashFunc(sha512.New512_256) +// } +// } +// +func CodecsFromPairs(keyPairs ...[]byte) []Codec { + codecs := make([]Codec, len(keyPairs)/2+len(keyPairs)%2) + for i := 0; i < len(keyPairs); i += 2 { + var blockKey []byte + if i+1 < len(keyPairs) { + blockKey = keyPairs[i+1] + } + codecs[i/2] = New(keyPairs[i], blockKey) + } + return codecs +} + +// EncodeMulti encodes a cookie value using a group of codecs. +// +// The codecs are tried in order. Multiple codecs are accepted to allow +// key rotation. +// +// On error, may return a MultiError. +func EncodeMulti(name string, value interface{}, codecs ...Codec) (string, error) { + if len(codecs) == 0 { + return "", errNoCodecs + } + + var errors MultiError + for _, codec := range codecs { + encoded, err := codec.Encode(name, value) + if err == nil { + return encoded, nil + } + errors = append(errors, err) + } + return "", errors +} + +// DecodeMulti decodes a cookie value using a group of codecs. +// +// The codecs are tried in order. Multiple codecs are accepted to allow +// key rotation. +// +// On error, may return a MultiError. +func DecodeMulti(name string, value string, dst interface{}, codecs ...Codec) error { + if len(codecs) == 0 { + return errNoCodecs + } + + var errors MultiError + for _, codec := range codecs { + err := codec.Decode(name, value, dst) + if err == nil { + return nil + } + errors = append(errors, err) + } + return errors +} + +// MultiError groups multiple errors. +type MultiError []error + +func (m MultiError) IsUsage() bool { return m.any(func(e Error) bool { return e.IsUsage() }) } +func (m MultiError) IsDecode() bool { return m.any(func(e Error) bool { return e.IsDecode() }) } +func (m MultiError) IsInternal() bool { return m.any(func(e Error) bool { return e.IsInternal() }) } + +// Cause returns nil for MultiError; there is no unique underlying cause in the +// general case. +// +// Note: we could conceivably return a non-nil Cause only when there is exactly +// one child error with a Cause. However, it would be brittle for client code +// to rely on the arity of causes inside a MultiError, so we have opted not to +// provide this functionality. Clients which really wish to access the Causes +// of the underlying errors are free to iterate through the errors themselves. +func (m MultiError) Cause() error { return nil } + +func (m MultiError) Error() string { + s, n := "", 0 + for _, e := range m { + if e != nil { + if n == 0 { + s = e.Error() + } + n++ + } + } + switch n { + case 0: + return "(0 errors)" + case 1: + return s + case 2: + return s + " (and 1 other error)" + } + return fmt.Sprintf("%s (and %d other errors)", s, n-1) +} + +// any returns true if any element of m is an Error for which pred returns true. +func (m MultiError) any(pred func(Error) bool) bool { + for _, e := range m { + if ourErr, ok := e.(Error); ok && pred(ourErr) { + return true + } + } + return false +} diff --git a/vendor/github.com/gorilla/securecookie/securecookie_test.go b/vendor/github.com/gorilla/securecookie/securecookie_test.go new file mode 100644 index 0000000..33ce4fc --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/securecookie_test.go @@ -0,0 +1,274 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package securecookie + +import ( + "crypto/aes" + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "fmt" + "reflect" + "strings" + "testing" +) + +// Asserts that cookieError and MultiError are Error implementations. +var _ Error = cookieError{} +var _ Error = MultiError{} + +var testCookies = []interface{}{ + map[string]string{"foo": "bar"}, + map[string]string{"baz": "ding"}, +} + +var testStrings = []string{"foo", "bar", "baz"} + +func TestSecureCookie(t *testing.T) { + // TODO test too old / too new timestamps + s1 := New([]byte("12345"), []byte("1234567890123456")) + s2 := New([]byte("54321"), []byte("6543210987654321")) + value := map[string]interface{}{ + "foo": "bar", + "baz": 128, + } + + for i := 0; i < 50; i++ { + // Running this multiple times to check if any special character + // breaks encoding/decoding. + encoded, err1 := s1.Encode("sid", value) + if err1 != nil { + t.Error(err1) + continue + } + dst := make(map[string]interface{}) + err2 := s1.Decode("sid", encoded, &dst) + if err2 != nil { + t.Fatalf("%v: %v", err2, encoded) + } + if !reflect.DeepEqual(dst, value) { + t.Fatalf("Expected %v, got %v.", value, dst) + } + dst2 := make(map[string]interface{}) + err3 := s2.Decode("sid", encoded, &dst2) + if err3 == nil { + t.Fatalf("Expected failure decoding.") + } + err4, ok := err3.(Error) + if !ok { + t.Fatalf("Expected error to implement Error, got: %#v", err3) + } + if !err4.IsDecode() { + t.Fatalf("Expected DecodeError, got: %#v", err4) + } + + // Test other error type flags. + if err4.IsUsage() { + t.Fatalf("Expected IsUsage() == false, got: %#v", err4) + } + if err4.IsInternal() { + t.Fatalf("Expected IsInternal() == false, got: %#v", err4) + } + } +} + +func TestSecureCookieNilKey(t *testing.T) { + s1 := New(nil, nil) + value := map[string]interface{}{ + "foo": "bar", + "baz": 128, + } + _, err := s1.Encode("sid", value) + if err != errHashKeyNotSet { + t.Fatal("Wrong error returned:", err) + } +} + +func TestDecodeInvalid(t *testing.T) { + // List of invalid cookies, which must not be accepted, base64-decoded + // (they will be encoded before passing to Decode). + invalidCookies := []string{ + "", + " ", + "\n", + "||", + "|||", + "cookie", + } + s := New([]byte("12345"), nil) + var dst string + for i, v := range invalidCookies { + for _, enc := range []*base64.Encoding{ + base64.StdEncoding, + base64.URLEncoding, + } { + err := s.Decode("name", enc.EncodeToString([]byte(v)), &dst) + if err == nil { + t.Fatalf("%d: expected failure decoding", i) + } + err2, ok := err.(Error) + if !ok || !err2.IsDecode() { + t.Fatalf("%d: Expected IsDecode(), got: %#v", i, err) + } + } + } +} + +func TestAuthentication(t *testing.T) { + hash := hmac.New(sha256.New, []byte("secret-key")) + for _, value := range testStrings { + hash.Reset() + signed := createMac(hash, []byte(value)) + hash.Reset() + err := verifyMac(hash, []byte(value), signed) + if err != nil { + t.Error(err) + } + } +} + +func TestEncryption(t *testing.T) { + block, err := aes.NewCipher([]byte("1234567890123456")) + if err != nil { + t.Fatalf("Block could not be created") + } + var encrypted, decrypted []byte + for _, value := range testStrings { + if encrypted, err = encrypt(block, []byte(value)); err != nil { + t.Error(err) + } else { + if decrypted, err = decrypt(block, encrypted); err != nil { + t.Error(err) + } + if string(decrypted) != value { + t.Errorf("Expected %v, got %v.", value, string(decrypted)) + } + } + } +} + +func TestGobSerialization(t *testing.T) { + var ( + sz GobEncoder + serialized []byte + deserialized map[string]string + err error + ) + for _, value := range testCookies { + if serialized, err = sz.Serialize(value); err != nil { + t.Error(err) + } else { + deserialized = make(map[string]string) + if err = sz.Deserialize(serialized, &deserialized); err != nil { + t.Error(err) + } + if fmt.Sprintf("%v", deserialized) != fmt.Sprintf("%v", value) { + t.Errorf("Expected %v, got %v.", value, deserialized) + } + } + } +} + +func TestJSONSerialization(t *testing.T) { + var ( + sz JSONEncoder + serialized []byte + deserialized map[string]string + err error + ) + for _, value := range testCookies { + if serialized, err = sz.Serialize(value); err != nil { + t.Error(err) + } else { + deserialized = make(map[string]string) + if err = sz.Deserialize(serialized, &deserialized); err != nil { + t.Error(err) + } + if fmt.Sprintf("%v", deserialized) != fmt.Sprintf("%v", value) { + t.Errorf("Expected %v, got %v.", value, deserialized) + } + } + } +} + +func TestEncoding(t *testing.T) { + for _, value := range testStrings { + encoded := encode([]byte(value)) + decoded, err := decode(encoded) + if err != nil { + t.Error(err) + } else if string(decoded) != value { + t.Errorf("Expected %v, got %s.", value, string(decoded)) + } + } +} + +func TestMultiError(t *testing.T) { + s1, s2 := New(nil, nil), New(nil, nil) + _, err := EncodeMulti("sid", "value", s1, s2) + if len(err.(MultiError)) != 2 { + t.Errorf("Expected 2 errors, got %s.", err) + } else { + if strings.Index(err.Error(), "hash key is not set") == -1 { + t.Errorf("Expected missing hash key error, got %s.", err.Error()) + } + ourErr, ok := err.(Error) + if !ok || !ourErr.IsUsage() { + t.Fatalf("Expected error to be a usage error; got %#v", err) + } + if ourErr.IsDecode() { + t.Errorf("Expected error NOT to be a decode error; got %#v", ourErr) + } + if ourErr.IsInternal() { + t.Errorf("Expected error NOT to be an internal error; got %#v", ourErr) + } + } +} + +func TestMultiNoCodecs(t *testing.T) { + _, err := EncodeMulti("foo", "bar") + if err != errNoCodecs { + t.Errorf("EncodeMulti: bad value for error, got: %v", err) + } + + var dst []byte + err = DecodeMulti("foo", "bar", &dst) + if err != errNoCodecs { + t.Errorf("DecodeMulti: bad value for error, got: %v", err) + } +} + +func TestMissingKey(t *testing.T) { + s1 := New(nil, nil) + + var dst []byte + err := s1.Decode("sid", "value", &dst) + if err != errHashKeyNotSet { + t.Fatalf("Expected %#v, got %#v", errHashKeyNotSet, err) + } + if err2, ok := err.(Error); !ok || !err2.IsUsage() { + t.Errorf("Expected missing hash key to be IsUsage(); was %#v", err) + } +} + +// ---------------------------------------------------------------------------- + +type FooBar struct { + Foo int + Bar string +} + +func TestCustomType(t *testing.T) { + s1 := New([]byte("12345"), []byte("1234567890123456")) + // Type is not registered in gob. (!!!) + src := &FooBar{42, "bar"} + encoded, _ := s1.Encode("sid", src) + + dst := &FooBar{} + _ = s1.Decode("sid", encoded, dst) + if dst.Foo != 42 || dst.Bar != "bar" { + t.Fatalf("Expected %#v, got %#v", src, dst) + } +} diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore new file mode 100644 index 0000000..daf913b --- /dev/null +++ b/vendor/github.com/pkg/errors/.gitignore @@ -0,0 +1,24 @@ +# 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 +*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml new file mode 100644 index 0000000..588ceca --- /dev/null +++ b/vendor/github.com/pkg/errors/.travis.yml @@ -0,0 +1,11 @@ +language: go +go_import_path: github.com/pkg/errors +go: + - 1.4.3 + - 1.5.4 + - 1.6.2 + - 1.7.1 + - tip + +script: + - go test -v ./... diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE new file mode 100644 index 0000000..835ba3e --- /dev/null +++ b/vendor/github.com/pkg/errors/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2015, Dave Cheney +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* 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. + +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. diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md new file mode 100644 index 0000000..273db3c --- /dev/null +++ b/vendor/github.com/pkg/errors/README.md @@ -0,0 +1,52 @@ +# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) + +Package errors provides simple error handling primitives. + +`go get github.com/pkg/errors` + +The traditional error handling idiom in Go is roughly akin to +```go +if err != nil { + return err +} +``` +which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. + +## Adding context to an error + +The errors.Wrap function returns a new error that adds context to the original error. For example +```go +_, err := ioutil.ReadAll(r) +if err != nil { + return errors.Wrap(err, "read failed") +} +``` +## Retrieving the cause of an error + +Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. +```go +type causer interface { + Cause() error +} +``` +`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: +```go +switch err := errors.Cause(err).(type) { +case *MyError: + // handle specifically +default: + // unknown error +} +``` + +[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). + +## Contributing + +We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. + +Before proposing a change, please discuss your change by raising an issue. + +## Licence + +BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml new file mode 100644 index 0000000..a932ead --- /dev/null +++ b/vendor/github.com/pkg/errors/appveyor.yml @@ -0,0 +1,32 @@ +version: build-{build}.{branch} + +clone_folder: C:\gopath\src\github.com\pkg\errors +shallow_clone: true # for startup speed + +environment: + GOPATH: C:\gopath + +platform: + - x64 + +# http://www.appveyor.com/docs/installed-software +install: + # some helpful output for debugging builds + - go version + - go env + # pre-installed MinGW at C:\MinGW is 32bit only + # but MSYS2 at C:\msys64 has mingw64 + - set PATH=C:\msys64\mingw64\bin;%PATH% + - gcc --version + - g++ --version + +build_script: + - go install -v ./... + +test_script: + - set PATH=C:\gopath\bin;%PATH% + - go test -v ./... + +#artifacts: +# - path: '%GOPATH%\bin\*.exe' +deploy: off diff --git a/vendor/github.com/pkg/errors/bench_test.go b/vendor/github.com/pkg/errors/bench_test.go new file mode 100644 index 0000000..0416a3c --- /dev/null +++ b/vendor/github.com/pkg/errors/bench_test.go @@ -0,0 +1,59 @@ +// +build go1.7 + +package errors + +import ( + "fmt" + "testing" + + stderrors "errors" +) + +func noErrors(at, depth int) error { + if at >= depth { + return stderrors.New("no error") + } + return noErrors(at+1, depth) +} +func yesErrors(at, depth int) error { + if at >= depth { + return New("ye error") + } + return yesErrors(at+1, depth) +} + +func BenchmarkErrors(b *testing.B) { + var toperr error + type run struct { + stack int + std bool + } + runs := []run{ + {10, false}, + {10, true}, + {100, false}, + {100, true}, + {1000, false}, + {1000, true}, + } + for _, r := range runs { + part := "pkg/errors" + if r.std { + part = "errors" + } + name := fmt.Sprintf("%s-stack-%d", part, r.stack) + b.Run(name, func(b *testing.B) { + var err error + f := yesErrors + if r.std { + f = noErrors + } + b.ReportAllocs() + for i := 0; i < b.N; i++ { + err = f(0, r.stack) + } + b.StopTimer() + toperr = err + }) + } +} diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go new file mode 100644 index 0000000..842ee80 --- /dev/null +++ b/vendor/github.com/pkg/errors/errors.go @@ -0,0 +1,269 @@ +// Package errors provides simple error handling primitives. +// +// The traditional error handling idiom in Go is roughly akin to +// +// if err != nil { +// return err +// } +// +// which applied recursively up the call stack results in error reports +// without context or debugging information. The errors package allows +// programmers to add context to the failure path in their code in a way +// that does not destroy the original value of the error. +// +// Adding context to an error +// +// The errors.Wrap function returns a new error that adds context to the +// original error by recording a stack trace at the point Wrap is called, +// and the supplied message. For example +// +// _, err := ioutil.ReadAll(r) +// if err != nil { +// return errors.Wrap(err, "read failed") +// } +// +// If additional control is required the errors.WithStack and errors.WithMessage +// functions destructure errors.Wrap into its component operations of annotating +// an error with a stack trace and an a message, respectively. +// +// Retrieving the cause of an error +// +// Using errors.Wrap constructs a stack of errors, adding context to the +// preceding error. Depending on the nature of the error it may be necessary +// to reverse the operation of errors.Wrap to retrieve the original error +// for inspection. Any error value which implements this interface +// +// type causer interface { +// Cause() error +// } +// +// can be inspected by errors.Cause. errors.Cause will recursively retrieve +// the topmost error which does not implement causer, which is assumed to be +// the original cause. For example: +// +// switch err := errors.Cause(err).(type) { +// case *MyError: +// // handle specifically +// default: +// // unknown error +// } +// +// causer interface is not exported by this package, but is considered a part +// of stable public API. +// +// Formatted printing of errors +// +// All error values returned from this package implement fmt.Formatter and can +// be formatted by the fmt package. The following verbs are supported +// +// %s print the error. If the error has a Cause it will be +// printed recursively +// %v see %s +// %+v extended format. Each Frame of the error's StackTrace will +// be printed in detail. +// +// Retrieving the stack trace of an error or wrapper +// +// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are +// invoked. This information can be retrieved with the following interface. +// +// type stackTracer interface { +// StackTrace() errors.StackTrace +// } +// +// Where errors.StackTrace is defined as +// +// type StackTrace []Frame +// +// The Frame type represents a call site in the stack trace. Frame supports +// the fmt.Formatter interface that can be used for printing information about +// the stack trace of this error. For example: +// +// if err, ok := err.(stackTracer); ok { +// for _, f := range err.StackTrace() { +// fmt.Printf("%+s:%d", f) +// } +// } +// +// stackTracer interface is not exported by this package, but is considered a part +// of stable public API. +// +// See the documentation for Frame.Format for more details. +package errors + +import ( + "fmt" + "io" +) + +// New returns an error with the supplied message. +// New also records the stack trace at the point it was called. +func New(message string) error { + return &fundamental{ + msg: message, + stack: callers(), + } +} + +// Errorf formats according to a format specifier and returns the string +// as a value that satisfies error. +// Errorf also records the stack trace at the point it was called. +func Errorf(format string, args ...interface{}) error { + return &fundamental{ + msg: fmt.Sprintf(format, args...), + stack: callers(), + } +} + +// fundamental is an error that has a message and a stack, but no caller. +type fundamental struct { + msg string + *stack +} + +func (f *fundamental) Error() string { return f.msg } + +func (f *fundamental) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + io.WriteString(s, f.msg) + f.stack.Format(s, verb) + return + } + fallthrough + case 's': + io.WriteString(s, f.msg) + case 'q': + fmt.Fprintf(s, "%q", f.msg) + } +} + +// WithStack annotates err with a stack trace at the point WithStack was called. +// If err is nil, WithStack returns nil. +func WithStack(err error) error { + if err == nil { + return nil + } + return &withStack{ + err, + callers(), + } +} + +type withStack struct { + error + *stack +} + +func (w *withStack) Cause() error { return w.error } + +func (w *withStack) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + fmt.Fprintf(s, "%+v", w.Cause()) + w.stack.Format(s, verb) + return + } + fallthrough + case 's': + io.WriteString(s, w.Error()) + case 'q': + fmt.Fprintf(s, "%q", w.Error()) + } +} + +// Wrap returns an error annotating err with a stack trace +// at the point Wrap is called, and the supplied message. +// If err is nil, Wrap returns nil. +func Wrap(err error, message string) error { + if err == nil { + return nil + } + err = &withMessage{ + cause: err, + msg: message, + } + return &withStack{ + err, + callers(), + } +} + +// Wrapf returns an error annotating err with a stack trace +// at the point Wrapf is call, and the format specifier. +// If err is nil, Wrapf returns nil. +func Wrapf(err error, format string, args ...interface{}) error { + if err == nil { + return nil + } + err = &withMessage{ + cause: err, + msg: fmt.Sprintf(format, args...), + } + return &withStack{ + err, + callers(), + } +} + +// WithMessage annotates err with a new message. +// If err is nil, WithMessage returns nil. +func WithMessage(err error, message string) error { + if err == nil { + return nil + } + return &withMessage{ + cause: err, + msg: message, + } +} + +type withMessage struct { + cause error + msg string +} + +func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } +func (w *withMessage) Cause() error { return w.cause } + +func (w *withMessage) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + if s.Flag('+') { + fmt.Fprintf(s, "%+v\n", w.Cause()) + io.WriteString(s, w.msg) + return + } + fallthrough + case 's', 'q': + io.WriteString(s, w.Error()) + } +} + +// Cause returns the underlying cause of the error, if possible. +// An error value has a cause if it implements the following +// interface: +// +// type causer interface { +// Cause() error +// } +// +// If the error does not implement Cause, the original error will +// be returned. If the error is nil, nil will be returned without further +// investigation. +func Cause(err error) error { + type causer interface { + Cause() error + } + + for err != nil { + cause, ok := err.(causer) + if !ok { + break + } + err = cause.Cause() + } + return err +} diff --git a/vendor/github.com/pkg/errors/errors_test.go b/vendor/github.com/pkg/errors/errors_test.go new file mode 100644 index 0000000..1d8c635 --- /dev/null +++ b/vendor/github.com/pkg/errors/errors_test.go @@ -0,0 +1,226 @@ +package errors + +import ( + "errors" + "fmt" + "io" + "reflect" + "testing" +) + +func TestNew(t *testing.T) { + tests := []struct { + err string + want error + }{ + {"", fmt.Errorf("")}, + {"foo", fmt.Errorf("foo")}, + {"foo", New("foo")}, + {"string with format specifiers: %v", errors.New("string with format specifiers: %v")}, + } + + for _, tt := range tests { + got := New(tt.err) + if got.Error() != tt.want.Error() { + t.Errorf("New.Error(): got: %q, want %q", got, tt.want) + } + } +} + +func TestWrapNil(t *testing.T) { + got := Wrap(nil, "no error") + if got != nil { + t.Errorf("Wrap(nil, \"no error\"): got %#v, expected nil", got) + } +} + +func TestWrap(t *testing.T) { + tests := []struct { + err error + message string + want string + }{ + {io.EOF, "read error", "read error: EOF"}, + {Wrap(io.EOF, "read error"), "client error", "client error: read error: EOF"}, + } + + for _, tt := range tests { + got := Wrap(tt.err, tt.message).Error() + if got != tt.want { + t.Errorf("Wrap(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) + } + } +} + +type nilError struct{} + +func (nilError) Error() string { return "nil error" } + +func TestCause(t *testing.T) { + x := New("error") + tests := []struct { + err error + want error + }{{ + // nil error is nil + err: nil, + want: nil, + }, { + // explicit nil error is nil + err: (error)(nil), + want: nil, + }, { + // typed nil is nil + err: (*nilError)(nil), + want: (*nilError)(nil), + }, { + // uncaused error is unaffected + err: io.EOF, + want: io.EOF, + }, { + // caused error returns cause + err: Wrap(io.EOF, "ignored"), + want: io.EOF, + }, { + err: x, // return from errors.New + want: x, + }, { + WithMessage(nil, "whoops"), + nil, + }, { + WithMessage(io.EOF, "whoops"), + io.EOF, + }, { + WithStack(nil), + nil, + }, { + WithStack(io.EOF), + io.EOF, + }} + + for i, tt := range tests { + got := Cause(tt.err) + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want) + } + } +} + +func TestWrapfNil(t *testing.T) { + got := Wrapf(nil, "no error") + if got != nil { + t.Errorf("Wrapf(nil, \"no error\"): got %#v, expected nil", got) + } +} + +func TestWrapf(t *testing.T) { + tests := []struct { + err error + message string + want string + }{ + {io.EOF, "read error", "read error: EOF"}, + {Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"}, + {Wrapf(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"}, + } + + for _, tt := range tests { + got := Wrapf(tt.err, tt.message).Error() + if got != tt.want { + t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) + } + } +} + +func TestErrorf(t *testing.T) { + tests := []struct { + err error + want string + }{ + {Errorf("read error without format specifiers"), "read error without format specifiers"}, + {Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"}, + } + + for _, tt := range tests { + got := tt.err.Error() + if got != tt.want { + t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want) + } + } +} + +func TestWithStackNil(t *testing.T) { + got := WithStack(nil) + if got != nil { + t.Errorf("WithStack(nil): got %#v, expected nil", got) + } +} + +func TestWithStack(t *testing.T) { + tests := []struct { + err error + want string + }{ + {io.EOF, "EOF"}, + {WithStack(io.EOF), "EOF"}, + } + + for _, tt := range tests { + got := WithStack(tt.err).Error() + if got != tt.want { + t.Errorf("WithStack(%v): got: %v, want %v", tt.err, got, tt.want) + } + } +} + +func TestWithMessageNil(t *testing.T) { + got := WithMessage(nil, "no error") + if got != nil { + t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got) + } +} + +func TestWithMessage(t *testing.T) { + tests := []struct { + err error + message string + want string + }{ + {io.EOF, "read error", "read error: EOF"}, + {WithMessage(io.EOF, "read error"), "client error", "client error: read error: EOF"}, + } + + for _, tt := range tests { + got := WithMessage(tt.err, tt.message).Error() + if got != tt.want { + t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want) + } + } + +} + +// errors.New, etc values are not expected to be compared by value +// but the change in errors#27 made them incomparable. Assert that +// various kinds of errors have a functional equality operator, even +// if the result of that equality is always false. +func TestErrorEquality(t *testing.T) { + vals := []error{ + nil, + io.EOF, + errors.New("EOF"), + New("EOF"), + Errorf("EOF"), + Wrap(io.EOF, "EOF"), + Wrapf(io.EOF, "EOF%d", 2), + WithMessage(nil, "whoops"), + WithMessage(io.EOF, "whoops"), + WithStack(io.EOF), + WithStack(nil), + } + + for i := range vals { + for j := range vals { + _ = vals[i] == vals[j] // mustn't panic + } + } +} diff --git a/vendor/github.com/pkg/errors/example_test.go b/vendor/github.com/pkg/errors/example_test.go new file mode 100644 index 0000000..c1fc13e --- /dev/null +++ b/vendor/github.com/pkg/errors/example_test.go @@ -0,0 +1,205 @@ +package errors_test + +import ( + "fmt" + + "github.com/pkg/errors" +) + +func ExampleNew() { + err := errors.New("whoops") + fmt.Println(err) + + // Output: whoops +} + +func ExampleNew_printf() { + err := errors.New("whoops") + fmt.Printf("%+v", err) + + // Example output: + // whoops + // github.com/pkg/errors_test.ExampleNew_printf + // /home/dfc/src/github.com/pkg/errors/example_test.go:17 + // testing.runExample + // /home/dfc/go/src/testing/example.go:114 + // testing.RunExamples + // /home/dfc/go/src/testing/example.go:38 + // testing.(*M).Run + // /home/dfc/go/src/testing/testing.go:744 + // main.main + // /github.com/pkg/errors/_test/_testmain.go:106 + // runtime.main + // /home/dfc/go/src/runtime/proc.go:183 + // runtime.goexit + // /home/dfc/go/src/runtime/asm_amd64.s:2059 +} + +func ExampleWithMessage() { + cause := errors.New("whoops") + err := errors.WithMessage(cause, "oh noes") + fmt.Println(err) + + // Output: oh noes: whoops +} + +func ExampleWithStack() { + cause := errors.New("whoops") + err := errors.WithStack(cause) + fmt.Println(err) + + // Output: whoops +} + +func ExampleWithStack_printf() { + cause := errors.New("whoops") + err := errors.WithStack(cause) + fmt.Printf("%+v", err) + + // Example Output: + // whoops + // github.com/pkg/errors_test.ExampleWithStack_printf + // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55 + // testing.runExample + // /usr/lib/go/src/testing/example.go:114 + // testing.RunExamples + // /usr/lib/go/src/testing/example.go:38 + // testing.(*M).Run + // /usr/lib/go/src/testing/testing.go:744 + // main.main + // github.com/pkg/errors/_test/_testmain.go:106 + // runtime.main + // /usr/lib/go/src/runtime/proc.go:183 + // runtime.goexit + // /usr/lib/go/src/runtime/asm_amd64.s:2086 + // github.com/pkg/errors_test.ExampleWithStack_printf + // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:56 + // testing.runExample + // /usr/lib/go/src/testing/example.go:114 + // testing.RunExamples + // /usr/lib/go/src/testing/example.go:38 + // testing.(*M).Run + // /usr/lib/go/src/testing/testing.go:744 + // main.main + // github.com/pkg/errors/_test/_testmain.go:106 + // runtime.main + // /usr/lib/go/src/runtime/proc.go:183 + // runtime.goexit + // /usr/lib/go/src/runtime/asm_amd64.s:2086 +} + +func ExampleWrap() { + cause := errors.New("whoops") + err := errors.Wrap(cause, "oh noes") + fmt.Println(err) + + // Output: oh noes: whoops +} + +func fn() error { + e1 := errors.New("error") + e2 := errors.Wrap(e1, "inner") + e3 := errors.Wrap(e2, "middle") + return errors.Wrap(e3, "outer") +} + +func ExampleCause() { + err := fn() + fmt.Println(err) + fmt.Println(errors.Cause(err)) + + // Output: outer: middle: inner: error + // error +} + +func ExampleWrap_extended() { + err := fn() + fmt.Printf("%+v\n", err) + + // Example output: + // error + // github.com/pkg/errors_test.fn + // /home/dfc/src/github.com/pkg/errors/example_test.go:47 + // github.com/pkg/errors_test.ExampleCause_printf + // /home/dfc/src/github.com/pkg/errors/example_test.go:63 + // testing.runExample + // /home/dfc/go/src/testing/example.go:114 + // testing.RunExamples + // /home/dfc/go/src/testing/example.go:38 + // testing.(*M).Run + // /home/dfc/go/src/testing/testing.go:744 + // main.main + // /github.com/pkg/errors/_test/_testmain.go:104 + // runtime.main + // /home/dfc/go/src/runtime/proc.go:183 + // runtime.goexit + // /home/dfc/go/src/runtime/asm_amd64.s:2059 + // github.com/pkg/errors_test.fn + // /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner + // github.com/pkg/errors_test.fn + // /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle + // github.com/pkg/errors_test.fn + // /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer +} + +func ExampleWrapf() { + cause := errors.New("whoops") + err := errors.Wrapf(cause, "oh noes #%d", 2) + fmt.Println(err) + + // Output: oh noes #2: whoops +} + +func ExampleErrorf_extended() { + err := errors.Errorf("whoops: %s", "foo") + fmt.Printf("%+v", err) + + // Example output: + // whoops: foo + // github.com/pkg/errors_test.ExampleErrorf + // /home/dfc/src/github.com/pkg/errors/example_test.go:101 + // testing.runExample + // /home/dfc/go/src/testing/example.go:114 + // testing.RunExamples + // /home/dfc/go/src/testing/example.go:38 + // testing.(*M).Run + // /home/dfc/go/src/testing/testing.go:744 + // main.main + // /github.com/pkg/errors/_test/_testmain.go:102 + // runtime.main + // /home/dfc/go/src/runtime/proc.go:183 + // runtime.goexit + // /home/dfc/go/src/runtime/asm_amd64.s:2059 +} + +func Example_stackTrace() { + type stackTracer interface { + StackTrace() errors.StackTrace + } + + err, ok := errors.Cause(fn()).(stackTracer) + if !ok { + panic("oops, err does not implement stackTracer") + } + + st := err.StackTrace() + fmt.Printf("%+v", st[0:2]) // top two frames + + // Example output: + // github.com/pkg/errors_test.fn + // /home/dfc/src/github.com/pkg/errors/example_test.go:47 + // github.com/pkg/errors_test.Example_stackTrace + // /home/dfc/src/github.com/pkg/errors/example_test.go:127 +} + +func ExampleCause_printf() { + err := errors.Wrap(func() error { + return func() error { + return errors.Errorf("hello %s", fmt.Sprintf("world")) + }() + }(), "failed") + + fmt.Printf("%v", err) + + // Output: failed: hello world +} diff --git a/vendor/github.com/pkg/errors/format_test.go b/vendor/github.com/pkg/errors/format_test.go new file mode 100644 index 0000000..15fd7d8 --- /dev/null +++ b/vendor/github.com/pkg/errors/format_test.go @@ -0,0 +1,535 @@ +package errors + +import ( + "errors" + "fmt" + "io" + "regexp" + "strings" + "testing" +) + +func TestFormatNew(t *testing.T) { + tests := []struct { + error + format string + want string + }{{ + New("error"), + "%s", + "error", + }, { + New("error"), + "%v", + "error", + }, { + New("error"), + "%+v", + "error\n" + + "github.com/pkg/errors.TestFormatNew\n" + + "\t.+/github.com/pkg/errors/format_test.go:26", + }, { + New("error"), + "%q", + `"error"`, + }} + + for i, tt := range tests { + testFormatRegexp(t, i, tt.error, tt.format, tt.want) + } +} + +func TestFormatErrorf(t *testing.T) { + tests := []struct { + error + format string + want string + }{{ + Errorf("%s", "error"), + "%s", + "error", + }, { + Errorf("%s", "error"), + "%v", + "error", + }, { + Errorf("%s", "error"), + "%+v", + "error\n" + + "github.com/pkg/errors.TestFormatErrorf\n" + + "\t.+/github.com/pkg/errors/format_test.go:56", + }} + + for i, tt := range tests { + testFormatRegexp(t, i, tt.error, tt.format, tt.want) + } +} + +func TestFormatWrap(t *testing.T) { + tests := []struct { + error + format string + want string + }{{ + Wrap(New("error"), "error2"), + "%s", + "error2: error", + }, { + Wrap(New("error"), "error2"), + "%v", + "error2: error", + }, { + Wrap(New("error"), "error2"), + "%+v", + "error\n" + + "github.com/pkg/errors.TestFormatWrap\n" + + "\t.+/github.com/pkg/errors/format_test.go:82", + }, { + Wrap(io.EOF, "error"), + "%s", + "error: EOF", + }, { + Wrap(io.EOF, "error"), + "%v", + "error: EOF", + }, { + Wrap(io.EOF, "error"), + "%+v", + "EOF\n" + + "error\n" + + "github.com/pkg/errors.TestFormatWrap\n" + + "\t.+/github.com/pkg/errors/format_test.go:96", + }, { + Wrap(Wrap(io.EOF, "error1"), "error2"), + "%+v", + "EOF\n" + + "error1\n" + + "github.com/pkg/errors.TestFormatWrap\n" + + "\t.+/github.com/pkg/errors/format_test.go:103\n", + }, { + Wrap(New("error with space"), "context"), + "%q", + `"context: error with space"`, + }} + + for i, tt := range tests { + testFormatRegexp(t, i, tt.error, tt.format, tt.want) + } +} + +func TestFormatWrapf(t *testing.T) { + tests := []struct { + error + format string + want string + }{{ + Wrapf(io.EOF, "error%d", 2), + "%s", + "error2: EOF", + }, { + Wrapf(io.EOF, "error%d", 2), + "%v", + "error2: EOF", + }, { + Wrapf(io.EOF, "error%d", 2), + "%+v", + "EOF\n" + + "error2\n" + + "github.com/pkg/errors.TestFormatWrapf\n" + + "\t.+/github.com/pkg/errors/format_test.go:134", + }, { + Wrapf(New("error"), "error%d", 2), + "%s", + "error2: error", + }, { + Wrapf(New("error"), "error%d", 2), + "%v", + "error2: error", + }, { + Wrapf(New("error"), "error%d", 2), + "%+v", + "error\n" + + "github.com/pkg/errors.TestFormatWrapf\n" + + "\t.+/github.com/pkg/errors/format_test.go:149", + }} + + for i, tt := range tests { + testFormatRegexp(t, i, tt.error, tt.format, tt.want) + } +} + +func TestFormatWithStack(t *testing.T) { + tests := []struct { + error + format string + want []string + }{{ + WithStack(io.EOF), + "%s", + []string{"EOF"}, + }, { + WithStack(io.EOF), + "%v", + []string{"EOF"}, + }, { + WithStack(io.EOF), + "%+v", + []string{"EOF", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:175"}, + }, { + WithStack(New("error")), + "%s", + []string{"error"}, + }, { + WithStack(New("error")), + "%v", + []string{"error"}, + }, { + WithStack(New("error")), + "%+v", + []string{"error", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:189", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:189"}, + }, { + WithStack(WithStack(io.EOF)), + "%+v", + []string{"EOF", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:197", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:197"}, + }, { + WithStack(WithStack(Wrapf(io.EOF, "message"))), + "%+v", + []string{"EOF", + "message", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:205", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:205", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:205"}, + }, { + WithStack(Errorf("error%d", 1)), + "%+v", + []string{"error1", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:216", + "github.com/pkg/errors.TestFormatWithStack\n" + + "\t.+/github.com/pkg/errors/format_test.go:216"}, + }} + + for i, tt := range tests { + testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) + } +} + +func TestFormatWithMessage(t *testing.T) { + tests := []struct { + error + format string + want []string + }{{ + WithMessage(New("error"), "error2"), + "%s", + []string{"error2: error"}, + }, { + WithMessage(New("error"), "error2"), + "%v", + []string{"error2: error"}, + }, { + WithMessage(New("error"), "error2"), + "%+v", + []string{ + "error", + "github.com/pkg/errors.TestFormatWithMessage\n" + + "\t.+/github.com/pkg/errors/format_test.go:244", + "error2"}, + }, { + WithMessage(io.EOF, "addition1"), + "%s", + []string{"addition1: EOF"}, + }, { + WithMessage(io.EOF, "addition1"), + "%v", + []string{"addition1: EOF"}, + }, { + WithMessage(io.EOF, "addition1"), + "%+v", + []string{"EOF", "addition1"}, + }, { + WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), + "%v", + []string{"addition2: addition1: EOF"}, + }, { + WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), + "%+v", + []string{"EOF", "addition1", "addition2"}, + }, { + Wrap(WithMessage(io.EOF, "error1"), "error2"), + "%+v", + []string{"EOF", "error1", "error2", + "github.com/pkg/errors.TestFormatWithMessage\n" + + "\t.+/github.com/pkg/errors/format_test.go:272"}, + }, { + WithMessage(Errorf("error%d", 1), "error2"), + "%+v", + []string{"error1", + "github.com/pkg/errors.TestFormatWithMessage\n" + + "\t.+/github.com/pkg/errors/format_test.go:278", + "error2"}, + }, { + WithMessage(WithStack(io.EOF), "error"), + "%+v", + []string{ + "EOF", + "github.com/pkg/errors.TestFormatWithMessage\n" + + "\t.+/github.com/pkg/errors/format_test.go:285", + "error"}, + }, { + WithMessage(Wrap(WithStack(io.EOF), "inside-error"), "outside-error"), + "%+v", + []string{ + "EOF", + "github.com/pkg/errors.TestFormatWithMessage\n" + + "\t.+/github.com/pkg/errors/format_test.go:293", + "inside-error", + "github.com/pkg/errors.TestFormatWithMessage\n" + + "\t.+/github.com/pkg/errors/format_test.go:293", + "outside-error"}, + }} + + for i, tt := range tests { + testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) + } +} + +func TestFormatGeneric(t *testing.T) { + starts := []struct { + err error + want []string + }{ + {New("new-error"), []string{ + "new-error", + "github.com/pkg/errors.TestFormatGeneric\n" + + "\t.+/github.com/pkg/errors/format_test.go:315"}, + }, {Errorf("errorf-error"), []string{ + "errorf-error", + "github.com/pkg/errors.TestFormatGeneric\n" + + "\t.+/github.com/pkg/errors/format_test.go:319"}, + }, {errors.New("errors-new-error"), []string{ + "errors-new-error"}, + }, + } + + wrappers := []wrapper{ + { + func(err error) error { return WithMessage(err, "with-message") }, + []string{"with-message"}, + }, { + func(err error) error { return WithStack(err) }, + []string{ + "github.com/pkg/errors.(func·002|TestFormatGeneric.func2)\n\t" + + ".+/github.com/pkg/errors/format_test.go:333", + }, + }, { + func(err error) error { return Wrap(err, "wrap-error") }, + []string{ + "wrap-error", + "github.com/pkg/errors.(func·003|TestFormatGeneric.func3)\n\t" + + ".+/github.com/pkg/errors/format_test.go:339", + }, + }, { + func(err error) error { return Wrapf(err, "wrapf-error%d", 1) }, + []string{ + "wrapf-error1", + "github.com/pkg/errors.(func·004|TestFormatGeneric.func4)\n\t" + + ".+/github.com/pkg/errors/format_test.go:346", + }, + }, + } + + for s := range starts { + err := starts[s].err + want := starts[s].want + testFormatCompleteCompare(t, s, err, "%+v", want, false) + testGenericRecursive(t, err, want, wrappers, 3) + } +} + +func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) { + got := fmt.Sprintf(format, arg) + gotLines := strings.SplitN(got, "\n", -1) + wantLines := strings.SplitN(want, "\n", -1) + + if len(wantLines) > len(gotLines) { + t.Errorf("test %d: wantLines(%d) > gotLines(%d):\n got: %q\nwant: %q", n+1, len(wantLines), len(gotLines), got, want) + return + } + + for i, w := range wantLines { + match, err := regexp.MatchString(w, gotLines[i]) + if err != nil { + t.Fatal(err) + } + if !match { + t.Errorf("test %d: line %d: fmt.Sprintf(%q, err):\n got: %q\nwant: %q", n+1, i+1, format, got, want) + } + } +} + +var stackLineR = regexp.MustCompile(`\.`) + +// parseBlocks parses input into a slice, where: +// - incase entry contains a newline, its a stacktrace +// - incase entry contains no newline, its a solo line. +// +// Detecting stack boundaries only works incase the WithStack-calls are +// to be found on the same line, thats why it is optionally here. +// +// Example use: +// +// for _, e := range blocks { +// if strings.ContainsAny(e, "\n") { +// // Match as stack +// } else { +// // Match as line +// } +// } +// +func parseBlocks(input string, detectStackboundaries bool) ([]string, error) { + var blocks []string + + stack := "" + wasStack := false + lines := map[string]bool{} // already found lines + + for _, l := range strings.Split(input, "\n") { + isStackLine := stackLineR.MatchString(l) + + switch { + case !isStackLine && wasStack: + blocks = append(blocks, stack, l) + stack = "" + lines = map[string]bool{} + case isStackLine: + if wasStack { + // Detecting two stacks after another, possible cause lines match in + // our tests due to WithStack(WithStack(io.EOF)) on same line. + if detectStackboundaries { + if lines[l] { + if len(stack) == 0 { + return nil, errors.New("len of block must not be zero here") + } + + blocks = append(blocks, stack) + stack = l + lines = map[string]bool{l: true} + continue + } + } + + stack = stack + "\n" + l + } else { + stack = l + } + lines[l] = true + case !isStackLine && !wasStack: + blocks = append(blocks, l) + default: + return nil, errors.New("must not happen") + } + + wasStack = isStackLine + } + + // Use up stack + if stack != "" { + blocks = append(blocks, stack) + } + return blocks, nil +} + +func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format string, want []string, detectStackBoundaries bool) { + gotStr := fmt.Sprintf(format, arg) + + got, err := parseBlocks(gotStr, detectStackBoundaries) + if err != nil { + t.Fatal(err) + } + + if len(got) != len(want) { + t.Fatalf("test %d: fmt.Sprintf(%s, err) -> wrong number of blocks: got(%d) want(%d)\n got: %s\nwant: %s\ngotStr: %q", + n+1, format, len(got), len(want), prettyBlocks(got), prettyBlocks(want), gotStr) + } + + for i := range got { + if strings.ContainsAny(want[i], "\n") { + // Match as stack + match, err := regexp.MatchString(want[i], got[i]) + if err != nil { + t.Fatal(err) + } + if !match { + t.Fatalf("test %d: block %d: fmt.Sprintf(%q, err):\ngot:\n%q\nwant:\n%q\nall-got:\n%s\nall-want:\n%s\n", + n+1, i+1, format, got[i], want[i], prettyBlocks(got), prettyBlocks(want)) + } + } else { + // Match as message + if got[i] != want[i] { + t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i]) + } + } + } +} + +type wrapper struct { + wrap func(err error) error + want []string +} + +func prettyBlocks(blocks []string, prefix ...string) string { + var out []string + + for _, b := range blocks { + out = append(out, fmt.Sprintf("%v", b)) + } + + return " " + strings.Join(out, "\n ") +} + +func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, list []wrapper, maxDepth int) { + if len(beforeWant) == 0 { + panic("beforeWant must not be empty") + } + for _, w := range list { + if len(w.want) == 0 { + panic("want must not be empty") + } + + err := w.wrap(beforeErr) + + // Copy required cause append(beforeWant, ..) modified beforeWant subtly. + beforeCopy := make([]string, len(beforeWant)) + copy(beforeCopy, beforeWant) + + beforeWant := beforeCopy + last := len(beforeWant) - 1 + var want []string + + // Merge two stacks behind each other. + if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") { + want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...) + } else { + want = append(beforeWant, w.want...) + } + + testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false) + if maxDepth > 0 { + testGenericRecursive(t, err, want, list, maxDepth-1) + } + } +} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go new file mode 100644 index 0000000..6b1f289 --- /dev/null +++ b/vendor/github.com/pkg/errors/stack.go @@ -0,0 +1,178 @@ +package errors + +import ( + "fmt" + "io" + "path" + "runtime" + "strings" +) + +// Frame represents a program counter inside a stack frame. +type Frame uintptr + +// pc returns the program counter for this frame; +// multiple frames may have the same PC value. +func (f Frame) pc() uintptr { return uintptr(f) - 1 } + +// file returns the full path to the file that contains the +// function for this Frame's pc. +func (f Frame) file() string { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return "unknown" + } + file, _ := fn.FileLine(f.pc()) + return file +} + +// line returns the line number of source code of the +// function for this Frame's pc. +func (f Frame) line() int { + fn := runtime.FuncForPC(f.pc()) + if fn == nil { + return 0 + } + _, line := fn.FileLine(f.pc()) + return line +} + +// Format formats the frame according to the fmt.Formatter interface. +// +// %s source file +// %d source line +// %n function name +// %v equivalent to %s:%d +// +// Format accepts flags that alter the printing of some verbs, as follows: +// +// %+s path of source file relative to the compile time GOPATH +// %+v equivalent to %+s:%d +func (f Frame) Format(s fmt.State, verb rune) { + switch verb { + case 's': + switch { + case s.Flag('+'): + pc := f.pc() + fn := runtime.FuncForPC(pc) + if fn == nil { + io.WriteString(s, "unknown") + } else { + file, _ := fn.FileLine(pc) + fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file) + } + default: + io.WriteString(s, path.Base(f.file())) + } + case 'd': + fmt.Fprintf(s, "%d", f.line()) + case 'n': + name := runtime.FuncForPC(f.pc()).Name() + io.WriteString(s, funcname(name)) + case 'v': + f.Format(s, 's') + io.WriteString(s, ":") + f.Format(s, 'd') + } +} + +// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). +type StackTrace []Frame + +func (st StackTrace) Format(s fmt.State, verb rune) { + switch verb { + case 'v': + switch { + case s.Flag('+'): + for _, f := range st { + fmt.Fprintf(s, "\n%+v", f) + } + case s.Flag('#'): + fmt.Fprintf(s, "%#v", []Frame(st)) + default: + fmt.Fprintf(s, "%v", []Frame(st)) + } + case 's': + fmt.Fprintf(s, "%s", []Frame(st)) + } +} + +// stack represents a stack of program counters. +type stack []uintptr + +func (s *stack) Format(st fmt.State, verb rune) { + switch verb { + case 'v': + switch { + case st.Flag('+'): + for _, pc := range *s { + f := Frame(pc) + fmt.Fprintf(st, "\n%+v", f) + } + } + } +} + +func (s *stack) StackTrace() StackTrace { + f := make([]Frame, len(*s)) + for i := 0; i < len(f); i++ { + f[i] = Frame((*s)[i]) + } + return f +} + +func callers() *stack { + const depth = 32 + var pcs [depth]uintptr + n := runtime.Callers(3, pcs[:]) + var st stack = pcs[0:n] + return &st +} + +// funcname removes the path prefix component of a function's name reported by func.Name(). +func funcname(name string) string { + i := strings.LastIndex(name, "/") + name = name[i+1:] + i = strings.Index(name, ".") + return name[i+1:] +} + +func trimGOPATH(name, file string) string { + // Here we want to get the source file path relative to the compile time + // GOPATH. As of Go 1.6.x there is no direct way to know the compiled + // GOPATH at runtime, but we can infer the number of path segments in the + // GOPATH. We note that fn.Name() returns the function name qualified by + // the import path, which does not include the GOPATH. Thus we can trim + // segments from the beginning of the file path until the number of path + // separators remaining is one more than the number of path separators in + // the function name. For example, given: + // + // GOPATH /home/user + // file /home/user/src/pkg/sub/file.go + // fn.Name() pkg/sub.Type.Method + // + // We want to produce: + // + // pkg/sub/file.go + // + // From this we can easily see that fn.Name() has one less path separator + // than our desired output. We count separators from the end of the file + // path until it finds two more than in the function name and then move + // one character forward to preserve the initial path segment without a + // leading separator. + const sep = "/" + goal := strings.Count(name, sep) + 2 + i := len(file) + for n := 0; n < goal; n++ { + i = strings.LastIndex(file[:i], sep) + if i == -1 { + // not enough separators found, set i so that the slice expression + // below leaves file unmodified + i = -len(sep) + break + } + } + // get back to 0 or trim the leading separator + file = file[i+len(sep):] + return file +} diff --git a/vendor/github.com/pkg/errors/stack_test.go b/vendor/github.com/pkg/errors/stack_test.go new file mode 100644 index 0000000..510c27a --- /dev/null +++ b/vendor/github.com/pkg/errors/stack_test.go @@ -0,0 +1,292 @@ +package errors + +import ( + "fmt" + "runtime" + "testing" +) + +var initpc, _, _, _ = runtime.Caller(0) + +func TestFrameLine(t *testing.T) { + var tests = []struct { + Frame + want int + }{{ + Frame(initpc), + 9, + }, { + func() Frame { + var pc, _, _, _ = runtime.Caller(0) + return Frame(pc) + }(), + 20, + }, { + func() Frame { + var pc, _, _, _ = runtime.Caller(1) + return Frame(pc) + }(), + 28, + }, { + Frame(0), // invalid PC + 0, + }} + + for _, tt := range tests { + got := tt.Frame.line() + want := tt.want + if want != got { + t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got) + } + } +} + +type X struct{} + +func (x X) val() Frame { + var pc, _, _, _ = runtime.Caller(0) + return Frame(pc) +} + +func (x *X) ptr() Frame { + var pc, _, _, _ = runtime.Caller(0) + return Frame(pc) +} + +func TestFrameFormat(t *testing.T) { + var tests = []struct { + Frame + format string + want string + }{{ + Frame(initpc), + "%s", + "stack_test.go", + }, { + Frame(initpc), + "%+s", + "github.com/pkg/errors.init\n" + + "\t.+/github.com/pkg/errors/stack_test.go", + }, { + Frame(0), + "%s", + "unknown", + }, { + Frame(0), + "%+s", + "unknown", + }, { + Frame(initpc), + "%d", + "9", + }, { + Frame(0), + "%d", + "0", + }, { + Frame(initpc), + "%n", + "init", + }, { + func() Frame { + var x X + return x.ptr() + }(), + "%n", + `\(\*X\).ptr`, + }, { + func() Frame { + var x X + return x.val() + }(), + "%n", + "X.val", + }, { + Frame(0), + "%n", + "", + }, { + Frame(initpc), + "%v", + "stack_test.go:9", + }, { + Frame(initpc), + "%+v", + "github.com/pkg/errors.init\n" + + "\t.+/github.com/pkg/errors/stack_test.go:9", + }, { + Frame(0), + "%v", + "unknown:0", + }} + + for i, tt := range tests { + testFormatRegexp(t, i, tt.Frame, tt.format, tt.want) + } +} + +func TestFuncname(t *testing.T) { + tests := []struct { + name, want string + }{ + {"", ""}, + {"runtime.main", "main"}, + {"github.com/pkg/errors.funcname", "funcname"}, + {"funcname", "funcname"}, + {"io.copyBuffer", "copyBuffer"}, + {"main.(*R).Write", "(*R).Write"}, + } + + for _, tt := range tests { + got := funcname(tt.name) + want := tt.want + if got != want { + t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got) + } + } +} + +func TestTrimGOPATH(t *testing.T) { + var tests = []struct { + Frame + want string + }{{ + Frame(initpc), + "github.com/pkg/errors/stack_test.go", + }} + + for i, tt := range tests { + pc := tt.Frame.pc() + fn := runtime.FuncForPC(pc) + file, _ := fn.FileLine(pc) + got := trimGOPATH(fn.Name(), file) + testFormatRegexp(t, i, got, "%s", tt.want) + } +} + +func TestStackTrace(t *testing.T) { + tests := []struct { + err error + want []string + }{{ + New("ooh"), []string{ + "github.com/pkg/errors.TestStackTrace\n" + + "\t.+/github.com/pkg/errors/stack_test.go:172", + }, + }, { + Wrap(New("ooh"), "ahh"), []string{ + "github.com/pkg/errors.TestStackTrace\n" + + "\t.+/github.com/pkg/errors/stack_test.go:177", // this is the stack of Wrap, not New + }, + }, { + Cause(Wrap(New("ooh"), "ahh")), []string{ + "github.com/pkg/errors.TestStackTrace\n" + + "\t.+/github.com/pkg/errors/stack_test.go:182", // this is the stack of New + }, + }, { + func() error { return New("ooh") }(), []string{ + `github.com/pkg/errors.(func·009|TestStackTrace.func1)` + + "\n\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New + "github.com/pkg/errors.TestStackTrace\n" + + "\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New's caller + }, + }, { + Cause(func() error { + return func() error { + return Errorf("hello %s", fmt.Sprintf("world")) + }() + }()), []string{ + `github.com/pkg/errors.(func·010|TestStackTrace.func2.1)` + + "\n\t.+/github.com/pkg/errors/stack_test.go:196", // this is the stack of Errorf + `github.com/pkg/errors.(func·011|TestStackTrace.func2)` + + "\n\t.+/github.com/pkg/errors/stack_test.go:197", // this is the stack of Errorf's caller + "github.com/pkg/errors.TestStackTrace\n" + + "\t.+/github.com/pkg/errors/stack_test.go:198", // this is the stack of Errorf's caller's caller + }, + }} + for i, tt := range tests { + x, ok := tt.err.(interface { + StackTrace() StackTrace + }) + if !ok { + t.Errorf("expected %#v to implement StackTrace() StackTrace", tt.err) + continue + } + st := x.StackTrace() + for j, want := range tt.want { + testFormatRegexp(t, i, st[j], "%+v", want) + } + } +} + +func stackTrace() StackTrace { + const depth = 8 + var pcs [depth]uintptr + n := runtime.Callers(1, pcs[:]) + var st stack = pcs[0:n] + return st.StackTrace() +} + +func TestStackTraceFormat(t *testing.T) { + tests := []struct { + StackTrace + format string + want string + }{{ + nil, + "%s", + `\[\]`, + }, { + nil, + "%v", + `\[\]`, + }, { + nil, + "%+v", + "", + }, { + nil, + "%#v", + `\[\]errors.Frame\(nil\)`, + }, { + make(StackTrace, 0), + "%s", + `\[\]`, + }, { + make(StackTrace, 0), + "%v", + `\[\]`, + }, { + make(StackTrace, 0), + "%+v", + "", + }, { + make(StackTrace, 0), + "%#v", + `\[\]errors.Frame{}`, + }, { + stackTrace()[:2], + "%s", + `\[stack_test.go stack_test.go\]`, + }, { + stackTrace()[:2], + "%v", + `\[stack_test.go:225 stack_test.go:272\]`, + }, { + stackTrace()[:2], + "%+v", + "\n" + + "github.com/pkg/errors.stackTrace\n" + + "\t.+/github.com/pkg/errors/stack_test.go:225\n" + + "github.com/pkg/errors.TestStackTraceFormat\n" + + "\t.+/github.com/pkg/errors/stack_test.go:276", + }, { + stackTrace()[:2], + "%#v", + `\[\]errors.Frame{stack_test.go:225, stack_test.go:284}`, + }} + + for i, tt := range tests { + testFormatRegexp(t, i, tt.StackTrace, tt.format, tt.want) + } +} From 8aae08ff9fb9a8fe293deea3d057f37d89744670 Mon Sep 17 00:00:00 2001 From: Richard Musiol Date: Tue, 12 Sep 2017 17:53:03 +0200 Subject: [PATCH 14/48] [fix] Remove unused variable "token" from TestNoCookie (#71) For some reason the Go compiler does not complain about it, but the `go/types` package does when reading this file. --- csrf_test.go | 5 ----- 1 file changed, 5 deletions(-) diff --git a/csrf_test.go b/csrf_test.go index eed669c..2f458a7 100644 --- a/csrf_test.go +++ b/csrf_test.go @@ -132,11 +132,6 @@ func TestNoCookie(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) - })) - // POST the token back in the header. r, err := http.NewRequest("POST", "http://www.gorillatoolkit.org/", nil) if err != nil { From 90b0c5962e48154b643f4a7b3db659629c0ab52e Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Mon, 21 May 2018 22:11:00 -0700 Subject: [PATCH 15/48] [build] Define go.mod (#83) Removes committed /vendor dir. Retains Godeps (dep) manifests for the time being. --- go.mod | 7 + vendor/github.com/gorilla/context/.travis.yml | 19 - vendor/github.com/gorilla/context/LICENSE | 27 - vendor/github.com/gorilla/context/README.md | 7 - vendor/github.com/gorilla/context/context.go | 143 ---- .../gorilla/context/context_test.go | 161 ----- vendor/github.com/gorilla/context/doc.go | 82 --- .../gorilla/securecookie/.travis.yml | 18 - .../github.com/gorilla/securecookie/LICENSE | 27 - .../github.com/gorilla/securecookie/README.md | 76 --- vendor/github.com/gorilla/securecookie/doc.go | 61 -- .../github.com/gorilla/securecookie/fuzz.go | 25 - .../gorilla/securecookie/fuzz/gencorpus.go | 47 -- .../gorilla/securecookie/securecookie.go | 646 ------------------ .../gorilla/securecookie/securecookie_test.go | 274 -------- vendor/github.com/pkg/errors/.gitignore | 24 - vendor/github.com/pkg/errors/.travis.yml | 11 - vendor/github.com/pkg/errors/LICENSE | 23 - vendor/github.com/pkg/errors/README.md | 52 -- vendor/github.com/pkg/errors/appveyor.yml | 32 - vendor/github.com/pkg/errors/bench_test.go | 59 -- vendor/github.com/pkg/errors/errors.go | 269 -------- vendor/github.com/pkg/errors/errors_test.go | 226 ------ vendor/github.com/pkg/errors/example_test.go | 205 ------ vendor/github.com/pkg/errors/format_test.go | 535 --------------- vendor/github.com/pkg/errors/stack.go | 178 ----- vendor/github.com/pkg/errors/stack_test.go | 292 -------- 27 files changed, 7 insertions(+), 3519 deletions(-) create mode 100644 go.mod delete mode 100644 vendor/github.com/gorilla/context/.travis.yml delete mode 100644 vendor/github.com/gorilla/context/LICENSE delete mode 100644 vendor/github.com/gorilla/context/README.md delete mode 100644 vendor/github.com/gorilla/context/context.go delete mode 100644 vendor/github.com/gorilla/context/context_test.go delete mode 100644 vendor/github.com/gorilla/context/doc.go delete mode 100644 vendor/github.com/gorilla/securecookie/.travis.yml delete mode 100644 vendor/github.com/gorilla/securecookie/LICENSE delete mode 100644 vendor/github.com/gorilla/securecookie/README.md delete mode 100644 vendor/github.com/gorilla/securecookie/doc.go delete mode 100644 vendor/github.com/gorilla/securecookie/fuzz.go delete mode 100644 vendor/github.com/gorilla/securecookie/fuzz/gencorpus.go delete mode 100644 vendor/github.com/gorilla/securecookie/securecookie.go delete mode 100644 vendor/github.com/gorilla/securecookie/securecookie_test.go delete mode 100644 vendor/github.com/pkg/errors/.gitignore delete mode 100644 vendor/github.com/pkg/errors/.travis.yml delete mode 100644 vendor/github.com/pkg/errors/LICENSE delete mode 100644 vendor/github.com/pkg/errors/README.md delete mode 100644 vendor/github.com/pkg/errors/appveyor.yml delete mode 100644 vendor/github.com/pkg/errors/bench_test.go delete mode 100644 vendor/github.com/pkg/errors/errors.go delete mode 100644 vendor/github.com/pkg/errors/errors_test.go delete mode 100644 vendor/github.com/pkg/errors/example_test.go delete mode 100644 vendor/github.com/pkg/errors/format_test.go delete mode 100644 vendor/github.com/pkg/errors/stack.go delete mode 100644 vendor/github.com/pkg/errors/stack_test.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..2d2ce4d --- /dev/null +++ b/go.mod @@ -0,0 +1,7 @@ +module github.com/gorilla/csrf + +require ( + github.com/gorilla/context v1.1.1 + github.com/gorilla/securecookie v1.1.1 + github.com/pkg/errors v0.8.0 +) diff --git a/vendor/github.com/gorilla/context/.travis.yml b/vendor/github.com/gorilla/context/.travis.yml deleted file mode 100644 index faca4da..0000000 --- a/vendor/github.com/gorilla/context/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -language: go -sudo: false - -matrix: - include: - - go: 1.3 - - go: 1.4 - - go: 1.5 - - go: 1.6 - - go: tip - -install: - - go get golang.org/x/tools/cmd/vet - -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d .) - - go tool vet . - - go test -v -race ./... diff --git a/vendor/github.com/gorilla/context/LICENSE b/vendor/github.com/gorilla/context/LICENSE deleted file mode 100644 index 0e5fb87..0000000 --- a/vendor/github.com/gorilla/context/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 Rodrigo Moraes. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * 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. - * Neither the name of Google Inc. 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 -OWNER 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. diff --git a/vendor/github.com/gorilla/context/README.md b/vendor/github.com/gorilla/context/README.md deleted file mode 100644 index c60a31b..0000000 --- a/vendor/github.com/gorilla/context/README.md +++ /dev/null @@ -1,7 +0,0 @@ -context -======= -[![Build Status](https://travis-ci.org/gorilla/context.png?branch=master)](https://travis-ci.org/gorilla/context) - -gorilla/context is a general purpose registry for global request variables. - -Read the full documentation here: http://www.gorillatoolkit.org/pkg/context diff --git a/vendor/github.com/gorilla/context/context.go b/vendor/github.com/gorilla/context/context.go deleted file mode 100644 index 81cb128..0000000 --- a/vendor/github.com/gorilla/context/context.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2012 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package context - -import ( - "net/http" - "sync" - "time" -) - -var ( - mutex sync.RWMutex - data = make(map[*http.Request]map[interface{}]interface{}) - datat = make(map[*http.Request]int64) -) - -// Set stores a value for a given key in a given request. -func Set(r *http.Request, key, val interface{}) { - mutex.Lock() - if data[r] == nil { - data[r] = make(map[interface{}]interface{}) - datat[r] = time.Now().Unix() - } - data[r][key] = val - mutex.Unlock() -} - -// Get returns a value stored for a given key in a given request. -func Get(r *http.Request, key interface{}) interface{} { - mutex.RLock() - if ctx := data[r]; ctx != nil { - value := ctx[key] - mutex.RUnlock() - return value - } - mutex.RUnlock() - return nil -} - -// GetOk returns stored value and presence state like multi-value return of map access. -func GetOk(r *http.Request, key interface{}) (interface{}, bool) { - mutex.RLock() - if _, ok := data[r]; ok { - value, ok := data[r][key] - mutex.RUnlock() - return value, ok - } - mutex.RUnlock() - return nil, false -} - -// GetAll returns all stored values for the request as a map. Nil is returned for invalid requests. -func GetAll(r *http.Request) map[interface{}]interface{} { - mutex.RLock() - if context, ok := data[r]; ok { - result := make(map[interface{}]interface{}, len(context)) - for k, v := range context { - result[k] = v - } - mutex.RUnlock() - return result - } - mutex.RUnlock() - return nil -} - -// GetAllOk returns all stored values for the request as a map and a boolean value that indicates if -// the request was registered. -func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) { - mutex.RLock() - context, ok := data[r] - result := make(map[interface{}]interface{}, len(context)) - for k, v := range context { - result[k] = v - } - mutex.RUnlock() - return result, ok -} - -// Delete removes a value stored for a given key in a given request. -func Delete(r *http.Request, key interface{}) { - mutex.Lock() - if data[r] != nil { - delete(data[r], key) - } - mutex.Unlock() -} - -// Clear removes all values stored for a given request. -// -// This is usually called by a handler wrapper to clean up request -// variables at the end of a request lifetime. See ClearHandler(). -func Clear(r *http.Request) { - mutex.Lock() - clear(r) - mutex.Unlock() -} - -// clear is Clear without the lock. -func clear(r *http.Request) { - delete(data, r) - delete(datat, r) -} - -// Purge removes request data stored for longer than maxAge, in seconds. -// It returns the amount of requests removed. -// -// If maxAge <= 0, all request data is removed. -// -// This is only used for sanity check: in case context cleaning was not -// properly set some request data can be kept forever, consuming an increasing -// amount of memory. In case this is detected, Purge() must be called -// periodically until the problem is fixed. -func Purge(maxAge int) int { - mutex.Lock() - count := 0 - if maxAge <= 0 { - count = len(data) - data = make(map[*http.Request]map[interface{}]interface{}) - datat = make(map[*http.Request]int64) - } else { - min := time.Now().Unix() - int64(maxAge) - for r := range data { - if datat[r] < min { - clear(r) - count++ - } - } - } - mutex.Unlock() - return count -} - -// ClearHandler wraps an http.Handler and clears request values at the end -// of a request lifetime. -func ClearHandler(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer Clear(r) - h.ServeHTTP(w, r) - }) -} diff --git a/vendor/github.com/gorilla/context/context_test.go b/vendor/github.com/gorilla/context/context_test.go deleted file mode 100644 index 9814c50..0000000 --- a/vendor/github.com/gorilla/context/context_test.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2012 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package context - -import ( - "net/http" - "testing" -) - -type keyType int - -const ( - key1 keyType = iota - key2 -) - -func TestContext(t *testing.T) { - assertEqual := func(val interface{}, exp interface{}) { - if val != exp { - t.Errorf("Expected %v, got %v.", exp, val) - } - } - - r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - emptyR, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - - // Get() - assertEqual(Get(r, key1), nil) - - // Set() - Set(r, key1, "1") - assertEqual(Get(r, key1), "1") - assertEqual(len(data[r]), 1) - - Set(r, key2, "2") - assertEqual(Get(r, key2), "2") - assertEqual(len(data[r]), 2) - - //GetOk - value, ok := GetOk(r, key1) - assertEqual(value, "1") - assertEqual(ok, true) - - value, ok = GetOk(r, "not exists") - assertEqual(value, nil) - assertEqual(ok, false) - - Set(r, "nil value", nil) - value, ok = GetOk(r, "nil value") - assertEqual(value, nil) - assertEqual(ok, true) - - // GetAll() - values := GetAll(r) - assertEqual(len(values), 3) - - // GetAll() for empty request - values = GetAll(emptyR) - if values != nil { - t.Error("GetAll didn't return nil value for invalid request") - } - - // GetAllOk() - values, ok = GetAllOk(r) - assertEqual(len(values), 3) - assertEqual(ok, true) - - // GetAllOk() for empty request - values, ok = GetAllOk(emptyR) - assertEqual(value, nil) - assertEqual(ok, false) - - // Delete() - Delete(r, key1) - assertEqual(Get(r, key1), nil) - assertEqual(len(data[r]), 2) - - Delete(r, key2) - assertEqual(Get(r, key2), nil) - assertEqual(len(data[r]), 1) - - // Clear() - Clear(r) - assertEqual(len(data), 0) -} - -func parallelReader(r *http.Request, key string, iterations int, wait, done chan struct{}) { - <-wait - for i := 0; i < iterations; i++ { - Get(r, key) - } - done <- struct{}{} - -} - -func parallelWriter(r *http.Request, key, value string, iterations int, wait, done chan struct{}) { - <-wait - for i := 0; i < iterations; i++ { - Set(r, key, value) - } - done <- struct{}{} - -} - -func benchmarkMutex(b *testing.B, numReaders, numWriters, iterations int) { - - b.StopTimer() - r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) - done := make(chan struct{}) - b.StartTimer() - - for i := 0; i < b.N; i++ { - wait := make(chan struct{}) - - for i := 0; i < numReaders; i++ { - go parallelReader(r, "test", iterations, wait, done) - } - - for i := 0; i < numWriters; i++ { - go parallelWriter(r, "test", "123", iterations, wait, done) - } - - close(wait) - - for i := 0; i < numReaders+numWriters; i++ { - <-done - } - - } - -} - -func BenchmarkMutexSameReadWrite1(b *testing.B) { - benchmarkMutex(b, 1, 1, 32) -} -func BenchmarkMutexSameReadWrite2(b *testing.B) { - benchmarkMutex(b, 2, 2, 32) -} -func BenchmarkMutexSameReadWrite4(b *testing.B) { - benchmarkMutex(b, 4, 4, 32) -} -func BenchmarkMutex1(b *testing.B) { - benchmarkMutex(b, 2, 8, 32) -} -func BenchmarkMutex2(b *testing.B) { - benchmarkMutex(b, 16, 4, 64) -} -func BenchmarkMutex3(b *testing.B) { - benchmarkMutex(b, 1, 2, 128) -} -func BenchmarkMutex4(b *testing.B) { - benchmarkMutex(b, 128, 32, 256) -} -func BenchmarkMutex5(b *testing.B) { - benchmarkMutex(b, 1024, 2048, 64) -} -func BenchmarkMutex6(b *testing.B) { - benchmarkMutex(b, 2048, 1024, 512) -} diff --git a/vendor/github.com/gorilla/context/doc.go b/vendor/github.com/gorilla/context/doc.go deleted file mode 100644 index 73c7400..0000000 --- a/vendor/github.com/gorilla/context/doc.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2012 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package context stores values shared during a request lifetime. - -For example, a router can set variables extracted from the URL and later -application handlers can access those values, or it can be used to store -sessions values to be saved at the end of a request. There are several -others common uses. - -The idea was posted by Brad Fitzpatrick to the go-nuts mailing list: - - http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53 - -Here's the basic usage: first define the keys that you will need. The key -type is interface{} so a key can be of any type that supports equality. -Here we define a key using a custom int type to avoid name collisions: - - package foo - - import ( - "github.com/gorilla/context" - ) - - type key int - - const MyKey key = 0 - -Then set a variable. Variables are bound to an http.Request object, so you -need a request instance to set a value: - - context.Set(r, MyKey, "bar") - -The application can later access the variable using the same key you provided: - - func MyHandler(w http.ResponseWriter, r *http.Request) { - // val is "bar". - val := context.Get(r, foo.MyKey) - - // returns ("bar", true) - val, ok := context.GetOk(r, foo.MyKey) - // ... - } - -And that's all about the basic usage. We discuss some other ideas below. - -Any type can be stored in the context. To enforce a given type, make the key -private and wrap Get() and Set() to accept and return values of a specific -type: - - type key int - - const mykey key = 0 - - // GetMyKey returns a value for this package from the request values. - func GetMyKey(r *http.Request) SomeType { - if rv := context.Get(r, mykey); rv != nil { - return rv.(SomeType) - } - return nil - } - - // SetMyKey sets a value for this package in the request values. - func SetMyKey(r *http.Request, val SomeType) { - context.Set(r, mykey, val) - } - -Variables must be cleared at the end of a request, to remove all values -that were stored. This can be done in an http.Handler, after a request was -served. Just call Clear() passing the request: - - context.Clear(r) - -...or use ClearHandler(), which conveniently wraps an http.Handler to clear -variables at the end of a request lifetime. - -The Routers from the packages gorilla/mux and gorilla/pat call Clear() -so if you are using either of them you don't need to clear the context manually. -*/ -package context diff --git a/vendor/github.com/gorilla/securecookie/.travis.yml b/vendor/github.com/gorilla/securecookie/.travis.yml deleted file mode 100644 index 24882fc..0000000 --- a/vendor/github.com/gorilla/securecookie/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: go -sudo: false - -matrix: - include: - - go: 1.3 - - go: 1.4 - - go: 1.5 - - go: 1.6 - - go: tip - allow_failures: - - go: tip - -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d .) - - go vet $(go list ./... | grep -v /vendor/) - - go test -v -race ./... diff --git a/vendor/github.com/gorilla/securecookie/LICENSE b/vendor/github.com/gorilla/securecookie/LICENSE deleted file mode 100644 index 0e5fb87..0000000 --- a/vendor/github.com/gorilla/securecookie/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 Rodrigo Moraes. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * 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. - * Neither the name of Google Inc. 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 -OWNER 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. diff --git a/vendor/github.com/gorilla/securecookie/README.md b/vendor/github.com/gorilla/securecookie/README.md deleted file mode 100644 index 5ed299e..0000000 --- a/vendor/github.com/gorilla/securecookie/README.md +++ /dev/null @@ -1,76 +0,0 @@ -securecookie -============ -[![GoDoc](https://godoc.org/github.com/gorilla/securecookie?status.svg)](https://godoc.org/github.com/gorilla/securecookie) [![Build Status](https://travis-ci.org/gorilla/securecookie.png?branch=master)](https://travis-ci.org/gorilla/securecookie) - -securecookie encodes and decodes authenticated and optionally encrypted -cookie values. - -Secure cookies can't be forged, because their values are validated using HMAC. -When encrypted, the content is also inaccessible to malicious eyes. It is still -recommended that sensitive data not be stored in cookies, and that HTTPS be used -to prevent cookie [replay attacks](https://en.wikipedia.org/wiki/Replay_attack). - -## Examples - -To use it, first create a new SecureCookie instance: - -```go -// Hash keys should be at least 32 bytes long -var hashKey = []byte("very-secret") -// Block keys should be 16 bytes (AES-128) or 32 bytes (AES-256) long. -// Shorter keys may weaken the encryption used. -var blockKey = []byte("a-lot-secret") -var s = securecookie.New(hashKey, blockKey) -``` - -The hashKey is required, used to authenticate the cookie value using HMAC. -It is recommended to use a key with 32 or 64 bytes. - -The blockKey is optional, used to encrypt the cookie value -- set it to nil -to not use encryption. If set, the length must correspond to the block size -of the encryption algorithm. For AES, used by default, valid lengths are -16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. - -Strong keys can be created using the convenience function GenerateRandomKey(). - -Once a SecureCookie instance is set, use it to encode a cookie value: - -```go -func SetCookieHandler(w http.ResponseWriter, r *http.Request) { - value := map[string]string{ - "foo": "bar", - } - if encoded, err := s.Encode("cookie-name", value); err == nil { - cookie := &http.Cookie{ - Name: "cookie-name", - Value: encoded, - Path: "/", - } - http.SetCookie(w, cookie) - } -} -``` - -Later, use the same SecureCookie instance to decode and validate a cookie -value: - -```go -func ReadCookieHandler(w http.ResponseWriter, r *http.Request) { - if cookie, err := r.Cookie("cookie-name"); err == nil { - value := make(map[string]string) - if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil { - fmt.Fprintf(w, "The value of foo is %q", value["foo"]) - } - } -} -``` - -We stored a map[string]string, but secure cookies can hold any value that -can be encoded using `encoding/gob`. To store custom types, they must be -registered first using gob.Register(). For basic types this is not needed; -it works out of the box. An optional JSON encoder that uses `encoding/json` is -available for types compatible with JSON. - -## License - -BSD licensed. See the LICENSE file for details. diff --git a/vendor/github.com/gorilla/securecookie/doc.go b/vendor/github.com/gorilla/securecookie/doc.go deleted file mode 100644 index ae89408..0000000 --- a/vendor/github.com/gorilla/securecookie/doc.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2012 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package securecookie encodes and decodes authenticated and optionally -encrypted cookie values. - -Secure cookies can't be forged, because their values are validated using HMAC. -When encrypted, the content is also inaccessible to malicious eyes. - -To use it, first create a new SecureCookie instance: - - var hashKey = []byte("very-secret") - var blockKey = []byte("a-lot-secret") - var s = securecookie.New(hashKey, blockKey) - -The hashKey is required, used to authenticate the cookie value using HMAC. -It is recommended to use a key with 32 or 64 bytes. - -The blockKey is optional, used to encrypt the cookie value -- set it to nil -to not use encryption. If set, the length must correspond to the block size -of the encryption algorithm. For AES, used by default, valid lengths are -16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. - -Strong keys can be created using the convenience function GenerateRandomKey(). - -Once a SecureCookie instance is set, use it to encode a cookie value: - - func SetCookieHandler(w http.ResponseWriter, r *http.Request) { - value := map[string]string{ - "foo": "bar", - } - if encoded, err := s.Encode("cookie-name", value); err == nil { - cookie := &http.Cookie{ - Name: "cookie-name", - Value: encoded, - Path: "/", - } - http.SetCookie(w, cookie) - } - } - -Later, use the same SecureCookie instance to decode and validate a cookie -value: - - func ReadCookieHandler(w http.ResponseWriter, r *http.Request) { - if cookie, err := r.Cookie("cookie-name"); err == nil { - value := make(map[string]string) - if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil { - fmt.Fprintf(w, "The value of foo is %q", value["foo"]) - } - } - } - -We stored a map[string]string, but secure cookies can hold any value that -can be encoded using encoding/gob. To store custom types, they must be -registered first using gob.Register(). For basic types this is not needed; -it works out of the box. -*/ -package securecookie diff --git a/vendor/github.com/gorilla/securecookie/fuzz.go b/vendor/github.com/gorilla/securecookie/fuzz.go deleted file mode 100644 index e4d0534..0000000 --- a/vendor/github.com/gorilla/securecookie/fuzz.go +++ /dev/null @@ -1,25 +0,0 @@ -// +build gofuzz - -package securecookie - -var hashKey = []byte("very-secret12345") -var blockKey = []byte("a-lot-secret1234") -var s = New(hashKey, blockKey) - -type Cookie struct { - B bool - I int - S string -} - -func Fuzz(data []byte) int { - datas := string(data) - var c Cookie - if err := s.Decode("fuzz", datas, &c); err != nil { - return 0 - } - if _, err := s.Encode("fuzz", c); err != nil { - panic(err) - } - return 1 -} diff --git a/vendor/github.com/gorilla/securecookie/fuzz/gencorpus.go b/vendor/github.com/gorilla/securecookie/fuzz/gencorpus.go deleted file mode 100644 index 368192b..0000000 --- a/vendor/github.com/gorilla/securecookie/fuzz/gencorpus.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - "fmt" - "io" - "math/rand" - "os" - "reflect" - "testing/quick" - - "github.com/gorilla/securecookie" -) - -var hashKey = []byte("very-secret12345") -var blockKey = []byte("a-lot-secret1234") -var s = securecookie.New(hashKey, blockKey) - -type Cookie struct { - B bool - I int - S string -} - -func main() { - var c Cookie - t := reflect.TypeOf(c) - rnd := rand.New(rand.NewSource(0)) - for i := 0; i < 100; i++ { - v, ok := quick.Value(t, rnd) - if !ok { - panic("couldn't generate value") - } - encoded, err := s.Encode("fuzz", v.Interface()) - if err != nil { - panic(err) - } - f, err := os.Create(fmt.Sprintf("corpus/%d.sc", i)) - if err != nil { - panic(err) - } - _, err = io.WriteString(f, encoded) - if err != nil { - panic(err) - } - f.Close() - } -} diff --git a/vendor/github.com/gorilla/securecookie/securecookie.go b/vendor/github.com/gorilla/securecookie/securecookie.go deleted file mode 100644 index 83dd606..0000000 --- a/vendor/github.com/gorilla/securecookie/securecookie.go +++ /dev/null @@ -1,646 +0,0 @@ -// Copyright 2012 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package securecookie - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/hmac" - "crypto/rand" - "crypto/sha256" - "crypto/subtle" - "encoding/base64" - "encoding/gob" - "encoding/json" - "fmt" - "hash" - "io" - "strconv" - "strings" - "time" -) - -// Error is the interface of all errors returned by functions in this library. -type Error interface { - error - - // IsUsage returns true for errors indicating the client code probably - // uses this library incorrectly. For example, the client may have - // failed to provide a valid hash key, or may have failed to configure - // the Serializer adequately for encoding value. - IsUsage() bool - - // IsDecode returns true for errors indicating that a cookie could not - // be decoded and validated. Since cookies are usually untrusted - // user-provided input, errors of this type should be expected. - // Usually, the proper action is simply to reject the request. - IsDecode() bool - - // IsInternal returns true for unexpected errors occurring in the - // securecookie implementation. - IsInternal() bool - - // Cause, if it returns a non-nil value, indicates that this error was - // propagated from some underlying library. If this method returns nil, - // this error was raised directly by this library. - // - // Cause is provided principally for debugging/logging purposes; it is - // rare that application logic should perform meaningfully different - // logic based on Cause. See, for example, the caveats described on - // (MultiError).Cause(). - Cause() error -} - -// errorType is a bitmask giving the error type(s) of an cookieError value. -type errorType int - -const ( - usageError = errorType(1 << iota) - decodeError - internalError -) - -type cookieError struct { - typ errorType - msg string - cause error -} - -func (e cookieError) IsUsage() bool { return (e.typ & usageError) != 0 } -func (e cookieError) IsDecode() bool { return (e.typ & decodeError) != 0 } -func (e cookieError) IsInternal() bool { return (e.typ & internalError) != 0 } - -func (e cookieError) Cause() error { return e.cause } - -func (e cookieError) Error() string { - parts := []string{"securecookie: "} - if e.msg == "" { - parts = append(parts, "error") - } else { - parts = append(parts, e.msg) - } - if c := e.Cause(); c != nil { - parts = append(parts, " - caused by: ", c.Error()) - } - return strings.Join(parts, "") -} - -var ( - errGeneratingIV = cookieError{typ: internalError, msg: "failed to generate random iv"} - - errNoCodecs = cookieError{typ: usageError, msg: "no codecs provided"} - errHashKeyNotSet = cookieError{typ: usageError, msg: "hash key is not set"} - errBlockKeyNotSet = cookieError{typ: usageError, msg: "block key is not set"} - errEncodedValueTooLong = cookieError{typ: usageError, msg: "the value is too long"} - - errValueToDecodeTooLong = cookieError{typ: decodeError, msg: "the value is too long"} - errTimestampInvalid = cookieError{typ: decodeError, msg: "invalid timestamp"} - errTimestampTooNew = cookieError{typ: decodeError, msg: "timestamp is too new"} - errTimestampExpired = cookieError{typ: decodeError, msg: "expired timestamp"} - errDecryptionFailed = cookieError{typ: decodeError, msg: "the value could not be decrypted"} - errValueNotByte = cookieError{typ: decodeError, msg: "value not a []byte."} - - // ErrMacInvalid indicates that cookie decoding failed because the HMAC - // could not be extracted and verified. Direct use of this error - // variable is deprecated; it is public only for legacy compatibility, - // and may be privatized in the future, as it is rarely useful to - // distinguish between this error and other Error implementations. - ErrMacInvalid = cookieError{typ: decodeError, msg: "the value is not valid"} -) - -// Codec defines an interface to encode and decode cookie values. -type Codec interface { - Encode(name string, value interface{}) (string, error) - Decode(name, value string, dst interface{}) error -} - -// New returns a new SecureCookie. -// -// hashKey is required, used to authenticate values using HMAC. Create it using -// GenerateRandomKey(). It is recommended to use a key with 32 or 64 bytes. -// -// blockKey is optional, used to encrypt values. Create it using -// GenerateRandomKey(). The key length must correspond to the block size -// of the encryption algorithm. For AES, used by default, valid lengths are -// 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. -// The default encoder used for cookie serialization is encoding/gob. -// -// Note that keys created using GenerateRandomKey() are not automatically -// persisted. New keys will be created when the application is restarted, and -// previously issued cookies will not be able to be decoded. -func New(hashKey, blockKey []byte) *SecureCookie { - s := &SecureCookie{ - hashKey: hashKey, - blockKey: blockKey, - hashFunc: sha256.New, - maxAge: 86400 * 30, - maxLength: 4096, - sz: GobEncoder{}, - } - if hashKey == nil { - s.err = errHashKeyNotSet - } - if blockKey != nil { - s.BlockFunc(aes.NewCipher) - } - return s -} - -// SecureCookie encodes and decodes authenticated and optionally encrypted -// cookie values. -type SecureCookie struct { - hashKey []byte - hashFunc func() hash.Hash - blockKey []byte - block cipher.Block - maxLength int - maxAge int64 - minAge int64 - err error - sz Serializer - // For testing purposes, the function that returns the current timestamp. - // If not set, it will use time.Now().UTC().Unix(). - timeFunc func() int64 -} - -// Serializer provides an interface for providing custom serializers for cookie -// values. -type Serializer interface { - Serialize(src interface{}) ([]byte, error) - Deserialize(src []byte, dst interface{}) error -} - -// GobEncoder encodes cookie values using encoding/gob. This is the simplest -// encoder and can handle complex types via gob.Register. -type GobEncoder struct{} - -// JSONEncoder encodes cookie values using encoding/json. Users who wish to -// encode complex types need to satisfy the json.Marshaller and -// json.Unmarshaller interfaces. -type JSONEncoder struct{} - -// NopEncoder does not encode cookie values, and instead simply accepts a []byte -// (as an interface{}) and returns a []byte. This is particularly useful when -// you encoding an object upstream and do not wish to re-encode it. -type NopEncoder struct{} - -// MaxLength restricts the maximum length, in bytes, for the cookie value. -// -// Default is 4096, which is the maximum value accepted by Internet Explorer. -func (s *SecureCookie) MaxLength(value int) *SecureCookie { - s.maxLength = value - return s -} - -// MaxAge restricts the maximum age, in seconds, for the cookie value. -// -// Default is 86400 * 30. Set it to 0 for no restriction. -func (s *SecureCookie) MaxAge(value int) *SecureCookie { - s.maxAge = int64(value) - return s -} - -// MinAge restricts the minimum age, in seconds, for the cookie value. -// -// Default is 0 (no restriction). -func (s *SecureCookie) MinAge(value int) *SecureCookie { - s.minAge = int64(value) - return s -} - -// HashFunc sets the hash function used to create HMAC. -// -// Default is crypto/sha256.New. -func (s *SecureCookie) HashFunc(f func() hash.Hash) *SecureCookie { - s.hashFunc = f - return s -} - -// BlockFunc sets the encryption function used to create a cipher.Block. -// -// Default is crypto/aes.New. -func (s *SecureCookie) BlockFunc(f func([]byte) (cipher.Block, error)) *SecureCookie { - if s.blockKey == nil { - s.err = errBlockKeyNotSet - } else if block, err := f(s.blockKey); err == nil { - s.block = block - } else { - s.err = cookieError{cause: err, typ: usageError} - } - return s -} - -// Encoding sets the encoding/serialization method for cookies. -// -// Default is encoding/gob. To encode special structures using encoding/gob, -// they must be registered first using gob.Register(). -func (s *SecureCookie) SetSerializer(sz Serializer) *SecureCookie { - s.sz = sz - - return s -} - -// Encode encodes a cookie value. -// -// It serializes, optionally encrypts, signs with a message authentication code, -// and finally encodes the value. -// -// The name argument is the cookie name. It is stored with the encoded value. -// The value argument is the value to be encoded. It can be any value that can -// be encoded using the currently selected serializer; see SetSerializer(). -// -// It is the client's responsibility to ensure that value, when encoded using -// the current serialization/encryption settings on s and then base64-encoded, -// is shorter than the maximum permissible length. -func (s *SecureCookie) Encode(name string, value interface{}) (string, error) { - if s.err != nil { - return "", s.err - } - if s.hashKey == nil { - s.err = errHashKeyNotSet - return "", s.err - } - var err error - var b []byte - // 1. Serialize. - if b, err = s.sz.Serialize(value); err != nil { - return "", cookieError{cause: err, typ: usageError} - } - // 2. Encrypt (optional). - if s.block != nil { - if b, err = encrypt(s.block, b); err != nil { - return "", cookieError{cause: err, typ: usageError} - } - } - b = encode(b) - // 3. Create MAC for "name|date|value". Extra pipe to be used later. - b = []byte(fmt.Sprintf("%s|%d|%s|", name, s.timestamp(), b)) - mac := createMac(hmac.New(s.hashFunc, s.hashKey), b[:len(b)-1]) - // Append mac, remove name. - b = append(b, mac...)[len(name)+1:] - // 4. Encode to base64. - b = encode(b) - // 5. Check length. - if s.maxLength != 0 && len(b) > s.maxLength { - return "", errEncodedValueTooLong - } - // Done. - return string(b), nil -} - -// Decode decodes a cookie value. -// -// It decodes, verifies a message authentication code, optionally decrypts and -// finally deserializes the value. -// -// The name argument is the cookie name. It must be the same name used when -// it was stored. The value argument is the encoded cookie value. The dst -// argument is where the cookie will be decoded. It must be a pointer. -func (s *SecureCookie) Decode(name, value string, dst interface{}) error { - if s.err != nil { - return s.err - } - if s.hashKey == nil { - s.err = errHashKeyNotSet - return s.err - } - // 1. Check length. - if s.maxLength != 0 && len(value) > s.maxLength { - return errValueToDecodeTooLong - } - // 2. Decode from base64. - b, err := decode([]byte(value)) - if err != nil { - return err - } - // 3. Verify MAC. Value is "date|value|mac". - parts := bytes.SplitN(b, []byte("|"), 3) - if len(parts) != 3 { - return ErrMacInvalid - } - h := hmac.New(s.hashFunc, s.hashKey) - b = append([]byte(name+"|"), b[:len(b)-len(parts[2])-1]...) - if err = verifyMac(h, b, parts[2]); err != nil { - return err - } - // 4. Verify date ranges. - var t1 int64 - if t1, err = strconv.ParseInt(string(parts[0]), 10, 64); err != nil { - return errTimestampInvalid - } - t2 := s.timestamp() - if s.minAge != 0 && t1 > t2-s.minAge { - return errTimestampTooNew - } - if s.maxAge != 0 && t1 < t2-s.maxAge { - return errTimestampExpired - } - // 5. Decrypt (optional). - b, err = decode(parts[1]) - if err != nil { - return err - } - if s.block != nil { - if b, err = decrypt(s.block, b); err != nil { - return err - } - } - // 6. Deserialize. - if err = s.sz.Deserialize(b, dst); err != nil { - return cookieError{cause: err, typ: decodeError} - } - // Done. - return nil -} - -// timestamp returns the current timestamp, in seconds. -// -// For testing purposes, the function that generates the timestamp can be -// overridden. If not set, it will return time.Now().UTC().Unix(). -func (s *SecureCookie) timestamp() int64 { - if s.timeFunc == nil { - return time.Now().UTC().Unix() - } - return s.timeFunc() -} - -// Authentication ------------------------------------------------------------- - -// createMac creates a message authentication code (MAC). -func createMac(h hash.Hash, value []byte) []byte { - h.Write(value) - return h.Sum(nil) -} - -// verifyMac verifies that a message authentication code (MAC) is valid. -func verifyMac(h hash.Hash, value []byte, mac []byte) error { - mac2 := createMac(h, value) - // Check that both MACs are of equal length, as subtle.ConstantTimeCompare - // does not do this prior to Go 1.4. - if len(mac) == len(mac2) && subtle.ConstantTimeCompare(mac, mac2) == 1 { - return nil - } - return ErrMacInvalid -} - -// Encryption ----------------------------------------------------------------- - -// encrypt encrypts a value using the given block in counter mode. -// -// A random initialization vector (http://goo.gl/zF67k) with the length of the -// block size is prepended to the resulting ciphertext. -func encrypt(block cipher.Block, value []byte) ([]byte, error) { - iv := GenerateRandomKey(block.BlockSize()) - if iv == nil { - return nil, errGeneratingIV - } - // Encrypt it. - stream := cipher.NewCTR(block, iv) - stream.XORKeyStream(value, value) - // Return iv + ciphertext. - return append(iv, value...), nil -} - -// decrypt decrypts a value using the given block in counter mode. -// -// The value to be decrypted must be prepended by a initialization vector -// (http://goo.gl/zF67k) with the length of the block size. -func decrypt(block cipher.Block, value []byte) ([]byte, error) { - size := block.BlockSize() - if len(value) > size { - // Extract iv. - iv := value[:size] - // Extract ciphertext. - value = value[size:] - // Decrypt it. - stream := cipher.NewCTR(block, iv) - stream.XORKeyStream(value, value) - return value, nil - } - return nil, errDecryptionFailed -} - -// Serialization -------------------------------------------------------------- - -// Serialize encodes a value using gob. -func (e GobEncoder) Serialize(src interface{}) ([]byte, error) { - buf := new(bytes.Buffer) - enc := gob.NewEncoder(buf) - if err := enc.Encode(src); err != nil { - return nil, cookieError{cause: err, typ: usageError} - } - return buf.Bytes(), nil -} - -// Deserialize decodes a value using gob. -func (e GobEncoder) Deserialize(src []byte, dst interface{}) error { - dec := gob.NewDecoder(bytes.NewBuffer(src)) - if err := dec.Decode(dst); err != nil { - return cookieError{cause: err, typ: decodeError} - } - return nil -} - -// Serialize encodes a value using encoding/json. -func (e JSONEncoder) Serialize(src interface{}) ([]byte, error) { - buf := new(bytes.Buffer) - enc := json.NewEncoder(buf) - if err := enc.Encode(src); err != nil { - return nil, cookieError{cause: err, typ: usageError} - } - return buf.Bytes(), nil -} - -// Deserialize decodes a value using encoding/json. -func (e JSONEncoder) Deserialize(src []byte, dst interface{}) error { - dec := json.NewDecoder(bytes.NewReader(src)) - if err := dec.Decode(dst); err != nil { - return cookieError{cause: err, typ: decodeError} - } - return nil -} - -// Serialize passes a []byte through as-is. -func (e NopEncoder) Serialize(src interface{}) ([]byte, error) { - if b, ok := src.([]byte); ok { - return b, nil - } - - return nil, errValueNotByte -} - -// Deserialize passes a []byte through as-is. -func (e NopEncoder) Deserialize(src []byte, dst interface{}) error { - if _, ok := dst.([]byte); ok { - dst = src - return nil - } - - return errValueNotByte -} - -// Encoding ------------------------------------------------------------------- - -// encode encodes a value using base64. -func encode(value []byte) []byte { - encoded := make([]byte, base64.URLEncoding.EncodedLen(len(value))) - base64.URLEncoding.Encode(encoded, value) - return encoded -} - -// decode decodes a cookie using base64. -func decode(value []byte) ([]byte, error) { - decoded := make([]byte, base64.URLEncoding.DecodedLen(len(value))) - b, err := base64.URLEncoding.Decode(decoded, value) - if err != nil { - return nil, cookieError{cause: err, typ: decodeError, msg: "base64 decode failed"} - } - return decoded[:b], nil -} - -// Helpers -------------------------------------------------------------------- - -// GenerateRandomKey creates a random key with the given length in bytes. -// On failure, returns nil. -// -// Callers should explicitly check for the possibility of a nil return, treat -// it as a failure of the system random number generator, and not continue. -func GenerateRandomKey(length int) []byte { - k := make([]byte, length) - if _, err := io.ReadFull(rand.Reader, k); err != nil { - return nil - } - return k -} - -// CodecsFromPairs returns a slice of SecureCookie instances. -// -// It is a convenience function to create a list of codecs for key rotation. Note -// that the generated Codecs will have the default options applied: callers -// should iterate over each Codec and type-assert the underlying *SecureCookie to -// change these. -// -// Example: -// -// codecs := securecookie.CodecsFromPairs( -// []byte("new-hash-key"), -// []byte("new-block-key"), -// []byte("old-hash-key"), -// []byte("old-block-key"), -// ) -// -// // Modify each instance. -// for _, s := range codecs { -// if cookie, ok := s.(*securecookie.SecureCookie); ok { -// cookie.MaxAge(86400 * 7) -// cookie.SetSerializer(securecookie.JSONEncoder{}) -// cookie.HashFunc(sha512.New512_256) -// } -// } -// -func CodecsFromPairs(keyPairs ...[]byte) []Codec { - codecs := make([]Codec, len(keyPairs)/2+len(keyPairs)%2) - for i := 0; i < len(keyPairs); i += 2 { - var blockKey []byte - if i+1 < len(keyPairs) { - blockKey = keyPairs[i+1] - } - codecs[i/2] = New(keyPairs[i], blockKey) - } - return codecs -} - -// EncodeMulti encodes a cookie value using a group of codecs. -// -// The codecs are tried in order. Multiple codecs are accepted to allow -// key rotation. -// -// On error, may return a MultiError. -func EncodeMulti(name string, value interface{}, codecs ...Codec) (string, error) { - if len(codecs) == 0 { - return "", errNoCodecs - } - - var errors MultiError - for _, codec := range codecs { - encoded, err := codec.Encode(name, value) - if err == nil { - return encoded, nil - } - errors = append(errors, err) - } - return "", errors -} - -// DecodeMulti decodes a cookie value using a group of codecs. -// -// The codecs are tried in order. Multiple codecs are accepted to allow -// key rotation. -// -// On error, may return a MultiError. -func DecodeMulti(name string, value string, dst interface{}, codecs ...Codec) error { - if len(codecs) == 0 { - return errNoCodecs - } - - var errors MultiError - for _, codec := range codecs { - err := codec.Decode(name, value, dst) - if err == nil { - return nil - } - errors = append(errors, err) - } - return errors -} - -// MultiError groups multiple errors. -type MultiError []error - -func (m MultiError) IsUsage() bool { return m.any(func(e Error) bool { return e.IsUsage() }) } -func (m MultiError) IsDecode() bool { return m.any(func(e Error) bool { return e.IsDecode() }) } -func (m MultiError) IsInternal() bool { return m.any(func(e Error) bool { return e.IsInternal() }) } - -// Cause returns nil for MultiError; there is no unique underlying cause in the -// general case. -// -// Note: we could conceivably return a non-nil Cause only when there is exactly -// one child error with a Cause. However, it would be brittle for client code -// to rely on the arity of causes inside a MultiError, so we have opted not to -// provide this functionality. Clients which really wish to access the Causes -// of the underlying errors are free to iterate through the errors themselves. -func (m MultiError) Cause() error { return nil } - -func (m MultiError) Error() string { - s, n := "", 0 - for _, e := range m { - if e != nil { - if n == 0 { - s = e.Error() - } - n++ - } - } - switch n { - case 0: - return "(0 errors)" - case 1: - return s - case 2: - return s + " (and 1 other error)" - } - return fmt.Sprintf("%s (and %d other errors)", s, n-1) -} - -// any returns true if any element of m is an Error for which pred returns true. -func (m MultiError) any(pred func(Error) bool) bool { - for _, e := range m { - if ourErr, ok := e.(Error); ok && pred(ourErr) { - return true - } - } - return false -} diff --git a/vendor/github.com/gorilla/securecookie/securecookie_test.go b/vendor/github.com/gorilla/securecookie/securecookie_test.go deleted file mode 100644 index 33ce4fc..0000000 --- a/vendor/github.com/gorilla/securecookie/securecookie_test.go +++ /dev/null @@ -1,274 +0,0 @@ -// Copyright 2012 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package securecookie - -import ( - "crypto/aes" - "crypto/hmac" - "crypto/sha256" - "encoding/base64" - "fmt" - "reflect" - "strings" - "testing" -) - -// Asserts that cookieError and MultiError are Error implementations. -var _ Error = cookieError{} -var _ Error = MultiError{} - -var testCookies = []interface{}{ - map[string]string{"foo": "bar"}, - map[string]string{"baz": "ding"}, -} - -var testStrings = []string{"foo", "bar", "baz"} - -func TestSecureCookie(t *testing.T) { - // TODO test too old / too new timestamps - s1 := New([]byte("12345"), []byte("1234567890123456")) - s2 := New([]byte("54321"), []byte("6543210987654321")) - value := map[string]interface{}{ - "foo": "bar", - "baz": 128, - } - - for i := 0; i < 50; i++ { - // Running this multiple times to check if any special character - // breaks encoding/decoding. - encoded, err1 := s1.Encode("sid", value) - if err1 != nil { - t.Error(err1) - continue - } - dst := make(map[string]interface{}) - err2 := s1.Decode("sid", encoded, &dst) - if err2 != nil { - t.Fatalf("%v: %v", err2, encoded) - } - if !reflect.DeepEqual(dst, value) { - t.Fatalf("Expected %v, got %v.", value, dst) - } - dst2 := make(map[string]interface{}) - err3 := s2.Decode("sid", encoded, &dst2) - if err3 == nil { - t.Fatalf("Expected failure decoding.") - } - err4, ok := err3.(Error) - if !ok { - t.Fatalf("Expected error to implement Error, got: %#v", err3) - } - if !err4.IsDecode() { - t.Fatalf("Expected DecodeError, got: %#v", err4) - } - - // Test other error type flags. - if err4.IsUsage() { - t.Fatalf("Expected IsUsage() == false, got: %#v", err4) - } - if err4.IsInternal() { - t.Fatalf("Expected IsInternal() == false, got: %#v", err4) - } - } -} - -func TestSecureCookieNilKey(t *testing.T) { - s1 := New(nil, nil) - value := map[string]interface{}{ - "foo": "bar", - "baz": 128, - } - _, err := s1.Encode("sid", value) - if err != errHashKeyNotSet { - t.Fatal("Wrong error returned:", err) - } -} - -func TestDecodeInvalid(t *testing.T) { - // List of invalid cookies, which must not be accepted, base64-decoded - // (they will be encoded before passing to Decode). - invalidCookies := []string{ - "", - " ", - "\n", - "||", - "|||", - "cookie", - } - s := New([]byte("12345"), nil) - var dst string - for i, v := range invalidCookies { - for _, enc := range []*base64.Encoding{ - base64.StdEncoding, - base64.URLEncoding, - } { - err := s.Decode("name", enc.EncodeToString([]byte(v)), &dst) - if err == nil { - t.Fatalf("%d: expected failure decoding", i) - } - err2, ok := err.(Error) - if !ok || !err2.IsDecode() { - t.Fatalf("%d: Expected IsDecode(), got: %#v", i, err) - } - } - } -} - -func TestAuthentication(t *testing.T) { - hash := hmac.New(sha256.New, []byte("secret-key")) - for _, value := range testStrings { - hash.Reset() - signed := createMac(hash, []byte(value)) - hash.Reset() - err := verifyMac(hash, []byte(value), signed) - if err != nil { - t.Error(err) - } - } -} - -func TestEncryption(t *testing.T) { - block, err := aes.NewCipher([]byte("1234567890123456")) - if err != nil { - t.Fatalf("Block could not be created") - } - var encrypted, decrypted []byte - for _, value := range testStrings { - if encrypted, err = encrypt(block, []byte(value)); err != nil { - t.Error(err) - } else { - if decrypted, err = decrypt(block, encrypted); err != nil { - t.Error(err) - } - if string(decrypted) != value { - t.Errorf("Expected %v, got %v.", value, string(decrypted)) - } - } - } -} - -func TestGobSerialization(t *testing.T) { - var ( - sz GobEncoder - serialized []byte - deserialized map[string]string - err error - ) - for _, value := range testCookies { - if serialized, err = sz.Serialize(value); err != nil { - t.Error(err) - } else { - deserialized = make(map[string]string) - if err = sz.Deserialize(serialized, &deserialized); err != nil { - t.Error(err) - } - if fmt.Sprintf("%v", deserialized) != fmt.Sprintf("%v", value) { - t.Errorf("Expected %v, got %v.", value, deserialized) - } - } - } -} - -func TestJSONSerialization(t *testing.T) { - var ( - sz JSONEncoder - serialized []byte - deserialized map[string]string - err error - ) - for _, value := range testCookies { - if serialized, err = sz.Serialize(value); err != nil { - t.Error(err) - } else { - deserialized = make(map[string]string) - if err = sz.Deserialize(serialized, &deserialized); err != nil { - t.Error(err) - } - if fmt.Sprintf("%v", deserialized) != fmt.Sprintf("%v", value) { - t.Errorf("Expected %v, got %v.", value, deserialized) - } - } - } -} - -func TestEncoding(t *testing.T) { - for _, value := range testStrings { - encoded := encode([]byte(value)) - decoded, err := decode(encoded) - if err != nil { - t.Error(err) - } else if string(decoded) != value { - t.Errorf("Expected %v, got %s.", value, string(decoded)) - } - } -} - -func TestMultiError(t *testing.T) { - s1, s2 := New(nil, nil), New(nil, nil) - _, err := EncodeMulti("sid", "value", s1, s2) - if len(err.(MultiError)) != 2 { - t.Errorf("Expected 2 errors, got %s.", err) - } else { - if strings.Index(err.Error(), "hash key is not set") == -1 { - t.Errorf("Expected missing hash key error, got %s.", err.Error()) - } - ourErr, ok := err.(Error) - if !ok || !ourErr.IsUsage() { - t.Fatalf("Expected error to be a usage error; got %#v", err) - } - if ourErr.IsDecode() { - t.Errorf("Expected error NOT to be a decode error; got %#v", ourErr) - } - if ourErr.IsInternal() { - t.Errorf("Expected error NOT to be an internal error; got %#v", ourErr) - } - } -} - -func TestMultiNoCodecs(t *testing.T) { - _, err := EncodeMulti("foo", "bar") - if err != errNoCodecs { - t.Errorf("EncodeMulti: bad value for error, got: %v", err) - } - - var dst []byte - err = DecodeMulti("foo", "bar", &dst) - if err != errNoCodecs { - t.Errorf("DecodeMulti: bad value for error, got: %v", err) - } -} - -func TestMissingKey(t *testing.T) { - s1 := New(nil, nil) - - var dst []byte - err := s1.Decode("sid", "value", &dst) - if err != errHashKeyNotSet { - t.Fatalf("Expected %#v, got %#v", errHashKeyNotSet, err) - } - if err2, ok := err.(Error); !ok || !err2.IsUsage() { - t.Errorf("Expected missing hash key to be IsUsage(); was %#v", err) - } -} - -// ---------------------------------------------------------------------------- - -type FooBar struct { - Foo int - Bar string -} - -func TestCustomType(t *testing.T) { - s1 := New([]byte("12345"), []byte("1234567890123456")) - // Type is not registered in gob. (!!!) - src := &FooBar{42, "bar"} - encoded, _ := s1.Encode("sid", src) - - dst := &FooBar{} - _ = s1.Decode("sid", encoded, dst) - if dst.Foo != 42 || dst.Bar != "bar" { - t.Fatalf("Expected %#v, got %#v", src, dst) - } -} diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore deleted file mode 100644 index daf913b..0000000 --- a/vendor/github.com/pkg/errors/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# 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 -*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml deleted file mode 100644 index 588ceca..0000000 --- a/vendor/github.com/pkg/errors/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: go -go_import_path: github.com/pkg/errors -go: - - 1.4.3 - - 1.5.4 - - 1.6.2 - - 1.7.1 - - tip - -script: - - go test -v ./... diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE deleted file mode 100644 index 835ba3e..0000000 --- a/vendor/github.com/pkg/errors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2015, Dave Cheney -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* 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. - -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. diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 273db3c..0000000 --- a/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. - -## Adding context to an error - -The errors.Wrap function returns a new error that adds context to the original error. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## Retrieving the cause of an error - -Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Contributing - -We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. - -Before proposing a change, please discuss your change by raising an issue. - -## Licence - -BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932ead..0000000 --- a/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/vendor/github.com/pkg/errors/bench_test.go b/vendor/github.com/pkg/errors/bench_test.go deleted file mode 100644 index 0416a3c..0000000 --- a/vendor/github.com/pkg/errors/bench_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// +build go1.7 - -package errors - -import ( - "fmt" - "testing" - - stderrors "errors" -) - -func noErrors(at, depth int) error { - if at >= depth { - return stderrors.New("no error") - } - return noErrors(at+1, depth) -} -func yesErrors(at, depth int) error { - if at >= depth { - return New("ye error") - } - return yesErrors(at+1, depth) -} - -func BenchmarkErrors(b *testing.B) { - var toperr error - type run struct { - stack int - std bool - } - runs := []run{ - {10, false}, - {10, true}, - {100, false}, - {100, true}, - {1000, false}, - {1000, true}, - } - for _, r := range runs { - part := "pkg/errors" - if r.std { - part = "errors" - } - name := fmt.Sprintf("%s-stack-%d", part, r.stack) - b.Run(name, func(b *testing.B) { - var err error - f := yesErrors - if r.std { - f = noErrors - } - b.ReportAllocs() - for i := 0; i < b.N; i++ { - err = f(0, r.stack) - } - b.StopTimer() - toperr = err - }) - } -} diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go deleted file mode 100644 index 842ee80..0000000 --- a/vendor/github.com/pkg/errors/errors.go +++ /dev/null @@ -1,269 +0,0 @@ -// Package errors provides simple error handling primitives. -// -// The traditional error handling idiom in Go is roughly akin to -// -// if err != nil { -// return err -// } -// -// which applied recursively up the call stack results in error reports -// without context or debugging information. The errors package allows -// programmers to add context to the failure path in their code in a way -// that does not destroy the original value of the error. -// -// Adding context to an error -// -// The errors.Wrap function returns a new error that adds context to the -// original error by recording a stack trace at the point Wrap is called, -// and the supplied message. For example -// -// _, err := ioutil.ReadAll(r) -// if err != nil { -// return errors.Wrap(err, "read failed") -// } -// -// If additional control is required the errors.WithStack and errors.WithMessage -// functions destructure errors.Wrap into its component operations of annotating -// an error with a stack trace and an a message, respectively. -// -// Retrieving the cause of an error -// -// Using errors.Wrap constructs a stack of errors, adding context to the -// preceding error. Depending on the nature of the error it may be necessary -// to reverse the operation of errors.Wrap to retrieve the original error -// for inspection. Any error value which implements this interface -// -// type causer interface { -// Cause() error -// } -// -// can be inspected by errors.Cause. errors.Cause will recursively retrieve -// the topmost error which does not implement causer, which is assumed to be -// the original cause. For example: -// -// switch err := errors.Cause(err).(type) { -// case *MyError: -// // handle specifically -// default: -// // unknown error -// } -// -// causer interface is not exported by this package, but is considered a part -// of stable public API. -// -// Formatted printing of errors -// -// All error values returned from this package implement fmt.Formatter and can -// be formatted by the fmt package. The following verbs are supported -// -// %s print the error. If the error has a Cause it will be -// printed recursively -// %v see %s -// %+v extended format. Each Frame of the error's StackTrace will -// be printed in detail. -// -// Retrieving the stack trace of an error or wrapper -// -// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are -// invoked. This information can be retrieved with the following interface. -// -// type stackTracer interface { -// StackTrace() errors.StackTrace -// } -// -// Where errors.StackTrace is defined as -// -// type StackTrace []Frame -// -// The Frame type represents a call site in the stack trace. Frame supports -// the fmt.Formatter interface that can be used for printing information about -// the stack trace of this error. For example: -// -// if err, ok := err.(stackTracer); ok { -// for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d", f) -// } -// } -// -// stackTracer interface is not exported by this package, but is considered a part -// of stable public API. -// -// See the documentation for Frame.Format for more details. -package errors - -import ( - "fmt" - "io" -) - -// New returns an error with the supplied message. -// New also records the stack trace at the point it was called. -func New(message string) error { - return &fundamental{ - msg: message, - stack: callers(), - } -} - -// Errorf formats according to a format specifier and returns the string -// as a value that satisfies error. -// Errorf also records the stack trace at the point it was called. -func Errorf(format string, args ...interface{}) error { - return &fundamental{ - msg: fmt.Sprintf(format, args...), - stack: callers(), - } -} - -// fundamental is an error that has a message and a stack, but no caller. -type fundamental struct { - msg string - *stack -} - -func (f *fundamental) Error() string { return f.msg } - -func (f *fundamental) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} - -// WithStack annotates err with a stack trace at the point WithStack was called. -// If err is nil, WithStack returns nil. -func WithStack(err error) error { - if err == nil { - return nil - } - return &withStack{ - err, - callers(), - } -} - -type withStack struct { - error - *stack -} - -func (w *withStack) Cause() error { return w.error } - -func (w *withStack) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v", w.Cause()) - w.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, w.Error()) - case 'q': - fmt.Fprintf(s, "%q", w.Error()) - } -} - -// Wrap returns an error annotating err with a stack trace -// at the point Wrap is called, and the supplied message. -// If err is nil, Wrap returns nil. -func Wrap(err error, message string) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: message, - } - return &withStack{ - err, - callers(), - } -} - -// Wrapf returns an error annotating err with a stack trace -// at the point Wrapf is call, and the format specifier. -// If err is nil, Wrapf returns nil. -func Wrapf(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } - return &withStack{ - err, - callers(), - } -} - -// WithMessage annotates err with a new message. -// If err is nil, WithMessage returns nil. -func WithMessage(err error, message string) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: message, - } -} - -type withMessage struct { - cause error - msg string -} - -func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } -func (w *withMessage) Cause() error { return w.cause } - -func (w *withMessage) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v\n", w.Cause()) - io.WriteString(s, w.msg) - return - } - fallthrough - case 's', 'q': - io.WriteString(s, w.Error()) - } -} - -// Cause returns the underlying cause of the error, if possible. -// An error value has a cause if it implements the following -// interface: -// -// type causer interface { -// Cause() error -// } -// -// If the error does not implement Cause, the original error will -// be returned. If the error is nil, nil will be returned without further -// investigation. -func Cause(err error) error { - type causer interface { - Cause() error - } - - for err != nil { - cause, ok := err.(causer) - if !ok { - break - } - err = cause.Cause() - } - return err -} diff --git a/vendor/github.com/pkg/errors/errors_test.go b/vendor/github.com/pkg/errors/errors_test.go deleted file mode 100644 index 1d8c635..0000000 --- a/vendor/github.com/pkg/errors/errors_test.go +++ /dev/null @@ -1,226 +0,0 @@ -package errors - -import ( - "errors" - "fmt" - "io" - "reflect" - "testing" -) - -func TestNew(t *testing.T) { - tests := []struct { - err string - want error - }{ - {"", fmt.Errorf("")}, - {"foo", fmt.Errorf("foo")}, - {"foo", New("foo")}, - {"string with format specifiers: %v", errors.New("string with format specifiers: %v")}, - } - - for _, tt := range tests { - got := New(tt.err) - if got.Error() != tt.want.Error() { - t.Errorf("New.Error(): got: %q, want %q", got, tt.want) - } - } -} - -func TestWrapNil(t *testing.T) { - got := Wrap(nil, "no error") - if got != nil { - t.Errorf("Wrap(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWrap(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {Wrap(io.EOF, "read error"), "client error", "client error: read error: EOF"}, - } - - for _, tt := range tests { - got := Wrap(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("Wrap(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) - } - } -} - -type nilError struct{} - -func (nilError) Error() string { return "nil error" } - -func TestCause(t *testing.T) { - x := New("error") - tests := []struct { - err error - want error - }{{ - // nil error is nil - err: nil, - want: nil, - }, { - // explicit nil error is nil - err: (error)(nil), - want: nil, - }, { - // typed nil is nil - err: (*nilError)(nil), - want: (*nilError)(nil), - }, { - // uncaused error is unaffected - err: io.EOF, - want: io.EOF, - }, { - // caused error returns cause - err: Wrap(io.EOF, "ignored"), - want: io.EOF, - }, { - err: x, // return from errors.New - want: x, - }, { - WithMessage(nil, "whoops"), - nil, - }, { - WithMessage(io.EOF, "whoops"), - io.EOF, - }, { - WithStack(nil), - nil, - }, { - WithStack(io.EOF), - io.EOF, - }} - - for i, tt := range tests { - got := Cause(tt.err) - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want) - } - } -} - -func TestWrapfNil(t *testing.T) { - got := Wrapf(nil, "no error") - if got != nil { - t.Errorf("Wrapf(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWrapf(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"}, - {Wrapf(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"}, - } - - for _, tt := range tests { - got := Wrapf(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) - } - } -} - -func TestErrorf(t *testing.T) { - tests := []struct { - err error - want string - }{ - {Errorf("read error without format specifiers"), "read error without format specifiers"}, - {Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"}, - } - - for _, tt := range tests { - got := tt.err.Error() - if got != tt.want { - t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want) - } - } -} - -func TestWithStackNil(t *testing.T) { - got := WithStack(nil) - if got != nil { - t.Errorf("WithStack(nil): got %#v, expected nil", got) - } -} - -func TestWithStack(t *testing.T) { - tests := []struct { - err error - want string - }{ - {io.EOF, "EOF"}, - {WithStack(io.EOF), "EOF"}, - } - - for _, tt := range tests { - got := WithStack(tt.err).Error() - if got != tt.want { - t.Errorf("WithStack(%v): got: %v, want %v", tt.err, got, tt.want) - } - } -} - -func TestWithMessageNil(t *testing.T) { - got := WithMessage(nil, "no error") - if got != nil { - t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWithMessage(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {WithMessage(io.EOF, "read error"), "client error", "client error: read error: EOF"}, - } - - for _, tt := range tests { - got := WithMessage(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want) - } - } - -} - -// errors.New, etc values are not expected to be compared by value -// but the change in errors#27 made them incomparable. Assert that -// various kinds of errors have a functional equality operator, even -// if the result of that equality is always false. -func TestErrorEquality(t *testing.T) { - vals := []error{ - nil, - io.EOF, - errors.New("EOF"), - New("EOF"), - Errorf("EOF"), - Wrap(io.EOF, "EOF"), - Wrapf(io.EOF, "EOF%d", 2), - WithMessage(nil, "whoops"), - WithMessage(io.EOF, "whoops"), - WithStack(io.EOF), - WithStack(nil), - } - - for i := range vals { - for j := range vals { - _ = vals[i] == vals[j] // mustn't panic - } - } -} diff --git a/vendor/github.com/pkg/errors/example_test.go b/vendor/github.com/pkg/errors/example_test.go deleted file mode 100644 index c1fc13e..0000000 --- a/vendor/github.com/pkg/errors/example_test.go +++ /dev/null @@ -1,205 +0,0 @@ -package errors_test - -import ( - "fmt" - - "github.com/pkg/errors" -) - -func ExampleNew() { - err := errors.New("whoops") - fmt.Println(err) - - // Output: whoops -} - -func ExampleNew_printf() { - err := errors.New("whoops") - fmt.Printf("%+v", err) - - // Example output: - // whoops - // github.com/pkg/errors_test.ExampleNew_printf - // /home/dfc/src/github.com/pkg/errors/example_test.go:17 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 -} - -func ExampleWithMessage() { - cause := errors.New("whoops") - err := errors.WithMessage(cause, "oh noes") - fmt.Println(err) - - // Output: oh noes: whoops -} - -func ExampleWithStack() { - cause := errors.New("whoops") - err := errors.WithStack(cause) - fmt.Println(err) - - // Output: whoops -} - -func ExampleWithStack_printf() { - cause := errors.New("whoops") - err := errors.WithStack(cause) - fmt.Printf("%+v", err) - - // Example Output: - // whoops - // github.com/pkg/errors_test.ExampleWithStack_printf - // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55 - // testing.runExample - // /usr/lib/go/src/testing/example.go:114 - // testing.RunExamples - // /usr/lib/go/src/testing/example.go:38 - // testing.(*M).Run - // /usr/lib/go/src/testing/testing.go:744 - // main.main - // github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /usr/lib/go/src/runtime/proc.go:183 - // runtime.goexit - // /usr/lib/go/src/runtime/asm_amd64.s:2086 - // github.com/pkg/errors_test.ExampleWithStack_printf - // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:56 - // testing.runExample - // /usr/lib/go/src/testing/example.go:114 - // testing.RunExamples - // /usr/lib/go/src/testing/example.go:38 - // testing.(*M).Run - // /usr/lib/go/src/testing/testing.go:744 - // main.main - // github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /usr/lib/go/src/runtime/proc.go:183 - // runtime.goexit - // /usr/lib/go/src/runtime/asm_amd64.s:2086 -} - -func ExampleWrap() { - cause := errors.New("whoops") - err := errors.Wrap(cause, "oh noes") - fmt.Println(err) - - // Output: oh noes: whoops -} - -func fn() error { - e1 := errors.New("error") - e2 := errors.Wrap(e1, "inner") - e3 := errors.Wrap(e2, "middle") - return errors.Wrap(e3, "outer") -} - -func ExampleCause() { - err := fn() - fmt.Println(err) - fmt.Println(errors.Cause(err)) - - // Output: outer: middle: inner: error - // error -} - -func ExampleWrap_extended() { - err := fn() - fmt.Printf("%+v\n", err) - - // Example output: - // error - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:47 - // github.com/pkg/errors_test.ExampleCause_printf - // /home/dfc/src/github.com/pkg/errors/example_test.go:63 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:104 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer -} - -func ExampleWrapf() { - cause := errors.New("whoops") - err := errors.Wrapf(cause, "oh noes #%d", 2) - fmt.Println(err) - - // Output: oh noes #2: whoops -} - -func ExampleErrorf_extended() { - err := errors.Errorf("whoops: %s", "foo") - fmt.Printf("%+v", err) - - // Example output: - // whoops: foo - // github.com/pkg/errors_test.ExampleErrorf - // /home/dfc/src/github.com/pkg/errors/example_test.go:101 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:102 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 -} - -func Example_stackTrace() { - type stackTracer interface { - StackTrace() errors.StackTrace - } - - err, ok := errors.Cause(fn()).(stackTracer) - if !ok { - panic("oops, err does not implement stackTracer") - } - - st := err.StackTrace() - fmt.Printf("%+v", st[0:2]) // top two frames - - // Example output: - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:47 - // github.com/pkg/errors_test.Example_stackTrace - // /home/dfc/src/github.com/pkg/errors/example_test.go:127 -} - -func ExampleCause_printf() { - err := errors.Wrap(func() error { - return func() error { - return errors.Errorf("hello %s", fmt.Sprintf("world")) - }() - }(), "failed") - - fmt.Printf("%v", err) - - // Output: failed: hello world -} diff --git a/vendor/github.com/pkg/errors/format_test.go b/vendor/github.com/pkg/errors/format_test.go deleted file mode 100644 index 15fd7d8..0000000 --- a/vendor/github.com/pkg/errors/format_test.go +++ /dev/null @@ -1,535 +0,0 @@ -package errors - -import ( - "errors" - "fmt" - "io" - "regexp" - "strings" - "testing" -) - -func TestFormatNew(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - New("error"), - "%s", - "error", - }, { - New("error"), - "%v", - "error", - }, { - New("error"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatNew\n" + - "\t.+/github.com/pkg/errors/format_test.go:26", - }, { - New("error"), - "%q", - `"error"`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatErrorf(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Errorf("%s", "error"), - "%s", - "error", - }, { - Errorf("%s", "error"), - "%v", - "error", - }, { - Errorf("%s", "error"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatErrorf\n" + - "\t.+/github.com/pkg/errors/format_test.go:56", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWrap(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Wrap(New("error"), "error2"), - "%s", - "error2: error", - }, { - Wrap(New("error"), "error2"), - "%v", - "error2: error", - }, { - Wrap(New("error"), "error2"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:82", - }, { - Wrap(io.EOF, "error"), - "%s", - "error: EOF", - }, { - Wrap(io.EOF, "error"), - "%v", - "error: EOF", - }, { - Wrap(io.EOF, "error"), - "%+v", - "EOF\n" + - "error\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:96", - }, { - Wrap(Wrap(io.EOF, "error1"), "error2"), - "%+v", - "EOF\n" + - "error1\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:103\n", - }, { - Wrap(New("error with space"), "context"), - "%q", - `"context: error with space"`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWrapf(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Wrapf(io.EOF, "error%d", 2), - "%s", - "error2: EOF", - }, { - Wrapf(io.EOF, "error%d", 2), - "%v", - "error2: EOF", - }, { - Wrapf(io.EOF, "error%d", 2), - "%+v", - "EOF\n" + - "error2\n" + - "github.com/pkg/errors.TestFormatWrapf\n" + - "\t.+/github.com/pkg/errors/format_test.go:134", - }, { - Wrapf(New("error"), "error%d", 2), - "%s", - "error2: error", - }, { - Wrapf(New("error"), "error%d", 2), - "%v", - "error2: error", - }, { - Wrapf(New("error"), "error%d", 2), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatWrapf\n" + - "\t.+/github.com/pkg/errors/format_test.go:149", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWithStack(t *testing.T) { - tests := []struct { - error - format string - want []string - }{{ - WithStack(io.EOF), - "%s", - []string{"EOF"}, - }, { - WithStack(io.EOF), - "%v", - []string{"EOF"}, - }, { - WithStack(io.EOF), - "%+v", - []string{"EOF", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:175"}, - }, { - WithStack(New("error")), - "%s", - []string{"error"}, - }, { - WithStack(New("error")), - "%v", - []string{"error"}, - }, { - WithStack(New("error")), - "%+v", - []string{"error", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:189", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:189"}, - }, { - WithStack(WithStack(io.EOF)), - "%+v", - []string{"EOF", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:197", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:197"}, - }, { - WithStack(WithStack(Wrapf(io.EOF, "message"))), - "%+v", - []string{"EOF", - "message", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205"}, - }, { - WithStack(Errorf("error%d", 1)), - "%+v", - []string{"error1", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:216", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:216"}, - }} - - for i, tt := range tests { - testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) - } -} - -func TestFormatWithMessage(t *testing.T) { - tests := []struct { - error - format string - want []string - }{{ - WithMessage(New("error"), "error2"), - "%s", - []string{"error2: error"}, - }, { - WithMessage(New("error"), "error2"), - "%v", - []string{"error2: error"}, - }, { - WithMessage(New("error"), "error2"), - "%+v", - []string{ - "error", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:244", - "error2"}, - }, { - WithMessage(io.EOF, "addition1"), - "%s", - []string{"addition1: EOF"}, - }, { - WithMessage(io.EOF, "addition1"), - "%v", - []string{"addition1: EOF"}, - }, { - WithMessage(io.EOF, "addition1"), - "%+v", - []string{"EOF", "addition1"}, - }, { - WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), - "%v", - []string{"addition2: addition1: EOF"}, - }, { - WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), - "%+v", - []string{"EOF", "addition1", "addition2"}, - }, { - Wrap(WithMessage(io.EOF, "error1"), "error2"), - "%+v", - []string{"EOF", "error1", "error2", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:272"}, - }, { - WithMessage(Errorf("error%d", 1), "error2"), - "%+v", - []string{"error1", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:278", - "error2"}, - }, { - WithMessage(WithStack(io.EOF), "error"), - "%+v", - []string{ - "EOF", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:285", - "error"}, - }, { - WithMessage(Wrap(WithStack(io.EOF), "inside-error"), "outside-error"), - "%+v", - []string{ - "EOF", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:293", - "inside-error", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:293", - "outside-error"}, - }} - - for i, tt := range tests { - testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) - } -} - -func TestFormatGeneric(t *testing.T) { - starts := []struct { - err error - want []string - }{ - {New("new-error"), []string{ - "new-error", - "github.com/pkg/errors.TestFormatGeneric\n" + - "\t.+/github.com/pkg/errors/format_test.go:315"}, - }, {Errorf("errorf-error"), []string{ - "errorf-error", - "github.com/pkg/errors.TestFormatGeneric\n" + - "\t.+/github.com/pkg/errors/format_test.go:319"}, - }, {errors.New("errors-new-error"), []string{ - "errors-new-error"}, - }, - } - - wrappers := []wrapper{ - { - func(err error) error { return WithMessage(err, "with-message") }, - []string{"with-message"}, - }, { - func(err error) error { return WithStack(err) }, - []string{ - "github.com/pkg/errors.(func·002|TestFormatGeneric.func2)\n\t" + - ".+/github.com/pkg/errors/format_test.go:333", - }, - }, { - func(err error) error { return Wrap(err, "wrap-error") }, - []string{ - "wrap-error", - "github.com/pkg/errors.(func·003|TestFormatGeneric.func3)\n\t" + - ".+/github.com/pkg/errors/format_test.go:339", - }, - }, { - func(err error) error { return Wrapf(err, "wrapf-error%d", 1) }, - []string{ - "wrapf-error1", - "github.com/pkg/errors.(func·004|TestFormatGeneric.func4)\n\t" + - ".+/github.com/pkg/errors/format_test.go:346", - }, - }, - } - - for s := range starts { - err := starts[s].err - want := starts[s].want - testFormatCompleteCompare(t, s, err, "%+v", want, false) - testGenericRecursive(t, err, want, wrappers, 3) - } -} - -func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) { - got := fmt.Sprintf(format, arg) - gotLines := strings.SplitN(got, "\n", -1) - wantLines := strings.SplitN(want, "\n", -1) - - if len(wantLines) > len(gotLines) { - t.Errorf("test %d: wantLines(%d) > gotLines(%d):\n got: %q\nwant: %q", n+1, len(wantLines), len(gotLines), got, want) - return - } - - for i, w := range wantLines { - match, err := regexp.MatchString(w, gotLines[i]) - if err != nil { - t.Fatal(err) - } - if !match { - t.Errorf("test %d: line %d: fmt.Sprintf(%q, err):\n got: %q\nwant: %q", n+1, i+1, format, got, want) - } - } -} - -var stackLineR = regexp.MustCompile(`\.`) - -// parseBlocks parses input into a slice, where: -// - incase entry contains a newline, its a stacktrace -// - incase entry contains no newline, its a solo line. -// -// Detecting stack boundaries only works incase the WithStack-calls are -// to be found on the same line, thats why it is optionally here. -// -// Example use: -// -// for _, e := range blocks { -// if strings.ContainsAny(e, "\n") { -// // Match as stack -// } else { -// // Match as line -// } -// } -// -func parseBlocks(input string, detectStackboundaries bool) ([]string, error) { - var blocks []string - - stack := "" - wasStack := false - lines := map[string]bool{} // already found lines - - for _, l := range strings.Split(input, "\n") { - isStackLine := stackLineR.MatchString(l) - - switch { - case !isStackLine && wasStack: - blocks = append(blocks, stack, l) - stack = "" - lines = map[string]bool{} - case isStackLine: - if wasStack { - // Detecting two stacks after another, possible cause lines match in - // our tests due to WithStack(WithStack(io.EOF)) on same line. - if detectStackboundaries { - if lines[l] { - if len(stack) == 0 { - return nil, errors.New("len of block must not be zero here") - } - - blocks = append(blocks, stack) - stack = l - lines = map[string]bool{l: true} - continue - } - } - - stack = stack + "\n" + l - } else { - stack = l - } - lines[l] = true - case !isStackLine && !wasStack: - blocks = append(blocks, l) - default: - return nil, errors.New("must not happen") - } - - wasStack = isStackLine - } - - // Use up stack - if stack != "" { - blocks = append(blocks, stack) - } - return blocks, nil -} - -func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format string, want []string, detectStackBoundaries bool) { - gotStr := fmt.Sprintf(format, arg) - - got, err := parseBlocks(gotStr, detectStackBoundaries) - if err != nil { - t.Fatal(err) - } - - if len(got) != len(want) { - t.Fatalf("test %d: fmt.Sprintf(%s, err) -> wrong number of blocks: got(%d) want(%d)\n got: %s\nwant: %s\ngotStr: %q", - n+1, format, len(got), len(want), prettyBlocks(got), prettyBlocks(want), gotStr) - } - - for i := range got { - if strings.ContainsAny(want[i], "\n") { - // Match as stack - match, err := regexp.MatchString(want[i], got[i]) - if err != nil { - t.Fatal(err) - } - if !match { - t.Fatalf("test %d: block %d: fmt.Sprintf(%q, err):\ngot:\n%q\nwant:\n%q\nall-got:\n%s\nall-want:\n%s\n", - n+1, i+1, format, got[i], want[i], prettyBlocks(got), prettyBlocks(want)) - } - } else { - // Match as message - if got[i] != want[i] { - t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i]) - } - } - } -} - -type wrapper struct { - wrap func(err error) error - want []string -} - -func prettyBlocks(blocks []string, prefix ...string) string { - var out []string - - for _, b := range blocks { - out = append(out, fmt.Sprintf("%v", b)) - } - - return " " + strings.Join(out, "\n ") -} - -func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, list []wrapper, maxDepth int) { - if len(beforeWant) == 0 { - panic("beforeWant must not be empty") - } - for _, w := range list { - if len(w.want) == 0 { - panic("want must not be empty") - } - - err := w.wrap(beforeErr) - - // Copy required cause append(beforeWant, ..) modified beforeWant subtly. - beforeCopy := make([]string, len(beforeWant)) - copy(beforeCopy, beforeWant) - - beforeWant := beforeCopy - last := len(beforeWant) - 1 - var want []string - - // Merge two stacks behind each other. - if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") { - want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...) - } else { - want = append(beforeWant, w.want...) - } - - testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false) - if maxDepth > 0 { - testGenericRecursive(t, err, want, list, maxDepth-1) - } - } -} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go deleted file mode 100644 index 6b1f289..0000000 --- a/vendor/github.com/pkg/errors/stack.go +++ /dev/null @@ -1,178 +0,0 @@ -package errors - -import ( - "fmt" - "io" - "path" - "runtime" - "strings" -) - -// Frame represents a program counter inside a stack frame. -type Frame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f Frame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f Frame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f Frame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s path of source file relative to the compile time GOPATH -// %+v equivalent to %+s:%d -func (f Frame) Format(s fmt.State, verb rune) { - switch verb { - case 's': - switch { - case s.Flag('+'): - pc := f.pc() - fn := runtime.FuncForPC(pc) - if fn == nil { - io.WriteString(s, "unknown") - } else { - file, _ := fn.FileLine(pc) - fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file) - } - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - fmt.Fprintf(s, "%d", f.line()) - case 'n': - name := runtime.FuncForPC(f.pc()).Name() - io.WriteString(s, funcname(name)) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). -type StackTrace []Frame - -func (st StackTrace) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case s.Flag('+'): - for _, f := range st { - fmt.Fprintf(s, "\n%+v", f) - } - case s.Flag('#'): - fmt.Fprintf(s, "%#v", []Frame(st)) - default: - fmt.Fprintf(s, "%v", []Frame(st)) - } - case 's': - fmt.Fprintf(s, "%s", []Frame(st)) - } -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := Frame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func (s *stack) StackTrace() StackTrace { - f := make([]Frame, len(*s)) - for i := 0; i < len(f); i++ { - f[i] = Frame((*s)[i]) - } - return f -} - -func callers() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// funcname removes the path prefix component of a function's name reported by func.Name(). -func funcname(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] -} - -func trimGOPATH(name, file string) string { - // Here we want to get the source file path relative to the compile time - // GOPATH. As of Go 1.6.x there is no direct way to know the compiled - // GOPATH at runtime, but we can infer the number of path segments in the - // GOPATH. We note that fn.Name() returns the function name qualified by - // the import path, which does not include the GOPATH. Thus we can trim - // segments from the beginning of the file path until the number of path - // separators remaining is one more than the number of path separators in - // the function name. For example, given: - // - // GOPATH /home/user - // file /home/user/src/pkg/sub/file.go - // fn.Name() pkg/sub.Type.Method - // - // We want to produce: - // - // pkg/sub/file.go - // - // From this we can easily see that fn.Name() has one less path separator - // than our desired output. We count separators from the end of the file - // path until it finds two more than in the function name and then move - // one character forward to preserve the initial path segment without a - // leading separator. - const sep = "/" - goal := strings.Count(name, sep) + 2 - i := len(file) - for n := 0; n < goal; n++ { - i = strings.LastIndex(file[:i], sep) - if i == -1 { - // not enough separators found, set i so that the slice expression - // below leaves file unmodified - i = -len(sep) - break - } - } - // get back to 0 or trim the leading separator - file = file[i+len(sep):] - return file -} diff --git a/vendor/github.com/pkg/errors/stack_test.go b/vendor/github.com/pkg/errors/stack_test.go deleted file mode 100644 index 510c27a..0000000 --- a/vendor/github.com/pkg/errors/stack_test.go +++ /dev/null @@ -1,292 +0,0 @@ -package errors - -import ( - "fmt" - "runtime" - "testing" -) - -var initpc, _, _, _ = runtime.Caller(0) - -func TestFrameLine(t *testing.T) { - var tests = []struct { - Frame - want int - }{{ - Frame(initpc), - 9, - }, { - func() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) - }(), - 20, - }, { - func() Frame { - var pc, _, _, _ = runtime.Caller(1) - return Frame(pc) - }(), - 28, - }, { - Frame(0), // invalid PC - 0, - }} - - for _, tt := range tests { - got := tt.Frame.line() - want := tt.want - if want != got { - t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got) - } - } -} - -type X struct{} - -func (x X) val() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) -} - -func (x *X) ptr() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) -} - -func TestFrameFormat(t *testing.T) { - var tests = []struct { - Frame - format string - want string - }{{ - Frame(initpc), - "%s", - "stack_test.go", - }, { - Frame(initpc), - "%+s", - "github.com/pkg/errors.init\n" + - "\t.+/github.com/pkg/errors/stack_test.go", - }, { - Frame(0), - "%s", - "unknown", - }, { - Frame(0), - "%+s", - "unknown", - }, { - Frame(initpc), - "%d", - "9", - }, { - Frame(0), - "%d", - "0", - }, { - Frame(initpc), - "%n", - "init", - }, { - func() Frame { - var x X - return x.ptr() - }(), - "%n", - `\(\*X\).ptr`, - }, { - func() Frame { - var x X - return x.val() - }(), - "%n", - "X.val", - }, { - Frame(0), - "%n", - "", - }, { - Frame(initpc), - "%v", - "stack_test.go:9", - }, { - Frame(initpc), - "%+v", - "github.com/pkg/errors.init\n" + - "\t.+/github.com/pkg/errors/stack_test.go:9", - }, { - Frame(0), - "%v", - "unknown:0", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.Frame, tt.format, tt.want) - } -} - -func TestFuncname(t *testing.T) { - tests := []struct { - name, want string - }{ - {"", ""}, - {"runtime.main", "main"}, - {"github.com/pkg/errors.funcname", "funcname"}, - {"funcname", "funcname"}, - {"io.copyBuffer", "copyBuffer"}, - {"main.(*R).Write", "(*R).Write"}, - } - - for _, tt := range tests { - got := funcname(tt.name) - want := tt.want - if got != want { - t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got) - } - } -} - -func TestTrimGOPATH(t *testing.T) { - var tests = []struct { - Frame - want string - }{{ - Frame(initpc), - "github.com/pkg/errors/stack_test.go", - }} - - for i, tt := range tests { - pc := tt.Frame.pc() - fn := runtime.FuncForPC(pc) - file, _ := fn.FileLine(pc) - got := trimGOPATH(fn.Name(), file) - testFormatRegexp(t, i, got, "%s", tt.want) - } -} - -func TestStackTrace(t *testing.T) { - tests := []struct { - err error - want []string - }{{ - New("ooh"), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:172", - }, - }, { - Wrap(New("ooh"), "ahh"), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:177", // this is the stack of Wrap, not New - }, - }, { - Cause(Wrap(New("ooh"), "ahh")), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:182", // this is the stack of New - }, - }, { - func() error { return New("ooh") }(), []string{ - `github.com/pkg/errors.(func·009|TestStackTrace.func1)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New's caller - }, - }, { - Cause(func() error { - return func() error { - return Errorf("hello %s", fmt.Sprintf("world")) - }() - }()), []string{ - `github.com/pkg/errors.(func·010|TestStackTrace.func2.1)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:196", // this is the stack of Errorf - `github.com/pkg/errors.(func·011|TestStackTrace.func2)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:197", // this is the stack of Errorf's caller - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:198", // this is the stack of Errorf's caller's caller - }, - }} - for i, tt := range tests { - x, ok := tt.err.(interface { - StackTrace() StackTrace - }) - if !ok { - t.Errorf("expected %#v to implement StackTrace() StackTrace", tt.err) - continue - } - st := x.StackTrace() - for j, want := range tt.want { - testFormatRegexp(t, i, st[j], "%+v", want) - } - } -} - -func stackTrace() StackTrace { - const depth = 8 - var pcs [depth]uintptr - n := runtime.Callers(1, pcs[:]) - var st stack = pcs[0:n] - return st.StackTrace() -} - -func TestStackTraceFormat(t *testing.T) { - tests := []struct { - StackTrace - format string - want string - }{{ - nil, - "%s", - `\[\]`, - }, { - nil, - "%v", - `\[\]`, - }, { - nil, - "%+v", - "", - }, { - nil, - "%#v", - `\[\]errors.Frame\(nil\)`, - }, { - make(StackTrace, 0), - "%s", - `\[\]`, - }, { - make(StackTrace, 0), - "%v", - `\[\]`, - }, { - make(StackTrace, 0), - "%+v", - "", - }, { - make(StackTrace, 0), - "%#v", - `\[\]errors.Frame{}`, - }, { - stackTrace()[:2], - "%s", - `\[stack_test.go stack_test.go\]`, - }, { - stackTrace()[:2], - "%v", - `\[stack_test.go:225 stack_test.go:272\]`, - }, { - stackTrace()[:2], - "%+v", - "\n" + - "github.com/pkg/errors.stackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:225\n" + - "github.com/pkg/errors.TestStackTraceFormat\n" + - "\t.+/github.com/pkg/errors/stack_test.go:276", - }, { - stackTrace()[:2], - "%#v", - `\[\]errors.Frame{stack_test.go:225, stack_test.go:284}`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.StackTrace, tt.format, tt.want) - } -} From 05b4a732b984ec326cac085631060968d4706b17 Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Mon, 21 May 2018 23:16:36 -0700 Subject: [PATCH 16/48] [build] Run CI for Go 1.7.x - 1.10.x (#84) --- .travis.yml | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index db5e560..5c814da 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,10 +3,16 @@ sudo: false matrix: include: - - go: 1.3 - - go: 1.4 - - go: 1.5 - - go: 1.6 + - go: "1.x" + env: "LATEST=true" + - go: "1.3.x" + - go: "1.4.x" + - go: "1.5.x" + - go: "1.6.x" + - go: "1.7.x" + - go: "1.8.x" + - go: "1.9.x" + - go: "1.10.x" - go: tip allow_failures: - go: tip @@ -17,5 +23,6 @@ install: script: - go get -t -v ./... - diff -u <(echo -n) <(gofmt -d .) - - go vet $(go list ./... | grep -v /vendor/) + - if [ "${LATEST}" = "true" ]; then go vet ./...; fi - go test -v -race ./... + From 9f56e6eb7c93e0f0bd9c61f92413d90bf7d48490 Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Fri, 8 Jun 2018 02:48:43 +0000 Subject: [PATCH 17/48] Update LICENSE & AUTHORS files --- AUTHORS | 20 ++++++++++++++++++++ LICENSE | 3 +-- 2 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 AUTHORS diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..4e84c37 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,20 @@ +# 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 +田浩浩 +陈东海 diff --git a/LICENSE b/LICENSE index f407b7f..c1eb344 100644 --- a/LICENSE +++ b/LICENSE @@ -1,5 +1,4 @@ -Copyright (c) 2015, Matt Silverlock (matt@eatsleeprepeat.net) All rights -reserved. +Copyright (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: From 10bfafc91ef1c8d20ea9d015720365906b7f3fbd Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Wed, 20 Jun 2018 13:30:27 -0700 Subject: [PATCH 18/48] [docs] Note that developers should check the HTTP method (#91) Fixes #90 --- README.md | 49 +++++++++++++++++++++++++++---------------------- doc.go | 5 ++++- 2 files changed, 31 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 75e8525..6bcca60 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,27 @@ # gorilla/csrf + [![GoDoc](https://godoc.org/github.com/gorilla/csrf?status.svg)](https://godoc.org/github.com/gorilla/csrf) [![Build Status](https://travis-ci.org/gorilla/csrf.svg?branch=master)](https://travis-ci.org/gorilla/csrf) [![Sourcegraph](https://sourcegraph.com/github.com/gorilla/csrf/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/csrf?badge) 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: +protection. It includes: -* The `csrf.Protect` middleware/handler provides CSRF protection on routes +- 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, +- 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` +- ... 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](http://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. +- The [Gorilla](http://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). @@ -28,16 +29,17 @@ gorilla/csrf is also compatible with middleware 'helper' libraries like ## 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 Options](#setting-options) +- [HTML Forms](#html-forms) +- [JavaScript Apps](#javascript-applications) +- [Google App Engine](#google-app-engine) +- [Setting Options](#setting-options) gorilla/csrf is easy to use: add the middleware to your router with the below: @@ -77,7 +79,10 @@ func main() { r := mux.NewRouter() r.HandleFunc("/signup", ShowSignupForm) // All POST requests without a valid token will return HTTP 403 Forbidden. - r.HandleFunc("/signup/post", SubmitSignupForm) + // 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", @@ -207,22 +212,22 @@ added, open an issue. Getting CSRF protection right is important, so here's some background: -* This library generates unique-per-request (masked) tokens as a mitigation +- 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 +- 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 +- 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 +- 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) +- 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 +- 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. diff --git a/doc.go b/doc.go index 3046cdc..503c948 100644 --- a/doc.go +++ b/doc.go @@ -71,7 +71,10 @@ in order to protect malicious POST requests being made: r := mux.NewRouter() r.HandleFunc("/signup", ShowSignupForm) // All POST requests without a valid token will return HTTP 403 Forbidden. - r.HandleFunc("/signup/post", SubmitSignupForm) + // 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", From f903b4ea4d6056635620f6f39e930528b97f9a55 Mon Sep 17 00:00:00 2001 From: Kamil Kisiel Date: Fri, 12 Oct 2018 08:34:37 -0700 Subject: [PATCH 19/48] README.md: Update site URL --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6bcca60..86aae4a 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ protection. It includes: gorilla/csrf is designed to work with any Go web framework, including: -- The [Gorilla](http://www.gorillatoolkit.org/) toolkit +- 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) @@ -120,7 +120,7 @@ This approach is useful if you're using a front-end JavaScript framework like React, Ember or Angular, or are providing a JSON API. We'll also look at applying selective CSRF protection using -[gorilla/mux's](http://www.gorillatoolkit.org/pkg/mux) sub-routers, +[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 From abcfd258958b0f4a4a4eda0f9db1cd132295eadf Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Fri, 7 Dec 2018 09:39:22 -0600 Subject: [PATCH 20/48] Add stalebot config --- .github/stale | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .github/stale diff --git a/.github/stale b/.github/stale new file mode 100644 index 0000000..f5c1622 --- /dev/null +++ b/.github/stale @@ -0,0 +1,11 @@ +daysUntilStale: 60 +daysUntilClose: 7 +# Issues with these labels will never be considered stale +exemptLabels: + - v2 + - needs-review +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 From 472e8526a193a66a6badc56b37fec6732f462658 Mon Sep 17 00:00:00 2001 From: Scott Albertson Date: Fri, 7 Dec 2018 07:49:52 -0800 Subject: [PATCH 21/48] [docs] Add a "Reviewed by Hound" badge (#98) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 86aae4a..ff2d89e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # gorilla/csrf -[![GoDoc](https://godoc.org/github.com/gorilla/csrf?status.svg)](https://godoc.org/github.com/gorilla/csrf) [![Build Status](https://travis-ci.org/gorilla/csrf.svg?branch=master)](https://travis-ci.org/gorilla/csrf) [![Sourcegraph](https://sourcegraph.com/github.com/gorilla/csrf/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/csrf?badge) +[![GoDoc](https://godoc.org/github.com/gorilla/csrf?status.svg)](https://godoc.org/github.com/gorilla/csrf) [![Build Status](https://travis-ci.org/gorilla/csrf.svg?branch=master)](https://travis-ci.org/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) gorilla/csrf is a HTTP middleware library that provides [cross-site request forgery](http://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/) (CSRF) From 40703b8c74f410f241bf24526d4b636e972deeae Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Sat, 8 Dec 2018 13:10:53 -0800 Subject: [PATCH 22/48] Update and rename stale to stale.yml (#102) --- .github/{stale => stale.yml} | 1 + 1 file changed, 1 insertion(+) rename .github/{stale => stale.yml} (94%) diff --git a/.github/stale b/.github/stale.yml similarity index 94% rename from .github/stale rename to .github/stale.yml index f5c1622..de8a678 100644 --- a/.github/stale +++ b/.github/stale.yml @@ -4,6 +4,7 @@ daysUntilClose: 7 exemptLabels: - v2 - needs-review + - work-required staleLabel: stale markComment: > This issue has been automatically marked as stale because it hasn't seen From d1620373958b3d521d88c063d1c9b678e734e9df Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Sun, 9 Dec 2018 16:02:52 -0800 Subject: [PATCH 23/48] [docs] Improve JS header/form instructions (#103) --- README.md | 49 +++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ff2d89e..7265ad2 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,15 @@ body. ### JavaScript Applications This approach is useful if you're using a front-end JavaScript framework like -React, Ember or Angular, or are providing a JSON API. +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, @@ -133,12 +141,13 @@ import ( 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", - csrf.Protect([]byte("32-byte-long-auth-key"))(r)) + http.ListenAndServe(":8000", r) } func GetUser(w http.ResponseWriter, r *http.Request) { @@ -159,11 +168,39 @@ func GetUser(w http.ResponseWriter, r *http.Request) { } ``` +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 +} +``` + ### 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), -which doesn't allow you to hook into the default `http.ServeMux` directly, +(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 @@ -180,6 +217,10 @@ func init() { } ``` +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 Options What about providing your own error handler and changing the HTTP header the From 3719438df5e0d58eee6152cc5f73d2b417d279d4 Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Tue, 25 Jun 2019 18:10:22 -0700 Subject: [PATCH 24/48] [build] Add CircleCI config (#112) * [build] Add CircleCI config * Remove CI jobs for Go 1.6 and below. --- .circleci/config.yml | 66 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 .circleci/config.yml diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..a4cd11e --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,66 @@ +version: 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" From 38c9e4619f0d5d8ff3fb574fc6260901f2495776 Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Tue, 25 Jun 2019 18:18:22 -0700 Subject: [PATCH 25/48] Remove gorilla/context as part of pre-1.7 support (#114) --- .travis.yml | 28 ---------------------------- context_legacy.go | 28 ---------------------------- go.mod | 1 - go.sum | 4 ++++ 4 files changed, 4 insertions(+), 57 deletions(-) delete mode 100644 .travis.yml delete mode 100644 context_legacy.go create mode 100644 go.sum diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 5c814da..0000000 --- a/.travis.yml +++ /dev/null @@ -1,28 +0,0 @@ -language: go -sudo: false - -matrix: - include: - - go: "1.x" - env: "LATEST=true" - - go: "1.3.x" - - go: "1.4.x" - - go: "1.5.x" - - go: "1.6.x" - - go: "1.7.x" - - go: "1.8.x" - - go: "1.9.x" - - go: "1.10.x" - - go: tip - allow_failures: - - go: tip - -install: - - # skip - -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d .) - - if [ "${LATEST}" = "true" ]; then go vet ./...; fi - - go test -v -race ./... - diff --git a/context_legacy.go b/context_legacy.go deleted file mode 100644 index f88c9eb..0000000 --- a/context_legacy.go +++ /dev/null @@ -1,28 +0,0 @@ -// +build !go1.7 - -package csrf - -import ( - "net/http" - - "github.com/gorilla/context" - - "github.com/pkg/errors" -) - -func contextGet(r *http.Request, key string) (interface{}, error) { - if val, ok := context.GetOk(r, key); ok { - return val, nil - } - - return nil, errors.Errorf("no value exists in the context for key %q", key) -} - -func contextSave(r *http.Request, key string, val interface{}) *http.Request { - context.Set(r, key, val) - return r -} - -func contextClear(r *http.Request) { - context.Clear(r) -} diff --git a/go.mod b/go.mod index 2d2ce4d..a5bf9b2 100644 --- a/go.mod +++ b/go.mod @@ -1,7 +1,6 @@ module github.com/gorilla/csrf require ( - github.com/gorilla/context v1.1.1 github.com/gorilla/securecookie v1.1.1 github.com/pkg/errors v0.8.0 ) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..2d11d99 --- /dev/null +++ b/go.sum @@ -0,0 +1,4 @@ +github.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= From 9b0e3acb4f79e4bf9415d6144123987e7b8527cb Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Tue, 25 Jun 2019 18:23:33 -0700 Subject: [PATCH 26/48] Add CircleCI status badge to README (#113) --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7265ad2..6162c21 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ # gorilla/csrf -[![GoDoc](https://godoc.org/github.com/gorilla/csrf?status.svg)](https://godoc.org/github.com/gorilla/csrf) [![Build Status](https://travis-ci.org/gorilla/csrf.svg?branch=master)](https://travis-ci.org/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) +[![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) From 5050f9cc5be66009854ff58f897ea3ee1c9a6b4c Mon Sep 17 00:00:00 2001 From: Fernando Jorge Mota Date: Sat, 20 Jul 2019 17:17:29 -0300 Subject: [PATCH 27/48] Add trusted origins feature (#117) * Add trusted origins feature Closes #116 * Refactor Trusted Origins feature to be more like Django. Instead of accepting []*url.URL, which can cause weird problems, now TrustedOrigins accept []string, which is the list of hosts accepted by the middleware...So the schema doesn't matter anymore and it's more friendly to use. * Add table driven tests for the Trusted Origins feature as requested * Fix documentation of the TrustedOrigins feature * Add a section describing the Trusted Origins feature for Javascript applications on the README * Add more test cases for the table driven tests for the TrustedOrigins feature * Fix documentation of the TrustedOrigins feature so the lint error is fixed --- README.md | 43 +++++++++++++++++++++++++++++++++++ csrf.go | 26 +++++++++++++++------ csrf_test.go | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++ options.go | 15 +++++++++++- 4 files changed, 140 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 6162c21..2129446 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,49 @@ try { } ``` +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 diff --git a/csrf.go b/csrf.go index cc7878f..8f78653 100644 --- a/csrf.go +++ b/csrf.go @@ -66,12 +66,13 @@ type options struct { 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 - RequestHeader string - FieldName string - ErrorHandler http.Handler - CookieName string + HttpOnly bool + Secure bool + RequestHeader string + FieldName string + ErrorHandler http.Handler + CookieName string + TrustedOrigins []string } // Protect is HTTP middleware that provides Cross-Site Request Forgery @@ -233,7 +234,18 @@ func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - if sameOrigin(r.URL, referer) == false { + 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 diff --git a/csrf_test.go b/csrf_test.go index 2f458a7..0841d5f 100644 --- a/csrf_test.go +++ b/csrf_test.go @@ -272,6 +272,70 @@ func TestBadReferer(t *testing.T) { } } +// 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() diff --git a/options.go b/options.go index b50ebd4..872de89 100644 --- a/options.go +++ b/options.go @@ -1,6 +1,8 @@ package csrf -import "net/http" +import ( + "net/http" +) // Option describes a functional option for configuring the CSRF handler. type Option func(*csrf) @@ -97,6 +99,17 @@ func CookieName(name string) Option { } } +// 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 { From a7479e757eab87953eb377ef03c5b968a362c1de Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Sat, 20 Jul 2019 13:19:52 -0700 Subject: [PATCH 28/48] Create release-drafter.yml (#118) --- .github/release-drafter.yml | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .github/release-drafter.yml diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml new file mode 100644 index 0000000..b37234b --- /dev/null +++ b/.github/release-drafter.yml @@ -0,0 +1,8 @@ +# Config for https://github.com/apps/release-drafter +template: | + + + + ## CHANGELOG + $CHANGES + From 7b29b05df5ae7dc777b92fab3dadee1b15d15ed6 Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Sun, 25 Aug 2019 17:41:49 -0700 Subject: [PATCH 29/48] bugfix: correctly set a defaultMaxAge when MaxAge isn't called (#120) --- options.go | 6 +++++- options_test.go | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/options.go b/options.go index 872de89..9219147 100644 --- a/options.go +++ b/options.go @@ -8,7 +8,8 @@ import ( type Option func(*csrf) // MaxAge sets the maximum age (in seconds) of a CSRF token's underlying cookie. -// Defaults to 12 hours. +// 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 @@ -131,6 +132,9 @@ func parseOptions(h http.Handler, opts ...Option) *csrf { cs.opts.Secure = true cs.opts.HttpOnly = true + // 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 diff --git a/options_test.go b/options_test.go index 13e259c..1fe40bf 100644 --- a/options_test.go +++ b/options_test.go @@ -71,3 +71,26 @@ func TestOptions(t *testing.T) { 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) + } + }) + +} From 4b50158aba1b9683db9b198ddc61436713e778f8 Mon Sep 17 00:00:00 2001 From: Tom <33637037+tflyons@users.noreply.github.com> Date: Mon, 7 Oct 2019 19:23:26 -0700 Subject: [PATCH 30/48] feature: Support SameSite option (#123) * Add SameSite with build constraied * Update options test * Fix after feedback * Add docs --- README.md | 28 ++++++++ csrf.go | 18 +++++ options.go | 23 ++++++ options_test.go | 5 ++ store.go | 4 ++ store_legacy.go | 86 +++++++++++++++++++++++ store_legacy_test.go | 162 +++++++++++++++++++++++++++++++++++++++++++ store_test.go | 36 +++++++++- 8 files changed, 360 insertions(+), 2 deletions(-) create mode 100644 store_legacy.go create mode 100644 store_legacy_test.go diff --git a/README.md b/README.md index 2129446..3c7b533 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ go get github.com/gorilla/csrf - [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 @@ -267,6 +268,30 @@ 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 @@ -314,6 +339,9 @@ Getting CSRF protection right is important, so here's some background: - 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. diff --git a/csrf.go b/csrf.go index 8f78653..76352de 100644 --- a/csrf.go +++ b/csrf.go @@ -52,6 +52,22 @@ var ( 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 @@ -68,6 +84,7 @@ type options struct { // 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 @@ -166,6 +183,7 @@ func Protect(authKey []byte, opts ...Option) func(http.Handler) http.Handler { 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, diff --git a/options.go b/options.go index 9219147..da82167 100644 --- a/options.go +++ b/options.go @@ -61,6 +61,26 @@ func HttpOnly(h bool) Option { } } +// 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 @@ -132,6 +152,9 @@ func parseOptions(h http.Handler, opts ...Option) *csrf { 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 diff --git a/options_test.go b/options_test.go index 1fe40bf..d133fd1 100644 --- a/options_test.go +++ b/options_test.go @@ -24,6 +24,7 @@ func TestOptions(t *testing.T) { Path(path), HttpOnly(false), Secure(false), + SameSite(SameSiteStrictMode), RequestHeader(header), FieldName(field), ErrorHandler(http.HandlerFunc(errorHandler)), @@ -53,6 +54,10 @@ func TestOptions(t *testing.T) { 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) } diff --git a/store.go b/store.go index 39f47ad..f7997fc 100644 --- a/store.go +++ b/store.go @@ -1,3 +1,5 @@ +// +build go1.11 + package csrf import ( @@ -28,6 +30,7 @@ type cookieStore struct { path string domain string sc *securecookie.SecureCookie + sameSite SameSiteMode } // Get retrieves a CSRF token from the session cookie. It returns an empty token @@ -63,6 +66,7 @@ func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error { MaxAge: cs.maxAge, HttpOnly: cs.httpOnly, Secure: cs.secure, + SameSite: http.SameSite(cs.sameSite), Path: cs.path, Domain: cs.domain, } diff --git a/store_legacy.go b/store_legacy.go new file mode 100644 index 0000000..b211164 --- /dev/null +++ b/store_legacy.go @@ -0,0 +1,86 @@ +// +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 +} diff --git a/store_legacy_test.go b/store_legacy_test.go new file mode 100644 index 0000000..a3a4ac1 --- /dev/null +++ b/store_legacy_test.go @@ -0,0 +1,162 @@ +// +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) + } +} diff --git a/store_test.go b/store_test.go index e2836e5..cfa0534 100644 --- a/store_test.go +++ b/store_test.go @@ -1,3 +1,5 @@ +// +build go1.11 + package csrf import ( @@ -68,7 +70,7 @@ func TestCookieDecode(t *testing.T) { // Test with a nil hash key sc := securecookie.New(nil, nil) sc.MaxAge(age) - st := &cookieStore{cookieName, age, true, true, "", "", sc} + 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")) @@ -86,7 +88,7 @@ func TestCookieEncode(t *testing.T) { // Test with a nil hash key sc := securecookie.New(nil, nil) sc.MaxAge(age) - st := &cookieStore{cookieName, age, true, true, "", "", sc} + st := &cookieStore{cookieName, age, true, true, "", "", sc, SameSiteDefaultMode} rr := httptest.NewRecorder() @@ -127,3 +129,33 @@ func TestMaxAgeZero(t *testing.T) { 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) + } +} From dbfab4e112fc10c9e55c9c1f5f117e4fe480ecf1 Mon Sep 17 00:00:00 2001 From: Euan Kemp Date: Sun, 26 Apr 2020 09:47:29 -0700 Subject: [PATCH 31/48] bugfix: Don't set a default samesite for backwards compatibility (#132) Also add a comment over SameSiteDefaultMode discouraging its use. --- csrf.go | 3 +++ go.mod | 2 ++ options.go | 3 --- store_test.go | 30 ++++++++++++++++++++++++++++++ 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/csrf.go b/csrf.go index 76352de..1102b3d 100644 --- a/csrf.go +++ b/csrf.go @@ -62,6 +62,9 @@ type SameSiteMode int // SameSite options const ( + // SameSiteDefaultMode sets an invalid SameSite header which defaults to + // 'Lax' in most browsers, but may cause some browsers to ignore the cookie + // entirely. SameSiteDefaultMode SameSiteMode = iota + 1 SameSiteLaxMode SameSiteStrictMode diff --git a/go.mod b/go.mod index a5bf9b2..ae06dfb 100644 --- a/go.mod +++ b/go.mod @@ -4,3 +4,5 @@ require ( github.com/gorilla/securecookie v1.1.1 github.com/pkg/errors v0.8.0 ) + +go 1.13 diff --git a/options.go b/options.go index da82167..0205f5f 100644 --- a/options.go +++ b/options.go @@ -152,9 +152,6 @@ func parseOptions(h http.Handler, opts ...Option) *csrf { 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 diff --git a/store_test.go b/store_test.go index cfa0534..7fe6913 100644 --- a/store_test.go +++ b/store_test.go @@ -159,3 +159,33 @@ func TestSameSizeSet(t *testing.T) { t.Fatalf("cookie incorrectly does not have the SameSite attribute set: got %q", cookie) } } + +// TestSamesiteBackwardsCompat tests that the default set of options do not set +// any SameSite attribute. +func TestSamesiteBackwardsCompat(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) + } + + cookie := rr.Header().Get("Set-Cookie") + if cookie == "" { + t.Fatalf("cookie not get set-cookie header: got headers %v", rr.Header()) + } + + if strings.Contains(cookie, "SameSite") { + t.Fatalf("cookie should not contain the substring 'SameSite' by default, but did: %q", cookie) + } +} From 79c60d0e4fcf1fbc9653c1cb13d28e82248cf43c Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Sun, 26 Apr 2020 10:13:33 -0700 Subject: [PATCH 32/48] fix: Set SameSite=Lax by default (#136) * change: set SameSite=Lax by default * deps: update errors to v0.9.1 * build: add go 1.13, go 1.14 * docs: update SameSiteDefaultMode godoc --- .circleci/config.yml | 12 ++++++++++++ csrf.go | 7 ++++--- go.mod | 2 +- go.sum | 2 ++ options.go | 4 ++++ store_test.go | 13 +++++++------ 6 files changed, 30 insertions(+), 10 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index a4cd11e..c2eea3a 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -23,6 +23,16 @@ jobs: LATEST: "true" GO111MODULE: "on" + "1.14": + <<: *test + docker: + - image: circleci/golang:1.14 + + "1.13": + <<: *test + docker: + - image: circleci/golang:1.13 + "1.12": <<: *test docker: @@ -58,6 +68,8 @@ workflows: build: jobs: - "latest" + - "1.14" + - "1.13" - "1.12" - "1.11" - "1.10" diff --git a/csrf.go b/csrf.go index 1102b3d..f21e0a2 100644 --- a/csrf.go +++ b/csrf.go @@ -62,9 +62,10 @@ type SameSiteMode int // SameSite options const ( - // SameSiteDefaultMode sets an invalid SameSite header which defaults to - // 'Lax' in most browsers, but may cause some browsers to ignore the cookie - // entirely. + // SameSiteDefaultMode sets the `SameSite` cookie attribute, which is + // invalid in some older browsers due to changes in the SameSite spec. These + // browsers will not send the cookie to the server. + // csrf uses SameSiteLaxMode (SameSite=Lax) as the default as of v1.7.0+ SameSiteDefaultMode SameSiteMode = iota + 1 SameSiteLaxMode SameSiteStrictMode diff --git a/go.mod b/go.mod index ae06dfb..23a5c6e 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,7 @@ module github.com/gorilla/csrf require ( github.com/gorilla/securecookie v1.1.1 - github.com/pkg/errors v0.8.0 + github.com/pkg/errors v0.9.1 ) go 1.13 diff --git a/go.sum b/go.sum index 2d11d99..ff4965c 100644 --- a/go.sum +++ b/go.sum @@ -2,3 +2,5 @@ github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyC 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= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= diff --git a/options.go b/options.go index 0205f5f..c61d301 100644 --- a/options.go +++ b/options.go @@ -152,6 +152,10 @@ func parseOptions(h http.Handler, opts ...Option) *csrf { cs.opts.Secure = true cs.opts.HttpOnly = true + // Set SameSite=Lax by default, allowing the CSRF cookie to only be sent on + // top-level navigations. + cs.opts.SameSite = SameSiteLaxMode + // Default; only override this if the package user explicitly calls MaxAge(0) cs.opts.MaxAge = defaultAge diff --git a/store_test.go b/store_test.go index 7fe6913..27e6157 100644 --- a/store_test.go +++ b/store_test.go @@ -160,9 +160,9 @@ func TestSameSizeSet(t *testing.T) { } } -// TestSamesiteBackwardsCompat tests that the default set of options do not set -// any SameSite attribute. -func TestSamesiteBackwardsCompat(t *testing.T) { +// TestSameSiteDefault tests that the default set of options +// set SameSite=Lax on the CSRF cookie. +func TestSameSiteDefaultLaxMode(t *testing.T) { s := http.NewServeMux() s.HandleFunc("/", testHandler) @@ -182,10 +182,11 @@ func TestSamesiteBackwardsCompat(t *testing.T) { cookie := rr.Header().Get("Set-Cookie") if cookie == "" { - t.Fatalf("cookie not get set-cookie header: got headers %v", rr.Header()) + t.Fatalf("cookie not get Set-Cookie header: got headers %v", rr.Header()) } - if strings.Contains(cookie, "SameSite") { - t.Fatalf("cookie should not contain the substring 'SameSite' by default, but did: %q", cookie) + sameSiteLax := "SameSite=Lax" + if !strings.Contains(cookie, sameSiteLax) { + t.Fatalf("cookie should contain %q by default: got %s", sameSiteLax, cookie) } } From 4be14634cc857af3b80e118e9ebb40e2edaf29fc Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Sat, 30 May 2020 10:00:00 -0700 Subject: [PATCH 33/48] docs: add TOC to README (#137) --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index 3c7b533..9540e4b 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,18 @@ gorilla/csrf is designed to work with any Go web framework, including: gorilla/csrf is also compatible with middleware 'helper' libraries like [Alice](https://github.com/justinas/alice) and [Negroni](https://github.com/codegangsta/negroni). +## Contents + + * [Install](#install) + * [Examples](#examples) + + [HTML Forms](#html-forms) + + [JavaScript Applications](#javascript-applications) + + [Google App Engine](#google-app-engine) + + [Setting SameSite](#setting-samesite) + + [Setting Options](#setting-options) + * [Design Notes](#design-notes) + * [License](#license) + ## Install With a properly configured Go toolchain: From d1ee07fb166e69b31fffa5cc0f2f6a390bef32e5 Mon Sep 17 00:00:00 2001 From: Brent Mitton Date: Wed, 26 Aug 2020 09:38:05 -0400 Subject: [PATCH 34/48] docs: change TrustedOrigin to TrustedOrigins in README (#140) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9540e4b..ae7ab5d 100644 --- a/README.md +++ b/README.md @@ -226,7 +226,7 @@ import ( func main() { r := mux.NewRouter() - csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key"), csrf.TrustedOrigin([]string{"ui.domain.com"})) + csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key"), csrf.TrustedOrigins([]string{"ui.domain.com"})) api := r.PathPrefix("/api").Subrouter() api.Use(csrfMiddleware) From 9565ae2856dc7afa0ec76b0eaf6898f7f59c504b Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Sat, 12 Sep 2020 12:27:21 -0700 Subject: [PATCH 35/48] build: use build matrix; drop Go <= 1.10 (#142) --- .circleci/config.yml | 130 ++++++++++++++++++++----------------------- 1 file changed, 61 insertions(+), 69 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index c2eea3a..e7c6f24 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,78 +1,70 @@ -version: 2.0 +version: 2.1 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 + "test": + parameters: + version: + type: string + default: "latest" + golint: + type: boolean + default: true + modules: + type: boolean + default: true + goproxy: + type: string + default: "" docker: - - image: circleci/golang:latest - environment: - GO111MODULE: "on" + - image: "circleci/golang:<< parameters.version >>" 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.14": - <<: *test - docker: - - image: circleci/golang:1.14 - - "1.13": - <<: *test - docker: - - image: circleci/golang:1.13 - - "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 + GOPROXY: "<< parameters.goproxy >>" + steps: + - checkout + - run: + name: "Print the Go version" + command: > + go version + - run: + name: "Fetch dependencies" + command: > + if [[ << parameters.modules >> = true ]]; then + go mod download + export GO111MODULE=on + else + go get -v ./... + fi + # Only run gofmt, vet & lint against the latest Go version + - run: + name: "Run golint" + command: > + if [ << parameters.version >> = "latest" ] && [ << parameters.golint >> = true ]; then + go get -u golang.org/x/lint/golint + golint ./... + fi + - run: + name: "Run gofmt" + command: > + if [[ << parameters.version >> = "latest" ]]; then + diff -u <(echo -n) <(gofmt -d -e .) + fi + - run: + name: "Run go vet" + command: > + if [[ << parameters.version >> = "latest" ]]; then + go vet -v ./... + fi + - run: + name: "Run go test (+ race detector)" + command: > + go test -v -race ./... workflows: - version: 2 - build: + tests: jobs: - - "latest" - - "1.14" - - "1.13" - - "1.12" - - "1.11" - - "1.10" - - "1.9" - - "1.8" - - "1.7" + - test: + matrix: + parameters: + version: ["latest", "1.15", "1.14", "1.13", "1.12", "1.11"] From 46c01904ff6ce411fdc09d58ebc66edcebc4c934 Mon Sep 17 00:00:00 2001 From: Karel Bilek Date: Sun, 11 Apr 2021 20:41:23 +0700 Subject: [PATCH 36/48] Add note about csrf.Path option (#147) --- README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/README.md b/README.md index ae7ab5d..be1558c 100644 --- a/README.md +++ b/README.md @@ -304,6 +304,21 @@ func main() { } ``` +### Cookie path + +By default, CSRF cookies are set on the path of the request. + +This can create issues, if the request is done from one path to a different path. + +You might want to set up a root path for all the cookies; that way, the CSRF will always work across all your paths. + +``` + CSRF := csrf.Protect( + []byte("a-32-byte-long-key-goes-here"), + csrf.Path("/"), + ) +``` + ### Setting Options What about providing your own error handler and changing the HTTP header the From c61da383cc183c9a7ff9a471bf929c5099cbe1da Mon Sep 17 00:00:00 2001 From: Massimo Maggi Date: Sat, 29 May 2021 00:24:27 +0200 Subject: [PATCH 37/48] Add a note about secrecy of CSRF token in the README.md (#154) --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index be1558c..4abf569 100644 --- a/README.md +++ b/README.md @@ -68,9 +68,12 @@ 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 +Note that the authentication key passed to `csrf.Protect([]byte(key))` should: +- be 32-bytes long +- persist across application restarts. +- kept secret from potential malicious users - do not hardcode it into the source code, especially not in open-source applications. + +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 From b69cbb30a1ca62a91c30fc52f16a3cb24a73a8f7 Mon Sep 17 00:00:00 2001 From: Florian Loch Date: Thu, 29 Jul 2021 17:50:12 +0200 Subject: [PATCH 38/48] bugfix: Not providing any token in requests results in wrong error message (#149) * Fix wrong error being reported when token missing in request * Remove a condition that never becomes true * Add myself to the list of AUTHORS assuming this is good style * Fix minor style issue --- AUTHORS | 1 + csrf.go | 16 +++++++++++----- csrf_test.go | 42 ++++++++++++++++++++++++++++++++++++++++++ helpers.go | 11 ++++++++--- 4 files changed, 62 insertions(+), 8 deletions(-) diff --git a/AUTHORS b/AUTHORS index 4e84c37..e8d6043 100644 --- a/AUTHORS +++ b/AUTHORS @@ -2,6 +2,7 @@ # Please keep the list sorted. adiabatic +Florian D. Loch Google LLC (https://opensource.google.com) jamesgroat Joshua Carp diff --git a/csrf.go b/csrf.go index f21e0a2..21223d4 100644 --- a/csrf.go +++ b/csrf.go @@ -274,16 +274,22 @@ func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } - // If the token returned from the session store is nil for non-idempotent - // ("unsafe") methods, call the error handler. - if realToken == nil { + // Retrieve the combined token (pad + masked) token... + maskedToken, err := cs.requestToken(r) + if err != nil { + r = envError(r, ErrBadToken) + cs.opts.ErrorHandler.ServeHTTP(w, r) + return + } + + if maskedToken == 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)) + // ... and unmask it. + requestToken := unmask(maskedToken) // Compare the request token against the real token if !compareTokens(requestToken, realToken) { diff --git a/csrf_test.go b/csrf_test.go index 0841d5f..a97fb10 100644 --- a/csrf_test.go +++ b/csrf_test.go @@ -374,6 +374,48 @@ func TestWithReferer(t *testing.T) { } } +// Requests without a token should fail with ErrNoToken. +func TestNoTokenProvided(t *testing.T) { + var finalErr error + + s := http.NewServeMux() + p := Protect(testKey, ErrorHandler(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + finalErr = FailureReason(r) + })))(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) + // By accident we use the wrong header name for the token... + r.Header.Set("X-CSRF-nekot", token) + r.Header.Set("Referer", "http://www.gorillatoolkit.org/") + + rr = httptest.NewRecorder() + p.ServeHTTP(rr, r) + + if finalErr != nil && finalErr != ErrNoToken { + t.Fatalf("middleware failed to return correct error: got '%v' want '%v'", finalErr, ErrNoToken) + } +} + func setCookie(rr *httptest.ResponseRecorder, r *http.Request) { r.Header.Set("Cookie", rr.Header().Get("Set-Cookie")) } diff --git a/helpers.go b/helpers.go index 3dacfd2..c19dc47 100644 --- a/helpers.go +++ b/helpers.go @@ -105,7 +105,7 @@ func unmask(issued []byte) []byte { // 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 { +func (cs *csrf) requestToken(r *http.Request) ([]byte, error) { // 1. Check the HTTP header first. issued := r.Header.Get(cs.opts.RequestHeader) @@ -123,14 +123,19 @@ func (cs *csrf) requestToken(r *http.Request) []byte { } } + // Return nil (equivalent to empty byte slice) if no token was found + if issued == "" { + return nil, nil + } + // 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 nil, err } - return decoded + return decoded, nil } // generateRandomBytes returns securely generated random bytes. From e40f2349c645679e20e0e2a4b53285e06c98ccc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Husiaty=C5=84ski?= <1517+husio@users.noreply.github.com> Date: Fri, 21 Jan 2022 12:18:02 +0100 Subject: [PATCH 39/48] Remove pkg/errors dependency (#161) --- context.go | 7 +++---- csrf.go | 3 +-- go.mod | 5 +---- go.sum | 4 ---- store.go | 1 + store_legacy.go | 2 ++ store_legacy_test.go | 5 +++-- store_test.go | 4 ++-- 8 files changed, 13 insertions(+), 18 deletions(-) diff --git a/context.go b/context.go index d8bb42f..c2df9a1 100644 --- a/context.go +++ b/context.go @@ -1,20 +1,19 @@ +//go:build go1.7 // +build go1.7 package csrf import ( "context" + "fmt" "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 nil, fmt.Errorf("no value exists in the context for key %q", key) } - return val, nil } diff --git a/csrf.go b/csrf.go index 21223d4..fccc175 100644 --- a/csrf.go +++ b/csrf.go @@ -1,12 +1,11 @@ package csrf import ( + "errors" "fmt" "net/http" "net/url" - "github.com/pkg/errors" - "github.com/gorilla/securecookie" ) diff --git a/go.mod b/go.mod index 23a5c6e..d2ce198 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,5 @@ module github.com/gorilla/csrf -require ( - github.com/gorilla/securecookie v1.1.1 - github.com/pkg/errors v0.9.1 -) +require github.com/gorilla/securecookie v1.1.1 go 1.13 diff --git a/go.sum b/go.sum index ff4965c..e6a7ed5 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,2 @@ github.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= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= diff --git a/store.go b/store.go index f7997fc..4e6382b 100644 --- a/store.go +++ b/store.go @@ -1,3 +1,4 @@ +//go:build go1.11 // +build go1.11 package csrf diff --git a/store_legacy.go b/store_legacy.go index b211164..4e1fb9e 100644 --- a/store_legacy.go +++ b/store_legacy.go @@ -1,4 +1,6 @@ +//go:build !go1.11 // +build !go1.11 + // file for compatibility with go versions prior to 1.11 package csrf diff --git a/store_legacy_test.go b/store_legacy_test.go index a3a4ac1..ce64a6e 100644 --- a/store_legacy_test.go +++ b/store_legacy_test.go @@ -1,17 +1,18 @@ +//go:build !go1.11 // +build !go1.11 + // file for compatibility with go versions prior to 1.11 package csrf import ( + "errors" "fmt" "net/http" "net/http/httptest" "strings" "testing" - "github.com/pkg/errors" - "github.com/gorilla/securecookie" ) diff --git a/store_test.go b/store_test.go index 27e6157..058b61c 100644 --- a/store_test.go +++ b/store_test.go @@ -1,16 +1,16 @@ +//go:build go1.11 // +build go1.11 package csrf import ( + "errors" "fmt" "net/http" "net/http/httptest" "strings" "testing" - "github.com/pkg/errors" - "github.com/gorilla/securecookie" ) From 93379db1992f1b2fbdd4ba1b55a1bf0414b0535e Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Fri, 9 Dec 2022 11:10:23 -0500 Subject: [PATCH 40/48] archive mode --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 4abf569..cc54e77 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,12 @@ [![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) +--- + +**The Gorilla project has been archived, and is no longer under active maintainenance. You can read more here: https://github.com/gorilla#gorilla-toolkit** + +--- + 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: From 04cc5dba5dd0af4341b9b406f05dc569c5e0ab40 Mon Sep 17 00:00:00 2001 From: Corey Daley Date: Sat, 15 Jul 2023 10:49:40 -0400 Subject: [PATCH 41/48] Update README.md Signed-off-by: Corey Daley --- README.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/README.md b/README.md index cc54e77..4abf569 100644 --- a/README.md +++ b/README.md @@ -5,12 +5,6 @@ [![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) ---- - -**The Gorilla project has been archived, and is no longer under active maintainenance. You can read more here: https://github.com/gorilla#gorilla-toolkit** - ---- - 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: From 15d47eceb8d5861882e276508d7cbb5b0082b980 Mon Sep 17 00:00:00 2001 From: Apoorva Jagtap <35304110+apoorvajagtap@users.noreply.github.com> Date: Wed, 26 Jul 2023 01:07:43 +0530 Subject: [PATCH 42/48] [GPT-96] Update go version & add verification/testing tools (#166) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What type of PR is this? (check all applicable) - [ ] Refactor - [ ] Feature - [ ] Bug Fix - [ ] Optimization - [ ] Documentation Update ## Description ## Related Tickets & Documents - Related Issue # - Closes # ## Added/updated tests? - [ ] Yes - [ ] No, and this is why: _please replace this line with details on why tests have not been included_ - [ ] I need help with writing tests ## Run verifications and test - [ ] `make verify` is passing - [ ] `make test` is passing --- .circleci/config.yml | 70 -- .editorconfig | 20 + .github/release-drafter.yml | 8 - .github/stale.yml | 12 - .github/workflows/issues.yml | 20 + .github/workflows/test.yml | 55 ++ .gitignore | 1 + AUTHORS | 21 - Makefile | 34 + README.md | 11 +- context.go | 2 +- csrf.go | 9 +- csrf_test.go | 12 +- go.mod | 2 +- helpers.go | 13 +- helpers_test.go | 26 +- store_test.go | 2 +- .../gorilla/securecookie/.travis.yml | 19 + .../github.com/gorilla/securecookie/LICENSE | 27 + .../github.com/gorilla/securecookie/README.md | 80 +++ vendor/github.com/gorilla/securecookie/doc.go | 61 ++ .../github.com/gorilla/securecookie/fuzz.go | 25 + .../gorilla/securecookie/securecookie.go | 646 ++++++++++++++++++ vendor/modules.txt | 3 + 24 files changed, 1037 insertions(+), 142 deletions(-) delete mode 100644 .circleci/config.yml create mode 100644 .editorconfig delete mode 100644 .github/release-drafter.yml delete mode 100644 .github/stale.yml create mode 100644 .github/workflows/issues.yml create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore delete mode 100644 AUTHORS create mode 100644 Makefile create mode 100644 vendor/github.com/gorilla/securecookie/.travis.yml create mode 100644 vendor/github.com/gorilla/securecookie/LICENSE create mode 100644 vendor/github.com/gorilla/securecookie/README.md create mode 100644 vendor/github.com/gorilla/securecookie/doc.go create mode 100644 vendor/github.com/gorilla/securecookie/fuzz.go create mode 100644 vendor/github.com/gorilla/securecookie/securecookie.go create mode 100644 vendor/modules.txt diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index e7c6f24..0000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,70 +0,0 @@ -version: 2.1 - -jobs: - "test": - parameters: - version: - type: string - default: "latest" - golint: - type: boolean - default: true - modules: - type: boolean - default: true - goproxy: - type: string - default: "" - docker: - - image: "circleci/golang:<< parameters.version >>" - working_directory: /go/src/github.com/gorilla/csrf - environment: - GO111MODULE: "on" - GOPROXY: "<< parameters.goproxy >>" - steps: - - checkout - - run: - name: "Print the Go version" - command: > - go version - - run: - name: "Fetch dependencies" - command: > - if [[ << parameters.modules >> = true ]]; then - go mod download - export GO111MODULE=on - else - go get -v ./... - fi - # Only run gofmt, vet & lint against the latest Go version - - run: - name: "Run golint" - command: > - if [ << parameters.version >> = "latest" ] && [ << parameters.golint >> = true ]; then - go get -u golang.org/x/lint/golint - golint ./... - fi - - run: - name: "Run gofmt" - command: > - if [[ << parameters.version >> = "latest" ]]; then - diff -u <(echo -n) <(gofmt -d -e .) - fi - - run: - name: "Run go vet" - command: > - if [[ << parameters.version >> = "latest" ]]; then - go vet -v ./... - fi - - run: - name: "Run go test (+ race detector)" - command: > - go test -v -race ./... - -workflows: - tests: - jobs: - - test: - matrix: - parameters: - version: ["latest", "1.15", "1.14", "1.13", "1.12", "1.11"] diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c6b74c3 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,20 @@ +; https://editorconfig.org/ + +root = true + +[*] +insert_final_newline = true +charset = utf-8 +trim_trailing_whitespace = true +indent_style = space +indent_size = 2 + +[{Makefile,go.mod,go.sum,*.go,.gitmodules}] +indent_style = tab +indent_size = 4 + +[*.md] +indent_size = 4 +trim_trailing_whitespace = false + +eclint_indent_style = unset \ No newline at end of file diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml deleted file mode 100644 index b37234b..0000000 --- a/.github/release-drafter.yml +++ /dev/null @@ -1,8 +0,0 @@ -# Config for https://github.com/apps/release-drafter -template: | - - - - ## CHANGELOG - $CHANGES - diff --git a/.github/stale.yml b/.github/stale.yml deleted file mode 100644 index de8a678..0000000 --- a/.github/stale.yml +++ /dev/null @@ -1,12 +0,0 @@ -daysUntilStale: 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 diff --git a/.github/workflows/issues.yml b/.github/workflows/issues.yml new file mode 100644 index 0000000..055ca82 --- /dev/null +++ b/.github/workflows/issues.yml @@ -0,0 +1,20 @@ +# Add issues or pull-requests created to the project. +name: Add issue or pull request to Project + +on: + issues: + types: + - opened + pull_request: + types: + - opened + +jobs: + add-to-project: + runs-on: ubuntu-latest + steps: + - name: Add issue to project + uses: actions/add-to-project@v0.5.0 + with: + project-url: https://github.com/orgs/gorilla/projects/4 + github-token: ${{ secrets.ADD_TO_PROJECT_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..f2e4b4d --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,55 @@ +name: CI +on: + push: + branches: + - main + pull_request: + branches: + - main + +permissions: + contents: read + +jobs: + verify-and-test: + strategy: + matrix: + go: ['1.19','1.20'] + os: [ubuntu-latest, macos-latest, windows-latest] + fail-fast: true + runs-on: ${{ matrix.os }} + steps: + - name: Checkout Code + uses: actions/checkout@v3 + + - name: Setup Go ${{ matrix.go }} + uses: actions/setup-go@v4 + with: + go-version: ${{ matrix.go }} + cache: false + + - name: Run GolangCI-Lint + uses: golangci/golangci-lint-action@v3 + with: + version: v1.53 + args: --timeout=5m + + - name: Run GoSec + if: matrix.os == 'ubuntu-latest' + uses: securego/gosec@master + with: + args: ./... + + - name: Run GoVulnCheck + uses: golang/govulncheck-action@v1 + with: + go-version-input: ${{ matrix.go }} + go-package: ./... + + - name: Run Tests + run: go test -race -cover -coverprofile=coverage -covermode=atomic -v ./... + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v3 + with: + files: ./coverage diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..84039fe --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +coverage.coverprofile diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index e8d6043..0000000 --- a/AUTHORS +++ /dev/null @@ -1,21 +0,0 @@ -# This is the official list of gorilla/csrf authors for copyright purposes. -# Please keep the list sorted. - -adiabatic -Florian D. Loch -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 -田浩浩 -陈东海 diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..ac37ffd --- /dev/null +++ b/Makefile @@ -0,0 +1,34 @@ +GO_LINT=$(shell which golangci-lint 2> /dev/null || echo '') +GO_LINT_URI=github.com/golangci/golangci-lint/cmd/golangci-lint@latest + +GO_SEC=$(shell which gosec 2> /dev/null || echo '') +GO_SEC_URI=github.com/securego/gosec/v2/cmd/gosec@latest + +GO_VULNCHECK=$(shell which govulncheck 2> /dev/null || echo '') +GO_VULNCHECK_URI=golang.org/x/vuln/cmd/govulncheck@latest + +.PHONY: golangci-lint +golangci-lint: + $(if $(GO_LINT), ,go install $(GO_LINT_URI)) + @echo "##### Running golangci-lint" + golangci-lint run -v + +.PHONY: gosec +gosec: + $(if $(GO_SEC), ,go install $(GO_SEC_URI)) + @echo "##### Running gosec" + gosec ./... + +.PHONY: govulncheck +govulncheck: + $(if $(GO_VULNCHECK), ,go install $(GO_VULNCHECK_URI)) + @echo "##### Running govulncheck" + govulncheck ./... + +.PHONY: verify +verify: golangci-lint gosec govulncheck + +.PHONY: test +test: + @echo "##### Running tests" + go test -race -cover -coverprofile=coverage.coverprofile -covermode=atomic -v ./... diff --git a/README.md b/README.md index 4abf569..d768c81 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,12 @@ # 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) +![testing](https://github.com/gorilla/csrf/actions/workflows/test.yml/badge.svg) +[![codecov](https://codecov.io/github/gorilla/csrf/branch/main/graph/badge.svg)](https://codecov.io/github/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) + + +![Gorilla Logo](https://github.com/gorilla/.github/assets/53367916/d92caabf-98e0-473e-bfbf-ab554ba435e5) gorilla/csrf is a HTTP middleware library that provides [cross-site request forgery](http://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/) (CSRF) diff --git a/context.go b/context.go index c2df9a1..d24b146 100644 --- a/context.go +++ b/context.go @@ -19,7 +19,7 @@ func contextGet(r *http.Request, key string) (interface{}, error) { func contextSave(r *http.Request, key string, val interface{}) *http.Request { ctx := r.Context() - ctx = context.WithValue(ctx, key, val) + ctx = context.WithValue(ctx, key, val) // nolint:staticcheck return r.WithContext(ctx) } diff --git a/csrf.go b/csrf.go index fccc175..97a3925 100644 --- a/csrf.go +++ b/csrf.go @@ -14,8 +14,8 @@ const tokenLength = 32 // Context/session keys & prefixes const ( - tokenKey string = "gorilla.csrf.Token" - formKey string = "gorilla.csrf.Form" + tokenKey string = "gorilla.csrf.Token" // #nosec G101 + formKey string = "gorilla.csrf.Form" // #nosec G101 errorKey string = "gorilla.csrf.Error" skipCheckKey string = "gorilla.csrf.Skip" cookieName string = "_gorilla_csrf" @@ -107,6 +107,7 @@ type options struct { // 'Forbidden' error response. // // Example: +// // package main // // import ( @@ -143,7 +144,6 @@ type options struct { // // 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...) @@ -266,7 +266,7 @@ func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } - if valid == false { + if !valid { r = envError(r, ErrBadReferer) cs.opts.ErrorHandler.ServeHTTP(w, r) return @@ -314,5 +314,4 @@ func unauthorizedHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, fmt.Sprintf("%s - %s", http.StatusText(http.StatusForbidden), FailureReason(r)), http.StatusForbidden) - return } diff --git a/csrf_test.go b/csrf_test.go index a97fb10..0559a59 100644 --- a/csrf_test.go +++ b/csrf_test.go @@ -153,7 +153,7 @@ func TestBadCookie(t *testing.T) { p := Protect(testKey)(s) var token string - s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { token = Token(r) })) @@ -238,7 +238,7 @@ func TestBadReferer(t *testing.T) { p := Protect(testKey)(s) var token string - s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { token = Token(r) })) @@ -294,7 +294,7 @@ func TestTrustedReferer(t *testing.T) { p := Protect(testKey, TrustedOrigins(item.trustedOrigin))(s) var token string - s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { token = Token(r) })) @@ -342,7 +342,7 @@ func TestWithReferer(t *testing.T) { p := Protect(testKey)(s) var token string - s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { token = Token(r) })) @@ -379,12 +379,12 @@ func TestNoTokenProvided(t *testing.T) { var finalErr error s := http.NewServeMux() - p := Protect(testKey, ErrorHandler(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + p := Protect(testKey, ErrorHandler(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { finalErr = FailureReason(r) })))(s) var token string - s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { token = Token(r) })) diff --git a/go.mod b/go.mod index d2ce198..ebb010e 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,4 @@ module github.com/gorilla/csrf require github.com/gorilla/securecookie v1.1.1 -go 1.13 +go 1.19 diff --git a/helpers.go b/helpers.go index c19dc47..99005ee 100644 --- a/helpers.go +++ b/helpers.go @@ -51,18 +51,17 @@ func UnsafeSkipCheck(r *http.Request) *http.Request { // // Example: // -// // The following tag in our form.tmpl template: -// {{ .csrfField }} -// -// // ... becomes: -// +// // 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(fragment) // #nosec G203 } return template.HTML("") @@ -75,7 +74,7 @@ func TemplateField(r *http.Request) template.HTML { // 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 { +func mask(realToken []byte, _ *http.Request) string { otp, err := generateRandomBytes(tokenLength) if err != nil { return "" diff --git a/helpers_test.go b/helpers_test.go index 30ee7b3..399db8d 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -6,6 +6,7 @@ import ( "encoding/base64" "fmt" "io" + "log" "mime/multipart" "net/http" "net/http/httptest" @@ -34,9 +35,12 @@ func TestFormToken(t *testing.T) { 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{}{ + err := t.Execute(w, map[string]interface{}{ TemplateTag: TemplateField(r), }) + if err != nil { + log.Printf("errored during executing the template: %v", err) + } })) r, err := http.NewRequest("GET", "/", nil) @@ -71,9 +75,12 @@ func TestMultipartFormToken(t *testing.T) { 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{}{ + err := t.Execute(w, map[string]interface{}{ TemplateTag: TemplateField(r), }) + if err != nil { + log.Printf("errored during executing the template: %v", err) + } })) r, err := http.NewRequest("GET", "/", nil) @@ -93,7 +100,11 @@ func TestMultipartFormToken(t *testing.T) { t.Fatal(err) } - wr.Write([]byte(token)) + _, err = wr.Write([]byte(token)) + if err != nil { + t.Fatal(err) + } + mp.Close() r, err = http.NewRequest("POST", "http://www.gorillatoolkit.org/", &b) @@ -185,7 +196,7 @@ func TestXOR(t *testing.T) { for _, token := range testTokens { if res := xorToken(token.a, token.b); res != nil { - if bytes.Compare(res, token.expected) != 0 { + if !bytes.Equal(res, token.expected) { t.Fatalf("xorBytes failed to return the expected result: got %v want %v", res, token.expected) } @@ -226,9 +237,12 @@ func TestTemplateField(t *testing.T) { token = Token(r) templateField = string(TemplateField(r)) t := template.Must((template.New("base").Parse(testTemplate))) - t.Execute(w, map[string]interface{}{ + err := t.Execute(w, map[string]interface{}{ TemplateTag: TemplateField(r), }) + if err != nil { + log.Printf("errored during executing the template: %v", err) + } })) testFieldName := "custom_field_name" @@ -280,7 +294,7 @@ func TestUnsafeSkipCSRFCheck(t *testing.T) { 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) { + s.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { // Set a non-200 header to make the test explicit. w.WriteHeader(teapot) })) diff --git a/store_test.go b/store_test.go index 058b61c..712a438 100644 --- a/store_test.go +++ b/store_test.go @@ -19,7 +19,7 @@ var _ store = &cookieStore{} // brokenSaveStore is a CSRF store that cannot, well, save. type brokenSaveStore struct { - store + store // nolint:unused } func (bs *brokenSaveStore) Get(*http.Request) ([]byte, error) { diff --git a/vendor/github.com/gorilla/securecookie/.travis.yml b/vendor/github.com/gorilla/securecookie/.travis.yml new file mode 100644 index 0000000..6f440f1 --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/.travis.yml @@ -0,0 +1,19 @@ +language: go +sudo: false + +matrix: + include: + - go: 1.3 + - go: 1.4 + - go: 1.5 + - go: 1.6 + - go: 1.7 + - go: tip + allow_failures: + - go: tip + +script: + - go get -t -v ./... + - diff -u <(echo -n) <(gofmt -d .) + - go vet $(go list ./... | grep -v /vendor/) + - go test -v -race ./... diff --git a/vendor/github.com/gorilla/securecookie/LICENSE b/vendor/github.com/gorilla/securecookie/LICENSE new file mode 100644 index 0000000..0e5fb87 --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012 Rodrigo Moraes. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Google Inc. 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 +OWNER 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. diff --git a/vendor/github.com/gorilla/securecookie/README.md b/vendor/github.com/gorilla/securecookie/README.md new file mode 100644 index 0000000..aa7bd1a --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/README.md @@ -0,0 +1,80 @@ +securecookie +============ +[![GoDoc](https://godoc.org/github.com/gorilla/securecookie?status.svg)](https://godoc.org/github.com/gorilla/securecookie) [![Build Status](https://travis-ci.org/gorilla/securecookie.png?branch=master)](https://travis-ci.org/gorilla/securecookie) +[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/securecookie/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/securecookie?badge) + + +securecookie encodes and decodes authenticated and optionally encrypted +cookie values. + +Secure cookies can't be forged, because their values are validated using HMAC. +When encrypted, the content is also inaccessible to malicious eyes. It is still +recommended that sensitive data not be stored in cookies, and that HTTPS be used +to prevent cookie [replay attacks](https://en.wikipedia.org/wiki/Replay_attack). + +## Examples + +To use it, first create a new SecureCookie instance: + +```go +// Hash keys should be at least 32 bytes long +var hashKey = []byte("very-secret") +// Block keys should be 16 bytes (AES-128) or 32 bytes (AES-256) long. +// Shorter keys may weaken the encryption used. +var blockKey = []byte("a-lot-secret") +var s = securecookie.New(hashKey, blockKey) +``` + +The hashKey is required, used to authenticate the cookie value using HMAC. +It is recommended to use a key with 32 or 64 bytes. + +The blockKey is optional, used to encrypt the cookie value -- set it to nil +to not use encryption. If set, the length must correspond to the block size +of the encryption algorithm. For AES, used by default, valid lengths are +16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. + +Strong keys can be created using the convenience function GenerateRandomKey(). + +Once a SecureCookie instance is set, use it to encode a cookie value: + +```go +func SetCookieHandler(w http.ResponseWriter, r *http.Request) { + value := map[string]string{ + "foo": "bar", + } + if encoded, err := s.Encode("cookie-name", value); err == nil { + cookie := &http.Cookie{ + Name: "cookie-name", + Value: encoded, + Path: "/", + Secure: true, + HttpOnly: true, + } + http.SetCookie(w, cookie) + } +} +``` + +Later, use the same SecureCookie instance to decode and validate a cookie +value: + +```go +func ReadCookieHandler(w http.ResponseWriter, r *http.Request) { + if cookie, err := r.Cookie("cookie-name"); err == nil { + value := make(map[string]string) + if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil { + fmt.Fprintf(w, "The value of foo is %q", value["foo"]) + } + } +} +``` + +We stored a map[string]string, but secure cookies can hold any value that +can be encoded using `encoding/gob`. To store custom types, they must be +registered first using gob.Register(). For basic types this is not needed; +it works out of the box. An optional JSON encoder that uses `encoding/json` is +available for types compatible with JSON. + +## License + +BSD licensed. See the LICENSE file for details. diff --git a/vendor/github.com/gorilla/securecookie/doc.go b/vendor/github.com/gorilla/securecookie/doc.go new file mode 100644 index 0000000..ae89408 --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/doc.go @@ -0,0 +1,61 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package securecookie encodes and decodes authenticated and optionally +encrypted cookie values. + +Secure cookies can't be forged, because their values are validated using HMAC. +When encrypted, the content is also inaccessible to malicious eyes. + +To use it, first create a new SecureCookie instance: + + var hashKey = []byte("very-secret") + var blockKey = []byte("a-lot-secret") + var s = securecookie.New(hashKey, blockKey) + +The hashKey is required, used to authenticate the cookie value using HMAC. +It is recommended to use a key with 32 or 64 bytes. + +The blockKey is optional, used to encrypt the cookie value -- set it to nil +to not use encryption. If set, the length must correspond to the block size +of the encryption algorithm. For AES, used by default, valid lengths are +16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. + +Strong keys can be created using the convenience function GenerateRandomKey(). + +Once a SecureCookie instance is set, use it to encode a cookie value: + + func SetCookieHandler(w http.ResponseWriter, r *http.Request) { + value := map[string]string{ + "foo": "bar", + } + if encoded, err := s.Encode("cookie-name", value); err == nil { + cookie := &http.Cookie{ + Name: "cookie-name", + Value: encoded, + Path: "/", + } + http.SetCookie(w, cookie) + } + } + +Later, use the same SecureCookie instance to decode and validate a cookie +value: + + func ReadCookieHandler(w http.ResponseWriter, r *http.Request) { + if cookie, err := r.Cookie("cookie-name"); err == nil { + value := make(map[string]string) + if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil { + fmt.Fprintf(w, "The value of foo is %q", value["foo"]) + } + } + } + +We stored a map[string]string, but secure cookies can hold any value that +can be encoded using encoding/gob. To store custom types, they must be +registered first using gob.Register(). For basic types this is not needed; +it works out of the box. +*/ +package securecookie diff --git a/vendor/github.com/gorilla/securecookie/fuzz.go b/vendor/github.com/gorilla/securecookie/fuzz.go new file mode 100644 index 0000000..e4d0534 --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/fuzz.go @@ -0,0 +1,25 @@ +// +build gofuzz + +package securecookie + +var hashKey = []byte("very-secret12345") +var blockKey = []byte("a-lot-secret1234") +var s = New(hashKey, blockKey) + +type Cookie struct { + B bool + I int + S string +} + +func Fuzz(data []byte) int { + datas := string(data) + var c Cookie + if err := s.Decode("fuzz", datas, &c); err != nil { + return 0 + } + if _, err := s.Encode("fuzz", c); err != nil { + panic(err) + } + return 1 +} diff --git a/vendor/github.com/gorilla/securecookie/securecookie.go b/vendor/github.com/gorilla/securecookie/securecookie.go new file mode 100644 index 0000000..cd4e097 --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/securecookie.go @@ -0,0 +1,646 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package securecookie + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/gob" + "encoding/json" + "fmt" + "hash" + "io" + "strconv" + "strings" + "time" +) + +// Error is the interface of all errors returned by functions in this library. +type Error interface { + error + + // IsUsage returns true for errors indicating the client code probably + // uses this library incorrectly. For example, the client may have + // failed to provide a valid hash key, or may have failed to configure + // the Serializer adequately for encoding value. + IsUsage() bool + + // IsDecode returns true for errors indicating that a cookie could not + // be decoded and validated. Since cookies are usually untrusted + // user-provided input, errors of this type should be expected. + // Usually, the proper action is simply to reject the request. + IsDecode() bool + + // IsInternal returns true for unexpected errors occurring in the + // securecookie implementation. + IsInternal() bool + + // Cause, if it returns a non-nil value, indicates that this error was + // propagated from some underlying library. If this method returns nil, + // this error was raised directly by this library. + // + // Cause is provided principally for debugging/logging purposes; it is + // rare that application logic should perform meaningfully different + // logic based on Cause. See, for example, the caveats described on + // (MultiError).Cause(). + Cause() error +} + +// errorType is a bitmask giving the error type(s) of an cookieError value. +type errorType int + +const ( + usageError = errorType(1 << iota) + decodeError + internalError +) + +type cookieError struct { + typ errorType + msg string + cause error +} + +func (e cookieError) IsUsage() bool { return (e.typ & usageError) != 0 } +func (e cookieError) IsDecode() bool { return (e.typ & decodeError) != 0 } +func (e cookieError) IsInternal() bool { return (e.typ & internalError) != 0 } + +func (e cookieError) Cause() error { return e.cause } + +func (e cookieError) Error() string { + parts := []string{"securecookie: "} + if e.msg == "" { + parts = append(parts, "error") + } else { + parts = append(parts, e.msg) + } + if c := e.Cause(); c != nil { + parts = append(parts, " - caused by: ", c.Error()) + } + return strings.Join(parts, "") +} + +var ( + errGeneratingIV = cookieError{typ: internalError, msg: "failed to generate random iv"} + + errNoCodecs = cookieError{typ: usageError, msg: "no codecs provided"} + errHashKeyNotSet = cookieError{typ: usageError, msg: "hash key is not set"} + errBlockKeyNotSet = cookieError{typ: usageError, msg: "block key is not set"} + errEncodedValueTooLong = cookieError{typ: usageError, msg: "the value is too long"} + + errValueToDecodeTooLong = cookieError{typ: decodeError, msg: "the value is too long"} + errTimestampInvalid = cookieError{typ: decodeError, msg: "invalid timestamp"} + errTimestampTooNew = cookieError{typ: decodeError, msg: "timestamp is too new"} + errTimestampExpired = cookieError{typ: decodeError, msg: "expired timestamp"} + errDecryptionFailed = cookieError{typ: decodeError, msg: "the value could not be decrypted"} + errValueNotByte = cookieError{typ: decodeError, msg: "value not a []byte."} + errValueNotBytePtr = cookieError{typ: decodeError, msg: "value not a pointer to []byte."} + + // ErrMacInvalid indicates that cookie decoding failed because the HMAC + // could not be extracted and verified. Direct use of this error + // variable is deprecated; it is public only for legacy compatibility, + // and may be privatized in the future, as it is rarely useful to + // distinguish between this error and other Error implementations. + ErrMacInvalid = cookieError{typ: decodeError, msg: "the value is not valid"} +) + +// Codec defines an interface to encode and decode cookie values. +type Codec interface { + Encode(name string, value interface{}) (string, error) + Decode(name, value string, dst interface{}) error +} + +// New returns a new SecureCookie. +// +// hashKey is required, used to authenticate values using HMAC. Create it using +// GenerateRandomKey(). It is recommended to use a key with 32 or 64 bytes. +// +// blockKey is optional, used to encrypt values. Create it using +// GenerateRandomKey(). The key length must correspond to the block size +// of the encryption algorithm. For AES, used by default, valid lengths are +// 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. +// The default encoder used for cookie serialization is encoding/gob. +// +// Note that keys created using GenerateRandomKey() are not automatically +// persisted. New keys will be created when the application is restarted, and +// previously issued cookies will not be able to be decoded. +func New(hashKey, blockKey []byte) *SecureCookie { + s := &SecureCookie{ + hashKey: hashKey, + blockKey: blockKey, + hashFunc: sha256.New, + maxAge: 86400 * 30, + maxLength: 4096, + sz: GobEncoder{}, + } + if hashKey == nil { + s.err = errHashKeyNotSet + } + if blockKey != nil { + s.BlockFunc(aes.NewCipher) + } + return s +} + +// SecureCookie encodes and decodes authenticated and optionally encrypted +// cookie values. +type SecureCookie struct { + hashKey []byte + hashFunc func() hash.Hash + blockKey []byte + block cipher.Block + maxLength int + maxAge int64 + minAge int64 + err error + sz Serializer + // For testing purposes, the function that returns the current timestamp. + // If not set, it will use time.Now().UTC().Unix(). + timeFunc func() int64 +} + +// Serializer provides an interface for providing custom serializers for cookie +// values. +type Serializer interface { + Serialize(src interface{}) ([]byte, error) + Deserialize(src []byte, dst interface{}) error +} + +// GobEncoder encodes cookie values using encoding/gob. This is the simplest +// encoder and can handle complex types via gob.Register. +type GobEncoder struct{} + +// JSONEncoder encodes cookie values using encoding/json. Users who wish to +// encode complex types need to satisfy the json.Marshaller and +// json.Unmarshaller interfaces. +type JSONEncoder struct{} + +// NopEncoder does not encode cookie values, and instead simply accepts a []byte +// (as an interface{}) and returns a []byte. This is particularly useful when +// you encoding an object upstream and do not wish to re-encode it. +type NopEncoder struct{} + +// MaxLength restricts the maximum length, in bytes, for the cookie value. +// +// Default is 4096, which is the maximum value accepted by Internet Explorer. +func (s *SecureCookie) MaxLength(value int) *SecureCookie { + s.maxLength = value + return s +} + +// MaxAge restricts the maximum age, in seconds, for the cookie value. +// +// Default is 86400 * 30. Set it to 0 for no restriction. +func (s *SecureCookie) MaxAge(value int) *SecureCookie { + s.maxAge = int64(value) + return s +} + +// MinAge restricts the minimum age, in seconds, for the cookie value. +// +// Default is 0 (no restriction). +func (s *SecureCookie) MinAge(value int) *SecureCookie { + s.minAge = int64(value) + return s +} + +// HashFunc sets the hash function used to create HMAC. +// +// Default is crypto/sha256.New. +func (s *SecureCookie) HashFunc(f func() hash.Hash) *SecureCookie { + s.hashFunc = f + return s +} + +// BlockFunc sets the encryption function used to create a cipher.Block. +// +// Default is crypto/aes.New. +func (s *SecureCookie) BlockFunc(f func([]byte) (cipher.Block, error)) *SecureCookie { + if s.blockKey == nil { + s.err = errBlockKeyNotSet + } else if block, err := f(s.blockKey); err == nil { + s.block = block + } else { + s.err = cookieError{cause: err, typ: usageError} + } + return s +} + +// Encoding sets the encoding/serialization method for cookies. +// +// Default is encoding/gob. To encode special structures using encoding/gob, +// they must be registered first using gob.Register(). +func (s *SecureCookie) SetSerializer(sz Serializer) *SecureCookie { + s.sz = sz + + return s +} + +// Encode encodes a cookie value. +// +// It serializes, optionally encrypts, signs with a message authentication code, +// and finally encodes the value. +// +// The name argument is the cookie name. It is stored with the encoded value. +// The value argument is the value to be encoded. It can be any value that can +// be encoded using the currently selected serializer; see SetSerializer(). +// +// It is the client's responsibility to ensure that value, when encoded using +// the current serialization/encryption settings on s and then base64-encoded, +// is shorter than the maximum permissible length. +func (s *SecureCookie) Encode(name string, value interface{}) (string, error) { + if s.err != nil { + return "", s.err + } + if s.hashKey == nil { + s.err = errHashKeyNotSet + return "", s.err + } + var err error + var b []byte + // 1. Serialize. + if b, err = s.sz.Serialize(value); err != nil { + return "", cookieError{cause: err, typ: usageError} + } + // 2. Encrypt (optional). + if s.block != nil { + if b, err = encrypt(s.block, b); err != nil { + return "", cookieError{cause: err, typ: usageError} + } + } + b = encode(b) + // 3. Create MAC for "name|date|value". Extra pipe to be used later. + b = []byte(fmt.Sprintf("%s|%d|%s|", name, s.timestamp(), b)) + mac := createMac(hmac.New(s.hashFunc, s.hashKey), b[:len(b)-1]) + // Append mac, remove name. + b = append(b, mac...)[len(name)+1:] + // 4. Encode to base64. + b = encode(b) + // 5. Check length. + if s.maxLength != 0 && len(b) > s.maxLength { + return "", errEncodedValueTooLong + } + // Done. + return string(b), nil +} + +// Decode decodes a cookie value. +// +// It decodes, verifies a message authentication code, optionally decrypts and +// finally deserializes the value. +// +// The name argument is the cookie name. It must be the same name used when +// it was stored. The value argument is the encoded cookie value. The dst +// argument is where the cookie will be decoded. It must be a pointer. +func (s *SecureCookie) Decode(name, value string, dst interface{}) error { + if s.err != nil { + return s.err + } + if s.hashKey == nil { + s.err = errHashKeyNotSet + return s.err + } + // 1. Check length. + if s.maxLength != 0 && len(value) > s.maxLength { + return errValueToDecodeTooLong + } + // 2. Decode from base64. + b, err := decode([]byte(value)) + if err != nil { + return err + } + // 3. Verify MAC. Value is "date|value|mac". + parts := bytes.SplitN(b, []byte("|"), 3) + if len(parts) != 3 { + return ErrMacInvalid + } + h := hmac.New(s.hashFunc, s.hashKey) + b = append([]byte(name+"|"), b[:len(b)-len(parts[2])-1]...) + if err = verifyMac(h, b, parts[2]); err != nil { + return err + } + // 4. Verify date ranges. + var t1 int64 + if t1, err = strconv.ParseInt(string(parts[0]), 10, 64); err != nil { + return errTimestampInvalid + } + t2 := s.timestamp() + if s.minAge != 0 && t1 > t2-s.minAge { + return errTimestampTooNew + } + if s.maxAge != 0 && t1 < t2-s.maxAge { + return errTimestampExpired + } + // 5. Decrypt (optional). + b, err = decode(parts[1]) + if err != nil { + return err + } + if s.block != nil { + if b, err = decrypt(s.block, b); err != nil { + return err + } + } + // 6. Deserialize. + if err = s.sz.Deserialize(b, dst); err != nil { + return cookieError{cause: err, typ: decodeError} + } + // Done. + return nil +} + +// timestamp returns the current timestamp, in seconds. +// +// For testing purposes, the function that generates the timestamp can be +// overridden. If not set, it will return time.Now().UTC().Unix(). +func (s *SecureCookie) timestamp() int64 { + if s.timeFunc == nil { + return time.Now().UTC().Unix() + } + return s.timeFunc() +} + +// Authentication ------------------------------------------------------------- + +// createMac creates a message authentication code (MAC). +func createMac(h hash.Hash, value []byte) []byte { + h.Write(value) + return h.Sum(nil) +} + +// verifyMac verifies that a message authentication code (MAC) is valid. +func verifyMac(h hash.Hash, value []byte, mac []byte) error { + mac2 := createMac(h, value) + // Check that both MACs are of equal length, as subtle.ConstantTimeCompare + // does not do this prior to Go 1.4. + if len(mac) == len(mac2) && subtle.ConstantTimeCompare(mac, mac2) == 1 { + return nil + } + return ErrMacInvalid +} + +// Encryption ----------------------------------------------------------------- + +// encrypt encrypts a value using the given block in counter mode. +// +// A random initialization vector (http://goo.gl/zF67k) with the length of the +// block size is prepended to the resulting ciphertext. +func encrypt(block cipher.Block, value []byte) ([]byte, error) { + iv := GenerateRandomKey(block.BlockSize()) + if iv == nil { + return nil, errGeneratingIV + } + // Encrypt it. + stream := cipher.NewCTR(block, iv) + stream.XORKeyStream(value, value) + // Return iv + ciphertext. + return append(iv, value...), nil +} + +// decrypt decrypts a value using the given block in counter mode. +// +// The value to be decrypted must be prepended by a initialization vector +// (http://goo.gl/zF67k) with the length of the block size. +func decrypt(block cipher.Block, value []byte) ([]byte, error) { + size := block.BlockSize() + if len(value) > size { + // Extract iv. + iv := value[:size] + // Extract ciphertext. + value = value[size:] + // Decrypt it. + stream := cipher.NewCTR(block, iv) + stream.XORKeyStream(value, value) + return value, nil + } + return nil, errDecryptionFailed +} + +// Serialization -------------------------------------------------------------- + +// Serialize encodes a value using gob. +func (e GobEncoder) Serialize(src interface{}) ([]byte, error) { + buf := new(bytes.Buffer) + enc := gob.NewEncoder(buf) + if err := enc.Encode(src); err != nil { + return nil, cookieError{cause: err, typ: usageError} + } + return buf.Bytes(), nil +} + +// Deserialize decodes a value using gob. +func (e GobEncoder) Deserialize(src []byte, dst interface{}) error { + dec := gob.NewDecoder(bytes.NewBuffer(src)) + if err := dec.Decode(dst); err != nil { + return cookieError{cause: err, typ: decodeError} + } + return nil +} + +// Serialize encodes a value using encoding/json. +func (e JSONEncoder) Serialize(src interface{}) ([]byte, error) { + buf := new(bytes.Buffer) + enc := json.NewEncoder(buf) + if err := enc.Encode(src); err != nil { + return nil, cookieError{cause: err, typ: usageError} + } + return buf.Bytes(), nil +} + +// Deserialize decodes a value using encoding/json. +func (e JSONEncoder) Deserialize(src []byte, dst interface{}) error { + dec := json.NewDecoder(bytes.NewReader(src)) + if err := dec.Decode(dst); err != nil { + return cookieError{cause: err, typ: decodeError} + } + return nil +} + +// Serialize passes a []byte through as-is. +func (e NopEncoder) Serialize(src interface{}) ([]byte, error) { + if b, ok := src.([]byte); ok { + return b, nil + } + + return nil, errValueNotByte +} + +// Deserialize passes a []byte through as-is. +func (e NopEncoder) Deserialize(src []byte, dst interface{}) error { + if dat, ok := dst.(*[]byte); ok { + *dat = src + return nil + } + return errValueNotBytePtr +} + +// Encoding ------------------------------------------------------------------- + +// encode encodes a value using base64. +func encode(value []byte) []byte { + encoded := make([]byte, base64.URLEncoding.EncodedLen(len(value))) + base64.URLEncoding.Encode(encoded, value) + return encoded +} + +// decode decodes a cookie using base64. +func decode(value []byte) ([]byte, error) { + decoded := make([]byte, base64.URLEncoding.DecodedLen(len(value))) + b, err := base64.URLEncoding.Decode(decoded, value) + if err != nil { + return nil, cookieError{cause: err, typ: decodeError, msg: "base64 decode failed"} + } + return decoded[:b], nil +} + +// Helpers -------------------------------------------------------------------- + +// GenerateRandomKey creates a random key with the given length in bytes. +// On failure, returns nil. +// +// Callers should explicitly check for the possibility of a nil return, treat +// it as a failure of the system random number generator, and not continue. +func GenerateRandomKey(length int) []byte { + k := make([]byte, length) + if _, err := io.ReadFull(rand.Reader, k); err != nil { + return nil + } + return k +} + +// CodecsFromPairs returns a slice of SecureCookie instances. +// +// It is a convenience function to create a list of codecs for key rotation. Note +// that the generated Codecs will have the default options applied: callers +// should iterate over each Codec and type-assert the underlying *SecureCookie to +// change these. +// +// Example: +// +// codecs := securecookie.CodecsFromPairs( +// []byte("new-hash-key"), +// []byte("new-block-key"), +// []byte("old-hash-key"), +// []byte("old-block-key"), +// ) +// +// // Modify each instance. +// for _, s := range codecs { +// if cookie, ok := s.(*securecookie.SecureCookie); ok { +// cookie.MaxAge(86400 * 7) +// cookie.SetSerializer(securecookie.JSONEncoder{}) +// cookie.HashFunc(sha512.New512_256) +// } +// } +// +func CodecsFromPairs(keyPairs ...[]byte) []Codec { + codecs := make([]Codec, len(keyPairs)/2+len(keyPairs)%2) + for i := 0; i < len(keyPairs); i += 2 { + var blockKey []byte + if i+1 < len(keyPairs) { + blockKey = keyPairs[i+1] + } + codecs[i/2] = New(keyPairs[i], blockKey) + } + return codecs +} + +// EncodeMulti encodes a cookie value using a group of codecs. +// +// The codecs are tried in order. Multiple codecs are accepted to allow +// key rotation. +// +// On error, may return a MultiError. +func EncodeMulti(name string, value interface{}, codecs ...Codec) (string, error) { + if len(codecs) == 0 { + return "", errNoCodecs + } + + var errors MultiError + for _, codec := range codecs { + encoded, err := codec.Encode(name, value) + if err == nil { + return encoded, nil + } + errors = append(errors, err) + } + return "", errors +} + +// DecodeMulti decodes a cookie value using a group of codecs. +// +// The codecs are tried in order. Multiple codecs are accepted to allow +// key rotation. +// +// On error, may return a MultiError. +func DecodeMulti(name string, value string, dst interface{}, codecs ...Codec) error { + if len(codecs) == 0 { + return errNoCodecs + } + + var errors MultiError + for _, codec := range codecs { + err := codec.Decode(name, value, dst) + if err == nil { + return nil + } + errors = append(errors, err) + } + return errors +} + +// MultiError groups multiple errors. +type MultiError []error + +func (m MultiError) IsUsage() bool { return m.any(func(e Error) bool { return e.IsUsage() }) } +func (m MultiError) IsDecode() bool { return m.any(func(e Error) bool { return e.IsDecode() }) } +func (m MultiError) IsInternal() bool { return m.any(func(e Error) bool { return e.IsInternal() }) } + +// Cause returns nil for MultiError; there is no unique underlying cause in the +// general case. +// +// Note: we could conceivably return a non-nil Cause only when there is exactly +// one child error with a Cause. However, it would be brittle for client code +// to rely on the arity of causes inside a MultiError, so we have opted not to +// provide this functionality. Clients which really wish to access the Causes +// of the underlying errors are free to iterate through the errors themselves. +func (m MultiError) Cause() error { return nil } + +func (m MultiError) Error() string { + s, n := "", 0 + for _, e := range m { + if e != nil { + if n == 0 { + s = e.Error() + } + n++ + } + } + switch n { + case 0: + return "(0 errors)" + case 1: + return s + case 2: + return s + " (and 1 other error)" + } + return fmt.Sprintf("%s (and %d other errors)", s, n-1) +} + +// any returns true if any element of m is an Error for which pred returns true. +func (m MultiError) any(pred func(Error) bool) bool { + for _, e := range m { + if ourErr, ok := e.(Error); ok && pred(ourErr) { + return true + } + } + return false +} diff --git a/vendor/modules.txt b/vendor/modules.txt new file mode 100644 index 0000000..88ea80b --- /dev/null +++ b/vendor/modules.txt @@ -0,0 +1,3 @@ +# github.com/gorilla/securecookie v1.1.1 +## explicit +github.com/gorilla/securecookie From a71a12f7d30580b6da2183b0f398527be93c0ca9 Mon Sep 17 00:00:00 2001 From: Apoorva Jagtap <35304110+apoorvajagtap@users.noreply.github.com> Date: Wed, 26 Jul 2023 19:33:29 +0530 Subject: [PATCH 43/48] updated licence (#167) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What type of PR is this? (check all applicable) - [ ] Refactor - [ ] Feature - [ ] Bug Fix - [ ] Optimization - [ ] Documentation Update ## Description ## Related Tickets & Documents - Related Issue # - Closes # ## Added/updated tests? - [ ] Yes - [ ] No, and this is why: _please replace this line with details on why tests have not been included_ - [ ] I need help with writing tests ## Run verifications and test - [ ] `make verify` is passing - [ ] `make test` is passing --- LICENSE | 47 ++++++++++++++++++++++++----------------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/LICENSE b/LICENSE index c1eb344..bb9d80b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,26 +1,27 @@ -Copyright (c) 2015-2018, The Gorilla Authors. All rights reserved. +Copyright (c) 2023 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: +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. + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. -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. +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 +OWNER 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. From 73c96a512fc353d11f3da50cffde1e454884f405 Mon Sep 17 00:00:00 2001 From: Corey Daley Date: Mon, 31 Jul 2023 03:43:02 -0400 Subject: [PATCH 44/48] Update issues.yml (#168) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What type of PR is this? (check all applicable) - [ ] Refactor - [ ] Feature - [ ] Bug Fix - [ ] Optimization - [ ] Documentation Update ## Description ## Related Tickets & Documents - Related Issue # - Closes # ## Added/updated tests? - [ ] Yes - [ ] No, and this is why: _please replace this line with details on why tests have not been included_ - [ ] I need help with writing tests ## Run verifications and test - [ ] `make verify` is passing - [ ] `make test` is passing Signed-off-by: Corey Daley --- .github/workflows/issues.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/issues.yml b/.github/workflows/issues.yml index 055ca82..8be6ced 100644 --- a/.github/workflows/issues.yml +++ b/.github/workflows/issues.yml @@ -5,9 +5,10 @@ on: issues: types: - opened - pull_request: + pull_request_target: types: - opened + - reopened jobs: add-to-project: @@ -17,4 +18,4 @@ jobs: uses: actions/add-to-project@v0.5.0 with: project-url: https://github.com/orgs/gorilla/projects/4 - github-token: ${{ secrets.ADD_TO_PROJECT_TOKEN }} \ No newline at end of file + github-token: ${{ secrets.ADD_TO_PROJECT_TOKEN }} From c1f4eb3aba6fe4cd0d1ef0ed5ca556876b14c29f Mon Sep 17 00:00:00 2001 From: Franco Posa Date: Thu, 17 Aug 2023 11:58:59 -0700 Subject: [PATCH 45/48] issues/158/examples for working api with javascript frontend (#162) Fixes #158, which is essentially that 1. none of the examples in the README for working with a JavaScript frontend will work without proper CORS config on the backend 2. there is no example at all for using the HTTP header instead of getting the CSRF token from the hidden form field **Summary of Changes** I have merged/copied over these simplified examples from my own repository of working examples. I was not sure how the maintainers may want to reference these examples in the main README. Copying them over to the README verbatim would be putting a lot of code into the README, but without changing the current README, the content there differs significantly from the examples. --------- Co-authored-by: Corey Daley --- examples/api-backends/README.md | 11 ++++ examples/api-backends/gorilla-mux/go.mod | 17 +++++ examples/api-backends/gorilla-mux/go.sum | 13 ++++ examples/api-backends/gorilla-mux/main.go | 66 +++++++++++++++++++ examples/javascript-frontends/README.md | 19 ++++++ .../example-frontend-server/go.mod | 10 +++ .../example-frontend-server/go.sum | 7 ++ .../example-frontend-server/main.go | 42 ++++++++++++ .../frontends/axios/index.html | 34 ++++++++++ .../frontends/axios/index.js | 50 ++++++++++++++ 10 files changed, 269 insertions(+) create mode 100644 examples/api-backends/README.md create mode 100644 examples/api-backends/gorilla-mux/go.mod create mode 100644 examples/api-backends/gorilla-mux/go.sum create mode 100644 examples/api-backends/gorilla-mux/main.go create mode 100644 examples/javascript-frontends/README.md create mode 100644 examples/javascript-frontends/example-frontend-server/go.mod create mode 100644 examples/javascript-frontends/example-frontend-server/go.sum create mode 100644 examples/javascript-frontends/example-frontend-server/main.go create mode 100644 examples/javascript-frontends/frontends/axios/index.html create mode 100644 examples/javascript-frontends/frontends/axios/index.js diff --git a/examples/api-backends/README.md b/examples/api-backends/README.md new file mode 100644 index 0000000..c2a8eb0 --- /dev/null +++ b/examples/api-backends/README.md @@ -0,0 +1,11 @@ +# API Backends + +Examples in this directory are intended to provide basic working backend CSRF-protected APIs, +compatible with the JavaScript frontend examples available in the +[`examples/javascript-frontends`](../javascript-frontends). + +In addition to CSRF protection, these backends provide the CORS configuration required for +communicating the CSRF cookies and headers with JavaScript client code running in the browser. + +See [`examples/javascript-frontends`](../javascript-frontends/README.md) for details on CORS and +CSRF configuration compatibility requirements. diff --git a/examples/api-backends/gorilla-mux/go.mod b/examples/api-backends/gorilla-mux/go.mod new file mode 100644 index 0000000..17e266f --- /dev/null +++ b/examples/api-backends/gorilla-mux/go.mod @@ -0,0 +1,17 @@ +// +build ignore + +module github.com/gorilla-mux/examples/api-backends/gorilla-mux + +go 1.20 + +require ( + github.com/gorilla/csrf v1.7.1 + github.com/gorilla/handlers v1.5.1 + github.com/gorilla/mux v1.8.0 +) + +require ( + github.com/felixge/httpsnoop v1.0.3 // indirect + github.com/gorilla/securecookie v1.1.1 // indirect + github.com/pkg/errors v0.9.1 // indirect +) diff --git a/examples/api-backends/gorilla-mux/go.sum b/examples/api-backends/gorilla-mux/go.sum new file mode 100644 index 0000000..8271f7f --- /dev/null +++ b/examples/api-backends/gorilla-mux/go.sum @@ -0,0 +1,13 @@ +github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= +github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/gorilla/csrf v1.7.1 h1:Ir3o2c1/Uzj6FBxMlAUB6SivgVMy1ONXwYgXn+/aHPE= +github.com/gorilla/csrf v1.7.1/go.mod h1:+a/4tCmqhG6/w4oafeAZ9pEa3/NZOWYVbD9fV0FwIQA= +github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= +github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= +github.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.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= diff --git a/examples/api-backends/gorilla-mux/main.go b/examples/api-backends/gorilla-mux/main.go new file mode 100644 index 0000000..849549a --- /dev/null +++ b/examples/api-backends/gorilla-mux/main.go @@ -0,0 +1,66 @@ +// +build ignore + +package main + +import ( + "fmt" + "log" + "net/http" + "os" + "strings" + "time" + + "github.com/gorilla/csrf" + "github.com/gorilla/handlers" + "github.com/gorilla/mux" +) + +func main() { + router := mux.NewRouter() + + loggingMiddleware := func(h http.Handler) http.Handler { + return handlers.LoggingHandler(os.Stdout, h) + } + router.Use(loggingMiddleware) + + CSRFMiddleware := csrf.Protect( + []byte("place-your-32-byte-long-key-here"), + csrf.Secure(false), // false in development only! + csrf.RequestHeader("X-CSRF-Token"), // Must be in CORS Allowed and Exposed Headers + ) + + APIRouter := router.PathPrefix("/api").Subrouter() + APIRouter.Use(CSRFMiddleware) + APIRouter.HandleFunc("", Get).Methods(http.MethodGet) + APIRouter.HandleFunc("", Post).Methods(http.MethodPost) + + CORSMiddleware := handlers.CORS( + handlers.AllowCredentials(), + handlers.AllowedOriginValidator( + func(origin string) bool { + return strings.HasPrefix(origin, "http://localhost") + }, + ), + handlers.AllowedHeaders([]string{"X-CSRF-Token"}), + handlers.ExposedHeaders([]string{"X-CSRF-Token"}), + ) + + server := &http.Server{ + Handler: CORSMiddleware(router), + Addr: "localhost:8080", + ReadTimeout: 60 * time.Second, + WriteTimeout: 60 * time.Second, + } + + fmt.Println("starting http server on localhost:8080") + log.Panic(server.ListenAndServe()) +} + +func Get(w http.ResponseWriter, r *http.Request) { + w.Header().Add("X-CSRF-Token", csrf.Token(r)) + w.WriteHeader(http.StatusOK) +} + +func Post(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) +} diff --git a/examples/javascript-frontends/README.md b/examples/javascript-frontends/README.md new file mode 100644 index 0000000..02a1de4 --- /dev/null +++ b/examples/javascript-frontends/README.md @@ -0,0 +1,19 @@ +# JavaScript Frontends + +Examples in this directory are intended to provide basic working frontend JavaScript, compatible +with the API backend examples available in the [`examples/api-backends`](../api-backends). + +## CSRF and CORS compatibility + +In order to be compatible with a CSRF-protected backend, frontend clients must: + +1. Be served from a domain allowed by the backend's CORS Allowed Origins configuration. + 1. `http://localhost*` for the backend examples provided + 2. An example server to serve the HTML and JavaScript for the frontend examples from localhost is included in + [`examples/javascript-frontends/example-frontend-server`](../javascript-frontends/example-frontend-server) +3. Use the HTTP headers expected by the backend to send and receive CSRF Tokens. + The backends configure this as the Gorilla `csrf.RequestHeader`, + as well as the CORS Allowed Headers and Exposed Headers. + 1. `X-CSRF-Token` for the backend examples provided + 2. Note that some JavaScript HTTP clients automatically lowercase all received headers, + so the values must be accessed with the key `"x-csrf-token"` in the frontend code. diff --git a/examples/javascript-frontends/example-frontend-server/go.mod b/examples/javascript-frontends/example-frontend-server/go.mod new file mode 100644 index 0000000..af48442 --- /dev/null +++ b/examples/javascript-frontends/example-frontend-server/go.mod @@ -0,0 +1,10 @@ +module github.com/gorilla-mux/examples/javascript-frontends/example-frontend-server + +go 1.20 + +require ( + github.com/gorilla/handlers v1.5.1 + github.com/gorilla/mux v1.8.0 +) + +require github.com/felixge/httpsnoop v1.0.3 // indirect diff --git a/examples/javascript-frontends/example-frontend-server/go.sum b/examples/javascript-frontends/example-frontend-server/go.sum new file mode 100644 index 0000000..1e9fd4d --- /dev/null +++ b/examples/javascript-frontends/example-frontend-server/go.sum @@ -0,0 +1,7 @@ +github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk= +github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= +github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= diff --git a/examples/javascript-frontends/example-frontend-server/main.go b/examples/javascript-frontends/example-frontend-server/main.go new file mode 100644 index 0000000..6cac20b --- /dev/null +++ b/examples/javascript-frontends/example-frontend-server/main.go @@ -0,0 +1,42 @@ +// +build ignore + +package main + +import ( + "fmt" + "log" + "net/http" + "os" + "time" + + "github.com/gorilla/handlers" + "github.com/gorilla/mux" +) + +func main() { + router := mux.NewRouter() + + loggingMiddleware := func(h http.Handler) http.Handler { + return handlers.LoggingHandler(os.Stdout, h) + } + router.Use(loggingMiddleware) + + wd, err := os.Getwd() + if err != nil { + log.Panic(err) + } + // change this directory to point at a different Javascript frontend to serve + httpStaticAssetsDir := http.Dir(fmt.Sprintf("%s/../frontends/axios/", wd)) + + router.PathPrefix("/").Handler(http.FileServer(httpStaticAssetsDir)) + + server := &http.Server{ + Handler: router, + Addr: "localhost:8081", + ReadTimeout: 60 * time.Second, + WriteTimeout: 60 * time.Second, + } + + fmt.Println("starting http server on localhost:8081") + log.Panic(server.ListenAndServe()) +} diff --git a/examples/javascript-frontends/frontends/axios/index.html b/examples/javascript-frontends/frontends/axios/index.html new file mode 100644 index 0000000..29ac9c0 --- /dev/null +++ b/examples/javascript-frontends/frontends/axios/index.html @@ -0,0 +1,34 @@ + + + + + Gorilla CSRF + + + +
+

Gorilla CSRF: Axios JS Frontend

+

See Console and Network tabs of your browser's Developer Tools for further details

+
+ +
+

Get Request:

+

Full Response:

+ +

CSRF Token:

+ +
+ + +
+

Post Request:

+

Full Response:

+

+ Note that the X-CSRF-Token value is in the Axios config.headers; + it is not a response header set by the server. +

+ +
+ + + \ No newline at end of file diff --git a/examples/javascript-frontends/frontends/axios/index.js b/examples/javascript-frontends/frontends/axios/index.js new file mode 100644 index 0000000..d931c58 --- /dev/null +++ b/examples/javascript-frontends/frontends/axios/index.js @@ -0,0 +1,50 @@ +// make GET request to backend on page load in order to obtain +// a CSRF Token and load it into the Axios instance's headers +// https://github.com/axios/axios#creating-an-instance +const initializeAxiosInstance = async (url) => { + try { + let resp = await axios.get(url, {withCredentials: true}); + console.log(resp); + document.getElementById("get-request-full-response").innerHTML = JSON.stringify(resp); + + let csrfToken = parseCSRFToken(resp); + console.log(csrfToken); + document.getElementById("get-response-csrf-token").innerHTML = csrfToken; + + return axios.create({ + // withCredentials must be true to in order for the browser + // to send cookies, which are necessary for CSRF verification + withCredentials: true, + headers: {"X-CSRF-Token": csrfToken} + }); + } catch (err) { + console.log(err); + } +}; + +const post = async (axiosInstance, url) => { + try { + let resp = await axiosInstance.post(url); + console.log(resp); + document.getElementById("post-request-full-response").innerHTML = JSON.stringify(resp); + } catch (err) { + console.log(err); + } +}; + +// general-purpose func to deal with clients like Axios, +// which lowercase all headers received from the server response +const parseCSRFToken = (resp) => { + let csrfToken = resp.headers[csrfTokenHeader]; + if (!csrfToken) { + csrfToken = resp.headers[csrfTokenHeader.toLowerCase()]; + } + return csrfToken +} + +const url = "http://localhost:8080/api"; +const csrfTokenHeader = "X-CSRF-Token"; +initializeAxiosInstance(url) + .then(axiosInstance => { + post(axiosInstance, url); + }); From 94b5a9efbc27ce51c4ac1b1287c964e8f13013ca Mon Sep 17 00:00:00 2001 From: Corey Daley Date: Wed, 18 Oct 2023 07:45:27 -0400 Subject: [PATCH 46/48] updating github action workflows (#169) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What type of PR is this? (check all applicable) - [x] Refactor - [ ] Feature - [ ] Bug Fix - [ ] Optimization - [ ] Documentation Update - [ ] Go Version Update - [ ] Dependency Update ## Description ## Related Tickets & Documents - Related Issue # - Closes # ## Added/updated tests? - [ ] Yes - [ ] No, and this is why: _please replace this line with details on why tests have not been included_ - [ ] I need help with writing tests ## Run verifications and test - [x] `make verify` is passing - [x] `make test` is passing --- .github/workflows/issues.yml | 2 +- .github/workflows/security.yml | 37 ++++++++++++++++++++++++++++++++++ .github/workflows/test.yml | 26 +++--------------------- .github/workflows/verify.yml | 32 +++++++++++++++++++++++++++++ go.mod | 2 +- 5 files changed, 74 insertions(+), 25 deletions(-) create mode 100644 .github/workflows/security.yml create mode 100644 .github/workflows/verify.yml diff --git a/.github/workflows/issues.yml b/.github/workflows/issues.yml index 8be6ced..768b05b 100644 --- a/.github/workflows/issues.yml +++ b/.github/workflows/issues.yml @@ -1,4 +1,4 @@ -# Add issues or pull-requests created to the project. +# Add all the issues created to the project. name: Add issue or pull request to Project on: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml new file mode 100644 index 0000000..ff4a613 --- /dev/null +++ b/.github/workflows/security.yml @@ -0,0 +1,37 @@ +name: Security +on: + push: + branches: + - main + pull_request: + branches: + - main +permissions: + contents: read +jobs: + scan: + strategy: + matrix: + go: ['1.20','1.21'] + fail-fast: true + runs-on: ubuntu-latest + steps: + - name: Checkout Code + uses: actions/checkout@v3 + + - name: Setup Go ${{ matrix.go }} + uses: actions/setup-go@v4 + with: + go-version: ${{ matrix.go }} + cache: false + + - name: Run GoSec + uses: securego/gosec@master + with: + args: -exclude-dir examples ./... + + - name: Run GoVulnCheck + uses: golang/govulncheck-action@v1 + with: + go-version-input: ${{ matrix.go }} + go-package: ./... diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f2e4b4d..50a3946 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,4 +1,4 @@ -name: CI +name: Test on: push: branches: @@ -6,15 +6,13 @@ on: pull_request: branches: - main - permissions: contents: read - jobs: - verify-and-test: + unit: strategy: matrix: - go: ['1.19','1.20'] + go: ['1.20','1.21'] os: [ubuntu-latest, macos-latest, windows-latest] fail-fast: true runs-on: ${{ matrix.os }} @@ -28,24 +26,6 @@ jobs: go-version: ${{ matrix.go }} cache: false - - name: Run GolangCI-Lint - uses: golangci/golangci-lint-action@v3 - with: - version: v1.53 - args: --timeout=5m - - - name: Run GoSec - if: matrix.os == 'ubuntu-latest' - uses: securego/gosec@master - with: - args: ./... - - - name: Run GoVulnCheck - uses: golang/govulncheck-action@v1 - with: - go-version-input: ${{ matrix.go }} - go-package: ./... - - name: Run Tests run: go test -race -cover -coverprofile=coverage -covermode=atomic -v ./... diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml new file mode 100644 index 0000000..a3eb74b --- /dev/null +++ b/.github/workflows/verify.yml @@ -0,0 +1,32 @@ +name: Verify +on: + push: + branches: + - main + pull_request: + branches: + - main +permissions: + contents: read +jobs: + lint: + strategy: + matrix: + go: ['1.20','1.21'] + fail-fast: true + runs-on: ubuntu-latest + steps: + - name: Checkout Code + uses: actions/checkout@v3 + + - name: Setup Go ${{ matrix.go }} + uses: actions/setup-go@v4 + with: + go-version: ${{ matrix.go }} + cache: false + + - name: Run GolangCI-Lint + uses: golangci/golangci-lint-action@v3 + with: + version: v1.53 + args: --timeout=5m diff --git a/go.mod b/go.mod index ebb010e..68e13f8 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,4 @@ module github.com/gorilla/csrf require github.com/gorilla/securecookie v1.1.1 -go 1.19 +go 1.20 From a009743572494ccbc9d159005bdc58b86a44ddba Mon Sep 17 00:00:00 2001 From: Corey Daley Date: Sat, 4 Nov 2023 22:08:39 -0400 Subject: [PATCH 47/48] Updating gorilla/securecookie to v1.1.2 (#170) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What type of PR is this? (check all applicable) - [ ] Refactor - [ ] Feature - [ ] Bug Fix - [ ] Optimization - [ ] Documentation Update - [ ] Go Version Update - [x] Dependency Update ## Description ## Related Tickets & Documents - Related Issue # - Closes # ## Added/updated tests? - [x] Yes - [ ] No, and this is why: _please replace this line with details on why tests have not been included_ - [ ] I need help with writing tests ## Run verifications and test - [x] `make verify` is passing - [x] `make test` is passing --- go.mod | 2 +- go.sum | 5 +- .../gorilla/securecookie/.editorconfig | 20 +++++ .../gorilla/securecookie/.gitignore | 1 + .../gorilla/securecookie/.travis.yml | 19 ----- .../github.com/gorilla/securecookie/LICENSE | 2 +- .../github.com/gorilla/securecookie/Makefile | 39 ++++++++++ .../github.com/gorilla/securecookie/README.md | 76 +++++++++++++++++-- .../github.com/gorilla/securecookie/fuzz.go | 25 ------ .../gorilla/securecookie/securecookie.go | 45 ++++++----- vendor/modules.txt | 4 +- 11 files changed, 161 insertions(+), 77 deletions(-) create mode 100644 vendor/github.com/gorilla/securecookie/.editorconfig create mode 100644 vendor/github.com/gorilla/securecookie/.gitignore delete mode 100644 vendor/github.com/gorilla/securecookie/.travis.yml create mode 100644 vendor/github.com/gorilla/securecookie/Makefile delete mode 100644 vendor/github.com/gorilla/securecookie/fuzz.go diff --git a/go.mod b/go.mod index 68e13f8..09c4174 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,5 @@ module github.com/gorilla/csrf -require github.com/gorilla/securecookie v1.1.1 +require github.com/gorilla/securecookie v1.1.2 go 1.20 diff --git a/go.sum b/go.sum index e6a7ed5..285ffee 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,3 @@ -github.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/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= +github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= diff --git a/vendor/github.com/gorilla/securecookie/.editorconfig b/vendor/github.com/gorilla/securecookie/.editorconfig new file mode 100644 index 0000000..2940ec9 --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/.editorconfig @@ -0,0 +1,20 @@ +; https://editorconfig.org/ + +root = true + +[*] +insert_final_newline = true +charset = utf-8 +trim_trailing_whitespace = true +indent_style = space +indent_size = 2 + +[{Makefile,go.mod,go.sum,*.go,.gitmodules}] +indent_style = tab +indent_size = 4 + +[*.md] +indent_size = 4 +trim_trailing_whitespace = false + +eclint_indent_style = unset diff --git a/vendor/github.com/gorilla/securecookie/.gitignore b/vendor/github.com/gorilla/securecookie/.gitignore new file mode 100644 index 0000000..84039fe --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/.gitignore @@ -0,0 +1 @@ +coverage.coverprofile diff --git a/vendor/github.com/gorilla/securecookie/.travis.yml b/vendor/github.com/gorilla/securecookie/.travis.yml deleted file mode 100644 index 6f440f1..0000000 --- a/vendor/github.com/gorilla/securecookie/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -language: go -sudo: false - -matrix: - include: - - go: 1.3 - - go: 1.4 - - go: 1.5 - - go: 1.6 - - go: 1.7 - - go: tip - allow_failures: - - go: tip - -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d .) - - go vet $(go list ./... | grep -v /vendor/) - - go test -v -race ./... diff --git a/vendor/github.com/gorilla/securecookie/LICENSE b/vendor/github.com/gorilla/securecookie/LICENSE index 0e5fb87..bb9d80b 100644 --- a/vendor/github.com/gorilla/securecookie/LICENSE +++ b/vendor/github.com/gorilla/securecookie/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2012 Rodrigo Moraes. All rights reserved. +Copyright (c) 2023 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 diff --git a/vendor/github.com/gorilla/securecookie/Makefile b/vendor/github.com/gorilla/securecookie/Makefile new file mode 100644 index 0000000..2b9008a --- /dev/null +++ b/vendor/github.com/gorilla/securecookie/Makefile @@ -0,0 +1,39 @@ +GO_LINT=$(shell which golangci-lint 2> /dev/null || echo '') +GO_LINT_URI=github.com/golangci/golangci-lint/cmd/golangci-lint@latest + +GO_SEC=$(shell which gosec 2> /dev/null || echo '') +GO_SEC_URI=github.com/securego/gosec/v2/cmd/gosec@latest + +GO_VULNCHECK=$(shell which govulncheck 2> /dev/null || echo '') +GO_VULNCHECK_URI=golang.org/x/vuln/cmd/govulncheck@latest + +.PHONY: golangci-lint +golangci-lint: + $(if $(GO_LINT), ,go install $(GO_LINT_URI)) + @echo "##### Running golangci-lint" + golangci-lint run -v + +.PHONY: gosec +gosec: + $(if $(GO_SEC), ,go install $(GO_SEC_URI)) + @echo "##### Running gosec" + gosec ./... + +.PHONY: govulncheck +govulncheck: + $(if $(GO_VULNCHECK), ,go install $(GO_VULNCHECK_URI)) + @echo "##### Running govulncheck" + govulncheck ./... + +.PHONY: verify +verify: golangci-lint gosec govulncheck + +.PHONY: test +test: + @echo "##### Running tests" + go test -race -cover -coverprofile=coverage.coverprofile -covermode=atomic -v ./... + +.PHONY: fuzz +fuzz: + @echo "##### Running fuzz tests" + go test -v -fuzz FuzzEncodeDecode -fuzztime 60s diff --git a/vendor/github.com/gorilla/securecookie/README.md b/vendor/github.com/gorilla/securecookie/README.md index aa7bd1a..c3b9815 100644 --- a/vendor/github.com/gorilla/securecookie/README.md +++ b/vendor/github.com/gorilla/securecookie/README.md @@ -1,10 +1,13 @@ -securecookie -============ -[![GoDoc](https://godoc.org/github.com/gorilla/securecookie?status.svg)](https://godoc.org/github.com/gorilla/securecookie) [![Build Status](https://travis-ci.org/gorilla/securecookie.png?branch=master)](https://travis-ci.org/gorilla/securecookie) -[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/securecookie/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/securecookie?badge) +# gorilla/securecookie +![testing](https://github.com/gorilla/securecookie/actions/workflows/test.yml/badge.svg) +[![codecov](https://codecov.io/github/gorilla/securecookie/branch/main/graph/badge.svg)](https://codecov.io/github/gorilla/securecookie) +[![godoc](https://godoc.org/github.com/gorilla/securecookie?status.svg)](https://godoc.org/github.com/gorilla/securecookie) +[![sourcegraph](https://sourcegraph.com/github.com/gorilla/securecookie/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/securecookie?badge) -securecookie encodes and decodes authenticated and optionally encrypted +![Gorilla Logo](https://github.com/gorilla/.github/assets/53367916/d92caabf-98e0-473e-bfbf-ab554ba435e5) + +securecookie encodes and decodes authenticated and optionally encrypted cookie values. Secure cookies can't be forged, because their values are validated using HMAC. @@ -33,7 +36,10 @@ to not use encryption. If set, the length must correspond to the block size of the encryption algorithm. For AES, used by default, valid lengths are 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. -Strong keys can be created using the convenience function GenerateRandomKey(). +Strong keys can be created using the convenience function +`GenerateRandomKey()`. Note that keys created using `GenerateRandomKey()` are not +automatically persisted. New keys will be created when the application is +restarted, and previously issued cookies will not be able to be decoded. Once a SecureCookie instance is set, use it to encode a cookie value: @@ -75,6 +81,64 @@ registered first using gob.Register(). For basic types this is not needed; it works out of the box. An optional JSON encoder that uses `encoding/json` is available for types compatible with JSON. +### Key Rotation +Rotating keys is an important part of any security strategy. The `EncodeMulti` and +`DecodeMulti` functions allow for multiple keys to be rotated in and out. +For example, let's take a system that stores keys in a map: + +```go +// keys stored in a map will not be persisted between restarts +// a more persistent storage should be considered for production applications. +var cookies = map[string]*securecookie.SecureCookie{ + "previous": securecookie.New( + securecookie.GenerateRandomKey(64), + securecookie.GenerateRandomKey(32), + ), + "current": securecookie.New( + securecookie.GenerateRandomKey(64), + securecookie.GenerateRandomKey(32), + ), +} +``` + +Using the current key to encode new cookies: +```go +func SetCookieHandler(w http.ResponseWriter, r *http.Request) { + value := map[string]string{ + "foo": "bar", + } + if encoded, err := securecookie.EncodeMulti("cookie-name", value, cookies["current"]); err == nil { + cookie := &http.Cookie{ + Name: "cookie-name", + Value: encoded, + Path: "/", + } + http.SetCookie(w, cookie) + } +} +``` + +Later, decode cookies. Check against all valid keys: +```go +func ReadCookieHandler(w http.ResponseWriter, r *http.Request) { + if cookie, err := r.Cookie("cookie-name"); err == nil { + value := make(map[string]string) + err = securecookie.DecodeMulti("cookie-name", cookie.Value, &value, cookies["current"], cookies["previous"]) + if err == nil { + fmt.Fprintf(w, "The value of foo is %q", value["foo"]) + } + } +} +``` + +Rotate the keys. This strategy allows previously issued cookies to be valid until the next rotation: +```go +func Rotate(newCookie *securecookie.SecureCookie) { + cookies["previous"] = cookies["current"] + cookies["current"] = newCookie +} +``` + ## License BSD licensed. See the LICENSE file for details. diff --git a/vendor/github.com/gorilla/securecookie/fuzz.go b/vendor/github.com/gorilla/securecookie/fuzz.go deleted file mode 100644 index e4d0534..0000000 --- a/vendor/github.com/gorilla/securecookie/fuzz.go +++ /dev/null @@ -1,25 +0,0 @@ -// +build gofuzz - -package securecookie - -var hashKey = []byte("very-secret12345") -var blockKey = []byte("a-lot-secret1234") -var s = New(hashKey, blockKey) - -type Cookie struct { - B bool - I int - S string -} - -func Fuzz(data []byte) int { - datas := string(data) - var c Cookie - if err := s.Decode("fuzz", datas, &c); err != nil { - return 0 - } - if _, err := s.Encode("fuzz", c); err != nil { - panic(err) - } - return 1 -} diff --git a/vendor/github.com/gorilla/securecookie/securecookie.go b/vendor/github.com/gorilla/securecookie/securecookie.go index cd4e097..4d5ea86 100644 --- a/vendor/github.com/gorilla/securecookie/securecookie.go +++ b/vendor/github.com/gorilla/securecookie/securecookie.go @@ -124,7 +124,7 @@ type Codec interface { // GenerateRandomKey(). It is recommended to use a key with 32 or 64 bytes. // // blockKey is optional, used to encrypt values. Create it using -// GenerateRandomKey(). The key length must correspond to the block size +// GenerateRandomKey(). The key length must correspond to the key size // of the encryption algorithm. For AES, used by default, valid lengths are // 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. // The default encoder used for cookie serialization is encoding/gob. @@ -141,7 +141,7 @@ func New(hashKey, blockKey []byte) *SecureCookie { maxLength: 4096, sz: GobEncoder{}, } - if hashKey == nil { + if len(hashKey) == 0 { s.err = errHashKeyNotSet } if blockKey != nil { @@ -286,7 +286,7 @@ func (s *SecureCookie) Encode(name string, value interface{}) (string, error) { b = encode(b) // 5. Check length. if s.maxLength != 0 && len(b) > s.maxLength { - return "", errEncodedValueTooLong + return "", fmt.Errorf("%s: %d", errEncodedValueTooLong, len(b)) } // Done. return string(b), nil @@ -310,7 +310,7 @@ func (s *SecureCookie) Decode(name, value string, dst interface{}) error { } // 1. Check length. if s.maxLength != 0 && len(value) > s.maxLength { - return errValueToDecodeTooLong + return fmt.Errorf("%s: %d", errValueToDecodeTooLong, len(value)) } // 2. Decode from base64. b, err := decode([]byte(value)) @@ -391,7 +391,7 @@ func verifyMac(h hash.Hash, value []byte, mac []byte) error { // encrypt encrypts a value using the given block in counter mode. // -// A random initialization vector (http://goo.gl/zF67k) with the length of the +// A random initialization vector ( https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Initialization_vector_(IV) ) with the length of the // block size is prepended to the resulting ciphertext. func encrypt(block cipher.Block, value []byte) ([]byte, error) { iv := GenerateRandomKey(block.BlockSize()) @@ -408,7 +408,7 @@ func encrypt(block cipher.Block, value []byte) ([]byte, error) { // decrypt decrypts a value using the given block in counter mode. // // The value to be decrypted must be prepended by a initialization vector -// (http://goo.gl/zF67k) with the length of the block size. +// ( https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Initialization_vector_(IV) ) with the length of the block size. func decrypt(block cipher.Block, value []byte) ([]byte, error) { size := block.BlockSize() if len(value) > size { @@ -506,6 +506,10 @@ func decode(value []byte) ([]byte, error) { // GenerateRandomKey creates a random key with the given length in bytes. // On failure, returns nil. // +// Note that keys created using `GenerateRandomKey()` are not automatically +// persisted. New keys will be created when the application is restarted, and +// previously issued cookies will not be able to be decoded. +// // Callers should explicitly check for the possibility of a nil return, treat // it as a failure of the system random number generator, and not continue. func GenerateRandomKey(length int) []byte { @@ -525,22 +529,21 @@ func GenerateRandomKey(length int) []byte { // // Example: // -// codecs := securecookie.CodecsFromPairs( -// []byte("new-hash-key"), -// []byte("new-block-key"), -// []byte("old-hash-key"), -// []byte("old-block-key"), -// ) -// -// // Modify each instance. -// for _, s := range codecs { -// if cookie, ok := s.(*securecookie.SecureCookie); ok { -// cookie.MaxAge(86400 * 7) -// cookie.SetSerializer(securecookie.JSONEncoder{}) -// cookie.HashFunc(sha512.New512_256) -// } -// } +// codecs := securecookie.CodecsFromPairs( +// []byte("new-hash-key"), +// []byte("new-block-key"), +// []byte("old-hash-key"), +// []byte("old-block-key"), +// ) // +// // Modify each instance. +// for _, s := range codecs { +// if cookie, ok := s.(*securecookie.SecureCookie); ok { +// cookie.MaxAge(86400 * 7) +// cookie.SetSerializer(securecookie.JSONEncoder{}) +// cookie.HashFunc(sha512.New512_256) +// } +// } func CodecsFromPairs(keyPairs ...[]byte) []Codec { codecs := make([]Codec, len(keyPairs)/2+len(keyPairs)%2) for i := 0; i < len(keyPairs); i += 2 { diff --git a/vendor/modules.txt b/vendor/modules.txt index 88ea80b..6224b61 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,3 +1,3 @@ -# github.com/gorilla/securecookie v1.1.1 -## explicit +# github.com/gorilla/securecookie v1.1.2 +## explicit; go 1.20 github.com/gorilla/securecookie From 9dd6af1f6d30fc79fb0d972394deebdabad6b5eb Mon Sep 17 00:00:00 2001 From: Patrick O'Doherty Date: Thu, 23 Jan 2025 12:14:50 -0800 Subject: [PATCH 48/48] Merge commit from fork * csrf: use context to determine TLS state r.URL.Scheme is never populated for "server" requests, and so the referer check never runs. Instead we now ask the caller application to signal this explicitly via request conext, and then enforce the check accordingly. Separately, browsers do not always send the full URL as a Referer, especially in the same-origin context meaning we cannot compare its host against our trusted origin list. If the referer does not contain a host we populate r.URL.Host with r.Host which is expected to be sent by all clients as the first header of their request. Add tests against the Origin header before attempting to enforce same-origin restrictions using the Referer header. Matching the Django CSRF behavior: if the Origin is present in either the cleartext or TLS case we will evaluate it. IFF we are in TLS and we have no Origin we will evaluate the Referer against the allowlist. In doing so we take care to permit "path only" Referers that are sent in same-origin context. * add csrf.TLSRequest helper API to set request TLS context Add a csrf.TLSRequest public API method that sets the appropriate TLS context key and signals to the midldeware the need to run the additiontal Referer checks. * Enable Referer-based origin checks by default Reverse the default position and presume that that the server is using TLS either directly or via an upstream proxy and require the user to explicitly disable referer-based checks. This safe default means that users that upgrade the library without making any other code changes will benefit from the Referer checks that they thought were active already. Without this change we risk that some codebases will mistakenly remain vulnerable even while using a patched version of the library. --- csrf.go | 89 ++++++++++--- csrf_test.go | 325 +++++++++++++++++++++++++++++++++--------------- helpers_test.go | 24 ++-- 3 files changed, 307 insertions(+), 131 deletions(-) diff --git a/csrf.go b/csrf.go index 97a3925..5dda254 100644 --- a/csrf.go +++ b/csrf.go @@ -1,10 +1,12 @@ package csrf import ( + "context" "errors" "fmt" "net/http" "net/url" + "slices" "github.com/gorilla/securecookie" ) @@ -22,6 +24,14 @@ const ( errorPrefix string = "gorilla/csrf: " ) +type contextKey string + +// PlaintextHTTPContextKey is the context key used to store whether the request +// is being served via plaintext HTTP. This is used to signal to the middleware +// that strict Referer checking should not be enforced as is done for HTTPS by +// default. +const PlaintextHTTPContextKey contextKey = "plaintext" + var ( // The name value used in form fields. fieldName = tokenKey @@ -41,6 +51,9 @@ var ( // ErrNoReferer is returned when a HTTPS request provides an empty Referer // header. ErrNoReferer = errors.New("referer not supplied") + // ErrBadOrigin is returned when the Origin header is present and is not a + // trusted origin. + ErrBadOrigin = errors.New("origin invalid") // ErrBadReferer is returned when the scheme & host in the URL do not match // the supplied Referer header. ErrBadReferer = errors.New("referer invalid") @@ -242,10 +255,50 @@ func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) { // 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" { + var isPlaintext bool + val := r.Context().Value(PlaintextHTTPContextKey) + if val != nil { + isPlaintext, _ = val.(bool) + } + + // take a copy of the request URL to avoid mutating the original + // attached to the request. + // set the scheme & host based on the request context as these are not + // populated by default for server requests + // ref: https://pkg.go.dev/net/http#Request + requestURL := *r.URL // shallow clone + + requestURL.Scheme = "https" + if isPlaintext { + requestURL.Scheme = "http" + } + if requestURL.Host == "" { + requestURL.Host = r.Host + } + + // if we have an Origin header, check it against our allowlist + origin := r.Header.Get("Origin") + if origin != "" { + parsedOrigin, err := url.Parse(origin) + if err != nil { + r = envError(r, ErrBadOrigin) + cs.opts.ErrorHandler.ServeHTTP(w, r) + return + } + if !sameOrigin(&requestURL, parsedOrigin) && !slices.Contains(cs.opts.TrustedOrigins, parsedOrigin.Host) { + r = envError(r, ErrBadOrigin) + cs.opts.ErrorHandler.ServeHTTP(w, r) + return + } + } + + // If we are serving via TLS and have no Origin header, prevent against + // CSRF via HTTP machine in the middle attacks by enforcing strict + // Referer origin checks. Consider an attacker who performs a + // successful HTTP Machine-in-the-Middle attack and uses this to inject + // a form and cause submission to our origin. We strictly disallow + // cleartext HTTP origins and evaluate the domain against an allowlist. + if origin == "" && !isPlaintext { // Fetch the Referer value. Call the error handler if it's empty or // otherwise fails to parse. referer, err := url.Parse(r.Referer()) @@ -255,18 +308,17 @@ func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - valid := sameOrigin(r.URL, referer) - - if !valid { - for _, trustedOrigin := range cs.opts.TrustedOrigins { - if referer.Host == trustedOrigin { - valid = true - break - } - } + // disallow cleartext HTTP referers when serving via TLS + if referer.Scheme == "http" { + r = envError(r, ErrBadReferer) + cs.opts.ErrorHandler.ServeHTTP(w, r) + return } - if !valid { + // If the request is being served via TLS and the Referer is not the + // same origin, check the domain against our allowlist. We only + // check when we have host information from the referer. + if referer.Host != "" && referer.Host != r.Host && !slices.Contains(cs.opts.TrustedOrigins, referer.Host) { r = envError(r, ErrBadReferer) cs.opts.ErrorHandler.ServeHTTP(w, r) return @@ -308,6 +360,15 @@ func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) { contextClear(r) } +// PlaintextHTTPRequest accepts as input a http.Request and returns a new +// http.Request with the PlaintextHTTPContextKey set to true. This is used to +// signal to the CSRF middleware that the request is being served over plaintext +// HTTP and that Referer-based origin allow-listing checks should be skipped. +func PlaintextHTTPRequest(r *http.Request) *http.Request { + ctx := context.WithValue(r.Context(), PlaintextHTTPContextKey, true) + return r.WithContext(ctx) +} + // unauthorizedhandler sets a HTTP 403 Forbidden status and writes the // CSRF failure reason to the response. func unauthorizedHandler(w http.ResponseWriter, r *http.Request) { diff --git a/csrf_test.go b/csrf_test.go index 0559a59..0281680 100644 --- a/csrf_test.go +++ b/csrf_test.go @@ -1,6 +1,7 @@ package csrf import ( + "fmt" "net/http" "net/http/httptest" "strings" @@ -16,10 +17,7 @@ func TestProtect(t *testing.T) { s := http.NewServeMux() s.HandleFunc("/", testHandler) - r, err := http.NewRequest("GET", "/", nil) - if err != nil { - t.Fatal(err) - } + r := createRequest("GET", "/", false) rr := httptest.NewRecorder() p := Protect(testKey)(s) @@ -46,10 +44,7 @@ func TestCookieOptions(t *testing.T) { s := http.NewServeMux() s.HandleFunc("/", testHandler) - r, err := http.NewRequest("GET", "/", nil) - if err != nil { - t.Fatal(err) - } + r := createRequest("GET", "/", false) rr := httptest.NewRecorder() p := Protect(testKey, CookieName("nameoverride"), Secure(false), HttpOnly(false), Path("/pathoverride"), Domain("domainoverride"), MaxAge(173))(s) @@ -86,10 +81,7 @@ func TestMethods(t *testing.T) { // Test idempontent ("safe") methods for _, method := range safeMethods { - r, err := http.NewRequest(method, "/", nil) - if err != nil { - t.Fatal(err) - } + r := createRequest(method, "/", false) rr := httptest.NewRecorder() p.ServeHTTP(rr, r) @@ -107,10 +99,7 @@ func TestMethods(t *testing.T) { // 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) - } + r := createRequest(method, "/", false) rr := httptest.NewRecorder() p.ServeHTTP(rr, r) @@ -133,10 +122,7 @@ func TestNoCookie(t *testing.T) { 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) - } + r := createRequest("POST", "/", false) rr := httptest.NewRecorder() p.ServeHTTP(rr, r) @@ -158,19 +144,13 @@ func TestBadCookie(t *testing.T) { })) // Obtain a CSRF cookie via a GET request. - r, err := http.NewRequest("GET", "http://www.gorillatoolkit.org/", nil) - if err != nil { - t.Fatal(err) - } + r := createRequest("GET", "/", false) 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) - } + r = createRequest("POST", "/", false) // Replace the cookie prefix badHeader := strings.Replace(cookieName+"=", rr.Header().Get("Set-Cookie"), "_badCookie", -1) @@ -193,10 +173,7 @@ func TestVaryHeader(t *testing.T) { s.HandleFunc("/", testHandler) p := Protect(testKey)(s) - r, err := http.NewRequest("HEAD", "https://www.golang.org/", nil) - if err != nil { - t.Fatal(err) - } + r := createRequest("GET", "/", true) rr := httptest.NewRecorder() p.ServeHTTP(rr, r) @@ -211,16 +188,13 @@ func TestVaryHeader(t *testing.T) { } } -// Requests with no Referer header should fail. +// TestNoReferer checks that HTTPS requests with no Referer header 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) - } + r := createRequest("POST", "https://golang.org/", true) rr := httptest.NewRecorder() p.ServeHTTP(rr, r) @@ -243,20 +217,12 @@ func TestBadReferer(t *testing.T) { })) // Obtain a CSRF cookie via a GET request. - r, err := http.NewRequest("GET", "https://www.gorillatoolkit.org/", nil) - if err != nil { - t.Fatal(err) - } - + r := createRequest("GET", "/", true) 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) - } - + r = createRequest("POST", "/", true) setCookie(rr, r) r.Header.Set("X-CSRF-Token", token) @@ -289,50 +255,47 @@ func TestTrustedReferer(t *testing.T) { } for _, item := range testTable { - s := http.NewServeMux() + t.Run(fmt.Sprintf("TrustedOrigin: %v", item.trustedOrigin), func(t *testing.T) { - p := Protect(testKey, TrustedOrigins(item.trustedOrigin))(s) + s := http.NewServeMux() - var token string - s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { - token = Token(r) - })) + p := Protect(testKey, TrustedOrigins(item.trustedOrigin))(s) - // Obtain a CSRF cookie via a GET request. - r, err := http.NewRequest("GET", "https://www.gorillatoolkit.org/", nil) - if err != nil { - t.Fatal(err) - } + var token string + s.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + token = Token(r) + })) - rr := httptest.NewRecorder() - p.ServeHTTP(rr, r) + // Obtain a CSRF cookie via a GET request. + r := createRequest("GET", "/", true) - // POST the token back in the header. - r, err = http.NewRequest("POST", "https://www.gorillatoolkit.org/", nil) - if err != nil { - t.Fatal(err) - } + rr := httptest.NewRecorder() + p.ServeHTTP(rr, r) - setCookie(rr, r) - r.Header.Set("X-CSRF-Token", token) + // POST the token back in the header. + r = createRequest("POST", "/", true) - // Set a non-matching Referer header. - r.Header.Set("Referer", "http://golang.org/") + setCookie(rr, r) + r.Header.Set("X-CSRF-Token", token) - rr = httptest.NewRecorder() - p.ServeHTTP(rr, r) + // Set a non-matching Referer header. + r.Header.Set("Referer", "https://golang.org/") - 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) + 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) + } } - } + }) } } @@ -347,23 +310,16 @@ func TestWithReferer(t *testing.T) { })) // Obtain a CSRF cookie via a GET request. - r, err := http.NewRequest("GET", "http://www.gorillatoolkit.org/", nil) - if err != nil { - t.Fatal(err) - } - + r := createRequest("GET", "/", true) 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) - } + r = createRequest("POST", "/", true) setCookie(rr, r) r.Header.Set("X-CSRF-Token", token) - r.Header.Set("Referer", "http://www.gorillatoolkit.org/") + r.Header.Set("Referer", "https://www.gorillatoolkit.org/") rr = httptest.NewRecorder() p.ServeHTTP(rr, r) @@ -387,26 +343,19 @@ func TestNoTokenProvided(t *testing.T) { s.Handle("/", http.HandlerFunc(func(_ 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) - } + r := createRequest("GET", "/", true) 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) - } + r = createRequest("POST", "/", true) setCookie(rr, r) // By accident we use the wrong header name for the token... r.Header.Set("X-CSRF-nekot", token) - r.Header.Set("Referer", "http://www.gorillatoolkit.org/") + r.Header.Set("Referer", "https://www.gorillatoolkit.org/") rr = httptest.NewRecorder() p.ServeHTTP(rr, r) @@ -419,3 +368,177 @@ func TestNoTokenProvided(t *testing.T) { func setCookie(rr *httptest.ResponseRecorder, r *http.Request) { r.Header.Set("Cookie", rr.Header().Get("Set-Cookie")) } + +func TestProtectScenarios(t *testing.T) { + tests := []struct { + name string + safeMethod bool + originUntrusted bool + originHTTP bool + originTrusted bool + secureRequest bool + refererTrusted bool + refererUntrusted bool + refererHTTPDowngrade bool + refererRelative bool + tokenValid bool + tokenInvalid bool + want bool + }{ + { + name: "safe method pass", + safeMethod: true, + want: true, + }, + { + name: "cleartext POST with trusted origin & valid token pass", + originHTTP: true, + tokenValid: true, + want: true, + }, + { + name: "cleartext POST with untrusted origin reject", + originUntrusted: true, + tokenValid: true, + }, + { + name: "cleartext POST with HTTP origin & invalid token reject", + originHTTP: true, + }, + { + name: "cleartext POST without origin with valid token pass", + tokenValid: true, + want: true, + }, + { + name: "cleartext POST without origin with invalid token reject", + }, + { + name: "TLS POST with HTTP origin & no referer & valid token reject", + tokenValid: true, + secureRequest: true, + originHTTP: true, + }, + { + name: "TLS POST without origin and without referer reject", + secureRequest: true, + tokenValid: true, + }, + { + name: "TLS POST without origin with untrusted referer reject", + secureRequest: true, + refererUntrusted: true, + tokenValid: true, + }, + { + name: "TLS POST without origin with trusted referer & valid token pass", + secureRequest: true, + refererTrusted: true, + tokenValid: true, + want: true, + }, + { + name: "TLS POST without origin from _cleartext_ same domain referer with valid token reject", + secureRequest: true, + refererHTTPDowngrade: true, + tokenValid: true, + }, + { + name: "TLS POST without origin from relative referer with valid token pass", + secureRequest: true, + refererRelative: true, + tokenValid: true, + want: true, + }, + { + name: "TLS POST without origin from relative referer with invalid token reject", + secureRequest: true, + refererRelative: true, + tokenInvalid: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var token string + var flag bool + mux := http.NewServeMux() + mux.Handle("/", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + token = Token(r) + })) + mux.Handle("/submit", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + flag = true + })) + p := Protect(testKey)(mux) + + // Obtain a CSRF cookie via a GET request. + r := createRequest("GET", "/", tt.secureRequest) + rr := httptest.NewRecorder() + p.ServeHTTP(rr, r) + + r = createRequest("POST", "/submit", tt.secureRequest) + if tt.safeMethod { + r = createRequest("GET", "/submit", tt.secureRequest) + } + + // Set the Origin header + switch { + case tt.originUntrusted: + r.Header.Set("Origin", "http://www.untrusted-origin.org") + case tt.originTrusted: + r.Header.Set("Origin", "https://www.gorillatoolkit.org") + case tt.originHTTP: + r.Header.Set("Origin", "http://www.gorillatoolkit.org") + } + + // Set the Referer header + switch { + case tt.refererTrusted: + p = Protect(testKey, TrustedOrigins([]string{"external-trusted-origin.test"}))(mux) + r.Header.Set("Referer", "https://external-trusted-origin.test/foobar") + case tt.refererUntrusted: + r.Header.Set("Referer", "http://www.invalid-referer.org") + case tt.refererHTTPDowngrade: + r.Header.Set("Referer", "http://www.gorillatoolkit.org/foobar") + case tt.refererRelative: + r.Header.Set("Referer", "/foobar") + } + + // Set the CSRF token & associated cookie + switch { + case tt.tokenInvalid: + setCookie(rr, r) + r.Header.Set("X-CSRF-Token", "this-is-an-invalid-token") + case tt.tokenValid: + setCookie(rr, r) + r.Header.Set("X-CSRF-Token", token) + } + + rr = httptest.NewRecorder() + p.ServeHTTP(rr, r) + + if tt.want && rr.Code != http.StatusOK { + t.Fatalf("middleware failed to pass to the next handler: got %v want %v", + rr.Code, http.StatusOK) + } + + if tt.want && !flag { + t.Fatalf("middleware failed to pass to the next handler: got %v want %v", + flag, true) + + } + if !tt.want && flag { + t.Fatalf("middleware failed to reject the request: got %v want %v", flag, false) + } + }) + } +} + +func createRequest(method, path string, useTLS bool) *http.Request { + r := httptest.NewRequest(method, path, nil) + r.Host = "www.gorillatoolkit.org" + if !useTLS { + return PlaintextHTTPRequest(r) + } + return r +} diff --git a/helpers_test.go b/helpers_test.go index 399db8d..f40c996 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -83,10 +83,7 @@ func TestMultipartFormToken(t *testing.T) { } })) - r, err := http.NewRequest("GET", "/", nil) - if err != nil { - t.Fatal(err) - } + r := createRequest("GET", "/", true) rr := httptest.NewRecorder() p := Protect(testKey)(s) @@ -107,13 +104,13 @@ func TestMultipartFormToken(t *testing.T) { mp.Close() - r, err = http.NewRequest("POST", "http://www.gorillatoolkit.org/", &b) - if err != nil { - t.Fatal(err) - } + r = httptest.NewRequest("POST", "/", &b) + r.Host = "www.gorillatoolkit.org" // Add the multipart header. r.Header.Set("Content-Type", mp.FormDataContentType()) + // Add Origin to pass the same-origin check. + r.Header.Set("Origin", "https://www.gorillatoolkit.org") // Send back the issued cookie. setCookie(rr, r) @@ -246,10 +243,8 @@ func TestTemplateField(t *testing.T) { })) testFieldName := "custom_field_name" - r, err := http.NewRequest("GET", "/", nil) - if err != nil { - t.Fatal(err) - } + r := createRequest("GET", "/", false) + // r, err := http.NewRequest("GET", "/", nil) rr := httptest.NewRecorder() p := Protect(testKey, FieldName(testFieldName))(s) @@ -299,10 +294,7 @@ func TestUnsafeSkipCSRFCheck(t *testing.T) { w.WriteHeader(teapot) })) - r, err := http.NewRequest("POST", "/", nil) - if err != nil { - t.Fatal(err) - } + r := createRequest("POST", "/", false) // Must be used prior to the CSRF handler being invoked. p := skipCheck(Protect(testKey)(s))