Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bugfix: correctly set a defaultMaxAge when MaxAge isn't called #120

Merged
merged 1 commit into from
Aug 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion options.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import "net/http"
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
Expand Down Expand Up @@ -118,6 +119,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
Expand Down
23 changes: 23 additions & 0 deletions options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})

}