Skip to content

Commit 7b29b05

Browse files
authored
bugfix: correctly set a defaultMaxAge when MaxAge isn't called (#120)
1 parent a7479e7 commit 7b29b05

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

options.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ import (
88
type Option func(*csrf)
99

1010
// MaxAge sets the maximum age (in seconds) of a CSRF token's underlying cookie.
11-
// Defaults to 12 hours.
11+
// Defaults to 12 hours. Call csrf.MaxAge(0) to explicitly set session-only
12+
// cookies.
1213
func MaxAge(age int) Option {
1314
return func(cs *csrf) {
1415
cs.opts.MaxAge = age
@@ -131,6 +132,9 @@ func parseOptions(h http.Handler, opts ...Option) *csrf {
131132
cs.opts.Secure = true
132133
cs.opts.HttpOnly = true
133134

135+
// Default; only override this if the package user explicitly calls MaxAge(0)
136+
cs.opts.MaxAge = defaultAge
137+
134138
// Range over each options function and apply it
135139
// to our csrf type to configure it. Options functions are
136140
// applied in order, with any conflicting options overriding

options_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,26 @@ func TestOptions(t *testing.T) {
7171
cs.opts.CookieName, name)
7272
}
7373
}
74+
75+
func TestMaxAge(t *testing.T) {
76+
t.Run("Ensure the default MaxAge is applied", func(t *testing.T) {
77+
handler := Protect(testKey)(nil)
78+
csrf := handler.(*csrf)
79+
cs := csrf.st.(*cookieStore)
80+
81+
if cs.maxAge != defaultAge {
82+
t.Fatalf("default maxAge not applied: got %d (want %d)", cs.maxAge, defaultAge)
83+
}
84+
})
85+
86+
t.Run("Support an explicit MaxAge of 0 (session-only)", func(t *testing.T) {
87+
handler := Protect(testKey, MaxAge(0))(nil)
88+
csrf := handler.(*csrf)
89+
cs := csrf.st.(*cookieStore)
90+
91+
if cs.maxAge != 0 {
92+
t.Fatalf("zero (0) maxAge not applied: got %d (want %d)", cs.maxAge, 0)
93+
}
94+
})
95+
96+
}

0 commit comments

Comments
 (0)