Repository navigation
fix(auth): reject non-default universe refreshes for ServiceAccountCredentials and UserCredentials #15245
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
fix(auth): reject non-default universe refreshes for ServiceAccountCredentials and UserCredentials #15245
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -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<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)); | ||||||||||||||
| } | ||||||||||||||
| 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since
Suggested change
|
||||||||||||||
| 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); | ||||||||||||||
|
|
||||||||||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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("[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"; | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If
universeDomaincontains leading or trailing whitespace (e.g.," googleapis.com "),universeDomain.trim().isEmpty()will befalse, but!Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain)will evaluate totruebecause the untrimmed string does not match"googleapis.com". This will cause an unexpectedIOExceptionto be thrown for what is conceptually the default universe domain.Trimming
universeDomainimmediately after retrieving it from the JSON map resolves this issue and ensures consistent behavior.