-
Notifications
You must be signed in to change notification settings - Fork 2.2k
feat(auth): multi-session multi-profile support (client + SSR) #14875
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
bobbor
wants to merge
5
commits into
main
Choose a base branch
from
auth/feat/multi-session-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
0df13cc
feat(core): add multi-session auth Hub events
bobbor 7700f22
feat(auth): add client-side multi-session support
bobbor 6594ef9
feat(auth): expose multi-session APIs for server-side rendering
bobbor 45360ae
chore(auth): add changeset for multi-session support
bobbor 2c52b05
fix(auth): address multi-session PR review feedback
bobbor File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| '@aws-amplify/auth': minor | ||
| '@aws-amplify/core': minor | ||
| 'aws-amplify': minor | ||
| --- | ||
|
|
||
| feat(auth): add multi-session multi-profile support. Introduces `setCurrentUser` and `listCurrentUsers` (client and server-side), an `AuthUserList` session roster alongside `LastAuthUser`, and boundary Hub events (`userSignedIn`, `switchActiveUser`, `userSignedOut`). Multiple Cognito users can be signed in simultaneously with one active session at a time. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
66 changes: 66 additions & 0 deletions
66
packages/auth/__tests__/providers/cognito/createAuthSessionSwitcher.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import { createAuthSessionSwitcher } from '../../../src/providers/cognito/tokenProvider/createAuthSessionSwitcher'; | ||
| import { USER_NOT_SIGNED_IN_EXCEPTION } from '../../../src/errors/constants'; | ||
|
|
||
| const mockGetAuthUserList = jest.fn(); | ||
| const mockGetStoredIdToken = jest.fn(); | ||
| const mockAddActiveSession = jest.fn(); | ||
| const mockStore = { | ||
| getAuthUserList: mockGetAuthUserList, | ||
| getStoredIdToken: mockGetStoredIdToken, | ||
| addActiveSession: mockAddActiveSession, | ||
| }; | ||
|
|
||
| describe('createAuthSessionSwitcher', () => { | ||
| beforeEach(() => { | ||
| mockAddActiveSession.mockResolvedValue(undefined); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| mockGetAuthUserList.mockReset(); | ||
| mockGetStoredIdToken.mockReset(); | ||
| mockAddActiveSession.mockReset(); | ||
| }); | ||
|
|
||
| it('listSessionUsernames delegates to the store roster read', async () => { | ||
| mockGetAuthUserList.mockResolvedValue(['alice', 'bob']); | ||
| const switcher = createAuthSessionSwitcher(mockStore); | ||
|
|
||
| await expect(switcher.listSessionUsernames()).resolves.toEqual([ | ||
| 'alice', | ||
| 'bob', | ||
| ]); | ||
| }); | ||
|
|
||
| it('getStoredIdToken delegates to the store', async () => { | ||
| const idToken = { payload: {}, toString: () => 'idToken' }; | ||
| mockGetStoredIdToken.mockResolvedValue(idToken); | ||
| const switcher = createAuthSessionSwitcher(mockStore); | ||
|
|
||
| await expect(switcher.getStoredIdToken('alice')).resolves.toBe(idToken); | ||
| expect(mockGetStoredIdToken).toHaveBeenCalledWith('alice'); | ||
| }); | ||
|
|
||
| it('setActiveSession throws when the username is absent and does not reorder', async () => { | ||
| mockGetAuthUserList.mockResolvedValue(['alice']); | ||
| const switcher = createAuthSessionSwitcher(mockStore); | ||
|
|
||
| await expect(switcher.setActiveSession('bob')).rejects.toMatchObject({ | ||
| name: USER_NOT_SIGNED_IN_EXCEPTION, | ||
| }); | ||
| // Non-destructive: never adds a non-signed-in user. | ||
| expect(mockAddActiveSession).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('setActiveSession reorders (non-destructively) when the username is present', async () => { | ||
| mockGetAuthUserList.mockResolvedValue(['alice', 'bob']); | ||
| const switcher = createAuthSessionSwitcher(mockStore); | ||
|
|
||
| await switcher.setActiveSession('bob'); | ||
|
|
||
| expect(mockAddActiveSession).toHaveBeenCalledWith('bob'); | ||
| expect(mockAddActiveSession).toHaveBeenCalledTimes(1); | ||
| }); | ||
| }); |
170 changes: 170 additions & 0 deletions
170
packages/auth/__tests__/providers/cognito/listCurrentUsers.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import { Amplify } from '@aws-amplify/core'; | ||
|
|
||
| import { listCurrentUsers } from '../../../src/providers/cognito/apis/listCurrentUsers'; | ||
| import { cognitoUserPoolsTokenProvider } from '../../../src/providers/cognito/tokenProvider'; | ||
|
|
||
| const userPoolClientId = '111111-aaaaa-42d8-891d-ee81a1549398'; | ||
| const authConfig = { | ||
| Cognito: { | ||
| userPoolClientId, | ||
| userPoolId: 'us-west-2_zzzzz', | ||
| }, | ||
| }; | ||
|
|
||
| cognitoUserPoolsTokenProvider.setAuthConfig(authConfig); | ||
| Amplify.configure({ | ||
| Auth: authConfig, | ||
| }); | ||
|
|
||
| const { authTokenStore } = cognitoUserPoolsTokenProvider; | ||
|
|
||
| const mockKeyValueStorage = { | ||
| getItem: jest.fn(), | ||
| setItem: jest.fn(), | ||
| removeItem: jest.fn(), | ||
| clear: jest.fn(), | ||
| }; | ||
|
|
||
| describe('listCurrentUsers', () => { | ||
| let getAuthUserListSpy: jest.SpyInstance; | ||
| let getStoredIdTokenSpy: jest.SpyInstance; | ||
| let loadTokensSpy: jest.SpyInstance; | ||
|
|
||
| beforeEach(() => { | ||
| jest | ||
| .spyOn(authTokenStore, 'getKeyValueStorage') | ||
| .mockReturnValue(mockKeyValueStorage); | ||
| getAuthUserListSpy = jest.spyOn(authTokenStore, 'getAuthUserList'); | ||
| getStoredIdTokenSpy = jest.spyOn(authTokenStore, 'getStoredIdToken'); | ||
| loadTokensSpy = jest.spyOn(authTokenStore, 'loadTokens'); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| jest.restoreAllMocks(); | ||
| mockKeyValueStorage.getItem.mockReset(); | ||
| }); | ||
|
|
||
| it('returns AuthUser[] resolved from stored id tokens in roster order', async () => { | ||
| getAuthUserListSpy.mockResolvedValue(['alice', 'bob']); | ||
| getStoredIdTokenSpy.mockImplementation((username: string) => | ||
| Promise.resolve({ | ||
| payload: { 'cognito:username': username, sub: `${username}-sub` }, | ||
| toString: () => `${username}-idToken`, | ||
| }), | ||
| ); | ||
|
|
||
| const result = await listCurrentUsers(); | ||
|
|
||
| expect(result).toEqual([ | ||
| { username: 'alice', userId: 'alice-sub' }, | ||
| { username: 'bob', userId: 'bob-sub' }, | ||
| ]); | ||
| }); | ||
|
|
||
| it('drops roster entries whose stored tokens cannot be resolved', async () => { | ||
| getAuthUserListSpy.mockResolvedValue(['alice', 'ghost', 'bob']); | ||
| getStoredIdTokenSpy.mockImplementation((username: string) => { | ||
| if (username === 'ghost') return Promise.resolve(undefined); | ||
|
|
||
| return Promise.resolve({ | ||
| payload: { 'cognito:username': username, sub: `${username}-sub` }, | ||
| toString: () => `${username}-idToken`, | ||
| }); | ||
| }); | ||
|
|
||
| const result = await listCurrentUsers(); | ||
|
|
||
| expect(result).toEqual([ | ||
| { username: 'alice', userId: 'alice-sub' }, | ||
| { username: 'bob', userId: 'bob-sub' }, | ||
| ]); | ||
| }); | ||
|
|
||
| it('drops roster entries whose stored id token lacks a `sub` claim', async () => { | ||
| getAuthUserListSpy.mockResolvedValue(['alice', 'nosub', 'bob']); | ||
| getStoredIdTokenSpy.mockImplementation((username: string) => { | ||
| if (username === 'nosub') { | ||
| return Promise.resolve({ | ||
| payload: { 'cognito:username': username }, | ||
| toString: () => `${username}-idToken`, | ||
| }); | ||
| } | ||
|
|
||
| return Promise.resolve({ | ||
| payload: { 'cognito:username': username, sub: `${username}-sub` }, | ||
| toString: () => `${username}-idToken`, | ||
| }); | ||
| }); | ||
|
|
||
| const result = await listCurrentUsers(); | ||
|
|
||
| expect(result).toEqual([ | ||
| { username: 'alice', userId: 'alice-sub' }, | ||
| { username: 'bob', userId: 'bob-sub' }, | ||
| ]); | ||
| }); | ||
|
|
||
| it('does not trigger a token refresh', async () => { | ||
| getAuthUserListSpy.mockResolvedValue(['alice']); | ||
| getStoredIdTokenSpy.mockResolvedValue({ | ||
| payload: { 'cognito:username': 'alice', sub: 'alice-sub' }, | ||
| toString: () => 'alice-idToken', | ||
| }); | ||
|
|
||
| await listCurrentUsers(); | ||
|
|
||
| // identities are read directly from stored tokens; loadTokens (which can | ||
| // drive a refresh) must not be invoked. | ||
| expect(loadTokensSpy).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('includes signInDetails when stored signInDetails key is present', async () => { | ||
| getAuthUserListSpy.mockResolvedValue(['alice']); | ||
| getStoredIdTokenSpy.mockResolvedValue({ | ||
| payload: { 'cognito:username': 'alice', sub: 'alice-sub' }, | ||
| toString: () => 'alice-idToken', | ||
| }); | ||
|
|
||
| const signInDetails = { | ||
| loginId: 'alice@example.com', | ||
| authFlowType: 'USER_SRP_AUTH', | ||
| }; | ||
| mockKeyValueStorage.getItem.mockImplementation((key: string) => { | ||
| if (key.endsWith('.signInDetails')) { | ||
| return Promise.resolve(JSON.stringify(signInDetails)); | ||
| } | ||
|
|
||
| return Promise.resolve(null); | ||
| }); | ||
|
|
||
| const result = await listCurrentUsers(); | ||
|
|
||
| expect(result).toEqual([ | ||
| { | ||
| username: 'alice', | ||
| userId: 'alice-sub', | ||
| signInDetails, | ||
| }, | ||
| ]); | ||
| }); | ||
|
|
||
| it('still returns the user when signInDetails read fails', async () => { | ||
| getAuthUserListSpy.mockResolvedValue(['alice']); | ||
| getStoredIdTokenSpy.mockResolvedValue({ | ||
| payload: { 'cognito:username': 'alice', sub: 'alice-sub' }, | ||
| toString: () => 'alice-idToken', | ||
| }); | ||
|
|
||
| // signInDetails key returns invalid JSON — parse will throw, but the | ||
| // implementation currently only reads it conditionally so it may return | ||
| // null. Either way the user should still be resolvable. | ||
| mockKeyValueStorage.getItem.mockResolvedValue(null); | ||
|
|
||
| const result = await listCurrentUsers(); | ||
|
|
||
| expect(result).toEqual([{ username: 'alice', userId: 'alice-sub' }]); | ||
| }); | ||
| }); | ||
90 changes: 90 additions & 0 deletions
90
packages/auth/__tests__/providers/cognito/server/listCurrentUsers.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import { getAmplifyServerContext } from '@aws-amplify/core/internals/adapter-core'; | ||
|
|
||
| import { listCurrentUsers } from '../../../../src/providers/cognito/apis/server/listCurrentUsers'; | ||
|
|
||
| jest.mock('@aws-amplify/core/internals/adapter-core'); | ||
|
|
||
| const mockGetAmplifyServerContext = jest.mocked(getAmplifyServerContext); | ||
| const mockListSessionUsernames = jest.fn(); | ||
| const mockGetStoredIdToken = jest.fn(); | ||
| const mockSwitcher = { | ||
| listSessionUsernames: mockListSessionUsernames, | ||
| getStoredIdToken: mockGetStoredIdToken, | ||
| setActiveSession: jest.fn(), | ||
| }; | ||
| const mockGetTokenProvider = jest.fn(); | ||
| const mockContextSpec = { token: { value: Symbol('test') } } as any; | ||
|
|
||
| const idToken = (username: string) => ({ | ||
| payload: { 'cognito:username': username, sub: `${username}-sub` }, | ||
| toString: () => `${username}-idToken`, | ||
| }); | ||
|
|
||
| describe('server-side listCurrentUsers', () => { | ||
| beforeEach(() => { | ||
| mockGetTokenProvider.mockReturnValue({ | ||
| getTokens: jest.fn(), | ||
| getSessionSwitcher: () => mockSwitcher, | ||
| }); | ||
| mockGetAmplifyServerContext.mockReturnValue({ | ||
| amplify: { | ||
| Auth: { getTokenProvider: mockGetTokenProvider }, | ||
| }, | ||
| } as any); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| it('returns AuthUser[] resolved from stored id tokens in roster order', async () => { | ||
| mockListSessionUsernames.mockResolvedValue(['alice', 'bob']); | ||
| mockGetStoredIdToken.mockImplementation((username: string) => | ||
| Promise.resolve(idToken(username)), | ||
| ); | ||
|
|
||
| await expect(listCurrentUsers(mockContextSpec)).resolves.toEqual([ | ||
| { username: 'alice', userId: 'alice-sub' }, | ||
| { username: 'bob', userId: 'bob-sub' }, | ||
| ]); | ||
| }); | ||
|
|
||
| it('drops roster entries whose stored id token cannot be resolved', async () => { | ||
| mockListSessionUsernames.mockResolvedValue(['alice', 'ghost', 'bob']); | ||
| mockGetStoredIdToken.mockImplementation((username: string) => | ||
| Promise.resolve(username === 'ghost' ? undefined : idToken(username)), | ||
| ); | ||
|
|
||
| await expect(listCurrentUsers(mockContextSpec)).resolves.toEqual([ | ||
| { username: 'alice', userId: 'alice-sub' }, | ||
| { username: 'bob', userId: 'bob-sub' }, | ||
| ]); | ||
| }); | ||
|
|
||
| it('drops roster entries whose stored id token lacks a `sub` claim', async () => { | ||
| mockListSessionUsernames.mockResolvedValue(['alice', 'nosub', 'bob']); | ||
| mockGetStoredIdToken.mockImplementation((username: string) => | ||
| Promise.resolve( | ||
| username === 'nosub' | ||
| ? { payload: { 'cognito:username': 'nosub' }, toString: () => 'x' } | ||
| : idToken(username), | ||
| ), | ||
| ); | ||
|
|
||
| await expect(listCurrentUsers(mockContextSpec)).resolves.toEqual([ | ||
| { username: 'alice', userId: 'alice-sub' }, | ||
| { username: 'bob', userId: 'bob-sub' }, | ||
| ]); | ||
| }); | ||
|
|
||
| it('throws when the context has no session-switching token provider', async () => { | ||
| mockGetTokenProvider.mockReturnValue(undefined); | ||
|
|
||
| await expect(listCurrentUsers(mockContextSpec)).rejects.toMatchObject({ | ||
| name: 'TokenProviderNotFoundException', | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nit] No test covers the
signInDetailsbranch (the storedsignInDetailskey being present and populated on the returnedAuthUser). Worth adding one case — the path is a distinct storage read that can fail independently of the idToken read.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added — one test with stored
signInDetailspopulated on the returnedAuthUser, one where the read fails and the user is still returned without it. Fixed in 2c52b05.