forked from mongodb/node-mongodb-native
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcredentialsProvider.test.ts
More file actions
554 lines (479 loc) · 19.2 KB
/
credentialsProvider.test.ts
File metadata and controls
554 lines (479 loc) · 19.2 KB
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
import { expect } from 'chai';
import * as http from 'http';
import * as sinon from 'sinon';
import { MongoCryptAzureKMSRequestError } from '../../../../src/client-side-encryption/errors';
import {
isEmptyCredentials,
type KMSProviders,
refreshKMSCredentials
} from '../../../../src/client-side-encryption/providers';
import {
fetchAzureKMSToken,
tokenCache
} from '../../../../src/client-side-encryption/providers/azure';
import { AWSSDKCredentialProvider } from '../../../../src/cmap/auth/aws_temporary_credentials';
import { MongoNetworkTimeoutError } from '../../../../src/error';
import * as utils from '../../../../src/utils';
import * as requirements from '../requirements.helper';
const originalAccessKeyId = process.env.AWS_ACCESS_KEY_ID;
const originalSecretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
const originalSessionToken = process.env.AWS_SESSION_TOKEN;
describe('#refreshKMSCredentials', function () {
context('isEmptyCredentials()', () => {
it('returns true for an empty object', () => {
expect(isEmptyCredentials('aws', { aws: {} })).to.be.true;
});
it('returns false for an object with keys', () => {
// @ts-expect-error Testing error conditions here
expect(isEmptyCredentials('aws', { aws: { password: 'secret' } })).to.be.false;
});
it('returns false for an nullish credentials', () => {
// @ts-expect-error Testing error conditions here
expect(isEmptyCredentials('aws', { aws: null })).to.be.false;
expect(isEmptyCredentials('aws', { aws: undefined })).to.be.false;
expect(isEmptyCredentials('aws', {})).to.be.false;
});
it('returns false for non object credentials', () => {
// @ts-expect-error Testing error conditions here
expect(isEmptyCredentials('aws', { aws: 0 })).to.be.false;
// @ts-expect-error Testing error conditions here
expect(isEmptyCredentials('aws', { aws: false })).to.be.false;
// @ts-expect-error Testing error conditions here
expect(isEmptyCredentials('aws', { aws: Symbol('secret') })).to.be.false;
});
});
context('when using aws', () => {
const accessKey = 'example';
const secretKey = 'example';
const sessionToken = 'example';
after(function () {
// After the entire suite runs, set the env back for the rest of the test run.
process.env.AWS_ACCESS_KEY_ID = originalAccessKeyId;
process.env.AWS_SECRET_ACCESS_KEY = originalSecretAccessKey;
process.env.AWS_SESSION_TOKEN = originalSessionToken;
});
context('when the credential provider finds credentials', function () {
before(function () {
process.env.AWS_ACCESS_KEY_ID = accessKey;
process.env.AWS_SECRET_ACCESS_KEY = secretKey;
process.env.AWS_SESSION_TOKEN = sessionToken;
});
context('when the credentials are empty', function () {
const kmsProviders = { aws: {} };
before(function () {
if (!requirements.credentialProvidersInstalled.aws && this.currentTest) {
this.currentTest.skipReason = 'Cannot refresh credentials without sdk provider';
this.currentTest.skip();
return;
}
});
it('refreshes the aws credentials', async function () {
const providers = await refreshKMSCredentials(kmsProviders);
expect(providers).to.deep.equal({
aws: {
accessKeyId: accessKey,
secretAccessKey: secretKey,
sessionToken: sessionToken
}
});
});
});
context('when the credentials are not empty', function () {
context('when aws is empty', function () {
const kmsProviders = {
local: {
key: Buffer.alloc(96)
},
aws: {}
};
before(function () {
if (!requirements.credentialProvidersInstalled.aws && this.currentTest) {
this.currentTest.skipReason = 'Cannot refresh credentials without sdk provider';
this.currentTest.skip();
return;
}
});
it('refreshes only the aws credentials', async function () {
const providers = await refreshKMSCredentials(kmsProviders);
expect(providers).to.deep.equal({
local: {
key: Buffer.alloc(96)
},
aws: {
accessKeyId: accessKey,
secretAccessKey: secretKey,
sessionToken: sessionToken
}
});
});
});
context('when aws is not empty', function () {
const kmsProviders: KMSProviders = {
local: {
key: Buffer.alloc(96)
},
aws: {
accessKeyId: 'example'
} as any
};
before(function () {
if (!requirements.credentialProvidersInstalled.aws && this.currentTest) {
this.currentTest.skipReason = 'Cannot refresh credentials without sdk provider';
this.currentTest.skip();
return;
}
});
it('does not refresh credentials', async function () {
const providers = await refreshKMSCredentials(kmsProviders);
expect(providers).to.deep.equal(kmsProviders);
});
});
});
});
context('when the AWS SDK returns unknown fields', function () {
beforeEach(() => {
sinon.stub(AWSSDKCredentialProvider.prototype, 'getCredentials').resolves({
Token: 'example',
SecretAccessKey: 'example',
AccessKeyId: 'example',
Expiration: new Date()
});
});
afterEach(() => sinon.restore());
it('only returns fields libmongocrypt expects', async function () {
const credentials = await refreshKMSCredentials({ aws: {} });
expect(credentials).to.deep.equal({
aws: {
accessKeyId: accessKey,
secretAccessKey: secretKey,
sessionToken: sessionToken
}
});
});
});
});
context('when using gcp', () => {
const setupHttpServer = status => {
let httpServer;
before(() => {
httpServer = http
.createServer((_, res) => {
if (status === 200) {
res.writeHead(200, {
'Content-Type': 'application/json',
'Metadata-Flavor': 'Google'
});
res.end(JSON.stringify({ access_token: 'abc' }));
} else {
res.writeHead(401, {
'Content-Type': 'application/json',
'Metadata-Flavor': 'Google'
});
res.end('{}');
}
})
.listen(5001);
process.env.GCE_METADATA_HOST = 'http://127.0.0.1:5001';
});
after(() => {
httpServer.close();
delete process.env.GCE_METADATA_HOST;
});
};
context('and gcp-metadata is installed', () => {
beforeEach(function () {
if (!requirements.credentialProvidersInstalled.gcp && this.currentTest) {
this.currentTest.skipReason = 'Tests require gcp-metadata to be installed';
this.currentTest.skip();
return;
}
});
context('when metadata http response is 200 ok', () => {
setupHttpServer(200);
context('when the credentials are empty', function () {
const kmsProviders = { gcp: {} };
it('refreshes the gcp credentials', async function () {
const providers = await refreshKMSCredentials(kmsProviders);
expect(providers).to.deep.equal({
gcp: {
accessToken: 'abc'
}
});
});
});
});
context('when metadata http response is 401 bad', () => {
setupHttpServer(401);
context('when the credentials are empty', function () {
const kmsProviders = { gcp: {} };
it('surfaces error from server', async function () {
const error = await refreshKMSCredentials(kmsProviders).catch(error => error);
expect(error).to.be.instanceOf(Error);
});
});
});
});
context('and gcp-metadata is not installed', () => {
beforeEach(function () {
if (requirements.credentialProvidersInstalled.gcp && this.currentTest) {
this.currentTest.skipReason = 'Tests require gcp-metadata to be installed';
this.currentTest.skip();
return;
}
});
context('when the credentials are empty', function () {
const kmsProviders = { gcp: {} };
it('does not modify the gcp credentials', async function () {
const providers = await refreshKMSCredentials(kmsProviders);
expect(providers).to.deep.equal({ gcp: {} });
});
});
});
});
context('when using azure', () => {
afterEach(() => tokenCache.resetCache());
afterEach(() => sinon.restore());
context('credential caching', () => {
const cache = tokenCache;
beforeEach(() => {
cache.resetCache();
});
context('when there is no cached token', () => {
const mockToken = {
accessToken: 'mock token',
expiresOnTimestamp: Date.now()
};
let token;
beforeEach(async () => {
sinon.stub(cache, '_getToken').resolves(mockToken);
token = await cache.getToken();
});
it('fetches a token', async () => {
expect(token).to.have.property('accessToken', mockToken.accessToken);
});
it('caches the token on the class', async () => {
expect(cache.cachedToken).to.equal(mockToken);
});
});
context('when there is a cached token', () => {
context('when the cached token expires <= 1 minute from the current time', () => {
const mockToken = {
accessToken: 'mock token',
expiresOnTimestamp: Date.now()
};
let token;
beforeEach(async () => {
cache.cachedToken = {
accessToken: 'a new key',
expiresOnTimestamp: Date.now() + 3000
};
sinon.stub(cache, '_getToken').resolves(mockToken);
token = await cache.getToken();
});
it('fetches a token', () => {
expect(token).to.have.property('accessToken', mockToken.accessToken);
});
it('caches the token on the class', () => {
expect(cache.cachedToken).to.equal(mockToken);
});
});
context('when the cached token expires > 1 minute from the current time', () => {
const expiredToken = {
token: 'mock token',
expiresOnTimestamp: Date.now()
};
const expectedMockToken = {
accessToken: 'a new key',
expiresOnTimestamp: Date.now() + 10000
};
let token;
beforeEach(async () => {
cache.cachedToken = expiredToken as any;
sinon.stub(cache, '_getToken').resolves(expectedMockToken);
token = await cache.getToken();
});
it('returns the cached token', () => {
expect(token).to.have.property('accessToken', expectedMockToken.accessToken);
});
});
});
});
context('request configuration', () => {
const mockResponse = {
status: 200,
body: '{ "access_token": "token", "expires_in": "10000" }'
};
let httpSpy;
beforeEach(async () => {
httpSpy = sinon.stub(utils, 'get');
httpSpy.resolves(mockResponse);
await refreshKMSCredentials({ azure: {} });
});
it('sets the `api-version` param to 2012-02-01', () => {
const url = httpSpy.args[0][0];
expect(url).to.be.instanceof(URL);
expect(url.searchParams.get('api-version'), '2018-02-01');
});
it('sets the `resource` param to `https://vault.azure.net`', () => {
const url = httpSpy.args[0][0];
expect(url).to.be.instanceof(URL);
expect(url.searchParams.get('resource'), 'https://vault.azure.net');
});
it('sends the request to `http://169.254.169.254/metadata/identity/oauth2/token`', () => {
const url = httpSpy.args[0][0];
expect(url).to.be.instanceof(URL);
expect(url.toString()).to.include('http://169.254.169.254/metadata/identity/oauth2/token');
});
it('sets the Metadata header to true', () => {
const options = httpSpy.args[0][1];
expect(options).to.have.property('headers').to.have.property('Metadata', true);
});
it('sets the Content-Type header to application/json', () => {
const options = httpSpy.args[0][1];
expect(options)
.to.have.property('headers')
.to.have.property('Content-Type', 'application/json');
});
context('prose test specific requirements', () => {
/**
* the driver prose tests require the ability to set custom URL endpoints
* for the IMDS call and set custom headers
*/
const url = new URL('http://customentpoint.com');
beforeEach(async () => {
sinon.restore();
httpSpy = sinon.stub(utils, 'get');
httpSpy.resolves(mockResponse);
await fetchAzureKMSToken({
url,
headers: {
customHeader1: 'value1',
customHeader2: 'value2'
}
});
});
it('allows custom headers to be specified', () => {
const options = httpSpy.args[0][1];
expect(options).to.have.property('headers').to.have.property('customHeader1', 'value1');
expect(options).to.have.property('headers').to.have.property('customHeader2', 'value2');
});
});
});
context('error handling', () => {
afterEach(() => sinon.restore());
context('when the request times out', () => {
before(() => {
sinon.stub(utils, 'get').rejects(new MongoNetworkTimeoutError('request timed out'));
});
it('throws a MongoCryptKMSRequestError', async () => {
const error = await refreshKMSCredentials({ azure: {} }).catch(e => e);
expect(error).to.be.instanceOf(MongoCryptAzureKMSRequestError);
});
});
context('when the request returns a non-200 error', () => {
context('when the request has no body', () => {
before(() => {
sinon.stub(utils, 'get').resolves({ status: 400 } as any);
});
it('throws a MongoCryptKMSRequestError', async () => {
const error = await refreshKMSCredentials({ azure: {} }).catch(e => e);
expect(error).to.be.instanceOf(MongoCryptAzureKMSRequestError);
expect(error).to.match(/Malformed JSON body in GET request/);
});
});
context('when the request has a non-json body', () => {
before(() => {
sinon.stub(utils, 'get').resolves({ status: 400, body: 'non-json body' });
});
it('throws a MongoCryptKMSRequestError', async () => {
const error = await refreshKMSCredentials({ azure: {} }).catch(e => e);
expect(error).to.be.instanceOf(MongoCryptAzureKMSRequestError);
expect(error).to.match(/Malformed JSON body in GET request/);
});
});
context('when the request has a json body', () => {
beforeEach(() => {
sinon
.stub(utils, 'get')
.resolves({ status: 400, body: '{ "error": "something went wrong" }' });
});
it('throws a MongoCryptKMSRequestError', async () => {
const error = await refreshKMSCredentials({ azure: {} }).catch(e => e);
expect(error).to.be.instanceOf(MongoCryptAzureKMSRequestError);
});
it('attaches the body to the error', async () => {
const error = await refreshKMSCredentials({ azure: {} }).catch(e => e);
expect(error).to.have.property('body').to.deep.equal({ error: 'something went wrong' });
});
});
});
context('when the request returns a 200 response', () => {
context('when the request has no body', () => {
before(() => {
sinon.stub(utils, 'get').resolves({ status: 200 } as any);
});
it('throws a MongoCryptKMSRequestError', async () => {
const error = await refreshKMSCredentials({ azure: {} }).catch(e => e);
expect(error).to.be.instanceOf(MongoCryptAzureKMSRequestError);
expect(error).to.match(/Malformed JSON body in GET request/);
});
});
context('when the request has a non-json body', () => {
before(() => {
sinon.stub(utils, 'get').resolves({ status: 200, body: 'non-json body' });
});
it('throws a MongoCryptKMSRequestError', async () => {
const error = await refreshKMSCredentials({ azure: {} }).catch(e => e);
expect(error).to.be.instanceOf(MongoCryptAzureKMSRequestError);
expect(error).to.match(/Malformed JSON body in GET request/);
});
});
context('when the body has no access_token', () => {
beforeEach(() => {
sinon.stub(utils, 'get').resolves({ status: 200, body: '{ "expires_in": "10000" }' });
});
it('throws a MongoCryptKMSRequestError', async () => {
const error = await refreshKMSCredentials({ azure: {} }).catch(e => e);
expect(error).to.be.instanceOf(MongoCryptAzureKMSRequestError);
expect(error).to.match(/missing field `access_token/);
});
});
context('when the body has no expires_in', () => {
beforeEach(() => {
sinon.stub(utils, 'get').resolves({ status: 200, body: '{ "access_token": "token" }' });
});
it('throws a MongoCryptKMSRequestError', async () => {
const error = await refreshKMSCredentials({ azure: {} }).catch(e => e);
expect(error).to.be.instanceOf(MongoCryptAzureKMSRequestError);
expect(error).to.match(/missing field `expires_in/);
});
});
context('when expires_in cannot be parsed into a number', () => {
beforeEach(() => {
sinon.stub(utils, 'get').resolves({
status: 200,
body: '{ "access_token": "token", "expires_in": "foo" }'
});
});
it('throws a MongoCryptKMSRequestError', async () => {
const error = await refreshKMSCredentials({ azure: {} }).catch(e => e);
expect(error).to.be.instanceOf(MongoCryptAzureKMSRequestError);
expect(error).to.match(/unable to parse int from `expires_in` field/);
});
});
});
context('when a valid token was returned', () => {
beforeEach(() => {
sinon
.stub(utils, 'get')
.resolves({ status: 200, body: '{ "access_token": "token", "expires_in": "10000" }' });
});
it('returns the token in the `azure` field of the kms providers', async () => {
const kmsProviders = await refreshKMSCredentials({ azure: {} });
const azure = kmsProviders.azure;
expect(azure).to.have.property('accessToken', 'token');
});
});
});
});
});