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 05de36c05694..f9bea5706bd8 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,9 +47,11 @@ 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; +import com.google.auth.oauth2.UserCredentials; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.util.concurrent.AbstractFuture; @@ -97,11 +99,16 @@ * 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 - * ClientSideCredentialAccessBoundaryFactory.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 ClientSideCredentialAccessBoundaryFactory.Builder} class for more details on these + * options. * *

Usage: * @@ -134,9 +141,17 @@ * 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, this factory inherits the universe domain from the + * source credential by default (or validates it against {@link Builder#setUniverseDomain(String)} + * when explicitly set). On the consumer side, 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 +196,16 @@ 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 + * minimumTokenLifetime}, this method synchronously refreshes the source credential and exchanges + * it at the STS endpoint ({@code https://sts./v1/token}) for a new intermediate + * access token and session key before generating the token. If the remaining lifetime is between + * {@code minimumTokenLifetime} and {@code refreshMargin}, it starts an asynchronous background + * refresh and uses the currently cached intermediate token and session key for this call. It then + * locally serializes and encrypts {@code accessBoundary} with the active session key and appends + * it to the intermediate token. The returned {@link AccessToken} shares the expiration time of + * that 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 @@ -605,7 +630,7 @@ public static Builder newBuilder() { public static class Builder { private GoogleCredentials sourceCredential; private HttpTransportFactory transportFactory; - private String universeDomain; + private @Nullable String universeDomain; private String tokenExchangeEndpoint; private Duration minimumTokenLifetime; private Duration refreshMargin; @@ -616,6 +641,18 @@ 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}. {@link UserCredentials} are also + * only supported in {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. Wrap a service account in + * {@link com.google.auth.oauth2.ImpersonatedCredentials ImpersonatedCredentials}, or use + * credentials such as {@link com.google.auth.oauth2.ComputeEngineCredentials + * ComputeEngineCredentials} or {@link com.google.auth.oauth2.ExternalAccountCredentials + * ExternalAccountCredentials} (for Workforce Identity Federation, service account impersonation + * must be configured). + * * @param sourceCredential the {@code GoogleCredentials} to set. This is a * required parameter. * @return this {@code Builder} object for chaining. @@ -693,13 +730,18 @@ public Builder setHttpTransportFactory(HttpTransportFactory transportFactory) { } /** - * Sets the optional universe domain. + * Sets an optional expected universe domain. + * + *

When omitted, {@code null}, or blank, the universe domain is inherited from the source + * credential. When explicitly set, {@link #build()} validates that it matches the source + * credential's universe domain. * - * @param universeDomain the universe domain to set + * @param universeDomain the expected universe domain, or {@code null} to inherit from the + * source credential * @return this {@code Builder} object */ @CanIgnoreReturnValue - public Builder setUniverseDomain(String universeDomain) { + public Builder setUniverseDomain(@Nullable String universeDomain) { this.universeDomain = universeDomain; return this; } @@ -720,10 +762,14 @@ public Builder setClock(Clock clock) { * builder configuration. * * @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 NullPointerException if {@code sourceCredential} is not set. + * @throws IllegalStateException if the source credential's universe domain cannot be retrieved + * or Tink AEAD registration fails. + * @throws IllegalArgumentException if the source credential's universe domain is {@code null} + * or blank, if an explicitly configured universe domain does not match the source + * credential, if a {@link ServiceAccountCredentials} or {@link UserCredentials} 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,22 +780,61 @@ public ClientSideCredentialAccessBoundaryFactory build() { getFromServiceLoader(HttpTransportFactory.class, OAuth2Utils.HTTP_TRANSPORT_FACTORY); } - // Default to GDU when not supplied. - if (Strings.isNullOrEmpty(universeDomain)) { - this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE; + String sourceUniverseDomain; + try { + sourceUniverseDomain = sourceCredential.getUniverseDomain(); + } catch (IOException e) { + // Throwing an IOException would be a breaking change, so wrap it here. + throw new IllegalStateException( + "Error occurred when attempting to retrieve source credential universe domain.", e); } - // Ensure source credential's universe domain matches. - try { - if (!universeDomain.equals(sourceCredential.getUniverseDomain())) { + if (sourceUniverseDomain == null || sourceUniverseDomain.trim().isEmpty()) { + throw new IllegalArgumentException( + "The source credential's universe domain must not be null or empty."); + } + + String resolvedUniverseDomain; + if (universeDomain == null || universeDomain.trim().isEmpty()) { + // Inherit the source credential's universe domain when not explicitly supplied. + resolvedUniverseDomain = sourceUniverseDomain; + } else { + // Validate explicit universe domain against the source credential. + if (!universeDomain.equals(sourceUniverseDomain)) { throw new IllegalArgumentException( "The client side access boundary credential's universe domain must be the same as the source " + "credential."); } - } catch (IOException e) { - // Throwing an IOException would be a breaking change, so wrap it here. - throw new IllegalStateException( - "Error occurred when attempting to retrieve source credential universe domain.", e); + resolvedUniverseDomain = universeDomain; + } + + if (!Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(resolvedUniverseDomain)) { + // Credential Access Boundaries require a Google-issued OAuth 2.0 access token, not a + // self-signed JWT + // (https://docs.cloud.google.com/iam/docs/create-downscoped-short-lived-credentials#before-you-begin). + if (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 (for Workforce" + + " Identity Federation, service account impersonation must be configured)" + + " instead.", + resolvedUniverseDomain, Credentials.GOOGLE_DEFAULT_UNIVERSE)); + } + if (sourceCredential instanceof UserCredentials) { + throw new IllegalArgumentException( + String.format( + "UserCredentials cannot be used as a source credential for" + + " ClientSideCredentialAccessBoundaryFactory in universe domain %s because" + + " UserCredentials are only supported in %s. Use credentials such as" + + " ImpersonatedCredentials, ComputeEngineCredentials, or" + + " ExternalAccountCredentials (for Workforce Identity Federation, service" + + " account impersonation must be configured) instead.", + resolvedUniverseDomain, Credentials.GOOGLE_DEFAULT_UNIVERSE)); + } } // Use default values for refreshMargin if not provided. @@ -769,7 +854,7 @@ public ClientSideCredentialAccessBoundaryFactory build() { "Refresh margin must be at least one minute longer than the minimum token lifetime."); } - this.tokenExchangeEndpoint = String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain); + this.tokenExchangeEndpoint = String.format(TOKEN_EXCHANGE_URL_FORMAT, resolvedUniverseDomain); return new ClientSideCredentialAccessBoundaryFactory(this); } } 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 741aa982e930..0ef1bbc8f6ae 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 @@ -40,6 +40,7 @@ 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.http.LowLevelHttpRequest; import com.google.api.client.util.Clock; @@ -53,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; @@ -68,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; @@ -89,6 +96,11 @@ class ClientSideCredentialAccessBoundaryFactoryTest { + "4Az2ZkmeuN6Fk/y9H+Lcb2pskJIXjrL533vrDWGOC48LrsThMQPv8cxBky8HFSEklPpkfTF95tpD43iVwJRB/GrCtGTw65IfJ4/tI09h6zGc4yqvIo1cHX/LQ+SxKLGyir/dQM925rGt/VojxY5ryJR7GLbCzxPnJm/oQJBANwOCO6D2hy1LQYJhXh7O+RLtA/tSnT1xyMQsGT+uUCMiKS2bSKx2wxo9k7h3OegNJIu1q6nZ6AbxDK8H3+d0dUCQQDTrPSXagBxzp8PecbaCHjzNRSQE2in81qYnrAFNB4o3DpHyMMY6s5ALLeHKscEWnqP8Ur6X4PvzZecCWU9BKAZAkAutLPknAuxSCsUOvUfS1i87ex77Ot+w6POp34pEX+UWb+u5iFn2cQacDTHLV1LtE80L8jVLSbrbrlH43H0DjU5AkEAgidhycxS86dxpEljnOMCw8CKoUBd5I880IUahEiUltk7OLJYS/Ts1wbn3kPOVX3wyJs8WBDtBkFrDHW2ezth2QJADj3e1YhMVdjJW5jqwlD/VNddGjgzyunmiZg0uOXsHXbytYmsA545S8KRQFaJKFXYYFo2kOjqOiC1T2cAzMDjCQ==\n" + "-----END PRIVATE KEY-----\n"; + private static final HttpTransportFactory UNEXPECTED_HTTP_TRANSPORT_FACTORY = + () -> { + throw new AssertionError("Unexpected HTTP request."); + }; + private MockStsTransportFactory mockStsTransportFactory; private static MockTokenServerTransportFactory mockTokenServerTransportFactory; @@ -191,6 +203,93 @@ 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(UNEXPECTED_HTTP_TRANSPORT_FACTORY).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() + .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()); + Map stsQuery = + TestUtils.parseQuery(mockStsTransportFactory.transport.getRequest().getContentAsString()); + assertEquals("impersonated-access-token", stsQuery.get("subject_token")); + assertNotNull(iamTransport.getRequest()); + assertEquals(expectedIamEndpoint, iamTransport.getRequest().getUrl()); + } + + @Test + void fetchIntermediateCredentials_wrappedNonDefaultUniverseServiceAccount_failsClosed() + throws IOException { + String universeDomain = "example.com"; + GoogleCredentials delegate = + getServiceAccountSourceCredentials(UNEXPECTED_HTTP_TRANSPORT_FACTORY).toBuilder() + .setUniverseDomain(universeDomain) + .build(); + ClientSideCredentialAccessBoundaryFactory factory = + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setSourceCredential(wrapCredentials(universeDomain, delegate)) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .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)); + } + + @Test + void fetchIntermediateCredentials_wrappedNonDefaultUniverseUserCredentials_failsClosed() { + String universeDomain = "example.com"; + GoogleCredentials delegate = getNonDefaultUniverseUserCredentials(universeDomain); + ClientSideCredentialAccessBoundaryFactory factory = + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setSourceCredential(wrapCredentials(universeDomain, delegate)) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .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)); + } + @Test void fetchIntermediateCredentials_sourceCredentialCannotRefresh_throwsIOException() throws Exception { @@ -522,6 +621,189 @@ void builder_universeDomainMismatch_throws() throws IOException { exception.getMessage()); } + @Test + void builder_omittedUniverseDomain_inheritsSourceUniverseDomain() throws IOException { + String universeDomain = "example.com"; + GoogleCredentials sourceCredentials = getCustomUniverseSourceCredentials(universeDomain); + + ClientSideCredentialAccessBoundaryFactory factory = + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setSourceCredential(sourceCredentials) + .setHttpTransportFactory(mockStsTransportFactory) + .build(); + + assertEquals( + String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), + factory.getTokenExchangeEndpoint()); + factory.fetchIntermediateCredentials(); + assertEquals( + String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), + mockStsTransportFactory.transport.getRequest().getUrl()); + } + + @Test + void builder_nullUniverseDomain_inheritsSourceUniverseDomain() { + String universeDomain = "example.com"; + ClientSideCredentialAccessBoundaryFactory factory = + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setSourceCredential(getCustomUniverseSourceCredentials(universeDomain)) + .setUniverseDomain(null) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .build(); + + assertEquals( + String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), + factory.getTokenExchangeEndpoint()); + } + + @Test + void builder_emptyUniverseDomain_inheritsSourceUniverseDomain() { + String universeDomain = "example.com"; + ClientSideCredentialAccessBoundaryFactory factory = + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setSourceCredential(getCustomUniverseSourceCredentials(universeDomain)) + .setUniverseDomain("") + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .build(); + + assertEquals( + String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), + factory.getTokenExchangeEndpoint()); + } + + @Test + void builder_whitespaceUniverseDomain_inheritsSourceUniverseDomain() { + String universeDomain = "example.com"; + ClientSideCredentialAccessBoundaryFactory factory = + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setSourceCredential(getCustomUniverseSourceCredentials(universeDomain)) + .setUniverseDomain(" ") + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .build(); + + assertEquals( + String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), + factory.getTokenExchangeEndpoint()); + } + + @Test + void builder_explicitDefaultUniverseWithNonDefaultSource_throws() { + GoogleCredentials sourceCredentials = getCustomUniverseSourceCredentials("example.com"); + + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setSourceCredential(sourceCredentials) + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .build()); + assertEquals( + "The client side access boundary credential's universe domain must be the same as the" + + " source credential.", + exception.getMessage()); + } + + @Test + void builder_nullSourceUniverseDomain_throws() { + GoogleCredentials sourceCredentials = getSourceCredentialsReturningUniverseDomain(null); + + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setSourceCredential(sourceCredentials) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .build()); + assertEquals( + "The source credential's universe domain must not be null or empty.", + exception.getMessage()); + } + + @Test + void builder_blankSourceUniverseDomain_throws() { + GoogleCredentials sourceCredentials = getSourceCredentialsReturningUniverseDomain(" "); + + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setSourceCredential(sourceCredentials) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .build()); + assertEquals( + "The source credential's universe domain must not be null or empty.", + exception.getMessage()); + } + + @Test + void builder_sourceUniverseDomainUnavailable_throws() { + GoogleCredentials sourceCredentials = + new GoogleCredentials() { + @Override + public String getUniverseDomain() throws IOException { + throw new IOException("universe lookup failed"); + } + }; + + IllegalStateException exception = + assertThrows( + IllegalStateException.class, + () -> + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setSourceCredential(sourceCredentials) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .build()); + assertEquals( + "Error occurred when attempting to retrieve source credential universe domain.", + exception.getMessage()); + } + + @Test + void builder_nonDefaultUniverseServiceAccount_throws() throws IOException { + String universeDomain = "example.com"; + GoogleCredentials sourceCredentials = + getServiceAccountSourceCredentials(UNEXPECTED_HTTP_TRANSPORT_FACTORY).toBuilder() + .setUniverseDomain(universeDomain) + .build(); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setSourceCredential(sourceCredentials) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .build()); + + assertTrue(error.getMessage().contains("ServiceAccountCredentials")); + assertTrue(error.getMessage().contains(universeDomain)); + assertTrue(error.getMessage().contains("ImpersonatedCredentials")); + assertTrue(error.getMessage().contains("Workforce Identity Federation")); + } + + @Test + void builder_nonDefaultUniverseUserCredentials_throws() { + String universeDomain = "example.com"; + GoogleCredentials sourceCredentials = getNonDefaultUniverseUserCredentials(universeDomain); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + ClientSideCredentialAccessBoundaryFactory.newBuilder() + .setSourceCredential(sourceCredentials) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .build()); + + assertTrue(error.getMessage().contains("UserCredentials")); + assertTrue(error.getMessage().contains(universeDomain)); + assertTrue(error.getMessage().contains("Workforce Identity Federation")); + } + @Test void builder_invalidRefreshMarginAndMinimumTokenLifetime_throws() throws IOException { GoogleCredentials sourceCredentials = @@ -613,7 +895,7 @@ void builder_refreshMarginNotSet_usesDefault() throws IOException { } private static GoogleCredentials getServiceAccountSourceCredentials( - MockTokenServerTransportFactory transportFactory) throws IOException { + HttpTransportFactory transportFactory) throws IOException { String email = "service-account@google.com"; ServiceAccountCredentials sourceCredentials = @@ -639,6 +921,36 @@ public AccessToken refreshAccessToken() { }; } + private static GoogleCredentials getSourceCredentialsReturningUniverseDomain( + String universeDomain) { + return new GoogleCredentials() { + @Override + public String getUniverseDomain() { + return universeDomain; + } + }; + } + + private static GoogleCredentials getNonDefaultUniverseUserCredentials(String universeDomain) { + return UserCredentials.newBuilder() + .setClientId("test-client-id") + .setClientSecret("test-client-secret") + .setRefreshToken("test-refresh-token") + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .setUniverseDomain(universeDomain) + .build(); + } + + private static GoogleCredentials wrapCredentials( + String universeDomain, GoogleCredentials delegate) { + return new GoogleCredentials(GoogleCredentials.newBuilder().setUniverseDomain(universeDomain)) { + @Override + public AccessToken refreshAccessToken() throws IOException { + return delegate.refreshAccessToken(); + } + }; + } + private ClientSideCredentialAccessBoundaryFactory getClientSideCredentialAccessBoundaryFactory( RefreshType refreshType) throws IOException { return getClientSideCredentialAccessBoundaryFactory(refreshType, new CountDownLatch(0)); 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 af47a588a39c..2c7767212821 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 @@ -95,9 +95,18 @@ * 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, + * {@code DownscopedCredentials} inherits the universe domain from the source credential by default + * (or validates it against {@link Builder#setUniverseDomain(String)} when explicitly set). On the + * consumer side, 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 universe domain. */ @NullMarked public final class DownscopedCredentials extends OAuth2Credentials { @@ -123,26 +132,61 @@ private DownscopedCredentials(Builder builder) { this.sourceCredential = checkNotNull(builder.sourceCredential); this.credentialAccessBoundary = checkNotNull(builder.credentialAccessBoundary); - // Default to GDU when not supplied. + String sourceUniverseDomain; + try { + sourceUniverseDomain = sourceCredential.getUniverseDomain(); + } catch (IOException e) { + // Throwing an IOException would be a breaking change, so wrap it here. + throw new IllegalStateException( + "Error occurred when attempting to retrieve source credential universe domain.", e); + } + + if (sourceUniverseDomain == null || sourceUniverseDomain.trim().isEmpty()) { + throw new IllegalArgumentException( + "The source credential's universe domain must not be null or empty."); + } + if (builder.universeDomain == null || builder.universeDomain.trim().isEmpty()) { - this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE; + // Inherit the source credential's universe domain when not explicitly supplied. + this.universeDomain = sourceUniverseDomain; } else { + // Validate explicit universe domain against the source credential. + if (!builder.universeDomain.equals(sourceUniverseDomain)) { + throw new IllegalArgumentException( + "The downscoped credential's universe domain must be the same as the source " + + "credential."); + } this.universeDomain = builder.universeDomain; } - // Ensure source credential's universe domain matches. - try { - if (!this.universeDomain.equals(sourceCredential.getUniverseDomain())) { + if (!Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(this.universeDomain)) { + // Credential Access Boundaries require a Google-issued OAuth 2.0 access token, not a + // self-signed JWT + // (https://docs.cloud.google.com/iam/docs/create-downscoped-short-lived-credentials#before-you-begin). + if (this.sourceCredential instanceof ServiceAccountCredentials) { throw new IllegalArgumentException( - "The downscoped credential's universe domain must be the same as the source " - + "credential."); + 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 (for Workforce" + + " Identity Federation, service account impersonation must be configured)" + + " instead.", + this.universeDomain, Credentials.GOOGLE_DEFAULT_UNIVERSE)); + } + if (this.sourceCredential instanceof UserCredentials) { + throw new IllegalArgumentException( + String.format( + "UserCredentials cannot be used as a source credential for DownscopedCredentials in" + + " universe domain %s because UserCredentials are only supported in %s. Use" + + " credentials such as ImpersonatedCredentials, ComputeEngineCredentials, or" + + " ExternalAccountCredentials (for Workforce Identity Federation, service" + + " account impersonation must be configured) instead.", + this.universeDomain, Credentials.GOOGLE_DEFAULT_UNIVERSE)); } - } catch (IOException e) { - // Throwing an IOException would be a breaking change, so wrap it here. - throw new IllegalStateException( - "Error occurred when attempting to retrieve source credential universe domain.", e); } - this.tokenExchangeEndpoint = String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain); + this.tokenExchangeEndpoint = String.format(TOKEN_EXCHANGE_URL_FORMAT, this.universeDomain); } @Override @@ -193,8 +237,8 @@ public CredentialAccessBoundary getCredentialAccessBoundary() { /** * Returns the universe domain for the credential. * - * @return An explicit universe domain if it was explicitly provided, otherwise the default Google - * universe will be returned. + * @return the universe domain inherited from the source credential (or validated against the + * explicitly configured universe domain) */ @Override public String getUniverseDomain() { @@ -252,6 +296,16 @@ 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}. {@link UserCredentials} are also + * only supported in {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. Wrap a service account in + * {@link ImpersonatedCredentials}, or use credentials such as {@link ComputeEngineCredentials} + * or {@link ExternalAccountCredentials} (for Workforce Identity Federation, service account + * impersonation must be configured). + * * @param sourceCredential the {@code GoogleCredentials} to set * @return this {@code Builder} object */ @@ -287,9 +341,14 @@ public Builder setHttpTransportFactory(@Nullable HttpTransportFactory transportF } /** - * Sets the optional universe domain. + * Sets an optional expected universe domain. + * + *

When omitted, {@code null}, or blank, the universe domain is inherited from the source + * credential. When explicitly set, {@link #build()} validates that it matches the source + * credential's universe domain. * - * @param universeDomain the universe domain to set + * @param universeDomain the expected universe domain, or {@code null} to inherit from the + * source credential * @return this {@code Builder} object */ @CanIgnoreReturnValue @@ -298,6 +357,19 @@ public Builder setUniverseDomain(@Nullable String universeDomain) { return this; } + /** + * Creates a new {@link DownscopedCredentials} instance based on the current builder + * configuration. + * + * @return a new {@code DownscopedCredentials} instance + * @throws NullPointerException if {@code sourceCredential} or {@code credentialAccessBoundary} + * is not set + * @throws IllegalStateException if the source credential's universe domain cannot be retrieved + * @throws IllegalArgumentException if the source credential's universe domain is {@code null} + * or blank, if an explicitly configured universe domain does not match the source + * credential, or if a {@link ServiceAccountCredentials} or {@link UserCredentials} is used + * directly in a non-default universe domain + */ @Override public DownscopedCredentials build() { return new DownscopedCredentials(this); 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 3e3665111d18..31ebeb2c2f81 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,8 +45,9 @@ /** * A refreshable alternative to {@link OAuth2Credentials}. * - *

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

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

Because {@link OAuth2CredentialsWithRefresh.OAuth2RefreshHandler} returns {@link AccessToken} * values without universe domain metadata, credentials default to {@link @@ -54,6 +55,17 @@ * should configure it explicitly via {@link * OAuth2CredentialsWithRefresh.Builder#setUniverseDomain}. If lazy or delegated universe domain * resolution is needed, subclass this class and override {@link #getUniverseDomain()}. + * + *

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..b533aea7aaf5 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 @@ -36,11 +36,16 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; 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; @@ -72,6 +77,11 @@ class DownscopedCredentialsTest extends BaseSerializationTest { .build()) .build(); + private static final HttpTransportFactory UNEXPECTED_HTTP_TRANSPORT_FACTORY = + () -> { + throw new AssertionError("Unexpected HTTP request."); + }; + static class MockStsTransportFactory implements HttpTransportFactory { MockStsTransport transport = new MockStsTransport(); @@ -192,6 +202,92 @@ 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"; + 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 = getNonDefaultUniverseServiceAccount(universeDomain); + 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) + .build(); + + AccessToken accessToken = downscopedCredentials.refreshAccessToken(); + + assertEquals(universeDomain, downscopedCredentials.getUniverseDomain()); + assertEquals(stsTransportFactory.transport.getAccessToken(), accessToken.getTokenValue()); + assertEquals( + String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), + stsTransportFactory.transport.getRequest().getUrl()); + Map stsQuery = + TestUtils.parseQuery(stsTransportFactory.transport.getRequest().getContentAsString()); + assertEquals("impersonated-access-token", stsQuery.get("subject_token")); + assertNotNull(iamTransportFactory.getTransport().getRequest()); + assertTrue( + iamTransportFactory + .getTransport() + .getRequest() + .getUrl() + .startsWith("https://iamcredentials." + universeDomain + "/")); + } + + @Test + void refreshAccessToken_wrappedNonDefaultUniverseServiceAccount_failsClosed() throws IOException { + String universeDomain = "example.com"; + GoogleCredentials delegate = getNonDefaultUniverseServiceAccount(universeDomain); + DownscopedCredentials downscopedCredentials = + DownscopedCredentials.newBuilder() + .setSourceCredential(wrapCredentials(universeDomain, delegate)) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .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)); + } + + @Test + void refreshAccessToken_wrappedNonDefaultUniverseUserCredentials_failsClosed() { + String universeDomain = "example.com"; + GoogleCredentials delegate = + getNonDefaultUniverseUserCredentials(universeDomain, /* cachedToken= */ null); + DownscopedCredentials downscopedCredentials = + DownscopedCredentials.newBuilder() + .setSourceCredential(wrapCredentials(universeDomain, delegate)) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .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)); + } + @Test void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IOException { // STS only returns expires_in if the source access token belongs to a service account. @@ -323,10 +419,154 @@ void builder_sourceUniverseDomainUnavailable_throws() { e.getMessage()); } + @Test + void builder_omittedUniverseDomain_inheritsSourceUniverseDomain() throws IOException { + MockStsTransportFactory transportFactory = new MockStsTransportFactory(); + String universeDomain = "example.com"; + + DownscopedCredentials downscopedCredentials = + DownscopedCredentials.newBuilder() + .setSourceCredential(getCustomUniverseSourceCredentials(universeDomain)) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(transportFactory) + .build(); + + assertEquals(universeDomain, downscopedCredentials.getUniverseDomain()); + downscopedCredentials.refreshAccessToken(); + assertEquals( + String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), + transportFactory.transport.getRequest().getUrl()); + } + + @Test + void builder_nullUniverseDomain_inheritsSourceUniverseDomain() { + String universeDomain = "example.com"; + DownscopedCredentials credentials = + DownscopedCredentials.newBuilder() + .setSourceCredential(getCustomUniverseSourceCredentials(universeDomain)) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .setUniverseDomain(null) + .build(); + + assertEquals(universeDomain, credentials.getUniverseDomain()); + } + + @Test + void builder_emptyUniverseDomain_inheritsSourceUniverseDomain() { + String universeDomain = "example.com"; + DownscopedCredentials credentials = + DownscopedCredentials.newBuilder() + .setSourceCredential(getCustomUniverseSourceCredentials(universeDomain)) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .setUniverseDomain("") + .build(); + + assertEquals(universeDomain, credentials.getUniverseDomain()); + } + + @Test + void builder_whitespaceUniverseDomain_inheritsSourceUniverseDomain() { + String universeDomain = "example.com"; + DownscopedCredentials credentials = + DownscopedCredentials.newBuilder() + .setSourceCredential(getCustomUniverseSourceCredentials(universeDomain)) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .setUniverseDomain(" ") + .build(); + + assertEquals(universeDomain, credentials.getUniverseDomain()); + } + + @Test + void builder_explicitDefaultUniverseWithNonDefaultSource_throws() { + DownscopedCredentials.Builder builder = + DownscopedCredentials.newBuilder() + .setSourceCredential(getCustomUniverseSourceCredentials("example.com")) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .setUniverseDomain(GOOGLE_DEFAULT_UNIVERSE); + + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, builder::build); + assertEquals( + "The downscoped credential's universe domain must be the same as the source credential.", + e.getMessage()); + } + + @Test + void builder_nullSourceUniverseDomain_throws() { + DownscopedCredentials.Builder builder = + DownscopedCredentials.newBuilder() + .setSourceCredential(getSourceCredentialsReturningUniverseDomain(null)) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY); + + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, builder::build); + assertEquals( + "The source credential's universe domain must not be null or empty.", e.getMessage()); + } + + @Test + void builder_blankSourceUniverseDomain_throws() { + DownscopedCredentials.Builder builder = + DownscopedCredentials.newBuilder() + .setSourceCredential(getSourceCredentialsReturningUniverseDomain(" ")) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY); + + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, builder::build); + assertEquals( + "The source credential's universe domain must not be null or empty.", e.getMessage()); + } + + @Test + void builder_nonDefaultUniverseServiceAccount_throws() throws IOException { + String universeDomain = "example.com"; + DownscopedCredentials.Builder builder = + DownscopedCredentials.newBuilder() + .setSourceCredential(getNonDefaultUniverseServiceAccount(universeDomain)) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY); + + IllegalArgumentException error = assertThrows(IllegalArgumentException.class, builder::build); + assertTrue(error.getMessage().contains("ServiceAccountCredentials")); + assertTrue(error.getMessage().contains(universeDomain)); + assertTrue(error.getMessage().contains("ImpersonatedCredentials")); + assertTrue(error.getMessage().contains("Workforce Identity Federation")); + } + + @Test + void builder_nonDefaultUniverseUserCredentials_throws() { + String universeDomain = "example.com"; + AccessToken cachedToken = + new AccessToken( + "cached-access-token", + new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1))); + DownscopedCredentials.Builder builder = + DownscopedCredentials.newBuilder() + .setSourceCredential(getNonDefaultUniverseUserCredentials(universeDomain, cachedToken)) + .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY); + + IllegalArgumentException error = assertThrows(IllegalArgumentException.class, builder::build); + assertTrue(error.getMessage().contains("UserCredentials")); + assertTrue(error.getMessage().contains(universeDomain)); + assertTrue(error.getMessage().contains("Workforce Identity Federation")); + } + 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 +580,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); } @@ -358,6 +594,53 @@ public AccessToken refreshAccessToken() { }; } + private static GoogleCredentials getSourceCredentialsReturningUniverseDomain( + String universeDomain) { + return new GoogleCredentials() { + @Override + public String getUniverseDomain() { + return universeDomain; + } + }; + } + + private static GoogleCredentials getNonDefaultUniverseServiceAccount(String universeDomain) + throws IOException { + return ServiceAccountCredentials.newBuilder() + .setClientEmail("service-account@google.com") + .setPrivateKey(OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8)) + .setPrivateKeyId("privateKeyId") + .setProjectId("projectId") + .setUniverseDomain(universeDomain) + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY) + .build() + .createScoped(OAuth2Utils.CLOUD_PLATFORM_SCOPE); + } + + private static GoogleCredentials getNonDefaultUniverseUserCredentials( + String universeDomain, AccessToken cachedToken) { + UserCredentials.Builder builder = + UserCredentials.newBuilder() + .setClientId("test-client-id") + .setClientSecret("test-client-secret") + .setRefreshToken("test-refresh-token") + .setHttpTransportFactory(UNEXPECTED_HTTP_TRANSPORT_FACTORY); + if (cachedToken != null) { + builder.setAccessToken(cachedToken); + } + return builder.setUniverseDomain(universeDomain).build(); + } + + private static GoogleCredentials wrapCredentials( + String universeDomain, GoogleCredentials delegate) { + return new GoogleCredentials(GoogleCredentials.newBuilder().setUniverseDomain(universeDomain)) { + @Override + public AccessToken refreshAccessToken() throws IOException { + return delegate.refreshAccessToken(); + } + }; + } + private static GoogleCredentials getUserSourceCredentials() { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient("clientId", "clientSecret");