/
test.googleauth.ts
1560 lines (1394 loc) · 56.4 KB
/
test.googleauth.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
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as assert from 'assert';
import {describe, it, beforeEach, afterEach} from 'mocha';
const assertRejects = require('assert-rejects');
import * as child_process from 'child_process';
import * as crypto from 'crypto';
import * as fs from 'fs';
import {
BASE_PATH,
HEADERS,
HOST_ADDRESS,
SECONDARY_HOST_ADDRESS,
resetIsAvailableCache,
} from 'gcp-metadata';
import * as nock from 'nock';
import * as os from 'os';
import * as path from 'path';
import * as sinon from 'sinon';
import {GoogleAuth, JWT, UserRefreshClient, IdTokenClient} from '../src';
import {CredentialBody} from '../src/auth/credentials';
import * as envDetect from '../src/auth/envDetect';
import {Compute} from '../src/auth/computeclient';
import * as messages from '../src/messages';
nock.disableNetConnect();
describe('googleauth', () => {
const isWindows = process.platform === 'win32';
const tokenPath = `${BASE_PATH}/instance/service-accounts/default/token`;
const host = HOST_ADDRESS;
const instancePath = `${BASE_PATH}/instance`;
const svcAccountPath = `${instancePath}/service-accounts/?recursive=true`;
const API_KEY = 'test-123';
const STUB_PROJECT = 'my-awesome-project';
const ENDPOINT = '/events:report';
const RESPONSE_BODY = 'RESPONSE_BODY';
const BASE_URL = [
'https://clouderrorreporting.googleapis.com/v1beta1/projects',
STUB_PROJECT,
].join('/');
const privateJSON = require('../../test/fixtures/private.json');
const private2JSON = require('../../test/fixtures/private2.json');
const refreshJSON = require('../../test/fixtures/refresh.json');
const privateKey = fs.readFileSync('./test/fixtures/private.pem', 'utf-8');
const wellKnownPathWindows = path.join(
'C:',
'fake',
'home',
'gcloud',
'application_default_credentials.json'
);
const wellKnownPathLinux = path.join(
'/',
'fake',
'user',
'.config',
'gcloud',
'application_default_credentials.json'
);
describe('googleauth', () => {
let auth: GoogleAuth;
const sandbox = sinon.createSandbox();
let osStub: sinon.SinonStub<[], NodeJS.Platform>;
let exposeWindowsWellKnownFile: boolean;
let exposeLinuxWellKnownFile: boolean;
let createLinuxWellKnownStream: Function;
let createWindowsWellKnownStream: Function;
beforeEach(() => {
resetIsAvailableCache();
auth = new GoogleAuth();
exposeWindowsWellKnownFile = false;
exposeLinuxWellKnownFile = false;
createLinuxWellKnownStream = () => {
throw new Error();
};
createWindowsWellKnownStream = () => {
throw new Error();
};
const envVars = Object.assign({}, process.env, {
GCLOUD_PROJECT: undefined,
GOOGLE_APPLICATION_CREDENTIALS: undefined,
google_application_credentials: undefined,
HOME: path.join('/', 'fake', 'user'),
});
sandbox.stub(process, 'env').value(envVars);
osStub = sandbox.stub(os, 'platform').returns('linux');
sandbox
.stub(fs, 'existsSync')
.callThrough()
.withArgs(wellKnownPathLinux)
.callsFake(() => exposeLinuxWellKnownFile)
.withArgs(wellKnownPathWindows)
.callsFake(() => exposeWindowsWellKnownFile);
sandbox
.stub(fs, 'createReadStream')
.callThrough()
.withArgs(wellKnownPathLinux)
.callsFake(() => createLinuxWellKnownStream())
.withArgs(wellKnownPathWindows)
.callsFake(() => createWindowsWellKnownStream());
sandbox
.stub(fs, 'realpathSync')
.callThrough()
.withArgs(wellKnownPathLinux)
.returnsArg(0)
.withArgs(wellKnownPathWindows)
.returnsArg(0);
sandbox
.stub(child_process, 'exec')
.callThrough()
.withArgs('gcloud config config-helper --format json', sinon.match.func)
.callsArgWith(1, null, '', null);
const fakeStat = {isFile: () => true} as fs.Stats;
sandbox
.stub(fs, 'lstatSync')
.callThrough()
.withArgs(wellKnownPathLinux)
.returns(fakeStat)
.withArgs(wellKnownPathWindows)
.returns(fakeStat);
});
afterEach(() => {
nock.cleanAll();
sandbox.restore();
});
function mockWindows() {
osStub.returns('win32');
process.env.HOME = '';
process.env.APPDATA = path.join('C:', 'fake', 'home');
}
function mockWindowsWellKnownFile() {
exposeWindowsWellKnownFile = true;
createWindowsWellKnownStream = () =>
fs.createReadStream('./test/fixtures/private2.json');
}
function mockLinuxWellKnownFile() {
exposeLinuxWellKnownFile = true;
createLinuxWellKnownStream = () =>
fs.createReadStream('./test/fixtures/private2.json');
}
function nockIsGCE() {
const primary = nock(host)
.get(instancePath)
.reply(200, {}, HEADERS);
const secondary = nock(SECONDARY_HOST_ADDRESS)
.get(instancePath)
.reply(200, {}, HEADERS);
return {
done: () => {
try {
primary.done();
secondary.done();
} catch (_err) {
// secondary can sometimes complete prior to primary.
}
},
};
}
function nockNotGCE() {
const primary = nock(host)
.get(instancePath)
.replyWithError({code: 'ENOTFOUND'});
const secondary = nock(SECONDARY_HOST_ADDRESS)
.get(instancePath)
.replyWithError({code: 'ENOTFOUND'});
return {
done: () => {
try {
primary.done();
secondary.done();
} catch (_err) {
// secondary can sometimes complete prior to primary.
}
},
};
}
function nock500GCE() {
const primary = nock(host)
.get(instancePath)
.reply(500, {}, HEADERS);
const secondary = nock(SECONDARY_HOST_ADDRESS)
.get(instancePath)
.reply(500, {}, HEADERS);
return {
done: () => {
try {
primary.done();
secondary.done();
} catch (err) {
// secondary can sometimes complete prior to primary.
}
},
};
}
function nock404GCE() {
const primary = nock(host)
.get(instancePath)
.reply(404);
const secondary = nock(SECONDARY_HOST_ADDRESS)
.get(instancePath)
.reply(404);
return {
done: () => {
try {
primary.done();
secondary.done();
} catch (err) {
// secondary can sometimes complete prior to primary.
}
},
};
}
function createGetProjectIdNock(projectId = 'not-real') {
return nock(host)
.get(`${BASE_PATH}/project/project-id`)
.reply(200, projectId, HEADERS);
}
// Creates a standard JSON auth object for testing.
function createJwtJSON() {
return {
private_key_id: 'key123',
private_key: 'privatekey',
client_email: 'hello@youarecool.com',
client_id: 'client123',
type: 'service_account',
};
}
// Pretend that we're GCE, and mock an access token.
function mockGCE() {
const scope1 = nockIsGCE();
const auth = new GoogleAuth();
// tslint:disable-next-line no-any
sinon.stub(auth as any, 'getDefaultServiceProjectId').resolves();
const scope2 = nock(HOST_ADDRESS)
.get(tokenPath)
.reply(200, {access_token: 'abc123', expires_in: 10000}, HEADERS);
return {auth, scopes: [scope1, scope2]};
}
// Intercepts the specified environment variable, returning the specified
// value.
function mockEnvVar(name: string, value = '') {
const envVars = Object.assign({}, process.env, {[name]: value});
return sandbox.stub(process, 'env').value(envVars);
}
it('fromJSON should support the instantiated named export', () => {
const result = auth.fromJSON(createJwtJSON());
assert(result);
});
it('fromJson should error on null json', () => {
const auth = new GoogleAuth();
assert.throws(() => {
// Test verifies invalid parameter tests, which requires cast to any.
// tslint:disable-next-line no-any
(auth as any).fromJSON(null);
});
});
it('fromJson should not overwrite previous client configuration', async () => {
const auth = new GoogleAuth({
keyFilename: './test/fixtures/private.json',
});
auth.fromJSON({
client_email: 'batman@example.com',
private_key: 'abc123',
});
const client = (await auth.getClient()) as JWT;
assert.strictEqual(client.email, 'hello@youarecool.com');
});
it('fromAPIKey should error given an invalid api key', () => {
assert.throws(() => {
// Test verifies invalid parameter tests, which requires cast to any.
// tslint:disable-next-line no-any
(auth as any).fromAPIKey(null);
});
});
it('should make a request with the api key', async () => {
const scope = nock(BASE_URL)
.post(ENDPOINT)
.reply(function(uri) {
assert.strictEqual(this.req.headers['x-goog-api-key'][0], API_KEY);
return [200, RESPONSE_BODY];
});
const client = auth.fromAPIKey(API_KEY);
const res = await client.request({
url: BASE_URL + ENDPOINT,
method: 'POST',
data: {test: true},
});
assert.strictEqual(RESPONSE_BODY, res.data);
scope.done();
});
it('should put the api key in the headers', async () => {
const client = auth.fromAPIKey(API_KEY);
const headers = await client.getRequestHeaders();
assert.strictEqual(headers['X-Goog-Api-Key'], API_KEY);
});
it('should make a request while preserving original parameters', async () => {
const OTHER_QS_PARAM = {test: 'abc'};
const scope = nock(BASE_URL)
.post(ENDPOINT)
.query({test: OTHER_QS_PARAM.test})
.reply(function(uri) {
assert.strictEqual(this.req.headers['x-goog-api-key'][0], API_KEY);
assert(uri.indexOf('test=' + OTHER_QS_PARAM.test) > -1);
return [200, RESPONSE_BODY];
});
const client = auth.fromAPIKey(API_KEY);
const res = await client.request({
url: BASE_URL + ENDPOINT,
method: 'POST',
data: {test: true},
params: OTHER_QS_PARAM,
});
assert.strictEqual(RESPONSE_BODY, res.data);
scope.done();
});
it('should make client with eagerRetryThresholdMillis set', () => {
const client = auth.fromAPIKey(API_KEY, {
eagerRefreshThresholdMillis: 100,
});
assert.strictEqual(100, client.eagerRefreshThresholdMillis);
});
it('fromJSON should error on empty json', () => {
const auth = new GoogleAuth();
assert.throws(() => {
auth.fromJSON({});
});
});
it('fromJSON should error on missing client_email', () => {
const json = createJwtJSON();
delete json.client_email;
assert.throws(() => {
auth.fromJSON(json);
});
});
it('fromJSON should error on missing private_key', () => {
const json = createJwtJSON();
delete json.private_key;
assert.throws(() => {
auth.fromJSON(json);
});
});
it('fromJSON should create JWT with client_email', () => {
const json = createJwtJSON();
const result = auth.fromJSON(json);
assert.strictEqual(json.client_email, (result as JWT).email);
});
it('fromJSON should create JWT with private_key', () => {
const json = createJwtJSON();
const result = auth.fromJSON(json);
assert.strictEqual(json.private_key, (result as JWT).key);
});
it('fromJSON should create JWT with null scopes', () => {
const json = createJwtJSON();
const result = auth.fromJSON(json);
assert.strictEqual(undefined, (result as JWT).scopes);
});
it('fromJSON should create JWT with null subject', () => {
const json = createJwtJSON();
const result = auth.fromJSON(json);
assert.strictEqual(undefined, (result as JWT).subject);
});
it('fromJSON should create JWT with null keyFile', () => {
const json = createJwtJSON();
const result = auth.fromJSON(json);
assert.strictEqual(undefined, (result as JWT).keyFile);
});
it('fromJSON should create JWT which eagerRefreshThresholdMillisset when this is set for GoogleAuth', () => {
const json = createJwtJSON();
const result = auth.fromJSON(json, {eagerRefreshThresholdMillis: 5000});
assert.strictEqual(5000, (result as JWT).eagerRefreshThresholdMillis);
});
it('fromJSON should create JWT with 5min as value for eagerRefreshThresholdMillis', () => {
const json = createJwtJSON();
const result = auth.fromJSON(json);
assert.strictEqual(300000, (result as JWT).eagerRefreshThresholdMillis);
});
it('fromStream should error on null stream', done => {
// Test verifies invalid parameter tests, which requires cast to any.
// tslint:disable-next-line no-any
(auth as any).fromStream(null, (err: Error) => {
assert.strictEqual(true, err instanceof Error);
done();
});
});
it('fromStream should read the stream and create a jwt', async () => {
const stream = fs.createReadStream('./test/fixtures/private.json');
const res = await auth.fromStream(stream);
const jwt = res as JWT;
// Ensure that the correct bits were pulled from the stream.
assert.strictEqual(privateJSON.private_key, jwt.key);
assert.strictEqual(privateJSON.client_email, jwt.email);
assert.strictEqual(undefined, jwt.keyFile);
assert.strictEqual(undefined, jwt.subject);
assert.strictEqual(undefined, jwt.scope);
});
it('fromStream should read the stream and create a jwt with eager refresh', async () => {
const stream = fs.createReadStream('./test/fixtures/private.json');
const auth = new GoogleAuth();
const result = await auth.fromStream(stream, {
eagerRefreshThresholdMillis: 1000 * 60 * 60,
});
const jwt = result as JWT;
// Ensure that the correct bits were pulled from the stream.
assert.strictEqual(privateJSON.private_key, jwt.key);
assert.strictEqual(privateJSON.client_email, jwt.email);
assert.strictEqual(undefined, jwt.keyFile);
assert.strictEqual(undefined, jwt.subject);
assert.strictEqual(undefined, jwt.scope);
assert.strictEqual(1000 * 60 * 60, jwt.eagerRefreshThresholdMillis);
});
it('should read another stream and create a UserRefreshClient', async () => {
const stream = fs.createReadStream('./test/fixtures/refresh.json');
const auth = new GoogleAuth();
const res = await auth.fromStream(stream);
// Ensure that the correct bits were pulled from the stream.
const rc = res as UserRefreshClient;
assert.strictEqual(refreshJSON.client_id, rc._clientId);
assert.strictEqual(refreshJSON.client_secret, rc._clientSecret);
assert.strictEqual(refreshJSON.refresh_token, rc._refreshToken);
});
it('should read another stream and create a UserRefreshClient with eager refresh', async () => {
const stream = fs.createReadStream('./test/fixtures/refresh.json');
const auth = new GoogleAuth();
const result = await auth.fromStream(stream, {
eagerRefreshThresholdMillis: 100,
});
// Ensure that the correct bits were pulled from the stream.
const rc = result as UserRefreshClient;
assert.strictEqual(refreshJSON.client_id, rc._clientId);
assert.strictEqual(refreshJSON.client_secret, rc._clientSecret);
assert.strictEqual(refreshJSON.refresh_token, rc._refreshToken);
assert.strictEqual(100, rc.eagerRefreshThresholdMillis);
});
it('getApplicationCredentialsFromFilePath should not error on valid symlink', async () => {
if (isWindows) {
// git does not create symlinks on Windows
return;
}
await auth._getApplicationCredentialsFromFilePath(
'./test/fixtures/goodlink'
);
});
it('getApplicationCredentialsFromFilePath should error on invalid symlink', async () => {
await assertRejects(
auth._getApplicationCredentialsFromFilePath('./test/fixtures/badlink')
);
});
it('getApplicationCredentialsFromFilePath should error on valid link to invalid data', async () => {
if (isWindows) {
// git does not create symlinks on Windows
return;
}
await assertRejects(
auth._getApplicationCredentialsFromFilePath('./test/fixtures/emptylink')
);
});
it('getApplicationCredentialsFromFilePath should error on null file path', async () => {
try {
// Test verifies invalid parameter tests, which requires cast to any.
// tslint:disable-next-line no-any
await (auth as any)._getApplicationCredentialsFromFilePath(null);
} catch (e) {
return;
}
assert.fail('failed to throw');
});
it('getApplicationCredentialsFromFilePath should error on empty file path', async () => {
try {
await auth._getApplicationCredentialsFromFilePath('');
} catch (e) {
return;
}
assert.fail('failed to throw');
});
it('getApplicationCredentialsFromFilePath should error on non-string file path', async () => {
try {
// Test verifies invalid parameter tests, which requires cast to any.
// tslint:disable-next-line no-any
await auth._getApplicationCredentialsFromFilePath(2 as any);
} catch (e) {
return;
}
assert.fail('failed to throw');
});
it('getApplicationCredentialsFromFilePath should error on invalid file path', async () => {
try {
await auth._getApplicationCredentialsFromFilePath(
'./nonexistantfile.json'
);
} catch (e) {
return;
}
assert.fail('failed to throw');
});
it('getApplicationCredentialsFromFilePath should error on directory', async () => {
// Make sure that the following path actually does point to a directory.
const directory = './test/fixtures';
await assertRejects(
auth._getApplicationCredentialsFromFilePath(directory)
);
});
it('getApplicationCredentialsFromFilePath should handle errors thrown from createReadStream', async () => {
await assertRejects(
auth._getApplicationCredentialsFromFilePath('./does/not/exist.json'),
/ENOENT: no such file or directory/
);
});
it('getApplicationCredentialsFromFilePath should handle errors thrown from fromStream', async () => {
sandbox.stub(auth, 'fromStream').throws('🤮');
await assertRejects(
auth._getApplicationCredentialsFromFilePath(
'./test/fixtures/private.json'
),
/🤮/
);
});
it('getApplicationCredentialsFromFilePath should handle errors passed from fromStream', async () => {
// Set up a mock to return an error from the fromStream method.
sandbox.stub(auth, 'fromStream').throws('🤮');
await assertRejects(
auth._getApplicationCredentialsFromFilePath(
'./test/fixtures/private.json'
),
/🤮/
);
});
it('getApplicationCredentialsFromFilePath should correctly read the file and create a valid JWT', async () => {
const result = await auth._getApplicationCredentialsFromFilePath(
'./test/fixtures/private.json'
);
assert(result);
const jwt = result as JWT;
assert.strictEqual(privateJSON.private_key, jwt.key);
assert.strictEqual(privateJSON.client_email, jwt.email);
assert.strictEqual(undefined, jwt.keyFile);
assert.strictEqual(undefined, jwt.subject);
assert.strictEqual(undefined, jwt.scope);
});
it('getApplicationCredentialsFromFilePath should correctly read the file and create a valid JWT with eager refresh', async () => {
const result = await auth._getApplicationCredentialsFromFilePath(
'./test/fixtures/private.json',
{eagerRefreshThresholdMillis: 7000}
);
assert(result);
const jwt = result as JWT;
assert.strictEqual(privateJSON.private_key, jwt.key);
assert.strictEqual(privateJSON.client_email, jwt.email);
assert.strictEqual(undefined, jwt.keyFile);
assert.strictEqual(undefined, jwt.subject);
assert.strictEqual(undefined, jwt.scope);
assert.strictEqual(7000, jwt.eagerRefreshThresholdMillis);
});
it('tryGetApplicationCredentialsFromEnvironmentVariable should return null when env const is not set', async () => {
// Set up a mock to return a null path string.
mockEnvVar('GOOGLE_APPLICATION_CREDENTIALS');
const client = await auth._tryGetApplicationCredentialsFromEnvironmentVariable();
assert.strictEqual(client, null);
});
it('tryGetApplicationCredentialsFromEnvironmentVariable should return null when env const is empty string', async () => {
// Set up a mock to return an empty path string.
const stub = mockEnvVar('GOOGLE_APPLICATION_CREDENTIALS');
const client = await auth._tryGetApplicationCredentialsFromEnvironmentVariable();
assert.strictEqual(client, null);
});
it('tryGetApplicationCredentialsFromEnvironmentVariable should handle invalid environment variable', async () => {
// Set up a mock to return a path to an invalid file.
mockEnvVar('GOOGLE_APPLICATION_CREDENTIALS', './nonexistantfile.json');
try {
await auth._tryGetApplicationCredentialsFromEnvironmentVariable();
} catch (e) {
return;
}
assert.fail('failed to throw');
});
it('tryGetApplicationCredentialsFromEnvironmentVariable should handle valid environment variable', async () => {
// Set up a mock to return path to a valid credentials file.
mockEnvVar(
'GOOGLE_APPLICATION_CREDENTIALS',
'./test/fixtures/private.json'
);
const result = await auth._tryGetApplicationCredentialsFromEnvironmentVariable();
const jwt = result as JWT;
assert.strictEqual(privateJSON.private_key, jwt.key);
assert.strictEqual(privateJSON.client_email, jwt.email);
assert.strictEqual(undefined, jwt.keyFile);
assert.strictEqual(undefined, jwt.subject);
assert.strictEqual(undefined, jwt.scope);
});
it('tryGetApplicationCredentialsFromEnvironmentVariable should handle valid environment variable when there is eager refresh set', async () => {
// Set up a mock to return path to a valid credentials file.
mockEnvVar(
'GOOGLE_APPLICATION_CREDENTIALS',
'./test/fixtures/private.json'
);
const result = await auth._tryGetApplicationCredentialsFromEnvironmentVariable(
{eagerRefreshThresholdMillis: 60 * 60 * 1000}
);
const jwt = result as JWT;
assert.strictEqual(privateJSON.private_key, jwt.key);
assert.strictEqual(privateJSON.client_email, jwt.email);
assert.strictEqual(undefined, jwt.keyFile);
assert.strictEqual(undefined, jwt.subject);
assert.strictEqual(undefined, jwt.scope);
assert.strictEqual(60 * 60 * 1000, jwt.eagerRefreshThresholdMillis);
});
it('_tryGetApplicationCredentialsFromWellKnownFile should build the correct directory for Windows', async () => {
mockWindows();
mockWindowsWellKnownFile();
const result = (await auth._tryGetApplicationCredentialsFromWellKnownFile()) as JWT;
assert.ok(result);
assert.strictEqual(result.email, private2JSON.client_email);
});
it('_tryGetApplicationCredentialsFromWellKnownFile should build the correct directory for non-Windows', async () => {
mockLinuxWellKnownFile();
const client = (await auth._tryGetApplicationCredentialsFromWellKnownFile()) as JWT;
assert.strictEqual(client.email, private2JSON.client_email);
});
it('_tryGetApplicationCredentialsFromWellKnownFile should fail on Windows when APPDATA is not defined', async () => {
mockWindows();
mockEnvVar('APPDATA');
mockWindowsWellKnownFile();
const result = await auth._tryGetApplicationCredentialsFromWellKnownFile();
assert.strictEqual(null, result);
});
it('_tryGetApplicationCredentialsFromWellKnownFile should fail on non-Windows when HOME is not defined', async () => {
mockEnvVar('HOME');
mockLinuxWellKnownFile();
const result = await auth._tryGetApplicationCredentialsFromWellKnownFile();
assert.strictEqual(null, result);
});
it('_tryGetApplicationCredentialsFromWellKnownFile should fail on Windows when file does not exist', async () => {
mockWindows();
const result = await auth._tryGetApplicationCredentialsFromWellKnownFile();
assert.strictEqual(null, result);
});
it('_tryGetApplicationCredentialsFromWellKnownFile should fail on non-Windows when file does not exist', async () => {
const result = await auth._tryGetApplicationCredentialsFromWellKnownFile();
assert.strictEqual(null, result);
});
it('_tryGetApplicationCredentialsFromWellKnownFile should pass along a failure on Windows', async () => {
mockWindows();
mockWindowsWellKnownFile();
sandbox
.stub(auth, '_getApplicationCredentialsFromFilePath')
.rejects('🤮');
await assertRejects(
auth._tryGetApplicationCredentialsFromWellKnownFile(),
/🤮/
);
});
it('_tryGetApplicationCredentialsFromWellKnownFile should pass along a failure on non-Windows', async () => {
mockLinuxWellKnownFile();
sandbox
.stub(auth, '_getApplicationCredentialsFromFilePath')
.rejects('🤮');
await assertRejects(
auth._tryGetApplicationCredentialsFromWellKnownFile(),
/🤮/
);
});
it('getProjectId should return a new projectId the first time and a cached projectId the second time', async () => {
mockEnvVar('GCLOUD_PROJECT', STUB_PROJECT);
// Ask for credentials, the first time.
const projectIdPromise = auth.getProjectId();
const projectId = await projectIdPromise;
assert.strictEqual(projectId, STUB_PROJECT);
// Null out all the private functions that make this method work
// tslint:disable-next-line no-any
const anyd = auth as any;
anyd.getProductionProjectId = null;
anyd.getFileProjectId = null;
anyd.getDefaultServiceProjectId = null;
anyd.getGCEProjectId = null;
// Ask for projectId again, from the same auth instance. If it isn't
// cached, this will crash.
const projectId2 = await auth.getProjectId();
// Make sure we get the original cached projectId back
assert.strictEqual(STUB_PROJECT, projectId2);
// Now create a second GoogleAuth instance, and ask for projectId.
// We should get a new projectId instance this time.
const auth2 = new GoogleAuth();
const getProjectIdPromise = auth2.getProjectId();
assert.notStrictEqual(getProjectIdPromise, projectIdPromise);
});
it('getProjectId should use GCLOUD_PROJECT environment variable when it is set', async () => {
mockEnvVar('GCLOUD_PROJECT', STUB_PROJECT);
const projectId = await auth.getProjectId();
assert.strictEqual(projectId, STUB_PROJECT);
});
it('getProjectId should use `gcloud_project` environment variable when it is set', async () => {
process.env.gcloud_project = STUB_PROJECT;
const projectId = await auth.getProjectId();
assert.strictEqual(projectId, STUB_PROJECT);
});
it('getProjectId should use GOOGLE_CLOUD_PROJECT environment variable when it is set', async () => {
process.env.GOOGLE_CLOUD_PROJECT = STUB_PROJECT;
const projectId = await auth.getProjectId();
assert.strictEqual(projectId, STUB_PROJECT);
});
it('getProjectId should use `google_cloud_project` environment variable when it is set', async () => {
process.env['google_cloud_project'] = STUB_PROJECT;
const projectId = await auth.getProjectId();
assert.strictEqual(projectId, STUB_PROJECT);
});
it('getProjectId should use `keyFilename` when it is available', async () => {
const auth = new GoogleAuth({
keyFilename: './test/fixtures/private2.json',
});
const projectId = await auth.getProjectId();
assert.strictEqual(projectId, STUB_PROJECT);
});
it('getProjectId should use GOOGLE_APPLICATION_CREDENTIALS file when it is available', async () => {
process.env.GOOGLE_APPLICATION_CREDENTIALS =
'./test/fixtures/private2.json';
const projectId = await auth.getProjectId();
assert.strictEqual(projectId, STUB_PROJECT);
});
it('getProjectId should use `google_application_credentials` file when it is available', async () => {
process.env['google_application_credentials'] =
'./test/fixtures/private2.json';
const projectId = await auth.getProjectId();
assert.strictEqual(projectId, STUB_PROJECT);
});
it('getProjectId should prefer configured projectId', async () => {
mockEnvVar('GCLOUD_PROJECT', STUB_PROJECT);
mockEnvVar('GOOGLE_CLOUD_PROJECT', STUB_PROJECT);
mockEnvVar(
'GOOGLE_APPLICATION_CREDENTIALS',
'./test/fixtures/private2.json'
);
const PROJECT_ID = 'configured-project-id-should-be-preferred';
const auth = new GoogleAuth({projectId: PROJECT_ID});
const projectId = await auth.getProjectId();
assert.strictEqual(projectId, PROJECT_ID);
});
it('getProjectId should use Cloud SDK when it is available and env vars are not set', async () => {
// Set up the creds.
// * Environment variable is not set.
// * Well-known file is set up to point to private2.json
// * Running on GCE is set to true.
const stdout = JSON.stringify({
configuration: {properties: {core: {project: STUB_PROJECT}}},
});
((child_process.exec as unknown) as sinon.SinonStub).restore();
const stub = sandbox
.stub(child_process, 'exec')
.callsArgWith(1, null, stdout, null);
const projectId = await auth.getProjectId();
assert(stub.calledOnce);
assert.strictEqual(projectId, STUB_PROJECT);
});
it('getProjectId should use GCE when well-known file and env const are not set', async () => {
const scope = createGetProjectIdNock(STUB_PROJECT);
const projectId = await auth.getProjectId();
const stub = (child_process.exec as unknown) as sinon.SinonStub;
stub.restore();
assert(stub.calledOnce);
assert.strictEqual(projectId, STUB_PROJECT);
scope.done();
});
it('getApplicationDefault should return a new credential the first time and a cached credential the second time', async () => {
// Create a function which will set up a GoogleAuth instance to match
// on an environment variable json file, but not on anything else.
mockEnvVar(
'GOOGLE_APPLICATION_CREDENTIALS',
'./test/fixtures/private2.json'
);
// Ask for credentials, the first time.
const result = await auth.getApplicationDefault();
assert.notStrictEqual(null, result);
// Capture the returned credential.
const cachedCredential = result.credential;
// Make sure our special test bit is not set yet, indicating that
// this is a new credentials instance.
// Test verifies invalid parameter tests, which requires cast to any.
// tslint:disable-next-line no-any
assert.strictEqual(undefined, (cachedCredential as any).specialTestBit);
// Now set the special test bit.
// Test verifies invalid parameter tests, which requires cast to any.
// tslint:disable-next-line no-any
(cachedCredential as any).specialTestBit = 'monkey';
// Ask for credentials again, from the same auth instance. We expect
// a cached instance this time.
const result2 = (await auth.getApplicationDefault()).credential;
assert.notStrictEqual(null, result2);
// Make sure the special test bit is set on the credentials we got
// back, indicating that we got cached credentials. Also make sure
// the object instance is the same.
// Test verifies invalid parameter tests, which requires cast to
// any.
// tslint:disable-next-line no-any
assert.strictEqual('monkey', (result2 as any).specialTestBit);
assert.strictEqual(cachedCredential, result2);
// Now create a second GoogleAuth instance, and ask for
// credentials. We should get a new credentials instance this time.
const auth2 = new GoogleAuth();
const result3 = (await auth2.getApplicationDefault()).credential;
assert.notStrictEqual(null, result3);
// Make sure we get a new (non-cached) credential instance back.
// Test verifies invalid parameter tests, which requires cast to
// any.
// tslint:disable-next-line no-any
assert.strictEqual(undefined, (result3 as any).specialTestBit);
assert.notStrictEqual(cachedCredential, result3);
});
it('getApplicationDefault should cache the credential when using GCE', async () => {
const scopes = [nockIsGCE(), createGetProjectIdNock()];
// Ask for credentials, the first time.
const result = await auth.getApplicationDefault();
scopes.forEach(x => x.done());
assert.notStrictEqual(null, result);
// Capture the returned credential.
const cachedCredential = result.credential;
// Ask for credentials again, from the same auth instance. We expect
// a cached instance this time.
const result2 = (await auth.getApplicationDefault()).credential;
assert.notStrictEqual(null, result2);
// Make sure it's the same object
assert.strictEqual(cachedCredential, result2);
});
it('getApplicationDefault should use environment variable when it is set', async () => {
// Set up the creds.
// * Environment variable is set up to point to private.json
// * Well-known file is set up to point to private2.json
// * Running on GCE is set to true.
mockEnvVar(
'GOOGLE_APPLICATION_CREDENTIALS',
'./test/fixtures/private2.json'
);
mockWindows();
mockWindowsWellKnownFile();
nockIsGCE();
const res = await auth.getApplicationDefault();
const client = res.credential as JWT;
assert.strictEqual(private2JSON.private_key, client.key);
assert.strictEqual(private2JSON.client_email, client.email);
assert.strictEqual(undefined, client.keyFile);
assert.strictEqual(undefined, client.subject);
assert.strictEqual(undefined, client.scope);
});
it('should use well-known file when it is available and env const is not set', async () => {
// Set up the creds.
// * Environment variable is not set.
// * Well-known file is set up to point to private2.json
mockLinuxWellKnownFile();
const res = await auth.getApplicationDefault();
const client = res.credential as JWT;
assert.strictEqual(private2JSON.private_key, client.key);
assert.strictEqual(private2JSON.client_email, client.email);
assert.strictEqual(undefined, client.keyFile);
assert.strictEqual(undefined, client.subject);
assert.strictEqual(undefined, client.scope);
});
it('getApplicationDefault should use GCE when well-known file and env const are not set', async () => {
// Set up the creds.
// * Environment variable is not set.
// * Well-known file is not set.
// * Running on GCE is set to true.
const scopes = [nockIsGCE(), createGetProjectIdNock()];
const res = await auth.getApplicationDefault();
scopes.forEach(x => x.done());
// This indicates that we got a ComputeClient instance back, rather than
// a JWTClient.
assert.strictEqual(
'compute-placeholder',
res.credential.credentials.refresh_token
);
});
it('getApplicationDefault should report GCE error when checking for GCE fails', async () => {
// Set up the creds.
// * Environment variable is not set.
// * Well-known file is not set.
// * Running on GCE is set to true.
mockWindows();
sandbox.stub(auth, '_checkIsGCE').rejects('🤮');
await assertRejects(
auth.getApplicationDefault(),
/Unexpected error determining execution environment/
);