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

feat: make x-goog-user-project work for additional auth clients #848

Merged
merged 5 commits into from
Dec 10, 2019
Merged
Show file tree
Hide file tree
Changes from 3 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
24 changes: 24 additions & 0 deletions src/auth/authclient.ts
Expand Up @@ -23,6 +23,7 @@ export declare interface AuthClient {
}

export abstract class AuthClient extends EventEmitter {
protected quotaProjectId?: string;
transporter = new DefaultTransporter();
credentials: Credentials = {};

Expand All @@ -37,4 +38,27 @@ export abstract class AuthClient extends EventEmitter {
setCredentials(credentials: Credentials) {
this.credentials = credentials;
}

/**
* Append additional headers, e.g., x-goog-user-project, shared across the
* classes inheriting AuthClient. This method should be used by any method
* that overrides getRequestMetadataAsync(), which is a shared helper for
* setting request information in both gRPC and HTTP API calls.
*
* @param headers objedcdt to append additional headers to.
*/
protected addSharedMetadataHeaders(headers: {
[key: string]: string;
bcoe marked this conversation as resolved.
Show resolved Hide resolved
}): {[key: string]: string} {
// quota_project_id, 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.quotaProjectId
) {
headers['x-goog-user-project'] = this.quotaProjectId;
}
return headers;
}
}
8 changes: 6 additions & 2 deletions src/auth/jwtclient.ts
Expand Up @@ -128,7 +128,11 @@ export class JWT extends OAuth2Client {
}).target_audience
) {
const {tokens} = await this.refreshToken();
return {headers: {Authorization: `Bearer ${tokens.id_token}`}};
return {
headers: this.addSharedMetadataHeaders({
Authorization: `Bearer ${tokens.id_token}`,
}),
};
} else {
// no scopes have been set, but a uri has been provided. Use JWTAccess
// credentials.
Expand All @@ -139,7 +143,7 @@ export class JWT extends OAuth2Client {
url,
this.additionalClaims
);
return {headers};
return {headers: this.addSharedMetadataHeaders(headers)};
}
} else {
return super.getRequestMetadataAsync(url);
Expand Down
14 changes: 1 addition & 13 deletions src/auth/oauth2client.ts
Expand Up @@ -383,7 +383,6 @@ export class OAuth2Client extends AuthClient {
private certificateCache: Certificates = {};
private certificateExpiry: Date | null = null;
private certificateCacheFormat: CertificateFormat = CertificateFormat.PEM;
protected quotaProjectId?: string;
protected refreshTokenPromises = new Map<string, Promise<GetTokenResponse>>();

// TODO: refactor tests to make this private
Expand Down Expand Up @@ -808,18 +807,7 @@ export class OAuth2Client extends AuthClient {
const headers: {[index: string]: string} = {
Authorization: credentials.token_type + ' ' + tokens.access_token,
};

// quota_project_id, 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.quotaProjectId
) {
headers['x-goog-user-project'] = this.quotaProjectId;
}

return {headers, res: r.res};
return {headers: this.addSharedMetadataHeaders(headers), res: r.res};
}

/**
Expand Down
13 changes: 13 additions & 0 deletions test/fixtures/service-account-with-quota.json
@@ -0,0 +1,13 @@
{
"type": "service_account",
"project_id": "my-account",
"private_key_id": "abc123",
"private_key": "-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQDI+tbB7kfmWFsD6Y+GUzRazzE62JbajO806zYVJrIx9TsmPx/E\nzfHVJy2hlONaSOfKJD7udT1w4bVo+OpWkMvXYAiqZFg+4EAg+FvuBzToyD2VyiqZ\n6hOXT3xVzPFLJDwpATm7SvGmzIbhAHLOH6QBePEw1ADhyXW2sHZbzzwEmwIDAQAB\nAoGBAJcmTy06j0hlWs3uccqL+OvytwuSqKFlLOGXo+z0VT/NNtbk0neoix/Lfz3u\nQ6469lfIOqwL8FFc7por2dGQxDu42yO2FVSaKkgNKZz2BIv64sZkKiSvMB/eScBe\nRBsUClBd828jShDlAaOucyoDqajop9EfiuysBPjSLo7Li4MBAkEA6h/tFUeyM0hv\n5OuoZU+gUTCVBGePaBFjarS1ufq8XiIIG9UPDIDGaYnBjWYJmodojwiigJ7glidc\nxV0yfu3kywJBANvCHT7QAXrnTw7xPMin0VbazUujf7fgTSpUM5/CMhI9AlAJZhx8\np8xPJG9mOd44lFS765IwHupVLqA5sPgUNXECQH3cAdihvUNiWnymztT/tEBRLJq8\njVQ1nMs9MEA1cVPtWYyUwc1H4OHVY05/HwSKbIQP8UPRpQwzRuT2j/G6M3cCQCbj\nEaPE0Q47kjzVqWjkcWHKNBvXYcla8qyz27LAfXXGv/sDvsL5uAOqWYsw7rqJDo5z\n9nqW81GKI0cNDmjHwrECQGnF6BaF1SvKw/kbKeF34OVw5FQOmmGZP5y3b49wC8Rp\nhGrm3z7yM8jiQIywqpv5KDBKKMiKMR5pIcbxscalY4k=\n-----END RSA PRIVATE KEY-----\n",
bcoe marked this conversation as resolved.
Show resolved Hide resolved
"client_email": "fake@example.com",
"client_id": "222222222222222222222",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/fake@example.com",
"quota_project_id": "fake-quota-project"
}
2 changes: 2 additions & 0 deletions test/test.googleauth.ts
Expand Up @@ -1469,6 +1469,7 @@ describe('googleauth', () => {
);
const auth = new GoogleAuth();
const client = await auth.getClient();
assert(client instanceof UserRefreshClient);
const headers = await client.getRequestHeaders();
assert.strictEqual(headers['x-goog-user-project'], 'my-quota-project');
tokenReq.done();
Expand All @@ -1480,6 +1481,7 @@ describe('googleauth', () => {
);
const auth = new GoogleAuth();
const client = await auth.getClient();
assert(client instanceof UserRefreshClient);
const apiReq = nock(BASE_URL)
.post(ENDPOINT)
.reply(function(uri) {
Expand Down
18 changes: 17 additions & 1 deletion test/test.jwt.ts
Expand Up @@ -18,7 +18,7 @@ import * as jws from 'jws';
import * as nock from 'nock';
import * as sinon from 'sinon';

import {JWT} from '../src';
import {GoogleAuth, JWT} from '../src';
import {CredentialRequest, JWTInput} from '../src/auth/credentials';

const keypair = require('keypair');
Expand Down Expand Up @@ -810,3 +810,19 @@ it('getCredentials should handle a json keyFile', async () => {
assert.strictEqual(private_key, json.private_key);
assert.strictEqual(client_email, json.client_email);
});

it('getRequestHeaders populates x-goog-user-project for JWT client', async () => {
// The first time auth.getClient() is called /token endpoint is used to
// fetch a JWT.
const tokenReq = nock('https://www.googleapis.com')
.post('/oauth2/v4/token')
.reply(200, {});
const auth = new GoogleAuth({
credentials: require('../../test/fixtures/service-account-with-quota.json'),
});
const client = await auth.getClient();
assert(client instanceof JWT);
const headers = await client.getRequestHeaders();
assert.strictEqual(headers['x-goog-user-project'], 'fake-quota-project');
tokenReq.done();
});