-
Notifications
You must be signed in to change notification settings - Fork 216
/
PluggableAuthHandler.java
312 lines (270 loc) · 12.2 KB
/
PluggableAuthHandler.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
/*
* Copyright 2022 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.auth.oauth2;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonParser;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Splitter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* Internal handler for retrieving 3rd party tokens from user defined scripts/executables for
* workload identity federation.
*
* <p>See {@link PluggableAuthCredentials}.
*/
final class PluggableAuthHandler implements ExecutableHandler {
// The maximum supported version for the executable response.
// The executable response always includes a version number that is used
// to detect compatibility with the response and library verions.
private static final int EXECUTABLE_SUPPORTED_MAX_VERSION = 1;
// The GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES dictates if this feature is enabled.
// The GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable must be set to '1' for
// security reasons.
private static final String GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES =
"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES";
// The exit status of the 3P script that represents a successful execution.
private static final int EXIT_CODE_SUCCESS = 0;
private final EnvironmentProvider environmentProvider;
private InternalProcessBuilder internalProcessBuilder;
PluggableAuthHandler(EnvironmentProvider environmentProvider) {
this.environmentProvider = environmentProvider;
}
@VisibleForTesting
PluggableAuthHandler(
EnvironmentProvider environmentProvider, InternalProcessBuilder internalProcessBuilder) {
this.environmentProvider = environmentProvider;
this.internalProcessBuilder = internalProcessBuilder;
}
@Override
public String retrieveTokenFromExecutable(ExecutableOptions options) throws IOException {
// Validate that executables are allowed to run. To use Pluggable Auth,
// The GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable must be set to 1
// for security reasons.
if (!"1".equals(this.environmentProvider.getEnv(GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES))) {
throw new PluggableAuthException(
"PLUGGABLE_AUTH_DISABLED",
"Pluggable Auth executables need "
+ "to be explicitly allowed to run by setting the "
+ "GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable to 1.");
}
// Users can specify an output file path in the Pluggable Auth ADC configuration.
// This is the file's absolute path. Their executable will handle writing the 3P credentials to
// this file.
// If specified, we will first check if we have valid unexpired credentials stored in this
// location to avoid running the executable until they are expired.
ExecutableResponse executableResponse = getCachedExecutableResponse(options);
// If the output_file does not contain a valid response, call the executable.
if (executableResponse == null) {
executableResponse = getExecutableResponse(options);
}
// If an output file is specified, successful responses must contain the `expiration_time`
// field.
if (options.getOutputFilePath() != null
&& !options.getOutputFilePath().isEmpty()
&& executableResponse.isSuccessful()
&& executableResponse.getExpirationTime() == null) {
throw new PluggableAuthException(
"INVALID_EXECUTABLE_RESPONSE",
"The executable response must contain the `expiration_time` field for successful responses when an "
+ "output_file has been specified in the configuration.");
}
// The executable response includes a version. Validate that the version is compatible
// with the library.
if (executableResponse.getVersion() > EXECUTABLE_SUPPORTED_MAX_VERSION) {
throw new PluggableAuthException(
"UNSUPPORTED_VERSION",
"The version of the executable response is not supported. "
+ String.format(
"The maximum version currently supported is %s.",
EXECUTABLE_SUPPORTED_MAX_VERSION));
}
if (!executableResponse.isSuccessful()) {
throw new PluggableAuthException(
executableResponse.getErrorCode(), executableResponse.getErrorMessage());
}
if (executableResponse.isExpired()) {
throw new PluggableAuthException("INVALID_RESPONSE", "The executable response is expired.");
}
// Subject token is valid and can be returned.
return executableResponse.getSubjectToken();
}
@Nullable
ExecutableResponse getCachedExecutableResponse(ExecutableOptions options)
throws PluggableAuthException {
ExecutableResponse executableResponse = null;
if (options.getOutputFilePath() != null && !options.getOutputFilePath().isEmpty()) {
// Try reading cached response from output_file.
try {
File outputFile = new File(options.getOutputFilePath());
// Check if the output file is valid and not empty.
if (outputFile.isFile() && outputFile.length() > 0) {
InputStream inputStream = new FileInputStream(options.getOutputFilePath());
BufferedReader reader =
new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(reader);
ExecutableResponse cachedResponse =
new ExecutableResponse(parser.parseAndClose(GenericJson.class));
// If the cached response is successful and unexpired, we can use it.
// Response version will be validated below.
if (cachedResponse.isValid()) {
executableResponse = cachedResponse;
}
}
} catch (Exception e) {
throw new PluggableAuthException(
"INVALID_OUTPUT_FILE",
"The output_file specified contains an invalid or malformed response." + e);
}
}
return executableResponse;
}
ExecutableResponse getExecutableResponse(ExecutableOptions options) throws IOException {
List<String> components = Splitter.on(" ").splitToList(options.getExecutableCommand());
// Create the process.
InternalProcessBuilder processBuilder = getProcessBuilder(components);
// Inject environment variables.
Map<String, String> envMap = processBuilder.environment();
envMap.putAll(options.getEnvironmentMap());
// Redirect error stream.
processBuilder.redirectErrorStream(true);
// Start the process.
Process process = processBuilder.start();
ExecutableResponse execResp;
String executableOutput = "";
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
// Consume the input stream while waiting for the program to finish so that
// the process won't hang if the STDOUT buffer is filled.
Future<String> future =
executor.submit(
() -> {
BufferedReader reader =
new BufferedReader(
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append(System.lineSeparator());
}
return sb.toString().trim();
});
boolean success = process.waitFor(options.getExecutableTimeoutMs(), TimeUnit.MILLISECONDS);
if (!success) {
// Process has not terminated within the specified timeout.
throw new PluggableAuthException(
"TIMEOUT_EXCEEDED", "The executable failed to finish within the timeout specified.");
}
int exitCode = process.exitValue();
if (exitCode != EXIT_CODE_SUCCESS) {
throw new PluggableAuthException(
"EXIT_CODE", String.format("The executable failed with exit code %s.", exitCode));
}
executableOutput = future.get();
executor.shutdownNow();
JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(executableOutput);
execResp = new ExecutableResponse(parser.parseAndClose(GenericJson.class));
} catch (IOException e) {
// Destroy the process.
process.destroy();
// Shutdown executor if needed.
if (!executor.isShutdown()) {
executor.shutdownNow();
}
if (e instanceof PluggableAuthException) {
throw e;
}
// An error may have occurred in the executable and should be surfaced.
throw new PluggableAuthException(
"INVALID_RESPONSE",
String.format("The executable returned an invalid response: %s.", executableOutput));
} catch (InterruptedException | ExecutionException e) {
// Destroy the process.
process.destroy();
throw new PluggableAuthException(
"INTERRUPTED", String.format("The execution was interrupted: %s.", e));
}
process.destroy();
return execResp;
}
InternalProcessBuilder getProcessBuilder(List<String> commandComponents) {
if (internalProcessBuilder != null) {
return internalProcessBuilder;
}
return new DefaultProcessBuilder(new ProcessBuilder(commandComponents));
}
/**
* An interface for creating and managing a process.
*
* <p>ProcessBuilder is final and does not implement any interface. This class allows concrete
* implementations to be specified to test these changes.
*/
abstract static class InternalProcessBuilder {
abstract Map<String, String> environment();
abstract InternalProcessBuilder redirectErrorStream(boolean redirectErrorStream);
abstract Process start() throws IOException;
}
/**
* A default implementation for {@link InternalProcessBuilder} that wraps {@link ProcessBuilder}.
*/
static final class DefaultProcessBuilder extends InternalProcessBuilder {
ProcessBuilder processBuilder;
DefaultProcessBuilder(ProcessBuilder processBuilder) {
this.processBuilder = processBuilder;
}
@Override
Map<String, String> environment() {
return this.processBuilder.environment();
}
@Override
InternalProcessBuilder redirectErrorStream(boolean redirectErrorStream) {
this.processBuilder.redirectErrorStream(redirectErrorStream);
return this;
}
@Override
Process start() throws IOException {
return this.processBuilder.start();
}
}
}