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: expand on x-goog-user-project to handle auth.getClient() #831

Merged
merged 6 commits into from Nov 21, 2019
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
16 changes: 1 addition & 15 deletions src/auth/googleauth.ts
Expand Up @@ -745,21 +745,7 @@ export class GoogleAuth {
*/
async getRequestHeaders(url?: string) {
const client = await this.getClient();
let headers = client.getRequestHeaders(url);
// quota_project, stored in application_default_credentials.json, is set in
// the x-goog-user-project header, to indicate an alternate account for
// billing and quota:
if (this.jsonContent?.quota_project) {
// If x-goog-user-project has explicitly been set in the client headers,
// it takes precedence.
headers = Object.assign(
{
'x-goog-user-project': this.jsonContent.quota_project,
},
headers
);
}
return headers;
return client.getRequestHeaders(url);
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/auth/jwtclient.ts
Expand Up @@ -267,6 +267,7 @@ export class JWT extends OAuth2Client {
this.key = json.private_key;
this.keyId = json.private_key_id;
this.projectId = json.project_id;
this.quotaProject = json.quota_project;
}

/**
Expand Down
16 changes: 13 additions & 3 deletions src/auth/oauth2client.ts
Expand Up @@ -28,7 +28,7 @@ import * as messages from '../messages';
import {BodyResponseCallback} from '../transporters';

import {AuthClient} from './authclient';
import {CredentialRequest, Credentials} from './credentials';
import {CredentialRequest, Credentials, JWTInput} from './credentials';
import {LoginTicket, TokenPayload} from './loginticket';

export interface Certificates {
Expand Down Expand Up @@ -367,6 +367,7 @@ export class OAuth2Client extends AuthClient {
private certificateCache: Certificates = {};
private certificateExpiry: Date | null = null;
private certificateCacheFormat: CertificateFormat = CertificateFormat.PEM;
protected quotaProject?: string;
protected refreshTokenPromises = new Map<string, Promise<GetTokenResponse>>();

// TODO: refactor tests to make this private
Expand Down Expand Up @@ -742,8 +743,17 @@ export class OAuth2Client extends AuthClient {
* @param url The optional url being authorized
*/
async getRequestHeaders(url?: string): Promise<Headers> {
const res = await this.getRequestMetadataAsync(url);
return res.headers;
const headers = (await this.getRequestMetadataAsync(url)).headers;
// quota_project, stored in application_default_credentials.json, is set in
// the x-goog-user-project header, to indicate an alternate account for
// billing and quota:
if (
!headers['x-goog-user-project'] && // don't override a value the user sets.
this.quotaProject
) {
headers['x-goog-user-project'] = this.quotaProject;
}
return headers;
}

protected async getRequestMetadataAsync(
Expand Down
8 changes: 7 additions & 1 deletion src/auth/refreshclient.ts
Expand Up @@ -16,7 +16,12 @@

import * as stream from 'stream';
import {JWTInput} from './credentials';
import {GetTokenResponse, OAuth2Client, RefreshOptions} from './oauth2client';
import {
Headers,
GetTokenResponse,
OAuth2Client,
RefreshOptions,
} from './oauth2client';

export interface UserRefreshClientOptions extends RefreshOptions {
clientId?: string;
Expand Down Expand Up @@ -112,6 +117,7 @@ export class UserRefreshClient extends OAuth2Client {
this._clientSecret = json.client_secret;
this._refreshToken = json.refresh_token;
this.credentials.refresh_token = json.refresh_token;
this.quotaProject = json.quota_project;
}

/**
Expand Down
@@ -0,0 +1,7 @@
{
"client_id": "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com",
"client_secret": "privatekey",
"refresh_token": "refreshtoken",
"type": "authorized_user",
"project_id": "my-project"
}
34 changes: 24 additions & 10 deletions test/test.googleauth.ts
Expand Up @@ -1445,11 +1445,11 @@ describe('googleauth', () => {
);
});

it('getRequestHeaders() populates x-goog-user-project with quota_project if present', async () => {
it('getRequestHeaders populates x-goog-user-project with quota_project if present', async () => {
// Fake a home directory in our fixtures path.
mockEnvVar('GCLOUD_PROJECT', 'my-fake-project');
mockEnvVar('HOME', './test/fixtures');
mockEnvVar('APPDATA', './test/fixtures/.config');
mockEnvVar('HOME', './test/fixtures/config-with-quota');
mockEnvVar('APPDATA', './test/fixtures/config-with-quota/.config');
// The first time auth.getClient() is called /token endpoint is used to
// fetch a JWT.
const req = nock('https://oauth2.googleapis.com')
Expand All @@ -1462,24 +1462,38 @@ describe('googleauth', () => {
req.done();
});

it('getRequestHeaders() does not populate x-goog-user-project if quota_project is not present', async () => {
it('getRequestHeaders does not populate x-goog-user-project if quota_project is not present', async () => {
// Fake a home directory in our fixtures path.
mockEnvVar('GCLOUD_PROJECT', 'my-fake-project');
mockEnvVar('HOME', './test/fixtures');
mockEnvVar('APPDATA', './test/fixtures/.config');
mockEnvVar('HOME', './test/fixtures/config-no-quota');
mockEnvVar('APPDATA', './test/fixtures/config-no-quota/.config');
// The first time auth.getClient() is called /token endpoint is used to
// fetch a JWT.
const req = nock('https://oauth2.googleapis.com')
.post('/token')
.reply(200, {});

const auth = new GoogleAuth();
// Force jsonContent to load, and then remove the quota_project parameter.
await auth.getClient();
delete auth.jsonContent!.quota_project;

const headers = await auth.getRequestHeaders();
assert.strictEqual(headers['x-goog-user-project'], undefined);
req.done();
});

it('getRequestHeaders populates x-goog-user-project when called on returned client', async () => {
// Fake a home directory in our fixtures path.
mockEnvVar('GCLOUD_PROJECT', 'my-fake-project');
mockEnvVar('HOME', './test/fixtures/config-with-quota');
mockEnvVar('APPDATA', './test/fixtures/config-with-quota/.config');
// The first time auth.getClient() is called /token endpoint is used to
// fetch a JWT.
const req = nock('https://oauth2.googleapis.com')
.post('/token')
.reply(200, {});

const auth = new GoogleAuth();
const client = await auth.getClient();
const headers = await client.getRequestHeaders();
assert.strictEqual(headers['x-goog-user-project'], 'my-quota-project');
req.done();
});
});
19 changes: 19 additions & 0 deletions test/test.refresh.ts
Expand Up @@ -16,6 +16,7 @@

import * as assert from 'assert';
import * as fs from 'fs';
import * as nock from 'nock';
import {UserRefreshClient} from '../src';

// Creates a standard JSON credentials object for testing.
Expand Down Expand Up @@ -123,3 +124,21 @@ it('fromStream should read the stream and create a UserRefreshClient', done => {
done();
});
});

it('getRequestHeaders should populate x-goog-user-project header if quota_project present', async () => {
// The first time auth.getRequestHeaders() is called /token endpoint is used to
// fetch a JWT.
const req = nock('https://oauth2.googleapis.com')
.post('/token')
.reply(200, {});

// Fake loading default credentials with quota project set:
const stream = fs.createReadStream(
'./test/fixtures/config-with-quota/.config/gcloud/application_default_credentials.json'
);
const refresh = new UserRefreshClient();
await refresh.fromStream(stream);

const headers = await refresh.getRequestHeaders();
assert.strictEqual(headers['x-goog-user-project'], 'my-quota-project');
});