diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/AcmJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/acm/AcmJsonHandler.java index d46986bc4a..8008ef7a03 100644 --- a/src/main/java/io/github/hectorvent/floci/services/acm/AcmJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/acm/AcmJsonHandler.java @@ -1,17 +1,31 @@ package io.github.hectorvent.floci.services.acm; -import io.github.hectorvent.floci.core.common.AwsErrorResponse; -import io.github.hectorvent.floci.services.acm.model.*; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.acm.model.Certificate; +import io.github.hectorvent.floci.services.acm.model.CertificateOptions; +import io.github.hectorvent.floci.services.acm.model.CertificateStatus; +import io.github.hectorvent.floci.services.acm.model.DomainValidation; +import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; +import io.github.hectorvent.floci.services.acm.model.ListResult; +import io.github.hectorvent.floci.services.acm.model.ResourceRecord; +import io.github.hectorvent.floci.services.acm.model.RevocationReason; +import io.github.hectorvent.floci.services.acm.model.ValidationMethod; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; -import java.util.*; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; /** * JSON handler for AWS Certificate Manager (ACM) API operations. @@ -118,7 +132,7 @@ public class AcmJsonHandler { // AWS returns RequestInProgressException for certificates still pending validation if (cert.getStatus() == CertificateStatus.PENDING_VALIDATION) { - throw new io.github.hectorvent.floci.core.common.AwsException( + throw new AwsException( "RequestInProgressException", "The certificate request is in progress. The certificate body is not yet available.", 400); @@ -322,7 +336,7 @@ public class AcmJsonHandler { } String value = optionsNode.path(field).asText(); if (!"ENABLED".equals(value) && !"DISABLED".equals(value)) { - throw new io.github.hectorvent.floci.core.common.AwsException( + throw new AwsException( "ValidationException", field + " must be ENABLED or DISABLED", 400); } return value; @@ -525,7 +539,7 @@ public class AcmJsonHandler { String domainName = option.path("DomainName").asText(null); String validationDomain = option.path("ValidationDomain").asText(null); if (domainName == null || domainName.isBlank() || validationDomain == null || validationDomain.isBlank()) { - throw new io.github.hectorvent.floci.core.common.AwsException( + throw new AwsException( "InvalidDomainValidationOptionsException", "One or more values in the DomainValidationOption structure is incorrect.", 400); @@ -540,7 +554,7 @@ public class AcmJsonHandler { try { return ValidationMethod.valueOf(method.toUpperCase()); } catch (IllegalArgumentException e) { - throw new io.github.hectorvent.floci.core.common.AwsException( + throw new AwsException( "ValidationException", "Invalid validation method: " + method + ". Must be DNS or EMAIL.", 400); 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.java index f157d26211..738bea7293 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 @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.acm; +import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.config.FlociCertificateAuthority; import io.github.hectorvent.floci.core.common.AwsArnUtils; @@ -10,8 +11,17 @@ import io.github.hectorvent.floci.core.resource.ResourceProvider; import io.github.hectorvent.floci.core.resource.SupportedResourceType; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; -import io.github.hectorvent.floci.services.acm.model.*; -import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.services.acm.model.Certificate; +import io.github.hectorvent.floci.services.acm.model.CertificateOptions; +import io.github.hectorvent.floci.services.acm.model.CertificateStatus; +import io.github.hectorvent.floci.services.acm.model.CertificateType; +import io.github.hectorvent.floci.services.acm.model.DomainValidation; +import io.github.hectorvent.floci.services.acm.model.IdempotencyTokenEntry; +import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; +import io.github.hectorvent.floci.services.acm.model.ListResult; +import io.github.hectorvent.floci.services.acm.model.ResourceRecord; +import io.github.hectorvent.floci.services.acm.model.RevocationReason; +import io.github.hectorvent.floci.services.acm.model.ValidationMethod; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -21,9 +31,22 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.time.Instant; -import java.util.*; -import java.util.LinkedHashSet; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; import java.util.HexFormat; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java b/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java index e87d9482c8..9d7770d2fc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java +++ b/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java @@ -3,7 +3,10 @@ package io.github.hectorvent.floci.services.acm; import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; import jakarta.enterprise.context.ApplicationScoped; import org.bouncycastle.asn1.ASN1Primitive; +import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo; +import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.BasicConstraints; @@ -20,6 +23,7 @@ import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.openssl.PEMKeyPair; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; @@ -27,14 +31,9 @@ import org.bouncycastle.openssl.jcajce.JcePEMEncryptorBuilder; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo; -import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.util.io.pem.PemObject; import org.jboss.logging.Logger; -import javax.crypto.Cipher; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.PBEParameterSpec; import java.io.StringReader; import java.io.StringWriter; import java.math.BigInteger; @@ -49,6 +48,8 @@ import java.security.Security; import java.security.Signature; import java.security.cert.X509Certificate; import java.security.interfaces.ECKey; +import java.security.interfaces.ECPublicKey; +import java.security.interfaces.RSAPublicKey; import java.security.spec.ECGenParameterSpec; import java.time.Instant; import java.time.temporal.ChronoUnit; @@ -58,6 +59,11 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.PBEParameterSpec; @ApplicationScoped public class CertificateGenerator { @@ -347,7 +353,7 @@ public class CertificateGenerator { String raw = stripBrackets(san); byte[] addr = InetAddress.getByName(raw).getAddress(); return new GeneralName(GeneralName.iPAddress, - new org.bouncycastle.asn1.DEROctetString(addr)); + new DEROctetString(addr)); } catch (Exception e) { // Only a malformed IPv6 literal reaches this: IPv4 is range-checked before it // gets here, and a value only arrives with a colon and a literal-shaped first @@ -448,18 +454,18 @@ public class CertificateGenerator { // salt and iteration count are passed explicitly so the output does not depend // on provider defaults. The ASN.1 below only wraps the result, so it needs no // provider either. - var secretKey = SecretKeyFactory.getInstance(PBE_ALGORITHM) + SecretKey secretKey = SecretKeyFactory.getInstance(PBE_ALGORITHM) .generateSecret(new PBEKeySpec(passphrase.toCharArray())); - var salt = new byte[PBE_SALT_BYTES]; + byte[] salt = new byte[PBE_SALT_BYTES]; SECURE_RANDOM.nextBytes(salt); - var cipher = Cipher.getInstance(PBE_ALGORITHM); + Cipher cipher = Cipher.getInstance(PBE_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new PBEParameterSpec(salt, PBE_ITERATIONS)); - var ciphertext = cipher.doFinal(privateKey.getEncoded()); + byte[] ciphertext = cipher.doFinal(privateKey.getEncoded()); - var scheme = new AlgorithmIdentifier( + AlgorithmIdentifier scheme = new AlgorithmIdentifier( PKCSObjectIdentifiers.id_PBES2, ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())); - var encryptedInfo = + PKCS8EncryptedPrivateKeyInfo encryptedInfo = new PKCS8EncryptedPrivateKeyInfo(new EncryptedPrivateKeyInfo(scheme, ciphertext)); StringWriter sw = new StringWriter(); @@ -493,10 +499,10 @@ public class CertificateGenerator { Object obj = parser.readObject(); JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); - if (obj instanceof org.bouncycastle.openssl.PEMKeyPair pemKeyPair) { + if (obj instanceof PEMKeyPair pemKeyPair) { // Only the private half is needed, and a SEC1 key may carry no public half at all. return converter.getPrivateKey(pemKeyPair.getPrivateKeyInfo()); - } else if (obj instanceof org.bouncycastle.asn1.pkcs.PrivateKeyInfo pkInfo) { + } else if (obj instanceof PrivateKeyInfo pkInfo) { return converter.getPrivateKey(pkInfo); } throw new IllegalArgumentException("Invalid private key PEM format"); @@ -518,7 +524,7 @@ public class CertificateGenerator { String algorithm = publicKey.getAlgorithm(); if ("RSA".equals(algorithm)) { try { - java.security.interfaces.RSAPublicKey rsaKey = (java.security.interfaces.RSAPublicKey) publicKey; + RSAPublicKey rsaKey = (RSAPublicKey) publicKey; int keySize = rsaKey.getModulus().bitLength(); return switch (keySize) { case 1024 -> KeyAlgorithm.RSA_1024; @@ -531,7 +537,7 @@ public class CertificateGenerator { } } else if ("EC".equals(algorithm)) { try { - java.security.interfaces.ECPublicKey ecKey = (java.security.interfaces.ECPublicKey) publicKey; + ECPublicKey ecKey = (ECPublicKey) publicKey; int fieldSize = ecKey.getParams().getCurve().getField().getFieldSize(); return switch (fieldSize) { case 384 -> KeyAlgorithm.EC_secp384r1; diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmEdgeCaseTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmEdgeCaseTest.java index a763690301..0aaad9e636 100644 --- a/src/test/java/io/github/hectorvent/floci/services/acm/AcmEdgeCaseTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmEdgeCaseTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.acm; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.json.JsonPath; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -117,7 +118,7 @@ class AcmEdgeCaseTest { .body("CertificateArn", startsWith("arn:aws:acm:")) .extract().jsonPath().getString("CertificateArn"); - var validationOptions = given() + JsonPath validationOptions = given() .header("X-Amz-Target", "CertificateManager.DescribeCertificate") .contentType(ACM_CONTENT_TYPE) .body(""" diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmIdempotencyTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmIdempotencyTest.java index 0ad8f24a1e..ecb096a997 100644 --- a/src/test/java/io/github/hectorvent/floci/services/acm/AcmIdempotencyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmIdempotencyTest.java @@ -13,6 +13,8 @@ import java.util.UUID; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; /** * Tests for idempotency token functionality with 1-hour TTL. @@ -68,8 +70,8 @@ class AcmIdempotencyTest { .body("CertificateArn", equalTo(firstArn)) .extract().jsonPath().getString("CertificateArn"); - // ARNs should match - org.junit.jupiter.api.Assertions.assertEquals(firstArn, secondArn); + // Both should return the same certificate ARN + assertEquals(firstArn, secondArn); } @Test @@ -110,7 +112,7 @@ class AcmIdempotencyTest { .extract().jsonPath().getString("CertificateArn"); // ARNs should be different - org.junit.jupiter.api.Assertions.assertNotEquals(firstArn, secondArn); + assertNotEquals(firstArn, secondArn); } @Test @@ -225,7 +227,7 @@ class AcmIdempotencyTest { .statusCode(200) .extract().jsonPath().getString("CertificateArn"); - org.junit.jupiter.api.Assertions.assertNotEquals(firstArn, secondArn); + assertNotEquals(firstArn, secondArn); } @Test @@ -268,6 +270,6 @@ class AcmIdempotencyTest { .statusCode(200) .extract().jsonPath().getString("CertificateArn"); - org.junit.jupiter.api.Assertions.assertEquals(firstArn, secondArn); + assertEquals(firstArn, secondArn); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmIntegrationTest.java index cb784500f7..d00a2bcde2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/acm/AcmIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmIntegrationTest.java @@ -271,7 +271,7 @@ class AcmIntegrationTest { @Test @Order(12) void getCertificate() throws Exception { - var response = getCertificatePems(createdCertificateArn); + JsonPath response = getCertificatePems(createdCertificateArn); X509Certificate leaf = assertLeafChainsToLocalCa(response.getString("Certificate"), response.getString("CertificateChain")); @@ -353,7 +353,7 @@ class AcmIntegrationTest { .statusCode(200) .extract().jsonPath().getString("CertificateArn"); - var response = getCertificatePems(arn); + JsonPath response = getCertificatePems(arn); assertLeafChainsToLocalCa(response.getString("Certificate"), response.getString("CertificateChain")); } @@ -361,7 +361,7 @@ class AcmIntegrationTest { @Test @Order(17) void ecCertificateKeepsItsKeyAlgorithmAndChainsToTheSameCa() throws Exception { - var response = getCertificatePems(ecCertificateArn); + JsonPath response = getCertificatePems(ecCertificateArn); X509Certificate leaf = assertLeafChainsToLocalCa(response.getString("Certificate"), response.getString("CertificateChain")); diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmResendValidationEmailIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmResendValidationEmailIntegrationTest.java index c4feee702b..90578cbe33 100644 --- a/src/test/java/io/github/hectorvent/floci/services/acm/AcmResendValidationEmailIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmResendValidationEmailIntegrationTest.java @@ -6,6 +6,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; @QuarkusTest class AcmResendValidationEmailIntegrationTest { @@ -54,7 +55,7 @@ class AcmResendValidationEmailIntegrationTest { .post("/") .then() .statusCode(400) - .body("__type", org.hamcrest.Matchers.equalTo("InvalidDomainValidationOptionsException")); + .body("__type", equalTo("InvalidDomainValidationOptionsException")); } @Test @@ -80,7 +81,7 @@ class AcmResendValidationEmailIntegrationTest { .post("/") .then() .statusCode(400) - .body("__type", org.hamcrest.Matchers.equalTo("InvalidDomainValidationOptionsException")); + .body("__type", equalTo("InvalidDomainValidationOptionsException")); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmValidationDomainIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmValidationDomainIntegrationTest.java index 8233f3c148..4beb488bc5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/acm/AcmValidationDomainIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmValidationDomainIntegrationTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.acm; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -118,7 +119,7 @@ class AcmValidationDomainIntegrationTest { .body("__type", Matchers.equalTo("InvalidDomainValidationOptionsException")); } - private static io.restassured.response.ValidatableResponse requestCertificate(String body) { + private static ValidatableResponse requestCertificate(String body) { return given() .header("X-Amz-Target", "CertificateManager.RequestCertificate") .contentType(ACM_CONTENT_TYPE) @@ -128,7 +129,7 @@ class AcmValidationDomainIntegrationTest { .then(); } - private static io.restassured.response.ValidatableResponse describeCertificate(String certificateArn) { + private static ValidatableResponse describeCertificate(String certificateArn) { return given() .header("X-Amz-Target", "CertificateManager.DescribeCertificate") .contentType(ACM_CONTENT_TYPE) diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorIssuerTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorIssuerTest.java index 1db19d77ea..b887f8fdbb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorIssuerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorIssuerTest.java @@ -1,5 +1,8 @@ package io.github.hectorvent.floci.services.acm; +import io.github.hectorvent.floci.services.acm.CertificateGenerator.GeneratedCertificate; +import io.github.hectorvent.floci.services.acm.CertificateGenerator.Issuer; +import io.github.hectorvent.floci.services.acm.CertificateGenerator.LeafUsage; import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.jupiter.api.BeforeAll; @@ -7,14 +10,17 @@ import org.junit.jupiter.api.Test; import java.math.BigInteger; import java.security.KeyPair; +import java.security.KeyPairGenerator; import java.security.Security; import java.security.cert.X509Certificate; +import java.security.spec.ECGenParameterSpec; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -33,15 +39,15 @@ class CertificateGeneratorIssuerTest { generator = new CertificateGenerator(); } - private static CertificateGenerator.Issuer newIssuer() { - var ca = generator.generateCaCertificate("Floci Local CA"); - return new CertificateGenerator.Issuer( + private static Issuer newIssuer() { + GeneratedCertificate ca = generator.generateCaCertificate("Floci Local CA"); + return new Issuer( generator.parseCertificate(ca.certificatePem()), generator.parsePrivateKey(ca.privateKeyPem())); } @Test void caCertificateIsSelfSignedAndCanSign() throws Exception { - var ca = generator.generateCaCertificate("Floci Local CA"); + GeneratedCertificate ca = generator.generateCaCertificate("Floci Local CA"); X509Certificate cert = generator.parseCertificate(ca.certificatePem()); assertEquals(cert.getSubjectX500Principal(), cert.getIssuerX500Principal()); @@ -57,10 +63,10 @@ class CertificateGeneratorIssuerTest { @Test void issuedLeafVerifiesAgainstIssuerAndCarriesServerAuth() throws Exception { - var issuer = newIssuer(); + Issuer issuer = newIssuer(); - var leaf = generator.generateIssuedCertificate("api.example.test", List.of("*.example.test"), - KeyAlgorithm.RSA_2048, null, issuer, CertificateGenerator.LeafUsage.SERVER); + GeneratedCertificate leaf = generator.generateIssuedCertificate("api.example.test", List.of("*.example.test"), + KeyAlgorithm.RSA_2048, null, issuer, LeafUsage.SERVER); X509Certificate cert = generator.parseCertificate(leaf.certificatePem()); assertEquals(issuer.certificate().getSubjectX500Principal(), cert.getIssuerX500Principal()); @@ -87,15 +93,15 @@ class CertificateGeneratorIssuerTest { @Test void issuedLeafReusesSuppliedKeyPairAndClientUsage() throws Exception { - var issuer = newIssuer(); - var first = generator.generateIssuedCertificate("device-1", List.of(), KeyAlgorithm.RSA_2048, null, issuer, - CertificateGenerator.LeafUsage.CLIENT); - var keyPair = new KeyPair( + Issuer issuer = newIssuer(); + GeneratedCertificate first = generator.generateIssuedCertificate("device-1", List.of(), KeyAlgorithm.RSA_2048, null, issuer, + LeafUsage.CLIENT); + KeyPair keyPair = new KeyPair( generator.parseCertificate(first.certificatePem()).getPublicKey(), generator.parsePrivateKey(first.privateKeyPem())); - var second = generator.generateIssuedCertificate("device-1", List.of(), KeyAlgorithm.RSA_2048, keyPair, issuer, - CertificateGenerator.LeafUsage.CLIENT); + GeneratedCertificate second = generator.generateIssuedCertificate("device-1", List.of(), KeyAlgorithm.RSA_2048, keyPair, issuer, + LeafUsage.CLIENT); X509Certificate cert = generator.parseCertificate(second.certificatePem()); assertEquals(keyPair.getPublic(), cert.getPublicKey(), "supplied key pair must be reused"); @@ -107,10 +113,10 @@ class CertificateGeneratorIssuerTest { @Test void ecLeafSignedByRsaCaReportsTheIssuerAlgorithmAndNoKeyEncipherment() throws Exception { - var issuer = newIssuer(); + Issuer issuer = newIssuer(); - var leaf = generator.generateIssuedCertificate("ec.example.test", null, KeyAlgorithm.EC_prime256v1, null, - issuer, CertificateGenerator.LeafUsage.SERVER); + GeneratedCertificate leaf = generator.generateIssuedCertificate("ec.example.test", null, KeyAlgorithm.EC_prime256v1, null, + issuer, LeafUsage.SERVER); X509Certificate cert = generator.parseCertificate(leaf.certificatePem()); assertEquals("EC", cert.getPublicKey().getAlgorithm()); @@ -123,69 +129,72 @@ class CertificateGeneratorIssuerTest { @Test void anIssuerWhoseKeyDoesNotMatchItsCertificateIsRefused() { - var one = generator.generateCaCertificate("One"); - var other = generator.generateCaCertificate("Other"); - var mismatched = new CertificateGenerator.Issuer( + GeneratedCertificate one = generator.generateCaCertificate("One"); + GeneratedCertificate other = generator.generateCaCertificate("Other"); + Issuer mismatched = new Issuer( generator.parseCertificate(one.certificatePem()), generator.parsePrivateKey(other.privateKeyPem())); - var refused = org.junit.jupiter.api.Assertions.assertThrows(CertificateGenerationException.class, + CertificateGenerationException refused = assertThrows(CertificateGenerationException.class, () -> generator.generateIssuedCertificate("x.example.test", List.of(), KeyAlgorithm.RSA_2048, null, - mismatched, CertificateGenerator.LeafUsage.SERVER)); + mismatched, LeafUsage.SERVER)); assertTrue(refused.getMessage().contains("Signature"), refused.getMessage()); } @Test void aSuppliedKeyPairThatIsNotAPairIsRefused() { - var issuer = newIssuer(); - var a = generator.generateIssuedCertificate("a", List.of(), KeyAlgorithm.RSA_2048, null, issuer, - CertificateGenerator.LeafUsage.CLIENT); - var b = generator.generateIssuedCertificate("b", List.of(), KeyAlgorithm.RSA_2048, null, issuer, - CertificateGenerator.LeafUsage.CLIENT); - var notAPair = new KeyPair(generator.parseCertificate(a.certificatePem()).getPublicKey(), + Issuer issuer = newIssuer(); + GeneratedCertificate a = generator.generateIssuedCertificate("a", List.of(), KeyAlgorithm.RSA_2048, null, issuer, + LeafUsage.CLIENT); + GeneratedCertificate b = generator.generateIssuedCertificate("b", List.of(), KeyAlgorithm.RSA_2048, null, issuer, + LeafUsage.CLIENT); + KeyPair notAPair = new KeyPair(generator.parseCertificate(a.certificatePem()).getPublicKey(), generator.parsePrivateKey(b.privateKeyPem())); - var refused = org.junit.jupiter.api.Assertions.assertThrows(CertificateGenerationException.class, + CertificateGenerationException refused = assertThrows(CertificateGenerationException.class, () -> generator.generateIssuedCertificate("a", List.of(), KeyAlgorithm.RSA_2048, notAPair, issuer, - CertificateGenerator.LeafUsage.CLIENT)); + LeafUsage.CLIENT)); assertTrue(refused.getMessage().contains("does not match"), refused.getMessage()); } @Test void aSuppliedKeyPairOfAnotherAlgorithmIsRefused() { - var issuer = newIssuer(); - var rsa = generator.generateIssuedCertificate("a", List.of(), KeyAlgorithm.RSA_2048, null, issuer, - CertificateGenerator.LeafUsage.CLIENT); - var rsaPair = new KeyPair(generator.parseCertificate(rsa.certificatePem()).getPublicKey(), + Issuer issuer = newIssuer(); + GeneratedCertificate rsa = generator.generateIssuedCertificate("a", List.of(), KeyAlgorithm.RSA_2048, null, issuer, + LeafUsage.CLIENT); + KeyPair rsaPair = new KeyPair(generator.parseCertificate(rsa.certificatePem()).getPublicKey(), generator.parsePrivateKey(rsa.privateKeyPem())); - var refused = org.junit.jupiter.api.Assertions.assertThrows(CertificateGenerationException.class, + CertificateGenerationException refused = assertThrows(CertificateGenerationException.class, () -> generator.generateIssuedCertificate("a", List.of(), KeyAlgorithm.EC_prime256v1, rsaPair, issuer, - CertificateGenerator.LeafUsage.CLIENT)); + LeafUsage.CLIENT)); assertTrue(refused.getMessage().contains("not the requested EC_prime256v1"), refused.getMessage()); } @Test void aSuppliedEcKeyPairOnACurveOfTheSameSizeIsRefused() throws Exception { - var issuer = newIssuer(); - java.security.KeyPairGenerator kpg = java.security.KeyPairGenerator.getInstance("EC", "BC"); - kpg.initialize(new java.security.spec.ECGenParameterSpec("secp256k1")); + // secp256k1 is an EC curve, but not the NIST P-256 prime256v1 ACM specifies: handing a + // k1 key to an EC_prime256v1 request must be rejected rather than issuing a certificate + // with the wrong curve. + Issuer issuer = newIssuer(); + KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", "BC"); + kpg.initialize(new ECGenParameterSpec("secp256k1")); KeyPair k1 = kpg.generateKeyPair(); - kpg.initialize(new java.security.spec.ECGenParameterSpec("secp256r1")); + kpg.initialize(new ECGenParameterSpec("secp256r1")); KeyPair p256 = kpg.generateKeyPair(); - var refused = org.junit.jupiter.api.Assertions.assertThrows(CertificateGenerationException.class, + CertificateGenerationException refused = assertThrows(CertificateGenerationException.class, () -> generator.generateIssuedCertificate("a", List.of(), KeyAlgorithm.EC_prime256v1, k1, issuer, - CertificateGenerator.LeafUsage.CLIENT)); + LeafUsage.CLIENT)); assertTrue(refused.getMessage().contains("not the requested EC_prime256v1"), refused.getMessage()); - var accepted = generator.generateIssuedCertificate("a", List.of(), KeyAlgorithm.EC_prime256v1, p256, issuer, - CertificateGenerator.LeafUsage.CLIENT); + GeneratedCertificate accepted = generator.generateIssuedCertificate("a", List.of(), KeyAlgorithm.EC_prime256v1, p256, issuer, + LeafUsage.CLIENT); assertEquals(p256.getPublic(), generator.parseCertificate(accepted.certificatePem()).getPublicKey()); } @Test void duplicateSansAreWrittenOnce() throws Exception { - var leaf = generator.generateIssuedCertificate("dup.example.test", List.of("dup.example.test", "other.example.test", - "other.example.test"), KeyAlgorithm.RSA_2048, null, newIssuer(), CertificateGenerator.LeafUsage.SERVER); + GeneratedCertificate leaf = generator.generateIssuedCertificate("dup.example.test", List.of("dup.example.test", "other.example.test", + "other.example.test"), KeyAlgorithm.RSA_2048, null, newIssuer(), LeafUsage.SERVER); X509Certificate cert = generator.parseCertificate(leaf.certificatePem()); assertEquals(List.of("dup.example.test", "other.example.test"), @@ -194,7 +203,7 @@ class CertificateGeneratorIssuerTest { @Test void existingSelfSignedPathIsUnchanged() throws Exception { - var selfSigned = generator.generateSelfSignedCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048); + GeneratedCertificate selfSigned = generator.generateSelfSignedCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048); X509Certificate ss = generator.parseCertificate(selfSigned.certificatePem()); assertEquals(ss.getSubjectX500Principal(), ss.getIssuerX500Principal()); assertTrue(ss.getBasicConstraints() >= 0); @@ -206,10 +215,10 @@ class CertificateGeneratorIssuerTest { @Test void ecPrivateKeysAreWrittenAsPkcs8AndReadBack() throws Exception { - var ec = generator.generateIssuedCertificate("ec.example.test", List.of(), KeyAlgorithm.EC_secp384r1, null, - newIssuer(), CertificateGenerator.LeafUsage.SERVER); - var rsa = generator.generateIssuedCertificate("rsa.example.test", List.of(), KeyAlgorithm.RSA_2048, null, - newIssuer(), CertificateGenerator.LeafUsage.CLIENT); + GeneratedCertificate ec = generator.generateIssuedCertificate("ec.example.test", List.of(), KeyAlgorithm.EC_secp384r1, null, + newIssuer(), LeafUsage.SERVER); + GeneratedCertificate rsa = generator.generateIssuedCertificate("rsa.example.test", List.of(), KeyAlgorithm.RSA_2048, null, + newIssuer(), LeafUsage.CLIENT); assertTrue(ec.privateKeyPem().startsWith("-----BEGIN PRIVATE KEY-----"), "PKCS#8 carries the curve"); assertTrue(rsa.privateKeyPem().startsWith("-----BEGIN RSA PRIVATE KEY-----"), "RSA stays PKCS#1, as AWS IoT hands out"); diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSanTypeTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSanTypeTest.java index 15cd1c9c60..72ae68df3c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSanTypeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSanTypeTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.acm; +import io.github.hectorvent.floci.services.acm.CertificateGenerator.GeneratedCertificate; import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.jce.provider.BouncyCastleProvider; @@ -37,7 +38,7 @@ class CertificateGeneratorSanTypeTest { @Test void ipv4AddressEncodedAsIpAddressSanType() throws Exception { - var cert = generator.generateSelfSignedCertificate( + GeneratedCertificate cert = generator.generateSelfSignedCertificate( "localhost", List.of("localhost", "192.168.1.100"), KeyAlgorithm.RSA_2048); @@ -56,7 +57,7 @@ class CertificateGeneratorSanTypeTest { @Test void ipv6LoopbackEncodedAsIpAddressSanType() throws Exception { - var cert = generator.generateSelfSignedCertificate( + GeneratedCertificate cert = generator.generateSelfSignedCertificate( "localhost", List.of("localhost", "0.0.0.0", "::1"), KeyAlgorithm.RSA_2048); @@ -81,7 +82,7 @@ class CertificateGeneratorSanTypeTest { @Test void dnsNamesEncodedAsDnsNameSanType() throws Exception { - var cert = generator.generateSelfSignedCertificate( + GeneratedCertificate cert = generator.generateSelfSignedCertificate( "localhost", List.of("myhost.example.com", "floci"), KeyAlgorithm.RSA_2048); @@ -106,7 +107,7 @@ class CertificateGeneratorSanTypeTest { @Test void wildcardEncodedAsDnsNameSanType() throws Exception { - var cert = generator.generateSelfSignedCertificate( + GeneratedCertificate cert = generator.generateSelfSignedCertificate( "localhost", List.of("localhost", "*.localhost"), KeyAlgorithm.RSA_2048); @@ -123,7 +124,7 @@ class CertificateGeneratorSanTypeTest { @Test void mixedIpsAndDnsNamesEncodedCorrectly() throws Exception { - var cert = generator.generateSelfSignedCertificate( + GeneratedCertificate cert = generator.generateSelfSignedCertificate( "localhost", List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost", "floci", "10.0.0.5"), KeyAlgorithm.RSA_2048); @@ -158,7 +159,7 @@ class CertificateGeneratorSanTypeTest { @ParameterizedTest @ValueSource(strings = {"1234", "0", "beef", "cafe", "abcd"}) void hexShapedLabelsAreDnsNamesNotAddresses(String name) throws Exception { - var cert = generator.generateSelfSignedCertificate( + GeneratedCertificate cert = generator.generateSelfSignedCertificate( "localhost", List.of("localhost", name), KeyAlgorithm.RSA_2048); X509Certificate x509 = generator.parseCertificate(cert.certificatePem()); @@ -183,7 +184,7 @@ class CertificateGeneratorSanTypeTest { /** A malformed IPv6 literal still reaches the DNS-name fallback rather than being dropped. */ @Test void aMalformedIpv6LiteralIsStillCoveredAsADnsName() throws Exception { - var cert = generator.generateSelfSignedCertificate( + GeneratedCertificate cert = generator.generateSelfSignedCertificate( "localhost", List.of("localhost", "fffff::1"), KeyAlgorithm.RSA_2048); X509Certificate x509 = generator.parseCertificate(cert.certificatePem()); diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSelfSignedTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSelfSignedTest.java index 07ee42c845..4fb1befeba 100644 --- a/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSelfSignedTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSelfSignedTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.acm; +import io.github.hectorvent.floci.services.acm.CertificateGenerator.GeneratedCertificate; import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.jupiter.api.BeforeAll; @@ -31,7 +32,7 @@ class CertificateGeneratorSelfSignedTest { @Test void selfSignedCertificateIsItsOwnIssuerAndACa() throws Exception { - var generated = generator.generateSelfSignedCertificate( + GeneratedCertificate generated = generator.generateSelfSignedCertificate( "localhost", List.of("localhost", "localhost.floci.io"), KeyAlgorithm.RSA_2048); X509Certificate cert = generator.parseCertificate(generated.certificatePem());