Skip to content
This repository was archived by the owner on Nov 20, 2025. It is now read-only.

Commit 4803e3c

Browse files
fix(compute): correctly specify scopes when fetching token (#735)
1 parent 62e2abf commit 4803e3c

File tree

2 files changed

+22
-10
lines changed

2 files changed

+22
-10
lines changed

src/auth/computeclient.ts

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,13 +80,15 @@ export class Compute extends OAuth2Client {
8080
const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;
8181
let data: CredentialRequest;
8282
try {
83-
data = await gcpMetadata.instance({
83+
const instanceOptions: gcpMetadata.Options = {
8484
property: tokenPath,
85-
params: {
86-
scopes: this.scopes,
87-
// TODO: clean up before submit, fix upstream type bug
88-
} as {},
89-
});
85+
};
86+
if (this.scopes.length > 0) {
87+
instanceOptions.params = {
88+
scopes: this.scopes.join(','),
89+
};
90+
}
91+
data = await gcpMetadata.instance(instanceOptions);
9092
} catch (e) {
9193
e.message = `Could not refresh access token: ${e.message}`;
9294
this.wrapError(e);

test/test.compute.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ const tokenPath = `${BASE_PATH}/instance/service-accounts/default/token`;
2929
function mockToken(statusCode = 200, scopes?: string[]) {
3030
let path = tokenPath;
3131
if (scopes && scopes.length > 0) {
32-
path += '?' + qs.stringify({scopes});
32+
path += `?scopes=${encodeURIComponent(scopes.join(','))}`;
3333
}
3434
return nock(HOST_ADDRESS)
3535
.get(path, undefined, {reqheaders: HEADERS})
@@ -68,15 +68,25 @@ it('should get an access token for the first request', async () => {
6868
assert.strictEqual(compute.credentials.access_token, 'abc123');
6969
});
7070

71-
it('should include scopes when asking for the token', async () => {
71+
it('should URI-encode and comma-separate scopes when fetching the token', async () => {
7272
const scopes = [
7373
'https://www.googleapis.com/reader',
7474
'https://www.googleapis.com/auth/plus',
7575
];
76-
const nockScopes = [mockToken(200, scopes), mockExample()];
76+
77+
const path = `${tokenPath}?scopes=${encodeURIComponent(scopes.join(','))}`;
78+
79+
const tokenFetchNock = nock(HOST_ADDRESS)
80+
.get(path, undefined, {reqheaders: HEADERS})
81+
.reply(200, {access_token: 'abc123', expires_in: 10000}, HEADERS);
82+
const apiRequestNock = mockExample();
83+
7784
const compute = new Compute({scopes});
7885
await compute.request({url});
79-
nockScopes.forEach(s => s.done());
86+
87+
tokenFetchNock.done();
88+
apiRequestNock.done();
89+
8090
assert.strictEqual(compute.credentials.access_token, 'abc123');
8191
});
8292

0 commit comments

Comments
 (0)