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 1e4adf96a5c8..7da107f4a9cd 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 @@ -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; @@ -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() @@ -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 @@ -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)); diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java index b06e324a0dd2..76a66d05b46d 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java @@ -525,10 +525,30 @@ private GenericData parseResponseAs(HttpResponse response) throws IOException { } /** - * 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}. + * + *

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). + * + *

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); diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java index c2eb38aa490c..35d37f3d727c 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java @@ -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; @@ -137,20 +138,34 @@ static UserCredentials fromJson(Map 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)); + } 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); + } + return builder.build(); } /** @@ -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); 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 e2759a292439..258e362ea0c5 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 @@ -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() @@ -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 @@ -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"); diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java index 8b795c05aaeb..07f2287dcf81 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java @@ -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; @@ -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; @@ -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}. */ @@ -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("user@example.com") + }; + + 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 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"; diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java index b4b06743ee24..0fd2e9a2273f 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java @@ -71,8 +71,8 @@ class UserCredentialsTest extends BaseSerializationTest { static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; - static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; - static final String REFRESH_TOKEN = "1/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; + static final String CLIENT_ID = "test-client-id"; + static final String REFRESH_TOKEN = "test-refresh-token"; private static final String ACCESS_TOKEN = "1/MkSJoj1xsli0AccessToken_NKPY2"; private static final String QUOTA_PROJECT = "sample-quota-project-id"; private static final Collection SCOPES = Collections.singletonList("dummy.scope"); @@ -883,6 +883,134 @@ void userCredentials_toBuilder_copyEveryAttribute() { assertEquals(credentials, otherCredentials); } + @Test + void refreshAccessToken_nonDefaultUniverse_throwsIOException() { + MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(null); + URI[] tokenUris = { + null, + URI.create("https://oauth2.example.com/token"), + URI.create("https://accounts.google.com/o/oauth2/token"), + URI.create("/token"), + URI.create("mailto:user@example.com") + }; + + for (URI tokenUri : tokenUris) { + UserCredentials credentials = + createUniverseUserCredentials(transportFactory, tokenUri, "example.com"); + IOException error = assertThrows(IOException.class, credentials::refreshAccessToken); + assertTrue(error.getMessage().contains("example.com")); + } + + UserCredentials defaultUriCredentials = + createUniverseUserCredentials(transportFactory, null, "example.com"); + assertThrows(IOException.class, defaultUriCredentials::refresh); + assertThrows(IOException.class, defaultUriCredentials::refreshIfExpired); + + GoogleCredentials fromToBuilder = + createUniverseUserCredentials(transportFactory, null, null).toBuilder() + .setUniverseDomain("example.com") + .build(); + assertThrows(IOException.class, fromToBuilder::refreshAccessToken); + + assertEquals(0, transportFactory.transport.buildRequestCount); + assertNull(transportFactory.transport.getRequest()); + } + + @Test + void idTokenWithAudience_nonDefaultUniverse_throwsIOException() { + MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(null); + UserCredentials credentials = + createUniverseUserCredentials(transportFactory, null, "example.com"); + + assertThrows( + IOException.class, + () -> credentials.idTokenWithAudience("https://target.example.com", null)); + assertEquals(0, transportFactory.transport.buildRequestCount); + assertNull(transportFactory.transport.getRequest()); + } + + @Test + void refreshAccessToken_defaultUniverseWithDefaultOrCustomTokenUri_succeeds() throws IOException { + URI[] tokenUris = {null, URI.create("https://oauth2.example.com/token")}; + + for (URI tokenUri : tokenUris) { + MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(tokenUri); + UserCredentials credentials = createUniverseUserCredentials(transportFactory, tokenUri, null); + + AccessToken token = credentials.refreshAccessToken(); + + URI expectedUri = tokenUri != null ? tokenUri : OAuth2Utils.TOKEN_SERVER_URI; + assertEquals(ACCESS_TOKEN, token.getTokenValue()); + assertEquals(expectedUri.toString(), transportFactory.transport.getRequest().getUrl()); + } + } + + @Test + void fromJson_nonDefaultUniverse_throwsIOException() { + String[] tokenUrls = { + null, OAuth2Utils.TOKEN_SERVER_URI.toString(), "https://oauth2.example.com/token" + }; + + for (String tokenUrl : tokenUrls) { + MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(null); + GenericJson json = writeUserJson(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, tokenUrl); + json.put("universe_domain", "example.com"); + + IOException error = + assertThrows(IOException.class, () -> UserCredentials.fromJson(json, transportFactory)); + assertTrue(error.getMessage().contains("example.com")); + assertEquals(0, transportFactory.transport.buildRequestCount); + assertNull(transportFactory.transport.getRequest()); + } + } + + @Test + void fromJson_defaultOrBlankUniverse_succeeds() throws IOException { + String[] universeDomains = {null, "", " ", "googleapis.com"}; + + for (String universeDomain : universeDomains) { + MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(null); + GenericJson json = writeUserJson(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, null); + if (universeDomain != null) { + json.put("universe_domain", universeDomain); + } + + UserCredentials credentials = UserCredentials.fromJson(json, transportFactory); + assertEquals("googleapis.com", credentials.getUniverseDomain()); + assertEquals(ACCESS_TOKEN, credentials.refreshAccessToken().getTokenValue()); + assertEquals( + OAuth2Utils.TOKEN_SERVER_URI.toString(), + transportFactory.transport.getRequest().getUrl()); + } + } + + private static MockTokenServerTransportFactory createMockTokenTransportFactory(URI tokenUri) { + MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); + if (tokenUri != null) { + transportFactory.transport.setTokenServerUri(tokenUri); + } + transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); + transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); + return transportFactory; + } + + private static UserCredentials createUniverseUserCredentials( + MockTokenServerTransportFactory transportFactory, URI tokenUri, String universeDomain) { + UserCredentials.Builder builder = + UserCredentials.newBuilder() + .setClientId(CLIENT_ID) + .setClientSecret(CLIENT_SECRET) + .setRefreshToken(REFRESH_TOKEN) + .setHttpTransportFactory(transportFactory); + if (tokenUri != null) { + builder.setTokenServerUri(tokenUri); + } + if (universeDomain != null) { + builder.setUniverseDomain(universeDomain); + } + return builder.build(); + } + static GenericJson writeUserJson( String clientId, String clientSecret,