Light, fluffy, and always free - The AWS Local Emulator alternative
fix(acm): reject mismatched certificate private keys (#5987)
David Phillips84dfb77f994f
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AcmImportKeyPairTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AcmImportKeyPairTest.javanew file mode 100644index 0000000000..3e279a560a--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AcmImportKeyPairTest.java@@ -0,0 +1,66 @@+package com.floci.test;++import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.function.Executable;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import software.amazon.awssdk.core.SdkBytes;+import software.amazon.awssdk.services.acm.AcmClient;+import software.amazon.awssdk.services.acm.model.AcmException;++import java.nio.charset.StandardCharsets;+import java.util.LinkedHashSet;+import java.util.Set;++import static org.assertj.core.api.Assertions.assertThat;+import static org.junit.jupiter.api.Assertions.assertAll;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assumptions.assumeFalse;++@DisplayName("ACM imported certificate key pairs")+class AcmImportKeyPairTest {+ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ @DisplayName("Mismatched keys are refused without replacing an imported certificate")+ void refusesMismatchedKeysAndAcceptsAMatchingRetry(boolean reimport) throws Exception {+ assumeFalse(TestFixtures.isRealAws(), "Local import fixtures and error mapping");+ byte[][] first = AcmTest.generateSelfSignedCert();+ byte[][] replacement = AcmTest.generateSelfSignedCert();+ Set<String> owned = new LinkedHashSet<>();+ try (AcmClient acm = TestFixtures.acmClient()) {+ try {+ String prior = reimport ? importPair(acm, first, null, owned) : null;+ byte[] certificate = reimport ? replacement[0] : first[0];+ byte[] mismatchedKey = reimport ? first[1] : replacement[1];+ AcmException refusal = assertThrows(AcmException.class, () -> {+ String unexpected = acm.importCertificate(b -> b.certificate(SdkBytes.fromByteArray(certificate))+ .privateKey(SdkBytes.fromByteArray(mismatchedKey)).certificateArn(prior)).certificateArn();+ owned.add(unexpected);+ });+ assertThat(refusal.statusCode()).isEqualTo(400);+ assertThat(refusal.awsErrorDetails().errorCode()).isEqualTo("ValidationException");+ if (reimport) {+ assertThat(acm.getCertificate(b -> b.certificateArn(prior)).certificate())+ .isEqualTo(new String(first[0], StandardCharsets.UTF_8));+ }+ byte[][] matching = reimport ? replacement : first;+ String retry = importPair(acm, matching, prior, owned);+ if (reimport) {+ assertThat(retry).isEqualTo(prior);+ }+ assertThat(acm.getCertificate(b -> b.certificateArn(retry)).certificate())+ .isEqualTo(new String(matching[0], StandardCharsets.UTF_8));+ } finally {+ assertAll("Delete every owned imported certificate", owned.stream().map(arn ->+ (Executable) () -> acm.deleteCertificate(b -> b.certificateArn(arn))));+ }+ }+ }++ private static String importPair(AcmClient acm, byte[][] material, String prior, Set<String> owned) {+ String arn = acm.importCertificate(b -> b.certificate(SdkBytes.fromByteArray(material[0]))+ .privateKey(SdkBytes.fromByteArray(material[1])).certificateArn(prior)).certificateArn();+ owned.add(arn);+ return arn;+ }+}diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AcmTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AcmTest.javaindex 8ee0f1211b..f8d3602495 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AcmTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AcmTest.java@@ -65,7 +65,7 @@ class AcmTest {// ============================================// Helper: generate a self-signed certificate using openssl// ============================================- private static byte[][] generateSelfSignedCert() throws Exception {+ static byte[][] generateSelfSignedCert() throws Exception {Path keyFile = Files.createTempFile("test-key", ".pem");Path certFile = Files.createTempFile("test-cert", ".pem");try {diff --git a/docs/services/acm.md b/docs/services/acm.mdindex b9f1275637..080ab80c16 100644--- a/docs/services/acm.md+++ b/docs/services/acm.md@@ -36,6 +36,7 @@- **Key Algorithms:** `RequestCertificate` accepts `RSA_2048`, `EC_prime256v1`, and `EC_secp384r1` and rejects the rest with a `ValidationException`, matching real ACM; the wider list (`RSA_1024`, `RSA_3072`, `RSA_4096`, `EC_secp521r1`) remains valid for `ImportCertificate`- **Alternative names:** `RequestCertificate` rejects an explicit empty `SubjectAlternativeNames` array with `ValidationException`, since the API requires at least one name in it; omit the field when there are no additional names. An `AWS::CertificateManager::Certificate` resource still accepts an empty array and requests the certificate for `DomainName` alone, but the CloudFormation template reference also lists a one-item minimum, so omit the property in templates that also deploy to AWS.- **Certificate Types:** `AMAZON_ISSUED` (default) and `PRIVATE` (when `CertificateAuthorityArn` is provided)+- **Imported keys:** `ImportCertificate` requires a private key that matches the certificate. A rejected import leaves an existing certificate unchanged.- **Export:** Only `PRIVATE` type certificates can be exported with their private key- **In use:** `DescribeCertificate` lists under `InUseBy` the CloudFront distribution of each Cognito custom domain that uses the certificate, and `DeleteCertificate` refuses with `ResourceInUseException` while that list is not empty. Other consumers, such as load balancers and API Gateway domain names, are not tracked yet.diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java b/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.javaindex 0aa71496ca..ee31a1b9fb 100644--- a/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java+++ b/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java@@ -402,7 +402,9 @@ public class AcmService implements ResourceProvider {// Parse and validate private keytry {- Pem.parsePrivateKey(privateKeyPem);+ if (!Pem.isPair(Pem.parsePrivateKey(privateKeyPem), x509Cert.getPublicKey())) {+ throw new IllegalArgumentException("The private key does not match the certificate");+ }} catch (Exception e) {throw new AwsException("ValidationException", "Invalid private key: " + e.getMessage(), 400);}diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmServiceTest.javaindex d6825ec6f4..039dfaa9fa 100644--- a/src/test/java/io/github/hectorvent/floci/services/acm/AcmServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmServiceTest.java@@ -73,6 +73,46 @@ class AcmServiceTest {service = newService(0);}+ @ParameterizedTest+ @EnumSource(value = KeyAlgorithm.class, names = {"RSA_2048", "EC_prime256v1"})+ void importRefusesAMismatchedKeyWithoutAllocatingACertificate(KeyAlgorithm algorithm) {+ CertificateGenerator.GeneratedCertificate first = generator.generateSelfSignedCertificate(+ "import.example.test", List.of(), algorithm);+ CertificateGenerator.GeneratedCertificate other = generator.generateSelfSignedCertificate(+ "other.example.test", List.of(), algorithm);+ AwsException failure = assertThrows(AwsException.class, () -> service.importCertificate(+ first.certificatePem(), other.privateKeyPem(), null, null, null, REGION));+ assertEquals("ValidationException", failure.getErrorCode());+ assertTrue(service.getResources().isEmpty());+ Certificate retry = service.importCertificate(first.certificatePem(), first.privateKeyPem(),+ null, null, null, REGION);+ assertEquals(first.certificatePem(), service.getCertificate(retry.getArn(), REGION).getCertificateBody());+ assertEquals(first.privateKeyPem(), service.getCertificate(retry.getArn(), REGION).getPrivateKey());+ }++ @ParameterizedTest+ @EnumSource(value = KeyAlgorithm.class, names = {"RSA_2048", "EC_prime256v1"})+ void reimportRefusesAMismatchedKeyWithoutReplacingTheExistingMaterial(KeyAlgorithm algorithm) {+ CertificateGenerator.GeneratedCertificate original = generator.generateSelfSignedCertificate(+ "existing.example.test", List.of(), algorithm);+ Certificate existing = service.importCertificate(original.certificatePem(), original.privateKeyPem(),+ null, null, null, REGION);+ CertificateGenerator.GeneratedCertificate replacement = generator.generateSelfSignedCertificate(+ "replacement.example.test", List.of(), algorithm);+ AwsException failure = assertThrows(AwsException.class, () -> service.importCertificate(+ replacement.certificatePem(), original.privateKeyPem(), null, existing.getArn(), null, REGION));+ assertEquals("ValidationException", failure.getErrorCode());+ Certificate unchanged = service.getCertificate(existing.getArn(), REGION);+ assertEquals(original.certificatePem(), unchanged.getCertificateBody());+ assertEquals(original.privateKeyPem(), unchanged.getPrivateKey());+ assertEquals(1, service.getResources().size());+ Certificate retry = service.importCertificate(replacement.certificatePem(), replacement.privateKeyPem(),+ null, existing.getArn(), null, REGION);+ assertEquals(existing.getArn(), retry.getArn());+ assertEquals(replacement.certificatePem(), service.getCertificate(existing.getArn(), REGION).getCertificateBody());+ assertEquals(replacement.privateKeyPem(), service.getCertificate(existing.getArn(), REGION).getPrivateKey());+ }+private AcmService newService(int validationWaitSeconds) {RegionResolver regionResolver = mock(RegionResolver.class);when(regionResolver.getAccountId()).thenReturn("000000000000");