UNPKG

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