From 5699b90b20ae58e89224fb492474de7c8c17f48f Mon Sep 17 00:00:00 2001 From: Justin Beckwith Date: Fri, 16 Feb 2018 18:02:09 -0800 Subject: [PATCH] fix: cache GCE credentials (#286) --- src/auth/googleauth.ts | 5 +++-- test/test.googleauth.ts | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/auth/googleauth.ts b/src/auth/googleauth.ts index 34354a33..a8e187b0 100644 --- a/src/auth/googleauth.ts +++ b/src/auth/googleauth.ts @@ -225,8 +225,9 @@ export class GoogleAuth { if (gce) { // For GCE, just return a default ComputeClient. It will take care of // the rest. - // TODO: cache the result - return {projectId: null, credential: new Compute(options)}; + this.cachedCredential = new Compute(options); + projectId = await this.getDefaultProjectId(); + return {projectId, credential: this.cachedCredential}; } else { // We failed to find the default credentials. Bail out with an error. throw new Error( diff --git a/test/test.googleauth.ts b/test/test.googleauth.ts index f53e4c30..a7be5598 100644 --- a/test/test.googleauth.ts +++ b/test/test.googleauth.ts @@ -1132,6 +1132,26 @@ describe('.getApplicationDefault', () => { assert.notEqual(cachedCredential, result3); }); + it('should cache the credential when using GCE', async () => { + nockIsGCE(); + const auth = new GoogleAuth(); + + // Ask for credentials, the first time. + const result = await auth.getApplicationDefault(); + assert.notEqual(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.notEqual(null, result2); + + // Make sure it's the same object + assert.equal(cachedCredential, result2); + }); + it('should use environment variable when it is set', (done) => { // We expect private.json to be the file that is used. const fileContents =