Skip to content

Commit

Permalink
fix: cache GCE credentials (#286)
Browse files Browse the repository at this point in the history
  • Loading branch information
JustinBeckwith authored Feb 17, 2018
1 parent 12feb2c commit 5699b90
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/auth/googleauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
20 changes: 20 additions & 0 deletions test/test.googleauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down

0 comments on commit 5699b90

Please sign in to comment.