in core/src/main/java/com/google/cloud/sql/core/DefaultConnectionInfoRepository.java [389:442]
private Certificate fetchEphemeralCertificate(
KeyPair keyPair,
CloudSqlInstanceName instanceName,
Optional<AccessToken> accessTokenOptional,
AuthType authType) {
// Use the SQL Admin API to create a new ephemeral certificate.
GenerateEphemeralCertRequest request =
new GenerateEphemeralCertRequest().setPublicKey(generatePublicKeyCert(keyPair));
if (authType == AuthType.IAM && accessTokenOptional.isPresent()) {
AccessToken accessToken = accessTokenOptional.get();
String token = accessToken.getTokenValue();
request.setAccessToken(token);
}
GenerateEphemeralCertResponse response;
try {
response =
new ApiClientRetryingCallable<>(
() ->
apiClient
.connect()
.generateEphemeralCert(
instanceName.getProjectId(), instanceName.getInstanceId(), request)
.execute())
.call();
} catch (Exception ex) {
throw addExceptionContext(
ex,
String.format(
"[%s] Failed to create ephemeral certificate for the Cloud SQL instance.",
instanceName.getConnectionName()),
instanceName);
}
// Parse the certificate from the response.
Certificate ephemeralCertificate;
try {
// The response contains a single certificate. This uses the parseCertificateChain method
// to parse the response, and then uses the first, and only, certificate.
ephemeralCertificate = parseCertificateChain(response.getEphemeralCert().getCert()).get(0);
} catch (CertificateException ex) {
throw new RuntimeException(
String.format(
"[%s] Unable to parse the ephemeral certificate for the Cloud SQL instance.",
instanceName.getConnectionName()),
ex);
}
logger.debug(String.format("[%s %d] CERT DONE", instanceName, Thread.currentThread().getId()));
return ephemeralCertificate;
}