Skip to content

Commit e6491ec

Browse files
committed
Addressed PR comments. All refresh logic within Google Credentials. Use supportsTrustBoundary to identify whether a child class supports tb prior to refresh.
1 parent 81ccd96 commit e6491ec

File tree

9 files changed

+84
-144
lines changed

9 files changed

+84
-144
lines changed

oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@
8282
* <p>These credentials use the IAM API to sign data. See {@link #sign(byte[])} for more details.
8383
*/
8484
public class ComputeEngineCredentials extends GoogleCredentials
85-
implements ServiceAccountSigner, IdTokenProvider, TrustBoundaryProvider {
85+
implements ServiceAccountSigner, IdTokenProvider {
8686

8787
static final String METADATA_RESPONSE_EMPTY_CONTENT_ERROR_MESSAGE =
8888
"Empty content from metadata token server request.";
@@ -387,7 +387,7 @@ public AccessToken refreshAccessToken() throws IOException {
387387
long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000;
388388
AccessToken newAccessToken = new AccessToken(accessToken, new Date(expiresAtMilliseconds));
389389

390-
refreshTrustBoundaries(newAccessToken);
390+
refreshTrustBoundary(newAccessToken, getTrustBoundaryUrl(), transportFactory);
391391

392392
return newAccessToken;
393393
}
@@ -707,12 +707,11 @@ public String getAccount() {
707707
}
708708

709709
@Override
710-
public HttpTransportFactory getTransportFactory() {
711-
return transportFactory;
710+
Boolean supportsTrustBoundary() {
711+
return true;
712712
}
713713

714-
@Override
715-
public String getTrustBoundaryUrl() throws IOException {
714+
String getTrustBoundaryUrl() throws IOException {
716715
return String.format(
717716
OAuth2Utils.IAM_CREDENTIALS_ALLOWED_LOCATIONS_URL_FORMAT_SERVICE_ACCOUNT,
718717
getUniverseDomain(),

oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java

Lines changed: 43 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,48 @@ public TrustBoundary getTrustBoundary() {
341341
return trustBoundary;
342342
}
343343

344+
Boolean supportsTrustBoundary() {
345+
return false;
346+
}
347+
348+
void refreshTrustBoundary(AccessToken newAccessToken, String trustBoundaryUrl, HttpTransportFactory transportFactory)
349+
throws IOException {
350+
351+
if (!supportsTrustBoundary() || !TrustBoundary.isTrustBoundaryEnabled() || !isDefaultUniverseDomain()) {
352+
return;
353+
}
354+
355+
TrustBoundary cachedTrustBoundary;
356+
357+
synchronized (lock) {
358+
// Do not refresh if the cached value is already NO_OP.
359+
if (trustBoundary != null && trustBoundary.isNoOp()) {
360+
return;
361+
}
362+
cachedTrustBoundary = trustBoundary;
363+
}
364+
365+
TrustBoundary newTrustBoundary;
366+
try {
367+
newTrustBoundary =
368+
TrustBoundary.refresh(
369+
transportFactory, trustBoundaryUrl, newAccessToken, cachedTrustBoundary);
370+
} catch (IOException e) {
371+
// If refresh fails, check for a cached value.
372+
if (cachedTrustBoundary == null) {
373+
// No cached value, so fail hard.
374+
throw new IOException(
375+
"Failed to refresh trust boundary and no cached value is available.", e);
376+
}
377+
return;
378+
}
379+
380+
// A lock is required to safely update the shared field.
381+
synchronized (lock) {
382+
trustBoundary = newTrustBoundary;
383+
}
384+
}
385+
344386
/**
345387
* Gets the universe domain for the credential.
346388
*
@@ -372,7 +414,7 @@ protected boolean isExplicitUniverseDomain() {
372414
* @return true if universe domain equals to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}, false
373415
* otherwise
374416
*/
375-
boolean isDefaultUniverseDomain() throws IOException {
417+
public boolean isDefaultUniverseDomain() throws IOException {
376418
return getUniverseDomain().equals(Credentials.GOOGLE_DEFAULT_UNIVERSE);
377419
}
378420

@@ -392,57 +434,6 @@ static Map<String, List<String>> addQuotaProjectIdToRequestMetadata(
392434
return Collections.unmodifiableMap(newRequestMetadata);
393435
}
394436

395-
/**
396-
* Refreshes the trust boundary associated with these credentials.
397-
*
398-
* @param newAccessToken The newly refreshed access token to use for the trust boundary request.
399-
* @throws IOException If the refresh fails and no cached trust boundary is available.
400-
* @throws IllegalArgumentException If the provided access token is null or expired.
401-
*/
402-
protected void refreshTrustBoundaries(AccessToken newAccessToken) throws IOException {
403-
if (!(this instanceof TrustBoundaryProvider)) {
404-
return;
405-
}
406-
if (!TrustBoundary.isTrustBoundaryEnabled() || !isDefaultUniverseDomain()) {
407-
return;
408-
}
409-
410-
TrustBoundaryProvider provider = (TrustBoundaryProvider) this;
411-
TrustBoundary cachedTrustBoundary;
412-
413-
synchronized (lock) {
414-
// Do not refresh if the cached value is already NO_OP.
415-
if (this.trustBoundary != null && this.trustBoundary.isNoOp()) {
416-
return;
417-
}
418-
cachedTrustBoundary = this.trustBoundary;
419-
}
420-
421-
TrustBoundary newTrustBoundary;
422-
try {
423-
newTrustBoundary =
424-
TrustBoundary.refresh(
425-
provider.getTransportFactory(),
426-
provider.getTrustBoundaryUrl(),
427-
newAccessToken,
428-
cachedTrustBoundary);
429-
} catch (IOException e) {
430-
// If refresh fails, check for a cached value.
431-
if (cachedTrustBoundary == null) {
432-
// No cached value, so fail hard.
433-
throw new IOException(
434-
"Failed to refresh trust boundary and no cached value is available.", e);
435-
}
436-
437-
return;
438-
}
439-
440-
// A lock is required to safely update the shared field.
441-
synchronized (lock) {
442-
this.trustBoundary = newTrustBoundary;
443-
}
444-
}
445-
446437
@Override
447438
protected Map<String, List<String>> getAdditionalHeaders() {
448439
Map<String, List<String>> headers = new HashMap<>(super.getAdditionalHeaders());

oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@
9393
* </pre>
9494
*/
9595
public class ImpersonatedCredentials extends GoogleCredentials
96-
implements ServiceAccountSigner, IdTokenProvider, TrustBoundaryProvider {
96+
implements ServiceAccountSigner, IdTokenProvider {
9797

9898
private static final long serialVersionUID = -2133257318957488431L;
9999
private static final String RFC3339 = "yyyy-MM-dd'T'HH:mm:ssX";
@@ -325,13 +325,12 @@ public GoogleCredentials getSourceCredentials() {
325325
return sourceCredentials;
326326
}
327327

328-
@Override
329-
public HttpTransportFactory getTransportFactory() {
330-
return transportFactory;
331-
}
328+
@Override
329+
Boolean supportsTrustBoundary() {
330+
return true;
331+
}
332332

333-
@Override
334-
public String getTrustBoundaryUrl() throws IOException {
333+
String getTrustBoundaryUrl() throws IOException {
335334
return String.format(
336335
OAuth2Utils.IAM_CREDENTIALS_ALLOWED_LOCATIONS_URL_FORMAT_SERVICE_ACCOUNT,
337336
getUniverseDomain(),
@@ -342,6 +341,7 @@ int getLifetime() {
342341
return this.lifetime;
343342
}
344343

344+
345345
public void setTransportFactory(HttpTransportFactory httpTransportFactory) {
346346
this.transportFactory = httpTransportFactory;
347347
}
@@ -602,7 +602,7 @@ public AccessToken refreshAccessToken() throws IOException {
602602
Date date = format.parse(expireTime);
603603
AccessToken newAccessToken = new AccessToken(accessToken, date);
604604

605-
refreshTrustBoundaries(newAccessToken);
605+
refreshTrustBoundary(newAccessToken, getTrustBoundaryUrl(), transportFactory);
606606

607607
return newAccessToken;
608608
} catch (ParseException pe) {

oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@
8989
* <p>By default uses a JSON Web Token (JWT) to fetch access tokens.
9090
*/
9191
public class ServiceAccountCredentials extends GoogleCredentials
92-
implements ServiceAccountSigner, IdTokenProvider, JwtProvider, TrustBoundaryProvider {
92+
implements ServiceAccountSigner, IdTokenProvider, JwtProvider {
9393

9494
private static final long serialVersionUID = 7807543542681217978L;
9595
private static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
@@ -582,7 +582,7 @@ public AccessToken refreshAccessToken() throws IOException {
582582
long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000L;
583583
AccessToken newAccessToken = new AccessToken(accessToken, new Date(expiresAtMilliseconds));
584584

585-
refreshTrustBoundaries(newAccessToken);
585+
refreshTrustBoundary(newAccessToken, getTrustBoundaryUrl(), transportFactory);
586586

587587
return newAccessToken;
588588
}
@@ -823,13 +823,12 @@ public boolean getUseJwtAccessWithScope() {
823823
return useJwtAccessWithScope;
824824
}
825825

826-
@Override
827-
public HttpTransportFactory getTransportFactory() {
828-
return transportFactory;
829-
}
826+
@Override
827+
Boolean supportsTrustBoundary() {
828+
return true;
829+
}
830830

831-
@Override
832-
public String getTrustBoundaryUrl() throws IOException {
831+
String getTrustBoundaryUrl() throws IOException {
833832
return String.format(
834833
OAuth2Utils.IAM_CREDENTIALS_ALLOWED_LOCATIONS_URL_FORMAT_SERVICE_ACCOUNT,
835834
getUniverseDomain(),

oauth2_http/java/com/google/auth/oauth2/TrustBoundary.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
import com.google.auth.http.HttpTransportFactory;
4747
import com.google.common.annotations.VisibleForTesting;
4848
import com.google.common.base.MoreObjects;
49+
import com.google.common.base.Preconditions;
4950
import java.io.IOException;
5051
import java.util.Collections;
5152
import java.util.Date;
@@ -168,9 +169,7 @@ static TrustBoundary refresh(
168169
AccessToken accessToken,
169170
@Nullable TrustBoundary cachedTrustBoundary)
170171
throws IOException {
171-
if (accessToken == null) {
172-
throw new IllegalArgumentException("The provided access token is null.");
173-
}
172+
Preconditions.checkNotNull(accessToken, "The provided access token is null.");
174173
if (accessToken.getExpirationTime() != null
175174
&& accessToken.getExpirationTime().before(new Date())) {
176175
throw new IllegalArgumentException("The provided access token is expired.");
@@ -213,7 +212,8 @@ static TrustBoundary refresh(
213212
}
214213
String encodedLocations = json.getEncodedLocations();
215214
if (encodedLocations == null) {
216-
throw new IOException("TrustBoundary: Malformed response from lookup endpoint.");
215+
throw new IOException(
216+
"TrustBoundary: Malformed response from lookup endpoint - `encodedLocations` was null.");
217217
}
218218
return new TrustBoundary(encodedLocations, json.getLocations());
219219
}

oauth2_http/java/com/google/auth/oauth2/TrustBoundaryProvider.java

Lines changed: 0 additions & 47 deletions
This file was deleted.

oauth2_http/javatests/com/google/auth/oauth2/ComputeEngineCredentialsTest.java

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,11 @@ public class ComputeEngineCredentialsTest extends BaseSerializationTest {
129129
})
130130
.collect(Collectors.toMap(data -> data[0], data -> data[1]));
131131

132+
@After
133+
public void tearDown() {
134+
TrustBoundary.setEnvironmentProviderForTest(null);
135+
}
136+
132137
@Test
133138
public void buildTokenUrlWithScopes_null_scopes() {
134139
ComputeEngineCredentials credentials =
@@ -397,7 +402,6 @@ public void getRequestMetadata_hasAccessToken() throws IOException {
397402
TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN);
398403
// verify metrics header added and other header intact
399404
Map<String, List<String>> requestHeaders = transportFactory.transport.getRequest().getHeaders();
400-
com.google.auth.oauth2.TestUtils.validateMetricsHeader(requestHeaders, "at", "mds");
401405
assertTrue(requestHeaders.containsKey("metadata-flavor"));
402406
assertTrue(requestHeaders.get("metadata-flavor").contains("Google"));
403407
}
@@ -423,11 +427,6 @@ public void getRequestMetadata_shouldInvalidateAccessTokenWhenScoped_newAccessTo
423427
TestUtils.assertNotContainsBearerToken(metadataForCopiedCredentials, ACCESS_TOKEN);
424428
}
425429

426-
@After
427-
public void tearDown() {
428-
TrustBoundary.setEnvironmentProviderForTest(null);
429-
}
430-
431430
@Test
432431
public void getRequestMetadata_missingServiceAccount_throws() {
433432
MockMetadataServerTransportFactory transportFactory = new MockMetadataServerTransportFactory();

oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,11 @@ public class GoogleCredentialsTest extends BaseSerializationTest {
102102
private static final String GOOGLE_DEFAULT_UNIVERSE = "googleapis.com";
103103
private static final String TPC_UNIVERSE = "foo.bar";
104104

105+
@After
106+
public void tearDown() {
107+
TrustBoundary.setEnvironmentProviderForTest(null);
108+
}
109+
105110
@Test
106111
public void getApplicationDefault_nullTransport_throws() throws IOException {
107112
try {
@@ -936,11 +941,6 @@ public void getCredentialInfo_impersonatedServiceAccount() throws IOException {
936941
ImpersonatedCredentialsTest.IMPERSONATED_CLIENT_EMAIL, credentialInfo.get("Principal"));
937942
}
938943

939-
@After
940-
public void tearDown() {
941-
TrustBoundary.setEnvironmentProviderForTest(null);
942-
}
943-
944944
@Test
945945
public void trustBoundary_shouldNotCallLookupEndpointWhenDisabled() throws IOException {
946946
TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider();
@@ -1079,9 +1079,8 @@ public void trustBoundary_refreshShouldThrowWhenNoValidAccessTokenIsPassed() thr
10791079
try {
10801080
credentials.getRequestMetadata();
10811081
fail("Should have thrown an IOException.");
1082-
} catch (IOException e) {
1083-
assertEquals(
1084-
"Failed to refresh trust boundary and no cached value is available.", e.getMessage());
1082+
} catch (IllegalArgumentException e) {
1083+
assertEquals("The provided access token is expired.", e.getMessage());
10851084
}
10861085
}
10871086

0 commit comments

Comments
 (0)