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: user agent enhancements - auth reduction #11465

Merged
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
18 changes: 17 additions & 1 deletion packages/amazon-cognito-identity-js/__tests__/Client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ import Client from '../src/Client';
import { promisifyCallback } from './util';
import { region, endpoint, networkError } from './constants';
import { netRequestMockSuccess } from '../__mocks__/mocks';
import {
addAuthCategoryToCognitoUserAgent,
addFrameworkToCognitoUserAgent,
} from '../src/UserAgent';
import { getUserAgent } from '../src/Platform';

describe('Client unit test suite', () => {
beforeAll(() => {
Expand Down Expand Up @@ -38,7 +43,10 @@ describe('Client unit test suite', () => {
});

test('Happy case for request', async () => {
jest.spyOn(window, 'fetch');
const fetchSpy = jest.spyOn(window, 'fetch');

addAuthCategoryToCognitoUserAgent();
addFrameworkToCognitoUserAgent('0');

window.fetch.mockResolvedValueOnce({
ok: true,
Expand All @@ -48,6 +56,14 @@ describe('Client unit test suite', () => {
await promisifyCallback(client, 'request', '', {}).then(res => {
expect(res).toMatchObject({ endpoint: endpoint });
});
expect(fetchSpy).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
headers: expect.objectContaining({
'X-Amz-User-Agent': `${getUserAgent()} auth framework/0`,
}),
})
);
});

test('Network Error case for request', async () => {
Expand Down
182 changes: 0 additions & 182 deletions packages/amazon-cognito-identity-js/__tests__/CognitoUser.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ import Client from '../src/Client';
import CognitoIdToken from '../src/CognitoIdToken';
import CognitoAccessToken from '../src/CognitoAccessToken';
import CognitoRefreshToken from '../src/CognitoRefreshToken';
import { getUserAgent } from '../src/Platform';
import { AuthAction } from '../src/Platform/constants';
import { addAuthCategoryToCognitoUserAgent } from '../src/UserAgent';

import {
callback,
Expand Down Expand Up @@ -187,31 +184,6 @@ describe('initiateAuth()', () => {
expect(cacheTokensSpy).toBeCalled();
expect(callback.onSuccess.mock.calls.length).toBe(1);
});

test('global fetch called with expected user agent header InitiateAuth', () => {
const fetchMock = jest
.spyOn(global, 'fetch')
.mockImplementation(() =>
Promise.resolve({ json: () => Promise.resolve([]) })
);

addAuthCategoryToCognitoUserAgent();

const authDetails = new AuthenticationDetails(authDetailData);
user.initiateAuth(authDetails, callback);

expect(global.fetch.mock.calls.length).toBe(1);
expect(fetchMock).toBeCalledWith(
expect.anything(),
expect.objectContaining({
headers: expect.objectContaining({
'X-Amz-User-Agent': `${getUserAgent()} auth/${
AuthAction.InitiateAuth
}`,
}),
})
);
});
});

describe('authenticateUser()', () => {
Expand Down Expand Up @@ -253,31 +225,6 @@ describe('authenticateUser()', () => {
user.authenticateUser(authDetails, callback);
expect(callback.onFailure.mock.calls.length).toBe(1);
});

test('global fetch called with expected user agent header InitiateAuth', () => {
const fetchMock = jest
.spyOn(global, 'fetch')
.mockImplementation(() =>
Promise.resolve({ json: () => Promise.resolve([]) })
);

addAuthCategoryToCognitoUserAgent();

user.setAuthenticationFlowType('USER_PASSWORD_AUTH');
user.authenticateUser(authDetails, callback);

expect(global.fetch.mock.calls.length).toBe(1);
expect(fetchMock).toBeCalledWith(
expect.anything(),
expect.objectContaining({
headers: expect.objectContaining({
'X-Amz-User-Agent': `${getUserAgent()} auth/${
AuthAction.InitiateAuth
}`,
}),
})
);
});
});

describe('authenticateUserDefaultAuth()', () => {
Expand Down Expand Up @@ -315,29 +262,6 @@ describe('authenticateUserDefaultAuth()', () => {
user.authenticateUserDefaultAuth(authDetails, callback);
expect(callback.onFailure.mock.calls.length).toBe(1);
});

test('global fetch called with expected user agent header InitiateAuth', () => {
const fetchMock = jest
.spyOn(global, 'fetch')
.mockImplementation(() =>
Promise.resolve({ json: () => Promise.resolve([]) })
);

addAuthCategoryToCognitoUserAgent();
user.authenticateUserDefaultAuth(authDetails, callback);

expect(global.fetch.mock.calls.length).toBe(1);
expect(fetchMock).toBeCalledWith(
expect.anything(),
expect.objectContaining({
headers: expect.objectContaining({
'X-Amz-User-Agent': `${getUserAgent()} auth/${
AuthAction.InitiateAuth
}`,
}),
})
);
});
});

describe('authenticateUserPlainUsernamePassword()', () => {
Expand Down Expand Up @@ -390,31 +314,6 @@ describe('authenticateUserPlainUsernamePassword()', () => {
);
expect(userSpy3.mock.results[0].value).toBe('test return value');
});

test('global fetch called with expected user agent header InitiateAuth', () => {
const fetchMock = jest
.spyOn(global, 'fetch')
.mockImplementation(() =>
Promise.resolve({ json: () => Promise.resolve([]) })
);

addAuthCategoryToCognitoUserAgent();

const authDetails = new AuthenticationDetails(authDetailData);
user.authenticateUserPlainUsernamePassword(authDetails, callback);

expect(global.fetch.mock.calls.length).toBe(1);
expect(fetchMock).toBeCalledWith(
expect.anything(),
expect.objectContaining({
headers: expect.objectContaining({
'X-Amz-User-Agent': `${getUserAgent()} auth/${
AuthAction.InitiateAuth
}`,
}),
})
);
});
});

describe('authenticateUserInternal()', () => {
Expand Down Expand Up @@ -586,30 +485,6 @@ describe('authenticateUserInternal()', () => {
user.authenticateUserInternal(authData, authHelper, callback);
expect(callback.onSuccess).toBeCalledWith(user.signInUserSession, true);
});

test('global fetch called with expected user agent header ConfirmDevice', () => {
const fetchMock = jest
.spyOn(global, 'fetch')
.mockImplementation(() =>
Promise.resolve({ json: () => Promise.resolve([]) })
);

addAuthCategoryToCognitoUserAgent();

user.authenticateUserInternal(authData, authHelper, callback);

expect(global.fetch.mock.calls.length).toBe(1);
expect(fetchMock).toBeCalledWith(
expect.anything(),
expect.objectContaining({
headers: expect.objectContaining({
'X-Amz-User-Agent': `${getUserAgent()} auth/${
AuthAction.ConfirmDevice
}`,
}),
})
);
});
});

describe('completeNewPasswordChallenge()', () => {
Expand Down Expand Up @@ -688,35 +563,6 @@ describe('completeNewPasswordChallenge()', () => {
);
expect(spyon2).toBeCalledTimes(1);
});

test('global fetch called with expected user agent header RespondToAuthChallenge', () => {
const fetchMock = jest
.spyOn(global, 'fetch')
.mockImplementation(() =>
Promise.resolve({ json: () => Promise.resolve([]) })
);

addAuthCategoryToCognitoUserAgent();

user.completeNewPasswordChallenge(
'NEWp@ssw0rd',
requiredAttributeData,
callback,
clientMetadata
);

expect(global.fetch.mock.calls.length).toBe(1);
expect(fetchMock).toBeCalledWith(
expect.anything(),
expect.objectContaining({
headers: expect.objectContaining({
'X-Amz-User-Agent': `${getUserAgent()} auth/${
AuthAction.RespondToAuthChallenge
}`,
}),
})
);
});
});

describe('getDeviceResponse()', () => {
Expand Down Expand Up @@ -760,34 +606,6 @@ describe('getDeviceResponse()', () => {
expect(callback.onFailure).toBeCalledWith(networkError);
});

test('global fetch called with expected user agent header RespondToAuthChallenge', () => {
const fetchMock = jest
.spyOn(global, 'fetch')
.mockImplementation(() =>
Promise.resolve({ json: () => Promise.resolve([]) })
);

addAuthCategoryToCognitoUserAgent();

jest
.spyOn(AuthenticationHelper.prototype, 'getLargeAValue')
.mockImplementation(cb => cb(null, 12345));

user.getDeviceResponse(callback, {});

expect(global.fetch.mock.calls.length).toBe(1);
expect(fetchMock).toBeCalledWith(
expect.anything(),
expect.objectContaining({
headers: expect.objectContaining({
'X-Amz-User-Agent': `${getUserAgent()} auth/${
AuthAction.RespondToAuthChallenge
}`,
}),
})
);
});

/**TODO: Check this clientRequestSpy */
describe('RespondToAuthChallenge nested Client method suite', () => {
let clientRequestSpy;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
import CognitoUserPool from '../src/CognitoUserPool';
import Client from '../src/Client';
import { getUserAgent } from '../src/Platform';
import { AuthAction } from '../src/Platform/constants';
import {
clientId,
userPoolId,
userPoolName,
userName,
password,
} from './constants';
import { addAuthCategoryToCognitoUserAgent } from '../src/UserAgent';

describe('Constructor and accessor methods', () => {
const minimalData = { UserPoolId: userPoolId, ClientId: clientId };
Expand Down Expand Up @@ -92,25 +89,4 @@ describe('Testing signUp of a user into a user pool', () => {
cognitoUserPool.signUp(userName, password, [], [], callback, []);
expect(callback.mock.calls.length).toBe(1);
});

test('headers contain user agent with auth category and sign up action', () => {
const fetchMock = jest
.spyOn(global, 'fetch')
.mockImplementation(() =>
Promise.resolve({ json: () => Promise.resolve([]) })
);

addAuthCategoryToCognitoUserAgent();

const callback = jest.fn();
cognitoUserPool.signUp(userName, password, [], [], callback, []);
expect(fetchMock).toBeCalledWith(
expect.anything(),
expect.objectContaining({
headers: expect.objectContaining({
'X-Amz-User-Agent': `${getUserAgent()} auth/${AuthAction.SignUp}`,
}),
})
);
});
});
18 changes: 8 additions & 10 deletions packages/amazon-cognito-identity-js/__tests__/UserAgent.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AuthAction, authCategory } from '../src/Platform/constants';
import { authCategory } from '../src/Platform/constants';
import UserAgent, {
addAuthCategoryToCognitoUserAgent,
addFrameworkToCognitoUserAgent,
Expand All @@ -8,11 +8,13 @@ import UserAgent, {

const DEFAULT_USER_AGENT = 'aws-amplify/0.1.x';
const USER_AGENT_FRAMEWORK0 = 'framework/0';
const USER_AGENT_AUTH_SIGNUP = `auth/${AuthAction.SignUp}`;
const USER_AGENT_AUTH = 'auth';

describe('UserAgent test', () => {
beforeEach(() => {
UserAgent.prototype.userAgent = DEFAULT_USER_AGENT;
UserAgent.category = undefined;
UserAgent.framework = undefined;
});
test('userAgent is set by default', () => {
expect(UserAgent.prototype.userAgent).toBe(DEFAULT_USER_AGENT);
Expand All @@ -27,9 +29,7 @@ describe('UserAgent test', () => {
appendToCognitoUserAgent('test');
expect(UserAgent.prototype.userAgent).toBe(`${DEFAULT_USER_AGENT} test`);

expect(getAmplifyUserAgentString(AuthAction.SignUp)).toBe(
`${DEFAULT_USER_AGENT} test`
);
expect(getAmplifyUserAgentString()).toBe(`${DEFAULT_USER_AGENT} test`);
});

test('appendToCognitoUserAgent does not append duplicate content', () => {
Expand All @@ -41,9 +41,7 @@ describe('UserAgent test', () => {

expect(UserAgent.prototype.userAgent).toBe(`${DEFAULT_USER_AGENT} test`);

expect(getAmplifyUserAgentString(AuthAction.SignUp)).toBe(
`${DEFAULT_USER_AGENT} test`
);
expect(getAmplifyUserAgentString()).toBe(`${DEFAULT_USER_AGENT} test`);
});

test('appendToCognitoUserAgent sets userAgent if userAgent has no content', () => {
Expand All @@ -60,8 +58,8 @@ describe('UserAgent test', () => {
addAuthCategoryToCognitoUserAgent();
expect(UserAgent.category).toBe(authCategory);

expect(getAmplifyUserAgentString(AuthAction.SignUp)).toBe(
`${DEFAULT_USER_AGENT} ${USER_AGENT_AUTH_SIGNUP}`
expect(getAmplifyUserAgentString()).toBe(
`${DEFAULT_USER_AGENT} ${USER_AGENT_AUTH}`
);
});

Expand Down
3 changes: 1 addition & 2 deletions packages/amazon-cognito-identity-js/src/Client.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import 'isomorphic-unfetch';

import { getAmplifyUserAgentString } from './UserAgent';
import { AuthAction } from './Platform/constants';

class CognitoError extends Error {
constructor(message, code, name, statusCode) {
Expand Down Expand Up @@ -80,7 +79,7 @@ export default class Client {
const headers = {
'Content-Type': 'application/x-amz-json-1.1',
'X-Amz-Target': `AWSCognitoIdentityProviderService.${operation}`,
'X-Amz-User-Agent': getAmplifyUserAgentString(AuthAction[operation]),
'X-Amz-User-Agent': getAmplifyUserAgentString(),
'Cache-Control': 'no-store',
};

Expand Down
Loading