Skip to content

feat(12820): implement crossTab auth events #14465

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { KeyValueStorageInterface } from '@aws-amplify/core';
import { decodeJWT } from '@aws-amplify/core/internals/utils';
import { Hub, KeyValueStorageInterface } from '@aws-amplify/core';
import { AMPLIFY_SYMBOL, decodeJWT } from '@aws-amplify/core/internals/utils';

import { DefaultTokenStore } from '../../../../src/providers/cognito/tokenProvider';
import {
AUTH_KEY_PREFIX,
DefaultTokenStore,
} from '../../../../src/providers/cognito/tokenProvider';

const userPoolId = 'us-west-1:0000523';
const userPoolClientId = 'mockCognitoUserPoolsId';
Expand All @@ -21,6 +24,9 @@ jest.mock(
TokenProviderErrorCode: 'mockErrorCode',
}),
);
jest.mock('../../../../src/providers/cognito/apis/getCurrentUser', () => ({
getCurrentUser: () => Promise.resolve({}),
}));

const mockedDecodeJWT = jest.mocked(decodeJWT);
mockedDecodeJWT.mockReturnValue({
Expand Down Expand Up @@ -72,6 +78,7 @@ const mockKeyValueStorage: jest.Mocked<KeyValueStorageInterface> = {
getItem: jest.fn(),
removeItem: jest.fn(),
clear: jest.fn(),
addListener: jest.fn(),
};

describe('TokenStore', () => {
Expand Down Expand Up @@ -403,4 +410,83 @@ describe('TokenStore', () => {
expect(finalTokens?.refreshToken).toBe(newMockAuthToken.refreshToken);
});
});

describe('setupNotify', () => {
it('should setup a KeyValueStorageEvent listener', async () => {
tokenStore.setupNotify();

const spy = jest.spyOn(keyValStorage, 'addListener');
const hubSpy = jest.spyOn(Hub, 'dispatch');

expect(spy).toHaveBeenCalledWith(expect.any(Function));

const listener = spy.mock.calls[0][0];

// does nothing if key does not match
await listener({
key: 'foo.bar',
oldValue: null,
newValue: null,
});

expect(hubSpy).not.toHaveBeenCalled();

// does nothing if both values are null
await listener({
key: `${AUTH_KEY_PREFIX}.someid.someotherId.refreshToken`,
oldValue: null,
newValue: null,
});

expect(hubSpy).not.toHaveBeenCalled();

// dispatches signedIn on new value
await listener({
key: `${AUTH_KEY_PREFIX}.someid.someotherId.refreshToken`,
newValue: '123',
oldValue: null,
});

expect(hubSpy).toHaveBeenCalledWith(
'auth',
{ event: 'signedIn', data: {} },
'Auth',
AMPLIFY_SYMBOL,
true,
);
hubSpy.mockClear();

// dispatches signedOut on null newValue
await listener({
key: `${AUTH_KEY_PREFIX}.someid.someotherId.refreshToken`,
newValue: null,
oldValue: '123',
});

expect(hubSpy).toHaveBeenCalledWith(
'auth',
{ event: 'signedOut' },
'Auth',
AMPLIFY_SYMBOL,
true,
);
hubSpy.mockClear();

// dispatches tokenRefresh for changed value
await listener({
key: `${AUTH_KEY_PREFIX}.someid.someotherId.refreshToken`,
newValue: '456',
oldValue: '123',
});

expect(hubSpy).toHaveBeenCalledWith(
'auth',
{ event: 'tokenRefresh' },
'Auth',
AMPLIFY_SYMBOL,
true,
);
hubSpy.mockClear();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export class CognitoUserPoolsTokenProvider
constructor() {
this.authTokenStore = new DefaultTokenStore();
this.authTokenStore.setKeyValueStorage(defaultStorage);
this.authTokenStore.setupNotify();
this.tokenOrchestrator = new TokenOrchestrator();
this.tokenOrchestrator.setAuthTokenStore(this.authTokenStore);
this.tokenOrchestrator.setTokenRefresher(refreshAuthTokens);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { AuthConfig, KeyValueStorageInterface } from '@aws-amplify/core';
import { AuthConfig, Hub, KeyValueStorageInterface } from '@aws-amplify/core';
import {
AMPLIFY_SYMBOL,
assertTokenProviderConfig,
decodeJWT,
} from '@aws-amplify/core/internals/utils';
import { KeyValueStorageEvent } from '@aws-amplify/core/src/types';

import { AuthError } from '../../../errors/AuthError';
import { getCurrentUser } from '../apis/getCurrentUser';

import {
AuthKeys,
Expand Down Expand Up @@ -42,6 +45,47 @@ export class DefaultTokenStore implements AuthTokenStore {
this.authConfig = authConfig;
}

setupNotify() {
this.keyValueStorage?.addListener?.(async (e: KeyValueStorageEvent) => {
const [key, , , id] = (e.key || '').split('.');
if (key === AUTH_KEY_PREFIX && id === 'refreshToken') {
const { newValue, oldValue } = e;
if (newValue && oldValue === null) {
Hub.dispatch(
'auth',
{
event: 'signedIn',
data: await getCurrentUser(),
},
'Auth',
AMPLIFY_SYMBOL,
true,
);
} else if (newValue === null && oldValue) {
Hub.dispatch(
'auth',
{
event: 'signedOut',
},
'Auth',
AMPLIFY_SYMBOL,
true,
);
} else if (newValue && oldValue) {
Hub.dispatch(
'auth',
{
event: 'tokenRefresh',
},
'Auth',
AMPLIFY_SYMBOL,
true,
);
}
}
});
}

async loadTokens(): Promise<CognitoAuthTokens | null> {
// TODO(v6): migration logic should be here
// Reading V5 tokens old format
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ import {
} from '@aws-amplify/core';
import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';

import { AUTH_KEY_PREFIX } from '../tokenProvider/constants';
import { getAuthStorageKeys } from '../tokenProvider/TokenStore';

import { OAuthStorageKeys, OAuthStore } from './types';

const V5_HOSTED_UI_KEY = 'amplify-signin-with-hostedUI';

const name = 'CognitoIdentityServiceProvider';
export class DefaultOAuthStore implements OAuthStore {
keyValueStorage: KeyValueStorageInterface;
cognitoConfig?: CognitoUserPoolConfig;
Expand All @@ -26,7 +26,7 @@ export class DefaultOAuthStore implements OAuthStore {
assertTokenProviderConfig(this.cognitoConfig);

const authKeys = createKeysForAuthStorage(
name,
AUTH_KEY_PREFIX,
this.cognitoConfig.userPoolClientId,
);
await Promise.all([
Expand All @@ -39,7 +39,7 @@ export class DefaultOAuthStore implements OAuthStore {
async clearOAuthData(): Promise<void> {
assertTokenProviderConfig(this.cognitoConfig);
const authKeys = createKeysForAuthStorage(
name,
AUTH_KEY_PREFIX,
this.cognitoConfig.userPoolClientId,
);
await this.clearOAuthInflightData();
Expand All @@ -52,7 +52,7 @@ export class DefaultOAuthStore implements OAuthStore {
assertTokenProviderConfig(this.cognitoConfig);

const authKeys = createKeysForAuthStorage(
name,
AUTH_KEY_PREFIX,
this.cognitoConfig.userPoolClientId,
);

Expand All @@ -63,7 +63,7 @@ export class DefaultOAuthStore implements OAuthStore {
assertTokenProviderConfig(this.cognitoConfig);

const authKeys = createKeysForAuthStorage(
name,
AUTH_KEY_PREFIX,
this.cognitoConfig.userPoolClientId,
);

Expand All @@ -74,7 +74,7 @@ export class DefaultOAuthStore implements OAuthStore {
assertTokenProviderConfig(this.cognitoConfig);

const authKeys = createKeysForAuthStorage(
name,
AUTH_KEY_PREFIX,
this.cognitoConfig.userPoolClientId,
);

Expand All @@ -85,7 +85,7 @@ export class DefaultOAuthStore implements OAuthStore {
assertTokenProviderConfig(this.cognitoConfig);

const authKeys = createKeysForAuthStorage(
name,
AUTH_KEY_PREFIX,
this.cognitoConfig.userPoolClientId,
);

Expand All @@ -100,7 +100,7 @@ export class DefaultOAuthStore implements OAuthStore {
assertTokenProviderConfig(this.cognitoConfig);

const authKeys = createKeysForAuthStorage(
name,
AUTH_KEY_PREFIX,
this.cognitoConfig.userPoolClientId,
);

Expand All @@ -112,7 +112,7 @@ export class DefaultOAuthStore implements OAuthStore {
async storeOAuthInFlight(inflight: boolean): Promise<void> {
assertTokenProviderConfig(this.cognitoConfig);
const authKeys = createKeysForAuthStorage(
name,
AUTH_KEY_PREFIX,
this.cognitoConfig.userPoolClientId,
);

Expand All @@ -126,7 +126,7 @@ export class DefaultOAuthStore implements OAuthStore {
assertTokenProviderConfig(this.cognitoConfig);

const authKeys = createKeysForAuthStorage(
name,
AUTH_KEY_PREFIX,
this.cognitoConfig.userPoolClientId,
);

Expand All @@ -151,7 +151,7 @@ export class DefaultOAuthStore implements OAuthStore {
assertTokenProviderConfig(this.cognitoConfig);

const authKeys = createKeysForAuthStorage(
name,
AUTH_KEY_PREFIX,
this.cognitoConfig.userPoolClientId,
);

Expand Down
10 changes: 5 additions & 5 deletions packages/aws-amplify/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@
"name": "[Analytics] record (Pinpoint)",
"path": "./dist/esm/analytics/index.mjs",
"import": "{ record }",
"limit": "18.10 kB"
"limit": "18.17 kB"
},
{
"name": "[Analytics] record (Kinesis)",
Expand Down Expand Up @@ -427,19 +427,19 @@
"name": "[Auth] setUpTOTP (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ setUpTOTP }",
"limit": "14 kB"
"limit": "14.08 kB"
},
{
"name": "[Auth] updateUserAttributes (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ updateUserAttributes }",
"limit": "13 kB"
"limit": "13.01 kB"
},
{
"name": "[Auth] getCurrentUser (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ getCurrentUser }",
"limit": "8.30 kB"
"limit": "8.37 kB"
},
{
"name": "[Auth] confirmUserAttribute (Cognito)",
Expand Down Expand Up @@ -493,7 +493,7 @@
"name": "[Storage] copy (S3)",
"path": "./dist/esm/storage/index.mjs",
"import": "{ copy }",
"limit": "17 kB"
"limit": "17.08 kB"
},
{
"name": "[Storage] downloadData (S3)",
Expand Down
Loading
Loading