mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(acm): reissue the certificate on RenewCertificate (#7074)
* fix(acm): reissue the certificate on RenewCertificate RenewCertificate on an issued private certificate now issues a new leaf from the local CA under the same ARN, with a fresh key pair of the same algorithm, so GetCertificate and ExportCertificate return material whose X.509 validity matches DescribeCertificate's NotBefore/NotAfter. Fixes #7070 * fix(acm): refresh attached consumers and store a new record on RenewCertificate Renewal now replaces the stored certificate with a new record, as a re-import does, so an ExportCertificate racing it never pairs the old key with the new body, and notifies the reference providers after the ACM guard is released so attached ELB and CloudFront consumers pick up the renewed material. RequestCertificate and renewal share one helper that copies issued material onto the record.
This commit is contained in:
1 parent
e0d199c359
commit
62cf61614b
4 files changed
+307
-33
No files matched your search
@@ -330,6 +330,12 @@
|
||||
</dependency>
|
||||
|
||||
<!-- Testing -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>acm</artifactId>
|
||||
<version>${aws.sdk.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>sts</artifactId>
|
||||
|
||||
@@ -211,16 +211,7 @@ public class AcmService implements ResourceProvider {
|
||||
cert.setValidationMethod(method);
|
||||
cert.setCreatedAt(now);
|
||||
cert.setIssuedAt(status == CertificateStatus.ISSUED ? now : null);
|
||||
cert.setNotBefore(generated.notBefore());
|
||||
cert.setNotAfter(generated.notAfter());
|
||||
cert.setSerial(generated.serial());
|
||||
cert.setSubject(generated.subject());
|
||||
cert.setIssuer(generated.issuer());
|
||||
cert.setKeyAlgorithm(alg);
|
||||
cert.setSignatureAlgorithm(generated.signatureAlgorithm());
|
||||
cert.setCertificateBody(generated.certificatePem());
|
||||
cert.setPrivateKey(generated.privateKeyPem());
|
||||
cert.setCertificateChain(certificateAuthority.caPem());
|
||||
applyIssuedMaterial(cert, alg, generated);
|
||||
cert.setCertOptions(options != null ? options : CertificateOptions.defaultOptions());
|
||||
cert.setCertAuthorityArn(certAuthorityArn);
|
||||
cert.setIdempotencyToken(idempotencyToken);
|
||||
@@ -495,16 +486,8 @@ public class AcmService implements ResourceProvider {
|
||||
}
|
||||
store.put(storageKey, cert);
|
||||
}
|
||||
// A consumer may acquire IAM before ACM; never invoke it while holding this guard.
|
||||
if (existingArn != null && !existingArn.isEmpty() && referenceProviders != null) {
|
||||
for (AcmCertificateReferenceProvider provider : referenceProviders) {
|
||||
try {
|
||||
provider.certificateReimported(cert.getArn(), region);
|
||||
} catch (RuntimeException failure) {
|
||||
LOG.warnv("ACM consumer refresh failed for {0} ({1}: {2}); an identical update can retry",
|
||||
cert.getArn(), failure.getClass().getSimpleName(), failure.getMessage());
|
||||
}
|
||||
}
|
||||
if (existingArn != null && !existingArn.isEmpty()) {
|
||||
notifyCertificateReimported(cert.getArn(), region);
|
||||
}
|
||||
LOG.infov("Imported certificate: {0}", cert.getArn());
|
||||
return cert;
|
||||
@@ -642,21 +625,83 @@ public class AcmService implements ResourceProvider {
|
||||
return cert;
|
||||
}
|
||||
|
||||
public synchronized Certificate renewCertificate(String certificateArn, String region) {
|
||||
Certificate cert = getCertificateByArn(certificateArn, region);
|
||||
if (cert.getStatus() == CertificateStatus.PENDING_VALIDATION) {
|
||||
throw new AwsException("RequestInProgressException", "Certificate is pending validation", 400);
|
||||
public Certificate renewCertificate(String certificateArn, String region) {
|
||||
Certificate renewed;
|
||||
synchronized (this) {
|
||||
Certificate cert = getCertificateByArn(certificateArn, region);
|
||||
if (cert.getStatus() == CertificateStatus.PENDING_VALIDATION) {
|
||||
throw new AwsException("RequestInProgressException", "Certificate is pending validation", 400);
|
||||
}
|
||||
if (cert.getType() != CertificateType.PRIVATE || cert.getStatus() != CertificateStatus.ISSUED) {
|
||||
throw new AwsException("InvalidArnException", "Certificate is not a private issued certificate", 400);
|
||||
}
|
||||
// A renewed private certificate is new material under the same ARN: a fresh key pair of the
|
||||
// same algorithm, stored as a new record so a concurrent export never pairs old and new material.
|
||||
KeyAlgorithm alg = cert.getKeyAlgorithm() != null ? cert.getKeyAlgorithm() : KeyAlgorithm.RSA_2048;
|
||||
List<String> sans = new ArrayList<>();
|
||||
if (cert.getSubjectAlternativeNames() != null) {
|
||||
for (String san : cert.getSubjectAlternativeNames()) {
|
||||
if (!san.equals(cert.getDomainName())) {
|
||||
sans.add(san);
|
||||
}
|
||||
}
|
||||
}
|
||||
CertificateGenerator.GeneratedCertificate generated = certificateAuthority.issueServerCertificate(
|
||||
cert.getDomainName(), sans, alg, null);
|
||||
|
||||
renewed = new Certificate();
|
||||
renewed.setArn(cert.getArn());
|
||||
renewed.setDomainName(cert.getDomainName());
|
||||
renewed.setSubjectAlternativeNames(cert.getSubjectAlternativeNames());
|
||||
renewed.setStatus(cert.getStatus());
|
||||
renewed.setType(cert.getType());
|
||||
renewed.setValidationMethod(cert.getValidationMethod());
|
||||
renewed.setCreatedAt(cert.getCreatedAt());
|
||||
renewed.setImportedAt(cert.getImportedAt());
|
||||
renewed.setIssuedAt(Instant.now());
|
||||
applyIssuedMaterial(renewed, alg, generated);
|
||||
renewed.setCertOptions(cert.getCertOptions());
|
||||
renewed.setCertAuthorityArn(cert.getCertAuthorityArn());
|
||||
renewed.setIdempotencyToken(cert.getIdempotencyToken());
|
||||
renewed.setTags(cert.getTags() != null ? new HashMap<>(cert.getTags()) : new HashMap<>());
|
||||
renewed.setInUseBy(cert.getInUseBy() != null ? new ArrayList<>(cert.getInUseBy()) : new ArrayList<>());
|
||||
renewed.setDomainValidationOptions(cert.getDomainValidationOptions() != null
|
||||
? new ArrayList<>(cert.getDomainValidationOptions()) : new ArrayList<>());
|
||||
store.put(regionKey(region, cert.extractCertificateId()), renewed);
|
||||
}
|
||||
if (cert.getType() != CertificateType.PRIVATE || cert.getStatus() != CertificateStatus.ISSUED) {
|
||||
throw new AwsException("InvalidArnException", "Certificate is not a private issued certificate", 400);
|
||||
notifyCertificateReimported(renewed.getArn(), region);
|
||||
LOG.infov("Renewed certificate: {0}", renewed.getArn());
|
||||
return renewed;
|
||||
}
|
||||
|
||||
/** The validity, identity and key material of a leaf issued by the local CA. */
|
||||
private void applyIssuedMaterial(Certificate cert, KeyAlgorithm alg,
|
||||
CertificateGenerator.GeneratedCertificate generated) {
|
||||
cert.setNotBefore(generated.notBefore());
|
||||
cert.setNotAfter(generated.notAfter());
|
||||
cert.setSerial(generated.serial());
|
||||
cert.setSubject(generated.subject());
|
||||
cert.setIssuer(generated.issuer());
|
||||
cert.setKeyAlgorithm(alg);
|
||||
cert.setSignatureAlgorithm(generated.signatureAlgorithm());
|
||||
cert.setCertificateBody(generated.certificatePem());
|
||||
cert.setPrivateKey(generated.privateKeyPem());
|
||||
cert.setCertificateChain(certificateAuthority.caPem());
|
||||
}
|
||||
|
||||
/** A consumer may acquire IAM before ACM; never invoke it while holding this guard. */
|
||||
private void notifyCertificateReimported(String certificateArn, String region) {
|
||||
if (referenceProviders == null) {
|
||||
return;
|
||||
}
|
||||
for (AcmCertificateReferenceProvider provider : referenceProviders) {
|
||||
try {
|
||||
provider.certificateReimported(certificateArn, region);
|
||||
} catch (RuntimeException failure) {
|
||||
LOG.warnv("ACM consumer refresh failed for {0} ({1}: {2}); an identical update can retry",
|
||||
certificateArn, failure.getClass().getSimpleName(), failure.getMessage());
|
||||
}
|
||||
}
|
||||
// TODO: certificate/key reissuance material is not regenerated in this local emulator.
|
||||
Instant now = Instant.now();
|
||||
cert.setIssuedAt(now);
|
||||
cert.setNotBefore(now);
|
||||
cert.setNotAfter(now.plusSeconds(365L * 24L * 60L * 60L));
|
||||
store.put(regionKey(region, cert.extractCertificateId()), cert);
|
||||
return cert;
|
||||
}
|
||||
|
||||
public synchronized void updateCertificateOptions(String certificateArn, CertificateOptions options, String region) {
|
||||
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package io.github.hectorvent.floci.services.acm;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.Pem;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.acm.AcmClient;
|
||||
import software.amazon.awssdk.services.acm.model.CertificateDetail;
|
||||
import software.amazon.awssdk.services.acm.model.ExportCertificateResponse;
|
||||
import software.amazon.awssdk.services.acm.model.GetCertificateResponse;
|
||||
import software.amazon.awssdk.services.acm.model.InvalidArnException;
|
||||
import software.amazon.awssdk.services.acm.model.Tag;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.EncryptedPrivateKeyInfo;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.PBEKeySpec;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.AlgorithmParameters;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* RenewCertificate on an issued private certificate reissues its material under the same ARN, so
|
||||
* GetCertificate and ExportCertificate hand out a leaf whose validity is what DescribeCertificate reports.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class AcmRenewCertificateIntegrationTest {
|
||||
|
||||
private static final String PCA_ARN =
|
||||
"arn:aws:acm-pca:us-east-1:000000000000:certificate-authority/renew-test";
|
||||
private static final String PASSPHRASE = "renew-passphrase";
|
||||
|
||||
@Test
|
||||
void renewReissuesTheCertificateWithTheReportedValidity() throws Exception {
|
||||
try (AcmClient acm = client()) {
|
||||
String arn = acm.requestCertificate(request -> request
|
||||
.domainName("renew-sdk.example.test")
|
||||
.subjectAlternativeNames("renew-sdk.example.test", "api.renew-sdk.example.test")
|
||||
.certificateAuthorityArn(PCA_ARN)
|
||||
.tags(Tag.builder().key("team").value("edge").build()))
|
||||
.certificateArn();
|
||||
GetCertificateResponse before = acm.getCertificate(request -> request.certificateArn(arn));
|
||||
|
||||
acm.renewCertificate(request -> request.certificateArn(arn));
|
||||
|
||||
GetCertificateResponse after = acm.getCertificate(request -> request.certificateArn(arn));
|
||||
assertNotEquals(before.certificate(), after.certificate(), "renewal issues a new certificate body");
|
||||
assertEquals(before.certificateChain(), after.certificateChain(), "still chained to the same CA");
|
||||
|
||||
CertificateDetail detail = acm.describeCertificate(request -> request.certificateArn(arn)).certificate();
|
||||
X509Certificate leaf = Pem.parseCertificate(after.certificate());
|
||||
assertEquals(arn, detail.certificateArn());
|
||||
assertEquals(leaf.getNotBefore().toInstant(), detail.notBefore().truncatedTo(ChronoUnit.SECONDS));
|
||||
assertEquals(leaf.getNotAfter().toInstant(), detail.notAfter().truncatedTo(ChronoUnit.SECONDS));
|
||||
assertEquals(List.of("renew-sdk.example.test", "api.renew-sdk.example.test"),
|
||||
detail.subjectAlternativeNames());
|
||||
assertEquals(List.of("renew-sdk.example.test", "api.renew-sdk.example.test"),
|
||||
leaf.getSubjectAlternativeNames().stream().map(san -> (String) san.get(1)).toList());
|
||||
assertEquals(List.of(Tag.builder().key("team").value("edge").build()),
|
||||
acm.listTagsForCertificate(request -> request.certificateArn(arn)).tags());
|
||||
|
||||
ExportCertificateResponse exported = acm.exportCertificate(request -> request
|
||||
.certificateArn(arn)
|
||||
.passphrase(SdkBytes.fromString(PASSPHRASE, StandardCharsets.UTF_8)));
|
||||
assertEquals(after.certificate(), exported.certificate(), "ExportCertificate returns the renewed body");
|
||||
assertEquals(after.certificateChain(), exported.certificateChain());
|
||||
PrivateKey key = decrypt(exported.privateKey(), leaf.getPublicKey().getAlgorithm());
|
||||
assertTrue(Pem.isPair(key, leaf.getPublicKey()), "the exported key belongs to the renewed certificate");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void renewIsOnlyForIssuedPrivateCertificates() {
|
||||
try (AcmClient acm = client()) {
|
||||
String arn = acm.requestCertificate(request -> request.domainName("renew-public.example.test"))
|
||||
.certificateArn();
|
||||
String serial = acm.describeCertificate(request -> request.certificateArn(arn)).certificate().serial();
|
||||
|
||||
InvalidArnException failure = assertThrows(InvalidArnException.class,
|
||||
() -> acm.renewCertificate(request -> request.certificateArn(arn)));
|
||||
|
||||
assertEquals(400, failure.statusCode());
|
||||
assertEquals(serial, acm.describeCertificate(request -> request.certificateArn(arn)).certificate().serial());
|
||||
}
|
||||
}
|
||||
|
||||
private static PrivateKey decrypt(String encryptedPem, String keyAlgorithm) throws Exception {
|
||||
String base64 = encryptedPem.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "")
|
||||
.replace("-----END ENCRYPTED PRIVATE KEY-----", "")
|
||||
.replaceAll("\\s", "");
|
||||
EncryptedPrivateKeyInfo info = new EncryptedPrivateKeyInfo(Base64.getDecoder().decode(base64));
|
||||
AlgorithmParameters parameters = info.getAlgParameters();
|
||||
String pbe = parameters.toString();
|
||||
SecretKey secret = SecretKeyFactory.getInstance(pbe).generateSecret(new PBEKeySpec(PASSPHRASE.toCharArray()));
|
||||
Cipher cipher = Cipher.getInstance(pbe);
|
||||
cipher.init(Cipher.DECRYPT_MODE, secret, parameters);
|
||||
PKCS8EncodedKeySpec spec = info.getKeySpec(cipher);
|
||||
return KeyFactory.getInstance(keyAlgorithm).generatePrivate(spec);
|
||||
}
|
||||
|
||||
private static AcmClient client() {
|
||||
return AcmClient.builder().endpointOverride(URI.create("http://localhost:" + RestAssured.port))
|
||||
.httpClientBuilder(UrlConnectionHttpClient.builder()).region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -491,6 +491,104 @@ class AcmServiceTest {
|
||||
"an EC private key is exportable too");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = KeyAlgorithm.class, names = {"RSA_2048", "EC_prime256v1"})
|
||||
void renewReissuesThePrivateCertificateUnderTheSameArn(KeyAlgorithm algorithm) throws Exception {
|
||||
Certificate requested = service.requestCertificate("renew.example.test", List.of("www.renew.example.test"),
|
||||
ValidationMethod.DNS, null, algorithm, PCA_ARN, new CertificateOptions(null, "ENABLED"),
|
||||
Map.of("team", "edge"), null, REGION);
|
||||
String arn = requested.getArn();
|
||||
String originalBody = requested.getCertificateBody();
|
||||
String originalKey = requested.getPrivateKey();
|
||||
String originalSerial = requested.getSerial();
|
||||
|
||||
Certificate renewed = service.renewCertificate(arn, REGION);
|
||||
|
||||
Certificate stored = service.getCertificate(arn, REGION);
|
||||
assertEquals(arn, renewed.getArn());
|
||||
assertTrue(!originalBody.equals(stored.getCertificateBody()), "the renewed body is new material");
|
||||
assertTrue(!originalSerial.equals(stored.getSerial()), "the renewed leaf has its own serial");
|
||||
assertTrue(!originalKey.equals(stored.getPrivateKey()), "renewal mints a fresh key pair");
|
||||
X509Certificate leaf = assertChainsToTheCa(stored);
|
||||
assertEquals(algorithm, generator.detectKeyAlgorithm(leaf.getPublicKey()));
|
||||
assertEquals(List.of("renew.example.test", "www.renew.example.test"), stored.getSubjectAlternativeNames());
|
||||
assertEquals(List.of("renew.example.test", "www.renew.example.test"),
|
||||
leaf.getSubjectAlternativeNames().stream().map(san -> san.get(1)).toList());
|
||||
assertEquals(Map.of("team", "edge"), stored.getTags());
|
||||
assertEquals("ENABLED", stored.getCertOptions().export());
|
||||
assertEquals(CertificateStatus.ISSUED, stored.getStatus());
|
||||
|
||||
String passphrase = Base64.getEncoder().encodeToString("abcd1234".getBytes(StandardCharsets.US_ASCII));
|
||||
Certificate exported = service.exportCertificate(arn, passphrase, REGION);
|
||||
assertEquals(stored.getCertificateBody(), exported.getCertificateBody());
|
||||
assertEquals(ca.caPem(), exported.getCertificateChain());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renewRefusesAPublicCertificateWithoutTouchingItsMaterial() {
|
||||
Certificate requested = service.requestCertificate("renew-public.example.test", null, ValidationMethod.DNS,
|
||||
null, null, null, null, null, REGION);
|
||||
String originalBody = requested.getCertificateBody();
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> service.renewCertificate(requested.getArn(), REGION));
|
||||
|
||||
assertEquals("InvalidArnException", failure.getErrorCode());
|
||||
assertEquals(originalBody, service.getCertificate(requested.getArn(), REGION).getCertificateBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renewStoresANewRecordAndLeavesTheOldMaterialPaired() {
|
||||
Certificate requested = service.requestCertificate("renew-record.example.test", List.of(),
|
||||
ValidationMethod.DNS, null, KeyAlgorithm.RSA_2048, PCA_ARN, new CertificateOptions(null, "ENABLED"),
|
||||
Map.of(), null, REGION);
|
||||
String originalBody = requested.getCertificateBody();
|
||||
String originalKey = requested.getPrivateKey();
|
||||
service.addInUseBy(requested.getArn(), "arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/a/b/c",
|
||||
REGION);
|
||||
|
||||
Certificate renewed = service.renewCertificate(requested.getArn(), REGION);
|
||||
|
||||
assertTrue(renewed != requested, "renewal replaces the stored record instead of mutating it");
|
||||
assertTrue(service.getCertificate(requested.getArn(), REGION) == renewed);
|
||||
assertEquals(originalBody, requested.getCertificateBody(), "a reader holding the old record keeps its body");
|
||||
assertEquals(originalKey, requested.getPrivateKey(), "and the key that pairs with it");
|
||||
assertEquals(requested.getInUseBy(), renewed.getInUseBy());
|
||||
assertEquals(requested.getCreatedAt(), renewed.getCreatedAt());
|
||||
Certificate described = service.describeCertificate(requested.getArn(), REGION);
|
||||
assertEquals(renewed.getCertificateBody(), described.getCertificateBody());
|
||||
assertEquals(renewed.getNotAfter(), described.getNotAfter());
|
||||
String passphrase = Base64.getEncoder().encodeToString("abcd1234".getBytes(StandardCharsets.US_ASCII));
|
||||
assertEquals(renewed.getCertificateBody(),
|
||||
service.exportCertificate(requested.getArn(), passphrase, REGION).getCertificateBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renewNotifiesAttachedConsumersOutsideTheGuard() {
|
||||
Certificate requested = service.requestCertificate("renew-consumer.example.test", List.of(),
|
||||
ValidationMethod.DNS, null, KeyAlgorithm.RSA_2048, PCA_ARN, null, Map.of(), null, REGION);
|
||||
List<String> material = new CopyOnWriteArrayList<>();
|
||||
AtomicBoolean heldGuard = new AtomicBoolean();
|
||||
AcmCertificateReferenceProvider consumer = new AcmCertificateReferenceProvider() {
|
||||
@Override
|
||||
public List<CertificateReference> acmCertificateReferences() { return List.of(); }
|
||||
|
||||
@Override
|
||||
public void certificateReimported(String arn, String region) {
|
||||
heldGuard.set(Thread.holdsLock(service));
|
||||
material.add(service.getCertificate(arn, region).getCertificateBody());
|
||||
}
|
||||
};
|
||||
Instance<AcmCertificateReferenceProvider> providers = mock();
|
||||
when(providers.iterator()).thenAnswer(call -> List.of(consumer).iterator());
|
||||
service.referenceProviders = providers;
|
||||
|
||||
Certificate renewed = service.renewCertificate(requested.getArn(), REGION);
|
||||
|
||||
assertEquals(List.of(renewed.getCertificateBody()), material, "the consumer reloads the renewed material");
|
||||
assertTrue(!heldGuard.get(), "consumers are notified after the ACM guard is released");
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentRequestsEachGetTheirOwnCertificateChainedToTheCa() throws Exception {
|
||||
int threads = 16;
|
||||
|
||||
Reference in new issue
Block a user