Skip to content

Commit

Permalink
fix: remove cookies with max-age=0 from cookie store (#2275)
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito authored Sep 10, 2024
1 parent 1263c0f commit c307ab2
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
20 changes: 20 additions & 0 deletions src/core/utils/cookieStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ class WebStorageCookieStore extends Store {
callback: (error: Error | null) => void,
): void {
try {
// Never set cookies with `maxAge` of `0`.
if (cookie.maxAge === 0) {
return
}

const store = this.getStore()
store.push(cookie)
this.updateStore(store)
Expand All @@ -90,6 +95,21 @@ class WebStorageCookieStore extends Store {
newCookie: CookieInstance,
callback: (error: Error | null) => void,
): void {
/**
* If updating a cookie with `maxAge` of `0`, remove it from the store.
* Otherwise, two cookie entries will be created.
* @see https://github.com/mswjs/msw/issues/2272
*/
if (newCookie.maxAge === 0) {
this.removeCookie(
newCookie.domain || '',
newCookie.path || '',
newCookie.key,
callback,
)
return
}

this.putCookie(newCookie, callback)
}

Expand Down
28 changes: 27 additions & 1 deletion test/browser/rest-api/request/request-cookies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,6 @@ test('inherits mocked "HttpOnly" cookies', async ({
test('respects cookie "Path" when exposing cookies', async ({
loadExample,
fetch,
page,
}) => {
await loadExample(require.resolve('./request-cookies.mocks.ts'))

Expand All @@ -203,3 +202,30 @@ test('respects cookie "Path" when exposing cookies', async ({
mockedCookie: 'mockedValue',
})
})

test('deletes a cookie when sending "max-age=0" in a mocked response', async ({
loadExample,
fetch,
}) => {
await loadExample(require.resolve('./request-cookies.mocks.ts'))

// First, set the cookie.
await fetch('/set-cookies', {
method: 'POST',
body: `mockedCookie=mockedValue`,
})

// Must forward the mocked cookied to the matching request.
await expect(fetch('/cookies').then((res) => res.json())).resolves.toEqual({
mockedCookie: 'mockedValue',
})

// Next, delete the cookie by setting "max-age=0".
await fetch('/set-cookies', {
method: 'POST',
body: `mockedCookie=mockedValue; max-age=0`,
})

// Must NOT have any cookies on the matching request.
await expect(fetch('/cookies').then((res) => res.json())).resolves.toEqual({})
})

0 comments on commit c307ab2

Please sign in to comment.