Skip to content

Commit

Permalink
feat: Implement UserRefreshClient#fetchIdToken (#1811)
Browse files Browse the repository at this point in the history
* feat: Implement `UserRefreshClient#fetchIdToken`

* test: UserRefreshClient client for getIdTokenClient

* refactor: Use `target_audience` > `audience`

* refactor: Use `transporter`

Removes redundant calls

* test: Improve tests
  • Loading branch information
d-goog authored May 10, 2024
1 parent bb306ef commit ae8bc54
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 16 deletions.
23 changes: 22 additions & 1 deletion src/auth/refreshclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@
// limitations under the License.

import * as stream from 'stream';
import {JWTInput} from './credentials';
import {CredentialRequest, JWTInput} from './credentials';
import {
GetTokenResponse,
OAuth2Client,
OAuth2ClientOptions,
} from './oauth2client';
import {stringify} from 'querystring';

export const USER_REFRESH_ACCOUNT_TYPE = 'authorized_user';

Expand Down Expand Up @@ -78,6 +79,26 @@ export class UserRefreshClient extends OAuth2Client {
return super.refreshTokenNoCache(this._refreshToken);
}

async fetchIdToken(targetAudience: string): Promise<string> {
const res = await this.transporter.request<CredentialRequest>({
...UserRefreshClient.RETRY_CONFIG,
url: this.endpoints.oauth2TokenUrl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
method: 'POST',
data: stringify({
client_id: this._clientId,
client_secret: this._clientSecret,
grant_type: 'refresh_token',
refresh_token: this._refreshToken,
target_audience: targetAudience,
}),
});

return res.data.id_token!;
}

/**
* Create a UserRefreshClient credentials instance using the given input
* options.
Expand Down
74 changes: 59 additions & 15 deletions test/test.googleauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
import {BaseExternalAccountClient} from '../src/auth/baseexternalclient';
import {AuthClient, DEFAULT_UNIVERSE} from '../src/auth/authclient';
import {ExternalAccountAuthorizedUserClient} from '../src/auth/externalAccountAuthorizedUserClient';
import {stringify} from 'querystring';

nock.disableNetConnect();

Expand Down Expand Up @@ -1520,37 +1521,80 @@ describe('googleauth', () => {
assert(client.idTokenProvider instanceof JWT);
});

it('should call getClient for getIdTokenClient', async () => {
it('should return a UserRefreshClient client for getIdTokenClient', async () => {
// Set up a mock to return path to a valid credentials file.
mockEnvVar(
'GOOGLE_APPLICATION_CREDENTIALS',
'./test/fixtures/private.json'
'./test/fixtures/refresh.json'
);
mockEnvVar('GOOGLE_CLOUD_PROJECT', 'some-project-id');

const spy = sinon.spy(auth, 'getClient');
const client = await auth.getIdTokenClient('a-target-audience');
assert(client instanceof IdTokenClient);
assert(spy.calledOnce);
assert(client.idTokenProvider instanceof UserRefreshClient);
});

it('should fail when using UserRefreshClient', async () => {
it('should properly use `UserRefreshClient` client for `getIdTokenClient`', async () => {
// Set up a mock to return path to a valid credentials file.
mockEnvVar(
'GOOGLE_APPLICATION_CREDENTIALS',
'./test/fixtures/refresh.json'
);
mockEnvVar('GOOGLE_CLOUD_PROJECT', 'some-project-id');

try {
await auth.getIdTokenClient('a-target-audience');
} catch (e) {
assert(e instanceof Error);
assert(
e.message.startsWith('Cannot fetch ID token in this environment')
);
return;
}
assert.fail('failed to throw');
// Assert `UserRefreshClient`
const baseClient = await auth.getClient();
assert(baseClient instanceof UserRefreshClient);

// Setup variables
const idTokenPayload = Buffer.from(JSON.stringify({exp: 100})).toString(
'base64'
);
const testIdToken = `TEST.${idTokenPayload}.TOKEN`;
const targetAudience = 'a-target-audience';
const tokenEndpoint = new URL(baseClient.endpoints.oauth2TokenUrl);
const expectedTokenRequestBody = stringify({
client_id: baseClient._clientId,
client_secret: baseClient._clientSecret,
grant_type: 'refresh_token',
refresh_token: baseClient._refreshToken,
target_audience: targetAudience,
});
const url = new URL('https://my-protected-endpoint.a.app');
const expectedRes = {hello: true};

// Setup mock endpoints
nock(tokenEndpoint.origin)
.post(tokenEndpoint.pathname, expectedTokenRequestBody)
.reply(200, {id_token: testIdToken});
nock(url.origin, {
reqheaders: {
authorization: `Bearer ${testIdToken}`,
},
})
.get(url.pathname)
.reply(200, expectedRes);

// Make assertions
const client = await auth.getIdTokenClient(targetAudience);
assert(client instanceof IdTokenClient);
assert(client.idTokenProvider instanceof UserRefreshClient);

const res = await client.request({url});
assert.deepStrictEqual(res.data, expectedRes);
});

it('should call getClient for getIdTokenClient', async () => {
// Set up a mock to return path to a valid credentials file.
mockEnvVar(
'GOOGLE_APPLICATION_CREDENTIALS',
'./test/fixtures/private.json'
);

const spy = sinon.spy(auth, 'getClient');
const client = await auth.getIdTokenClient('a-target-audience');
assert(client instanceof IdTokenClient);
assert(spy.calledOnce);
});

describe('getUniverseDomain', () => {
Expand Down

0 comments on commit ae8bc54

Please sign in to comment.