Repository navigation
Expand file tree
/
Copy pathOAuth2Utils.java
More file actions
499 lines (458 loc) · 19.9 KB
/
Copy pathOAuth2Utils.java
File metadata and controls
499 lines (458 loc) · 19.9 KB
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
/*
* Copyright 2015, 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 com.google.api.client.http.HttpBackOffIOExceptionHandler;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.client.util.PemReader;
import com.google.api.client.util.PemReader.Section;
import com.google.api.core.InternalApi;
import com.google.auth.http.AuthHttpConstants;
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.mtls.MtlsHttpTransportFactory;
import com.google.common.base.Strings;
import com.google.common.io.BaseEncoding;
import com.google.common.io.ByteStreams;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.math.BigDecimal;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/** Internal utilities for the com.google.auth.oauth2 namespace. */
@NullMarked
@InternalApi
public class OAuth2Utils {
enum Pkcs8Algorithm {
RSA,
EC
}
static final Pattern PEM_CERT_PATTERN =
Pattern.compile("-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----", Pattern.DOTALL);
static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
public static final String TOKEN_TYPE_ACCESS_TOKEN =
"urn:ietf:params:oauth:token-type:access_token";
static final String TOKEN_TYPE_TOKEN_EXCHANGE = "urn:ietf:params:oauth:token-type:token-exchange";
public static final String TOKEN_TYPE_ACCESS_BOUNDARY_INTERMEDIARY_TOKEN =
"urn:ietf:params:oauth:token-type:access_boundary_intermediary_token";
static final String GRANT_TYPE_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer";
public static final String TOKEN_EXCHANGE_URL_FORMAT = "https://sts.%s/v1/token";
static final URI TOKEN_SERVER_URI = URI.create("https://oauth2.googleapis.com/token");
static final URI TOKEN_REVOKE_URI = URI.create("https://oauth2.googleapis.com/revoke");
static final URI USER_AUTH_URI = URI.create("https://accounts.google.com/o/oauth2/auth");
public static final String CLOUD_PLATFORM_SCOPE =
"https://www.googleapis.com/auth/cloud-platform";
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static final HttpTransportFactory HTTP_TRANSPORT_FACTORY =
new DefaultHttpTransportFactory();
static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static String VALUE_NOT_FOUND_MESSAGE = "%sExpected value %s not found.";
private static String VALUE_WRONG_TYPE_MESSAGE = "%sExpected %s value %s of wrong type.";
static final String BEARER_PREFIX = AuthHttpConstants.BEARER + " ";
static final String TOKEN_RESPONSE_SCOPE = "scope";
static final int INITIAL_RETRY_INTERVAL_MILLIS = 1000;
static final double RETRY_RANDOMIZATION_FACTOR = 0.1;
static final double RETRY_MULTIPLIER = 2;
static final int DEFAULT_NUMBER_OF_RETRIES = 3;
static void setDefaultRetrySettings(HttpRequest request) {
request.setNumberOfRetries(DEFAULT_NUMBER_OF_RETRIES);
ExponentialBackOff backoff =
new ExponentialBackOff.Builder()
.setInitialIntervalMillis(INITIAL_RETRY_INTERVAL_MILLIS)
.setRandomizationFactor(RETRY_RANDOMIZATION_FACTOR)
.setMultiplier(RETRY_MULTIPLIER)
.build();
request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(backoff));
}
// Includes expected server errors from Google token endpoint
// Other 5xx codes are either not used or retries are unlikely to succeed
public static final Set<Integer> TOKEN_ENDPOINT_RETRYABLE_STATUS_CODES =
new HashSet<>(Arrays.asList(500, 503, 408, 429));
static class DefaultHttpTransportFactory implements HttpTransportFactory {
@Override
public HttpTransport create() {
return HTTP_TRANSPORT;
}
}
/**
* Returns whether the headers contain the specified value as one of the entries in the specified
* header.
*/
static boolean headersContainValue(HttpHeaders headers, String headerName, String value) {
Object values = headers.get(headerName);
if (values instanceof Collection) {
@SuppressWarnings("unchecked")
Collection<Object> valuesCollection = (Collection<Object>) values;
return valuesCollection.contains(value);
}
return false;
}
/** Parses the specified JSON text. */
static GenericJson parseJson(String json) throws IOException {
JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY);
InputStream stateStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
GenericJson stateJson =
parser.parseAndClose(stateStream, StandardCharsets.UTF_8, GenericJson.class);
return stateJson;
}
/** Return the specified string from JSON or throw a helpful error message. */
static String validateString(Map<String, Object> map, String key, String errorPrefix)
throws IOException {
Object value = map.get(key);
if (value == null) {
throw new IOException(String.format(VALUE_NOT_FOUND_MESSAGE, errorPrefix, key));
}
if (!(value instanceof String)) {
throw new IOException(String.format(VALUE_WRONG_TYPE_MESSAGE, errorPrefix, "string", key));
}
return (String) value;
}
/**
* Saves the end user credentials into the given file path.
*
* @param credentials InputStream containing user credentials in JSON format
* @param filePath Path to file where to store the credentials
* @throws IOException An error saving the credentials.
*/
static void writeInputStreamToFile(InputStream credentials, String filePath) throws IOException {
final OutputStream outputStream = new FileOutputStream(new File(filePath));
try {
ByteStreams.copy(credentials, outputStream);
} finally {
outputStream.close();
}
}
/** Return the specified optional string from JSON or throw a helpful error message. */
static @Nullable String validateOptionalString(
Map<String, Object> map, String key, String errorPrefix) throws IOException {
Object value = map.get(key);
if (value == null) {
return null;
}
if (!(value instanceof String)) {
throw new IOException(String.format(VALUE_WRONG_TYPE_MESSAGE, errorPrefix, "string", key));
}
return (String) value;
}
/** Return the specified list of strings from JSON or throw a helpful error message. */
@SuppressWarnings("unchecked")
static @Nullable List<String> validateOptionalListString(
Map<String, Object> map, String key, String errorPrefix) throws IOException {
Object value = map.get(key);
if (value == null) {
return null;
}
if (!(value instanceof List)) {
throw new IOException(
String.format(VALUE_WRONG_TYPE_MESSAGE, errorPrefix, "List<String>", key));
}
return (List<String>) value;
}
/** Return the specified integer from JSON or throw a helpful error message. */
static int validateInt32(Map<String, Object> map, String key, String errorPrefix)
throws IOException {
Object value = map.get(key);
if (value == null) {
throw new IOException(String.format(VALUE_NOT_FOUND_MESSAGE, errorPrefix, key));
}
if (value instanceof BigDecimal) {
BigDecimal bigDecimalValue = (BigDecimal) value;
return bigDecimalValue.intValueExact();
}
if (!(value instanceof Integer)) {
throw new IOException(String.format(VALUE_WRONG_TYPE_MESSAGE, errorPrefix, "integer", key));
}
return (Integer) value;
}
/** Return the specified long from JSON or throw a helpful error message. */
static long validateLong(Map<String, Object> map, String key, String errorPrefix)
throws IOException {
Object value = map.get(key);
if (value == null) {
throw new IOException(String.format(VALUE_NOT_FOUND_MESSAGE, errorPrefix, key));
}
if (value instanceof BigDecimal) {
BigDecimal bigDecimalValue = (BigDecimal) value;
return bigDecimalValue.longValueExact();
}
if (!(value instanceof Long)) {
throw new IOException(String.format(VALUE_WRONG_TYPE_MESSAGE, errorPrefix, "long", key));
}
return (Long) value;
}
/** Return the specified map from JSON or throw a helpful error message. */
@SuppressWarnings({"unchecked", "rawtypes"})
static Map<String, Object> validateMap(Map<String, Object> map, String key, String errorPrefix)
throws IOException {
Object value = map.get(key);
if (value == null) {
throw new IOException(String.format(VALUE_NOT_FOUND_MESSAGE, errorPrefix, key));
}
if (!(value instanceof Map)) {
throw new IOException(String.format(VALUE_WRONG_TYPE_MESSAGE, errorPrefix, "Map", key));
}
return (Map) value;
}
/**
* Converts a PKCS#8 string to an RSA private key.
*
* @param privateKeyPkcs8 the PKCS#8 string.
* @return the RSA private key.
* @throws IOException if the PKCS#8 data is invalid or if an unexpected exception occurs during
* key creation.
*/
public static PrivateKey privateKeyFromPkcs8(String privateKeyPkcs8) throws IOException {
return privateKeyFromPkcs8(privateKeyPkcs8, Pkcs8Algorithm.RSA);
}
/**
* Reads a private key from a PKCS#8 encoded string.
*
* <p>If the key is labeled with "-----BEGIN PRIVATE KEY-----", it is parsed as PKCS#8 as per RFC
* 7468 Section 10.
*
* @see <a href="https://datatracker.ietf.org/doc/html/rfc7468#section-10">RFC 7468 Section 10</a>
* @param privateKeyPkcs8 base64 encoded private key string
* @param algorithm expected algorithm of the private key
* @return the private key.
* @throws IOException if the private key data is invalid or if an unexpected exception occurs
* during key creation.
*/
public static PrivateKey privateKeyFromPkcs8(String privateKeyPkcs8, Pkcs8Algorithm algorithm)
throws IOException {
Reader reader = new StringReader(privateKeyPkcs8);
Section section = PemReader.readFirstSectionAndClose(reader, "PRIVATE KEY");
if (section == null) {
throw new IOException("Invalid PKCS#8 data.");
}
byte[] bytes = section.getBase64DecodedBytes();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
Exception unexpectedException;
try {
KeyFactory keyFactory = KeyFactory.getInstance(algorithm.toString());
return keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException exception) {
unexpectedException = exception;
}
throw new IOException("Unexpected exception reading PKCS#8 data", unexpectedException);
}
/**
* Generates a Basic Authentication header string for the provided username and password.
*
* <p>This method constructs a Basic Authentication string using the provided username and
* password. The credentials are encoded in Base64 format and prefixed with the "Basic " scheme
* identifier.
*
* @param username The username for authentication.
* @param password The password for authentication.
* @return The Basic Authentication header value.
* @throws IllegalArgumentException if either username or password is null or empty.
*/
static String generateBasicAuthHeader(String username, String password) {
if (Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(password)) {
throw new IllegalArgumentException("Username and password cannot be null or empty.");
}
String credentials = username + ":" + password;
String encodedCredentials = BaseEncoding.base64().encode(credentials.getBytes());
return "Basic " + encodedCredentials;
}
/**
* Returns whether the given throwable or any exception in its causal chain represents a 401
* Unauthorized error (either an {@link OAuthException} or {@link HttpResponseException} with
* status code 401).
*
* @param t the throwable to inspect
* @return {@code true} if {@code t} or any cause in its chain is a 401 error
*/
static boolean isUnauthorizedException(@Nullable Throwable t) {
while (t != null) {
if (t instanceof OAuthException && ((OAuthException) t).getHttpStatusCode() == 401) {
return true;
}
if (t instanceof HttpResponseException
&& ((HttpResponseException) t).getStatusCode() == 401) {
return true;
}
t = t.getCause();
}
return false;
}
/**
* Returns whether the given throwable or any exception in its causal chain represents an OAuth
* {@code invalid_grant} error (for example, HTTP 400 {@code invalid_grant} returned by STS when
* {@code trust_chain_path} is rotated before {@code cert_path} and {@code key_path}, so the
* pinned leaf certificate does not match the trust chain read from disk).
*
* @param t the throwable to inspect
* @return {@code true} if {@code t} or any cause in its chain is an {@code invalid_grant} {@link
* OAuthException}
*/
static boolean isInvalidGrantException(@Nullable Throwable t) {
while (t != null) {
if (t instanceof OAuthException
&& "invalid_grant".equals(((OAuthException) t).getErrorCode())) {
return true;
}
t = t.getCause();
}
return false;
}
/**
* Returns whether the given {@link HttpTransportFactory} is an {@link MtlsHttpTransportFactory}
* initialized with a client certificate {@link KeyStore}.
*/
static boolean hasMtlsKeyStore(@Nullable HttpTransportFactory transportFactory) {
return transportFactory instanceof MtlsHttpTransportFactory
&& ((MtlsHttpTransportFactory) transportFactory).hasKeyStore();
}
/**
* Returns whether the given {@link HttpTransportFactory} is an {@link MtlsHttpTransportFactory}
* without an initialized {@link KeyStore} (for example, after deserialization via the no-arg
* constructor before certificate loading).
*/
static boolean isKeylessMtlsTransportFactory(@Nullable HttpTransportFactory transportFactory) {
return transportFactory instanceof MtlsHttpTransportFactory
&& !((MtlsHttpTransportFactory) transportFactory).hasKeyStore();
}
/**
* Returns whether the given transport factory should be managed and upgraded to {@link
* MtlsHttpTransportFactory} when mTLS is configured:
*
* <ul>
* <li>{@code null}, {@link OAuth2Utils#HTTP_TRANSPORT_FACTORY}, or {@link
* OAuth2Utils.DefaultHttpTransportFactory}: no custom transport factory was provided, so
* mTLS credentials should upgrade to {@link MtlsHttpTransportFactory}.
* <li>Exact class {@link MtlsHttpTransportFactory}: standard mTLS transport (including when
* cloning an already-initialized mTLS credential), which should be refreshed per cycle with
* the latest {@link KeyStore}.
* <li>An {@link MtlsHttpTransportFactory} (or subclass) without a {@link KeyStore} loaded yet.
* </ul>
*
* <p>Conversely, if a caller supplies a custom {@link HttpTransportFactory} or a custom {@link
* MtlsHttpTransportFactory} subclass pre-configured with its own {@link KeyStore}, this returns
* {@code false} so the caller's custom transport is preserved.
*/
static boolean isDefaultOrMtlsTransportFactory(@Nullable HttpTransportFactory transportFactory) {
return transportFactory == null
|| transportFactory instanceof DefaultHttpTransportFactory
|| transportFactory.getClass() == MtlsHttpTransportFactory.class
|| isKeylessMtlsTransportFactory(transportFactory);
}
/**
* Returns whether the certificate chain or private key in {@code newKeyStore} differs from {@code
* oldKeyStore}. Used to avoid retrying 401, STS {@code invalid_grant}, and transport failures
* when the reloaded certificate and key are unchanged, and to decide whether a cached STS token
* can be reused.
*
* @param oldKeyStore the previously loaded keystore
* @param newKeyStore the newly reloaded keystore
* @return {@code true} if the certificates or keys differ, or if either keystore cannot be read
*/
static boolean hasCertificateChanged(
@Nullable KeyStore oldKeyStore, @Nullable KeyStore newKeyStore) {
if (oldKeyStore == newKeyStore) {
return false;
}
if (oldKeyStore == null || newKeyStore == null) {
return true;
}
List<Object> oldEntries = getKeyStoreEntries(oldKeyStore);
List<Object> newEntries = getKeyStoreEntries(newKeyStore);
if (oldEntries == null || newEntries == null) {
return true;
}
return !oldEntries.equals(newEntries);
}
private static @Nullable List<Object> getKeyStoreEntries(KeyStore keyStore) {
List<Object> entries = new ArrayList<>();
try {
Enumeration<String> aliases = keyStore.aliases();
if (aliases != null) {
List<String> aliasList = Collections.list(aliases);
Collections.sort(aliasList);
for (String alias : aliasList) {
Certificate[] chain = keyStore.getCertificateChain(alias);
if (chain != null && chain.length > 0) {
Collections.addAll(entries, chain);
} else {
Certificate cert = keyStore.getCertificate(alias);
if (cert != null) {
entries.add(cert);
}
}
if (keyStore.isKeyEntry(alias)) {
Key key = keyStore.getKey(alias, "".toCharArray());
if (key != null) {
entries.add(key);
}
}
}
}
} catch (GeneralSecurityException e) {
return null;
}
return entries;
}
private OAuth2Utils() {}
}