From 7b29b05df5ae7dc777b92fab3dadee1b15d15ed6 Mon Sep 17 00:00:00 2001 From: Matt Silverlock Date: Sun, 25 Aug 2019 17:41:49 -0700 Subject: [PATCH] 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) + } + }) + +}