Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
*
* <p>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.
* <p>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.
*
* <p>Usage:
*
Expand Down Expand Up @@ -134,9 +139,15 @@
* System.out.printf("Blob %s retrieved.", blob.getBlobId());
* </code></pre>
*
* Note that {@link OAuth2CredentialsWithRefresh} can instead be used to consume the downscoped
* token, allowing for automatic token refreshes by providing a {@link
* OAuth2CredentialsWithRefresh.OAuth2RefreshHandler}.
* <p>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 {
Expand Down Expand Up @@ -181,6 +192,13 @@ private ClientSideCredentialAccessBoundaryFactory(Builder builder) {
/**
* Generates a downscoped access token given the {@link CredentialAccessBoundary}.
*
* <p>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.<universeDomain>/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
Expand Down Expand Up @@ -616,6 +634,14 @@ private Builder() {}
/**
* Sets the required source credential.
*
* <p>In non-default universe domains, {@link ServiceAccountCredentials} cannot be used directly
* because Credential Access Boundaries require an OAuth 2.0 access token (see <a
* href="https://cloud.google.com/iam/docs/create-downscoped-short-lived-credentials#before-you-begin">Create
* a downscoped short-lived credential</a>) 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
* <strong>required</strong> parameter.
* @return this {@code Builder} object for chaining.
Expand Down Expand Up @@ -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;
}
Expand All @@ -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.");
Expand All @@ -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;
}

Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +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.http.LowLevelHttpRequest;
import com.google.api.client.util.Clock;
Expand All @@ -53,10 +55,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;
Expand All @@ -68,7 +73,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;
Expand Down Expand Up @@ -191,6 +199,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 = "[email protected]";
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 {
Expand Down
Loading
Loading