/
ImpersonatedCredentials.java
436 lines (380 loc) · 17.5 KB
/
ImpersonatedCredentials.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/*
* Copyright 2018, Google Inc. All rights reserved.
*
* 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 Inc. 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 static com.google.common.base.MoreObjects.firstNonNull;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpStatusCodes;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.GenericData;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.BaseEncoding;
import com.google.auth.ServiceAccountSigner;
/**
* ImpersonatedCredentials allowing credentials issued to a user or service account to impersonate
* another. <br> The source project using ImpersonatedCredentials must enable the "IAMCredentials"
* API.<br> Also, the target service account must grant the orginating principal the "Service
* Account Token Creator" IAM role. <br> Usage:<br>
* <pre>
* String credPath = "/path/to/svc_account.json";
* ServiceAccountCredentials sourceCredentials = ServiceAccountCredentials
* .fromStream(new FileInputStream(credPath));
* sourceCredentials = (ServiceAccountCredentials) sourceCredentials
* .createScoped(Arrays.asList("https://www.googleapis.com/auth/iam"));
*
* ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create(sourceCredentials,
* "impersonated-account@project.iam.gserviceaccount.com", null,
* Arrays.asList("https://www.googleapis.com/auth/devstorage.read_only"), 300);
*
* Storage storage_service = StorageOptions.newBuilder().setProjectId("project-id")
* .setCredentials(targetCredentials).build().getService();
*
* for (Bucket b : storage_service.list().iterateAll())
* System.out.println(b);
* </pre>
*/
public class ImpersonatedCredentials extends GoogleCredentials implements ServiceAccountSigner {
private static final long serialVersionUID = -2133257318957488431L;
private static final String RFC3339 = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private static final int ONE_HOUR_IN_SECONDS = 3600;
private static final String CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
private static final String IAM_ACCESS_TOKEN_ENDPOINT = "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/%s:generateAccessToken";
private static final String IAM_ID_TOKEN_ENDPOINT = "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/%s:generateIdToken";
private static final String IAM_SIGN_ENDPOINT = "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/%s:signBlob";
private static final String SCOPE_EMPTY_ERROR = "Scopes cannot be null";
private static final String LIFETIME_EXCEEDED_ERROR = "lifetime must be less than or equal to 3600";
private static final String PARSE_ERROR_SIGNATURE = "Error parsing signature response. ";
private static final String PARSE_ERROR_MESSAGE = "Error parsing error message response. ";
private GoogleCredentials sourceCredentials;
private String targetPrincipal;
private List<String> delegates;
private List<String> scopes;
private int lifetime;
private final String transportFactoryClassName;
private transient HttpTransportFactory transportFactory;
/**
* @param sourceCredentials The source credential used as to acquire the impersonated credentials
* @param targetPrincipal The service account to impersonate.
* @param delegates The chained list of delegates required to grant the final access_token. If
* set, the sequence of identities must have "Service Account Token Creator" capability granted to
* the preceding identity. For example, if set to [serviceAccountB, serviceAccountC], the
* sourceCredential must have the Token Creator role on serviceAccountB. serviceAccountB must have
* the Token Creator on serviceAccountC. Finally, C must have Token Creator on target_principal.
* If left unset, sourceCredential must have that role on targetPrincipal.
* @param scopes Scopes to request during the authorization grant.
* @param lifetime Number of seconds the delegated credential should be valid for (up to 3600).
* @param transportFactory HTTP transport factory, creates the transport used to get access
* tokens.
*/
public static ImpersonatedCredentials create(GoogleCredentials sourceCredentials,
String targetPrincipal,
List<String> delegates, List<String> scopes, int lifetime,
HttpTransportFactory transportFactory) {
return ImpersonatedCredentials.newBuilder()
.setSourceCredentials(sourceCredentials)
.setTargetPrincipal(targetPrincipal)
.setDelegates(delegates)
.setScopes(scopes)
.setLifetime(lifetime)
.setHttpTransportFactory(transportFactory)
.build();
}
/**
* @param sourceCredentials The source credential used as to acquire the impersonated credentials
* @param targetPrincipal The service account to impersonate.
* @param delegates The chained list of delegates required to grant the final access_token. If
* set, the sequence of identities must have "Service Account Token Creator" capability granted to
* the preceding identity. For example, if set to [serviceAccountB, serviceAccountC], the
* sourceCredential must have the Token Creator role on serviceAccountB. serviceAccountB must have
* the Token Creator on serviceAccountC. Finally, C must have Token Creator on target_principal.
* If left unset, sourceCredential must have that role on targetPrincipal.
* @param scopes Scopes to request during the authorization grant.
* @param lifetime Number of seconds the delegated credential should be valid for (up to 3600).
*/
public static ImpersonatedCredentials create(GoogleCredentials sourceCredentials,
String targetPrincipal,
List<String> delegates, List<String> scopes, int lifetime) {
return ImpersonatedCredentials.newBuilder()
.setSourceCredentials(sourceCredentials)
.setTargetPrincipal(targetPrincipal)
.setDelegates(delegates)
.setScopes(scopes)
.setLifetime(lifetime)
.build();
}
/**
* Returns the email field of the serviceAccount that is being impersonated.
*
* @return email address of the impesonated service account.
*/
@Override
public String getAccount() {
return this.targetPrincipal;
}
/**
* Signs the provided bytes using the private key associated with the impersonated
* service account
*
* @param toSign bytes to sign
* @return signed bytes
* @throws SigningException if the attempt to sign the provided bytes failed
* @see <a href="https://cloud.google.com/iam/credentials/reference/rest/v1/projects.serviceAccounts/signBlob">Blob Signing</a>
*/
@Override
public byte[] sign(byte[] toSign) {
BaseEncoding base64 = BaseEncoding.base64();
String signature;
try {
signature = getSignature(base64.encode(toSign));
} catch (IOException ex) {
throw new SigningException("Failed to sign the provided bytes", ex);
}
return base64.decode(signature);
}
private String getSignature(String bytes) throws IOException {
String signBlobUrl = String.format(IAM_SIGN_ENDPOINT, getAccount());
GenericUrl genericUrl = new GenericUrl(signBlobUrl);
GenericData signRequest = new GenericData();
signRequest.set("delegates", this.delegates);
signRequest.set("payload", bytes);
JsonHttpContent signContent = new JsonHttpContent(OAuth2Utils.JSON_FACTORY, signRequest);
HttpTransport httpTransport = this.transportFactory.create();
HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(sourceCredentials);
HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
HttpRequest request = requestFactory.buildPostRequest(genericUrl, signContent);
Map<String, List<String>> headers = getRequestMetadata();
HttpHeaders requestHeaders = request.getHeaders();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
requestHeaders.put(entry.getKey(), entry.getValue());
}
JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY);
adapter.initialize(request);
request.setParser(parser);
request.setThrowExceptionOnExecuteError(false);
HttpResponse response = request.execute();
int statusCode = response.getStatusCode();
if (statusCode >= 400 && statusCode < HttpStatusCodes.STATUS_CODE_SERVER_ERROR) {
GenericData responseError = response.parseAs(GenericData.class);
Map<String, Object> error = OAuth2Utils.validateMap(responseError, "error", PARSE_ERROR_MESSAGE);
String errorMessage = OAuth2Utils.validateString(error, "message", PARSE_ERROR_MESSAGE);
throw new IOException(String.format("Error code %s trying to sign provided bytes: %s",
statusCode, errorMessage));
}
if (statusCode != HttpStatusCodes.STATUS_CODE_OK) {
throw new IOException(String.format("Unexpected Error code %s trying to sign provided bytes: %s", statusCode,
response.parseAsString()));
}
InputStream content = response.getContent();
if (content == null) {
// Throw explicitly here on empty content to avoid NullPointerException from parseAs call.
// Mock transports will have success code with empty content by default.
throw new IOException("Empty content from sign blob server request.");
}
GenericData responseData = response.parseAs(GenericData.class);
return OAuth2Utils.validateString(responseData, "signedBlob", PARSE_ERROR_SIGNATURE);
}
private ImpersonatedCredentials(Builder builder) {
this.sourceCredentials = builder.getSourceCredentials();
this.targetPrincipal = builder.getTargetPrincipal();
this.delegates = builder.getDelegates();
this.scopes = builder.getScopes();
this.lifetime = builder.getLifetime();
this.transportFactory = firstNonNull(builder.getHttpTransportFactory(),
getFromServiceLoader(HttpTransportFactory.class, OAuth2Utils.HTTP_TRANSPORT_FACTORY));
this.transportFactoryClassName = this.transportFactory.getClass().getName();
if (this.delegates == null) {
this.delegates = new ArrayList<String>();
}
if (this.scopes == null) {
throw new IllegalStateException(SCOPE_EMPTY_ERROR);
}
if (this.lifetime > ONE_HOUR_IN_SECONDS) {
throw new IllegalStateException(LIFETIME_EXCEEDED_ERROR);
}
}
@Override
public AccessToken refreshAccessToken() throws IOException {
if (this.sourceCredentials.getAccessToken() == null) {
this.sourceCredentials = this.sourceCredentials
.createScoped(Arrays.asList(CLOUD_PLATFORM_SCOPE));
}
try {
this.sourceCredentials.refreshIfExpired();
} catch (IOException e) {
throw new IOException("Unable to refresh sourceCredentials", e);
}
HttpTransport httpTransport = this.transportFactory.create();
JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY);
HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(sourceCredentials);
HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
String endpointUrl = String.format(IAM_ACCESS_TOKEN_ENDPOINT, this.targetPrincipal);
GenericUrl url = new GenericUrl(endpointUrl);
Map<String, Object> body = ImmutableMap.<String, Object>of("delegates", this.delegates, "scope",
this.scopes,
"lifetime", this.lifetime + "s");
HttpContent requestContent = new JsonHttpContent(parser.getJsonFactory(), body);
HttpRequest request = requestFactory.buildPostRequest(url, requestContent);
adapter.initialize(request);
request.setParser(parser);
HttpResponse response = null;
try {
response = request.execute();
} catch (IOException e) {
throw new IOException("Error requesting access token", e);
}
GenericData responseData = response.parseAs(GenericData.class);
response.disconnect();
String accessToken = OAuth2Utils
.validateString(responseData, "accessToken", "Expected to find an accessToken");
String expireTime = OAuth2Utils
.validateString(responseData, "expireTime", "Expected to find an expireTime");
DateFormat format = new SimpleDateFormat(RFC3339);
Date date;
try {
date = format.parse(expireTime);
} catch (ParseException pe) {
throw new IOException("Error parsing expireTime: " + pe.getMessage());
}
return new AccessToken(accessToken, date);
}
@Override
public int hashCode() {
return Objects.hash(sourceCredentials, targetPrincipal, delegates, scopes, lifetime);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("sourceCredentials", sourceCredentials)
.add("targetPrincipal", targetPrincipal)
.add("delegates", delegates)
.add("scopes", scopes)
.add("lifetime", lifetime)
.add("transportFactoryClassName", transportFactoryClassName).toString();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ImpersonatedCredentials)) {
return false;
}
ImpersonatedCredentials other = (ImpersonatedCredentials) obj;
return Objects.equals(this.sourceCredentials, other.sourceCredentials)
&& Objects.equals(this.targetPrincipal, other.targetPrincipal)
&& Objects.equals(this.delegates, other.delegates)
&& Objects.equals(this.scopes, other.scopes)
&& Objects.equals(this.lifetime, other.lifetime)
&& Objects.equals(this.transportFactoryClassName, other.transportFactoryClassName);
}
public Builder toBuilder() {
return new Builder(this.sourceCredentials, this.targetPrincipal);
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder extends GoogleCredentials.Builder {
private GoogleCredentials sourceCredentials;
private String targetPrincipal;
private List<String> delegates;
private List<String> scopes;
private int lifetime;
private HttpTransportFactory transportFactory;
protected Builder() {
}
protected Builder(GoogleCredentials sourceCredentials, String targetPrincipal) {
this.sourceCredentials = sourceCredentials;
this.targetPrincipal = targetPrincipal;
}
public Builder setSourceCredentials(GoogleCredentials sourceCredentials) {
this.sourceCredentials = sourceCredentials;
return this;
}
public GoogleCredentials getSourceCredentials() {
return this.sourceCredentials;
}
public Builder setTargetPrincipal(String targetPrincipal) {
this.targetPrincipal = targetPrincipal;
return this;
}
public String getTargetPrincipal() {
return this.targetPrincipal;
}
public Builder setDelegates(List<String> delegates) {
this.delegates = delegates;
return this;
}
public List<String> getDelegates() {
return this.delegates;
}
public Builder setScopes(List<String> scopes) {
this.scopes = scopes;
return this;
}
public List<String> getScopes() {
return this.scopes;
}
public Builder setLifetime(int lifetime) {
this.lifetime = lifetime;
return this;
}
public int getLifetime() {
return this.lifetime;
}
public Builder setHttpTransportFactory(HttpTransportFactory transportFactory) {
this.transportFactory = transportFactory;
return this;
}
public HttpTransportFactory getHttpTransportFactory() {
return transportFactory;
}
public ImpersonatedCredentials build() {
return new ImpersonatedCredentials(this);
}
}
}