forked from googleapis/google-cloud-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomputeclient.ts
More file actions
209 lines (192 loc) · 6.92 KB
/
Copy pathcomputeclient.ts
File metadata and controls
209 lines (192 loc) · 6.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// Copyright 2013 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 {GaxiosError} from 'gaxios';
import * as gcpMetadata from 'gcp-metadata';
import {AuthClient} from './authclient';
import {CredentialRequest, Credentials} from './credentials';
import {
GetTokenResponse,
OAuth2Client,
OAuth2ClientOptions,
} from './oauth2client';
import {SERVICE_ACCOUNT_LOOKUP_ENDPOINT} from './regionalaccessboundary';
export interface ComputeOptions extends OAuth2ClientOptions {
/**
* 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 class Compute extends OAuth2Client {
private static readonly EMAIL_REGEX = /^[^@]+@[^@]+\.[^@]+$/;
readonly serviceAccountEmail: string;
scopes: string[];
private isNonEmailAccount = false;
/**
* Google Compute Engine service account credentials.
*
* Retrieve access token from the metadata server.
* See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications
*/
constructor(options: ComputeOptions = {}) {
super(options);
// Start with an expired refresh token, which will automatically be
// refreshed before the first API call is made.
this.credentials = {expiry_date: 1, refresh_token: 'compute-placeholder'};
this.serviceAccountEmail = options.serviceAccountEmail || 'default';
this.scopes = Array.isArray(options.scopes)
? options.scopes
: options.scopes
? [options.scopes]
: [];
}
/**
* Refreshes the access token.
* @param refreshToken Unused parameter
*/
protected async refreshTokenNoCache(): Promise<GetTokenResponse> {
const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;
let data: CredentialRequest;
try {
const instanceOptions: gcpMetadata.Options = {
property: tokenPath,
};
if (this.scopes.length > 0) {
instanceOptions.params = {
scopes: this.scopes.join(','),
};
}
data = await gcpMetadata.instance(instanceOptions);
} catch (e) {
if (e instanceof GaxiosError) {
e.message = `Could not refresh access token: ${e.message}`;
this.wrapError(e);
}
throw e;
}
const tokens = data as Credentials;
if (data && data.expires_in) {
tokens.expiry_date = new Date().getTime() + data.expires_in * 1000;
delete (tokens as CredentialRequest).expires_in;
}
this.emit('tokens', tokens);
return {tokens, res: null};
}
/**
* Fetches an ID token.
* @param targetAudience the audience for the fetched ID token.
*/
async fetchIdToken(targetAudience: string): Promise<string> {
const idTokenPath =
`service-accounts/${this.serviceAccountEmail}/identity` +
`?format=full&audience=${targetAudience}`;
let idToken: string;
try {
const instanceOptions: gcpMetadata.Options = {
property: idTokenPath,
};
idToken = await gcpMetadata.instance(instanceOptions);
} catch (e) {
if (e instanceof Error) {
e.message = `Could not fetch ID token: ${e.message}`;
}
throw e;
}
return idToken;
}
protected wrapError(e: GaxiosError) {
const res = e.response;
if (res && res.status) {
e.status = res.status;
if (res.status === 403) {
e.message =
'A Forbidden error was returned while attempting to retrieve an access ' +
'token for the Compute Engine built-in service account. This may be because the Compute ' +
'Engine instance does not have the correct permission scopes specified: ' +
e.message;
} else if (res.status === 404) {
e.message =
'A Not Found error was returned while attempting to retrieve an access' +
'token for the Compute Engine built-in service account. This may be because the Compute ' +
'Engine instance does not have any permission scopes specified: ' +
e.message;
}
}
}
/**
* Returns the regional access boundary lookup URL for the GCE instance.
* This implementation resolves the service account email of the GCE
* instance to construct the lookup endpoint. If the resolved email is invalid
* or not found, it returns `null` to skip the regional access boundary check.
*
* @return The regional access boundary URL string, or null if regional access
* boundary checks should be skipped.
* @internal
*/
public async getRegionalAccessBoundaryUrl(): Promise<string | null> {
const email = await this.resolveServiceAccountEmail();
if (email === null) {
// This credential corresponds to a non-email account; skip RAB lookup.
return null;
}
const regionalAccessBoundaryUrl = SERVICE_ACCOUNT_LOOKUP_ENDPOINT.replace(
'{service_account_email}',
encodeURIComponent(email),
);
return regionalAccessBoundaryUrl;
}
/**
* Resolves the service account email. If the email is set to 'default',
* it fetches the email from the GCE metadata server.
* @returns A promise that resolves with the service account email,
* or null if MDS returns an invalid email format
*/
private async resolveServiceAccountEmail(): Promise<string | null> {
if (this.isNonEmailAccount) {
return null;
}
if (this.serviceAccountEmail !== 'default') {
// If a specific email is provided, return it directly.
return this.serviceAccountEmail;
}
// Otherwise, fetch the default email from the metadata server.
try {
const email = await gcpMetadata.instance<string>(
'service-accounts/default/email',
);
// If the metadata server returned an non-email format, log a warning only once.
if (!email || !Compute.EMAIL_REGEX.test(email)) {
AuthClient.log.info(
`RegionalAccessBoundary: Service account email "${email}" is not in a valid email format. Skipping regional access boundary lookup.`,
);
this.isNonEmailAccount = true;
return null;
}
return email;
} catch (e) {
throw new Error(
'RegionalAccessBoundary: Failed to retrieve default service account email from metadata server.',
{
cause: e,
},
);
}
}
}