Skip to content

Commit

Permalink
fix: incorrect handling of negative cookie.maxAge #1900 (#1902)
Browse files Browse the repository at this point in the history
  • Loading branch information
ksw2000 authored Nov 15, 2024
1 parent bbc2b6f commit ed2d390
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
17 changes: 14 additions & 3 deletions cookie.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ type Cookie struct {
bufK []byte
bufV []byte

// maxAge=0 means no 'max-age' attribute specified.
// maxAge<0 means delete cookie now, equivalently 'max-age=0'
// maxAge>0 means 'max-age' attribute present and given in seconds
maxAge int

sameSite CookieSameSite
Expand Down Expand Up @@ -193,7 +196,10 @@ func (c *Cookie) MaxAge() int {
// SetMaxAge sets cookie expiration time based on seconds. This takes precedence
// over any absolute expiry set on the cookie.
//
// Set max age to 0 to unset.
// 'max-age' is set when the maxAge is non-zero. That is, if maxAge = 0,
// the 'max-age' is unset. If maxAge < 0, it indicates that the cookie should
// be deleted immediately, equivalent to 'max-age=0'. This behavior is
// consistent with the Go standard library's net/http package.
func (c *Cookie) SetMaxAge(seconds int) {
c.maxAge = seconds
}
Expand Down Expand Up @@ -278,11 +284,16 @@ func (c *Cookie) AppendBytes(dst []byte) []byte {
}
dst = append(dst, c.value...)

if c.maxAge > 0 {
if c.maxAge != 0 {
dst = append(dst, ';', ' ')
dst = append(dst, strCookieMaxAge...)
dst = append(dst, '=')
dst = AppendUint(dst, c.maxAge)
if c.maxAge < 0 {
// See https://github.com/valyala/fasthttp/issues/1900
dst = AppendUint(dst, 0)
} else {
dst = AppendUint(dst, c.maxAge)
}
} else if !c.expire.IsZero() {
c.bufV = AppendHTTPDate(c.bufV[:0], c.expire)
dst = append(dst, ';', ' ')
Expand Down
7 changes: 7 additions & 0 deletions cookie_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,13 @@ func TestCookieMaxAge(t *testing.T) {
if s != "foo=bar; expires=Thu, 01 Jan 1970 00:01:40 GMT" {
t.Fatalf("missing expires %q", s)
}

c.SetMaxAge(-100)
result := strings.ToLower(c.String())
const expectedMaxAge0 = "max-age=0"
if !strings.Contains(result, expectedMaxAge0) {
t.Fatalf("Unexpected cookie %q. Should contain %q", result, expectedMaxAge0)
}
}

func TestCookieHttpOnly(t *testing.T) {
Expand Down

0 comments on commit ed2d390

Please sign in to comment.