-
Notifications
You must be signed in to change notification settings - Fork 798
/
ProcessCredentialsProvider.java
371 lines (323 loc) · 15.2 KB
/
ProcessCredentialsProvider.java
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
package software.amazon.awssdk.auth.credentials;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.utils.DateUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Platform;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
import software.amazon.awssdk.utils.cache.CachedSupplier;
import software.amazon.awssdk.utils.cache.NonBlocking;
import software.amazon.awssdk.utils.cache.RefreshResult;
/**
* A credentials provider that can load credentials from an external process. This is used to support the credential_process
* setting in the profile credentials file. See
* <a href="https://docs.aws.amazon.com/cli/latest/topic/config-vars.html#sourcing-credentials-from-external-processes">sourcing credentials
* from external processes</a> for more information.
*
* <p>
* This class can be initialized using {@link #builder()}.
*
* <p>
* Available settings:
* <ul>
* <li>Command - The command that should be executed to retrieve credentials.</li>
* <li>CredentialRefreshThreshold - The amount of time between when the credentials expire and when the credentials should
* start to be refreshed. This allows the credentials to be refreshed *before* they are reported to expire. Default: 15
* seconds.</li>
* <li>ProcessOutputLimit - The maximum amount of data that can be returned by the external process before an exception is
* raised. Default: 64000 bytes (64KB).</li>
* </ul>
*/
@SdkPublicApi
public final class ProcessCredentialsProvider
implements AwsCredentialsProvider,
SdkAutoCloseable,
ToCopyableBuilder<ProcessCredentialsProvider.Builder, ProcessCredentialsProvider> {
private static final String PROVIDER_NAME = "ProcessCredentialsProvider";
private static final JsonNodeParser PARSER = JsonNodeParser.builder()
.removeErrorLocations(true)
.build();
private final List<String> executableCommand;
private final Duration credentialRefreshThreshold;
private final long processOutputLimit;
private final String staticAccountId;
private final CachedSupplier<AwsCredentials> processCredentialCache;
private final String commandFromBuilder;
private final List<String> commandAsListOfStringsFromBuilder;
private final Boolean asyncCredentialUpdateEnabled;
/**
* @see #builder()
*/
private ProcessCredentialsProvider(Builder builder) {
this.executableCommand = executableCommand(builder);
this.processOutputLimit = Validate.isPositive(builder.processOutputLimit, "processOutputLimit");
this.credentialRefreshThreshold = Validate.isPositive(builder.credentialRefreshThreshold, "expirationBuffer");
this.commandFromBuilder = builder.command;
this.commandAsListOfStringsFromBuilder = builder.commandAsListOfStrings;
this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
this.staticAccountId = builder.staticAccountId;
CachedSupplier.Builder<AwsCredentials> cacheBuilder = CachedSupplier.builder(this::refreshCredentials)
.cachedValueName(toString());
if (builder.asyncCredentialUpdateEnabled) {
cacheBuilder.prefetchStrategy(new NonBlocking("process-credentials-provider"));
}
this.processCredentialCache = cacheBuilder.build();
}
private List<String> executableCommand(Builder builder) {
if (builder.commandAsListOfStrings != null) {
return Collections.unmodifiableList(builder.commandAsListOfStrings);
} else {
List<String> cmd = new ArrayList<>();
if (Platform.isWindows()) {
cmd.add("cmd.exe");
cmd.add("/C");
} else {
cmd.add("sh");
cmd.add("-c");
}
String builderCommand = Validate.paramNotNull(builder.command, "command");
cmd.add(builderCommand);
return Collections.unmodifiableList(cmd);
}
}
/**
* Retrieve a new builder that can be used to create and configure a {@link ProcessCredentialsProvider}.
*/
public static Builder builder() {
return new Builder();
}
@Override
public AwsCredentials resolveCredentials() {
return processCredentialCache.get();
}
private RefreshResult<AwsCredentials> refreshCredentials() {
try {
String processOutput = executeCommand();
JsonNode credentialsJson = parseProcessOutput(processOutput);
AwsCredentials credentials = credentials(credentialsJson);
Instant credentialExpirationTime = credentialExpirationTime(credentialsJson);
return RefreshResult.builder(credentials)
.staleTime(credentialExpirationTime)
.prefetchTime(credentialExpirationTime.minusMillis(credentialRefreshThreshold.toMillis()))
.build();
} catch (InterruptedException e) {
throw new IllegalStateException("Process-based credential refreshing has been interrupted.", e);
} catch (Exception e) {
throw new IllegalStateException("Failed to refresh process-based credentials.", e);
}
}
/**
* Parse the output from the credentials process.
*/
private JsonNode parseProcessOutput(String processOutput) {
JsonNode credentialsJson = PARSER.parse(processOutput);
if (!credentialsJson.isObject()) {
throw new IllegalStateException("Process did not return a JSON object.");
}
JsonNode version = credentialsJson.field("Version").orElse(null);
if (version == null || !version.isNumber() || !version.asNumber().equals("1")) {
throw new IllegalStateException("Unsupported credential version: " + version);
}
return credentialsJson;
}
/**
* Parse the process output to retrieve the credentials.
*/
private AwsCredentials credentials(JsonNode credentialsJson) {
String accessKeyId = getText(credentialsJson, "AccessKeyId");
String secretAccessKey = getText(credentialsJson, "SecretAccessKey");
String sessionToken = getText(credentialsJson, "SessionToken");
String accountId = getText(credentialsJson, "AccountId");
Validate.notEmpty(accessKeyId, "AccessKeyId cannot be empty.");
Validate.notEmpty(secretAccessKey, "SecretAccessKey cannot be empty.");
String resolvedAccountId = accountId == null ? this.staticAccountId : accountId;
return sessionToken != null ?
AwsSessionCredentials.builder()
.accessKeyId(accessKeyId)
.secretAccessKey(secretAccessKey)
.sessionToken(sessionToken)
.expirationTime(credentialExpirationTime(credentialsJson))
.accountId(resolvedAccountId)
.providerName(PROVIDER_NAME)
.build() :
AwsBasicCredentials.builder()
.accessKeyId(accessKeyId)
.secretAccessKey(secretAccessKey)
.accountId(resolvedAccountId)
.providerName(PROVIDER_NAME)
.build();
}
/**
* Parse the process output to retrieve the expiration date and time.
*/
private Instant credentialExpirationTime(JsonNode credentialsJson) {
String expiration = getText(credentialsJson, "Expiration");
if (expiration != null) {
return DateUtils.parseIso8601Date(expiration);
} else {
return Instant.MAX;
}
}
/**
* Get a textual value from a json object.
*/
private String getText(JsonNode jsonObject, String nodeName) {
return jsonObject.field(nodeName).map(JsonNode::text).orElse(null);
}
/**
* Execute the external process to retrieve credentials.
*/
private String executeCommand() throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder(executableCommand);
ByteArrayOutputStream commandOutput = new ByteArrayOutputStream();
Process process = processBuilder.start();
try {
IoUtils.copy(process.getInputStream(), commandOutput, processOutputLimit);
process.waitFor();
if (process.exitValue() != 0) {
try (InputStream errorStream = process.getErrorStream()) {
String errorMessage = IoUtils.toUtf8String(errorStream);
throw new IllegalStateException(String.format("Command returned non-zero exit value (%s) with error message: "
+ "%s", process.exitValue(), errorMessage));
}
}
return new String(commandOutput.toByteArray(), StandardCharsets.UTF_8);
} finally {
process.destroy();
}
}
@Override
public void close() {
processCredentialCache.close();
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
/**
* Used to configure and create a {@link ProcessCredentialsProvider}. See {@link #builder()} creation.
*/
public static class Builder implements CopyableBuilder<Builder, ProcessCredentialsProvider> {
private Boolean asyncCredentialUpdateEnabled = false;
private String command;
private List<String> commandAsListOfStrings;
private Duration credentialRefreshThreshold = Duration.ofSeconds(15);
private long processOutputLimit = 64000;
private String staticAccountId;
/**
* @see #builder()
*/
private Builder() {
}
private Builder(ProcessCredentialsProvider provider) {
this.asyncCredentialUpdateEnabled = provider.asyncCredentialUpdateEnabled;
this.command = provider.commandFromBuilder;
this.commandAsListOfStrings = provider.commandAsListOfStringsFromBuilder;
this.credentialRefreshThreshold = provider.credentialRefreshThreshold;
this.processOutputLimit = provider.processOutputLimit;
this.staticAccountId = provider.staticAccountId;
}
/**
* Configure whether the provider should fetch credentials asynchronously in the background. If this is true,
* threads are less likely to block when credentials are loaded, but additional resources are used to maintain
* the provider.
*
* <p>By default, this is disabled.</p>
*/
@SuppressWarnings("unchecked")
public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
/**
* Configure the command that should be executed to retrieve credentials.
* See {@link ProcessBuilder} for details on how this command is used.
*
* @deprecated The recommended approach is to specify the command as a list of Strings, using {@link #command(List)}
* instead, which makes it easier to programmatically add parameters to commands without needing to escape those
* parameters to protect against command injection.
*/
@Deprecated
public Builder command(String command) {
this.command = command;
return this;
}
/**
* Configure the command that should be executed to retrieve credentials, as a list of strings.
* See {@link ProcessBuilder} for details on how this command is used.
*/
public Builder command(List<String> commandAsListOfStrings) {
this.commandAsListOfStrings = commandAsListOfStrings;
return this;
}
/**
* Configure the amount of time between when the credentials expire and when the credentials should start to be
* refreshed. This allows the credentials to be refreshed *before* they are reported to expire.
*
* <p>Default: 15 seconds.</p>
*/
public Builder credentialRefreshThreshold(Duration credentialRefreshThreshold) {
this.credentialRefreshThreshold = credentialRefreshThreshold;
return this;
}
/**
* Configure the maximum amount of data that can be returned by the external process before an exception is
* raised.
*
* <p>Default: 64000 bytes (64KB).</p>
*/
public Builder processOutputLimit(long outputByteLimit) {
this.processOutputLimit = outputByteLimit;
return this;
}
/**
* Configure a static account id for this credentials provider. Account id for ProcessCredentialsProvider is only
* relevant in a context where a service constructs endpoint URL containing an account id.
* This option should ONLY be used if the provider should return credentials with account id, and the process does not
* output account id. If a static account ID is configured, and the process also returns an account
* id, the process output value overrides the static value. If used, the static account id MUST match the credentials
* returned by the process.
*/
public Builder staticAccountId(String staticAccountId) {
this.staticAccountId = staticAccountId;
return this;
}
public ProcessCredentialsProvider build() {
return new ProcessCredentialsProvider(this);
}
}
@Override
public String toString() {
return ToString.builder(PROVIDER_NAME)
.add("cmd", executableCommand)
.build();
}
}