Skip to content
Merged
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 @@ -67,6 +67,7 @@
import java.security.GeneralSecurityException;
import java.time.Duration;
import java.util.Base64;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
Expand Down Expand Up @@ -158,10 +159,7 @@ void fetchIntermediateCredentials() throws Exception {
@Test
void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOException {
String universeDomain = "foobar";
GoogleCredentials sourceCredentials =
getServiceAccountSourceCredentials(mockTokenServerTransportFactory).toBuilder()
.setUniverseDomain(universeDomain)
.build();
GoogleCredentials sourceCredentials = getCustomUniverseSourceCredentials(universeDomain);

ClientSideCredentialAccessBoundaryFactory factory =
ClientSideCredentialAccessBoundaryFactory.newBuilder()
Expand All @@ -174,7 +172,7 @@ void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOException

// Verify domain.
String url = mockStsTransportFactory.transport.getRequest().getUrl();
assertEquals(url, String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain));
assertEquals(String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), url);
}

@Test
Expand Down Expand Up @@ -611,6 +609,17 @@ private static GoogleCredentials getServiceAccountSourceCredentials(
return sourceCredentials.createScoped("https://www.googleapis.com/auth/cloud-platform");
}

private static GoogleCredentials getCustomUniverseSourceCredentials(String universeDomain) {
return new GoogleCredentials(GoogleCredentials.newBuilder().setUniverseDomain(universeDomain)) {
@Override
public AccessToken refreshAccessToken() {
return new AccessToken(
"customUniverseAccessToken",
new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)));
}
};
}

private ClientSideCredentialAccessBoundaryFactory getClientSideCredentialAccessBoundaryFactory(
RefreshType refreshType) throws IOException {
return getClientSideCredentialAccessBoundaryFactory(refreshType, new CountDownLatch(0));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@
* external source for authentication to Google Cloud Platform, you must validate it before
* providing it to any Google API or library. Providing an unvalidated credential configuration to
* Google APIs can compromise the security of your systems and data. For more information, refer
* to {@see <a

Check failure on line 464 in google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java

View workflow job for this annotation

GitHub Actions / BomContentAssertionsTest (Test for assertion logic in BomContentTest)

no tag name after @

Check failure on line 464 in google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java

View workflow job for this annotation

GitHub Actions / bom-content-test

no tag name after @
* href="https://cloud.google.com/docs/authentication/external/externally-sourced-credentials">documentation</a>}.
*
* @param credentialsStream the stream with the credential definition.
Expand All @@ -481,7 +481,7 @@
* external source for authentication to Google Cloud Platform, you must validate it before
* providing it to any Google API or library. Providing an unvalidated credential configuration to
* Google APIs can compromise the security of your systems and data. For more information, refer
* to {@see <a

Check failure on line 484 in google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java

View workflow job for this annotation

GitHub Actions / BomContentAssertionsTest (Test for assertion logic in BomContentTest)

no tag name after @

Check failure on line 484 in google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java

View workflow job for this annotation

GitHub Actions / bom-content-test

no tag name after @
* href="https://cloud.google.com/docs/authentication/external/externally-sourced-credentials">documentation</a>}.
*
* @param credentialsStream the stream with the credential definition.
Expand Down Expand Up @@ -525,10 +525,30 @@
}

/**
* Refreshes the OAuth2 access token by getting a new access token using a JSON Web Token (JWT).
* Refreshes the OAuth2 access token by exchanging a signed JWT assertion at {@code
* tokenServerUri}.
*
* <p>This method is only used for the OAuth2 access token flow (not self-signed JWT
* authentication, which is handled directly by {@link #getRequestMetadata(URI)} without calling
* this method).
*
* <p>OAuth2 token exchange is only supported in {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. In
* non-default universe domains, this method throws {@link IOException}. Use {@link
* #getRequestMetadata(URI)} for self-signed JWT authentication, or wrap this credential in {@link
* ImpersonatedCredentials} if an OAuth2 access token is required.
*/
@Override
public AccessToken refreshAccessToken() throws IOException {
String universeDomain = getUniverseDomain();
if (!Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain)) {
throw new IOException(
String.format(
"OAuth2 access token refresh is not supported for ServiceAccountCredentials in"
+ " universe domain %s. Use self-signed JWT authentication via"
+ " getRequestMetadata() or wrap this credential in ImpersonatedCredentials to"
+ " obtain short-lived OAuth2 access tokens.",
universeDomain));
}
JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY;
long currentTime = clock.currentTimeMillis();
String assertion = createAssertion(jsonFactory, currentTime);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.GenericData;
import com.google.auth.CredentialTypeForMetrics;
import com.google.auth.Credentials;
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.oauth2.MetricsUtils.RequestType;
import com.google.common.base.MoreObjects;
Expand Down Expand Up @@ -137,20 +138,34 @@ static UserCredentials fromJson(Map<String, Object> json, HttpTransportFactory t
// currently "token_uri" is not a default field and needs to be added to json file manually
String tokenUrl = (String) json.get("token_uri");
URI tokenUri = (tokenUrl == null || tokenUrl.isEmpty()) ? null : URI.create(tokenUrl);
String universeDomain = (String) json.get("universe_domain");
if (universeDomain != null
&& !universeDomain.trim().isEmpty()
&& !Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain)) {
throw new IOException(
String.format(
"UserCredentials are not supported in universes other than %s (configured"
+ " universe_domain: %s).",
Credentials.GOOGLE_DEFAULT_UNIVERSE, universeDomain));
}
Comment on lines +141 to +150

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If universeDomain contains leading or trailing whitespace (e.g., " googleapis.com "), universeDomain.trim().isEmpty() will be false, but !Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain) will evaluate to true because the untrimmed string does not match "googleapis.com". This will cause an unexpected IOException to be thrown for what is conceptually the default universe domain.

Trimming universeDomain immediately after retrieving it from the JSON map resolves this issue and ensures consistent behavior.

    String universeDomain = (String) json.get("universe_domain");
    if (universeDomain != null) {
      universeDomain = universeDomain.trim();
    }
    if (universeDomain != null
        && !universeDomain.isEmpty()
        && !Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain)) {
      throw new IOException(
          String.format(
              "UserCredentials are not supported in universes other than %s (configured"
                  + " universe_domain: %s).",
              Credentials.GOOGLE_DEFAULT_UNIVERSE, universeDomain));
    }

String account = null;
if (json.containsKey("account")) {
account = (String) json.get("account");
}
return UserCredentials.newBuilder()
.setClientId(clientId)
.setClientSecret(clientSecret)
.setRefreshToken(refreshToken)
.setAccessToken(null)
.setHttpTransportFactory(transportFactory)
.setTokenServerUri(tokenUri)
.setQuotaProjectId(quotaProjectId)
.setAccount(account)
.build();
UserCredentials.Builder builder =
UserCredentials.newBuilder()
.setClientId(clientId)
.setClientSecret(clientSecret)
.setRefreshToken(refreshToken)
.setAccessToken(null)
.setHttpTransportFactory(transportFactory)
.setTokenServerUri(tokenUri)
.setQuotaProjectId(quotaProjectId)
.setAccount(account);
if (universeDomain != null && !universeDomain.trim().isEmpty()) {
builder.setUniverseDomain(universeDomain);
}
Comment on lines +165 to +167

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since universeDomain is trimmed early, we can simplify this check and avoid setting an untrimmed string to the builder.

Suggested change
if (universeDomain != null && !universeDomain.trim().isEmpty()) {
builder.setUniverseDomain(universeDomain);
}
if (universeDomain != null && !universeDomain.isEmpty()) {
builder.setUniverseDomain(universeDomain);
}

return builder.build();
}

/**
Expand Down Expand Up @@ -271,6 +286,13 @@ private GenericData doRefreshAccessToken() throws IOException {
throw new IllegalStateException(
"UserCredentials instance cannot refresh because there is no refresh token.");
}
String universeDomain = getUniverseDomain();
if (!Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain)) {
throw new IOException(
String.format(
"UserCredentials refresh is only supported in %s (configured universe domain: %s).",
Credentials.GOOGLE_DEFAULT_UNIVERSE, universeDomain));
}
GenericData tokenRequest = new GenericData();
tokenRequest.set("client_id", clientId);
tokenRequest.set("client_secret", clientSecret);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,7 @@ void refreshAccessToken() throws IOException {
void refreshAccessToken_withCustomUniverseDomain() throws IOException {
MockStsTransportFactory transportFactory = new MockStsTransportFactory();
String universeDomain = "foobar";
GoogleCredentials sourceCredentials =
getServiceAccountSourceCredentials(/* canRefresh= */ true).toBuilder()
.setUniverseDomain(universeDomain)
.build();
GoogleCredentials sourceCredentials = getCustomUniverseSourceCredentials(universeDomain);

DownscopedCredentials downscopedCredentials =
DownscopedCredentials.newBuilder()
Expand All @@ -192,7 +189,7 @@ void refreshAccessToken_withCustomUniverseDomain() throws IOException {

// Verify domain.
String url = transportFactory.transport.getRequest().getUrl();
assertEquals(url, String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain));
assertEquals(String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), url);
}

@Test
Expand Down Expand Up @@ -350,6 +347,17 @@ private static GoogleCredentials getServiceAccountSourceCredentials(boolean canR
return sourceCredentials.createScoped(OAuth2Utils.CLOUD_PLATFORM_SCOPE);
}

private static GoogleCredentials getCustomUniverseSourceCredentials(String universeDomain) {
return new GoogleCredentials(GoogleCredentials.newBuilder().setUniverseDomain(universeDomain)) {
@Override
public AccessToken refreshAccessToken() {
return new AccessToken(
"customUniverseAccessToken",
new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)));
}
};
}

private static GoogleCredentials getUserSourceCredentials() {
MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory();
transportFactory.transport.addClient("clientId", "clientSecret");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,21 @@
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpStatusCodes;
import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.json.webtoken.JsonWebSignature;
import com.google.api.client.json.webtoken.JsonWebToken;
import com.google.api.client.testing.http.FixedClock;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.api.client.util.Clock;
import com.google.api.client.util.Joiner;
Expand All @@ -59,6 +66,7 @@
import com.google.auth.RequestMetadataCallback;
import com.google.auth.TestUtils;
import com.google.auth.http.AuthHttpConstants;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.oauth2.GoogleCredentials.GoogleCredentialsInfo;
import com.google.common.collect.ImmutableSet;
Expand All @@ -81,6 +89,8 @@
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Test;

/** Test case for {@link ServiceAccountCredentials}. */
Expand Down Expand Up @@ -644,6 +654,108 @@ void refreshAccessToken_tokenExpiry() throws IOException {
assertEquals(3600 * 1000 * 1000L, accessToken.getExpirationTimeMillis().longValue());
}

@Test
void refreshAccessToken_nonDefaultUniverse_throwsIOExceptionWithoutNetworkCall()
throws IOException {
URI customTokenUri = URI.create("https://oauth2.example.com/token");
MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory();
transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN);

GoogleCredentials[] cases = {
createDefaultBuilder()
.setScopes(SCOPES)
.setHttpTransportFactory(transportFactory)
.setUniverseDomain("example.com")
.build(),
createDefaultBuilder()
.setScopes(SCOPES)
.setHttpTransportFactory(transportFactory)
.setTokenServerUri(customTokenUri)
.setUniverseDomain("example.com")
.build(),
createDefaultBuilder()
.setScopes(SCOPES)
.setHttpTransportFactory(transportFactory)
.setUniverseDomain("example.com")
.build()
.createDelegated("[email protected]")
};

for (GoogleCredentials credentials : cases) {
IOException error = assertThrows(IOException.class, credentials::refreshAccessToken);
assertTrue(error.getMessage().contains("example.com"));
}
assertThrows(IOException.class, cases[0]::refresh);
assertThrows(IOException.class, cases[0]::refreshIfExpired);
assertEquals(0, transportFactory.transport.buildRequestCount);
assertNull(transportFactory.transport.getRequest());
}

@Test
void refreshAccessToken_nonDefaultUniverseFromJson_throwsIOException() throws IOException {
MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory();
transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN);
GenericJson json = writeServiceAccountJson(PROJECT_ID, null, "example.com");
json.put("token_uri", OAuth2Utils.TOKEN_SERVER_URI.toString());

GoogleCredentials credentials =
ServiceAccountCredentials.fromJson(json, transportFactory).createScoped(SCOPES);

IOException error = assertThrows(IOException.class, credentials::refreshAccessToken);
assertTrue(error.getMessage().contains("example.com"));
assertEquals(0, transportFactory.transport.buildRequestCount);
assertNull(transportFactory.transport.getRequest());
}

@Test
void httpCredentialsAdapter_401WithNonDefaultUniverseServiceAccount_doesNotCallTokenServer()
throws IOException {
MockTokenServerTransportFactory tokenTransportFactory = new MockTokenServerTransportFactory();
tokenTransportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN);
ServiceAccountCredentials credentials =
createDefaultBuilder()
.setScopes(SCOPES)
.setHttpTransportFactory(tokenTransportFactory)
.setUniverseDomain("example.com")
.build();

AtomicInteger apiRequestCount = new AtomicInteger();
AtomicReference<String> authorizationHeader = new AtomicReference<>();
MockHttpTransport apiTransport =
new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() {
apiRequestCount.incrementAndGet();
authorizationHeader.set(getFirstHeaderValue(AuthHttpConstants.AUTHORIZATION));
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
response.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
response.addHeader("WWW-Authenticate", "Bearer error=\"invalid_token\"");
return response;
}
};
}
};

HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials);
HttpRequest request =
apiTransport
.createRequestFactory(adapter)
.buildGetRequest(new GenericUrl("https://storage.example.com/test"));
request.setThrowExceptionOnExecuteError(false);

HttpResponse response = request.execute();

assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatusCode());
assertEquals(1, apiRequestCount.get());
assertNotNull(authorizationHeader.get());
assertTrue(authorizationHeader.get().startsWith("Bearer "));
assertEquals(0, tokenTransportFactory.transport.buildRequestCount);
assertNull(tokenTransportFactory.transport.getRequest());
}

@Test
void refreshAccessToken_IOException_Retry() throws IOException {
final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2";
Expand Down
Loading
Loading