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: defines IdentityPoolClient used for K8s and Azure workloads #1042

Merged
merged 14 commits into from Aug 21, 2020
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
Expand Up @@ -47,7 +47,7 @@ const EXTERNAL_ACCOUNT_TYPE = 'external_account';
/**
* Base external account credentials json interface.
*/
export interface ExternalAccountClientOptions {
export interface BaseExternalAccountClientOptions {
type: string;
audience: string;
subject_token_type: string;
Expand Down Expand Up @@ -86,7 +86,7 @@ interface CredentialsWithResponse extends Credentials {
* retrieving the external credential based on the environment and
* credential_source will be left for the subclasses.
*/
export abstract class ExternalAccountClient extends AuthClient {
export abstract class BaseExternalAccountClient extends AuthClient {
/**
* OAuth scopes for the GCP access token to use. When not provided,
* the default https://www.googleapis.com/auth/cloud-platform is
Expand All @@ -102,7 +102,7 @@ export abstract class ExternalAccountClient extends AuthClient {
private readonly stsCredential: sts.StsCredentials;

/**
* Instantiate an ExternalAccountClient instance using the provided JSON
* Instantiate a BaseExternalAccountClient instance using the provided JSON
* object loaded from an external account credentials file.
* @param options The external account options object typically loaded
* from the external account JSON credential file.
Expand All @@ -111,7 +111,7 @@ export abstract class ExternalAccountClient extends AuthClient {
* whether to retry on 401/403 API request errors.
*/
constructor(
options: ExternalAccountClientOptions,
options: BaseExternalAccountClientOptions,
additionalOptions?: RefreshOptions
) {
super();
Expand Down
140 changes: 140 additions & 0 deletions src/auth/identitypoolclient.ts
@@ -0,0 +1,140 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import {GaxiosOptions} from 'gaxios';
import * as fs from 'fs';
import {promisify} from 'util';

import {
BaseExternalAccountClient,
BaseExternalAccountClientOptions,
} from './baseexternalclient';
import {RefreshOptions} from './oauth2client';

const readFile = promisify(fs.readFile);

/**
* Url-sourced/file-sourced credentials json interface.
* This is used for K8s and Azure workloads.
*/
export interface IdentityPoolClientOptions
extends BaseExternalAccountClientOptions {
credential_source: {
file?: string;
url?: string;
headers?: {
[key: string]: string;
};
};
}

/**
* Defines the Url-sourced and file-sourced external account clients mainly
* used for K8s and Azure workloads.
*/
export class IdentityPoolClient extends BaseExternalAccountClient {
private readonly file?: string;
private readonly url?: string;
private readonly headers?: {[key: string]: string};

/**
* Instantiate an IdentityPoolClient instance using the provided JSON
* object loaded from an external account credentials file.
* An error is thrown if the credential is not a valid file-sourced or
* url-sourced credential.
* @param options The external account options object typically loaded
* from the external account JSON credential file.
* @param additionalOptions Optional additional behavior customization
* options. These currently customize expiration threshold time and
* whether to retry on 401/403 API request errors.
*/
constructor(
options: IdentityPoolClientOptions,
additionalOptions?: RefreshOptions
) {
super(options, additionalOptions);
this.file = options.credential_source.file;
this.url = options.credential_source.url;
this.headers = options.credential_source.headers;
if (!this.file && !this.url) {
throw new Error('No valid Identity Pool "credential_source" provided');
}
}

/**
* Triggered when a external subject token is needed to be exchanged for a GCP
* access token via GCP STS endpoint.
* This uses the `options.credential_source` object to figure out how
* to retrieve the token using the current environment. In this case,
* this either retrieves the local credential from a file location (k8s
* workload) or by sending a GET request to a local metadata server (Azure
* workloads).
* @return A promise that resolves with the external subject token.
*/
async retrieveSubjectToken(): Promise<string> {
if (this.file) {
return await this.getTokenFromFile(this.file!);
} else {
return await this.getTokenFromUrl(this.url!, this.headers);
}
}

/**
* Looks up the external subject token in the file path provided and
* resolves with that token.
* @param file The file path where the external credential is located.
* @return A promise that resolves with the external subject token.
*/
private getTokenFromFile(filePath: string): Promise<string> {
// Make sure there is a file at the path. lstatSync will throw if there is
// nothing there.
try {
// Resolve path to actual file in case of symlink. Expect a thrown error
// if not resolvable.
filePath = fs.realpathSync(filePath);

if (!fs.lstatSync(filePath).isFile()) {
throw new Error();
}
} catch (err) {
err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`;
throw err;
}

return readFile(filePath, {encoding: 'utf8'});
}

/**
* Sends a GET request to the URL provided and resolves with the returned
* external subject token.
* @param url The URL to call to retrieve the subject token. This is typically
* a local metadata server.
* @param headers The optional additional headers to send with the request to
* the metadata server url.
* @return A promise that resolves with the external subject token.
*/
private async getTokenFromUrl(
url: string,
headers?: {[key: string]: string}
): Promise<string> {
const opts: GaxiosOptions = {
url,
method: 'GET',
headers,
responseType: 'text',
};
const response = await this.transporter.request<string>(opts);
return response.data;
}
}
121 changes: 121 additions & 0 deletions test/externalclienthelper.ts
@@ -0,0 +1,121 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import * as assert from 'assert';
import * as nock from 'nock';
import * as qs from 'querystring';
import {GetAccessTokenResponse} from '../src/auth/oauth2client';
import {OAuthErrorResponse} from '../src/auth/oauth2common';
import {StsSuccessfulResponse} from '../src/auth/stscredentials';
import {IamGenerateAccessTokenResponse} from '../src/auth/baseexternalclient';

interface IamGenerateAccessTokenError {
error: {
code: number;
message: string;
status: string;
};
}

interface NockMockStsToken {
statusCode: number;
response: StsSuccessfulResponse | OAuthErrorResponse;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
request: {[key: string]: any};
additionalHeaders?: {[key: string]: string};
}

interface NockMockGenerateAccessToken {
statusCode: number;
token: string;
response: IamGenerateAccessTokenResponse | IamGenerateAccessTokenError;
scopes: string[];
}

const projectNumber = '123456';
const poolId = 'POOL_ID';
const providerId = 'PROVIDER_ID';
const baseUrl = 'https://sts.googleapis.com';
const path = '/v1/token';
const saEmail = 'service-1234@service-name.iam.gserviceaccount.com';
const saBaseUrl = 'https://iamcredentials.googleapis.com';
const saPath = `/v1/projects/-/serviceAccounts/${saEmail}:generateAccessToken`;

export function mockStsTokenExchange(
nockParams: NockMockStsToken[]
): nock.Scope {
const scope = nock(baseUrl);
nockParams.forEach(nockMockStsToken => {
const headers = Object.assign(
{
'content-type': 'application/x-www-form-urlencoded',
},
nockMockStsToken.additionalHeaders || {}
);
scope
.post(path, qs.stringify(nockMockStsToken.request), {
reqheaders: headers,
})
.reply(nockMockStsToken.statusCode, nockMockStsToken.response);
});
return scope;
}

export function mockGenerateAccessToken(
nockParams: NockMockGenerateAccessToken[]
): nock.Scope {
const scope = nock(saBaseUrl);
nockParams.forEach(nockMockGenerateAccessToken => {
const token = nockMockGenerateAccessToken.token;
scope
.post(
saPath,
{
scope: nockMockGenerateAccessToken.scopes,
},
{
reqheaders: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
}
)
.reply(
nockMockGenerateAccessToken.statusCode,
nockMockGenerateAccessToken.response
);
});
return scope;
}

export function getAudience(): string {
return (
`//iam.googleapis.com/projects/${projectNumber}` +
`/locations/global/workloadIdentityPools/${poolId}/` +
`providers/${providerId}`
);
}

export function getTokenUrl(): string {
return `${baseUrl}${path}`;
}

export function getServiceAccountImpersonationUrl(): string {
return `${saBaseUrl}${saPath}`;
}

export function assertGaxiosResponsePresent(resp: GetAccessTokenResponse) {
const gaxiosResponse = resp.res || {};
assert('data' in gaxiosResponse && 'status' in gaxiosResponse);
}
1 change: 1 addition & 0 deletions test/fixtures/external-subject-token.txt
@@ -0,0 +1 @@
HEADER.SIMULATED_JWT_PAYLOAD.SIGNATURE