From 710327dc57a20c0809e7e3b808813cb02bc5d331 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Thu, 11 Jul 2024 10:46:31 -0700 Subject: [PATCH] Delete cookie without path attr before setting it --- ...eyValueStorageFromCookieStorageAdapter.test.ts | 15 +++++++++++++++ ...eateKeyValueStorageFromCookieStorageAdapter.ts | 5 +++++ 2 files changed, 20 insertions(+) diff --git a/packages/aws-amplify/__tests__/adapterCore/storageFactories/createKeyValueStorageFromCookieStorageAdapter.test.ts b/packages/aws-amplify/__tests__/adapterCore/storageFactories/createKeyValueStorageFromCookieStorageAdapter.test.ts index eae5ffe22a8..f2b900bfa87 100644 --- a/packages/aws-amplify/__tests__/adapterCore/storageFactories/createKeyValueStorageFromCookieStorageAdapter.test.ts +++ b/packages/aws-amplify/__tests__/adapterCore/storageFactories/createKeyValueStorageFromCookieStorageAdapter.test.ts @@ -40,6 +40,21 @@ describe('keyValueStorage', () => { ); }); + it('should remove item before setting item', async () => { + const testKey = 'testKey'; + const testValue = 'testValue'; + keyValueStorage.setItem(testKey, testValue); + expect(mockCookiesStorageAdapter.delete).toHaveBeenCalledWith(testKey); + expect(mockCookiesStorageAdapter.set).toHaveBeenCalledWith( + testKey, + testValue, + { + ...defaultSetCookieOptions, + expires: expect.any(Date), + }, + ); + }); + it('should set item with options', async () => { const testKey = 'testKey'; const testValue = 'testValue'; diff --git a/packages/aws-amplify/src/adapter-core/storageFactories/createKeyValueStorageFromCookieStorageAdapter.ts b/packages/aws-amplify/src/adapter-core/storageFactories/createKeyValueStorageFromCookieStorageAdapter.ts index 54e9a80dc58..dc6bd80fccf 100644 --- a/packages/aws-amplify/src/adapter-core/storageFactories/createKeyValueStorageFromCookieStorageAdapter.ts +++ b/packages/aws-amplify/src/adapter-core/storageFactories/createKeyValueStorageFromCookieStorageAdapter.ts @@ -27,6 +27,11 @@ export const createKeyValueStorageFromCookieStorageAdapter = ( ): KeyValueStorageInterface => { return { setItem(key, value) { + // Delete the cookie item first then set it. This results: + // SetCookie: key=;expires=1970-01-01;(path='current-path') <- remove path'ed cookies + // SetCookie: key=value;expires=Date.now() + 365 days;path=/;secure=true + cookieStorageAdapter.delete(key); + // TODO(HuiSF): follow up the default CookieSerializeOptions values cookieStorageAdapter.set(key, value, { ...defaultSetCookieOptions,