-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
credentials-manager.test.js
342 lines (264 loc) · 15 KB
/
credentials-manager.test.js
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
338
339
340
341
342
/**
* Tests.
*/
import 'aws-sdk-client-mock-jest';
import { STSClient, AssumeRoleWithSAMLCommand } from '@aws-sdk/client-sts';
import { CredentialsManager } from './credentials-manager.js';
import { RoleNotFoundError } from './errors.js';
import { Session } from './session.js';
import { Role } from './role';
import { mockClient } from 'aws-sdk-client-mock';
import { mkdtemp, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { jest } from '@jest/globals';
import * as fixtures from './fixtures.js';
const awsRegion = 'us-east-1';
const awsProfile = 'test';
const mockSessionData = {
accessKeyId: 'AAAAAABBBBBBCCCCCCDDDDDD',
role: new Role('Foobiz', 'arn:aws:iam::123456789:role/Foobiz', 'arn:aws:iam::123456789:saml-provider/GSuite'),
secretAccessKey: '0nKJNoiu9oSJBjkb+aDvVVVvvvB+ErF33r4',
expiresAt: new Date('2020-04-19T10:32:19.000Z'),
sessionToken: 'DMMDnnnnKAkjSJi///////oiuISHJbMNBMNjkhkbljkJHGJGUGALJBjbjksbKLJHlOOKmmNAhhB',
samlAssertion: 'T2NjdXB5IE1hcnMK'
};
const mockAssumeRoleWithSAMLCommandResponse = {
Credentials: {
AccessKeyId: mockSessionData.accessKeyId,
SecretAccessKey: mockSessionData.secretAccessKey,
Expiration: mockSessionData.expiresAt,
SessionToken: mockSessionData.sessionToken
}
};
jest.unstable_mockModule('./logger.js', async () => ({
Logger: function Logger() {
return {
format: jest.fn(),
start: jest.fn(),
stop: jest.fn(),
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
succeed: jest.fn()
}
}
}));
const { Logger } = (await import('./logger.js'));
const logger = new Logger();
const stsMock = mockClient(STSClient);
beforeEach(() => {
stsMock.reset();
});
describe('prepareRoleWithSAML', () => {
test('returns first role available if only one role is available', async () => {
const assertion = await fixtures.getSampleAssertion(fixtures.SAML_SESSION_BASIC);
const response = await fixtures.getResponseFromAssertion(assertion);
const credentialsManager = new CredentialsManager(logger, awsRegion);
const { roleToAssume, availableRoles, samlAssertion } = await credentialsManager.prepareRoleWithSAML(response);
const expectedRoleToAssume = new Role('foobar', 'arn:aws:iam::123456789:role/foobar', 'arn:aws:iam::123456789:saml-provider/GSuite');
await expect(roleToAssume).toEqual(expectedRoleToAssume);
await expect(availableRoles).toEqual([expectedRoleToAssume]);
await expect(samlAssertion).toEqual(assertion);
});
test('returns all roles available if custom role has not been requested and multiple roles are available', async () => {
const assertion = await fixtures.getSampleAssertion(fixtures.SAML_SESSION_BASIC_WITH_MULTIPLE_ROLES);
const response = await fixtures.getResponseFromAssertion(assertion);
const credentialsManager = new CredentialsManager(logger, awsRegion);
const { roleToAssume, availableRoles, samlAssertion } = await credentialsManager.prepareRoleWithSAML(response);
await expect(roleToAssume).toBeNull();
await expect(availableRoles).toEqual([
new Role('Foobar', 'arn:aws:iam::123456789:role/Foobar', 'arn:aws:iam::123456789:saml-provider/GSuite'),
new Role('Admin', 'arn:aws:iam::987654321:role/Admin', 'arn:aws:iam::987654321:saml-provider/GSuite'),
new Role('Foobiz', 'arn:aws:iam::987654321:role/Foobiz', 'arn:aws:iam::987654321:saml-provider/GSuite')
]);
await expect(samlAssertion).toEqual(assertion);
});
test('returns custom role if custom role requested was found', async () => {
const assertion = await fixtures.getSampleAssertion(fixtures.SAML_SESSION_BASIC_WITH_MULTIPLE_ROLES);
const response = await fixtures.getResponseFromAssertion(assertion);
const credentialsManager = new CredentialsManager(logger, awsRegion);
const { roleToAssume, availableRoles, samlAssertion } = await credentialsManager.prepareRoleWithSAML(response, 'arn:aws:iam::123456789:role/Foobar');
await expect(roleToAssume).toEqual(new Role('Foobar', 'arn:aws:iam::123456789:role/Foobar', 'arn:aws:iam::123456789:saml-provider/GSuite'));
await expect(availableRoles).toEqual([
new Role('Foobar', 'arn:aws:iam::123456789:role/Foobar', 'arn:aws:iam::123456789:saml-provider/GSuite'),
new Role('Admin', 'arn:aws:iam::987654321:role/Admin', 'arn:aws:iam::987654321:saml-provider/GSuite'),
new Role('Foobiz', 'arn:aws:iam::987654321:role/Foobiz', 'arn:aws:iam::987654321:saml-provider/GSuite')
]);
await expect(samlAssertion).toEqual(assertion);
});
test('throws if custom role is not found', async () => {
const assertion = await fixtures.getSampleAssertion(fixtures.SAML_SESSION_BASIC_WITH_MULTIPLE_ROLES);
const response = await fixtures.getResponseFromAssertion(assertion);
const credentialsManager = new CredentialsManager(logger, awsRegion);
let error;
try {
await credentialsManager.prepareRoleWithSAML(response, 'arn:aws:iam::987654321:role/Foobar');
} catch (e) {
error = e;
}
const expected = new RoleNotFoundError([
new Role('Foobar', 'arn:aws:iam::123456789:role/Foobar', 'arn:aws:iam::123456789:saml-provider/GSuite'),
new Role('Admin', 'arn:aws:iam::987654321:role/Admin', 'arn:aws:iam::987654321:saml-provider/GSuite'),
new Role('Foobiz', 'arn:aws:iam::987654321:role/Foobiz', 'arn:aws:iam::987654321:saml-provider/GSuite')
]);
await expect(error).toEqual(expected);
await expect(error.roles).toEqual(expected.roles);
});
});
describe('assumeRoleWithSAML', () => {
it('assumes role with SAML and saves credentials', async () => {
const cacheDir = await mkdtemp(join(tmpdir(), 'gsts-'));
const credentialsManager = new CredentialsManager(logger, awsRegion, cacheDir);
stsMock.on(AssumeRoleWithSAMLCommand).resolves(mockAssumeRoleWithSAMLCommandResponse);
await credentialsManager.assumeRoleWithSAML(mockSessionData.samlAssertion, mockSessionData.role, awsProfile);
expect(stsMock).toHaveReceivedCommandWith(AssumeRoleWithSAMLCommand, {
PrincipalArn: mockSessionData.role.principalArn,
RoleArn: mockSessionData.role.roleArn,
SAMLAssertion: mockSessionData.samlAssertion
});
expect((await credentialsManager.loadCredentials(awsProfile))).toEqual((new Session(mockSessionData)));
});
it('parses IAM role max session duration if custom session duration is defined', async () => {
const validationError = new Error(`1 validation error detected: Value '43201' at 'durationSeconds' failed to satisfy constraint: Member must have value less than or equal to 43200`);
validationError.Code = 'ValidationError';
stsMock.on(AssumeRoleWithSAMLCommand).rejectsOnce(validationError)
const credentialsManager = new CredentialsManager(logger, awsRegion);
await expect(credentialsManager.assumeRoleWithSAML(mockSessionData.samlAssertion, mockSessionData.role, mockSessionData.awsProfile))
.rejects
.toThrow(`1 validation error detected: Value '43201' at 'durationSeconds' failed to satisfy constraint: Member must have value less than or equal to 43200`);
});
it('uses custom role session duration if set', async () => {
const credentialsManager = new CredentialsManager(logger, awsRegion);
stsMock.on(AssumeRoleWithSAMLCommand).resolves(mockAssumeRoleWithSAMLCommandResponse);
await credentialsManager.assumeRoleWithSAML(mockSessionData.samlAssertion, mockSessionData.role, awsProfile, 900);
expect(stsMock).toHaveReceivedCommandWith(AssumeRoleWithSAMLCommand, {
DurationSeconds: 900,
PrincipalArn: mockSessionData.role.principalArn,
RoleArn: mockSessionData.role.roleArn,
SAMLAssertion: mockSessionData.samlAssertion
});
});
it('uses IdP-set role session duration if available', async () => {
const credentialsManager = new CredentialsManager(logger, awsRegion);
const roleWithCustomDuration = new Role(
mockSessionData.role.name,
mockSessionData.role.roleArn,
mockSessionData.role.principalArn,
900);
stsMock.on(AssumeRoleWithSAMLCommand).resolves(mockAssumeRoleWithSAMLCommandResponse);
await credentialsManager.assumeRoleWithSAML(mockSessionData.samlAssertion, roleWithCustomDuration, awsProfile);
expect(stsMock).toHaveReceivedCommandWith(AssumeRoleWithSAMLCommand, {
DurationSeconds: 900,
PrincipalArn: mockSessionData.role.principalArn,
RoleArn: mockSessionData.role.roleArn,
SAMLAssertion: mockSessionData.samlAssertion
});
});
it('saves credentials to cache dir if set', async () => {
const cacheDir = await mkdtemp(join(tmpdir(), 'gsts-'));
stsMock.on(AssumeRoleWithSAMLCommand).resolves({
Credentials: {
AccessKeyId: mockSessionData.accessKeyId,
SecretAccessKey: mockSessionData.secretAccessKey,
Expiration: mockSessionData.expiresAt,
SessionToken: mockSessionData.sessionToken
}
});
const credentialsManager = new CredentialsManager(logger, awsRegion, cacheDir);
await credentialsManager.assumeRoleWithSAML(mockSessionData.samlAssertion, mockSessionData.role, awsProfile);
expect((await credentialsManager.loadCredentials(awsProfile))).toEqual((new Session(mockSessionData)));
});
it('does not save credentials to cache dir if not set', async () => {
stsMock.on(AssumeRoleWithSAMLCommand).resolves(mockAssumeRoleWithSAMLCommandResponse);
const credentialsManager = new CredentialsManager(logger, awsRegion);
await credentialsManager.assumeRoleWithSAML(mockSessionData.samlAssertion, mockSessionData.role, awsProfile);
await expect(credentialsManager.loadCredentials(awsProfile)).rejects.toThrow('ENOENT');
});
});
describe('loadCredentialsFile', () => {
it('should throw an error if cache dir is not set', async () => {
const credentialsManager = new CredentialsManager(logger, awsRegion);
await expect(credentialsManager.loadCredentialsFile()).rejects.toThrow('ENOENT');
});
it('should throw an error if credentials file is not found in cache dir', async () => {
const cacheDir = await mkdtemp(join(tmpdir(), 'gsts-'));
const credentialsManager = new CredentialsManager(logger, awsRegion, cacheDir);
await expect(credentialsManager.loadCredentialsFile()).rejects.toThrow('ENOENT');
});
it('should load credentials file if found in cache dir', async () => {
const cacheDir = await mkdtemp(join(tmpdir(), 'gsts-'));
const credentialsManager = new CredentialsManager(logger, awsRegion, cacheDir);
await credentialsManager.saveCredentials(awsProfile, new Session(mockSessionData));
await expect((await credentialsManager.loadCredentialsFile(awsProfile))).not.toBeNull();
});
});
describe('loadCredentials', () => {
it('should throw an error if credentials are not found', async () => {
const cacheDir = await mkdtemp(join(tmpdir(), 'gsts-'));
const awsRoleArn = 'arn:aws:iam::123456789:role/Foobar';
const credentialsManager = new CredentialsManager(logger, awsRegion, cacheDir);
await expect(credentialsManager.loadCredentials(awsProfile, awsRoleArn)).rejects.toThrow('ENOENT');
});
it('should throw an error if credentials found are for a different role ARN', async () => {
const cacheDir = await mkdtemp(join(tmpdir(), 'gsts-'));
const awsRoleArn = 'arn:aws:iam::987654321:role/Foobar';
const credentialsManager = new CredentialsManager(logger, awsRegion, cacheDir);
await credentialsManager.saveCredentials(awsProfile, new Session(mockSessionData));
await expect(credentialsManager.loadCredentials(awsProfile, awsRoleArn)).rejects.toThrow('Received role arn:aws:iam::987654321:role/Foobar but expected arn:aws:iam::123456789:role/Foobiz');
});
it('should throw an error if credentials for requested profile are not found', async () => {
const cacheDir = await mkdtemp(join(tmpdir(), 'gsts-'));
const credentialsManager = new CredentialsManager(logger, awsRegion, cacheDir);
await credentialsManager.saveCredentials(awsProfile, new Session(mockSessionData));
await expect(credentialsManager.loadCredentials('test-other')).rejects.toThrow('Profile "test-other" not found in credentials file');
});
it('should throw an error if credentials for requested profile are not found', async () => {
const cacheDir = await mkdtemp(join(tmpdir(), 'gsts-'));
const credentialsManager = new CredentialsManager(logger, awsRegion, cacheDir);
await credentialsManager.saveCredentials(awsProfile, new Session(mockSessionData));
await expect(credentialsManager.loadCredentials('test-other')).rejects.toThrow('Profile "test-other" not found in credentials file');
});
it('should return the credentials for the requested profile', async () => {
const cacheDir = await mkdtemp(join(tmpdir(), 'gsts-'));
const credentialsManager = new CredentialsManager(logger, awsRegion, cacheDir);
const session = new Session(mockSessionData);
await credentialsManager.saveCredentials(awsProfile, session);
await expect((await credentialsManager.loadCredentials('test')).toJSON()).toEqual(session.toJSON());
});
});
describe('saveCredentials', () => {
it('creates cache directory if it does not exist', async () => {
const cacheDir = `${tmpdir()}/gsts-${Math.random().toString(16).slice(2, 8)}`;
const credentialsManager = new CredentialsManager(logger, awsRegion, cacheDir);
await credentialsManager.saveCredentials(awsProfile, new Session(mockSessionData));
await stat(cacheDir);
});
it('stores session with owner read-write permissions only', async () => {
const cacheDir = `${tmpdir()}/gsts-${Math.random().toString(16).slice(2, 8)}`;
const credentialsManager = new CredentialsManager(logger, awsRegion, cacheDir);
const session = new Session(mockSessionData);
await credentialsManager.saveCredentials(awsProfile, session);
expect((await stat(credentialsManager.credentialsFile)).mode.toString(8)).toEqual(process.platform === "win32" ? '100666' : '100600');
});
it('stores session content under credentials files', async () => {
const cacheDir = `${tmpdir()}/gsts-${Math.random().toString(16).slice(2, 8)}`;
const credentialsManager = new CredentialsManager(logger, awsRegion, cacheDir);
const session = new Session(mockSessionData);
await credentialsManager.saveCredentials(awsProfile, session);
const savedSession = await credentialsManager.loadCredentials(awsProfile);
expect(session).toEqual(savedSession);
});
it('stores multiple profile sessions under the same credentials files', async () => {
const cacheDir = `${tmpdir()}/gsts-${Math.random().toString(16).slice(2, 8)}`;
const credentialsManager = new CredentialsManager(logger, awsRegion, cacheDir);
const session = new Session(mockSessionData);
await credentialsManager.saveCredentials(awsProfile, session);
await credentialsManager.saveCredentials(`${awsProfile}_new`, session);
const savedSession1 = await credentialsManager.loadCredentials(awsProfile);
const savedSession2 = await credentialsManager.loadCredentials(`${awsProfile}_new`);
expect(session).toEqual(savedSession1);
expect(session).toEqual(savedSession2);
});
});