in core/src/main/java/com/google/cloud/sql/core/DefaultAccessTokenSupplier.java [71:136]
public Optional<AccessToken> get() throws IOException {
if (credentialFactory == null) {
return Optional.empty();
}
RetryingCallable<Optional<AccessToken>> retries =
new RetryingCallable<>(
() -> {
final GoogleCredentials credentials = credentialFactory.getCredentials();
try {
refreshIfRequired(credentials);
} catch (IllegalStateException e) {
throw new IllegalStateException("Error refreshing credentials " + credentials, e);
}
if (isAccessTokenEmpty(credentials)) {
String errorMessage = "Access Token has length of zero";
logger.debug(errorMessage);
throw new IllegalStateException(errorMessage);
}
validateAccessTokenExpiration(credentials.getAccessToken());
// Now, attempt to down-scope and refresh credentials
GoogleCredentials downscoped = getDownscopedCredentials(credentials);
// For some implementations of GoogleCredentials, particularly
// ImpersonatedCredentials, down-scoped credentials are not
// initialized with a token and need to be explicitly refreshed.
if (isAccessTokenEmpty(downscoped)) {
try {
downscoped.refresh();
} catch (Exception e) {
throw new IllegalStateException(
"Error refreshing downscoped credentials " + credentials, e);
}
// After attempting to refresh once, if the downscoped credentials do not have
// an access token after attempting to refresh, then throw an IllegalStateException
if (isAccessTokenEmpty(downscoped)) {
String errorMessage = "Downscoped access token has length of zero";
logger.debug(errorMessage);
throw new IllegalStateException(
errorMessage
+ ": "
+ downscoped.getClass().getName()
+ " from "
+ credentials.getClass().getName());
}
validateAccessTokenExpiration(downscoped.getAccessToken());
}
return Optional.of(downscoped.getAccessToken());
});
try {
return retries.call();
} catch (IOException | RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Unexpected exception refreshing authentication token", e);
}
}