Push before general cleanup to avoid merge errors

This commit is contained in:
2022-11-13 11:09:44 -05:00
parent a5196ef862
commit d5d6f84995
1451 changed files with 2065486 additions and 54 deletions

1092
node_modules/google-auth-library/CHANGELOG.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

202
node_modules/google-auth-library/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

1279
node_modules/google-auth-library/README.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,109 @@
/// <reference types="node" />
import { EventEmitter } from 'events';
import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
import { DefaultTransporter } from '../transporters';
import { Credentials } from './credentials';
import { Headers } from './oauth2client';
/**
* Defines the root interface for all clients that generate credentials
* for calling Google APIs. All clients should implement this interface.
*/
export interface CredentialsClient {
/**
* The project ID corresponding to the current credentials if available.
*/
projectId?: string | null;
/**
* The expiration threshold in milliseconds before forcing token refresh.
*/
eagerRefreshThresholdMillis: number;
/**
* Whether to force refresh on failure when making an authorization request.
*/
forceRefreshOnFailure: boolean;
/**
* @return A promise that resolves with the current GCP access token
* response. If the current credential is expired, a new one is retrieved.
*/
getAccessToken(): Promise<{
token?: string | null;
res?: GaxiosResponse | null;
}>;
/**
* The main authentication interface. It takes an optional url which when
* present is the endpoint being accessed, and returns a Promise which
* resolves with authorization header fields.
*
* The result has the form:
* { Authorization: 'Bearer <access_token_value>' }
* @param url The URI being authorized.
*/
getRequestHeaders(url?: string): Promise<Headers>;
/**
* Provides an alternative Gaxios request implementation with auth credentials
*/
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
/**
* Sets the auth credentials.
*/
setCredentials(credentials: Credentials): void;
/**
* Subscribes a listener to the tokens event triggered when a token is
* generated.
*
* @param event The tokens event to subscribe to.
* @param listener The listener that triggers on event trigger.
* @return The current client instance.
*/
on(event: 'tokens', listener: (tokens: Credentials) => void): this;
}
export declare interface AuthClient {
on(event: 'tokens', listener: (tokens: Credentials) => void): this;
}
export declare abstract class AuthClient extends EventEmitter implements CredentialsClient {
/**
* The quota project ID. The quota project can be used by client libraries for the billing purpose.
* See {@link https://cloud.google.com/docs/quota| Working with quotas}
*/
quotaProjectId?: string;
transporter: DefaultTransporter;
credentials: Credentials;
projectId?: string | null;
eagerRefreshThresholdMillis: number;
forceRefreshOnFailure: boolean;
/**
* Provides an alternative Gaxios request implementation with auth credentials
*/
abstract request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
/**
* The main authentication interface. It takes an optional url which when
* present is the endpoint being accessed, and returns a Promise which
* resolves with authorization header fields.
*
* The result has the form:
* { Authorization: 'Bearer <access_token_value>' }
* @param url The URI being authorized.
*/
abstract getRequestHeaders(url?: string): Promise<Headers>;
/**
* @return A promise that resolves with the current GCP access token
* response. If the current credential is expired, a new one is retrieved.
*/
abstract getAccessToken(): Promise<{
token?: string | null;
res?: GaxiosResponse | null;
}>;
/**
* Sets the auth credentials.
*/
setCredentials(credentials: Credentials): void;
/**
* 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 object to append additional headers to.
*/
protected addSharedMetadataHeaders(headers: Headers): Headers;
}

View File

@@ -0,0 +1,93 @@
import { BaseExternalAccountClient, BaseExternalAccountClientOptions } from './baseexternalclient';
import { RefreshOptions } from './oauth2client';
/**
* AWS credentials JSON interface. This is used for AWS workloads.
*/
export interface AwsClientOptions extends BaseExternalAccountClientOptions {
credential_source: {
environment_id: string;
region_url?: string;
url?: string;
regional_cred_verification_url: string;
imdsv2_session_token_url?: string;
};
}
/**
* AWS external account client. This is used for AWS workloads, where
* AWS STS GetCallerIdentity serialized signed requests are exchanged for
* GCP access token.
*/
export declare class AwsClient extends BaseExternalAccountClient {
private readonly environmentId;
private readonly regionUrl?;
private readonly securityCredentialsUrl?;
private readonly regionalCredVerificationUrl;
private readonly imdsV2SessionTokenUrl?;
private awsRequestSigner;
private region;
static AWS_EC2_METADATA_IPV4_ADDRESS: string;
static AWS_EC2_METADATA_IPV6_ADDRESS: string;
/**
* Instantiates an AwsClient instance using the provided JSON
* object loaded from an external account credentials file.
* An error is thrown if the credential is not a valid AWS 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: AwsClientOptions, additionalOptions?: RefreshOptions);
private validateEnvironmentId;
private validateMetadataServerURLs;
private validateMetadataURL;
/**
* Triggered when an 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 uses a serialized AWS signed request to the STS GetCallerIdentity
* endpoint.
* The logic is summarized as:
* 1. If imdsv2_session_token_url is provided in the credential source, then
* fetch the aws session token and include it in the headers of the
* metadata requests. This is a requirement for IDMSv2 but optional
* for IDMSv1.
* 2. Retrieve AWS region from availability-zone.
* 3a. Check AWS credentials in environment variables. If not found, get
* from security-credentials endpoint.
* 3b. Get AWS credentials from security-credentials endpoint. In order
* to retrieve this, the AWS role needs to be determined by calling
* security-credentials endpoint without any argument. Then the
* credentials can be retrieved via: security-credentials/role_name
* 4. Generate the signed request to AWS STS GetCallerIdentity action.
* 5. Inject x-goog-cloud-target-resource into header and serialize the
* signed request. This will be the subject-token to pass to GCP STS.
* @return A promise that resolves with the external subject token.
*/
retrieveSubjectToken(): Promise<string>;
/**
* @return A promise that resolves with the IMDSv2 Session Token.
*/
private getImdsV2SessionToken;
/**
* @param headers The headers to be used in the metadata request.
* @return A promise that resolves with the current AWS region.
*/
private getAwsRegion;
/**
* @param headers The headers to be used in the metadata request.
* @return A promise that resolves with the assigned role to the current
* AWS VM. This is needed for calling the security-credentials endpoint.
*/
private getAwsRoleName;
/**
* Retrieves the temporary AWS credentials by calling the security-credentials
* endpoint as specified in the `credential_source` object.
* @param roleName The role attached to the current VM.
* @param headers The headers to be used in the metadata request.
* @return A promise that resolves with the temporary AWS credentials
* needed for creating the GetCallerIdentity signed request.
*/
private getAwsSecurityCredentials;
}

View File

@@ -0,0 +1,41 @@
import { GaxiosOptions } from 'gaxios';
/**
* Interface defining AWS security credentials.
* These are either determined from AWS security_credentials endpoint or
* AWS environment variables.
*/
interface AwsSecurityCredentials {
accessKeyId: string;
secretAccessKey: string;
token?: string;
}
/**
* Implements an AWS API request signer based on the AWS Signature Version 4
* signing process.
* https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
*/
export declare class AwsRequestSigner {
private readonly getCredentials;
private readonly region;
private readonly crypto;
/**
* Instantiates an AWS API request signer used to send authenticated signed
* requests to AWS APIs based on the AWS Signature Version 4 signing process.
* This also provides a mechanism to generate the signed request without
* sending it.
* @param getCredentials A mechanism to retrieve AWS security credentials
* when needed.
* @param region The AWS region to use.
*/
constructor(getCredentials: () => Promise<AwsSecurityCredentials>, region: string);
/**
* Generates the signed request for the provided HTTP request for calling
* an AWS API. This follows the steps described at:
* https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
* @param amzOptions The AWS request options that need to be signed.
* @return A promise that resolves with the GaxiosOptions containing the
* signed HTTP request parameters.
*/
getRequestOptions(amzOptions: GaxiosOptions): Promise<GaxiosOptions>;
}
export {};

View File

@@ -0,0 +1,221 @@
import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
import { Credentials } from './credentials';
import { AuthClient } from './authclient';
import { BodyResponseCallback } from '../transporters';
import { GetAccessTokenResponse, Headers, RefreshOptions } from './oauth2client';
/**
* Offset to take into account network delays and server clock skews.
*/
export declare const EXPIRATION_TIME_OFFSET: number;
/**
* The credentials JSON file type for external account clients.
* There are 3 types of JSON configs:
* 1. authorized_user => Google end user credential
* 2. service_account => Google service account credential
* 3. external_Account => non-GCP service (eg. AWS, Azure, K8s)
*/
export declare const EXTERNAL_ACCOUNT_TYPE = "external_account";
/** Cloud resource manager URL used to retrieve project information. */
export declare const CLOUD_RESOURCE_MANAGER = "https://cloudresourcemanager.googleapis.com/v1/projects/";
/**
* Base external account credentials json interface.
*/
export interface BaseExternalAccountClientOptions {
type: string;
audience: string;
subject_token_type: string;
service_account_impersonation_url?: string;
service_account_impersonation?: {
token_lifetime_seconds?: number;
};
token_url: string;
token_info_url?: string;
client_id?: string;
client_secret?: string;
quota_project_id?: string;
workforce_pool_user_project?: string;
}
/**
* Interface defining the successful response for iamcredentials
* generateAccessToken API.
* https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken
*/
export interface IamGenerateAccessTokenResponse {
accessToken: string;
expireTime: string;
}
/**
* Interface defining the project information response returned by the cloud
* resource manager.
* https://cloud.google.com/resource-manager/reference/rest/v1/projects#Project
*/
export interface ProjectInfo {
projectNumber: string;
projectId: string;
lifecycleState: string;
name: string;
createTime?: string;
parent: {
[key: string]: any;
};
}
/**
* Internal interface for tracking the access token expiration time.
*/
interface CredentialsWithResponse extends Credentials {
res?: GaxiosResponse | null;
}
/**
* Base external account client. This is used to instantiate AuthClients for
* exchanging external account credentials for GCP access token and authorizing
* requests to GCP APIs.
* The base class implements common logic for exchanging various type of
* external credentials for GCP access token. The logic of determining and
* retrieving the external credential based on the environment and
* credential_source will be left for the subclasses.
*/
export declare 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
* used.
*/
scopes?: string | string[];
private cachedAccessToken;
protected readonly audience: string;
protected readonly subjectTokenType: string;
private readonly serviceAccountImpersonationUrl?;
private readonly serviceAccountImpersonationLifetime?;
private readonly stsCredential;
private readonly clientAuth?;
private readonly workforcePoolUserProject?;
projectId: string | null;
projectNumber: string | null;
readonly eagerRefreshThresholdMillis: number;
readonly forceRefreshOnFailure: boolean;
/**
* 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.
* @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: BaseExternalAccountClientOptions, additionalOptions?: RefreshOptions);
/** The service account email to be impersonated, if available. */
getServiceAccountEmail(): string | null;
/**
* Provides a mechanism to inject GCP access tokens directly.
* When the provided credential expires, a new credential, using the
* external account options, is retrieved.
* @param credentials The Credentials object to set on the current client.
*/
setCredentials(credentials: Credentials): void;
/**
* Triggered when a external subject token is needed to be exchanged for a GCP
* access token via GCP STS endpoint.
* This abstract method needs to be implemented by subclasses depending on
* the type of external credential used.
* @return A promise that resolves with the external subject token.
*/
abstract retrieveSubjectToken(): Promise<string>;
/**
* @return A promise that resolves with the current GCP access token
* response. If the current credential is expired, a new one is retrieved.
*/
getAccessToken(): Promise<GetAccessTokenResponse>;
/**
* The main authentication interface. It takes an optional url which when
* present is the endpoint being accessed, and returns a Promise which
* resolves with authorization header fields.
*
* The result has the form:
* { Authorization: 'Bearer <access_token_value>' }
*/
getRequestHeaders(): Promise<Headers>;
/**
* Provides a request implementation with OAuth 2.0 flow. In cases of
* HTTP 401 and 403 responses, it automatically asks for a new access token
* and replays the unsuccessful request.
* @param opts Request options.
* @param callback callback.
* @return A promise that resolves with the HTTP response when no callback is
* provided.
*/
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
request<T>(opts: GaxiosOptions, callback: BodyResponseCallback<T>): void;
/**
* @return A promise that resolves with the project ID corresponding to the
* current workload identity pool or current workforce pool if
* determinable. For workforce pool credential, it returns the project ID
* corresponding to the workforcePoolUserProject.
* This is introduced to match the current pattern of using the Auth
* library:
* const projectId = await auth.getProjectId();
* const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
* const res = await client.request({ url });
* The resource may not have permission
* (resourcemanager.projects.get) to call this API or the required
* scopes may not be selected:
* https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes
*/
getProjectId(): Promise<string | null>;
/**
* Authenticates the provided HTTP request, processes it and resolves with the
* returned response.
* @param opts The HTTP request options.
* @param retry Whether the current attempt is a retry after a failed attempt.
* @return A promise that resolves with the successful response.
*/
protected requestAsync<T>(opts: GaxiosOptions, retry?: boolean): Promise<GaxiosResponse<T>>;
/**
* Forces token refresh, even if unexpired tokens are currently cached.
* External credentials are exchanged for GCP access tokens via the token
* exchange endpoint and other settings provided in the client options
* object.
* If the service_account_impersonation_url is provided, an additional
* step to exchange the external account GCP access token for a service
* account impersonated token is performed.
* @return A promise that resolves with the fresh GCP access tokens.
*/
protected refreshAccessTokenAsync(): Promise<CredentialsWithResponse>;
/**
* Returns the workload identity pool project number if it is determinable
* from the audience resource name.
* @param audience The STS audience used to determine the project number.
* @return The project number associated with the workload identity pool, if
* this can be determined from the STS audience field. Otherwise, null is
* returned.
*/
private getProjectNumber;
/**
* Exchanges an external account GCP access token for a service
* account impersonated access token using iamcredentials
* GenerateAccessToken API.
* @param token The access token to exchange for a service account access
* token.
* @return A promise that resolves with the service account impersonated
* credentials response.
*/
private getImpersonatedAccessToken;
/**
* Returns whether the provided credentials are expired or not.
* If there is no expiry time, assumes the token is not expired or expiring.
* @param accessToken The credentials to check for expiration.
* @return Whether the credentials are expired or not.
*/
private isExpired;
/**
* @return The list of scopes for the requested GCP access token.
*/
private getScopesArray;
/**
* Checks whether Google APIs URL is valid.
* @param apiName The apiName of url.
* @param url The Google API URL to validate.
* @return Whether the URL is valid or not.
*/
private validateGoogleAPIsUrl;
}
export {};

View File

@@ -0,0 +1,37 @@
import { GaxiosError } from 'gaxios';
import { GetTokenResponse, OAuth2Client, RefreshOptions } from './oauth2client';
export interface ComputeOptions extends RefreshOptions {
/**
* The service account email to use, or 'default'. A Compute Engine instance
* may have multiple service accounts.
*/
serviceAccountEmail?: string;
/**
* The scopes that will be requested when acquiring service account
* credentials. Only applicable to modern App Engine and Cloud Function
* runtimes as of March 2019.
*/
scopes?: string | string[];
}
export declare class Compute extends OAuth2Client {
private serviceAccountEmail;
scopes: string[];
/**
* Google Compute Engine service account credentials.
*
* Retrieve access token from the metadata server.
* See: https://developers.google.com/compute/docs/authentication
*/
constructor(options?: ComputeOptions);
/**
* Refreshes the access token.
* @param refreshToken Unused parameter
*/
protected refreshTokenNoCache(refreshToken?: string | null): Promise<GetTokenResponse>;
/**
* Fetches an ID token.
* @param targetAudience the audience for the fetched ID token.
*/
fetchIdToken(targetAudience: string): Promise<string>;
protected wrapError(e: GaxiosError): void;
}

View File

@@ -0,0 +1,73 @@
export interface Credentials {
/**
* This field is only present if the access_type parameter was set to offline in the authentication request. For details, see Refresh tokens.
*/
refresh_token?: string | null;
/**
* The time in ms at which this token is thought to expire.
*/
expiry_date?: number | null;
/**
* A token that can be sent to a Google API.
*/
access_token?: string | null;
/**
* Identifies the type of token returned. At this time, this field always has the value Bearer.
*/
token_type?: string | null;
/**
* A JWT that contains identity information about the user that is digitally signed by Google.
*/
id_token?: string | null;
/**
* The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings.
*/
scope?: string;
}
export interface CredentialRequest {
/**
* This field is only present if the access_type parameter was set to offline in the authentication request. For details, see Refresh tokens.
*/
refresh_token?: string;
/**
* A token that can be sent to a Google API.
*/
access_token?: string;
/**
* Identifies the type of token returned. At this time, this field always has the value Bearer.
*/
token_type?: string;
/**
* The remaining lifetime of the access token in seconds.
*/
expires_in?: number;
/**
* A JWT that contains identity information about the user that is digitally signed by Google.
*/
id_token?: string;
/**
* The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings.
*/
scope?: string;
}
export interface JWTInput {
type?: string;
client_email?: string;
private_key?: string;
private_key_id?: string;
project_id?: string;
client_id?: string;
client_secret?: string;
refresh_token?: string;
quota_project_id?: string;
}
export interface ImpersonatedJWTInput {
type?: string;
source_credentials?: JWTInput;
service_account_impersonation_url?: string;
delegates?: string[];
}
export interface CredentialBody {
client_email?: string;
private_key?: string;
}

View File

@@ -0,0 +1,142 @@
import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
import { BodyResponseCallback } from '../transporters';
import { Credentials } from './credentials';
import { AuthClient } from './authclient';
import { GetAccessTokenResponse, Headers, RefreshOptions } from './oauth2client';
/**
* The maximum number of access boundary rules a Credential Access Boundary
* can contain.
*/
export declare const MAX_ACCESS_BOUNDARY_RULES_COUNT = 10;
/**
* Offset to take into account network delays and server clock skews.
*/
export declare const EXPIRATION_TIME_OFFSET: number;
/**
* Internal interface for tracking the access token expiration time.
*/
interface CredentialsWithResponse extends Credentials {
res?: GaxiosResponse | null;
}
/**
* Internal interface for tracking and returning the Downscoped access token
* expiration time in epoch time (seconds).
*/
interface DownscopedAccessTokenResponse extends GetAccessTokenResponse {
expirationTime?: number | null;
}
/**
* Defines an upper bound of permissions available for a GCP credential.
*/
export interface CredentialAccessBoundary {
accessBoundary: {
accessBoundaryRules: AccessBoundaryRule[];
};
}
/** Defines an upper bound of permissions on a particular resource. */
interface AccessBoundaryRule {
availablePermissions: string[];
availableResource: string;
availabilityCondition?: AvailabilityCondition;
}
/**
* An optional condition that can be used as part of a
* CredentialAccessBoundary to further restrict permissions.
*/
interface AvailabilityCondition {
expression: string;
title?: string;
description?: string;
}
/**
* Defines a set of Google credentials that are downscoped from an existing set
* of Google OAuth2 credentials. This is useful to restrict the Identity and
* Access Management (IAM) permissions that a short-lived credential can use.
* The common pattern of usage is to have a token broker with elevated access
* generate these downscoped credentials from higher access source credentials
* and pass the downscoped short-lived access tokens to a token consumer via
* some secure authenticated channel for limited access to Google Cloud Storage
* resources.
*/
export declare class DownscopedClient extends AuthClient {
private readonly authClient;
private readonly credentialAccessBoundary;
private cachedDownscopedAccessToken;
private readonly stsCredential;
readonly eagerRefreshThresholdMillis: number;
readonly forceRefreshOnFailure: boolean;
/**
* Instantiates a downscoped client object using the provided source
* AuthClient and credential access boundary rules.
* To downscope permissions of a source AuthClient, a Credential Access
* Boundary that specifies which resources the new credential can access, as
* well as an upper bound on the permissions that are available on each
* resource, has to be defined. A downscoped client can then be instantiated
* using the source AuthClient and the Credential Access Boundary.
* @param authClient The source AuthClient to be downscoped based on the
* provided Credential Access Boundary rules.
* @param credentialAccessBoundary The Credential Access Boundary which
* contains a list of access boundary rules. Each rule contains information
* on the resource that the rule applies to, the upper bound of the
* permissions that are available on that resource and an optional
* condition to further restrict permissions.
* @param additionalOptions Optional additional behavior customization
* options. These currently customize expiration threshold time and
* whether to retry on 401/403 API request errors.
* @param quotaProjectId Optional quota project id for setting up in the
* x-goog-user-project header.
*/
constructor(authClient: AuthClient, credentialAccessBoundary: CredentialAccessBoundary, additionalOptions?: RefreshOptions, quotaProjectId?: string);
/**
* Provides a mechanism to inject Downscoped access tokens directly.
* The expiry_date field is required to facilitate determination of the token
* expiration which would make it easier for the token consumer to handle.
* @param credentials The Credentials object to set on the current client.
*/
setCredentials(credentials: Credentials): void;
getAccessToken(): Promise<DownscopedAccessTokenResponse>;
/**
* The main authentication interface. It takes an optional url which when
* present is the endpoint being accessed, and returns a Promise which
* resolves with authorization header fields.
*
* The result has the form:
* { Authorization: 'Bearer <access_token_value>' }
*/
getRequestHeaders(): Promise<Headers>;
/**
* Provides a request implementation with OAuth 2.0 flow. In cases of
* HTTP 401 and 403 responses, it automatically asks for a new access token
* and replays the unsuccessful request.
* @param opts Request options.
* @param callback callback.
* @return A promise that resolves with the HTTP response when no callback
* is provided.
*/
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
request<T>(opts: GaxiosOptions, callback: BodyResponseCallback<T>): void;
/**
* Authenticates the provided HTTP request, processes it and resolves with the
* returned response.
* @param opts The HTTP request options.
* @param retry Whether the current attempt is a retry after a failed attempt.
* @return A promise that resolves with the successful response.
*/
protected requestAsync<T>(opts: GaxiosOptions, retry?: boolean): Promise<GaxiosResponse<T>>;
/**
* Forces token refresh, even if unexpired tokens are currently cached.
* GCP access tokens are retrieved from authclient object/source credential.
* Then GCP access tokens are exchanged for downscoped access tokens via the
* token exchange endpoint.
* @return A promise that resolves with the fresh downscoped access token.
*/
protected refreshAccessTokenAsync(): Promise<CredentialsWithResponse>;
/**
* Returns whether the provided credentials are expired or not.
* If there is no expiry time, assumes the token is not expired or expiring.
* @param downscopedAccessToken The credentials to check for expiration.
* @return Whether the credentials are expired or not.
*/
private isExpired;
}
export {};

View File

@@ -0,0 +1,10 @@
export declare enum GCPEnv {
APP_ENGINE = "APP_ENGINE",
KUBERNETES_ENGINE = "KUBERNETES_ENGINE",
CLOUD_FUNCTIONS = "CLOUD_FUNCTIONS",
COMPUTE_ENGINE = "COMPUTE_ENGINE",
CLOUD_RUN = "CLOUD_RUN",
NONE = "NONE"
}
export declare function clear(): void;
export declare function getEnv(): Promise<GCPEnv>;

View File

@@ -0,0 +1,137 @@
/**
* Interface defining the JSON formatted response of a 3rd party executable
* used by the pluggable auth client.
*/
export interface ExecutableResponseJson {
/**
* The version of the JSON response. Only version 1 is currently supported.
* Always required.
*/
version: number;
/**
* Whether the executable ran successfully. Always required.
*/
success: boolean;
/**
* The epoch time for expiration of the token in seconds, required for
* successful responses.
*/
expiration_time?: number;
/**
* The type of subject token in the response, currently supported values are:
* urn:ietf:params:oauth:token-type:saml2
* urn:ietf:params:oauth:token-type:id_token
* urn:ietf:params:oauth:token-type:jwt
*/
token_type?: string;
/**
* The error code from the executable, required when unsuccessful.
*/
code?: string;
/**
* The error message from the executable, required when unsuccessful.
*/
message?: string;
/**
* The ID token to be used as a subject token when token_type is id_token or jwt.
*/
id_token?: string;
/**
* The response to be used as a subject token when token_type is saml2.
*/
saml_response?: string;
}
/**
* Defines the response of a 3rd party executable run by the pluggable auth client.
*/
export declare class ExecutableResponse {
/**
* The version of the Executable response. Only version 1 is currently supported.
*/
readonly version: number;
/**
* Whether the executable ran successfully.
*/
readonly success: boolean;
/**
* The epoch time for expiration of the token in seconds.
*/
readonly expirationTime?: number;
/**
* The type of subject token in the response, currently supported values are:
* urn:ietf:params:oauth:token-type:saml2
* urn:ietf:params:oauth:token-type:id_token
* urn:ietf:params:oauth:token-type:jwt
*/
readonly tokenType?: string;
/**
* The error code from the executable.
*/
readonly errorCode?: string;
/**
* The error message from the executable.
*/
readonly errorMessage?: string;
/**
* The subject token from the executable, format depends on tokenType.
*/
readonly subjectToken?: string;
/**
* Instantiates an ExecutableResponse instance using the provided JSON object
* from the output of the executable.
* @param responseJson Response from a 3rd party executable, loaded from a
* run of the executable or a cached output file.
*/
constructor(responseJson: ExecutableResponseJson);
/**
* @return A boolean representing if the response has a valid token. Returns
* true when the response was successful and the token is not expired.
*/
isValid(): boolean;
/**
* @return A boolean representing if the response is expired. Returns true if the
* provided timeout has passed.
*/
isExpired(): boolean;
}
/**
* An error thrown by the ExecutableResponse class.
*/
export declare class ExecutableResponseError extends Error {
constructor(message: string);
}
/**
* An error thrown when the 'version' field in an executable response is missing or invalid.
*/
export declare class InvalidVersionFieldError extends ExecutableResponseError {
}
/**
* An error thrown when the 'success' field in an executable response is missing or invalid.
*/
export declare class InvalidSuccessFieldError extends ExecutableResponseError {
}
/**
* An error thrown when the 'expiration_time' field in an executable response is missing or invalid.
*/
export declare class InvalidExpirationTimeFieldError extends ExecutableResponseError {
}
/**
* An error thrown when the 'token_type' field in an executable response is missing or invalid.
*/
export declare class InvalidTokenTypeFieldError extends ExecutableResponseError {
}
/**
* An error thrown when the 'code' field in an executable response is missing or invalid.
*/
export declare class InvalidCodeFieldError extends ExecutableResponseError {
}
/**
* An error thrown when the 'message' field in an executable response is missing or invalid.
*/
export declare class InvalidMessageFieldError extends ExecutableResponseError {
}
/**
* An error thrown when the subject token in an executable response is missing or invalid.
*/
export declare class InvalidSubjectTokenError extends ExecutableResponseError {
}

View File

@@ -0,0 +1,25 @@
import { RefreshOptions } from './oauth2client';
import { BaseExternalAccountClient } from './baseexternalclient';
import { IdentityPoolClientOptions } from './identitypoolclient';
import { AwsClientOptions } from './awsclient';
import { PluggableAuthClientOptions } from './pluggable-auth-client';
export declare type ExternalAccountClientOptions = IdentityPoolClientOptions | AwsClientOptions | PluggableAuthClientOptions;
/**
* Dummy class with no constructor. Developers are expected to use fromJSON.
*/
export declare class ExternalAccountClient {
constructor();
/**
* This static method will instantiate the
* corresponding type of external account credential depending on the
* underlying credential source.
* @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.
* @return A BaseExternalAccountClient instance or null if the options
* provided do not correspond to an external account credential.
*/
static fromJSON(options: ExternalAccountClientOptions, additionalOptions?: RefreshOptions): BaseExternalAccountClient | null;
}

View File

@@ -0,0 +1,291 @@
/// <reference types="node" />
import { GaxiosOptions, GaxiosResponse } from 'gaxios';
import * as stream from 'stream';
import { DefaultTransporter, Transporter } from '../transporters';
import { Compute } from './computeclient';
import { CredentialBody, ImpersonatedJWTInput, JWTInput } from './credentials';
import { IdTokenClient } from './idtokenclient';
import { GCPEnv } from './envDetect';
import { JWT, JWTOptions } from './jwtclient';
import { Headers, OAuth2ClientOptions, RefreshOptions } from './oauth2client';
import { UserRefreshClient, UserRefreshClientOptions } from './refreshclient';
import { Impersonated, ImpersonatedOptions } from './impersonated';
import { ExternalAccountClientOptions } from './externalclient';
import { BaseExternalAccountClient } from './baseexternalclient';
import { AuthClient } from './authclient';
/**
* Defines all types of explicit clients that are determined via ADC JSON
* config file.
*/
export declare type JSONClient = JWT | UserRefreshClient | BaseExternalAccountClient | Impersonated;
export interface ProjectIdCallback {
(err?: Error | null, projectId?: string | null): void;
}
export interface CredentialCallback {
(err: Error | null, result?: JSONClient): void;
}
export interface ADCCallback {
(err: Error | null, credential?: AuthClient, projectId?: string | null): void;
}
export interface ADCResponse {
credential: AuthClient;
projectId: string | null;
}
export interface GoogleAuthOptions<T extends AuthClient = JSONClient> {
/**
* An `AuthClient` to use
*/
authClient?: T;
/**
* Path to a .json, .pem, or .p12 key file
*/
keyFilename?: string;
/**
* Path to a .json, .pem, or .p12 key file
*/
keyFile?: string;
/**
* Object containing client_email and private_key properties, or the
* external account client options.
*/
credentials?: CredentialBody | ExternalAccountClientOptions;
/**
* Options object passed to the constructor of the client
*/
clientOptions?: JWTOptions | OAuth2ClientOptions | UserRefreshClientOptions | ImpersonatedOptions;
/**
* Required scopes for the desired API request
*/
scopes?: string | string[];
/**
* Your project ID.
*/
projectId?: string;
}
export declare const CLOUD_SDK_CLIENT_ID = "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com";
export declare class GoogleAuth<T extends AuthClient = JSONClient> {
transporter?: Transporter;
/**
* Caches a value indicating whether the auth layer is running on Google
* Compute Engine.
* @private
*/
private checkIsGCE?;
useJWTAccessWithScope?: boolean;
defaultServicePath?: string;
get isGCE(): boolean | undefined;
private _findProjectIdPromise?;
private _cachedProjectId?;
jsonContent: JWTInput | ExternalAccountClientOptions | null;
cachedCredential: JSONClient | Impersonated | Compute | T | null;
/**
* Scopes populated by the client library by default. We differentiate between
* these and user defined scopes when deciding whether to use a self-signed JWT.
*/
defaultScopes?: string | string[];
private keyFilename?;
private scopes?;
private clientOptions?;
/**
* Export DefaultTransporter as a static property of the class.
*/
static DefaultTransporter: typeof DefaultTransporter;
constructor(opts?: GoogleAuthOptions<T>);
setGapicJWTValues(client: JWT): void;
/**
* Obtains the default project ID for the application.
* @param callback Optional callback
* @returns Promise that resolves with project Id (if used without callback)
*/
getProjectId(): Promise<string>;
getProjectId(callback: ProjectIdCallback): void;
/**
* A temporary method for internal `getProjectId` usages where `null` is
* acceptable. In a future major release, `getProjectId` should return `null`
* (as the `Promise<string | null>` base signature describes) and this private
* method should be removed.
*
* @returns Promise that resolves with project id (or `null`)
*/
private getProjectIdOptional;
private findAndCacheProjectId;
private getProjectIdAsync;
/**
* @returns Any scopes (user-specified or default scopes specified by the
* client library) that need to be set on the current Auth client.
*/
private getAnyScopes;
/**
* Obtains the default service-level credentials for the application.
* @param callback Optional callback.
* @returns Promise that resolves with the ADCResponse (if no callback was
* passed).
*/
getApplicationDefault(): Promise<ADCResponse>;
getApplicationDefault(callback: ADCCallback): void;
getApplicationDefault(options: RefreshOptions): Promise<ADCResponse>;
getApplicationDefault(options: RefreshOptions, callback: ADCCallback): void;
private getApplicationDefaultAsync;
private prepareAndCacheADC;
/**
* Determines whether the auth layer is running on Google Compute Engine.
* @returns A promise that resolves with the boolean.
* @api private
*/
_checkIsGCE(): Promise<boolean>;
/**
* Attempts to load default credentials from the environment variable path..
* @returns Promise that resolves with the OAuth2Client or null.
* @api private
*/
_tryGetApplicationCredentialsFromEnvironmentVariable(options?: RefreshOptions): Promise<JSONClient | null>;
/**
* Attempts to load default credentials from a well-known file location
* @return Promise that resolves with the OAuth2Client or null.
* @api private
*/
_tryGetApplicationCredentialsFromWellKnownFile(options?: RefreshOptions): Promise<JSONClient | null>;
/**
* Attempts to load default credentials from a file at the given path..
* @param filePath The path to the file to read.
* @returns Promise that resolves with the OAuth2Client
* @api private
*/
_getApplicationCredentialsFromFilePath(filePath: string, options?: RefreshOptions): Promise<JSONClient>;
/**
* Create a credentials instance using a given impersonated input options.
* @param json The impersonated input object.
* @returns JWT or UserRefresh Client with data
*/
fromImpersonatedJSON(json: ImpersonatedJWTInput): Impersonated;
/**
* Create a credentials instance using the given input options.
* @param json The input object.
* @param options The JWT or UserRefresh options for the client
* @returns JWT or UserRefresh Client with data
*/
fromJSON(json: JWTInput | ImpersonatedJWTInput, options?: RefreshOptions): JSONClient;
/**
* Return a JWT or UserRefreshClient from JavaScript object, caching both the
* object used to instantiate and the client.
* @param json The input object.
* @param options The JWT or UserRefresh options for the client
* @returns JWT or UserRefresh Client with data
*/
private _cacheClientFromJSON;
/**
* Create a credentials instance using the given input stream.
* @param inputStream The input stream.
* @param callback Optional callback.
*/
fromStream(inputStream: stream.Readable): Promise<JSONClient>;
fromStream(inputStream: stream.Readable, callback: CredentialCallback): void;
fromStream(inputStream: stream.Readable, options: RefreshOptions): Promise<JSONClient>;
fromStream(inputStream: stream.Readable, options: RefreshOptions, callback: CredentialCallback): void;
private fromStreamAsync;
/**
* Create a credentials instance using the given API key string.
* @param apiKey The API key string
* @param options An optional options object.
* @returns A JWT loaded from the key
*/
fromAPIKey(apiKey: string, options?: RefreshOptions): JWT;
/**
* Determines whether the current operating system is Windows.
* @api private
*/
private _isWindows;
/**
* Run the Google Cloud SDK command that prints the default project ID
*/
private getDefaultServiceProjectId;
/**
* Loads the project id from environment variables.
* @api private
*/
private getProductionProjectId;
/**
* Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.
* @api private
*/
private getFileProjectId;
/**
* Gets the project ID from external account client if available.
*/
private getExternalAccountClientProjectId;
/**
* Gets the Compute Engine project ID if it can be inferred.
*/
private getGCEProjectId;
/**
* The callback function handles a credential object that contains the
* client_email and private_key (if exists).
* getCredentials first checks if the client is using an external account and
* uses the service account email in place of client_email.
* If that doesn't exist, it checks for these values from the user JSON.
* If the user JSON doesn't exist, and the environment is on GCE, it gets the
* client_email from the cloud metadata server.
* @param callback Callback that handles the credential object that contains
* a client_email and optional private key, or the error.
* returned
*/
getCredentials(): Promise<CredentialBody>;
getCredentials(callback: (err: Error | null, credentials?: CredentialBody) => void): void;
private getCredentialsAsync;
/**
* Automatically obtain a client based on the provided configuration. If no
* options were passed, use Application Default Credentials.
*/
getClient(): Promise<Compute | JSONClient | T>;
/**
* Creates a client which will fetch an ID token for authorization.
* @param targetAudience the audience for the fetched ID token.
* @returns IdTokenClient for making HTTP calls authenticated with ID tokens.
*/
getIdTokenClient(targetAudience: string): Promise<IdTokenClient>;
/**
* Automatically obtain application default credentials, and return
* an access token for making requests.
*/
getAccessToken(): Promise<string | null | undefined>;
/**
* Obtain the HTTP headers that will provide authorization for a given
* request.
*/
getRequestHeaders(url?: string): Promise<Headers>;
/**
* Obtain credentials for a request, then attach the appropriate headers to
* the request options.
* @param opts Axios or Request options on which to attach the headers
*/
authorizeRequest(opts: {
url?: string;
uri?: string;
headers?: Headers;
}): Promise<{
url?: string | undefined;
uri?: string | undefined;
headers?: Headers | undefined;
}>;
/**
* Automatically obtain application default credentials, and make an
* HTTP request using the given options.
* @param opts Axios request options for the HTTP request.
*/
request<T = any>(opts: GaxiosOptions): Promise<GaxiosResponse<T>>;
/**
* Determine the compute environment in which the code is running.
*/
getEnv(): Promise<GCPEnv>;
/**
* Sign the given data with the current private key, or go out
* to the IAM API to sign it.
* @param data The data to be signed.
*/
sign(data: string): Promise<string>;
private signBlob;
}
export interface SignBlobResponse {
keyId: string;
signedBlob: string;
}

View File

@@ -0,0 +1,23 @@
export interface RequestMetadata {
'x-goog-iam-authority-selector': string;
'x-goog-iam-authorization-token': string;
}
export declare class IAMAuth {
selector: string;
token: string;
/**
* IAM credentials.
*
* @param selector the iam authority selector
* @param token the token
* @constructor
*/
constructor(selector: string, token: string);
/**
* Acquire the HTTP headers required to make an authenticated request.
*/
getRequestHeaders(): {
'x-goog-iam-authority-selector': string;
'x-goog-iam-authorization-token': string;
};
}

View File

@@ -0,0 +1,81 @@
import { BaseExternalAccountClient, BaseExternalAccountClientOptions } from './baseexternalclient';
import { RefreshOptions } from './oauth2client';
declare type SubjectTokenFormatType = 'json' | 'text';
/**
* 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;
};
format?: {
type: SubjectTokenFormatType;
subject_token_field_name?: string;
};
};
}
/**
* Defines the Url-sourced and file-sourced external account clients mainly
* used for K8s and Azure workloads.
*/
export declare class IdentityPoolClient extends BaseExternalAccountClient {
private readonly file?;
private readonly url?;
private readonly headers?;
private readonly formatType;
private readonly formatSubjectTokenFieldName?;
/**
* 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 or a workforce pool user project is provided
* with a non workforce audience.
* @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);
/**
* 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.
*/
retrieveSubjectToken(): Promise<string>;
/**
* 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.
* @param formatType The token file or URL response type (JSON or text).
* @param formatSubjectTokenFieldName For JSON response types, this is the
* subject_token field name. For Azure, this is access_token. For text
* response types, this is ignored.
* @return A promise that resolves with the external subject token.
*/
private getTokenFromFile;
/**
* 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 formatType The token file or URL response type (JSON or text).
* @param formatSubjectTokenFieldName For JSON response types, this is the
* subject_token field name. For Azure, this is access_token. For text
* response types, this is ignored.
* @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 getTokenFromUrl;
}
export {};

View File

@@ -0,0 +1,27 @@
import { OAuth2Client, RequestMetadataResponse } from './oauth2client';
export interface IdTokenOptions {
/**
* The client to make the request to fetch an ID token.
*/
idTokenProvider: IdTokenProvider;
/**
* The audience to use when requesting an ID token.
*/
targetAudience: string;
}
export interface IdTokenProvider {
fetchIdToken: (targetAudience: string) => Promise<string>;
}
export declare class IdTokenClient extends OAuth2Client {
targetAudience: string;
idTokenProvider: IdTokenProvider;
/**
* Google ID Token client
*
* Retrieve access token from the metadata server.
* See: https://developers.google.com/compute/docs/authentication
*/
constructor(options: IdTokenOptions);
protected getRequestMetadataAsync(url?: string | null): Promise<RequestMetadataResponse>;
private getIdTokenExpiryDate;
}

View File

@@ -0,0 +1,116 @@
/**
* Copyright 2021 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 { GetTokenResponse, OAuth2Client, RefreshOptions } from './oauth2client';
import { AuthClient } from './authclient';
import { IdTokenProvider } from './idtokenclient';
export interface ImpersonatedOptions extends RefreshOptions {
/**
* Client used to perform exchange for impersonated client.
*/
sourceClient?: AuthClient;
/**
* The service account to impersonate.
*/
targetPrincipal?: string;
/**
* Scopes to request during the authorization grant.
*/
targetScopes?: string[];
/**
* The chained list of delegates required to grant the final access_token.
*/
delegates?: string[];
/**
* Number of seconds the delegated credential should be valid.
*/
lifetime?: number | 3600;
/**
* API endpoint to fetch token from.
*/
endpoint?: string;
}
export declare const IMPERSONATED_ACCOUNT_TYPE = "impersonated_service_account";
export interface TokenResponse {
accessToken: string;
expireTime: string;
}
export interface FetchIdTokenOptions {
/**
* Include the service account email in the token.
* If set to `true`, the token will contain `email` and `email_verified` claims.
*/
includeEmail: boolean;
}
export interface FetchIdTokenResponse {
/** The OpenId Connect ID token. */
token: string;
}
export declare class Impersonated extends OAuth2Client implements IdTokenProvider {
private sourceClient;
private targetPrincipal;
private targetScopes;
private delegates;
private lifetime;
private endpoint;
/**
* Impersonated service account credentials.
*
* Create a new access token by impersonating another service account.
*
* Impersonated Credentials allowing credentials issued to a user or
* service account to impersonate another. The source project using
* Impersonated Credentials must enable the "IAMCredentials" API.
* Also, the target service account must grant the orginating principal
* the "Service Account Token Creator" IAM role.
*
* @param {object} options - The configuration object.
* @param {object} [options.sourceClient] the source credential used as to
* acquire the impersonated credentials.
* @param {string} [options.targetPrincipal] the service account to
* impersonate.
* @param {string[]} [options.delegates] the chained list of delegates
* required to grant the final access_token. If set, the sequence of
* identities must have "Service Account Token Creator" capability granted to
* the preceding identity. For example, if set to [serviceAccountB,
* serviceAccountC], the sourceCredential must have the Token Creator role on
* serviceAccountB. serviceAccountB must have the Token Creator on
* serviceAccountC. Finally, C must have Token Creator on target_principal.
* If left unset, sourceCredential must have that role on targetPrincipal.
* @param {string[]} [options.targetScopes] scopes to request during the
* authorization grant.
* @param {number} [options.lifetime] number of seconds the delegated
* credential should be valid for up to 3600 seconds by default, or 43,200
* seconds by extending the token's lifetime, see:
* https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth
* @param {string} [options.endpoint] api endpoint override.
*/
constructor(options?: ImpersonatedOptions);
/**
* Refreshes the access token.
* @param refreshToken Unused parameter
*/
protected refreshToken(refreshToken?: string | null): Promise<GetTokenResponse>;
/**
* Generates an OpenID Connect ID token for a service account.
*
* {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation}
*
* @param targetAudience the audience for the fetched ID token.
* @param options the for the request
* @return an OpenID Connect ID token
*/
fetchIdToken(targetAudience: string, options?: FetchIdTokenOptions): Promise<string>;
}

View File

@@ -0,0 +1,63 @@
/// <reference types="node" />
import * as stream from 'stream';
import { JWTInput } from './credentials';
import { Headers } from './oauth2client';
export interface Claims {
[index: string]: string;
}
export declare class JWTAccess {
email?: string | null;
key?: string | null;
keyId?: string | null;
projectId?: string;
eagerRefreshThresholdMillis: number;
private cache;
/**
* JWTAccess service account credentials.
*
* Create a new access token by using the credential to create a new JWT token
* that's recognized as the access token.
*
* @param email the service account email address.
* @param key the private key that will be used to sign the token.
* @param keyId the ID of the private key used to sign the token.
*/
constructor(email?: string | null, key?: string | null, keyId?: string | null, eagerRefreshThresholdMillis?: number);
/**
* Ensures that we're caching a key appropriately, giving precedence to scopes vs. url
*
* @param url The URI being authorized.
* @param scopes The scope or scopes being authorized
* @returns A string that returns the cached key.
*/
getCachedKey(url?: string, scopes?: string | string[]): string;
/**
* Get a non-expired access token, after refreshing if necessary.
*
* @param url The URI being authorized.
* @param additionalClaims An object with a set of additional claims to
* include in the payload.
* @returns An object that includes the authorization header.
*/
getRequestHeaders(url?: string, additionalClaims?: Claims, scopes?: string | string[]): Headers;
/**
* Returns an expiration time for the JWT token.
*
* @param iat The issued at time for the JWT.
* @returns An expiration time for the JWT.
*/
private static getExpirationTime;
/**
* Create a JWTAccess credentials instance using the given input options.
* @param json The input object.
*/
fromJSON(json: JWTInput): void;
/**
* Create a JWTAccess credentials instance using the given input stream.
* @param inputStream The input stream.
* @param callback Optional callback.
*/
fromStream(inputStream: stream.Readable): Promise<void>;
fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void;
private fromStreamAsync;
}

View File

@@ -0,0 +1,110 @@
/// <reference types="node" />
import { GoogleToken } from 'gtoken';
import * as stream from 'stream';
import { CredentialBody, Credentials, JWTInput } from './credentials';
import { IdTokenProvider } from './idtokenclient';
import { GetTokenResponse, OAuth2Client, RefreshOptions, RequestMetadataResponse } from './oauth2client';
export interface JWTOptions extends RefreshOptions {
email?: string;
keyFile?: string;
key?: string;
keyId?: string;
scopes?: string | string[];
subject?: string;
additionalClaims?: {};
}
export declare class JWT extends OAuth2Client implements IdTokenProvider {
email?: string;
keyFile?: string;
key?: string;
keyId?: string;
defaultScopes?: string | string[];
scopes?: string | string[];
scope?: string;
subject?: string;
gtoken?: GoogleToken;
additionalClaims?: {};
useJWTAccessWithScope?: boolean;
defaultServicePath?: string;
private access?;
/**
* JWT service account credentials.
*
* Retrieve access token using gtoken.
*
* @param email service account email address.
* @param keyFile path to private key file.
* @param key value of key
* @param scopes list of requested scopes or a single scope.
* @param subject impersonated account's email address.
* @param key_id the ID of the key
*/
constructor(options: JWTOptions);
constructor(email?: string, keyFile?: string, key?: string, scopes?: string | string[], subject?: string, keyId?: string);
/**
* Creates a copy of the credential with the specified scopes.
* @param scopes List of requested scopes or a single scope.
* @return The cloned instance.
*/
createScoped(scopes?: string | string[]): JWT;
/**
* Obtains the metadata to be sent with the request.
*
* @param url the URI being authorized.
*/
protected getRequestMetadataAsync(url?: string | null): Promise<RequestMetadataResponse>;
/**
* Fetches an ID token.
* @param targetAudience the audience for the fetched ID token.
*/
fetchIdToken(targetAudience: string): Promise<string>;
/**
* Determine if there are currently scopes available.
*/
private hasUserScopes;
/**
* Are there any default or user scopes defined.
*/
private hasAnyScopes;
/**
* Get the initial access token using gToken.
* @param callback Optional callback.
* @returns Promise that resolves with credentials
*/
authorize(): Promise<Credentials>;
authorize(callback: (err: Error | null, result?: Credentials) => void): void;
private authorizeAsync;
/**
* Refreshes the access token.
* @param refreshToken ignored
* @private
*/
protected refreshTokenNoCache(refreshToken?: string | null): Promise<GetTokenResponse>;
/**
* Create a gToken if it doesn't already exist.
*/
private createGToken;
/**
* Create a JWT credentials instance using the given input options.
* @param json The input object.
*/
fromJSON(json: JWTInput): void;
/**
* Create a JWT credentials instance using the given input stream.
* @param inputStream The input stream.
* @param callback Optional callback.
*/
fromStream(inputStream: stream.Readable): Promise<void>;
fromStream(inputStream: stream.Readable, callback: (err?: Error | null) => void): void;
private fromStreamAsync;
/**
* Creates a JWT credentials instance using an API Key for authentication.
* @param apiKey The API Key in string form.
*/
fromAPIKey(apiKey: string): void;
/**
* Using the key or keyFile on the JWT client, obtain an object that contains
* the key and the client email.
*/
getCredentials(): Promise<CredentialBody>;
}

View File

@@ -0,0 +1,140 @@
export declare class LoginTicket {
private envelope?;
private payload?;
/**
* Create a simple class to extract user ID from an ID Token
*
* @param {string} env Envelope of the jwt
* @param {TokenPayload} pay Payload of the jwt
* @constructor
*/
constructor(env?: string, pay?: TokenPayload);
getEnvelope(): string | undefined;
getPayload(): TokenPayload | undefined;
/**
* Create a simple class to extract user ID from an ID Token
*
* @return The user ID
*/
getUserId(): string | null;
/**
* Returns attributes from the login ticket. This can contain
* various information about the user session.
*
* @return The envelope and payload
*/
getAttributes(): {
envelope: string | undefined;
payload: TokenPayload | undefined;
};
}
export interface TokenPayload {
/**
* The Issuer Identifier for the Issuer of the response. Always
* https://accounts.google.com or accounts.google.com for Google ID tokens.
*/
iss: string;
/**
* Access token hash. Provides validation that the access token is tied to the
* identity token. If the ID token is issued with an access token in the
* server flow, this is always included. This can be used as an alternate
* mechanism to protect against cross-site request forgery attacks, but if you
* follow Step 1 and Step 3 it is not necessary to verify the access token.
*/
at_hash?: string;
/**
* True if the user's e-mail address has been verified; otherwise false.
*/
email_verified?: boolean;
/**
* An identifier for the user, unique among all Google accounts and never
* reused. A Google account can have multiple emails at different points in
* time, but the sub value is never changed. Use sub within your application
* as the unique-identifier key for the user.
*/
sub: string;
/**
* The client_id of the authorized presenter. This claim is only needed when
* the party requesting the ID token is not the same as the audience of the ID
* token. This may be the case at Google for hybrid apps where a web
* application and Android app have a different client_id but share the same
* project.
*/
azp?: string;
/**
* The user's email address. This may not be unique and is not suitable for
* use as a primary key. Provided only if your scope included the string
* "email".
*/
email?: string;
/**
* The URL of the user's profile page. Might be provided when:
* - The request scope included the string "profile"
* - The ID token is returned from a token refresh
* - When profile claims are present, you can use them to update your app's
* user records. Note that this claim is never guaranteed to be present.
*/
profile?: string;
/**
* The URL of the user's profile picture. Might be provided when:
* - The request scope included the string "profile"
* - The ID token is returned from a token refresh
* - When picture claims are present, you can use them to update your app's
* user records. Note that this claim is never guaranteed to be present.
*/
picture?: string;
/**
* The user's full name, in a displayable form. Might be provided when:
* - The request scope included the string "profile"
* - The ID token is returned from a token refresh
* - When name claims are present, you can use them to update your app's user
* records. Note that this claim is never guaranteed to be present.
*/
name?: string;
/**
* The user's given name, in a displayable form. Might be provided when:
* - The request scope included the string "profile"
* - The ID token is returned from a token refresh
* - When name claims are present, you can use them to update your app's user
* records. Note that this claim is never guaranteed to be present.
*/
given_name?: string;
/**
* The user's family name, in a displayable form. Might be provided when:
* - The request scope included the string "profile"
* - The ID token is returned from a token refresh
* - When name claims are present, you can use them to update your app's user
* records. Note that this claim is never guaranteed to be present.
*/
family_name?: string;
/**
* Identifies the audience that this ID token is intended for. It must be one
* of the OAuth 2.0 client IDs of your application.
*/
aud: string;
/**
* The time the ID token was issued, represented in Unix time (integer
* seconds).
*/
iat: number;
/**
* The time the ID token expires, represented in Unix time (integer seconds).
*/
exp: number;
/**
* The value of the nonce supplied by your app in the authentication request.
* You should enforce protection against replay attacks by ensuring it is
* presented only once.
*/
nonce?: string;
/**
* The hosted G Suite domain of the user. Provided only if the user belongs to
* a hosted domain.
*/
hd?: string;
/**
* The user's locale, represented by a BCP 47 language tag.
* Might be provided when a name claim is present.
*/
locale?: string;
}

View File

@@ -0,0 +1,515 @@
import { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
import { JwkCertificate } from '../crypto/crypto';
import { BodyResponseCallback } from '../transporters';
import { AuthClient } from './authclient';
import { Credentials } from './credentials';
import { LoginTicket } from './loginticket';
/**
* The results from the `generateCodeVerifierAsync` method. To learn more,
* See the sample:
* https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js
*/
export interface CodeVerifierResults {
/**
* The code verifier that will be used when calling `getToken` to obtain a new
* access token.
*/
codeVerifier: string;
/**
* The code_challenge that should be sent with the `generateAuthUrl` call
* to obtain a verifiable authentication url.
*/
codeChallenge?: string;
}
export interface Certificates {
[index: string]: string | JwkCertificate;
}
export interface PublicKeys {
[index: string]: string;
}
export interface Headers {
[index: string]: string;
}
export declare enum CodeChallengeMethod {
Plain = "plain",
S256 = "S256"
}
export declare enum CertificateFormat {
PEM = "PEM",
JWK = "JWK"
}
export interface GetTokenOptions {
code: string;
codeVerifier?: string;
/**
* The client ID for your application. The value passed into the constructor
* will be used if not provided. Must match any client_id option passed to
* a corresponding call to generateAuthUrl.
*/
client_id?: string;
/**
* Determines where the API server redirects the user after the user
* completes the authorization flow. The value passed into the constructor
* will be used if not provided. Must match any redirect_uri option passed to
* a corresponding call to generateAuthUrl.
*/
redirect_uri?: string;
}
export interface TokenInfo {
/**
* The application that is the intended user of the access token.
*/
aud: string;
/**
* This value lets you correlate profile information from multiple Google
* APIs. It is only present in the response if you included the profile scope
* in your request in step 1. The field value is an immutable identifier for
* the logged-in user that can be used to create and manage user sessions in
* your application. The identifier is the same regardless of which client ID
* is used to retrieve it. This enables multiple applications in the same
* organization to correlate profile information.
*/
user_id?: string;
/**
* An array of scopes that the user granted access to.
*/
scopes: string[];
/**
* The datetime when the token becomes invalid.
*/
expiry_date: number;
/**
* An identifier for the user, unique among all Google accounts and never
* reused. A Google account can have multiple emails at different points in
* time, but the sub value is never changed. Use sub within your application
* as the unique-identifier key for the user.
*/
sub?: string;
/**
* The client_id of the authorized presenter. This claim is only needed when
* the party requesting the ID token is not the same as the audience of the ID
* token. This may be the case at Google for hybrid apps where a web
* application and Android app have a different client_id but share the same
* project.
*/
azp?: string;
/**
* Indicates whether your application can refresh access tokens
* when the user is not present at the browser. Valid parameter values are
* 'online', which is the default value, and 'offline'. Set the value to
* 'offline' if your application needs to refresh access tokens when the user
* is not present at the browser. This value instructs the Google
* authorization server to return a refresh token and an access token the
* first time that your application exchanges an authorization code for
* tokens.
*/
access_type?: string;
/**
* The user's email address. This value may not be unique to this user and
* is not suitable for use as a primary key. Provided only if your scope
* included the email scope value.
*/
email?: string;
/**
* True if the user's e-mail address has been verified; otherwise false.
*/
email_verified?: boolean;
}
export interface GenerateAuthUrlOpts {
/**
* Recommended. Indicates whether your application can refresh access tokens
* when the user is not present at the browser. Valid parameter values are
* 'online', which is the default value, and 'offline'. Set the value to
* 'offline' if your application needs to refresh access tokens when the user
* is not present at the browser. This value instructs the Google
* authorization server to return a refresh token and an access token the
* first time that your application exchanges an authorization code for
* tokens.
*/
access_type?: string;
/**
* The hd (hosted domain) parameter streamlines the login process for G Suite
* hosted accounts. By including the domain of the G Suite user (for example,
* mycollege.edu), you can indicate that the account selection UI should be
* optimized for accounts at that domain. To optimize for G Suite accounts
* generally instead of just one domain, use an asterisk: hd=*.
* Don't rely on this UI optimization to control who can access your app,
* as client-side requests can be modified. Be sure to validate that the
* returned ID token has an hd claim value that matches what you expect
* (e.g. mycolledge.edu). Unlike the request parameter, the ID token claim is
* contained within a security token from Google, so the value can be trusted.
*/
hd?: string;
/**
* The 'response_type' will always be set to 'CODE'.
*/
response_type?: string;
/**
* The client ID for your application. The value passed into the constructor
* will be used if not provided. You can find this value in the API Console.
*/
client_id?: string;
/**
* Determines where the API server redirects the user after the user
* completes the authorization flow. The value must exactly match one of the
* 'redirect_uri' values listed for your project in the API Console. Note that
* the http or https scheme, case, and trailing slash ('/') must all match.
* The value passed into the constructor will be used if not provided.
*/
redirect_uri?: string;
/**
* Required. A space-delimited list of scopes that identify the resources that
* your application could access on the user's behalf. These values inform the
* consent screen that Google displays to the user. Scopes enable your
* application to only request access to the resources that it needs while
* also enabling users to control the amount of access that they grant to your
* application. Thus, there is an inverse relationship between the number of
* scopes requested and the likelihood of obtaining user consent. The
* OAuth 2.0 API Scopes document provides a full list of scopes that you might
* use to access Google APIs. We recommend that your application request
* access to authorization scopes in context whenever possible. By requesting
* access to user data in context, via incremental authorization, you help
* users to more easily understand why your application needs the access it is
* requesting.
*/
scope?: string[] | string;
/**
* Recommended. Specifies any string value that your application uses to
* maintain state between your authorization request and the authorization
* server's response. The server returns the exact value that you send as a
* name=value pair in the hash (#) fragment of the 'redirect_uri' after the
* user consents to or denies your application's access request. You can use
* this parameter for several purposes, such as directing the user to the
* correct resource in your application, sending nonces, and mitigating
* cross-site request forgery. Since your redirect_uri can be guessed, using a
* state value can increase your assurance that an incoming connection is the
* result of an authentication request. If you generate a random string or
* encode the hash of a cookie or another value that captures the client's
* state, you can validate the response to additionally ensure that the
* request and response originated in the same browser, providing protection
* against attacks such as cross-site request forgery. See the OpenID Connect
* documentation for an example of how to create and confirm a state token.
*/
state?: string;
/**
* Optional. Enables applications to use incremental authorization to request
* access to additional scopes in context. If you set this parameter's value
* to true and the authorization request is granted, then the new access token
* will also cover any scopes to which the user previously granted the
* application access. See the incremental authorization section for examples.
*/
include_granted_scopes?: boolean;
/**
* Optional. If your application knows which user is trying to authenticate,
* it can use this parameter to provide a hint to the Google Authentication
* Server. The server uses the hint to simplify the login flow either by
* prefilling the email field in the sign-in form or by selecting the
* appropriate multi-login session. Set the parameter value to an email
* address or sub identifier, which is equivalent to the user's Google ID.
*/
login_hint?: string;
/**
* Optional. A space-delimited, case-sensitive list of prompts to present the
* user. If you don't specify this parameter, the user will be prompted only
* the first time your app requests access. Possible values are:
*
* 'none' - Donot display any authentication or consent screens. Must not be
* specified with other values.
* 'consent' - Prompt the user for consent.
* 'select_account' - Prompt the user to select an account.
*/
prompt?: string;
/**
* Recommended. Specifies what method was used to encode a 'code_verifier'
* that will be used during authorization code exchange. This parameter must
* be used with the 'code_challenge' parameter. The value of the
* 'code_challenge_method' defaults to "plain" if not present in the request
* that includes a 'code_challenge'. The only supported values for this
* parameter are "S256" or "plain".
*/
code_challenge_method?: CodeChallengeMethod;
/**
* Recommended. Specifies an encoded 'code_verifier' that will be used as a
* server-side challenge during authorization code exchange. This parameter
* must be used with the 'code_challenge' parameter described above.
*/
code_challenge?: string;
}
export interface AccessTokenResponse {
access_token: string;
expiry_date: number;
}
export interface GetRefreshHandlerCallback {
(): Promise<AccessTokenResponse>;
}
export interface GetTokenCallback {
(err: GaxiosError | null, token?: Credentials | null, res?: GaxiosResponse | null): void;
}
export interface GetTokenResponse {
tokens: Credentials;
res: GaxiosResponse | null;
}
export interface GetAccessTokenCallback {
(err: GaxiosError | null, token?: string | null, res?: GaxiosResponse | null): void;
}
export interface GetAccessTokenResponse {
token?: string | null;
res?: GaxiosResponse | null;
}
export interface RefreshAccessTokenCallback {
(err: GaxiosError | null, credentials?: Credentials | null, res?: GaxiosResponse | null): void;
}
export interface RefreshAccessTokenResponse {
credentials: Credentials;
res: GaxiosResponse | null;
}
export interface RequestMetadataResponse {
headers: Headers;
res?: GaxiosResponse<void> | null;
}
export interface RequestMetadataCallback {
(err: GaxiosError | null, headers?: Headers, res?: GaxiosResponse<void> | null): void;
}
export interface GetFederatedSignonCertsCallback {
(err: GaxiosError | null, certs?: Certificates, response?: GaxiosResponse<void> | null): void;
}
export interface FederatedSignonCertsResponse {
certs: Certificates;
format: CertificateFormat;
res?: GaxiosResponse<void> | null;
}
export interface GetIapPublicKeysCallback {
(err: GaxiosError | null, pubkeys?: PublicKeys, response?: GaxiosResponse<void> | null): void;
}
export interface IapPublicKeysResponse {
pubkeys: PublicKeys;
res?: GaxiosResponse<void> | null;
}
export interface RevokeCredentialsResult {
success: boolean;
}
export interface VerifyIdTokenOptions {
idToken: string;
audience?: string | string[];
maxExpiry?: number;
}
export interface OAuth2ClientOptions extends RefreshOptions {
clientId?: string;
clientSecret?: string;
redirectUri?: string;
}
export interface RefreshOptions {
eagerRefreshThresholdMillis?: number;
forceRefreshOnFailure?: boolean;
}
export declare class OAuth2Client extends AuthClient {
private redirectUri?;
private certificateCache;
private certificateExpiry;
private certificateCacheFormat;
protected refreshTokenPromises: Map<string, Promise<GetTokenResponse>>;
_clientId?: string;
_clientSecret?: string;
apiKey?: string;
projectId?: string;
eagerRefreshThresholdMillis: number;
forceRefreshOnFailure: boolean;
refreshHandler?: GetRefreshHandlerCallback;
/**
* Handles OAuth2 flow for Google APIs.
*
* @param clientId The authentication client ID.
* @param clientSecret The authentication client secret.
* @param redirectUri The URI to redirect to after completing the auth
* request.
* @param opts optional options for overriding the given parameters.
* @constructor
*/
constructor(options?: OAuth2ClientOptions);
constructor(clientId?: string, clientSecret?: string, redirectUri?: string);
protected static readonly GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo";
/**
* The base URL for auth endpoints.
*/
private static readonly GOOGLE_OAUTH2_AUTH_BASE_URL_;
/**
* The base endpoint for token retrieval.
*/
private static readonly GOOGLE_OAUTH2_TOKEN_URL_;
/**
* The base endpoint to revoke tokens.
*/
private static readonly GOOGLE_OAUTH2_REVOKE_URL_;
/**
* Google Sign on certificates in PEM format.
*/
private static readonly GOOGLE_OAUTH2_FEDERATED_SIGNON_PEM_CERTS_URL_;
/**
* Google Sign on certificates in JWK format.
*/
private static readonly GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_;
/**
* Google Sign on certificates in JWK format.
*/
private static readonly GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_;
/**
* Clock skew - five minutes in seconds
*/
private static readonly CLOCK_SKEW_SECS_;
/**
* Max Token Lifetime is one day in seconds
*/
private static readonly MAX_TOKEN_LIFETIME_SECS_;
/**
* The allowed oauth token issuers.
*/
private static readonly ISSUERS_;
/**
* Generates URL for consent page landing.
* @param opts Options.
* @return URL to consent page.
*/
generateAuthUrl(opts?: GenerateAuthUrlOpts): string;
generateCodeVerifier(): void;
/**
* Convenience method to automatically generate a code_verifier, and its
* resulting SHA256. If used, this must be paired with a S256
* code_challenge_method.
*
* For a full example see:
* https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js
*/
generateCodeVerifierAsync(): Promise<CodeVerifierResults>;
/**
* Gets the access token for the given code.
* @param code The authorization code.
* @param callback Optional callback fn.
*/
getToken(code: string): Promise<GetTokenResponse>;
getToken(options: GetTokenOptions): Promise<GetTokenResponse>;
getToken(code: string, callback: GetTokenCallback): void;
getToken(options: GetTokenOptions, callback: GetTokenCallback): void;
private getTokenAsync;
/**
* Refreshes the access token.
* @param refresh_token Existing refresh token.
* @private
*/
protected refreshToken(refreshToken?: string | null): Promise<GetTokenResponse>;
protected refreshTokenNoCache(refreshToken?: string | null): Promise<GetTokenResponse>;
/**
* Retrieves the access token using refresh token
*
* @param callback callback
*/
refreshAccessToken(): Promise<RefreshAccessTokenResponse>;
refreshAccessToken(callback: RefreshAccessTokenCallback): void;
private refreshAccessTokenAsync;
/**
* Get a non-expired access token, after refreshing if necessary
*
* @param callback Callback to call with the access token
*/
getAccessToken(): Promise<GetAccessTokenResponse>;
getAccessToken(callback: GetAccessTokenCallback): void;
private getAccessTokenAsync;
/**
* The main authentication interface. It takes an optional url which when
* present is the endpoint being accessed, and returns a Promise which
* resolves with authorization header fields.
*
* In OAuth2Client, the result has the form:
* { Authorization: 'Bearer <access_token_value>' }
* @param url The optional url being authorized
*/
getRequestHeaders(url?: string): Promise<Headers>;
protected getRequestMetadataAsync(url?: string | null): Promise<RequestMetadataResponse>;
/**
* Generates an URL to revoke the given token.
* @param token The existing token to be revoked.
*/
static getRevokeTokenUrl(token: string): string;
/**
* Revokes the access given to token.
* @param token The existing token to be revoked.
* @param callback Optional callback fn.
*/
revokeToken(token: string): GaxiosPromise<RevokeCredentialsResult>;
revokeToken(token: string, callback: BodyResponseCallback<RevokeCredentialsResult>): void;
/**
* Revokes access token and clears the credentials object
* @param callback callback
*/
revokeCredentials(): GaxiosPromise<RevokeCredentialsResult>;
revokeCredentials(callback: BodyResponseCallback<RevokeCredentialsResult>): void;
private revokeCredentialsAsync;
/**
* Provides a request implementation with OAuth 2.0 flow. If credentials have
* a refresh_token, in cases of HTTP 401 and 403 responses, it automatically
* asks for a new access token and replays the unsuccessful request.
* @param opts Request options.
* @param callback callback.
* @return Request object
*/
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
request<T>(opts: GaxiosOptions, callback: BodyResponseCallback<T>): void;
protected requestAsync<T>(opts: GaxiosOptions, retry?: boolean): Promise<GaxiosResponse<T>>;
/**
* Verify id token is token by checking the certs and audience
* @param options that contains all options.
* @param callback Callback supplying GoogleLogin if successful
*/
verifyIdToken(options: VerifyIdTokenOptions): Promise<LoginTicket>;
verifyIdToken(options: VerifyIdTokenOptions, callback: (err: Error | null, login?: LoginTicket) => void): void;
private verifyIdTokenAsync;
/**
* Obtains information about the provisioned access token. Especially useful
* if you want to check the scopes that were provisioned to a given token.
*
* @param accessToken Required. The Access Token for which you want to get
* user info.
*/
getTokenInfo(accessToken: string): Promise<TokenInfo>;
/**
* Gets federated sign-on certificates to use for verifying identity tokens.
* Returns certs as array structure, where keys are key ids, and values
* are certificates in either PEM or JWK format.
* @param callback Callback supplying the certificates
*/
getFederatedSignonCerts(): Promise<FederatedSignonCertsResponse>;
getFederatedSignonCerts(callback: GetFederatedSignonCertsCallback): void;
getFederatedSignonCertsAsync(): Promise<FederatedSignonCertsResponse>;
/**
* Gets federated sign-on certificates to use for verifying identity tokens.
* Returns certs as array structure, where keys are key ids, and values
* are certificates in either PEM or JWK format.
* @param callback Callback supplying the certificates
*/
getIapPublicKeys(): Promise<IapPublicKeysResponse>;
getIapPublicKeys(callback: GetIapPublicKeysCallback): void;
getIapPublicKeysAsync(): Promise<IapPublicKeysResponse>;
verifySignedJwtWithCerts(): void;
/**
* Verify the id token is signed with the correct certificate
* and is from the correct audience.
* @param jwt The jwt to verify (The ID Token in this case).
* @param certs The array of certs to test the jwt against.
* @param requiredAudience The audience to test the jwt against.
* @param issuers The allowed issuers of the jwt (Optional).
* @param maxExpiry The max expiry the certificate can be (Optional).
* @return Returns a promise resolving to LoginTicket on verification.
*/
verifySignedJwtWithCertsAsync(jwt: string, certs: Certificates | PublicKeys, requiredAudience?: string | string[], issuers?: string[], maxExpiry?: number): Promise<LoginTicket>;
/**
* Returns a promise that resolves with AccessTokenResponse type if
* refreshHandler is defined.
* If not, nothing is returned.
*/
private processAndValidateRefreshHandler;
/**
* Returns true if a token is expired or will expire within
* eagerRefreshThresholdMillismilliseconds.
* If there is no expiry time, assumes the token is not expired or expiring.
*/
protected isTokenExpiring(): boolean;
}

View File

@@ -0,0 +1,82 @@
import { GaxiosOptions } from 'gaxios';
/**
* OAuth error codes.
* https://tools.ietf.org/html/rfc6749#section-5.2
*/
declare type OAuthErrorCode = 'invalid_request' | 'invalid_client' | 'invalid_grant' | 'unauthorized_client' | 'unsupported_grant_type' | 'invalid_scope' | string;
/**
* The standard OAuth error response.
* https://tools.ietf.org/html/rfc6749#section-5.2
*/
export interface OAuthErrorResponse {
error: OAuthErrorCode;
error_description?: string;
error_uri?: string;
}
/**
* OAuth client authentication types.
* https://tools.ietf.org/html/rfc6749#section-2.3
*/
export declare type ConfidentialClientType = 'basic' | 'request-body';
/**
* Defines the client authentication credentials for basic and request-body
* credentials.
* https://tools.ietf.org/html/rfc6749#section-2.3.1
*/
export interface ClientAuthentication {
confidentialClientType: ConfidentialClientType;
clientId: string;
clientSecret?: string;
}
/**
* Abstract class for handling client authentication in OAuth-based
* operations.
* When request-body client authentication is used, only application/json and
* application/x-www-form-urlencoded content types for HTTP methods that support
* request bodies are supported.
*/
export declare abstract class OAuthClientAuthHandler {
private readonly clientAuthentication?;
private crypto;
/**
* Instantiates an OAuth client authentication handler.
* @param clientAuthentication The client auth credentials.
*/
constructor(clientAuthentication?: ClientAuthentication | undefined);
/**
* Applies client authentication on the OAuth request's headers or POST
* body but does not process the request.
* @param opts The GaxiosOptions whose headers or data are to be modified
* depending on the client authentication mechanism to be used.
* @param bearerToken The optional bearer token to use for authentication.
* When this is used, no client authentication credentials are needed.
*/
protected applyClientAuthenticationOptions(opts: GaxiosOptions, bearerToken?: string): void;
/**
* Applies client authentication on the request's header if either
* basic authentication or bearer token authentication is selected.
*
* @param opts The GaxiosOptions whose headers or data are to be modified
* depending on the client authentication mechanism to be used.
* @param bearerToken The optional bearer token to use for authentication.
* When this is used, no client authentication credentials are needed.
*/
private injectAuthenticatedHeaders;
/**
* Applies client authentication on the request's body if request-body
* client authentication is selected.
*
* @param opts The GaxiosOptions whose headers or data are to be modified
* depending on the client authentication mechanism to be used.
*/
private injectAuthenticatedRequestBody;
}
/**
* Converts an OAuth error response to a native JavaScript Error.
* @param resp The OAuth error response to convert to a native Error object.
* @param err The optional original error. If provided, the error properties
* will be copied to the new error.
* @return The converted native Error object.
*/
export declare function getErrorFromOAuthErrorResponse(resp: OAuthErrorResponse, err?: Error): Error;
export {};

View File

@@ -0,0 +1,154 @@
import { BaseExternalAccountClient, BaseExternalAccountClientOptions } from './baseexternalclient';
import { RefreshOptions } from './oauth2client';
/**
* Defines the credential source portion of the configuration for PluggableAuthClient.
*
* <p>Command is the only required field. If timeout_millis is not specified, the library will
* default to a 30-second timeout.
*
* <pre>
* Sample credential source for Pluggable Auth Client:
* {
* ...
* "credential_source": {
* "executable": {
* "command": "/path/to/get/credentials.sh --arg1=value1 --arg2=value2",
* "timeout_millis": 5000,
* "output_file": "/path/to/generated/cached/credentials"
* }
* }
* }
* </pre>
*/
export interface PluggableAuthClientOptions extends BaseExternalAccountClientOptions {
credential_source: {
executable: {
/**
* The command used to retrieve the 3rd party token.
*/
command: string;
/**
* The timeout for executable to run in milliseconds. If none is provided it
* will be set to the default timeout of 30 seconds.
*/
timeout_millis?: number;
/**
* An optional output file location that will be checked for a cached response
* from a previous run of the executable.
*/
output_file?: string;
};
};
}
/**
* Error thrown from the executable run by PluggableAuthClient.
*/
export declare class ExecutableError extends Error {
/**
* The exit code returned by the executable.
*/
readonly code: string;
constructor(message: string, code: string);
}
/**
* PluggableAuthClient enables the exchange of workload identity pool external credentials for
* Google access tokens by retrieving 3rd party tokens through a user supplied executable. These
* scripts/executables are completely independent of the Google Cloud Auth libraries. These
* credentials plug into ADC and will call the specified executable to retrieve the 3rd party token
* to be exchanged for a Google access token.
*
* <p>To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable
* must be set to '1'. This is for security reasons.
*
* <p>Both OIDC and SAML are supported. The executable must adhere to a specific response format
* defined below.
*
* <p>The executable must print out the 3rd party token to STDOUT in JSON format. When an
* output_file is specified in the credential configuration, the executable must also handle writing the
* JSON response to this file.
*
* <pre>
* OIDC response sample:
* {
* "version": 1,
* "success": true,
* "token_type": "urn:ietf:params:oauth:token-type:id_token",
* "id_token": "HEADER.PAYLOAD.SIGNATURE",
* "expiration_time": 1620433341
* }
*
* SAML2 response sample:
* {
* "version": 1,
* "success": true,
* "token_type": "urn:ietf:params:oauth:token-type:saml2",
* "saml_response": "...",
* "expiration_time": 1620433341
* }
*
* Error response sample:
* {
* "version": 1,
* "success": false,
* "code": "401",
* "message": "Error message."
* }
* </pre>
*
* <p>The "expiration_time" field in the JSON response is only required for successful
* responses when an output file was specified in the credential configuration
*
* <p>The auth libraries will populate certain environment variables that will be accessible by the
* executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE,
* GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and
* GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE.
*
* <p>Please see this repositories README for a complete executable request/response specification.
*/
export declare class PluggableAuthClient extends BaseExternalAccountClient {
/**
* The command used to retrieve the third party token.
*/
private readonly command;
/**
* The timeout in milliseconds for running executable,
* set to default if none provided.
*/
private readonly timeoutMillis;
/**
* The path to file to check for cached executable response.
*/
private readonly outputFile?;
/**
* Executable and output file handler.
*/
private readonly handler;
/**
* Instantiates a PluggableAuthClient instance using the provided JSON
* object loaded from an external account credentials file.
* An error is thrown if the credential is not a valid pluggable auth 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: PluggableAuthClientOptions, additionalOptions?: RefreshOptions);
/**
* Triggered when an 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 calls a user provided executable which returns the subject token.
* The logic is summarized as:
* 1. Validated that the executable is allowed to run. The
* GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to
* 1 for security reasons.
* 2. If an output file is specified by the user, check the file location
* for a response. If the file exists and contains a valid response,
* return the subject token from the file.
* 3. Call the provided executable and return response.
* @return A promise that resolves with the external subject token.
*/
retrieveSubjectToken(): Promise<string>;
}

View File

@@ -0,0 +1,51 @@
import { ExecutableResponse } from './executable-response';
/**
* Defines the options used for the PluggableAuthHandler class.
*/
export interface PluggableAuthHandlerOptions {
/**
* The command used to retrieve the third party token.
*/
command: string;
/**
* The timeout in milliseconds for running executable,
* set to default if none provided.
*/
timeoutMillis: number;
/**
* The path to file to check for cached executable response.
*/
outputFile?: string;
}
/**
* A handler used to retrieve 3rd party token responses from user defined
* executables and cached file output for the PluggableAuthClient class.
*/
export declare class PluggableAuthHandler {
private readonly commandComponents;
private readonly timeoutMillis;
private readonly outputFile?;
/**
* Instantiates a PluggableAuthHandler instance using the provided
* PluggableAuthHandlerOptions object.
*/
constructor(options: PluggableAuthHandlerOptions);
/**
* Calls user provided executable to get a 3rd party subject token and
* returns the response.
* @param envMap a Map of additional Environment Variables required for
* the executable.
* @return A promise that resolves with the executable response.
*/
retrieveResponseFromExecutable(envMap: Map<string, string>): Promise<ExecutableResponse>;
/**
* Checks user provided output file for response from previous run of
* executable and return the response if it exists, is formatted correctly, and is not expired.
*/
retrieveCachedResponse(): Promise<ExecutableResponse | undefined>;
/**
* Parses given command string into component array, splitting on spaces unless
* spaces are between quotation marks.
*/
private static parseCommand;
}

View File

@@ -0,0 +1,43 @@
/// <reference types="node" />
import * as stream from 'stream';
import { JWTInput } from './credentials';
import { GetTokenResponse, OAuth2Client, RefreshOptions } from './oauth2client';
export interface UserRefreshClientOptions extends RefreshOptions {
clientId?: string;
clientSecret?: string;
refreshToken?: string;
}
export declare class UserRefreshClient extends OAuth2Client {
_refreshToken?: string | null;
/**
* User Refresh Token credentials.
*
* @param clientId The authentication client ID.
* @param clientSecret The authentication client secret.
* @param refreshToken The authentication refresh token.
*/
constructor(clientId?: string, clientSecret?: string, refreshToken?: string);
constructor(options: UserRefreshClientOptions);
constructor(clientId?: string, clientSecret?: string, refreshToken?: string);
/**
* Refreshes the access token.
* @param refreshToken An ignored refreshToken..
* @param callback Optional callback.
*/
protected refreshTokenNoCache(refreshToken?: string | null): Promise<GetTokenResponse>;
/**
* Create a UserRefreshClient credentials instance using the given input
* options.
* @param json The input object.
*/
fromJSON(json: JWTInput): void;
/**
* Create a UserRefreshClient credentials instance using the given input
* stream.
* @param inputStream The input stream.
* @param callback Optional callback.
*/
fromStream(inputStream: stream.Readable): Promise<void>;
fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void;
private fromStreamAsync;
}

View File

@@ -0,0 +1,114 @@
import { GaxiosResponse } from 'gaxios';
import { Headers } from './oauth2client';
import { ClientAuthentication, OAuthClientAuthHandler } from './oauth2common';
/**
* Defines the interface needed to initialize an StsCredentials instance.
* The interface does not directly map to the spec and instead is converted
* to be compliant with the JavaScript style guide. This is because this is
* instantiated internally.
* StsCredentials implement the OAuth 2.0 token exchange based on
* https://tools.ietf.org/html/rfc8693.
* Request options are defined in
* https://tools.ietf.org/html/rfc8693#section-2.1
*/
export interface StsCredentialsOptions {
/**
* REQUIRED. The value "urn:ietf:params:oauth:grant-type:token-exchange"
* indicates that a token exchange is being performed.
*/
grantType: string;
/**
* OPTIONAL. A URI that indicates the target service or resource where the
* client intends to use the requested security token.
*/
resource?: string;
/**
* OPTIONAL. The logical name of the target service where the client
* intends to use the requested security token. This serves a purpose
* similar to the "resource" parameter but with the client providing a
* logical name for the target service.
*/
audience?: string;
/**
* OPTIONAL. A list of space-delimited, case-sensitive strings, as defined
* in Section 3.3 of [RFC6749], that allow the client to specify the desired
* scope of the requested security token in the context of the service or
* resource where the token will be used.
*/
scope?: string[];
/**
* OPTIONAL. An identifier, as described in Section 3 of [RFC8693], eg.
* "urn:ietf:params:oauth:token-type:access_token" for the type of the
* requested security token.
*/
requestedTokenType?: string;
/**
* REQUIRED. A security token that represents the identity of the party on
* behalf of whom the request is being made.
*/
subjectToken: string;
/**
* REQUIRED. An identifier, as described in Section 3 of [RFC8693], that
* indicates the type of the security token in the "subject_token" parameter.
*/
subjectTokenType: string;
actingParty?: {
/**
* OPTIONAL. A security token that represents the identity of the acting
* party. Typically, this will be the party that is authorized to use the
* requested security token and act on behalf of the subject.
*/
actorToken: string;
/**
* An identifier, as described in Section 3, that indicates the type of the
* security token in the "actor_token" parameter. This is REQUIRED when the
* "actor_token" parameter is present in the request but MUST NOT be
* included otherwise.
*/
actorTokenType: string;
};
}
/**
* Defines the OAuth 2.0 token exchange successful response based on
* https://tools.ietf.org/html/rfc8693#section-2.2.1
*/
export interface StsSuccessfulResponse {
access_token: string;
issued_token_type: string;
token_type: string;
expires_in?: number;
refresh_token?: string;
scope?: string;
res?: GaxiosResponse | null;
}
/**
* Implements the OAuth 2.0 token exchange based on
* https://tools.ietf.org/html/rfc8693
*/
export declare class StsCredentials extends OAuthClientAuthHandler {
private readonly tokenExchangeEndpoint;
private transporter;
/**
* Initializes an STS credentials instance.
* @param tokenExchangeEndpoint The token exchange endpoint.
* @param clientAuthentication The client authentication credentials if
* available.
*/
constructor(tokenExchangeEndpoint: string, clientAuthentication?: ClientAuthentication);
/**
* Exchanges the provided token for another type of token based on the
* rfc8693 spec.
* @param stsCredentialsOptions The token exchange options used to populate
* the token exchange request.
* @param additionalHeaders Optional additional headers to pass along the
* request.
* @param options Optional additional GCP-specific non-spec defined options
* to send with the request.
* Example: `&options=${encodeUriComponent(JSON.stringified(options))}`
* @return A promise that resolves with the token exchange response containing
* the requested token and its expiration time.
*/
exchangeToken(stsCredentialsOptions: StsCredentialsOptions, additionalHeaders?: Headers, options?: {
[key: string]: any;
}): Promise<StsSuccessfulResponse>;
}

View File

@@ -0,0 +1,27 @@
import { Crypto, JwkCertificate } from '../crypto';
export declare class BrowserCrypto implements Crypto {
constructor();
sha256DigestBase64(str: string): Promise<string>;
randomBytesBase64(count: number): string;
private static padBase64;
verify(pubkey: JwkCertificate, data: string, signature: string): Promise<boolean>;
sign(privateKey: JwkCertificate, data: string): Promise<string>;
decodeBase64StringUtf8(base64: string): string;
encodeBase64StringUtf8(text: string): string;
/**
* Computes the SHA-256 hash of the provided string.
* @param str The plain text string to hash.
* @return A promise that resolves with the SHA-256 hash of the provided
* string in hexadecimal encoding.
*/
sha256DigestHex(str: string): Promise<string>;
/**
* Computes the HMAC hash of a message using the provided crypto key and the
* SHA-256 algorithm.
* @param key The secret crypto key in utf-8 or ArrayBuffer format.
* @param msg The plain text message.
* @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
* format.
*/
signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise<ArrayBuffer>;
}

View File

@@ -0,0 +1,141 @@
"use strict";
// Copyright 2019 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.
/* global window */
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserCrypto = void 0;
// This file implements crypto functions we need using in-browser
// SubtleCrypto interface `window.crypto.subtle`.
const base64js = require("base64-js");
// Not all browsers support `TextEncoder`. The following `require` will
// provide a fast UTF8-only replacement for those browsers that don't support
// text encoding natively.
// eslint-disable-next-line node/no-unsupported-features/node-builtins
if (typeof process === 'undefined' && typeof TextEncoder === 'undefined') {
require('fast-text-encoding');
}
const crypto_1 = require("../crypto");
class BrowserCrypto {
constructor() {
if (typeof window === 'undefined' ||
window.crypto === undefined ||
window.crypto.subtle === undefined) {
throw new Error("SubtleCrypto not found. Make sure it's an https:// website.");
}
}
async sha256DigestBase64(str) {
// SubtleCrypto digest() method is async, so we must make
// this method async as well.
// To calculate SHA256 digest using SubtleCrypto, we first
// need to convert an input string to an ArrayBuffer:
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const inputBuffer = new TextEncoder().encode(str);
// Result is ArrayBuffer as well.
const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);
return base64js.fromByteArray(new Uint8Array(outputBuffer));
}
randomBytesBase64(count) {
const array = new Uint8Array(count);
window.crypto.getRandomValues(array);
return base64js.fromByteArray(array);
}
static padBase64(base64) {
// base64js requires padding, so let's add some '='
while (base64.length % 4 !== 0) {
base64 += '=';
}
return base64;
}
async verify(pubkey, data, signature) {
const algo = {
name: 'RSASSA-PKCS1-v1_5',
hash: { name: 'SHA-256' },
};
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const dataArray = new TextEncoder().encode(data);
const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature));
const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']);
// SubtleCrypto's verify method is async so we must make
// this method async as well.
const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray);
return result;
}
async sign(privateKey, data) {
const algo = {
name: 'RSASSA-PKCS1-v1_5',
hash: { name: 'SHA-256' },
};
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const dataArray = new TextEncoder().encode(data);
const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']);
// SubtleCrypto's sign method is async so we must make
// this method async as well.
const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray);
return base64js.fromByteArray(new Uint8Array(result));
}
decodeBase64StringUtf8(base64) {
const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64));
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const result = new TextDecoder().decode(uint8array);
return result;
}
encodeBase64StringUtf8(text) {
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const uint8array = new TextEncoder().encode(text);
const result = base64js.fromByteArray(uint8array);
return result;
}
/**
* Computes the SHA-256 hash of the provided string.
* @param str The plain text string to hash.
* @return A promise that resolves with the SHA-256 hash of the provided
* string in hexadecimal encoding.
*/
async sha256DigestHex(str) {
// SubtleCrypto digest() method is async, so we must make
// this method async as well.
// To calculate SHA256 digest using SubtleCrypto, we first
// need to convert an input string to an ArrayBuffer:
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const inputBuffer = new TextEncoder().encode(str);
// Result is ArrayBuffer as well.
const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);
return (0, crypto_1.fromArrayBufferToHex)(outputBuffer);
}
/**
* Computes the HMAC hash of a message using the provided crypto key and the
* SHA-256 algorithm.
* @param key The secret crypto key in utf-8 or ArrayBuffer format.
* @param msg The plain text message.
* @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
* format.
*/
async signWithHmacSha256(key, msg) {
// Convert key, if provided in ArrayBuffer format, to string.
const rawKey = typeof key === 'string'
? key
: String.fromCharCode(...new Uint16Array(key));
// eslint-disable-next-line node/no-unsupported-features/node-builtins
const enc = new TextEncoder();
const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), {
name: 'HMAC',
hash: {
name: 'SHA-256',
},
}, false, ['sign']);
return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg));
}
}
exports.BrowserCrypto = BrowserCrypto;
//# sourceMappingURL=crypto.js.map

View File

@@ -0,0 +1,45 @@
/// <reference types="node" />
export interface JwkCertificate {
kty: string;
alg: string;
use?: string;
kid: string;
n: string;
e: string;
}
export interface CryptoSigner {
update(data: string): void;
sign(key: string, outputFormat: string): string;
}
export interface Crypto {
sha256DigestBase64(str: string): Promise<string>;
randomBytesBase64(n: number): string;
verify(pubkey: string | JwkCertificate, data: string | Buffer, signature: string): Promise<boolean>;
sign(privateKey: string | JwkCertificate, data: string | Buffer): Promise<string>;
decodeBase64StringUtf8(base64: string): string;
encodeBase64StringUtf8(text: string): string;
/**
* Computes the SHA-256 hash of the provided string.
* @param str The plain text string to hash.
* @return A promise that resolves with the SHA-256 hash of the provided
* string in hexadecimal encoding.
*/
sha256DigestHex(str: string): Promise<string>;
/**
* Computes the HMAC hash of a message using the provided crypto key and the
* SHA-256 algorithm.
* @param key The secret crypto key in utf-8 or ArrayBuffer format.
* @param msg The plain text message.
* @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
* format.
*/
signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise<ArrayBuffer>;
}
export declare function createCrypto(): Crypto;
export declare function hasBrowserCrypto(): boolean;
/**
* Converts an ArrayBuffer to a hexadecimal string.
* @param arrayBuffer The ArrayBuffer to convert to hexadecimal string.
* @return The hexadecimal encoding of the ArrayBuffer.
*/
export declare function fromArrayBufferToHex(arrayBuffer: ArrayBuffer): string;

View File

@@ -0,0 +1,26 @@
/// <reference types="node" />
import { Crypto } from '../crypto';
export declare class NodeCrypto implements Crypto {
sha256DigestBase64(str: string): Promise<string>;
randomBytesBase64(count: number): string;
verify(pubkey: string, data: string | Buffer, signature: string): Promise<boolean>;
sign(privateKey: string, data: string | Buffer): Promise<string>;
decodeBase64StringUtf8(base64: string): string;
encodeBase64StringUtf8(text: string): string;
/**
* Computes the SHA-256 hash of the provided string.
* @param str The plain text string to hash.
* @return A promise that resolves with the SHA-256 hash of the provided
* string in hexadecimal encoding.
*/
sha256DigestHex(str: string): Promise<string>;
/**
* Computes the HMAC hash of a message using the provided crypto key and the
* SHA-256 algorithm.
* @param key The secret crypto key in utf-8 or ArrayBuffer format.
* @param msg The plain text message.
* @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
* format.
*/
signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise<ArrayBuffer>;
}

View File

@@ -0,0 +1,83 @@
"use strict";
// Copyright 2019 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.
Object.defineProperty(exports, "__esModule", { value: true });
exports.NodeCrypto = void 0;
const crypto = require("crypto");
class NodeCrypto {
async sha256DigestBase64(str) {
return crypto.createHash('sha256').update(str).digest('base64');
}
randomBytesBase64(count) {
return crypto.randomBytes(count).toString('base64');
}
async verify(pubkey, data, signature) {
const verifier = crypto.createVerify('sha256');
verifier.update(data);
verifier.end();
return verifier.verify(pubkey, signature, 'base64');
}
async sign(privateKey, data) {
const signer = crypto.createSign('RSA-SHA256');
signer.update(data);
signer.end();
return signer.sign(privateKey, 'base64');
}
decodeBase64StringUtf8(base64) {
return Buffer.from(base64, 'base64').toString('utf-8');
}
encodeBase64StringUtf8(text) {
return Buffer.from(text, 'utf-8').toString('base64');
}
/**
* Computes the SHA-256 hash of the provided string.
* @param str The plain text string to hash.
* @return A promise that resolves with the SHA-256 hash of the provided
* string in hexadecimal encoding.
*/
async sha256DigestHex(str) {
return crypto.createHash('sha256').update(str).digest('hex');
}
/**
* Computes the HMAC hash of a message using the provided crypto key and the
* SHA-256 algorithm.
* @param key The secret crypto key in utf-8 or ArrayBuffer format.
* @param msg The plain text message.
* @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer
* format.
*/
async signWithHmacSha256(key, msg) {
const cryptoKey = typeof key === 'string' ? key : toBuffer(key);
return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest());
}
}
exports.NodeCrypto = NodeCrypto;
/**
* Converts a Node.js Buffer to an ArrayBuffer.
* https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer
* @param buffer The Buffer input to covert.
* @return The ArrayBuffer representation of the input.
*/
function toArrayBuffer(buffer) {
return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
}
/**
* Converts an ArrayBuffer to a Node.js Buffer.
* @param arrayBuffer The ArrayBuffer input to covert.
* @return The Buffer representation of the input.
*/
function toBuffer(arrayBuffer) {
return Buffer.from(arrayBuffer);
}
//# sourceMappingURL=crypto.js.map

23
node_modules/google-auth-library/build/src/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import { GoogleAuth } from './auth/googleauth';
export { AuthClient } from './auth/authclient';
export { Compute, ComputeOptions } from './auth/computeclient';
export { CredentialBody, CredentialRequest, Credentials, JWTInput, } from './auth/credentials';
export { GCPEnv } from './auth/envDetect';
export { GoogleAuthOptions, ProjectIdCallback } from './auth/googleauth';
export { IAMAuth, RequestMetadata } from './auth/iam';
export { IdTokenClient, IdTokenProvider } from './auth/idtokenclient';
export { Claims, JWTAccess } from './auth/jwtaccess';
export { JWT, JWTOptions } from './auth/jwtclient';
export { Impersonated, ImpersonatedOptions } from './auth/impersonated';
export { Certificates, CodeChallengeMethod, CodeVerifierResults, GenerateAuthUrlOpts, GetTokenOptions, OAuth2Client, OAuth2ClientOptions, RefreshOptions, TokenInfo, VerifyIdTokenOptions, } from './auth/oauth2client';
export { LoginTicket, TokenPayload } from './auth/loginticket';
export { UserRefreshClient, UserRefreshClientOptions, } from './auth/refreshclient';
export { AwsClient, AwsClientOptions } from './auth/awsclient';
export { IdentityPoolClient, IdentityPoolClientOptions, } from './auth/identitypoolclient';
export { ExternalAccountClient, ExternalAccountClientOptions, } from './auth/externalclient';
export { BaseExternalAccountClient, BaseExternalAccountClientOptions, } from './auth/baseexternalclient';
export { CredentialAccessBoundary, DownscopedClient, } from './auth/downscopedclient';
export { PluggableAuthClient, PluggableAuthClientOptions, } from './auth/pluggable-auth-client';
export { DefaultTransporter } from './transporters';
declare const auth: GoogleAuth<import("./auth/googleauth").JSONClient>;
export { auth, GoogleAuth };

View File

@@ -0,0 +1,11 @@
export declare enum WarningTypes {
WARNING = "Warning",
DEPRECATION = "DeprecationWarning"
}
export declare function warn(warning: Warning): void;
export interface Warning {
code: string;
type: WarningTypes;
message: string;
warned?: boolean;
}

View File

@@ -0,0 +1 @@
export declare function validate(options: any): void;

View File

@@ -0,0 +1,36 @@
import { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios';
export interface Transporter {
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
request<T>(opts: GaxiosOptions, callback?: BodyResponseCallback<T>): void;
request<T>(opts: GaxiosOptions, callback?: BodyResponseCallback<T>): GaxiosPromise | void;
}
export interface BodyResponseCallback<T> {
(err: Error | null, res?: GaxiosResponse<T> | null): void;
}
export interface RequestError extends GaxiosError {
errors: Error[];
}
export declare class DefaultTransporter {
/**
* Default user agent.
*/
static readonly USER_AGENT: string;
/**
* Configures request options before making a request.
* @param opts GaxiosOptions options.
* @return Configured options.
*/
configure(opts?: GaxiosOptions): GaxiosOptions;
/**
* Makes a request using Gaxios with given options.
* @param opts GaxiosOptions options.
* @param callback optional callback that contains GaxiosResponse object.
* @return GaxiosPromise, assuming no callback is passed.
*/
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
request<T>(opts: GaxiosOptions, callback?: BodyResponseCallback<T>): void;
/**
* Changes the error to include details from the body.
*/
private processError;
}

96
node_modules/google-auth-library/package.json generated vendored Normal file
View File

@@ -0,0 +1,96 @@
{
"name": "google-auth-library",
"version": "8.7.0",
"author": "Google Inc.",
"description": "Google APIs Authentication Client Library for Node.js",
"engines": {
"node": ">=12"
},
"main": "./build/src/index.js",
"types": "./build/src/index.d.ts",
"repository": "googleapis/google-auth-library-nodejs.git",
"keywords": [
"google",
"api",
"google apis",
"client",
"client library"
],
"dependencies": {
"arrify": "^2.0.0",
"base64-js": "^1.3.0",
"ecdsa-sig-formatter": "^1.0.11",
"fast-text-encoding": "^1.0.0",
"gaxios": "^5.0.0",
"gcp-metadata": "^5.0.0",
"gtoken": "^6.1.0",
"jws": "^4.0.0",
"lru-cache": "^6.0.0"
},
"devDependencies": {
"@compodoc/compodoc": "^1.1.7",
"@types/base64-js": "^1.2.5",
"@types/chai": "^4.1.7",
"@types/jws": "^3.1.0",
"@types/lru-cache": "^5.0.0",
"@types/mocha": "^9.0.0",
"@types/mv": "^2.1.0",
"@types/ncp": "^2.0.1",
"@types/node": "^16.0.0",
"@types/sinon": "^10.0.0",
"@types/tmp": "^0.2.0",
"assert-rejects": "^1.0.0",
"c8": "^7.0.0",
"chai": "^4.2.0",
"codecov": "^3.0.2",
"execa": "^5.0.0",
"gts": "^3.1.0",
"is-docker": "^2.0.0",
"karma": "^6.0.0",
"karma-chrome-launcher": "^3.0.0",
"karma-coverage": "^2.0.0",
"karma-firefox-launcher": "^2.0.0",
"karma-mocha": "^2.0.0",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^5.0.0",
"keypair": "^1.0.4",
"linkinator": "^4.0.0",
"mocha": "^9.2.2",
"mv": "^2.1.1",
"ncp": "^2.0.0",
"nock": "^13.0.0",
"null-loader": "^4.0.0",
"puppeteer": "^18.0.0",
"sinon": "^14.0.0",
"tmp": "^0.2.0",
"ts-loader": "^8.0.0",
"typescript": "^4.6.3",
"webpack": "^5.21.2",
"webpack-cli": "^4.0.0"
},
"files": [
"build/src",
"!build/src/**/*.map"
],
"scripts": {
"test": "c8 mocha build/test",
"clean": "gts clean",
"prepare": "npm run compile",
"lint": "gts check",
"compile": "tsc -p .",
"fix": "gts fix",
"pretest": "npm run compile",
"docs": "compodoc src/",
"samples-setup": "cd samples/ && npm link ../ && npm run setup && cd ../",
"samples-test": "cd samples/ && npm link ../ && npm test && cd ../",
"system-test": "mocha build/system-test --timeout 60000",
"presystem-test": "npm run compile",
"webpack": "webpack",
"browser-test": "karma start",
"docs-test": "linkinator docs",
"predocs-test": "npm run docs",
"prelint": "cd samples; npm link ../; npm install",
"precompile": "gts clean"
},
"license": "Apache-2.0"
}