Skip to content

Commit

Permalink
fix(compute): correctly specify scopes when fetching token (#735)
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenplusplus authored Jun 18, 2019
1 parent 62e2abf commit 4803e3c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
14 changes: 8 additions & 6 deletions src/auth/computeclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,15 @@ export class Compute extends OAuth2Client {
const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;
let data: CredentialRequest;
try {
data = await gcpMetadata.instance({
const instanceOptions: gcpMetadata.Options = {
property: tokenPath,
params: {
scopes: this.scopes,
// TODO: clean up before submit, fix upstream type bug
} as {},
});
};
if (this.scopes.length > 0) {
instanceOptions.params = {
scopes: this.scopes.join(','),
};
}
data = await gcpMetadata.instance(instanceOptions);
} catch (e) {
e.message = `Could not refresh access token: ${e.message}`;
this.wrapError(e);
Expand Down
18 changes: 14 additions & 4 deletions test/test.compute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const tokenPath = `${BASE_PATH}/instance/service-accounts/default/token`;
function mockToken(statusCode = 200, scopes?: string[]) {
let path = tokenPath;
if (scopes && scopes.length > 0) {
path += '?' + qs.stringify({scopes});
path += `?scopes=${encodeURIComponent(scopes.join(','))}`;
}
return nock(HOST_ADDRESS)
.get(path, undefined, {reqheaders: HEADERS})
Expand Down Expand Up @@ -68,15 +68,25 @@ it('should get an access token for the first request', async () => {
assert.strictEqual(compute.credentials.access_token, 'abc123');
});

it('should include scopes when asking for the token', async () => {
it('should URI-encode and comma-separate scopes when fetching the token', async () => {
const scopes = [
'https://www.googleapis.com/reader',
'https://www.googleapis.com/auth/plus',
];
const nockScopes = [mockToken(200, scopes), mockExample()];

const path = `${tokenPath}?scopes=${encodeURIComponent(scopes.join(','))}`;

const tokenFetchNock = nock(HOST_ADDRESS)
.get(path, undefined, {reqheaders: HEADERS})
.reply(200, {access_token: 'abc123', expires_in: 10000}, HEADERS);
const apiRequestNock = mockExample();

const compute = new Compute({scopes});
await compute.request({url});
nockScopes.forEach(s => s.done());

tokenFetchNock.done();
apiRequestNock.done();

assert.strictEqual(compute.credentials.access_token, 'abc123');
});

Expand Down

0 comments on commit 4803e3c

Please sign in to comment.