UNPKG

15.9 kBTypeScriptView Raw
1import { GaxiosOptions, GaxiosResponse } from 'gaxios';
2import * as stream from 'stream';
3import { DefaultTransporter, Transporter } from '../transporters';
4import { CredentialBody, ImpersonatedJWTInput, JWTInput } from './credentials';
5import { IdTokenClient } from './idtokenclient';
6import { GCPEnv } from './envDetect';
7import { JWT, JWTOptions } from './jwtclient';
8import { Headers, OAuth2ClientOptions } from './oauth2client';
9import { UserRefreshClient, UserRefreshClientOptions } from './refreshclient';
10import { Impersonated, ImpersonatedOptions } from './impersonated';
11import { ExternalAccountClientOptions } from './externalclient';
12import { BaseExternalAccountClient } from './baseexternalclient';
13import { AuthClient, AuthClientOptions } from './authclient';
14import { ExternalAccountAuthorizedUserClient } from './externalAccountAuthorizedUserClient';
15import { AnyAuthClient } from '..';
16/**
17 * Defines all types of explicit clients that are determined via ADC JSON
18 * config file.
19 */
20export type JSONClient = JWT | UserRefreshClient | BaseExternalAccountClient | ExternalAccountAuthorizedUserClient | Impersonated;
21export interface ProjectIdCallback {
22 (err?: Error | null, projectId?: string | null): void;
23}
24export interface CredentialCallback {
25 (err: Error | null, result?: JSONClient): void;
26}
27export interface ADCCallback {
28 (err: Error | null, credential?: AuthClient, projectId?: string | null): void;
29}
30export interface ADCResponse {
31 credential: AuthClient;
32 projectId: string | null;
33}
34export interface GoogleAuthOptions<T extends AuthClient = JSONClient> {
35 /**
36 * An API key to use, optional. Cannot be used with {@link GoogleAuthOptions.credentials `credentials`}.
37 */
38 apiKey?: string;
39 /**
40 * An `AuthClient` to use
41 */
42 authClient?: T;
43 /**
44 * Path to a .json, .pem, or .p12 key file
45 */
46 keyFilename?: string;
47 /**
48 * Path to a .json, .pem, or .p12 key file
49 */
50 keyFile?: string;
51 /**
52 * Object containing client_email and private_key properties, or the
53 * external account client options.
54 * Cannot be used with {@link GoogleAuthOptions.apiKey `apiKey`}.
55 *
56 * @remarks
57 *
58 * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.
59 */
60 credentials?: JWTInput | ExternalAccountClientOptions;
61 /**
62 * Options object passed to the constructor of the client
63 */
64 clientOptions?: JWTOptions | OAuth2ClientOptions | UserRefreshClientOptions | ImpersonatedOptions;
65 /**
66 * Required scopes for the desired API request
67 */
68 scopes?: string | string[];
69 /**
70 * Your project ID.
71 */
72 projectId?: string;
73 /**
74 * The default service domain for a given Cloud universe.
75 *
76 * This is an ergonomic equivalent to {@link clientOptions}'s `universeDomain`
77 * property and will be set for all generated {@link AuthClient}s.
78 */
79 universeDomain?: string;
80}
81export declare const CLOUD_SDK_CLIENT_ID = "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com";
82export declare const GoogleAuthExceptionMessages: {
83 readonly API_KEY_WITH_CREDENTIALS: "API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.";
84 readonly NO_PROJECT_ID_FOUND: string;
85 readonly NO_CREDENTIALS_FOUND: string;
86 readonly NO_ADC_FOUND: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.";
87 readonly NO_UNIVERSE_DOMAIN_FOUND: string;
88};
89export declare class GoogleAuth<T extends AuthClient = JSONClient> {
90 #private;
91 transporter?: Transporter;
92 /**
93 * Caches a value indicating whether the auth layer is running on Google
94 * Compute Engine.
95 * @private
96 */
97 private checkIsGCE?;
98 useJWTAccessWithScope?: boolean;
99 defaultServicePath?: string;
100 get isGCE(): boolean | undefined;
101 private _findProjectIdPromise?;
102 private _cachedProjectId?;
103 jsonContent: JWTInput | ExternalAccountClientOptions | null;
104 apiKey: string | null;
105 cachedCredential: AnyAuthClient | T | null;
106 /**
107 * Scopes populated by the client library by default. We differentiate between
108 * these and user defined scopes when deciding whether to use a self-signed JWT.
109 */
110 defaultScopes?: string | string[];
111 private keyFilename?;
112 private scopes?;
113 private clientOptions;
114 /**
115 * Export DefaultTransporter as a static property of the class.
116 */
117 static DefaultTransporter: typeof DefaultTransporter;
118 /**
119 * Configuration is resolved in the following order of precedence:
120 * - {@link GoogleAuthOptions.credentials `credentials`}
121 * - {@link GoogleAuthOptions.keyFilename `keyFilename`}
122 * - {@link GoogleAuthOptions.keyFile `keyFile`}
123 *
124 * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the
125 * {@link AuthClient `AuthClient`s}.
126 *
127 * @param opts
128 */
129 constructor(opts?: GoogleAuthOptions<T>);
130 setGapicJWTValues(client: JWT): void;
131 /**
132 * Obtains the default project ID for the application.
133 *
134 * Retrieves in the following order of precedence:
135 * - The `projectId` provided in this object's construction
136 * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable
137 * - GOOGLE_APPLICATION_CREDENTIALS JSON file
138 * - Cloud SDK: `gcloud config config-helper --format json`
139 * - GCE project ID from metadata server
140 */
141 getProjectId(): Promise<string>;
142 getProjectId(callback: ProjectIdCallback): void;
143 /**
144 * A temporary method for internal `getProjectId` usages where `null` is
145 * acceptable. In a future major release, `getProjectId` should return `null`
146 * (as the `Promise<string | null>` base signature describes) and this private
147 * method should be removed.
148 *
149 * @returns Promise that resolves with project id (or `null`)
150 */
151 private getProjectIdOptional;
152 /**
153 * A private method for finding and caching a projectId.
154 *
155 * Supports environments in order of precedence:
156 * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable
157 * - GOOGLE_APPLICATION_CREDENTIALS JSON file
158 * - Cloud SDK: `gcloud config config-helper --format json`
159 * - GCE project ID from metadata server
160 *
161 * @returns projectId
162 */
163 private findAndCacheProjectId;
164 private getProjectIdAsync;
165 /**
166 * Retrieves a universe domain from the metadata server via
167 * {@link gcpMetadata.universe}.
168 *
169 * @returns a universe domain
170 */
171 getUniverseDomainFromMetadataServer(): Promise<string>;
172 /**
173 * Retrieves, caches, and returns the universe domain in the following order
174 * of precedence:
175 * - The universe domain in {@link GoogleAuth.clientOptions}
176 * - An existing or ADC {@link AuthClient}'s universe domain
177 * - {@link gcpMetadata.universe}, if {@link Compute} client
178 *
179 * @returns The universe domain
180 */
181 getUniverseDomain(): Promise<string>;
182 /**
183 * @returns Any scopes (user-specified or default scopes specified by the
184 * client library) that need to be set on the current Auth client.
185 */
186 private getAnyScopes;
187 /**
188 * Obtains the default service-level credentials for the application.
189 * @param callback Optional callback.
190 * @returns Promise that resolves with the ADCResponse (if no callback was
191 * passed).
192 */
193 getApplicationDefault(): Promise<ADCResponse>;
194 getApplicationDefault(callback: ADCCallback): void;
195 getApplicationDefault(options: AuthClientOptions): Promise<ADCResponse>;
196 getApplicationDefault(options: AuthClientOptions, callback: ADCCallback): void;
197 private getApplicationDefaultAsync;
198 /**
199 * Determines whether the auth layer is running on Google Compute Engine.
200 * Checks for GCP Residency, then fallback to checking if metadata server
201 * is available.
202 *
203 * @returns A promise that resolves with the boolean.
204 * @api private
205 */
206 _checkIsGCE(): Promise<boolean>;
207 /**
208 * Attempts to load default credentials from the environment variable path..
209 * @returns Promise that resolves with the OAuth2Client or null.
210 * @api private
211 */
212 _tryGetApplicationCredentialsFromEnvironmentVariable(options?: AuthClientOptions): Promise<JSONClient | null>;
213 /**
214 * Attempts to load default credentials from a well-known file location
215 * @return Promise that resolves with the OAuth2Client or null.
216 * @api private
217 */
218 _tryGetApplicationCredentialsFromWellKnownFile(options?: AuthClientOptions): Promise<JSONClient | null>;
219 /**
220 * Attempts to load default credentials from a file at the given path..
221 * @param filePath The path to the file to read.
222 * @returns Promise that resolves with the OAuth2Client
223 * @api private
224 */
225 _getApplicationCredentialsFromFilePath(filePath: string, options?: AuthClientOptions): Promise<JSONClient>;
226 /**
227 * Create a credentials instance using a given impersonated input options.
228 * @param json The impersonated input object.
229 * @returns JWT or UserRefresh Client with data
230 */
231 fromImpersonatedJSON(json: ImpersonatedJWTInput): Impersonated;
232 /**
233 * Create a credentials instance using the given input options.
234 * This client is not cached.
235 *
236 * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.
237 *
238 * @param json The input object.
239 * @param options The JWT or UserRefresh options for the client
240 * @returns JWT or UserRefresh Client with data
241 */
242 fromJSON(json: JWTInput | ImpersonatedJWTInput, options?: AuthClientOptions): JSONClient;
243 /**
244 * Return a JWT or UserRefreshClient from JavaScript object, caching both the
245 * object used to instantiate and the client.
246 * @param json The input object.
247 * @param options The JWT or UserRefresh options for the client
248 * @returns JWT or UserRefresh Client with data
249 */
250 private _cacheClientFromJSON;
251 /**
252 * Create a credentials instance using the given input stream.
253 * @param inputStream The input stream.
254 * @param callback Optional callback.
255 */
256 fromStream(inputStream: stream.Readable): Promise<JSONClient>;
257 fromStream(inputStream: stream.Readable, callback: CredentialCallback): void;
258 fromStream(inputStream: stream.Readable, options: AuthClientOptions): Promise<JSONClient>;
259 fromStream(inputStream: stream.Readable, options: AuthClientOptions, callback: CredentialCallback): void;
260 private fromStreamAsync;
261 /**
262 * Create a credentials instance using the given API key string.
263 * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}.
264 *
265 * @param apiKey The API key string
266 * @param options An optional options object.
267 * @returns A JWT loaded from the key
268 */
269 fromAPIKey(apiKey: string, options?: AuthClientOptions): JWT;
270 /**
271 * Determines whether the current operating system is Windows.
272 * @api private
273 */
274 private _isWindows;
275 /**
276 * Run the Google Cloud SDK command that prints the default project ID
277 */
278 private getDefaultServiceProjectId;
279 /**
280 * Loads the project id from environment variables.
281 * @api private
282 */
283 private getProductionProjectId;
284 /**
285 * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.
286 * @api private
287 */
288 private getFileProjectId;
289 /**
290 * Gets the project ID from external account client if available.
291 */
292 private getExternalAccountClientProjectId;
293 /**
294 * Gets the Compute Engine project ID if it can be inferred.
295 */
296 private getGCEProjectId;
297 /**
298 * The callback function handles a credential object that contains the
299 * client_email and private_key (if exists).
300 * getCredentials first checks if the client is using an external account and
301 * uses the service account email in place of client_email.
302 * If that doesn't exist, it checks for these values from the user JSON.
303 * If the user JSON doesn't exist, and the environment is on GCE, it gets the
304 * client_email from the cloud metadata server.
305 * @param callback Callback that handles the credential object that contains
306 * a client_email and optional private key, or the error.
307 * returned
308 */
309 getCredentials(): Promise<CredentialBody>;
310 getCredentials(callback: (err: Error | null, credentials?: CredentialBody) => void): void;
311 private getCredentialsAsync;
312 /**
313 * Automatically obtain an {@link AuthClient `AuthClient`} based on the
314 * provided configuration. If no options were passed, use Application
315 * Default Credentials.
316 */
317 getClient(): Promise<AnyAuthClient | T>;
318 /**
319 * Creates a client which will fetch an ID token for authorization.
320 * @param targetAudience the audience for the fetched ID token.
321 * @returns IdTokenClient for making HTTP calls authenticated with ID tokens.
322 */
323 getIdTokenClient(targetAudience: string): Promise<IdTokenClient>;
324 /**
325 * Automatically obtain application default credentials, and return
326 * an access token for making requests.
327 */
328 getAccessToken(): Promise<string | null | undefined>;
329 /**
330 * Obtain the HTTP headers that will provide authorization for a given
331 * request.
332 */
333 getRequestHeaders(url?: string): Promise<Headers>;
334 /**
335 * Obtain credentials for a request, then attach the appropriate headers to
336 * the request options.
337 * @param opts Axios or Request options on which to attach the headers
338 */
339 authorizeRequest(opts: {
340 url?: string;
341 uri?: string;
342 headers?: Headers;
343 }): Promise<{
344 url?: string;
345 uri?: string;
346 headers?: Headers;
347 }>;
348 /**
349 * Automatically obtain application default credentials, and make an
350 * HTTP request using the given options.
351 * @param opts Axios request options for the HTTP request.
352 */
353 request<T = any>(opts: GaxiosOptions): Promise<GaxiosResponse<T>>;
354 /**
355 * Determine the compute environment in which the code is running.
356 */
357 getEnv(): Promise<GCPEnv>;
358 /**
359 * Sign the given data with the current private key, or go out
360 * to the IAM API to sign it.
361 * @param data The data to be signed.
362 * @param endpoint A custom endpoint to use.
363 *
364 * @example
365 * ```
366 * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/');
367 * ```
368 */
369 sign(data: string, endpoint?: string): Promise<string>;
370 private signBlob;
371}
372export interface SignBlobResponse {
373 keyId: string;
374 signedBlob: string;
375}