Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: throw when adc cannot acquire a projectId #658

Merged
merged 3 commits into from
Apr 2, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 18 additions & 13 deletions src/auth/googleauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,19 +170,24 @@ export class GoogleAuth {
// - Cloud SDK: `gcloud config config-helper --format json`
// - GCE project ID from metadata server)
if (!this._getDefaultProjectIdPromise) {
this._getDefaultProjectIdPromise =
new Promise(async (resolve, reject) => {
try {
const projectId = this.getProductionProjectId() ||
await this.getFileProjectId() ||
await this.getDefaultServiceProjectId() ||
await this.getGCEProjectId();
this._cachedProjectId = projectId;
resolve(projectId);
} catch (e) {
reject(e);
}
});
this._getDefaultProjectIdPromise = new Promise(async (resolve, reject) => {
try {
const projectId = this.getProductionProjectId() ||
await this.getFileProjectId() ||
await this.getDefaultServiceProjectId() ||
await this.getGCEProjectId();
this._cachedProjectId = projectId;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this addition, I'd way rather the library fail early than run in an undefined state with no project ID.

if (!projectId) {
throw new Error(
'Unable to detect a Project Id in the current environment. \n' +
'To learn more about authentication and Google APIs, visit: \n' +
'https://cloud.google.com/docs/authentication/getting-started');
}
resolve(projectId);
} catch (e) {
reject(e);
}
});
}
return this._getDefaultProjectIdPromise;
}
Expand Down
10 changes: 10 additions & 0 deletions test/test.googleauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1467,4 +1467,14 @@ describe('googleauth', () => {
const client = await auth.getClient() as JWT;
assert.strictEqual(client.subject, subject);
});

it('should throw if getProjectId cannot find a projectId', async () => {
blockGoogleApplicationCredentialEnvironmentVariable();
auth._fileExists = () => false;
// tslint:disable-next-line no-any
sinon.stub(auth as any, 'getDefaultServiceProjectId').resolves();
await assertRejects(
auth.getProjectId(),
/Unable to detect a Project Id in the current environment/);
});
});