Skip to content
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

feat(core): validate if access and id tokens are valid cognito tokens #13385

Merged
merged 12 commits into from
May 21, 2024
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { isValidCognitoToken } from '@aws-amplify/core/internals/utils';

import { createTokenValidator } from '../../src/utils/createTokenValidator';

jest.mock('@aws-amplify/core/internals/utils', () => ({
...jest.requireActual('@aws-amplify/core/internals/utils'),
isValidCognitoToken: jest.fn(),
}));
const mockIsValidCognitoToken = isValidCognitoToken as jest.Mock;

const userPoolId = 'userPoolId';
const userPoolClientId = 'clientId';
const tokenValidatorInput = {
userPoolId,
userPoolClientId,
};
const accessToken = {
key: 'CognitoIdentityServiceProvider.clientId.usersub.accessToken',
value:
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMTEiLCJpc3MiOiJodHRwc',
};
const idToken = {
key: 'CognitoIdentityServiceProvider.clientId.usersub.idToken',
value: 'eyJzdWIiOiIxMTEiLCJpc3MiOiJodHRwc.XAiOiJKV1QiLCJhbGciOiJIUzI1NiJ',
};

const tokenValidator = createTokenValidator({
userPoolId,
userPoolClientId,
});

describe('Validator', () => {
afterEach(() => {
jest.resetAllMocks();
});
it('should return a validator', () => {
expect(createTokenValidator(tokenValidatorInput)).toBeDefined();
});

it('should return true for non-token keys', async () => {
const result = await tokenValidator.getItem?.('mockKey', 'mockValue');
expect(result).toBe(true);
expect(mockIsValidCognitoToken).toHaveBeenCalledTimes(0);
});

it('should return true for valid accessToken', async () => {
mockIsValidCognitoToken.mockImplementation(() => Promise.resolve(true));

const result = await tokenValidator.getItem?.(
accessToken.key,
accessToken.value,
);

expect(result).toBe(true);
expect(mockIsValidCognitoToken).toHaveBeenCalledTimes(1);
expect(mockIsValidCognitoToken).toHaveBeenCalledWith({
userPoolId,
clientId: userPoolClientId,
token: accessToken.value,
tokenType: 'access',
});
});

it('should return true for valid idToken', async () => {
mockIsValidCognitoToken.mockImplementation(() => Promise.resolve(true));

const result = await tokenValidator.getItem?.(idToken.key, idToken.value);
expect(result).toBe(true);
expect(mockIsValidCognitoToken).toHaveBeenCalledTimes(1);
expect(mockIsValidCognitoToken).toHaveBeenCalledWith({
userPoolId,
clientId: userPoolClientId,
token: idToken.value,
tokenType: 'id',
});
});

it('should return false if invalid tokenType is access', async () => {
mockIsValidCognitoToken.mockImplementation(() => Promise.resolve(false));

const result = await tokenValidator.getItem?.(idToken.key, idToken.value);
expect(result).toBe(false);
expect(mockIsValidCognitoToken).toHaveBeenCalledTimes(1);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {

import { NextServer } from '../types';

import { createTokenValidator } from './createTokenValidator';
import { createCookieStorageAdapterFromNextServerContext } from './createCookieStorageAdapterFromNextServerContext';

export const createRunWithAmplifyServerContext = ({
Expand All @@ -34,6 +35,11 @@ export const createRunWithAmplifyServerContext = ({
createCookieStorageAdapterFromNextServerContext(
nextServerContext,
),
createTokenValidator({
userPoolId: resourcesConfig?.Auth.Cognito?.userPoolId,
userPoolClientId:
resourcesConfig?.Auth.Cognito?.userPoolClientId,
}),
);
const credentialsProvider = createAWSCredentialsAndIdentityIdProvider(
resourcesConfig.Auth,
Expand Down
37 changes: 37 additions & 0 deletions packages/adapter-nextjs/src/utils/createTokenValidator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { isValidCognitoToken } from '@aws-amplify/core/internals/utils';
import { KeyValueStorageMethodValidator } from '@aws-amplify/core/internals/adapter-core';

/**
* Creates a validator object for validating methods in a KeyValueStorage.
*/
export const createTokenValidator = ({
userPoolId,
userPoolClientId: clientId,
}: {
userPoolId: string | undefined;
userPoolClientId: string | undefined;
}): KeyValueStorageMethodValidator => {
ashwinkumar6 marked this conversation as resolved.
Show resolved Hide resolved
return {
// validate access, id tokens
getItem: async (key: string, value: string): Promise<boolean> => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The getItem method implies that it will get something but the return type is a boolean. We could either return the actual item/token and return null if it is invalid. The other option is to change the method name to something more deterministic that implies the validation of the token.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good point 🤔,
This function returns a validationMap where the key is name of the function in KeyValueStorage that we want to add validation for (getItem in this case) and the value is the validation function that returns a bool if the validation was successful or now

We could maybe improve the function name to clarity that

const tokenType = key.includes('.accessToken')
? 'access'
: key.includes('.idToken')
? 'id'
: null;
if (!tokenType) return true;

if (!userPoolId || !clientId) return false;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: we can require these two fields from createTokenValidator's consumer.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we make userPoolId and clientId required fields in this function, we would need make sure these are passed by it's consumer createRunWithAmplifyServerContext.

It's a bit tricky because if we add assertions in createRunWithAmplifyServerContext, we won't be able to get other keys from Storage if userPoolId or clientId are missing.


return isValidCognitoToken({
clientId,
userPoolId,
tokenType,
token: value,
});
},
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,44 @@ describe('keyValueStorage', () => {
}).toThrow('This method has not implemented.');
});
});

describe('in conjunction with token validator', () => {
const testKey = 'testKey';
const testValue = 'testValue';

beforeEach(() => {
mockCookiesStorageAdapter.get.mockReturnValueOnce({
name: testKey,
value: testValue,
});
});
afterEach(() => {
jest.clearAllMocks();
});

it('should return item successfully if validation passes when getting item', async () => {
const getItemValidator = jest.fn().mockImplementation(() => true);
const keyValueStorage = createKeyValueStorageFromCookieStorageAdapter(
mockCookiesStorageAdapter,
{ getItem: getItemValidator },
);

const value = await keyValueStorage.getItem(testKey);
expect(value).toBe(testValue);
expect(getItemValidator).toHaveBeenCalledTimes(1);
});

it('should return null if validation fails when getting item', async () => {
const getItemValidator = jest.fn().mockImplementation(() => false);
const keyValueStorage = createKeyValueStorageFromCookieStorageAdapter(
mockCookiesStorageAdapter,
{ getItem: getItemValidator },
);

const value = await keyValueStorage.getItem(testKey);
expect(value).toBe(null);
expect(getItemValidator).toHaveBeenCalledTimes(1);
});
});
});
});
56 changes: 28 additions & 28 deletions packages/aws-amplify/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -293,31 +293,31 @@
"name": "[Analytics] record (Pinpoint)",
"path": "./dist/esm/analytics/index.mjs",
"import": "{ record }",
"limit": "17.08 kB"
"limit": "17.23 kB"
ashwinkumar6 marked this conversation as resolved.
Show resolved Hide resolved
},
{
"name": "[Analytics] record (Kinesis)",
"path": "./dist/esm/analytics/kinesis/index.mjs",
"import": "{ record }",
"limit": "48.56 kB"
"limit": "48.67 kB"
},
{
"name": "[Analytics] record (Kinesis Firehose)",
"path": "./dist/esm/analytics/kinesis-firehose/index.mjs",
"import": "{ record }",
"limit": "45.68 kB"
"limit": "45.81 kB"
},
{
"name": "[Analytics] record (Personalize)",
"path": "./dist/esm/analytics/personalize/index.mjs",
"import": "{ record }",
"limit": "49.50 kB"
"limit": "49.63 kB"
},
{
"name": "[Analytics] identifyUser (Pinpoint)",
"path": "./dist/esm/analytics/index.mjs",
"import": "{ identifyUser }",
"limit": "15.57 kB"
"limit": "15.73 kB"
},
{
"name": "[Analytics] enable",
Expand All @@ -335,7 +335,7 @@
"name": "[API] generateClient (AppSync)",
"path": "./dist/esm/api/index.mjs",
"import": "{ generateClient }",
"limit": "40.09 kB"
"limit": "40.19 kB"
},
{
"name": "[API] REST API handlers",
Expand All @@ -353,13 +353,13 @@
"name": "[Auth] resetPassword (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ resetPassword }",
"limit": "12.44 kB"
"limit": "12.57 kB"
},
{
"name": "[Auth] confirmResetPassword (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ confirmResetPassword }",
"limit": "12.39 kB"
"limit": "12.51 kB"
},
{
"name": "[Auth] signIn (Cognito)",
Expand All @@ -371,7 +371,7 @@
"name": "[Auth] resendSignUpCode (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ resendSignUpCode }",
"limit": "12.40 kB"
"limit": "12.53 kB"
},
{
"name": "[Auth] confirmSignUp (Cognito)",
Expand All @@ -383,31 +383,31 @@
"name": "[Auth] confirmSignIn (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ confirmSignIn }",
"limit": "28.26 kB"
"limit": "28.42 kB"
},
{
"name": "[Auth] updateMFAPreference (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ updateMFAPreference }",
"limit": "11.74 kB"
"limit": "11.87 kB"
},
{
"name": "[Auth] fetchMFAPreference (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ fetchMFAPreference }",
"limit": "11.78 kB"
"limit": "11.90 kB"
},
{
"name": "[Auth] verifyTOTPSetup (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ verifyTOTPSetup }",
"limit": "12.59 kB"
"limit": "12.74 kB"
},
{
"name": "[Auth] updatePassword (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ updatePassword }",
"limit": "12.63 kB"
"limit": "12.76 kB"
},
{
"name": "[Auth] setUpTOTP (Cognito)",
Expand All @@ -419,85 +419,85 @@
"name": "[Auth] updateUserAttributes (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ updateUserAttributes }",
"limit": "11.87 kB"
"limit": "11.99 kB"
},
{
"name": "[Auth] getCurrentUser (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ getCurrentUser }",
"limit": "7.75 kB"
"limit": "7.89 kB"
},
{
"name": "[Auth] confirmUserAttribute (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ confirmUserAttribute }",
"limit": "12.61 kB"
"limit": "12.74 kB"
},
{
"name": "[Auth] signInWithRedirect (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ signInWithRedirect }",
"limit": "21.10 kB"
"limit": "21.18 kB"
},
{
"name": "[Auth] fetchUserAttributes (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ fetchUserAttributes }",
"limit": "11.69 kB"
"limit": "11.81 kB"
},
{
"name": "[Auth] Basic Auth Flow (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ signIn, signOut, fetchAuthSession, confirmSignIn }",
"limit": "30.06 kB"
"limit": "30.19 kB"
},
{
"name": "[Auth] OAuth Auth Flow (Cognito)",
"path": "./dist/esm/auth/index.mjs",
"import": "{ signInWithRedirect, signOut, fetchAuthSession }",
"limit": "21.47 kB"
"limit": "21.61 kB"
},
{
"name": "[Storage] copy (S3)",
"path": "./dist/esm/storage/index.mjs",
"import": "{ copy }",
"limit": "14.54 kB"
"limit": "14.65 kB"
},
{
"name": "[Storage] downloadData (S3)",
"path": "./dist/esm/storage/index.mjs",
"import": "{ downloadData }",
"limit": "15.17 kB"
"limit": "15.28 kB"
},
{
"name": "[Storage] getProperties (S3)",
"path": "./dist/esm/storage/index.mjs",
"import": "{ getProperties }",
"limit": "14.43 kB"
"limit": "14.54 kB"
},
{
"name": "[Storage] getUrl (S3)",
"path": "./dist/esm/storage/index.mjs",
"import": "{ getUrl }",
"limit": "15.51 kB"
"limit": "15.63 kB"
},
{
"name": "[Storage] list (S3)",
"path": "./dist/esm/storage/index.mjs",
"import": "{ list }",
"limit": "14.94 kB"
"limit": "15.05 kB"
},
{
"name": "[Storage] remove (S3)",
"path": "./dist/esm/storage/index.mjs",
"import": "{ remove }",
"limit": "14.29 kB"
"limit": "14.40 kB"
},
{
"name": "[Storage] uploadData (S3)",
"path": "./dist/esm/storage/index.mjs",
"import": "{ uploadData }",
"limit": "19.64 kB"
"limit": "19.74 kB"
}
]
}
Loading
Loading