-
Notifications
You must be signed in to change notification settings - Fork 4k
/
CredentialHelper.java
153 lines (137 loc) · 5.27 KB
/
CredentialHelper.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
// Copyright 2022 The Bazel Authors. 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.
// 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.
package com.google.devtools.build.lib.authandtls.credentialhelper;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.io.CharStreams;
import com.google.devtools.build.lib.shell.Subprocess;
import com.google.devtools.build.lib.shell.SubprocessBuilder;
import com.google.devtools.build.lib.vfs.Path;
import com.google.errorprone.annotations.Immutable;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.URI;
import java.util.Locale;
import java.util.Objects;
/** Wraps an external tool used to obtain credentials. */
@Immutable
public final class CredentialHelper {
private static final Gson GSON = new Gson();
// `Path` is immutable, but not annotated.
@SuppressWarnings("Immutable")
private final Path path;
CredentialHelper(Path path) {
this.path = Preconditions.checkNotNull(path);
}
@VisibleForTesting
public Path getPath() {
return path;
}
/**
* Fetches credentials for the specified {@link URI} by invoking the credential helper as
* subprocess according to the <a
* href="https://github.com/bazelbuild/proposals/blob/main/designs/2022-06-07-bazel-credential-helpers.md">credential
* helper protocol</a>.
*
* @param environment The environment to run the subprocess in.
* @param uri The {@link URI} to fetch credentials for.
* @return The response from the subprocess.
*/
public GetCredentialsResponse getCredentials(CredentialHelperEnvironment environment, URI uri)
throws InterruptedException, IOException {
Preconditions.checkNotNull(environment);
Preconditions.checkNotNull(uri);
Subprocess process = spawnSubprocess(environment, "get");
try (Reader stdout = new InputStreamReader(process.getInputStream(), UTF_8);
Reader stderr = new InputStreamReader(process.getErrorStream(), UTF_8)) {
try (Writer stdin = new OutputStreamWriter(process.getOutputStream(), UTF_8)) {
GSON.toJson(GetCredentialsRequest.newBuilder().setUri(uri).build(), stdin);
}
process.waitFor();
if (process.timedout()) {
throw new IOException(
String.format(
Locale.US,
"Failed to get credentials for '%s' from helper '%s': process timed out",
uri,
path));
}
if (process.exitValue() != 0) {
throw new IOException(
String.format(
Locale.US,
"Failed to get credentials for '%s' from helper '%s': process exited with code %d."
+ " stderr: %s",
uri,
path,
process.exitValue(),
CharStreams.toString(stderr)));
}
try {
GetCredentialsResponse response = GSON.fromJson(stdout, GetCredentialsResponse.class);
if (response == null) {
throw new IOException(
String.format(
Locale.US,
"Failed to get credentials for '%s' from helper '%s': process exited without"
+ " output. stderr: %s",
uri,
path,
CharStreams.toString(stderr)));
}
return response;
} catch (JsonSyntaxException e) {
throw new IOException(
String.format(
Locale.US,
"Failed to get credentials for '%s' from helper '%s': error parsing output. stderr:"
+ " %s",
uri,
path,
CharStreams.toString(stderr)),
e);
}
}
}
private Subprocess spawnSubprocess(CredentialHelperEnvironment environment, String... args)
throws IOException {
Preconditions.checkNotNull(environment);
Preconditions.checkNotNull(args);
return new SubprocessBuilder()
.setArgv(ImmutableList.<String>builder().add(path.getPathString()).add(args).build())
.setWorkingDirectory(environment.getWorkspacePath().getPathFile())
.setEnv(environment.getClientEnvironment())
.setTimeoutMillis(environment.getHelperExecutionTimeout().toMillis())
.start();
}
@Override
public boolean equals(Object o) {
if (o instanceof CredentialHelper) {
CredentialHelper that = (CredentialHelper) o;
return Objects.equals(this.getPath(), that.getPath());
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(getPath());
}
}