-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Credentials-test.ts
337 lines (281 loc) · 8.42 KB
/
Credentials-test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import { CredentialsClass as Credentials } from '../src/Credentials';
import { Amplify } from '../src/Amplify';
import { Hub } from '../src/Hub';
import {
CognitoIdentityClient,
GetCredentialsForIdentityCommand,
GetIdCommand,
} from '@aws-sdk/client-cognito-identity';
jest.mock('@aws-sdk/client-cognito-identity');
import { fromCognitoIdentity } from '@aws-sdk/credential-provider-cognito-identity';
jest.mock('@aws-sdk/credential-provider-cognito-identity');
const session = {};
const user = {
refreshSession: (_token, callback) => {
callback(null, 'success');
},
};
const storageClass = {
removeItem() {},
getItem() {},
};
const authClass = {
getModuleName() {
return 'Auth';
},
currentUserCredentials() {
return Promise.resolve('cred');
},
currentSession() {
return session;
},
currentUserPoolUser() {
return user;
},
configure(config: any) {
return config;
},
};
const cacheClass = {
getModuleName() {
return 'Cache';
},
getItem() {
return null;
},
configure(config: any) {
return config;
},
};
describe('Credentials test', () => {
describe('.Auth', () => {
it('should be undefined by default', async () => {
const credentials = new Credentials(null);
expect(credentials.Auth).toBeUndefined();
expect(credentials.get()).rejects.toMatchInlineSnapshot(
`"No Cognito Identity pool provided for unauthenticated access"`
);
});
it('should be Amplify.Auth if configured through Amplify', () => {
const credentials = new Credentials(null);
Amplify.register(authClass);
Amplify.register(credentials);
Amplify.configure({});
expect(credentials.Auth).toBe(authClass);
expect(credentials.get()).resolves.toBe('cred');
});
});
describe('configure test', () => {
test('happy case', done => {
expect.assertions(1);
const config = {
attr: 'attr',
};
Hub.listen('core', ({ channel, payload, source }) => {
if (
channel === 'core' &&
payload?.event === 'credentials_configured' &&
source === 'Credentials'
) {
done();
}
});
const credentials = new Credentials(null);
expect(credentials.configure(config)).toEqual({
attr: 'attr',
});
});
});
describe('different regions', () => {
const userPoolId = 'us-west-2:aaaaaaaaa';
const identityPoolId = 'us-east-1:bbbbbbbb';
const identityPoolRegion = 'us-east-1';
const region = 'us-west-2';
beforeAll(() => {
CognitoIdentityClient.mockImplementation(params => {
return {
send: params => {
if (params instanceof GetIdCommand) {
return { IdentityId: '123' };
}
if (params instanceof GetCredentialsForIdentityCommand) {
return {
Credentials: {
AccessKeyId: 'accessKey',
Expiration: 0,
SecretKey: 'secretKey',
SessionToken: 'sessionToken',
},
IdentityId: '123',
};
}
},
};
});
fromCognitoIdentity.mockImplementation(params => {
return async () => {
return {};
};
});
});
test('should use identityPoolRegion param for credentials for federation', async () => {
expect.assertions(2);
const credentials = new Credentials(null);
credentials.configure({
userPoolId,
identityPoolId,
identityPoolRegion,
region,
});
await credentials._setCredentialsFromFederation({
provider: 'google',
token: 'token',
identity_id: '123',
});
expect(CognitoIdentityClient).toHaveBeenCalledWith(
expect.objectContaining({ region: identityPoolRegion })
);
expect(fromCognitoIdentity).toBeCalledWith(
expect.objectContaining({
identityId: '123',
logins: {
'accounts.google.com': 'token',
},
})
);
});
test('should use identityPoolRegion param for credentials from session', async () => {
expect.assertions(2);
const credentials = new Credentials(null);
credentials.configure({
userPoolId,
identityPoolId,
identityPoolRegion,
region,
});
const session = {
getIdToken: () => {
return {
getJwtToken: () => {
return 'token';
},
};
},
};
await credentials._setCredentialsFromSession(session);
expect(CognitoIdentityClient).toHaveBeenCalledWith(
expect.objectContaining({ region: identityPoolRegion })
);
expect(GetIdCommand).toBeCalledWith({
IdentityPoolId: identityPoolId,
Logins: {
[`cognito-idp.${region}.amazonaws.com/${userPoolId}`]: 'token',
},
});
});
test('should use identityPoolRegion param for credentials for guest', async () => {
expect.assertions(2);
const credentials = new Credentials(null);
credentials.configure({
userPoolId,
identityPoolId,
identityPoolRegion,
region,
});
await credentials._setCredentialsForGuest();
expect(CognitoIdentityClient).toHaveBeenCalledWith(
expect.objectContaining({ region: identityPoolRegion })
);
expect(GetIdCommand).toBeCalledWith({
IdentityPoolId: identityPoolId,
});
});
});
describe('getCredSource test', () => {
test('happy case', () => {
const credentials = new Credentials(null);
credentials['_credentials_source'] = 'source';
expect(credentials.getCredSource()).toBe('source');
});
});
describe('token expiration test', () => {
let credentials: Credentials;
const timestamp = Date.now();
const dateSpy = jest.spyOn(global.Date, 'now');
const manualRefreshSpy = jest.spyOn(user, 'refreshSession');
const userCredentialsSpy = jest.spyOn(authClass, 'currentUserCredentials');
beforeAll(() => {
Amplify.register(authClass);
credentials = new Credentials(null);
const ttlExpiration = timestamp + 50 * 60 * 1000; // TTL expires after 50 min
const sessionExpiration = timestamp + 60 * 60 * 1000; // Session expires after 60 min
credentials['_credentials'] = {
expiration: new Date(sessionExpiration),
};
credentials['_nextCredentialsRefresh'] = ttlExpiration;
});
afterEach(() => {
// These spies need to be cleared so they start counting # of calls from scratch
manualRefreshSpy.mockClear();
userCredentialsSpy.mockClear();
});
afterAll(() => {
// Restore original implemenmtation for `Date.now()`
dateSpy.mockRestore();
});
test('session does not refresh before TTL expires', async () => {
const mockCurrentTime = timestamp + 45 * 60 * 1000; // before TTL expiration
dateSpy.mockImplementation(() => mockCurrentTime); // mock current time
await credentials.get();
expect(manualRefreshSpy).not.toHaveBeenCalled();
expect(userCredentialsSpy).toHaveBeenCalledTimes(1);
});
test('session refreshes between TTL and expiration', async () => {
const mockCurrentTime = timestamp + 55 * 60 * 1000; // between TTL and session expiration
dateSpy.mockImplementation(() => mockCurrentTime); // mock current time
await credentials.get();
expect(manualRefreshSpy).toHaveBeenCalledTimes(1);
expect(userCredentialsSpy).toHaveBeenCalledTimes(1);
});
test('session refreshes after expiration and TTL', async () => {
const mockCurrentTime = timestamp + 65 * 60 * 1000; // after session expiration
dateSpy.mockImplementation(() => mockCurrentTime); // mock current time
await credentials.get();
expect(manualRefreshSpy).not.toBeCalled();
expect(userCredentialsSpy).toHaveBeenCalledTimes(1);
});
});
describe('get test', () => {
test('credentials in the memory and not expired', async () => {
Amplify.register(authClass);
Amplify.register(cacheClass);
const credentials = new Credentials(null);
const expiration = new Date(new Date().getTime() + 20 * 60 * 1000);
credentials['_credentials'] = {
expiration,
};
credentials['_nextCredentialsRefresh'] = expiration.getTime() + 1;
expect(await credentials.get()).toEqual(credentials['_credentials']);
});
test('credentials not in memory or being expired', async () => {
Amplify.register(authClass);
const credentials = new Credentials(null);
expect(await credentials.get()).toBe('cred');
});
});
describe('clear test', () => {
test('credentials can be cleared from storage', async () => {
Amplify.register(authClass);
Amplify.register(cacheClass);
const identityPoolId = 'IDENTITY_POOL_ID';
const credentials = new Credentials({
storage: storageClass,
identityPoolId,
});
const removeItemSpy = jest.spyOn(storageClass, 'removeItem');
credentials.clear();
expect(removeItemSpy).toHaveBeenCalledTimes(1);
expect(removeItemSpy).toHaveBeenCalledWith('aws-amplify-federatedInfo');
});
});
});