From 0b5fd216d8d5896ff31873da3c58b2ef9fbed2a7 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Wed, 25 Nov 2026 20:02:57 +0000 Subject: [PATCH] fix(auth): fail fast on non-default universe ServiceAccountCredentials in CAB builders and clarify Javadocs - Fails fast in ClientSideCredentialAccessBoundaryFactory.Builder.build() and DownscopedCredentials.Builder.build() when given a ServiceAccountCredentials in a non-default universe domain, since Credential Access Boundaries require an OAuth 2.0 access token rather than a self-signed JWT. - Aligns ClientSideCredentialAccessBoundaryFactory.Builder whitespace-only universeDomain normalization and @Nullable annotation with DownscopedCredentials.Builder. - Consolidates CAB and OAuth2CredentialsWithRefresh Javadocs for non-default universe usage and adds CAB builder and fail-closed unit tests. --- ...ntSideCredentialAccessBoundaryFactory.java | 67 ++++++-- ...deCredentialAccessBoundaryFactoryTest.java | 161 ++++++++++++++++++ .../auth/oauth2/DownscopedCredentials.java | 36 +++- .../oauth2/OAuth2CredentialsWithRefresh.java | 18 +- .../oauth2/DownscopedCredentialsTest.java | 159 ++++++++++++++++- 5 files changed, 419 insertions(+), 22 deletions(-) diff --git a/google-auth-library-java/cab-token-generator/java/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactory.java b/google-auth-library-java/cab-token-generator/java/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactory.java index 9fbb02d056ee..080989a28d50 100644 --- a/google-auth-library-java/cab-token-generator/java/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactory.java +++ b/google-auth-library-java/cab-token-generator/java/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactory.java @@ -47,6 +47,7 @@ import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.OAuth2CredentialsWithRefresh; import com.google.auth.oauth2.OAuth2Utils; +import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.auth.oauth2.StsRequestHandler; import com.google.auth.oauth2.StsTokenExchangeRequest; import com.google.auth.oauth2.StsTokenExchangeResponse; @@ -97,11 +98,15 @@ * the upper bound of permissions that the credential can access. You must also provide a source * credential which will be used to acquire the downscoped credential. * - *

The factory can be configured with options such as the {@code refreshMargin} and {@code - * minimumTokenLifetime}. The {@code refreshMargin} controls how far in advance of the underlying - * credentials' expiry a refresh is attempted. The {@code minimumTokenLifetime} ensures that - * generated tokens have a minimum usable lifespan. See the {@link Builder} class for more details - * on these options. + *

On the first call to {@link #generateToken(CredentialAccessBoundary)}, and whenever the cached + * intermediate access token approaches expiry, this factory refreshes the source credential and + * exchanges it with the Security Token Service (STS) for an intermediate access token and an access + * boundary session key. Each {@link #generateToken(CredentialAccessBoundary)} call then locally + * serializes and encrypts the {@link CredentialAccessBoundary} rules with that session key and + * appends them to the intermediate token, returning an {@link AccessToken} whose expiration matches + * the intermediate token. The {@code refreshMargin} and {@code minimumTokenLifetime} options + * control when the cached intermediate token is refreshed asynchronously or synchronously. See the + * {@link Builder} class for more details on these options. * *

Usage: * @@ -134,9 +139,15 @@ * System.out.printf("Blob %s retrieved.", blob.getBlobId()); * * - * Note that {@link OAuth2CredentialsWithRefresh} can instead be used to consume the downscoped - * token, allowing for automatic token refreshes by providing a {@link - * OAuth2CredentialsWithRefresh.OAuth2RefreshHandler}. + *

For automatic token refreshes, consume the downscoped token with {@link + * OAuth2CredentialsWithRefresh} and an {@link OAuth2CredentialsWithRefresh.OAuth2RefreshHandler} + * that obtains a fresh token from {@link #generateToken(CredentialAccessBoundary)} (typically via a + * token broker, or directly in-process by wrapping checked exceptions in {@link IOException}). When + * operating in a non-default universe domain, configure {@link + * OAuth2CredentialsWithRefresh.Builder#setUniverseDomain(String)} for automatic refreshes, or wrap + * a single token with {@link GoogleCredentials#create(String, AccessToken)} (which does not + * auto-refresh and throws {@link IllegalStateException} from {@code refreshAccessToken()}, so + * callers must obtain a new token and create a new credential before expiry). */ @NullMarked public class ClientSideCredentialAccessBoundaryFactory { @@ -181,6 +192,13 @@ private ClientSideCredentialAccessBoundaryFactory(Builder builder) { /** * Generates a downscoped access token given the {@link CredentialAccessBoundary}. * + *

If no intermediate access token is cached, or if its remaining lifetime is within {@code + * refreshMargin} or {@code minimumTokenLifetime}, this method refreshes the source credential and + * exchanges it at the STS endpoint ({@code https://sts./v1/token}) for an + * intermediate access token and session key. It then locally serializes and encrypts {@code + * accessBoundary} with that session key and appends it to the intermediate token. The returned + * {@link AccessToken} shares the expiration time of the intermediate token. + * * @param accessBoundary The credential access boundary that defines the restrictions for the * generated CAB token. * @return The downscoped access token in an {@link AccessToken} object @@ -616,6 +634,14 @@ private Builder() {} /** * Sets the required source credential. * + *

In non-default universe domains, {@link ServiceAccountCredentials} cannot be used directly + * because Credential Access Boundaries require an OAuth 2.0 access token (see Create + * a downscoped short-lived credential) and service account OAuth2 token refresh is only + * supported in {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. Wrap the service account in {@code + * ImpersonatedCredentials}, or use credentials such as {@code ComputeEngineCredentials} or + * {@code ExternalAccountCredentials}. + * * @param sourceCredential the {@code GoogleCredentials} to set. This is a * required parameter. * @return this {@code Builder} object for chaining. @@ -698,7 +724,7 @@ public Builder setHttpTransportFactory(HttpTransportFactory transportFactory) { * @return this {@code Builder} object */ @CanIgnoreReturnValue - public Builder setUniverseDomain(String universeDomain) { + public Builder setUniverseDomain(@Nullable String universeDomain) { this.universeDomain = universeDomain; return this; } @@ -721,8 +747,10 @@ public Builder setClock(Clock clock) { * @return A new {@code ClientSideCredentialAccessBoundaryFactory} instance. * @throws IllegalStateException if the builder is not properly configured (e.g., if the source * credential is not set). - * @throws IllegalArgumentException if the refresh margin is not at least one minute longer than - * the minimum token lifetime. + * @throws IllegalArgumentException if the universe domain does not match the source credential, + * if a {@link ServiceAccountCredentials} is used directly in a non-default universe domain, + * or if the refresh margin is not at least one minute longer than the minimum token + * lifetime. */ public ClientSideCredentialAccessBoundaryFactory build() { checkNotNull(sourceCredential, "Source credential must not be null."); @@ -734,7 +762,7 @@ public ClientSideCredentialAccessBoundaryFactory build() { } // Default to GDU when not supplied. - if (Strings.isNullOrEmpty(universeDomain)) { + if (universeDomain == null || universeDomain.trim().isEmpty()) { this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE; } @@ -751,6 +779,21 @@ public ClientSideCredentialAccessBoundaryFactory build() { "Error occurred when attempting to retrieve source credential universe domain.", e); } + // Credential Access Boundaries require a Google-issued OAuth 2.0 access token, not a + // self-signed JWT + // (https://cloud.google.com/iam/docs/create-downscoped-short-lived-credentials#before-you-begin). + if (!Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain) + && sourceCredential instanceof ServiceAccountCredentials) { + throw new IllegalArgumentException( + String.format( + "ServiceAccountCredentials cannot be used directly as a source credential for" + + " ClientSideCredentialAccessBoundaryFactory in universe domain %s because" + + " OAuth2 access token refresh is only supported in %s. Wrap the service" + + " account in ImpersonatedCredentials, or use credentials such as" + + " ComputeEngineCredentials or ExternalAccountCredentials instead.", + universeDomain, Credentials.GOOGLE_DEFAULT_UNIVERSE)); + } + // Use default values for refreshMargin if not provided. if (refreshMargin == null) { this.refreshMargin = DEFAULT_REFRESH_MARGIN; diff --git a/google-auth-library-java/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java b/google-auth-library-java/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java index 7da107f4a9cd..8dba36537399 100644 --- a/google-auth-library-java/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java +++ b/google-auth-library-java/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java @@ -35,10 +35,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.Clock; import com.google.auth.Credentials; @@ -51,10 +54,13 @@ import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.CredentialAccessBoundary; import com.google.auth.oauth2.GoogleCredentials; +import com.google.auth.oauth2.ImpersonatedCredentials; +import com.google.auth.oauth2.MockIAMCredentialsServiceTransport; import com.google.auth.oauth2.MockStsTransport; import com.google.auth.oauth2.MockTokenServerTransportFactory; import com.google.auth.oauth2.OAuth2Utils; import com.google.auth.oauth2.ServiceAccountCredentials; +import com.google.auth.oauth2.UserCredentials; import com.google.common.collect.ImmutableList; import com.google.crypto.tink.Aead; import com.google.crypto.tink.InsecureSecretKeyAccess; @@ -66,7 +72,10 @@ import java.io.IOException; import java.security.GeneralSecurityException; import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.Base64; +import java.util.Collections; import java.util.Date; import java.util.Map; import java.util.concurrent.CountDownLatch; @@ -175,6 +184,158 @@ void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOException assertEquals(String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), url); } + @Test + void fetchIntermediateCredentials_impersonatedNonDefaultUniverseServiceAccount_succeeds() + throws IOException { + String universeDomain = "example.com"; + String targetPrincipal = "target@example.iam.gserviceaccount.com"; + String expectedIamEndpoint = + String.format( + "https://iamcredentials.%s/v1/projects/-/serviceAccounts/%s:generateAccessToken", + universeDomain, targetPrincipal); + + MockIAMCredentialsServiceTransport iamTransport = new MockIAMCredentialsServiceTransport(); + iamTransport.setTargetPrincipal(targetPrincipal); + iamTransport.setAccessTokenEndpoint(expectedIamEndpoint); + iamTransport.setAccessToken("impersonated-access-token"); + iamTransport.setExpireTime( + Instant.now().plusSeconds(3600).truncatedTo(ChronoUnit.SECONDS).toString()); + iamTransport.addStatusCodeAndMessage(HttpStatusCodes.STATUS_CODE_OK, ""); + + GoogleCredentials sourceSa = + getServiceAccountSourceCredentials(mockTokenServerTransportFactory).toBuilder() + .setUniverseDomain(universeDomain) + .build(); + ImpersonatedCredentials impersonatedCredentials = + ImpersonatedCredentials.newBuilder() + .setSourceCredentials(sourceSa) + .setTargetPrincipal(targetPrincipal) + .setScopes(Collections.singletonList(OAuth2Utils.CLOUD_PLATFORM_SCOPE)) + .setHttpTransportFactory(() -> iamTransport) + .build(); + + ClientSideCredentialAccessBoundaryFactory factory = + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setUniverseDomain(universeDomain) + .setSourceCredential(impersonatedCredentials) + .setHttpTransportFactory(mockStsTransportFactory) + .build(); + + IntermediateCredentials intermediateCredentials = factory.fetchIntermediateCredentials(); + + assertEquals( + mockStsTransportFactory.transport.getAccessToken(), + intermediateCredentials.getIntermediateAccessToken().getTokenValue()); + assertEquals( + String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), + mockStsTransportFactory.transport.getRequest().getUrl()); + assertNotNull(iamTransport.getRequest()); + assertEquals(expectedIamEndpoint, iamTransport.getRequest().getUrl()); + assertNull(mockTokenServerTransportFactory.transport.getRequest()); + } + + @Test + void builder_whitespaceUniverseDomain_defaultsToGoogleDefaultUniverse() throws IOException { + GoogleCredentials sourceCredentials = + getServiceAccountSourceCredentials(mockTokenServerTransportFactory); + + ClientSideCredentialAccessBoundaryFactory factory = + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setUniverseDomain(" ") + .setSourceCredential(sourceCredentials) + .setHttpTransportFactory(mockStsTransportFactory) + .build(); + + assertEquals( + String.format(TOKEN_EXCHANGE_URL_FORMAT, Credentials.GOOGLE_DEFAULT_UNIVERSE), + factory.getTokenExchangeEndpoint()); + } + + @Test + void builder_nonDefaultUniverseServiceAccount_throws() throws IOException { + String universeDomain = "example.com"; + GoogleCredentials sourceCredentials = + getServiceAccountSourceCredentials(mockTokenServerTransportFactory).toBuilder() + .setUniverseDomain(universeDomain) + .build(); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setUniverseDomain(universeDomain) + .setSourceCredential(sourceCredentials) + .setHttpTransportFactory(mockStsTransportFactory) + .build()); + + assertTrue(error.getMessage().contains("ServiceAccountCredentials")); + assertTrue(error.getMessage().contains("ImpersonatedCredentials")); + assertNull(mockTokenServerTransportFactory.transport.getRequest()); + assertEquals(0, mockStsTransportFactory.transport.getRequestCount()); + } + + @Test + void fetchIntermediateCredentials_wrappedNonDefaultUniverseServiceAccount_failsClosed() + throws IOException { + String universeDomain = "example.com"; + GoogleCredentials delegate = + getServiceAccountSourceCredentials(mockTokenServerTransportFactory).toBuilder() + .setUniverseDomain(universeDomain) + .build(); + GoogleCredentials wrapped = + new GoogleCredentials(GoogleCredentials.newBuilder().setUniverseDomain(universeDomain)) { + @Override + public AccessToken refreshAccessToken() throws IOException { + return delegate.refreshAccessToken(); + } + }; + + ClientSideCredentialAccessBoundaryFactory factory = + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setUniverseDomain(universeDomain) + .setSourceCredential(wrapped) + .setHttpTransportFactory(mockStsTransportFactory) + .build(); + + IOException error = assertThrows(IOException.class, factory::fetchIntermediateCredentials); + assertEquals("Unable to refresh the provided source credential.", error.getMessage()); + assertNotNull(error.getCause()); + assertTrue(error.getCause().getMessage().contains(universeDomain)); + assertNull(mockTokenServerTransportFactory.transport.getRequest()); + assertEquals(0, mockStsTransportFactory.transport.getRequestCount()); + } + + @Test + void fetchIntermediateCredentials_nonDefaultUniverseUserCredentials_failsClosed() { + MockTokenServerTransportFactory tokenTransportFactory = new MockTokenServerTransportFactory(); + tokenTransportFactory.transport.addClient("test-client-id", "test-client-secret"); + tokenTransportFactory.transport.addRefreshToken("test-refresh-token", "test-access-token"); + + GoogleCredentials sourceCredentials = + UserCredentials.newBuilder() + .setClientId("test-client-id") + .setClientSecret("test-client-secret") + .setRefreshToken("test-refresh-token") + .setHttpTransportFactory(tokenTransportFactory) + .setUniverseDomain("example.com") + .build(); + + ClientSideCredentialAccessBoundaryFactory factory = + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setUniverseDomain("example.com") + .setSourceCredential(sourceCredentials) + .setHttpTransportFactory(mockStsTransportFactory) + .build(); + + IOException error = assertThrows(IOException.class, factory::fetchIntermediateCredentials); + assertEquals("Unable to refresh the provided source credential.", error.getMessage()); + assertNotNull(error.getCause()); + assertTrue(error.getCause().getMessage().contains("example.com")); + assertNull(tokenTransportFactory.transport.getRequest()); + assertEquals(0, mockStsTransportFactory.transport.getRequestCount()); + } + @Test void fetchIntermediateCredentials_sourceCredentialCannotRefresh_throwsIOException() throws Exception { diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/DownscopedCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/DownscopedCredentials.java index c7a0f4c16a1b..dc449fb5def5 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/DownscopedCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/DownscopedCredentials.java @@ -94,9 +94,16 @@ * System.out.printf("Blob %s retrieved.", blob.getBlobId()); * * - * Note that {@link OAuth2CredentialsWithRefresh} can instead be used to consume the downscoped - * token, allowing for automatic token refreshes by providing a {@link - * OAuth2CredentialsWithRefresh.OAuth2RefreshHandler}. + *

When passing downscoped tokens from a token broker to a separate consumer that needs automatic + * refreshes, consume the token with {@link OAuth2CredentialsWithRefresh} and an {@link + * OAuth2CredentialsWithRefresh.OAuth2RefreshHandler} that requests a fresh token from the broker + * (backed by {@link #refreshAccessToken()}). When operating in a non-default universe domain, + * configure {@link OAuth2CredentialsWithRefresh.Builder#setUniverseDomain(String)} for automatic + * refreshes, or wrap a single token with {@link GoogleCredentials#create(String, AccessToken)} + * (which does not auto-refresh and throws {@link IllegalStateException} from {@code + * refreshAccessToken()}, so callers must obtain a new token and create a new credential before + * expiry). Callers running in the same process can also use {@code DownscopedCredentials} directly, + * as it automatically refreshes tokens and preserves the configured universe domain. */ @NullMarked public final class DownscopedCredentials extends OAuth2Credentials { @@ -141,6 +148,21 @@ private DownscopedCredentials(Builder builder) { throw new IllegalStateException( "Error occurred when attempting to retrieve source credential universe domain.", e); } + + // Credential Access Boundaries require a Google-issued OAuth 2.0 access token, not a + // self-signed JWT + // (https://cloud.google.com/iam/docs/create-downscoped-short-lived-credentials#before-you-begin). + if (!Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(this.universeDomain) + && this.sourceCredential instanceof ServiceAccountCredentials) { + throw new IllegalArgumentException( + String.format( + "ServiceAccountCredentials cannot be used directly as a source credential for" + + " DownscopedCredentials in universe domain %s because OAuth2 access token" + + " refresh is only supported in %s. Wrap the service account in" + + " ImpersonatedCredentials, or use credentials such as ComputeEngineCredentials" + + " or ExternalAccountCredentials instead.", + this.universeDomain, Credentials.GOOGLE_DEFAULT_UNIVERSE)); + } this.tokenExchangeEndpoint = String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain); } @@ -251,6 +273,14 @@ private Builder() {} /** * Sets the required source credential used to acquire the downscoped credential. * + *

In non-default universe domains, {@link ServiceAccountCredentials} cannot be used directly + * because Credential Access Boundaries require an OAuth 2.0 access token (see Create + * a downscoped short-lived credential) and service account OAuth2 token refresh is only + * supported in {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. Wrap the service account in {@link + * ImpersonatedCredentials}, or use credentials such as {@link ComputeEngineCredentials} or + * {@link ExternalAccountCredentials}. + * * @param sourceCredential the {@code GoogleCredentials} to set * @return this {@code Builder} object */ diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java index d8ab23c92aec..d629495e943f 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java @@ -45,13 +45,25 @@ /** * A refreshable alternative to {@link OAuth2Credentials}. * - *

To enable automatic token refreshes, you must provide an {@link OAuth2RefreshHandler}. + *

Wraps an expiring {@link AccessToken} and automatically invokes the configured {@link + * OAuth2RefreshHandler} to fetch a new token when the current token nears expiry (for example, from + * a token broker issuing downscoped tokens). * *

Because {@link OAuth2RefreshHandler} returns {@link AccessToken} values without universe * domain metadata, credentials default to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. Callers * refreshing tokens for a custom universe domain should configure it explicitly via {@link - * Builder#setUniverseDomain(String)}. If lazy or delegated universe domain resolution is needed, - * subclass this class and override {@link #getUniverseDomain()}. + * Builder#setUniverseDomain(String)}. + * + *

Usage: + * + *

{@code
+ * OAuth2CredentialsWithRefresh credentials =
+ *     OAuth2CredentialsWithRefresh.newBuilder()
+ *         .setAccessToken(accessToken)
+ *         .setUniverseDomain(universeDomain) // optional, defaults to googleapis.com
+ *         .setRefreshHandler(this::fetchRefreshedAccessToken)
+ *         .build();
+ * }
*/ @NullMarked public class OAuth2CredentialsWithRefresh extends OAuth2Credentials { diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java index 258e362ea0c5..01df18547c5e 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java @@ -35,12 +35,18 @@ import static com.google.auth.oauth2.OAuth2Utils.TOKEN_EXCHANGE_URL_FORMAT; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpTransport; import com.google.auth.TestUtils; import com.google.auth.http.HttpTransportFactory; import java.io.IOException; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Collections; import java.util.Date; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -192,6 +198,148 @@ void refreshAccessToken_withCustomUniverseDomain() throws IOException { assertEquals(String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), url); } + @Test + void refreshAccessToken_impersonatedNonDefaultUniverseServiceAccount_succeeds() + throws IOException { + String universeDomain = "example.com"; + String targetPrincipal = "target@example.iam.gserviceaccount.com"; + MockTokenServerTransportFactory tokenTransportFactory = new MockTokenServerTransportFactory(); + MockStsTransportFactory stsTransportFactory = new MockStsTransportFactory(); + + MockIAMCredentialsServiceTransportFactory iamTransportFactory = + new MockIAMCredentialsServiceTransportFactory(universeDomain); + iamTransportFactory.getTransport().setTargetPrincipal(targetPrincipal); + iamTransportFactory.getTransport().setAccessToken("impersonated-access-token"); + iamTransportFactory + .getTransport() + .setExpireTime(Instant.now().plusSeconds(3600).truncatedTo(ChronoUnit.SECONDS).toString()); + iamTransportFactory.getTransport().addStatusCodeAndMessage(HttpStatusCodes.STATUS_CODE_OK, ""); + + GoogleCredentials sourceSa = + getServiceAccountSourceCredentials(tokenTransportFactory).toBuilder() + .setUniverseDomain(universeDomain) + .build(); + ImpersonatedCredentials impersonatedCredentials = + ImpersonatedCredentials.newBuilder() + .setSourceCredentials(sourceSa) + .setTargetPrincipal(targetPrincipal) + .setScopes(Collections.singletonList(OAuth2Utils.CLOUD_PLATFORM_SCOPE)) + .setHttpTransportFactory(iamTransportFactory) + .build(); + + DownscopedCredentials downscopedCredentials = + DownscopedCredentials.newBuilder() + .setSourceCredential(impersonatedCredentials) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(stsTransportFactory) + .setUniverseDomain(universeDomain) + .build(); + + AccessToken accessToken = downscopedCredentials.refreshAccessToken(); + + assertEquals(stsTransportFactory.transport.getAccessToken(), accessToken.getTokenValue()); + assertEquals( + String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), + stsTransportFactory.transport.getRequest().getUrl()); + assertNotNull(iamTransportFactory.getTransport().getRequest()); + assertTrue( + iamTransportFactory + .getTransport() + .getRequest() + .getUrl() + .startsWith("https://iamcredentials." + universeDomain + "/")); + assertEquals(0, tokenTransportFactory.transport.buildRequestCount); + assertNull(tokenTransportFactory.transport.getRequest()); + } + + @Test + void builder_nonDefaultUniverseServiceAccount_throws() throws IOException { + MockTokenServerTransportFactory tokenTransportFactory = new MockTokenServerTransportFactory(); + GoogleCredentials sourceCredentials = + getServiceAccountSourceCredentials(tokenTransportFactory).toBuilder() + .setUniverseDomain("example.com") + .build(); + + DownscopedCredentials.Builder builder = + DownscopedCredentials.newBuilder() + .setSourceCredential(sourceCredentials) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setUniverseDomain("example.com"); + + IllegalArgumentException error = assertThrows(IllegalArgumentException.class, builder::build); + assertTrue(error.getMessage().contains("ServiceAccountCredentials")); + assertTrue(error.getMessage().contains("ImpersonatedCredentials")); + assertEquals(0, tokenTransportFactory.transport.buildRequestCount); + assertNull(tokenTransportFactory.transport.getRequest()); + } + + @Test + void refreshAccessToken_wrappedNonDefaultUniverseServiceAccount_failsClosed() throws IOException { + MockStsTransportFactory stsTransportFactory = new MockStsTransportFactory(); + MockTokenServerTransportFactory tokenTransportFactory = new MockTokenServerTransportFactory(); + String universeDomain = "example.com"; + GoogleCredentials delegate = + getServiceAccountSourceCredentials(tokenTransportFactory).toBuilder() + .setUniverseDomain(universeDomain) + .build(); + GoogleCredentials wrapped = + new GoogleCredentials(GoogleCredentials.newBuilder().setUniverseDomain(universeDomain)) { + @Override + public AccessToken refreshAccessToken() throws IOException { + return delegate.refreshAccessToken(); + } + }; + + DownscopedCredentials downscopedCredentials = + DownscopedCredentials.newBuilder() + .setSourceCredential(wrapped) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(stsTransportFactory) + .setUniverseDomain(universeDomain) + .build(); + + IOException error = assertThrows(IOException.class, downscopedCredentials::refreshAccessToken); + assertEquals("Unable to refresh the provided source credential.", error.getMessage()); + assertNotNull(error.getCause()); + assertTrue(error.getCause().getMessage().contains(universeDomain)); + assertEquals(0, tokenTransportFactory.transport.buildRequestCount); + assertNull(tokenTransportFactory.transport.getRequest()); + assertEquals(0, stsTransportFactory.transport.getRequestCount()); + } + + @Test + void refreshAccessToken_nonDefaultUniverseUserCredentials_failsClosed() { + MockStsTransportFactory stsTransportFactory = new MockStsTransportFactory(); + MockTokenServerTransportFactory tokenTransportFactory = new MockTokenServerTransportFactory(); + tokenTransportFactory.transport.addClient("test-client-id", "test-client-secret"); + tokenTransportFactory.transport.addRefreshToken("test-refresh-token", "test-access-token"); + + GoogleCredentials sourceCredentials = + UserCredentials.newBuilder() + .setClientId("test-client-id") + .setClientSecret("test-client-secret") + .setRefreshToken("test-refresh-token") + .setHttpTransportFactory(tokenTransportFactory) + .setUniverseDomain("example.com") + .build(); + + DownscopedCredentials downscopedCredentials = + DownscopedCredentials.newBuilder() + .setSourceCredential(sourceCredentials) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(stsTransportFactory) + .setUniverseDomain("example.com") + .build(); + + IOException error = assertThrows(IOException.class, downscopedCredentials::refreshAccessToken); + assertEquals("Unable to refresh the provided source credential.", error.getMessage()); + assertNotNull(error.getCause()); + assertTrue(error.getCause().getMessage().contains("example.com")); + assertEquals(0, tokenTransportFactory.transport.buildRequestCount); + assertNull(tokenTransportFactory.transport.getRequest()); + assertEquals(0, stsTransportFactory.transport.getRequestCount()); + } + @Test void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IOException { // STS only returns expires_in if the source access token belongs to a service account. @@ -326,7 +474,14 @@ void builder_sourceUniverseDomainUnavailable_throws() { private static GoogleCredentials getServiceAccountSourceCredentials(boolean canRefresh) throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); + if (!canRefresh) { + transportFactory.transport.setError(new IOException()); + } + return getServiceAccountSourceCredentials(transportFactory); + } + private static GoogleCredentials getServiceAccountSourceCredentials( + MockTokenServerTransportFactory transportFactory) throws IOException { String email = "service-account@google.com"; ServiceAccountCredentials sourceCredentials = @@ -340,10 +495,6 @@ private static GoogleCredentials getServiceAccountSourceCredentials(boolean canR transportFactory.transport.addServiceAccount(email, "accessToken"); - if (!canRefresh) { - transportFactory.transport.setError(new IOException()); - } - return sourceCredentials.createScoped(OAuth2Utils.CLOUD_PLATFORM_SCOPE); }