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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Implement UserRefreshClient#fetchIdToken #1811

Merged
merged 5 commits into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
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