-
Notifications
You must be signed in to change notification settings - Fork 388
/
Copy pathdefaultawssecuritycredentialssupplier.ts
275 lines (261 loc) Β· 10 KB
/
defaultawssecuritycredentialssupplier.ts
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// Copyright 2024 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 {ExternalAccountSupplierContext} from './baseexternalclient';
import {Gaxios, GaxiosOptions} from 'gaxios';
import {AwsSecurityCredentialsSupplier} from './awsclient';
import {AwsSecurityCredentials} from './awsrequestsigner';
import {AuthClient} from './authclient';
/**
* Interface defining the AWS security-credentials endpoint response.
*/
interface AwsSecurityCredentialsResponse {
Code: string;
LastUpdated: string;
Type: string;
AccessKeyId: string;
SecretAccessKey: string;
Token: string;
Expiration: string;
}
/**
* Interface defining the options used to build a {@link DefaultAwsSecurityCredentialsSupplier}.
*/
export interface DefaultAwsSecurityCredentialsSupplierOptions {
/**
* The URL to call to retrieve the active AWS region.
**/
regionUrl?: string;
/**
* The URL to call to retrieve AWS security credentials.
**/
securityCredentialsUrl?: string;
/**
** The URL to call to retrieve the IMDSV2 session token.
**/
imdsV2SessionTokenUrl?: string;
/**
* Additional Gaxios options to use when making requests to the AWS metadata
* endpoints.
*/
additionalGaxiosOptions?: GaxiosOptions;
}
/**
* Internal AWS security credentials supplier implementation used by {@link AwsClient}
* when a credential source is provided instead of a user defined supplier.
* 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.
*/
export class DefaultAwsSecurityCredentialsSupplier
implements AwsSecurityCredentialsSupplier
{
private readonly regionUrl?: string;
private readonly securityCredentialsUrl?: string;
private readonly imdsV2SessionTokenUrl?: string;
private readonly additionalGaxiosOptions?: GaxiosOptions;
/**
* Instantiates a new DefaultAwsSecurityCredentialsSupplier using information
* from the credential_source stored in the ADC file.
* @param opts The default aws security credentials supplier options object to
* build the supplier with.
*/
constructor(opts: DefaultAwsSecurityCredentialsSupplierOptions) {
this.regionUrl = opts.regionUrl;
this.securityCredentialsUrl = opts.securityCredentialsUrl;
this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl;
this.additionalGaxiosOptions = opts.additionalGaxiosOptions;
}
/**
* Returns the active AWS region. This first checks to see if the region
* is available as an environment variable. If it is not, then the supplier
* will call the region URL.
* @param context {@link ExternalAccountSupplierContext} from the calling
* {@link AwsClient}, contains the requested audience and subject token type
* for the external account identity.
* @return A promise that resolves with the AWS region string.
*/
async getAwsRegion(context: ExternalAccountSupplierContext): Promise<string> {
// Priority order for region determination:
// AWS_REGION > AWS_DEFAULT_REGION > metadata server.
if (this.#regionFromEnv) {
return this.#regionFromEnv;
}
const metadataHeaders = new Headers();
if (!this.#regionFromEnv && this.imdsV2SessionTokenUrl) {
metadataHeaders.set(
'x-aws-ec2-metadata-token',
await this.#getImdsV2SessionToken(context.transporter),
);
}
if (!this.regionUrl) {
throw new RangeError(
'Unable to determine AWS region due to missing ' +
'"options.credential_source.region_url"',
);
}
const opts: GaxiosOptions = {
...this.additionalGaxiosOptions,
url: this.regionUrl,
method: 'GET',
headers: metadataHeaders,
};
AuthClient.setMethodName(opts, 'getAwsRegion');
const response = await context.transporter.request<string>(opts);
// Remove last character. For example, if us-east-2b is returned,
// the region would be us-east-2.
return response.data.substr(0, response.data.length - 1);
}
/**
* Returns AWS security credentials. This first checks to see if the credentials
* is available as environment variables. If it is not, then the supplier
* will call the security credentials URL.
* @param context {@link ExternalAccountSupplierContext} from the calling
* {@link AwsClient}, contains the requested audience and subject token type
* for the external account identity.
* @return A promise that resolves with the AWS security credentials.
*/
async getAwsSecurityCredentials(
context: ExternalAccountSupplierContext,
): Promise<AwsSecurityCredentials> {
// Check environment variables for permanent credentials first.
// https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html
if (this.#securityCredentialsFromEnv) {
return this.#securityCredentialsFromEnv;
}
const metadataHeaders = new Headers();
if (this.imdsV2SessionTokenUrl) {
metadataHeaders.set(
'x-aws-ec2-metadata-token',
await this.#getImdsV2SessionToken(context.transporter),
);
}
// Since the role on a VM can change, we don't need to cache it.
const roleName = await this.#getAwsRoleName(
metadataHeaders,
context.transporter,
);
// Temporary credentials typically last for several hours.
// Expiration is returned in response.
// Consider future optimization of this logic to cache AWS tokens
// until their natural expiration.
const awsCreds = await this.#retrieveAwsSecurityCredentials(
roleName,
metadataHeaders,
context.transporter,
);
return {
accessKeyId: awsCreds.AccessKeyId,
secretAccessKey: awsCreds.SecretAccessKey,
token: awsCreds.Token,
};
}
/**
* @param transporter The transporter to use for requests.
* @return A promise that resolves with the IMDSv2 Session Token.
*/
async #getImdsV2SessionToken(transporter: Gaxios): Promise<string> {
const opts: GaxiosOptions = {
...this.additionalGaxiosOptions,
url: this.imdsV2SessionTokenUrl,
method: 'PUT',
headers: {'x-aws-ec2-metadata-token-ttl-seconds': '300'},
};
AuthClient.setMethodName(opts, '#getImdsV2SessionToken');
const response = await transporter.request<string>(opts);
return response.data;
}
/**
* @param headers The headers to be used in the metadata request.
* @param transporter The transporter to use for requests.
* @return A promise that resolves with the assigned role to the current
* AWS VM. This is needed for calling the security-credentials endpoint.
*/
async #getAwsRoleName(
headers: Headers,
transporter: Gaxios,
): Promise<string> {
if (!this.securityCredentialsUrl) {
throw new Error(
'Unable to determine AWS role name due to missing ' +
'"options.credential_source.url"',
);
}
const opts: GaxiosOptions = {
...this.additionalGaxiosOptions,
url: this.securityCredentialsUrl,
method: 'GET',
headers: headers,
};
AuthClient.setMethodName(opts, '#getAwsRoleName');
const response = await transporter.request<string>(opts);
return response.data;
}
/**
* 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.
* @param transporter The transporter to use for requests.
* @return A promise that resolves with the temporary AWS credentials
* needed for creating the GetCallerIdentity signed request.
*/
async #retrieveAwsSecurityCredentials(
roleName: string,
headers: Headers,
transporter: Gaxios,
): Promise<AwsSecurityCredentialsResponse> {
const opts = {
...this.additionalGaxiosOptions,
url: `${this.securityCredentialsUrl}/${roleName}`,
headers: headers,
} as GaxiosOptions;
AuthClient.setMethodName(opts, '#retrieveAwsSecurityCredentials');
const response =
await transporter.request<AwsSecurityCredentialsResponse>(opts);
return response.data;
}
get #regionFromEnv(): string | null {
// The AWS region can be provided through AWS_REGION or AWS_DEFAULT_REGION.
// Only one is required.
return (
process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION'] || null
);
}
get #securityCredentialsFromEnv(): AwsSecurityCredentials | null {
// Both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required.
if (
process.env['AWS_ACCESS_KEY_ID'] &&
process.env['AWS_SECRET_ACCESS_KEY']
) {
return {
accessKeyId: process.env['AWS_ACCESS_KEY_ID'],
secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'],
token: process.env['AWS_SESSION_TOKEN'],
};
}
return null;
}
}