Skip to content

Commit

Permalink
fix(amazon-cognito-identity-js): set crypto for Node (#7136)
Browse files Browse the repository at this point in the history
* Set crypto for node

* add crypto to webpack externals

* add unit tests for crypto
  • Loading branch information
amhinson authored Nov 6, 2020
1 parent 8b3183f commit 5173a99
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const crypto = require('crypto');

describe('cryptoSecureRandomInt test', () => {
let windowSpy;

beforeEach(() => {
jest.resetModules();
windowSpy = jest.spyOn(window, 'window', 'get');
});

afterEach(() => {
windowSpy.mockRestore();
});

test('crypto is set for window (browser)', () => {
windowSpy.mockImplementation(() => ({
crypto: {
getRandomValues: () => [12345],
},
}));

const cryptoSecureRandomInt = require('../src/utils/cryptoSecureRandomInt')
.default;
expect(window.crypto).toBeTruthy();
expect(cryptoSecureRandomInt()).toBe(12345);
});

test('crypto is set for window (IE 11)', () => {
windowSpy.mockImplementation(() => ({
crypto: undefined,
msCrypto: {
getRandomValues: () => [67890],
},
}));

const cryptoSecureRandomInt = require('../src/utils/cryptoSecureRandomInt')
.default;
expect(window.msCrypto).toBeTruthy();
expect(cryptoSecureRandomInt()).toBe(67890);
});

test('crypto is set for Node', () => {
windowSpy.mockImplementation(() => ({
crypto: null,
}));

const randomBytesMock = jest
.spyOn(crypto, 'randomBytes')
.mockImplementationOnce(() => ({
readInt32LE: jest.fn().mockReturnValueOnce(54321),
}));

const cryptoSecureRandomInt = require('../src/utils/cryptoSecureRandomInt')
.default;
expect(cryptoSecureRandomInt()).toBe(54321);

randomBytesMock.mockRestore();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ if (!crypto && typeof global !== 'undefined' && global.crypto) {
crypto = global.crypto;
}

// Native crypto import via require (NodeJS)
if (!crypto && typeof require === 'function') {
try {
crypto = require('crypto');
} catch (err) {}
}

/*
* Cryptographically secure pseudorandom number generator
* As Math.random() is cryptographically not safe to use
Expand Down
3 changes: 3 additions & 0 deletions packages/amazon-cognito-identity-js/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ var config = {
devtoolModuleFilenameTemplate: require('../aws-amplify/webpack-utils')
.devtoolModuleFilenameTemplate,
},
externals: {
crypto: 'crypto',
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.BannerPlugin({ banner, raw: true }),
Expand Down

0 comments on commit 5173a99

Please sign in to comment.