Light, fluffy, and always free - The AWS Local Emulator alternative
feat: serve custom domains over TLS as soon as they are created (#3086)
Mario Toffia67bbd2cf1322
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 20e17753fe..d89a27319d 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@@ -12,8 +12,12 @@ import software.amazon.awssdk.core.SdkBytes;import software.amazon.awssdk.services.acm.AcmClient;import software.amazon.awssdk.services.acm.model.*;+import java.io.ByteArrayInputStream;+import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;+import java.security.cert.CertificateFactory;+import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.List;@@ -118,8 +122,8 @@ class AcmTest {@Test@Order(3)- @DisplayName("Get a certificate")- void testGetCertificate() {+ @DisplayName("Get a certificate whose chain validates it")+ void testGetCertificate() throws Exception {Assumptions.assumeTrue(requestedCertArn != null, "RequestCertificate must succeed first");GetCertificateResponse response = acm.getCertificate(b -> b@@ -127,6 +131,20 @@ class AcmTest {assertThat(response.certificate()).isNotNull();assertThat(response.certificate()).contains("BEGIN CERTIFICATE");+ assertThat(response.certificateChain()).isNotNull();++ // Certificate and CertificateChain form a chain of trust: the first chain entry is the+ // issuing CA, so a client that pins the chain can validate the leaf.+ CertificateFactory factory = CertificateFactory.getInstance("X.509");+ X509Certificate leaf = (X509Certificate) factory.generateCertificate(+ new ByteArrayInputStream(response.certificate().getBytes(StandardCharsets.US_ASCII)));+ List<X509Certificate> chain = factory.generateCertificates(+ new ByteArrayInputStream(response.certificateChain().getBytes(StandardCharsets.US_ASCII)))+ .stream().map(X509Certificate.class::cast).toList();+ assertThat(chain).isNotEmpty();+ assertThat(leaf.getIssuerX500Principal()).isEqualTo(chain.get(0).getSubjectX500Principal());+ assertThat(leaf.getBasicConstraints()).isEqualTo(-1);+ leaf.verify(chain.get(0).getPublicKey());}@Testdiff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CustomDomainTlsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CustomDomainTlsTest.javanew file mode 100644index 0000000000..c27127547e--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CustomDomainTlsTest.java@@ -0,0 +1,184 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.Assumptions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.acm.AcmClient;+import software.amazon.awssdk.services.acm.model.GetCertificateResponse;+import software.amazon.awssdk.services.apigateway.ApiGatewayClient;+import software.amazon.awssdk.services.apigateway.model.EndpointConfiguration;+import software.amazon.awssdk.services.apigateway.model.EndpointType;++import javax.net.ssl.SNIHostName;+import javax.net.ssl.SSLContext;+import javax.net.ssl.SSLParameters;+import javax.net.ssl.SSLSocket;+import javax.net.ssl.TrustManagerFactory;+import java.io.ByteArrayInputStream;+import java.io.IOException;+import java.net.InetSocketAddress;+import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;+import java.nio.charset.StandardCharsets;+import java.security.KeyStore;+import java.security.cert.Certificate;+import java.security.cert.CertificateFactory;+import java.security.cert.X509Certificate;+import java.util.Collection;+import java.util.List;+import java.util.Set;+import java.util.TreeSet;++import static org.assertj.core.api.Assertions.assertThat;++/**+ * What a deployment tool does with a custom domain: request an ACM certificate for it, create+ * the API Gateway domain name with that certificate, then reach https://<domain> with a+ * client that trusts only the chain ACM returned. DNS is not involved: the socket goes to the+ * Floci host and carries the domain as SNI, which is what a hosts-file or local DNS setup does.+ *+ * <p>Needs Floci with FLOCI_TLS_ENABLED=true; skipped otherwise. Floci-only: on AWS the+ * certificate would wait for DNS validation.+ */+class CustomDomainTlsTest {++ private static AcmClient acm;+ private static ApiGatewayClient apigw;+ private static String certificateArn;+ private static String domainName;++ @BeforeAll+ static void setup() throws Exception {+ Assumptions.assumeFalse(TestFixtures.isRealAws(), "Floci-only: real AWS needs DNS validation");+ Assumptions.assumeTrue(tlsIsServed(), "needs Floci with FLOCI_TLS_ENABLED=true");+ acm = TestFixtures.acmClient();+ apigw = TestFixtures.apiGatewayClient();+ domainName = TestFixtures.uniqueName("api") + ".dev.localhost.floci.io";+ }++ @AfterAll+ static void cleanup() {+ if (apigw != null) {+ try {+ apigw.deleteDomainName(b -> b.domainName(domainName));+ } catch (Exception e) {+ System.err.println("CustomDomainTlsTest cleanup: deleteDomainName failed: " + e.getMessage());+ }+ apigw.close();+ }+ if (acm != null) {+ if (certificateArn != null) {+ try {+ acm.deleteCertificate(b -> b.certificateArn(certificateArn));+ } catch (Exception e) {+ System.err.println("CustomDomainTlsTest cleanup: deleteCertificate failed: " + e.getMessage());+ }+ }+ acm.close();+ }+ }++ @Test+ void clientTrustingOnlyTheAcmChainReachesTheCustomDomain() throws Exception {+ certificateArn = acm.requestCertificate(b -> b.domainName(domainName).validationMethod("DNS")).certificateArn();+ GetCertificateResponse issued = acm.getCertificate(b -> b.certificateArn(certificateArn));+ assertThat(issued.certificate()).contains("BEGIN CERTIFICATE");+ assertThat(issued.certificateChain()).contains("BEGIN CERTIFICATE");++ apigw.createDomainName(b -> b+ .domainName(domainName)+ .regionalCertificateArn(certificateArn)+ .endpointConfiguration(EndpointConfiguration.builder().types(EndpointType.REGIONAL).build()));++ X509Certificate served = handshake(issued.certificateChain(), domainName);++ assertThat(sans(served)).contains(domainName);+ X509Certificate acmLeaf = parse(issued.certificate()).iterator().next();+ assertThat(served.getIssuerX500Principal()).isEqualTo(acmLeaf.getIssuerX500Principal());+ }++ /**+ * The compatibility workflow runs Floci with FLOCI_TLS_ENABLED=true but hands the tests+ * FLOCI_ENDPOINT=http://floci:4566 (one port serves both), so the URL scheme says nothing+ * about TLS. Probe instead: fetch the CA over plain HTTP and try one handshake against the+ * same host and port.+ */+ private static boolean tlsIsServed() throws Exception {+ String caPem = HttpClient.newHttpClient().send(+ HttpRequest.newBuilder(URI.create("http://" + host() + ":" + port() + "/_floci/ca.pem")).build(),+ HttpResponse.BodyHandlers.ofString()).body();+ if (!caPem.contains("BEGIN CERTIFICATE")) {+ System.err.println("CustomDomainTlsTest: no CA served on " + host() + ":" + port() + ", skipping");+ return false;+ }+ try {+ handshake(caPem, null);+ return true;+ } catch (IOException e) {+ System.err.println("CustomDomainTlsTest: no TLS on " + host() + ":" + port() + " (" + e.getMessage() + "), skipping");+ return false;+ }+ }++ private static String host() {+ return TestFixtures.endpoint().getHost();+ }++ private static int port() {+ URI endpoint = TestFixtures.endpoint();+ if (endpoint.getPort() != -1) {+ return endpoint.getPort();+ }+ return "https".equalsIgnoreCase(endpoint.getScheme()) ? 443 : 80;+ }++ /**+ * TLS to the Floci host trusting only {@code chainPem}. With {@code sniHost} set, sends it as+ * SNI and asks for hostname verification, the way an SDK would; {@code null} is a bare probe.+ * The JDK falls back to the peer host when the SNI name does not match, and the Floci host+ * is always in the certificate, so the SAN assertion in the test is the check that the+ * domain is served, not the handshake alone.+ */+ private static X509Certificate handshake(String chainPem, String sniHost) throws Exception {+ KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());+ trust.load(null, null);+ int i = 0;+ for (X509Certificate ca : parse(chainPem)) {+ trust.setCertificateEntry("chain-" + i++, ca);+ }+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());+ tmf.init(trust);+ SSLContext ctx = SSLContext.getInstance("TLS");+ ctx.init(null, tmf.getTrustManagers(), null);++ try (SSLSocket socket = (SSLSocket) ctx.getSocketFactory().createSocket()) {+ socket.connect(new InetSocketAddress(host(), port()), 5000);+ socket.setSoTimeout(10000);+ if (sniHost != null) {+ SSLParameters params = socket.getSSLParameters();+ params.setServerNames(List.of(new SNIHostName(sniHost)));+ params.setEndpointIdentificationAlgorithm("HTTPS");+ socket.setSSLParameters(params);+ }+ socket.startHandshake();+ return (X509Certificate) socket.getSession().getPeerCertificates()[0];+ }+ }++ private static Collection<X509Certificate> parse(String pem) throws Exception {+ Collection<? extends Certificate> certs = CertificateFactory.getInstance("X.509")+ .generateCertificates(new ByteArrayInputStream(pem.getBytes(StandardCharsets.UTF_8)));+ return certs.stream().map(X509Certificate.class::cast).toList();+ }++ private static Set<String> sans(X509Certificate cert) throws Exception {+ Set<String> out = new TreeSet<>();+ for (List<?> entry : cert.getSubjectAlternativeNames()) {+ out.add(String.valueOf(entry.get(1)));+ }+ return out;+ }+}diff --git a/compatibility-tests/sdk-test-python/tests/test_acm.py b/compatibility-tests/sdk-test-python/tests/test_acm.pyindex f974b60a4e..19e7be2525 100644--- a/compatibility-tests/sdk-test-python/tests/test_acm.py+++ b/compatibility-tests/sdk-test-python/tests/test_acm.py@@ -7,7 +7,7 @@ import pytestfrom botocore.exceptions import ClientErrorfrom cryptography import x509from cryptography.hazmat.primitives import hashes, serialization-from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa+from cryptography.hazmat.primitives.asymmetric import ec, rsafrom cryptography.x509.oid import NameOIDFAKE_ARN = "arn:aws:acm:us-east-1:000000000000:certificate/00000000-0000-0000-0000-000000000000"@@ -42,20 +42,14 @@ class TestACMCertificateLifecycle:arn = response["CertificateArn"]try:- pem = acm_client.get_certificate(CertificateArn=arn)["Certificate"]- certificate = x509.load_pem_x509_certificate(pem.encode())+ response = acm_client.get_certificate(CertificateArn=arn)+ certificate = x509.load_pem_x509_certificate(response["Certificate"].encode())assert isinstance(certificate.public_key(), key_type)- # A certificate whose signature does not match its own contents would- # still parse, so check the self-signature rather than trusting the PEM.- certificate.public_key().verify(- certificate.signature,- certificate.tbs_certificate_bytes,- *(- (ec.ECDSA(certificate.signature_hash_algorithm),)- if isinstance(certificate.public_key(), ec.EllipticCurvePublicKey)- else (padding.PKCS1v15(), certificate.signature_hash_algorithm)- ),- )+ # As on AWS, the certificate is signed by the issuing CA, returned first in+ # CertificateChain, not by its own key: check that signature, not just the PEM.+ issuer = x509.load_pem_x509_certificate(response["CertificateChain"].encode())+ assert certificate.issuer == issuer.subject+ certificate.verify_directly_issued_by(issuer)finally:acm_client.delete_certificate(CertificateArn=arn)diff --git a/docs/configuration/tls.md b/docs/configuration/tls.mdindex 0feb0828be..9c7886dbb0 100644--- a/docs/configuration/tls.md+++ b/docs/configuration/tls.md@@ -8,7 +8,7 @@ Floci supports optional TLS, enabling `https://` for all REST/JSON/Query endpoindocker run -e FLOCI_TLS_ENABLED=true -p 4566:4566 floci/floci:latest```-Then point your SDK at `https://localhost:4566` and trust Floci's local CA in the processes that talk to it. Every certificate Floci issues (its HTTPS endpoint, and in later releases ACM and IoT device certificates) chains to that one CA:+Then point your SDK at `https://localhost:4566` and trust Floci's local CA in the processes that talk to it. Every certificate Floci issues (its HTTPS endpoint, every ACM certificate and, in a later release, IoT device certificates) chains to that one CA:```bashcurl -s http://localhost:4566/_floci/ca.pem -o floci-root-ca.pem@@ -85,6 +85,14 @@ services:The generated certificate will include `floci` in its SANs, so TLS validation succeeds when `app` connects to `https://floci:4566`. Fetch `ca.pem` from Floci into `app` (an entrypoint `curl`, or a shared volume mounted from `{persistent-path}/tls/`) so the bundle path above exists.+### Custom Domains Learned at Runtime++A wildcard SAN matches one label only, so `*.localhost.floci.io` covers `api.localhost.floci.io` but not `api.dev.localhost.floci.io`. For names like that, Floci can add an exact hostname to the server certificate while it runs: the certificate is reissued by the local CA with the same key and the new name, and the HTTPS listener switches to it at once. No restart, no new CA, nothing new for clients to trust. Learned names are recorded in `{persistent-path}/tls/floci-server.metadata.json`, so they survive restarts and a regeneration after a `FLOCI_HOSTNAME` change; `POST /_floci/state/reset` drops them.++Only a name under a local suffix is accepted: `localhost`, `localhost.floci.io`, `localhost.localstack.cloud`, `FLOCI_HOSTNAME`, the `FLOCI_BASE_URL` host, and every `FLOCI_DNS_EXTRA_SUFFIXES` entry. Any other name is refused with a warning, so a Floci certificate can never cover a public name. This only applies to the generated certificate; a user-provided one is never changed.++Names are added by the custom domain operations: API Gateway `CreateDomainName`, IoT Core `CreateDomainConfiguration` with a `domainName`, and Cognito `CreateUserPoolDomain` with a `CustomDomainConfig`. The AWS operation succeeds either way; a name outside the local suffixes, or a reissue that fails, is logged as a warning.+## User-Provided CertificatesTo use your own certificate (e.g., from a corporate CA or mkcert):diff --git a/docs/services/acm.md b/docs/services/acm.mdindex 64e0e9c063..0fdf36f7ab 100644--- a/docs/services/acm.md+++ b/docs/services/acm.md@@ -30,6 +30,8 @@- **Auto-Issuance:** All requested certificates are immediately issued with status `ISSUED` (no DNS/email validation required)- **Real Cryptography:** Certificates are generated with real RSA/EC keys and valid X.509 structure+- **One Local CA:** Every issued certificate (`AMAZON_ISSUED` and `PRIVATE`) is signed by Floci's local root CA, and `GetCertificate` returns that CA as `CertificateChain`. Trust it once (`GET /_floci/ca.pem`, see [TLS](../configuration/tls.md)) and both Floci's HTTPS endpoint and every ACM certificate validate. `DescribeCertificate` reports `Issuer` as the CA's name, `CN=Floci Local CA`, where AWS reports `Amazon`. `ImportCertificate` keeps the chain you upload.+- **CA on First Use:** The CA is created under `{persistent-path}/tls/` the first time a certificate is issued, also with TLS off and in `memory` storage mode, so that directory must be writable. A certificate keeps the chain it was issued with; after a CA regeneration, delete and re-request it.- **Key Algorithms:** Supports `RSA_2048`, `RSA_3072`, `RSA_4096`, `EC_prime256v1`, `EC_secp384r1`, `EC_secp521r1`- **Certificate Types:** `AMAZON_ISSUED` (default) and `PRIVATE` (when `CertificateAuthorityArn` is provided)- **Export:** Only `PRIVATE` type certificates can be exported with their private keydiff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.mdindex c69a5a97ff..153c97ed4b 100644--- a/docs/services/api-gateway.md+++ b/docs/services/api-gateway.md@@ -120,6 +120,10 @@ already has one is a `ConflictException`. A `PRIVATE` endpoint type is refused:domains are not emulated. Mutual TLS, ownership verification certificates, routing modes andendpoint access modes are accepted and ignored.+With TLS enabled, `CreateDomainName` also adds the domain to Floci's server certificate, so+`https://<domain>` verifies against the ACM chain without a restart. The name must sit under a+local suffix such as `localhost.floci.io`; see [TLS](../configuration/tls.md).+Templates can create domains and mappings with `AWS::ApiGateway::DomainName` and`AWS::ApiGateway::BasePathMapping`; see [CloudFormation](cloudformation.md).diff --git a/docs/services/cognito.md b/docs/services/cognito.mdindex e421f13968..780ae329f0 100644--- a/docs/services/cognito.md+++ b/docs/services/cognito.md@@ -119,6 +119,11 @@ URLs when one exists. Prefix domains (`<prefix>.auth.<region>.amazoncognito.com`routed, since that hostname never reaches Floci. `/oauth2/authorize`, `/login` and `/logout` are notserved on any host.+With TLS enabled, a custom domain (`CustomDomainConfig` set) is added to Floci's server+certificate as soon as it is created, so `https://<domain>` verifies without a restart; see+[TLS](../configuration/tls.md) for the accepted suffixes. A prefix domain is served under+`amazoncognito.com` on AWS, not by Floci, and is left alone.+### Log Delivery| Action | Description |diff --git a/docs/services/iot.md b/docs/services/iot.mdindex ec0da4f584..11a4b6ff56 100644--- a/docs/services/iot.md+++ b/docs/services/iot.md@@ -60,6 +60,7 @@ Status: control plane only.- `ListDomainConfigurations` filters by `serviceType` and pages with `marker` and `pageSize`.- Tags work through `TagResource`, `UntagResource` and `ListTagsForResource` on the configuration ARN.- CloudFormation provisions `AWS::IoT::DomainConfiguration` through the same operations; see the CloudFormation service page for the attribute list.+- With TLS enabled, a customer-managed configuration (`domainName` set) adds its domain to Floci's server certificate as soon as it is created, so `https://<domain>` verifies without a restart; see [TLS](../configuration/tls.md) for the accepted suffixes. A configuration without a domain name registers nothing.- The four AWS-managed configurations every account has (`iot:Data-ATS`, `iot:Data`, `iot:CredentialProvider`, `iot:Jobs`) exist in every region without being created: `AWS_MANAGED`, `ENABLED`, no server certificate, and the address `DescribeEndpoint` returns as their domain name. They can be updated and tagged but not deleted, as on AWS.Current limitations:diff --git a/src/main/java/io/github/hectorvent/floci/config/CertificateMetadata.java b/src/main/java/io/github/hectorvent/floci/config/CertificateMetadata.javaindex 770ea16747..2add8484c9 100644--- a/src/main/java/io/github/hectorvent/floci/config/CertificateMetadata.java+++ b/src/main/java/io/github/hectorvent/floci/config/CertificateMetadata.java@@ -17,7 +17,7 @@ import java.util.Objects;* changes.** <p>- * The metadata file is stored as JSON at {@code {persistent-path}/tls/floci-selfsigned.metadata.json}.+ * The metadata file is stored as JSON at {@code {persistent-path}/tls/floci-server.metadata.json}.*/@JsonIgnoreProperties(ignoreUnknown = true)@RegisterForReflection@@ -30,6 +30,13 @@ public class CertificateMetadata {*/private List<String> hostnames;+ /**+ * Hostnames added at runtime by {@link TlsCertificateManager#ensureHost(String)} (API Gateway,+ * IoT and Cognito custom domains). Kept apart from {@link #hostnames} so a change in the+ * configured list is detected without losing what was learned.+ */+ private List<String> learnedHostnames = List.of();+/*** ISO-8601 timestamp when the certificate was generated.* Used for debugging and auditing purposes.@@ -80,6 +87,14 @@ public class CertificateMetadata {this.hostnames = hostnames;}+ public List<String> getLearnedHostnames() {+ return learnedHostnames == null ? List.of() : learnedHostnames;+ }++ public void setLearnedHostnames(List<String> learnedHostnames) {+ this.learnedHostnames = learnedHostnames == null ? List.of() : List.copyOf(learnedHostnames);+ }+public String getGeneratedAt() {return generatedAt;}@@ -102,19 +117,21 @@ public class CertificateMetadata {if (o == null || getClass() != o.getClass()) return false;CertificateMetadata that = (CertificateMetadata) o;return Objects.equals(hostnames, that.hostnames) &&+ Objects.equals(getLearnedHostnames(), that.getLearnedHostnames()) &&Objects.equals(generatedAt, that.generatedAt) &&Objects.equals(flociVersion, that.flociVersion);}@Overridepublic int hashCode() {- return Objects.hash(hostnames, generatedAt, flociVersion);+ return Objects.hash(hostnames, getLearnedHostnames(), generatedAt, flociVersion);}@Overridepublic String toString() {return "CertificateMetadata{" +"hostnames=" + hostnames ++ ", learnedHostnames=" + learnedHostnames +", generatedAt='" + generatedAt + '\'' +", flociVersion='" + flociVersion + '\'' +'}';diff --git a/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.javaindex dccedc25f6..e2269ac9ea 100644--- a/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java+++ b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java@@ -19,7 +19,7 @@ import java.util.List;/*** Floci's one local root CA. Every certificate the emulator hands out that a client is expected- * to validate (the HTTPS server leaf, and later ACM and IoT device certificates) chains to it, so+ * to validate (the HTTPS server leaf, ACM certificates and, later, IoT device certificates) chains to it, so* a developer trusts one file once: {@code {persistent-path}/tls/floci-root-ca.crt}, also served* at {@code GET /_floci/ca.pem}.*diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsCertificateManager.java b/src/main/java/io/github/hectorvent/floci/config/TlsCertificateManager.javanew file mode 100644index 0000000000..fb1e813e2c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/config/TlsCertificateManager.java@@ -0,0 +1,308 @@+package io.github.hectorvent.floci.config;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.Resettable;+import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.quarkus.tls.CertificateUpdatedEvent;+import io.quarkus.tls.TlsConfiguration;+import io.quarkus.tls.TlsConfigurationRegistry;+import io.quarkus.tls.runtime.config.TlsConfig;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.enterprise.event.Event;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.io.IOException;+import java.net.URI;+import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.StandardCopyOption;+import java.security.KeyPair;+import java.security.cert.CertificateParsingException;+import java.security.cert.X509Certificate;+import java.util.ArrayList;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Locale;+import java.util.Set;+import java.util.regex.Pattern;++/**+ * Grows the HTTPS server certificate's SAN list at runtime so a custom domain created through+ * API Gateway, IoT or Cognito is served under its exact name in the same call.+ *+ * <p>A reissue keeps the key pair: only the SAN extension and the serial change, and the same+ * local CA signs it, so anyone who trusts {@code floci-root-ca.crt} keeps validating. The key+ * file is never rewritten. Certificate and metadata are replaced by atomic renames, then the+ * default entry of the Quarkus TLS registry is reloaded and {@link CertificateUpdatedEvent} is+ * fired, which is what {@code HttpCertificateUpdateEventListener} waits for before calling+ * {@code HttpServer.updateSSLOptions}: the next handshake sees the new certificate.+ *+ * <p>Only names under a local suffix are accepted. Floci verifies no request signature, so a+ * certificate covering an arbitrary public name would let any local process impersonate that+ * name to every client trusting the Floci CA.+ */+@ApplicationScoped+public class TlsCertificateManager implements Resettable {++ private static final Logger LOG = Logger.getLogger(TlsCertificateManager.class);+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();+ private static final List<String> BUILTIN_SUFFIXES = List.of("localhost", "localhost.floci.io", "localhost.localstack.cloud");+ private static final String LABEL = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";+ /** RFC 1123 labels, optionally one leading wildcard label (RFC 6125 section 6.4.3). */+ private static final Pattern HOSTNAME = Pattern.compile("(?:\\*\\.)?" + LABEL + "(?:\\." + LABEL + ")*");+ private static final int MAX_HOSTNAME_LENGTH = 253;++ static final String CERT_NAME = "floci-server.crt";+ static final String KEY_NAME = "floci-server.key";+ static final String METADATA_NAME = "floci-server.metadata.json";++ private final EmulatorConfig config;+ private final FlociCertificateAuthority ca;+ private final TlsConfigurationRegistry registry;+ private final Event<CertificateUpdatedEvent> certificateUpdated;+ private final CertificateGenerator generator = new CertificateGenerator();+ private final Object lock = new Object();++ private Set<String> knownHostnames = Set.of();+ private List<String> configuredHostnames = List.of();+ private Set<String> learnedHostnames = new LinkedHashSet<>();+ private KeyPair keyPair;+ private KeyAlgorithm keyAlgorithm;+ private boolean loaded;+ /** True between a successful file write and a successful listener swap. */+ private boolean listenerBehindFiles;++ @Inject+ public TlsCertificateManager(EmulatorConfig config, FlociCertificateAuthority ca,+ TlsConfigurationRegistry registry, Event<CertificateUpdatedEvent> certificateUpdated) {+ this.config = config;+ this.ca = ca;+ this.registry = registry;+ this.certificateUpdated = certificateUpdated;+ }++ /**+ * Makes sure {@code host} is covered by the server certificate. Idempotent, wildcard-aware,+ * and never throws: a failure is logged and the caller's AWS operation still succeeds.+ *+ * <p>Blocking: the Quarkus listener waits for every HTTP server to swap its SSL options, so+ * call this from a worker thread (a JAX-RS handler), never from a Vert.x event loop.+ */+ public void ensureHost(String host) {+ String name = normalize(host);+ if (name == null || !managesServerCertificate()) {+ return;+ }+ synchronized (lock) {+ if (!loadOnce() || covers(name)) {+ return;+ }+ if (!isAllowed(name)) {+ LOG.warnv("TLS: refusing to add {0} to the server certificate: not under a local suffix "+ + "(localhost, localhost.floci.io, localhost.localstack.cloud, floci.hostname, "+ + "the floci.base-url host, floci.dns.extra-suffixes)", name);+ return;+ }+ Set<String> learned = new LinkedHashSet<>(learnedHostnames);+ learned.add(name);+ try {+ reissue(learned);+ LOG.infov("TLS: server certificate now covers {0}", name);+ } catch (Exception e) {+ LOG.warnv(e, "TLS: could not extend the server certificate with {0}: {1}", name, e.getMessage());+ }+ }+ }++ /** Every SAN on the served leaf, configured and learned, lower-cased. Empty when not managed. */+ public Set<String> knownHostnames() {+ if (!managesServerCertificate()) {+ return Set.of();+ }+ synchronized (lock) {+ loadOnce();+ return knownHostnames;+ }+ }++ /** Reset: forget the learned names, keep the configured ones. */+ @Override+ public void clear() {+ if (!managesServerCertificate()) {+ return;+ }+ synchronized (lock) {+ if (!loadOnce() || (learnedHostnames.isEmpty() && !listenerBehindFiles)) {+ return;+ }+ try {+ reissue(new LinkedHashSet<>());+ LOG.info("TLS: server certificate reset to the configured hostnames");+ } catch (Exception e) {+ LOG.warnv(e, "TLS: could not reset the server certificate: {0}", e.getMessage());+ }+ }+ }++ /** False with TLS off or a user-provided certificate, whose SAN list is not ours to change. */+ private boolean managesServerCertificate() {+ return config.tls().enabled() && config.tls().certPath().filter(p -> !p.isBlank()).isEmpty();+ }++ private boolean loadOnce() {+ if (loaded) {+ return true;+ }+ Path dir = tlsDir();+ Path certFile = dir.resolve(CERT_NAME);+ Path keyFile = dir.resolve(KEY_NAME);+ if (!Files.exists(certFile) || !Files.exists(keyFile)) {+ LOG.debugv("TLS: no server certificate under {0}; nothing to extend", dir);+ return false;+ }+ try {+ X509Certificate cert = generator.parseCertificate(Files.readString(certFile));+ keyPair = new KeyPair(cert.getPublicKey(), generator.parsePrivateKey(Files.readString(keyFile)));+ keyAlgorithm = generator.detectKeyAlgorithm(cert.getPublicKey());+ Set<String> sans = sansOf(cert);++ Path metadataFile = dir.resolve(METADATA_NAME);+ CertificateMetadata metadata = Files.exists(metadataFile)+ ? OBJECT_MAPPER.readValue(Files.readString(metadataFile), CertificateMetadata.class)+ : null;+ configuredHostnames = metadata == null || metadata.getHostnames() == null+ ? List.copyOf(sans)+ : List.copyOf(metadata.getHostnames());+ learnedHostnames = new LinkedHashSet<>();+ if (metadata != null) {+ metadata.getLearnedHostnames().forEach(n -> learnedHostnames.add(n.toLowerCase(Locale.ROOT)));+ }+ // A SAN the metadata does not list was learned by a reissue whose metadata write did+ // not complete; keep serving it rather than dropping it on the next reissue.+ Set<String> configuredLower = new LinkedHashSet<>();+ configuredHostnames.forEach(n -> configuredLower.add(n.toLowerCase(Locale.ROOT)));+ sans.stream().filter(n -> !configuredLower.contains(n)).forEach(learnedHostnames::add);++ knownHostnames = Set.copyOf(sans);+ loaded = true;+ return true;+ } catch (Exception e) {+ LOG.warnv(e, "TLS: could not read the server certificate under {0}: {1}", dir, e.getMessage());+ return false;+ }+ }++ private void reissue(Set<String> learned) throws Exception {+ List<String> sans = new ArrayList<>(new LinkedHashSet<>(configuredHostnames));+ for (String name : learned) {+ if (!sans.contains(name)) {+ sans.add(name);+ }+ }+ CertificateGenerator.GeneratedCertificate issued = ca.issueServerCertificate("localhost", sans, keyAlgorithm, keyPair);++ Path dir = tlsDir();+ CertificateMetadata metadata = CertificateMetadata.create(configuredHostnames, resolveFlociVersion());+ metadata.setLearnedHostnames(new ArrayList<>(learned));+ writeAtomically(dir.resolve(CERT_NAME), issued.certificatePem());+ writeAtomically(dir.resolve(METADATA_NAME), OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(metadata));+ // The learned list follows the files, so a name whose reload fails below is still carried+ // by every later reissue; the known set follows the listener, so that name is retried by+ // its next ensureHost call instead of being reported as served.+ learnedHostnames = new LinkedHashSet<>(learned);+ listenerBehindFiles = true;+ reloadServer();+ listenerBehindFiles = false;+ knownHostnames = sansOf(generator.parseCertificate(issued.certificatePem()));+ }++ /** Re-reads the files into the registry and swaps the listener; throws when either did not happen. */+ private void reloadServer() {+ TlsConfiguration cfg = registry.getDefault().orElseThrow(() -> new IllegalStateException(+ "no default TLS configuration is registered; the new server certificate applies on the next restart"));+ if (!cfg.reload()) {+ throw new IllegalStateException(+ "the TLS registry could not reload the server certificate; the next call retries");+ }+ certificateUpdated.fire(new CertificateUpdatedEvent(TlsConfig.DEFAULT_NAME, cfg));+ }++ private boolean covers(String name) {+ if (knownHostnames.contains(name)) {+ return true;+ }+ int dot = name.indexOf('.');+ return dot > 0 && knownHostnames.contains("*" + name.substring(dot));+ }++ private boolean isAllowed(String name) {+ List<String> suffixes = new ArrayList<>(BUILTIN_SUFFIXES);+ config.hostname().filter(h -> !h.isBlank()).ifPresent(h -> suffixes.add(h.toLowerCase(Locale.ROOT)));+ try {+ String baseHost = URI.create(config.baseUrl()).getHost();+ if (baseHost != null) {+ suffixes.add(baseHost.toLowerCase(Locale.ROOT));+ }+ } catch (RuntimeException e) {+ LOG.debugv("TLS: floci.base-url {0} has no usable host: {1}", config.baseUrl(), e.getMessage());+ }+ config.dns().extraSuffixes().ifPresent(list -> list.forEach(s -> suffixes.add(s.toLowerCase(Locale.ROOT))));+ String bare = name.startsWith("*.") ? name.substring(2) : name;+ for (String suffix : suffixes) {+ if (bare.equals(suffix) || bare.endsWith("." + suffix)) {+ return true;+ }+ }+ return false;+ }++ /**+ * Lower-cased, trailing dot dropped, and checked to be a host name: RFC 1123 labels and at+ * most one leading wildcard label, which is how API Gateway spells a wildcard custom domain+ * and the only wildcard form X.509 name matching honours. Anything else yields null.+ */+ private static String normalize(String host) {+ if (host == null) {+ return null;+ }+ String name = host.strip().toLowerCase(Locale.ROOT);+ if (name.endsWith(".")) {+ name = name.substring(0, name.length() - 1);+ }+ if (name.length() > MAX_HOSTNAME_LENGTH || !HOSTNAME.matcher(name).matches()) {+ return null;+ }+ return name;+ }++ private static Set<String> sansOf(X509Certificate cert) throws CertificateParsingException {+ Set<String> sans = new LinkedHashSet<>();+ if (cert.getSubjectAlternativeNames() != null) {+ for (List<?> entry : cert.getSubjectAlternativeNames()) {+ sans.add(String.valueOf(entry.get(1)).toLowerCase(Locale.ROOT));+ }+ }+ return Set.copyOf(sans);+ }++ private Path tlsDir() {+ return FlociCertificateAuthorityProducer.tlsDir(config);+ }++ private static void writeAtomically(Path target, String content) throws IOException {+ Path tmp = target.resolveSibling(target.getFileName() + ".tmp");+ try {+ Files.writeString(tmp, content);+ Files.move(tmp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);+ } finally {+ Files.deleteIfExists(tmp);+ }+ }++ private static String resolveFlociVersion() {+ String env = System.getenv("FLOCI_VERSION");+ return env == null || env.isBlank() ? "dev" : env;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.javaindex c4ad2cc968..17dd82782d 100644--- a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java+++ b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java@@ -71,7 +71,7 @@ public class TlsConfigSource implements ConfigSource {resolvedTlsDir = null;String enabled = resolveProperty("floci.tls.enabled", "false");if (!"true".equalsIgnoreCase(enabled)) {- LOG.debug("TLS disabled — TlsConfigSource inactive");+ LOG.debug("TLS disabled, TlsConfigSource inactive");return;}@@ -128,7 +128,7 @@ public class TlsConfigSource implements ConfigSource {properties.put("quarkus.http.port", "4510");properties.put("quarkus.http.ssl-port", "4511");- LOG.infov("TLS: HTTPS enabled — proxy will listen on port {0} (HTTP+HTTPS), cert={1}",+ LOG.infov("TLS: HTTPS enabled, proxy will listen on port {0} (HTTP+HTTPS), cert={1}",resolveProperty("floci.port", "4566"), certPath);}@@ -176,8 +176,15 @@ public class TlsConfigSource implements ConfigSource {private void generateServerCert(Path tlsDir, Path certFile, Path keyFile, FlociCertificateAuthority ca) {try {Files.createDirectories(tlsDir);- List<String> allSans = new ArrayList<>(DEFAULT_SAN_HOSTNAMES);- allSans.addAll(extractCustomHostnames());+ List<String> configured = new ArrayList<>(DEFAULT_SAN_HOSTNAMES);+ configured.addAll(extractCustomHostnames());+ List<String> learned = readLearnedHostnames(tlsDir, certFile);+ List<String> allSans = new ArrayList<>(configured);+ for (String name : learned) {+ if (!allSans.contains(name)) {+ allSans.add(name);+ }+ }CertificateGenerator.GeneratedCertificate generated = ca.issueServerCertificate("localhost", allSans,KeyAlgorithm.RSA_2048, null);@@ -187,12 +194,58 @@ public class TlsConfigSource implements ConfigSource {LOG.infov("TLS: generated server certificate {0} issued by {1}", certFile,ca.certificate().getSubjectX500Principal().getName());- persistMetadata(tlsDir, allSans);+ persistMetadata(tlsDir, configured, learned);} catch (IOException e) {throw new IllegalStateException("Failed to write TLS server certificate", e);}}+ /**+ * Hostnames {@link TlsCertificateManager} added at runtime. A boot that regenerates the+ * certificate (changed configuration, expired or foreign leaf) must keep serving them. The+ * served certificate is the source of truth: a SAN it carries beyond the metadata's configured+ * list was learned by a reissue whose metadata write did not complete, and is kept too.+ */+ private List<String> readLearnedHostnames(Path tlsDir, Path certFile) {+ Path metadataFile = tlsDir.resolve(SERVER_METADATA_NAME);+ if (!Files.exists(metadataFile)) {+ return List.of();+ }+ try {+ CertificateMetadata metadata = OBJECT_MAPPER.readValue(Files.readString(metadataFile), CertificateMetadata.class);+ Set<String> learned = new LinkedHashSet<>(metadata.getLearnedHostnames());+ if (metadata.getHostnames() != null && Files.exists(certFile)) {+ Set<String> configured = new LinkedHashSet<>(metadata.getHostnames());+ for (String san : servedSans(certFile)) {+ if (!configured.contains(san)) {+ learned.add(san);+ }+ }+ }+ return new ArrayList<>(learned);+ } catch (IOException e) {+ LOG.warnv("TLS: could not read learned hostnames from {0} ({1}); the new certificate starts without them",+ metadataFile, e.getMessage());+ return List.of();+ }+ }++ private static List<String> servedSans(Path certFile) {+ List<String> sans = new ArrayList<>();+ try {+ X509Certificate cert = new CertificateGenerator().parseCertificate(Files.readString(certFile));+ if (cert.getSubjectAlternativeNames() != null) {+ for (List<?> entry : cert.getSubjectAlternativeNames()) {+ sans.add(String.valueOf(entry.get(1)));+ }+ }+ } catch (Exception e) {+ LOG.debugv("TLS: could not read the SAN list of {0} ({1}); learned names come from the metadata only",+ certFile, e.getMessage());+ }+ return sans;+ }+private static void validateFileExists(String path, String description) {if (!Files.isReadable(Path.of(path))) {throw new IllegalStateException(@@ -274,14 +327,17 @@ public class TlsConfigSource implements ConfigSource {* Writes metadata to {tls-dir}/floci-server.metadata.json.** @param tlsDir The TLS directory where metadata should be written- * @param hostnames List of hostnames included in the certificate SANs+ * @param hostnames List of configured hostnames included in the certificate SANs+ * @param learnedHostnames Hostnames added at runtime, also in the SANs but kept apart so a+ * configuration change is still detected by comparing {@code hostnames}*/- private void persistMetadata(Path tlsDir, List<String> hostnames) {+ private void persistMetadata(Path tlsDir, List<String> hostnames, List<String> learnedHostnames) {Path metadataFile = tlsDir.resolve(SERVER_METADATA_NAME);try {String version = resolveFlociVersion();CertificateMetadata metadata = CertificateMetadata.create(hostnames, version);-+ metadata.setLearnedHostnames(learnedHostnames);+String json = OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(metadata);Files.writeString(metadataFile, json);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 cbd055b5fb..418adbc97c 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,6 +1,7 @@package io.github.hectorvent.floci.services.acm;import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.config.FlociCertificateAuthority;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;@@ -15,8 +16,6 @@ import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import org.jboss.logging.Logger;-import java.io.IOException;-import java.io.InputStream;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;@@ -49,6 +48,7 @@ public class AcmService implements ResourceProvider {private static final int MAX_DOMAIN_LENGTH = 253;private final StorageBackend<String, Certificate> store;private final CertificateGenerator certificateGenerator;+ private final FlociCertificateAuthority certificateAuthority;private final RegionResolver regionResolver;private final int validationWaitSeconds;private final AtomicInteger accountDaysBeforeExpiry = new AtomicInteger(45);@@ -68,23 +68,24 @@ public class AcmService implements ResourceProvider {@Injectpublic AcmService(StorageFactory factory, CertificateGenerator certificateGenerator,- EmulatorConfig config, RegionResolver regionResolver) {+ FlociCertificateAuthority certificateAuthority, EmulatorConfig config,+ RegionResolver regionResolver) {this(factory.create("acm", "acm-certificates.json",new TypeReference<Map<String, Certificate>>() {}),certificateGenerator,+ certificateAuthority,regionResolver,config.services().acm().validationWaitSeconds());}AcmService(StorageBackend<String, Certificate> store, CertificateGenerator certificateGenerator,- RegionResolver regionResolver, int validationWaitSeconds) {+ FlociCertificateAuthority certificateAuthority, RegionResolver regionResolver,+ int validationWaitSeconds) {this.store = store;this.certificateGenerator = certificateGenerator;+ this.certificateAuthority = certificateAuthority;this.regionResolver = regionResolver;this.validationWaitSeconds = validationWaitSeconds;-- // Validate Root CA resource availability- validateRootCaResource();}/**@@ -98,19 +99,6 @@ public class AcmService implements ResourceProvider {}}- private void validateRootCaResource() {- try (InputStream is = getClass().getResourceAsStream("/certs/amazon-root-ca.pem")) {- if (is == null) {- LOG.warn("Amazon Root CA certificate not found at /certs/amazon-root-ca.pem - " +- "certificate chains will be empty");- } else {- LOG.info("Amazon Root CA certificate loaded successfully");- }- } catch (IOException e) {- LOG.warnv("Failed to validate Root CA resource: {0}", e.getMessage());- }- }-// ============ RequestCertificate ============public Certificate requestCertificate(String domainName, List<String> sans, ValidationMethod validationMethod,@@ -149,10 +137,10 @@ public class AcmService implements ResourceProvider {status = validationWaitSeconds > 0 ? CertificateStatus.PENDING_VALIDATION : CertificateStatus.ISSUED;}- // Generate real X.509 certificate- CertificateGenerator.GeneratedCertificate generated = certificateGenerator.generateCertificate(- domainName, sans, alg- );+ // A server leaf signed by the local CA, so Certificate plus CertificateChain from+ // GetCertificate validate the way an ACM certificate and its chain do on AWS.+ CertificateGenerator.GeneratedCertificate generated = certificateAuthority.issueServerCertificate(+ domainName, sans, alg, null);Instant now = Instant.now();@@ -182,7 +170,7 @@ public class AcmService implements ResourceProvider {cert.setSignatureAlgorithm(generated.signatureAlgorithm());cert.setCertificateBody(generated.certificatePem());cert.setPrivateKey(generated.privateKeyPem());- cert.setCertificateChain(getAwsRootCa());+ cert.setCertificateChain(certificateAuthority.caPem());cert.setCertOptions(options != null ? options : CertificateOptions.defaultOptions());cert.setCertAuthorityArn(certAuthorityArn);cert.setIdempotencyToken(idempotencyToken);@@ -750,17 +738,4 @@ public class AcmService implements ResourceProvider {.map(s -> s.substring(3)).orElse(dn);}-- private String getAwsRootCa() {- try (InputStream is = getClass().getResourceAsStream("/certs/amazon-root-ca.pem")) {- if (is == null) {- LOG.warn("Could not load Amazon Root CA from resources, using empty chain");- return "";- }- return new String(is.readAllBytes(), StandardCharsets.UTF_8);- } catch (IOException e) {- LOG.warn("Failed to load Amazon Root CA: " + e.getMessage());- return "";- }- }}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.javaindex f43f1fbc38..c66b6b945c 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@@ -28,6 +28,7 @@ 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;@@ -47,6 +48,7 @@ import java.security.SecureRandom;import java.security.Security;import java.security.Signature;import java.security.cert.X509Certificate;+import java.security.interfaces.ECKey;import java.security.spec.ECGenParameterSpec;import java.time.Instant;import java.time.temporal.ChronoUnit;@@ -61,7 +63,6 @@ import java.util.regex.Pattern;public class CertificateGenerator {private static final Logger LOG = Logger.getLogger(CertificateGenerator.class);- private static final String ISSUER_DN = "CN=Amazon,OU=Server CA 1B,O=Amazon,C=US";private static final SecureRandom SECURE_RANDOM = new SecureRandom();private static final String PBE_ALGORITHM = "PBEWithHmacSHA256AndAES_256";private static final int PBE_SALT_BYTES = 16;@@ -96,21 +97,6 @@ public class CertificateGenerator {/** A signer: the issuer's certificate (for its DN) and its private key. */public record Issuer(X509Certificate certificate, PrivateKey key) {}- /**- * Generates a certificate for local emulation that mimics an ACM-issued certificate:- * the subject is {@code CN=<domainName>} but the issuer is a cosmetic Amazon CA DN, matching- * what real ACM returns. It is signed by its own key, so it is <em>not</em> verifiable as a- * trust anchor (the issuer DN does not match any certificate a client could hold). Use this- * for ACM responses; use {@link #generateSelfSignedCertificate} for a cert clients must trust.- *- * <p>Note: RSA key generation (especially 4096-bit) can take 100-500ms.- * In production emulator usage, consider moving this to a worker thread- * or using virtual threads for concurrent certificate generation.</p>- */- public GeneratedCertificate generateCertificate(String domainName, List<String> sans, KeyAlgorithm keyAlgorithm) {- return buildCertificate(domainName, sans, keyAlgorithm, ISSUER_DN, false, null);- }-/*** Generates a genuinely self-signed certificate (issuer == subject, marked as a CA) suitable* for use as a <em>trust anchor</em>: a client that adds this certificate to its CA store can@@ -119,7 +105,7 @@ public class CertificateGenerator {* Floci once the certificate is installed in their CA bundle.*/public GeneratedCertificate generateSelfSignedCertificate(String domainName, List<String> sans, KeyAlgorithm keyAlgorithm) {- return buildCertificate(domainName, sans, keyAlgorithm, "CN=" + domainName, true, null);+ return buildSelfSignedCertificate(domainName, sans, keyAlgorithm, null);}/**@@ -131,7 +117,7 @@ public class CertificateGenerator {*/public GeneratedCertificate generateSelfSignedCertificate(String domainName, List<String> sans,KeyAlgorithm keyAlgorithm, KeyPair keyPair) {- return buildCertificate(domainName, sans, keyAlgorithm, "CN=" + domainName, true, keyPair);+ return buildSelfSignedCertificate(domainName, sans, keyAlgorithm, keyPair);}/**@@ -191,7 +177,7 @@ public class CertificateGenerator {*/boolean isOfAlgorithm(PublicKey key, KeyAlgorithm keyAlgorithm) {if ("EC".equals(keyAlgorithm.getAlgorithm())) {- if (!"EC".equals(key.getAlgorithm())) {+ if (!(key instanceof ECKey)) {return false;}X962Parameters parameters = X962Parameters.getInstance(@@ -199,12 +185,12 @@ public class CertificateGenerator {return parameters.isNamedCurve()&& ECNamedCurveTable.getOID(keyAlgorithm.getCurveName()).equals(parameters.getParameters());}- return "RSA".equals(key.getAlgorithm()) && detectKeyAlgorithm(key) == keyAlgorithm;+ return !(key instanceof ECKey) && detectKeyAlgorithm(key) == keyAlgorithm;}/** True when {@code privateKey} signs what {@code publicKey} verifies. */public static boolean isPair(PrivateKey privateKey, PublicKey publicKey) throws Exception {- String algorithm = "EC".equals(privateKey.getAlgorithm()) ? "SHA256withECDSA" : "SHA256withRSA";+ String algorithm = privateKey instanceof ECKey ? "SHA256withECDSA" : "SHA256withRSA";byte[] probe = "floci".getBytes(StandardCharsets.US_ASCII);Signature signer = Signature.getInstance(algorithm);signer.initSign(privateKey);@@ -216,16 +202,15 @@ public class CertificateGenerator {return verifier.verify(signature);}- private GeneratedCertificate buildCertificate(String domainName, List<String> sans, KeyAlgorithm keyAlgorithm,- String issuerDn, boolean asCa, KeyPair suppliedKeyPair) {+ private GeneratedCertificate buildSelfSignedCertificate(String domainName, List<String> sans,+ KeyAlgorithm keyAlgorithm, KeyPair suppliedKeyPair) {try {KeyPair keyPair = suppliedKeyPair != null ? suppliedKeyPair : generateKeyPair(keyAlgorithm);- String subjectDn = "CN=" + domainName;- // Signed with the subject's own key, as before: generateCertificate keeps its cosmetic- // Amazon issuer DN, generateSelfSignedCertificate keeps issuer == subject.- X509Certificate cert = signCertificate(new X500Name(subjectDn), keyPair.getPublic(),- new X500Name(issuerDn), keyPair.getPrivate(), withDomainFirst(domainName, sans), asCa, null, 365);- return toGenerated(cert, keyPair.getPrivate(), subjectDn, issuerDn);+ String dn = "CN=" + domainName;+ // Signed with the subject's own key: issuer == subject, and a CA so it can be a trust anchor.+ X509Certificate cert = signCertificate(new X500Name(dn), keyPair.getPublic(),+ new X500Name(dn), keyPair.getPrivate(), withDomainFirst(domainName, sans), true, null, 365);+ return toGenerated(cert, keyPair.getPrivate(), dn, dn);} catch (Exception e) {LOG.error("Failed to generate certificate", e);throw new CertificateGenerationException("Certificate generation failed: " + e.getMessage(), e);@@ -276,7 +261,7 @@ public class CertificateGenerator {new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));}- String signatureAlgorithm = "EC".equals(issuerKey.getAlgorithm()) ? "SHA512withECDSA" : "SHA512WithRSA";+ String signatureAlgorithm = issuerKey instanceof ECKey ? "SHA512withECDSA" : "SHA512WithRSA";ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(issuerKey);X509CertificateHolder holder = certBuilder.build(signer);return new JcaX509CertificateConverter().getCertificate(holder);@@ -364,10 +349,20 @@ public class CertificateGenerator {return IP_ADDRESS_PATTERN.matcher(value).matches();}+ /**+ * PEM for a certificate or key. A JDK EC private key goes out as PKCS#8 ({@code PRIVATE KEY}):+ * {@link JcaPEMWriter} would write it as a bare SEC1 structure without the curve, which neither+ * OpenSSL nor {@link #parsePrivateKey} can read. RSA keys stay PKCS#1 ({@code RSA PRIVATE KEY}),+ * the form AWS IoT hands out.+ */public String toPem(Object obj) throws Exception {StringWriter sw = new StringWriter();try (JcaPEMWriter pemWriter = new JcaPEMWriter(sw)) {- pemWriter.writeObject(obj);+ if (obj instanceof PrivateKey key && key instanceof ECKey) {+ pemWriter.writeObject(new PemObject("PRIVATE KEY", key.getEncoded()));+ } else {+ pemWriter.writeObject(obj);+ }}return sw.toString();}@@ -434,7 +429,8 @@ public class CertificateGenerator {JcaPEMKeyConverter converter = new JcaPEMKeyConverter();if (obj instanceof org.bouncycastle.openssl.PEMKeyPair pemKeyPair) {- return converter.getKeyPair(pemKeyPair).getPrivate();+ // 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) {return converter.getPrivateKey(pkInfo);}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.javaindex e855539b33..14f19fba9b 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java@@ -17,6 +17,7 @@ import org.jboss.logging.Logger;import com.fasterxml.jackson.core.type.TypeReference;import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.config.TlsCertificateManager;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.ReservedTags;import io.github.hectorvent.floci.core.storage.StorageBackend;@@ -73,6 +74,7 @@ public class ApiGatewayService {* also keeps a mapping from being created under a domain that is being deleted at that moment.*/private final Object domainNameLock = new Object();+ private final TlsCertificateManager certificateManager;// Constantsprivate static final String EPC_KEY = "endpointConfiguration";@@ -80,7 +82,9 @@ public class ApiGatewayService {private static final String EPC_VPC_IDS_KEY = "vpcEndpointIds";@Inject- public ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config) {+ public ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config,+ TlsCertificateManager certificateManager) {+ this.certificateManager = certificateManager;this.apiStore = storageFactory.create("apigateway", "apigateway-apis.json",new TypeReference<>() {});@@ -1327,6 +1331,8 @@ public class ApiGatewayService {}domainStore.put(domainKey(region, domainName), domain);}+ // Outside the lock: the reissue blocks until the HTTPS listener has switched certificates.+ certificateManager.ensureHost(domainName);LOG.infov("Created custom domain {0} in {1}", domainName, region);return domain;}diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.javaindex 504ca1e8a9..8cea708a03 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.node.ArrayNode;import io.github.hectorvent.floci.services.cognito.model.EmailMfaSettings;import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.config.TlsCertificateManager;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;@@ -129,6 +130,7 @@ public class CognitoService implements ResourceProvider {private final AcmService acmService;private final VerificationCodeService verificationCodeService;private final CognitoMessageDispatcher messageDispatcher;+ private final TlsCertificateManager certificateManager;// Keyed by session token; contains SRP ephemeral state (bPrivate, B, A, secretBlock)private final CognitoAuthFlowHandler authFlowHandler;@@ -136,7 +138,8 @@ public class CognitoService implements ResourceProvider {@Injectpublic CognitoService(StorageFactory storageFactory, EmulatorConfig emulatorConfig,RegionResolver regionResolver, LambdaService lambdaService, AcmService acmService,- SesService sesService, SnsService snsService, Clock clock) {+ SesService sesService, SnsService snsService, Clock clock,+ TlsCertificateManager certificateManager) {this(storageFactory.create("cognito", "cognito-pools.json",new TypeReference<Map<String, UserPool>>() {}),@@ -159,7 +162,8 @@ public class CognitoService implements ResourceProvider {lambdaService,acmService,new VerificationCodeService(storageFactory, clock),- new CognitoMessageDispatcher(sesService, snsService)+ new CognitoMessageDispatcher(sesService, snsService),+ certificateManager);}@@ -175,7 +179,7 @@ public class CognitoService implements ResourceProvider {AcmService acmService) {this(poolStore, clientStore, resourceServerStore, new InMemoryStorage<>(),new InMemoryStorage<>(), userStore, groupStore, revokedTokenStore, baseUrl,- regionResolver, lambdaService, acmService, null, null);+ regionResolver, lambdaService, acmService, null, null, null);}CognitoService(StorageBackend<String, UserPool> poolStore,@@ -189,7 +193,8 @@ public class CognitoService implements ResourceProvider {String baseUrl,RegionResolver regionResolver, LambdaService lambdaService, AcmService acmService,VerificationCodeService verificationCodeService,- CognitoMessageDispatcher messageDispatcher) {+ CognitoMessageDispatcher messageDispatcher,+ TlsCertificateManager certificateManager) {this.poolStore = poolStore;this.clientStore = clientStore;this.resourceServerStore = resourceServerStore;@@ -204,6 +209,7 @@ public class CognitoService implements ResourceProvider {this.acmService = acmService;this.verificationCodeService = verificationCodeService;this.messageDispatcher = messageDispatcher;+ this.certificateManager = certificateManager;this.authFlowHandler = new CognitoAuthFlowHandler(this, lambdaService, regionResolver);}@@ -1137,6 +1143,11 @@ public class CognitoService implements ResourceProvider {}domainStore.put(domain, userPoolDomain);}+ // Outside the lock: the reissue blocks until the HTTPS listener has switched certificates.+ // A prefix domain is served under amazoncognito.com on AWS, not by Floci; a custom domain is.+ if (customDomainConfig != null && certificateManager != null) {+ certificateManager.ensureHost(domain);+ }LOG.infov("Created User Pool Domain: {0} for pool {1}", domain, userPoolId);return userPoolDomain;}diff --git a/src/main/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationService.java b/src/main/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationService.javaindex fe1bf82c26..2bfdc1c115 100644--- a/src/main/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationService.java+++ b/src/main/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationService.java@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.node.JsonNodeFactory;import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.config.TlsCertificateManager;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;@@ -56,6 +57,7 @@ public class IotDomainConfigurationService {private final StorageBackend<String, IotDomainConfiguration> store;private final RegionResolver regionResolver;private final EmulatorConfig config;+ private final TlsCertificateManager certificateManager;/*** Guards every read-modify-write on the store: the duplicate check and store of a create, the* seeding of the AWS-managed configurations, and the update, delete and tag paths, which all@@ -65,16 +67,17 @@ public class IotDomainConfigurationService {@Injectpublic IotDomainConfigurationService(StorageFactory storageFactory, RegionResolver regionResolver,- EmulatorConfig config) {+ EmulatorConfig config, TlsCertificateManager certificateManager) {this(storageFactory.create("iot", "iot-domain-configurations.json",- new TypeReference<Map<String, IotDomainConfiguration>>() {}), regionResolver, config);+ new TypeReference<Map<String, IotDomainConfiguration>>() {}), regionResolver, config, certificateManager);}IotDomainConfigurationService(StorageBackend<String, IotDomainConfiguration> store, RegionResolver regionResolver,- EmulatorConfig config) {+ EmulatorConfig config, TlsCertificateManager certificateManager) {this.store = store;this.regionResolver = regionResolver;this.config = config;+ this.certificateManager = certificateManager;}public IotDomainConfiguration createDomainConfiguration(String name, JsonNode request, String region) {@@ -119,6 +122,10 @@ public class IotDomainConfigurationService {}store.put(key, configuration);}+ // Outside the lock: the reissue blocks until the HTTPS listener has switched certificates.+ if (domainName != null) {+ certificateManager.ensureHost(domainName);+ }return configuration;}diff --git a/src/main/resources/certs/amazon-root-ca.pem b/src/main/resources/certs/amazon-root-ca.pemdeleted file mode 100644index 7e2f844d8f..0000000000--- a/src/main/resources/certs/amazon-root-ca.pem+++ /dev/null@@ -1,25 +0,0 @@------BEGIN CERTIFICATE------MIIESTCCAzGgAwIBAgITBntQXCplJ7wevi2i0ZmY7bibLDANBgkqhkiG9w0BAQsF-ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6-b24gUm9vdCBDQSAxMB4XDTE1MTAyMTIyMjQzNFoXDTQwMTAyMTIyMjQzNFowRjEL-MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEVMBMGA1UECxMMU2VydmVyIENB-IDFCMQ8wDQYDVQQDEwZBbWF6b24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK-AoIBAQDCThZn3c68asg3CZwaH2N2FfD7JfHr/RXfbLXEVhvwCMk9CeNAGKnX9EUH-2z9+RH3bQ7wBLM/FY/lBJH/O4Yl+XNM6sFPaLMJy9Ll4iqL7B/f6Mf5c5aFl3bG-m5z3bCMwdBZL2c5OJRFmVF9RhJh3lQbSs7nbVxN3bvVMVlNM5lXCBAB3FZPbEFYi-dB0wfPL9vY1dB7AJ5v4bMl9z5z9qWP2dW7m7v5vRVo+A9TFxn8B7EZVrTXFn3CyM-H9W8+K4iKbQ/7HZ7bVz3AYB5vOZjFU7Lz1h/0OG/m5v6cKGOiJAOmUjThVL3Cjb5-6nRIoTUdHHqP3L9rOi9a7VXnNdWRAgMBAAGjggE7MIIBNzASBgNVHRMBAf8ECDAG-AQH/AgEAMA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUWaRmBlKge5WSPKOUByeW-dFv5PdAwHwYDVR0jBBgwFoAUhBjMhTTsvAyUlC4IWZzHshBOCggwewYIKwYBBQUH-AQEEbzBtMC8GCCsGAQUFBzABhiNodHRwOi8vb2NzcC5yb290Y2ExLmFtYXpvbnRy-dXN0LmNvbTA6BggrBgEFBQcwAoYuaHR0cDovL2NydC5yb290Y2ExLmFtYXpvbnRy-dXN0LmNvbS9yb290Y2ExLmNlcjA/BgNVHR8EODA2MDSgMqAwhi5odHRwOi8vY3Js-LnJvb3RjYTEuYW1hem9udHJ1c3QuY29tL3Jvb3RjYTEuY3JsMBEGA1UdIAQKMAgw-BgYEVR0gADANBgkqhkiG9w0BAQsFAAOCAQEARP3m7HzM/VfnKaFC5rlI+TFkk5N4-rlCWElGh2v9s4k+1p5yTniV3n5/sR3DVHMa5TQ8m+4Z7PsKl/D8UFRl/5eEILxQ+-7e5RLk4kcPfbc3VYl/lYgIhEY9CWA2t/FSXJJJu5f0EH0wEcN1A3F8mFbNNgN2N9-RvPWmGd4TCNy58bGmVQYO8+xJJbgTXTJ1HkIw/7VOp6ePm4CIk9MK2K8j9j3fB7b-vRmA1VwLB0K3Vw8jLDl1oLcz/nXPdfXhzzzXJy/TKgIUYJb3SB/k2bECiyM2xyIb-tTmFPau9YqHPBPK8xSpWJ9JfD/2pK1gORqVmBT8R88zcbAj6Qwk/pfKurw==------END CERTIFICATE-----diff --git a/src/test/java/io/github/hectorvent/floci/config/CertificateMetadataTest.java b/src/test/java/io/github/hectorvent/floci/config/CertificateMetadataTest.javanew file mode 100644index 0000000000..f189d5e367--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/CertificateMetadataTest.java@@ -0,0 +1,55 @@+package io.github.hectorvent.floci.config;++import com.fasterxml.jackson.databind.ObjectMapper;+import org.junit.jupiter.api.Test;++import java.util.List;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;++class CertificateMetadataTest {++ private static final ObjectMapper MAPPER = new ObjectMapper();++ @Test+ void learnedHostnamesRoundTripThroughJson() throws Exception {+ CertificateMetadata metadata = CertificateMetadata.create(List.of("localhost"), "dev");+ metadata.setLearnedHostnames(List.of("api.example.localhost.floci.io"));++ CertificateMetadata read = MAPPER.readValue(MAPPER.writeValueAsString(metadata), CertificateMetadata.class);++ assertEquals(List.of("api.example.localhost.floci.io"), read.getLearnedHostnames());+ assertEquals(List.of("localhost"), read.getHostnames(), "configured names stay apart from learned ones");+ assertEquals(metadata, read);+ }++ @Test+ void metadataWrittenBeforeTheFieldExistedReadsAsNoLearnedHostnames() throws Exception {+ String legacyJson = "{\"hostnames\":[\"localhost\"],\"generatedAt\":\"2026-01-01T00:00:00Z\",\"flociVersion\":\"dev\"}";++ CertificateMetadata read = MAPPER.readValue(legacyJson, CertificateMetadata.class);++ assertEquals(List.of(), read.getLearnedHostnames());+ }++ @Test+ void nullLearnedHostnamesReadAsEmpty() {+ CertificateMetadata metadata = new CertificateMetadata();+ metadata.setLearnedHostnames(null);++ assertEquals(List.of(), metadata.getLearnedHostnames());+ }++ @Test+ void learnedHostnamesTakePartInEquality() {+ CertificateMetadata a = new CertificateMetadata(List.of("localhost"), "2026-01-01T00:00:00Z", "dev");+ CertificateMetadata b = new CertificateMetadata(List.of("localhost"), "2026-01-01T00:00:00Z", "dev");+ assertEquals(a, b);++ b.setLearnedHostnames(List.of("api.example.localhost.floci.io"));++ assertNotEquals(a, b);+ assertNotEquals(a.hashCode(), b.hashCode());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/CustomDomainTlsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/CustomDomainTlsIntegrationTest.javanew file mode 100644index 0000000000..56401c48af--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/CustomDomainTlsIntegrationTest.java@@ -0,0 +1,192 @@+package io.github.hectorvent.floci.config;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import io.restassured.http.ContentType;+import org.eclipse.microprofile.config.inject.ConfigProperty;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import javax.net.ssl.SNIHostName;+import javax.net.ssl.SSLContext;+import javax.net.ssl.SSLHandshakeException;+import javax.net.ssl.SSLParameters;+import javax.net.ssl.SSLSocket;+import javax.net.ssl.TrustManagerFactory;+import java.io.ByteArrayInputStream;+import java.io.IOException;+import java.net.InetAddress;+import java.net.InetSocketAddress;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;+import java.security.KeyStore;+import java.security.cert.CertificateFactory;+import java.security.cert.X509Certificate;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.TreeSet;++import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;+import static io.github.hectorvent.floci.testing.RestAssuredJsonUtils.awsActionJson;+import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * End to end, with TLS on and the real certificate manager: an ACM certificate is requested, the+ * three custom domain operations are called over the wire with their normal responses, and a+ * client that trusts only the chain ACM returned, sends each domain as SNI and verifies the+ * server's identity for it completes the handshake, where it failed before the domain existed.+ * A reset takes the names back. The fixture leaf carries no 127.0.0.1 SAN and the socket connects+ * by IP, so the SNI name is the only one the identity check can match.+ */+@QuarkusTest+@TestProfile(CustomDomainTlsIntegrationTest.Profile.class)+class CustomDomainTlsIntegrationTest {++ static final Path DATA_DIR = Path.of("target", "floci-custom-domain-tls-test").toAbsolutePath();+ static final Path TLS_DIR = DATA_DIR.resolve("tls");+ static final String API_DOMAIN = "api.custom-domain-it.localhost.floci.io";+ static final String IOT_DOMAIN = "iot.custom-domain-it.localhost.floci.io";+ static final String AUTH_DOMAIN = "auth.custom-domain-it.localhost.floci.io";++ @ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")+ int sslPort;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void customDomainsAreServedUnderTheAcmChainAsSoonAsTheyExist() throws Exception {+ JsonNode requested = awsActionJson("CertificateManager", "RequestCertificate",+ "{\"DomainName\": \"*.custom-domain-it.localhost.floci.io\", \"ValidationMethod\": \"DNS\"}");+ String certificateArn = requested.path("CertificateArn").asText();+ String chain = awsActionJson("CertificateManager", "GetCertificate",+ "{\"CertificateArn\": \"" + certificateArn + "\"}").path("CertificateChain").asText();+ assertTrue(chain.contains("BEGIN CERTIFICATE"), chain);++ for (String domain : List.of(API_DOMAIN, IOT_DOMAIN, AUTH_DOMAIN)) {+ assertThrows(SSLHandshakeException.class, () -> handshake(chain, domain, true),+ "precondition: " + domain + " is not served before it is created");+ }++ given().contentType(ContentType.JSON)+ .body("{\"domainName\":\"" + API_DOMAIN + "\",\"regionalCertificateArn\":\"" + certificateArn + "\","+ + "\"endpointConfiguration\":{\"types\":[\"REGIONAL\"]}}")+ .when().post("/domainnames").then().statusCode(201);+ given().contentType(ContentType.JSON)+ .body("{\"domainName\":\"" + IOT_DOMAIN + "\",\"serverCertificateArns\":[\"" + certificateArn + "\"]}")+ .when().post("/domainConfigurations/custom-domain-it").then().statusCode(200);+ String poolId = cognitoJson("CreateUserPool", "{\"PoolName\": \"custom-domain-it\"}")+ .path("UserPool").path("Id").asText();+ JsonNode created = cognitoJson("CreateUserPoolDomain", "{\"Domain\": \"" + AUTH_DOMAIN + "\", \"UserPoolId\": \""+ + poolId + "\", \"CustomDomainConfig\": {\"CertificateArn\": \"" + certificateArn + "\"}}");+ assertTrue(created.path("CloudFrontDomain").asText().endsWith(".cloudfront.net"), created.toString());++ for (String domain : List.of(API_DOMAIN, IOT_DOMAIN, AUTH_DOMAIN)) {+ X509Certificate served = handshake(chain, domain, true);+ assertTrue(sans(served).contains(domain), domain + " not in " + sans(served));+ assertEquals(parse(chain).get(0).getSubjectX500Principal(), served.getIssuerX500Principal(),+ "the served leaf is issued by the CA in the ACM chain");+ }++ given().when().post("/_floci/state/reset").then().statusCode(200);++ for (String domain : List.of(API_DOMAIN, IOT_DOMAIN, AUTH_DOMAIN)) {+ assertThrows(SSLHandshakeException.class, () -> handshake(chain, domain, true),+ "reset drops " + domain);+ }+ assertFalse(sans(handshake(chain, API_DOMAIN, false)).contains(API_DOMAIN));+ }++ /**+ * TLS by IP trusting only {@code chainPem}, sending {@code sniHost} as SNI and, when asked,+ * verifying the server's identity for that name the way an SDK does.+ */+ private X509Certificate handshake(String chainPem, String sniHost, boolean verifyIdentity) throws Exception {+ KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());+ trust.load(null, null);+ int i = 0;+ for (X509Certificate ca : parse(chainPem)) {+ trust.setCertificateEntry("chain-" + i++, ca);+ }+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());+ tmf.init(trust);+ SSLContext ctx = SSLContext.getInstance("TLS");+ ctx.init(null, tmf.getTrustManagers(), null);+ try (SSLSocket socket = (SSLSocket) ctx.getSocketFactory().createSocket()) {+ socket.connect(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), sslPort), 5000);+ SSLParameters params = socket.getSSLParameters();+ params.setServerNames(List.of(new SNIHostName(sniHost)));+ if (verifyIdentity) {+ params.setEndpointIdentificationAlgorithm("HTTPS");+ }+ socket.setSSLParameters(params);+ socket.startHandshake();+ return (X509Certificate) socket.getSession().getPeerCertificates()[0];+ }+ }++ private static List<X509Certificate> parse(String pem) throws Exception {+ return CertificateFactory.getInstance("X.509")+ .generateCertificates(new ByteArrayInputStream(pem.getBytes(StandardCharsets.UTF_8)))+ .stream().map(X509Certificate.class::cast).toList();+ }++ private static Set<String> sans(X509Certificate leaf) throws Exception {+ Set<String> sans = new TreeSet<>();+ for (List<?> entry : leaf.getSubjectAlternativeNames()) {+ sans.add(String.valueOf(entry.get(1)));+ }+ return sans;+ }++ /**+ * Boots with TLS on and a CA-issued leaf like the one TlsConfigSource writes, in a directory+ * of its own. The wildcard covers one label only, so the three-label names are uncovered+ * until the operations add them.+ */+ public static final class Profile implements QuarkusTestProfile {++ static {+ try {+ Files.createDirectories(TLS_DIR);+ for (String name : List.of("floci-server.crt", "floci-server.key", "floci-server.metadata.json")) {+ Files.deleteIfExists(TLS_DIR.resolve(name));+ }+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);+ List<String> sans = List.of("localhost", "*.localhost.floci.io");+ var leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);+ Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());+ Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());+ Files.writeString(TLS_DIR.resolve("floci-server.metadata.json"),+ new ObjectMapper().writeValueAsString(CertificateMetadata.create(sans, "dev")));+ } catch (IOException e) {+ throw new IllegalStateException("could not prepare the TLS fixtures", e);+ }+ }++ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of(+ "floci.tls.enabled", "true",+ "floci.tls.self-signed", "true",+ "floci.tls.aws-https-port", "0",+ "floci.storage.persistent-path", DATA_DIR.toString(),+ "quarkus.tls.key-store.pem.0.cert", TLS_DIR.resolve("floci-server.crt").toString(),+ "quarkus.tls.key-store.pem.0.key", TLS_DIR.resolve("floci-server.key").toString(),+ "quarkus.http.insecure-requests", "enabled");+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityTest.java b/src/test/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityTest.javaindex 65c0efd925..bda8eb5685 100644--- a/src/test/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityTest.java@@ -122,7 +122,8 @@ class FlociCertificateAuthorityTest {@Testvoid aLeafInPlaceOfTheCaIsRegenerated() throws Exception {- var leaf = new CertificateGenerator().generateCertificate("localhost", List.of(), KeyAlgorithm.RSA_2048);+ var leaf = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("another-ca"))+ .issueServerCertificate("localhost", List.of(), KeyAlgorithm.RSA_2048, null);Files.writeString(tempDir.resolve("floci-root-ca.crt"), leaf.certificatePem());Files.writeString(tempDir.resolve("floci-root-ca.key"), leaf.privateKeyPem());diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.javaindex f75ddba2ef..cdb6b4867d 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java@@ -190,7 +190,7 @@ class TlsCertificateHostnameTest {// Generate certificate without metadataCertificateGenerator gen = new CertificateGenerator();- CertificateGenerator.GeneratedCertificate generated = gen.generateCertificate(+ CertificateGenerator.GeneratedCertificate generated = gen.generateSelfSignedCertificate("localhost",List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost", "localhost.floci.io", "*.localhost.floci.io"),KeyAlgorithm.RSA_2048);@@ -276,7 +276,7 @@ class TlsCertificateHostnameTest {Path userKeyFile = tempDir.resolve("user-key.key");CertificateGenerator gen = new CertificateGenerator();- CertificateGenerator.GeneratedCertificate userCert = gen.generateCertificate(+ CertificateGenerator.GeneratedCertificate userCert = gen.generateSelfSignedCertificate("user-domain.com",List.of("user-domain.com", "*.user-domain.com"),KeyAlgorithm.RSA_2048);@@ -390,7 +390,7 @@ class TlsCertificateHostnameTest {Path userCert = tempDir.resolve("user.crt");Path userKey = tempDir.resolve("user.key");- var user = new CertificateGenerator().generateCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);+ var user = new CertificateGenerator().generateSelfSignedCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);Files.writeString(userCert, user.certificatePem());Files.writeString(userKey, user.privateKeyPem());System.setProperty("floci.tls.enabled", "true");diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateManagerFixture.java b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateManagerFixture.javanew file mode 100644index 0000000000..76dd13cd04--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateManagerFixture.java@@ -0,0 +1,119 @@+package io.github.hectorvent.floci.config;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.quarkus.tls.CertificateUpdatedEvent;+import io.quarkus.tls.TlsConfiguration;+import io.quarkus.tls.TlsConfigurationRegistry;+import jakarta.enterprise.event.Event;+import org.bouncycastle.jce.provider.BouncyCastleProvider;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.io.TempDir;++import java.nio.file.Files;+import java.nio.file.Path;+import java.security.Security;+import java.security.cert.X509Certificate;+import java.util.List;+import java.util.Optional;+import java.util.Set;+import java.util.TreeSet;++import static org.junit.jupiter.api.Assertions.assertNull;+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * A server leaf on disk as {@code TlsConfigSource} leaves it, a mocked configuration, TLS registry+ * and event, for the {@link TlsCertificateManager} unit tests.+ */+abstract class TlsCertificateManagerFixture {++ static final List<String> CONFIGURED = List.of("localhost", "127.0.0.1", "*.localhost.floci.io", "localhost.floci.io");+ static final String NEW_HOST = "api.example.localhost.floci.io";++ @TempDir+ Path tempDir;++ Path tlsDir;+ FlociCertificateAuthority ca;+ EmulatorConfig config;+ TlsConfigurationRegistry registry;+ TlsConfiguration defaultTls;+ @SuppressWarnings("unchecked")+ final Event<CertificateUpdatedEvent> events = mock(Event.class);++ @BeforeAll+ static void bouncyCastle() {+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {+ Security.addProvider(new BouncyCastleProvider());+ }+ }++ @BeforeEach+ void serverLeafOnDisk() throws Exception {+ forgetBootstrapTlsDir();+ tlsDir = Files.createDirectories(tempDir.resolve("tls"));+ ca = FlociCertificateAuthority.loadOrCreate(tlsDir);+ var leaf = ca.issueServerCertificate("localhost", CONFIGURED, KeyAlgorithm.RSA_2048, null);+ Files.writeString(tlsDir.resolve("floci-server.crt"), leaf.certificatePem());+ Files.writeString(tlsDir.resolve("floci-server.key"), leaf.privateKeyPem());+ Files.writeString(tlsDir.resolve("floci-server.metadata.json"),+ new ObjectMapper().writeValueAsString(CertificateMetadata.create(CONFIGURED, "dev")));++ config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);+ when(config.tls().enabled()).thenReturn(true);+ when(config.tls().certPath()).thenReturn(Optional.empty());+ when(config.storage().persistentPath()).thenReturn(tempDir.toString());+ when(config.hostname()).thenReturn(Optional.of("floci"));+ when(config.baseUrl()).thenReturn("http://localhost:4566");+ when(config.dns().extraSuffixes()).thenReturn(Optional.of(List.of("example.internal")));++ registry = mock(TlsConfigurationRegistry.class);+ defaultTls = mock(TlsConfiguration.class);+ when(registry.getDefault()).thenReturn(Optional.of(defaultTls));+ when(defaultTls.reload()).thenReturn(true);+ }++ TlsCertificateManager manager() {+ return new TlsCertificateManager(config, ca, registry, events);+ }++ /**+ * The manager resolves the TLS directory like every CDI consumer: the one the config+ * bootstrap laid down, else the configured persistent path. Another test class in this JVM+ * may have run a TLS-on bootstrap; a TLS-off bootstrap clears that static, as a real boot does.+ */+ private static void forgetBootstrapTlsDir() {+ System.setProperty("floci.tls.enabled", "false");+ try {+ new TlsConfigSource();+ } finally {+ System.clearProperty("floci.tls.enabled");+ }+ assertNull(TlsConfigSource.resolvedTlsDir());+ }++ X509Certificate read(String name) throws Exception {+ return new CertificateGenerator().parseCertificate(Files.readString(tlsDir.resolve(name)));+ }++ byte[] servedCertificate() throws Exception {+ return Files.readAllBytes(tlsDir.resolve("floci-server.crt"));+ }++ CertificateMetadata readMetadata() throws Exception {+ return new ObjectMapper().readValue(tlsDir.resolve("floci-server.metadata.json").toFile(), CertificateMetadata.class);+ }++ static Set<String> sans(X509Certificate cert) throws Exception {+ Set<String> out = new TreeSet<>();+ for (List<?> entry : cert.getSubjectAlternativeNames()) {+ out.add(String.valueOf(entry.get(1)));+ }+ return out;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateManagerNameRulesTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateManagerNameRulesTest.javanew file mode 100644index 0000000000..749eae61dc--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateManagerNameRulesTest.java@@ -0,0 +1,159 @@+package io.github.hectorvent.floci.config;++import org.bouncycastle.asn1.x509.GeneralName;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Optional;+import java.util.Set;+import java.util.TreeSet;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++/**+ * Which names {@code ensureHost} accepts: host name syntax, the one-label wildcard rule that+ * X.509 name matching and API Gateway custom domains share, and the local-suffix allow-list.+ */+class TlsCertificateManagerNameRulesTest extends TlsCertificateManagerFixture {++ @Test+ void knownOrWildcardCoveredHostIsANoOp() throws Exception {+ byte[] certBefore = servedCertificate();++ TlsCertificateManager m = manager();+ m.ensureHost("localhost");+ m.ensureHost("LOCALHOST.floci.io.");+ m.ensureHost("one-label.localhost.floci.io");+ m.ensureHost(" 127.0.0.1 ");++ assertArrayEquals(certBefore, servedCertificate());+ verify(defaultTls, never()).reload();+ verify(events, never()).fire(any());+ }++ @Test+ void aWildcardCoversExactlyOneLabel() throws Exception {+ TlsCertificateManager m = manager();++ m.ensureHost("one.localhost.floci.io");+ verify(defaultTls, never()).reload();++ m.ensureHost("two.labels.localhost.floci.io");+ verify(defaultTls, times(1)).reload();++ m.ensureHost("other.labels.localhost.floci.io");+ verify(defaultTls, times(2)).reload();+ assertTrue(sans(read("floci-server.crt")).contains("*.localhost.floci.io"), "the wildcard itself is kept");+ }++ @Test+ void wildcardIsAcceptedOnlyAsAWholeLeftmostLabel() throws Exception {+ TlsCertificateManager m = manager();++ m.ensureHost("*.api.example.localhost.floci.io");+ assertTrue(sans(read("floci-server.crt")).contains("*.api.example.localhost.floci.io"),+ "one leading *. label is a valid SAN");+ verify(defaultTls, times(1)).reload();++ m.ensureHost("*");+ m.ensureHost("*.");+ m.ensureHost("api*.example.localhost.floci.io");+ m.ensureHost("*.*.example.localhost.floci.io");+ m.ensureHost("example.*.localhost.floci.io");+ verify(defaultTls, times(1)).reload();+ Set<String> starred = new TreeSet<>(sans(read("floci-server.crt")));+ starred.removeIf(n -> !n.contains("*"));+ assertEquals(Set.of("*.localhost.floci.io", "*.api.example.localhost.floci.io"), starred,+ "malformed wildcards must not reach the certificate");+ }++ @Test+ void namesThatAreNotHostnamesAreRefused() throws Exception {+ byte[] certBefore = servedCertificate();++ TlsCertificateManager m = manager();+ m.ensureHost(null);+ m.ensureHost("");+ m.ensureHost(" ");+ m.ensureHost(".");+ m.ensureHost("api.example.localhost.floci.io:443");+ m.ensureHost("https://api.example.localhost.floci.io");+ m.ensureHost("api example.localhost.floci.io");+ m.ensureHost("api_1.example.localhost.floci.io");+ m.ensureHost("api..example.localhost.floci.io");+ m.ensureHost(".api.example.localhost.floci.io");+ m.ensureHost("-api.example.localhost.floci.io");+ m.ensureHost("api-.example.localhost.floci.io");+ m.ensureHost("a".repeat(64) + ".localhost.floci.io");+ m.ensureHost("a".repeat(63) + "." + "b".repeat(63) + "." + "c".repeat(63) + "." + "d".repeat(63) + ".localhost.floci.io");++ assertArrayEquals(certBefore, servedCertificate());+ verify(defaultTls, never()).reload();+ verify(events, never()).fire(any());+ }++ @Test+ void hostOutsideTheAllowListIsRefused() throws Exception {+ byte[] certBefore = servedCertificate();++ TlsCertificateManager m = manager();+ m.ensureHost("accounts.google.com");+ m.ensureHost("evil-localhost.floci.io");+ m.ensureHost("localhost.floci.io.attacker.example");+ m.ensureHost("floci.example");+ m.ensureHost("*.google.com");++ assertArrayEquals(certBefore, servedCertificate());+ verify(defaultTls, never()).reload();+ assertEquals(List.of(), readMetadata().getLearnedHostnames());+ }++ @Test+ void allowListIncludesConfiguredHostnameBaseUrlAndExtraSuffixes() throws Exception {+ when(config.baseUrl()).thenReturn("https://Floci.Corp.Example:4566");+ TlsCertificateManager m = manager();++ m.ensureHost("api.floci");+ m.ensureHost("floci");+ m.ensureHost("iot.example.internal");+ m.ensureHost("data.localhost.localstack.cloud");+ m.ensureHost("api.floci.corp.example");++ Set<String> sans = sans(read("floci-server.crt"));+ assertTrue(sans.containsAll(List.of("api.floci", "floci", "iot.example.internal",+ "data.localhost.localstack.cloud", "api.floci.corp.example")), sans.toString());+ }++ @Test+ void unusableBaseUrlAndAbsentOptionalConfigStillAllowBuiltinSuffixes() throws Exception {+ when(config.baseUrl()).thenReturn("not a url");+ when(config.hostname()).thenReturn(Optional.empty());+ when(config.dns().extraSuffixes()).thenReturn(Optional.empty());++ manager().ensureHost(NEW_HOST);++ assertTrue(sans(read("floci-server.crt")).contains(NEW_HOST));+ }++ @Test+ void anIpAddressAllowedByTheBaseUrlBecomesAnIpSan() throws Exception {+ when(config.baseUrl()).thenReturn("https://192.168.1.100:4566");++ manager().ensureHost("192.168.1.100");++ boolean ipSan = false;+ for (List<?> entry : read("floci-server.crt").getSubjectAlternativeNames()) {+ if (entry.get(0).equals(GeneralName.iPAddress) && "192.168.1.100".equals(entry.get(1))) {+ ipSan = true;+ }+ }+ assertTrue(ipSan, "an IP is encoded as an iPAddress SAN, not a dNSName");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateManagerTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateManagerTest.javanew file mode 100644index 0000000000..b36c31a9e4--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateManagerTest.java@@ -0,0 +1,360 @@+package io.github.hectorvent.floci.config;++import io.quarkus.tls.CertificateUpdatedEvent;+import org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;++import java.nio.file.Files;+import java.security.cert.X509Certificate;+import java.time.Instant;+import java.time.temporal.ChronoUnit;+import java.util.ArrayList;+import java.util.List;+import java.util.Optional;+import java.util.Set;+import java.util.TreeSet;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;+import java.util.concurrent.TimeUnit;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+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.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyList;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.doCallRealMethod;+import static org.mockito.Mockito.doNothing;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.spy;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++/** Reissue, reload, persistence, reset, failure handling and concurrency. Name rules are next door. */+class TlsCertificateManagerTest extends TlsCertificateManagerFixture {++ @Test+ void newHostIsAppendedWithTheSameKeyAndReloaded() throws Exception {+ byte[] keyBefore = Files.readAllBytes(tlsDir.resolve("floci-server.key"));+ X509Certificate before = read("floci-server.crt");++ manager().ensureHost(NEW_HOST);++ X509Certificate after = read("floci-server.crt");+ assertTrue(sans(after).contains(NEW_HOST), sans(after).toString());+ assertTrue(sans(after).containsAll(CONFIGURED));+ assertEquals(before.getPublicKey(), after.getPublicKey(), "same key pair");+ assertArrayEquals(keyBefore, Files.readAllBytes(tlsDir.resolve("floci-server.key")), "key file never rewritten");+ after.verify(ca.certificate().getPublicKey());++ CertificateMetadata metadata = readMetadata();+ assertEquals(CONFIGURED, metadata.getHostnames(), "configured list untouched");+ assertEquals(List.of(NEW_HOST), metadata.getLearnedHostnames());++ verify(defaultTls).reload();+ ArgumentCaptor<CertificateUpdatedEvent> event = ArgumentCaptor.forClass(CertificateUpdatedEvent.class);+ verify(events).fire(event.capture());+ assertEquals("<default>", event.getValue().name());+ assertEquals(defaultTls, event.getValue().tlsConfiguration());+ assertFalse(Files.exists(tlsDir.resolve("floci-server.crt.tmp")), "temporary file renamed away");+ assertFalse(Files.exists(tlsDir.resolve("floci-server.metadata.json.tmp")), "temporary file renamed away");+ }++ @Test+ void reissuedLeafKeepsTheShapeOfTheBootLeaf() throws Exception {+ X509Certificate before = read("floci-server.crt");++ manager().ensureHost(NEW_HOST);++ X509Certificate after = read("floci-server.crt");+ assertEquals(before.getSubjectX500Principal(), after.getSubjectX500Principal(), "subject unchanged");+ assertEquals(ca.certificate().getSubjectX500Principal(), after.getIssuerX500Principal(), "issued by the local CA");+ assertTrue(ca.isIssuedByUs(after));+ assertNotEquals(before.getSerialNumber(), after.getSerialNumber(), "a reissue is a new certificate");+ assertEquals(-1, after.getBasicConstraints(), "a server leaf, not a CA");+ assertEquals(List.of("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.2"), after.getExtendedKeyUsage(),+ "serverAuth and clientAuth, as an ACM-issued certificate carries");+ after.checkValidity();+ assertTrue(after.getNotAfter().toInstant().isBefore(Instant.now().plus(366, ChronoUnit.DAYS)),+ "validity is not extended beyond a normal leaf");+ assertTrue(after.getNotAfter().toInstant().isAfter(Instant.now().plus(364, ChronoUnit.DAYS)));++ List<String> ordered = new ArrayList<>();+ for (List<?> entry : after.getSubjectAlternativeNames()) {+ ordered.add(String.valueOf(entry.get(1)));+ }+ assertEquals(CONFIGURED, ordered.subList(0, CONFIGURED.size()), "configured names first, in their order");+ assertEquals(NEW_HOST, ordered.get(ordered.size() - 1), "learned names appended");+ }++ @Test+ void secondCallForTheSameHostDoesNotReissue() throws Exception {+ TlsCertificateManager m = manager();+ m.ensureHost(NEW_HOST);+ byte[] certAfterFirst = servedCertificate();++ m.ensureHost(NEW_HOST);+ m.ensureHost(NEW_HOST.toUpperCase());++ assertArrayEquals(certAfterFirst, servedCertificate());+ verify(defaultTls, times(1)).reload();+ }++ @Test+ void learnedHostsSurviveANewManagerInstance() throws Exception {+ manager().ensureHost(NEW_HOST);++ TlsCertificateManager fresh = manager();+ fresh.ensureHost(NEW_HOST);++ verify(defaultTls, times(1)).reload();+ assertTrue(fresh.knownHostnames().contains(NEW_HOST));+ assertTrue(fresh.knownHostnames().containsAll(CONFIGURED));+ }++ @Test+ void aSecondLearnedHostKeepsTheFirst() throws Exception {+ manager().ensureHost(NEW_HOST);++ manager().ensureHost("auth.example.localhost.floci.io");++ Set<String> sans = sans(read("floci-server.crt"));+ assertTrue(sans.containsAll(List.of(NEW_HOST, "auth.example.localhost.floci.io")), sans.toString());+ assertEquals(List.of(NEW_HOST, "auth.example.localhost.floci.io"), readMetadata().getLearnedHostnames());+ }++ @Test+ void clearDropsLearnedHostsAndKeepsConfiguredOnes() throws Exception {+ TlsCertificateManager m = manager();+ m.ensureHost(NEW_HOST);++ m.clear();++ Set<String> sans = sans(read("floci-server.crt"));+ assertFalse(sans.contains(NEW_HOST));+ assertTrue(sans.containsAll(CONFIGURED));+ assertEquals(List.of(), readMetadata().getLearnedHostnames());+ assertEquals(CONFIGURED, readMetadata().getHostnames());+ assertFalse(m.knownHostnames().contains(NEW_HOST));+ verify(defaultTls, times(2)).reload();+ }++ @Test+ void clearWithNothingLearnedTouchesNothing() throws Exception {+ byte[] certBefore = servedCertificate();++ manager().clear();++ assertArrayEquals(certBefore, servedCertificate());+ verify(defaultTls, never()).reload();+ }++ @Test+ void doesNothingWhenTlsIsOff() throws Exception {+ when(config.tls().enabled()).thenReturn(false);+ byte[] certBefore = servedCertificate();++ TlsCertificateManager m = manager();+ m.ensureHost(NEW_HOST);+ m.clear();++ assertArrayEquals(certBefore, servedCertificate());+ assertEquals(Set.of(), m.knownHostnames());+ verify(defaultTls, never()).reload();+ }++ @Test+ void doesNothingWithAUserProvidedCertificate() throws Exception {+ when(config.tls().certPath()).thenReturn(Optional.of("/etc/floci/user.crt"));+ byte[] certBefore = servedCertificate();++ manager().ensureHost(NEW_HOST);++ assertArrayEquals(certBefore, servedCertificate());+ verify(defaultTls, never()).reload();+ }++ @Test+ void doesNothingWithoutAServerLeafOnDisk() throws Exception {+ Files.delete(tlsDir.resolve("floci-server.crt"));++ TlsCertificateManager m = manager();+ m.ensureHost(NEW_HOST);++ assertFalse(Files.exists(tlsDir.resolve("floci-server.crt")));+ assertEquals(Set.of(), m.knownHostnames());+ verify(defaultTls, never()).reload();+ }++ @Test+ void aFailedReloadIsRetriedByTheNextCall() throws Exception {+ when(defaultTls.reload()).thenReturn(false);+ TlsCertificateManager m = manager();++ m.ensureHost(NEW_HOST);++ assertTrue(sans(read("floci-server.crt")).contains(NEW_HOST), "the file is still written for the next boot");+ verify(events, never()).fire(any());+ assertFalse(m.knownHostnames().contains(NEW_HOST), "a name the listener does not serve is not known");++ when(defaultTls.reload()).thenReturn(true);+ m.ensureHost(NEW_HOST);++ verify(defaultTls, times(2)).reload();+ verify(events, times(1)).fire(any());+ assertTrue(m.knownHostnames().contains(NEW_HOST));+ assertEquals(List.of(NEW_HOST), readMetadata().getLearnedHostnames());+ }++ @Test+ void aNameWhoseReloadFailedIsCarriedIntoTheNextReissue() throws Exception {+ when(defaultTls.reload()).thenReturn(false);+ TlsCertificateManager m = manager();+ m.ensureHost(NEW_HOST);+ assertFalse(m.knownHostnames().contains(NEW_HOST));++ when(defaultTls.reload()).thenReturn(true);+ m.ensureHost("auth.example.localhost.floci.io");++ Set<String> sans = sans(read("floci-server.crt"));+ assertTrue(sans.contains(NEW_HOST), "the name written to disk is not dropped by the next reissue: " + sans);+ assertTrue(sans.contains("auth.example.localhost.floci.io"), sans.toString());+ assertTrue(m.knownHostnames().containsAll(List.of(NEW_HOST, "auth.example.localhost.floci.io")));+ assertEquals(List.of(NEW_HOST, "auth.example.localhost.floci.io"), readMetadata().getLearnedHostnames());+ verify(defaultTls, times(2)).reload();+ verify(events, times(1)).fire(any());+ }++ @Test+ void aResetWhoseReloadFailedIsRetriedByTheNextReset() throws Exception {+ TlsCertificateManager m = manager();+ m.ensureHost(NEW_HOST);++ when(defaultTls.reload()).thenReturn(false);+ m.clear();+ assertEquals(List.of(), readMetadata().getLearnedHostnames(), "the files are reset");+ assertTrue(m.knownHostnames().contains(NEW_HOST), "the listener still serves the name");++ when(defaultTls.reload()).thenReturn(true);+ m.clear();++ verify(defaultTls, times(3)).reload();+ assertFalse(m.knownHostnames().contains(NEW_HOST));+ assertFalse(sans(read("floci-server.crt")).contains(NEW_HOST));+ }++ @Test+ void aMissingDefaultTlsConfigurationIsRetriedByTheNextCall() throws Exception {+ when(registry.getDefault()).thenReturn(Optional.empty());+ TlsCertificateManager m = manager();++ m.ensureHost(NEW_HOST);++ verify(events, never()).fire(any());+ assertFalse(m.knownHostnames().contains(NEW_HOST));++ when(registry.getDefault()).thenReturn(Optional.of(defaultTls));+ m.ensureHost(NEW_HOST);++ verify(defaultTls, times(1)).reload();+ verify(events, times(1)).fire(any());+ assertTrue(m.knownHostnames().contains(NEW_HOST));+ }++ @Test+ void aFailingListenerIsRetriedByTheNextCall() throws Exception {+ doThrow(new IllegalStateException("observer failed")).when(events).fire(any());+ TlsCertificateManager m = manager();++ m.ensureHost(NEW_HOST);+ assertFalse(m.knownHostnames().contains(NEW_HOST));++ doNothing().when(events).fire(any());+ m.ensureHost(NEW_HOST);++ verify(defaultTls, times(2)).reload();+ assertTrue(m.knownHostnames().contains(NEW_HOST));+ }++ @Test+ void aFailedReissueLeavesTheServedFilesIntactAndDoesNotThrow() throws Exception {+ FlociCertificateAuthority broken = spy(ca);+ doThrow(new IllegalStateException("boom")).when(broken).issueServerCertificate(anyString(), anyList(), any(), any());+ byte[] certBefore = servedCertificate();+ String metadataBefore = Files.readString(tlsDir.resolve("floci-server.metadata.json"));++ TlsCertificateManager m = new TlsCertificateManager(config, broken, registry, events);+ m.ensureHost(NEW_HOST);++ assertArrayEquals(certBefore, servedCertificate());+ assertEquals(metadataBefore, Files.readString(tlsDir.resolve("floci-server.metadata.json")));+ assertFalse(m.knownHostnames().contains(NEW_HOST), "a name that was never served is not known");+ verify(defaultTls, never()).reload();++ doCallRealMethod().when(broken).issueServerCertificate(anyString(), anyList(), any(), any());+ m.ensureHost("auth.example.localhost.floci.io");+ Set<String> sans = sans(read("floci-server.crt"));+ assertTrue(sans.contains("auth.example.localhost.floci.io"), sans.toString());+ assertFalse(sans.contains(NEW_HOST), "the failed name is not carried into later reissues");+ assertEquals(List.of("auth.example.localhost.floci.io"), readMetadata().getLearnedHostnames());+ }++ @Test+ void concurrentCallsForDistinctHostsAllLandInTheCertificate() throws Exception {+ TlsCertificateManager m = manager();+ List<String> hosts = new ArrayList<>();+ for (int i = 0; i < 8; i++) {+ hosts.add("svc" + i + ".example.localhost.floci.io");+ }++ runConcurrently(hosts, m);++ Set<String> sans = sans(read("floci-server.crt"));+ assertTrue(sans.containsAll(hosts), sans.toString());+ assertTrue(sans.containsAll(CONFIGURED));+ assertEquals(new TreeSet<>(hosts), new TreeSet<>(readMetadata().getLearnedHostnames()));+ assertTrue(m.knownHostnames().containsAll(hosts));+ verify(defaultTls, times(8)).reload();+ }++ @Test+ void concurrentCallsForTheSameHostReissueOnce() throws Exception {+ TlsCertificateManager m = manager();+ List<String> hosts = new ArrayList<>();+ for (int i = 0; i < 8; i++) {+ hosts.add(NEW_HOST);+ }++ runConcurrently(hosts, m);++ assertEquals(List.of(NEW_HOST), readMetadata().getLearnedHostnames());+ verify(defaultTls, times(1)).reload();+ }++ private static void runConcurrently(List<String> hosts, TlsCertificateManager m) throws Exception {+ ExecutorService pool = Executors.newFixedThreadPool(hosts.size());+ CountDownLatch start = new CountDownLatch(1);+ List<Future<?>> futures = new ArrayList<>();+ try {+ for (String host : hosts) {+ futures.add(pool.submit(() -> {+ start.await();+ m.ensureHost(host);+ return null;+ }));+ }+ start.countDown();+ for (Future<?> f : futures) {+ f.get(60, TimeUnit.SECONDS);+ }+ } finally {+ pool.shutdownNow();+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceLearnedHostnamesTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceLearnedHostnamesTest.javanew file mode 100644index 0000000000..ee3f634eb0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceLearnedHostnamesTest.java@@ -0,0 +1,177 @@+package io.github.hectorvent.floci.config;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import org.bouncycastle.asn1.x500.X500Name;+import org.bouncycastle.jce.provider.BouncyCastleProvider;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++import java.nio.file.Files;+import java.nio.file.Path;+import java.security.KeyPair;+import java.security.KeyPairGenerator;+import java.security.Security;+import java.security.cert.X509Certificate;+import java.util.ArrayList;+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.assertTrue;++/**+ * Hostnames {@link TlsCertificateManager} learned at runtime must survive every boot path of+ * {@link TlsConfigSource}: a reused certificate, a regeneration after a configuration change,+ * a reissue of an expired leaf, and a certificate whose metadata write did not complete.+ */+class TlsConfigSourceLearnedHostnamesTest {++ private static final String LEARNED = "api.example.localhost.floci.io";+ private static final List<String> DEFAULTS = List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",+ "localhost.floci.io", "*.localhost.floci.io", "*.execute-api.localhost.floci.io",+ "*.execute-api.localhost.localstack.cloud", "host.docker.internal");+ private static final ObjectMapper MAPPER = new ObjectMapper();++ @TempDir+ Path tempDir;++ private Path tlsDir;+ private Path metadataFile;++ @BeforeAll+ static void bouncyCastle() {+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {+ Security.addProvider(new BouncyCastleProvider());+ }+ }++ @BeforeEach+ void tlsOn() {+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());+ tlsDir = tempDir.resolve("tls");+ metadataFile = tlsDir.resolve("floci-server.metadata.json");+ }++ @AfterEach+ void clearProperties() {+ System.clearProperty("floci.hostname");+ System.clearProperty("floci.tls.enabled");+ System.clearProperty("floci.tls.self-signed");+ System.clearProperty("floci.storage.persistent-path");+ }++ @Test+ void learnedHostnamesAreKeptWhenBootRegeneratesTheCertificate() throws Exception {+ System.setProperty("floci.hostname", "host1");+ new TlsConfigSource();+ recordAsLearned(LEARNED);++ System.setProperty("floci.hostname", "host2");+ new TlsConfigSource();++ List<String> sans = servedSans();+ assertTrue(sans.contains("host2"), sans.toString());+ assertFalse(sans.contains("host1"), sans.toString());+ assertTrue(sans.contains(LEARNED), "learned name must survive: " + sans);+ CertificateMetadata after = readMetadata();+ assertEquals(List.of(LEARNED), after.getLearnedHostnames());+ assertFalse(after.getHostnames().contains(LEARNED), "learned names stay out of the configured list");+ }++ @Test+ void aLearnedHostnameDoesNotCountAsAConfigurationChange() throws Exception {+ new TlsConfigSource();+ recordAsLearned(LEARNED);+ String certBefore = Files.readString(tlsDir.resolve("floci-server.crt"));++ new TlsConfigSource();++ assertEquals(certBefore, Files.readString(tlsDir.resolve("floci-server.crt")),+ "same configuration: the certificate is reused, not regenerated");+ }++ @Test+ void learnedHostnamesAreKeptWhenAnExpiredLeafIsReissued() throws Exception {+ Files.createDirectories(tlsDir);+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);+ CertificateGenerator gen = new CertificateGenerator();+ List<String> sans = new ArrayList<>(DEFAULTS);+ sans.add(LEARNED);+ KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();+ X509Certificate expired = gen.signCertificate(new X500Name("CN=localhost"), keyPair.getPublic(),+ X500Name.getInstance(ca.certificate().getSubjectX500Principal().getEncoded()), ca.key(), sans, false,+ CertificateGenerator.LeafUsage.SERVER, -1);+ Files.writeString(tlsDir.resolve("floci-server.crt"), gen.toPem(expired));+ Files.writeString(tlsDir.resolve("floci-server.key"), gen.toPem(keyPair.getPrivate()));+ CertificateMetadata metadata = CertificateMetadata.create(DEFAULTS, "dev");+ metadata.setLearnedHostnames(List.of(LEARNED));+ Files.writeString(metadataFile, MAPPER.writeValueAsString(metadata));++ new TlsConfigSource();++ X509Certificate leaf = parseCertificate(tlsDir.resolve("floci-server.crt"));+ leaf.checkValidity();+ assertNotEquals(expired.getSerialNumber(), leaf.getSerialNumber(), "the expired leaf was reissued");+ List<String> reissued = servedSans();+ assertTrue(reissued.contains(LEARNED), "learned name must survive: " + reissued);+ assertTrue(reissued.containsAll(DEFAULTS), reissued.toString());+ }++ @Test+ void aSanTheMetadataDoesNotListIsKeptAsLearnedWhenBootRegenerates() throws Exception {+ System.setProperty("floci.hostname", "host1");+ new TlsConfigSource();+ CertificateMetadata bootMetadata = readMetadata();++ // A runtime reissue whose certificate rename succeeded and whose metadata rename did not:+ // the served leaf carries the learned name, the metadata knows nothing about it.+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);+ CertificateGenerator gen = new CertificateGenerator();+ X509Certificate served = parseCertificate(tlsDir.resolve("floci-server.crt"));+ KeyPair keyPair = new KeyPair(served.getPublicKey(),+ gen.parsePrivateKey(Files.readString(tlsDir.resolve("floci-server.key"))));+ List<String> sans = new ArrayList<>(bootMetadata.getHostnames());+ sans.add(LEARNED);+ Files.writeString(tlsDir.resolve("floci-server.crt"),+ ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, keyPair).certificatePem());++ System.setProperty("floci.hostname", "host2");+ new TlsConfigSource();++ List<String> regenerated = servedSans();+ assertTrue(regenerated.contains(LEARNED), "served name must survive: " + regenerated);+ assertTrue(regenerated.contains("host2"), regenerated.toString());+ assertFalse(regenerated.contains("host1"), "a previously configured name is not mistaken for a learned one");+ assertEquals(List.of(LEARNED), readMetadata().getLearnedHostnames());+ }++ private void recordAsLearned(String name) throws Exception {+ CertificateMetadata metadata = readMetadata();+ metadata.setLearnedHostnames(List.of(name));+ Files.writeString(metadataFile, MAPPER.writeValueAsString(metadata));+ }++ private CertificateMetadata readMetadata() throws Exception {+ return MAPPER.readValue(metadataFile.toFile(), CertificateMetadata.class);+ }++ private List<String> servedSans() throws Exception {+ List<String> sans = new ArrayList<>();+ for (List<?> entry : parseCertificate(tlsDir.resolve("floci-server.crt")).getSubjectAlternativeNames()) {+ sans.add(String.valueOf(entry.get(1)));+ }+ return sans;+ }++ private static X509Certificate parseCertificate(Path certFile) throws Exception {+ return new CertificateGenerator().parseCertificate(Files.readString(certFile));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsEnsureHostIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsEnsureHostIntegrationTest.javanew file mode 100644index 0000000000..be7e3556ec--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsEnsureHostIntegrationTest.java@@ -0,0 +1,183 @@+package io.github.hectorvent.floci.config;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import jakarta.inject.Inject;+import org.eclipse.microprofile.config.inject.ConfigProperty;+import org.junit.jupiter.api.Test;++import javax.net.ssl.HttpsURLConnection;+import javax.net.ssl.SNIHostName;+import javax.net.ssl.SSLContext;+import javax.net.ssl.SSLHandshakeException;+import javax.net.ssl.SSLParameters;+import javax.net.ssl.SSLSocket;+import javax.net.ssl.TrustManagerFactory;+import java.io.IOException;+import java.net.InetAddress;+import java.net.InetSocketAddress;+import java.net.URI;+import java.nio.file.Files;+import java.nio.file.Path;+import java.security.KeyStore;+import java.security.cert.X509Certificate;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.TreeSet;++import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * End to end: after {@code ensureHost}, a TLS client that trusts only the local CA and sends the+ * new name as SNI receives a leaf whose SAN list contains it, and a client that also verifies the+ * server's identity for that name (what every SDK does) completes the handshake, with no restart+ * in between. A file assertion cannot show that the reload reached the listener; only a+ * handshake can.+ */+@QuarkusTest+@TestProfile(TlsEnsureHostIntegrationTest.Profile.class)+class TlsEnsureHostIntegrationTest {++ static final Path DATA_DIR = Path.of("target", "floci-tls-ensure-host-test").toAbsolutePath();+ static final Path TLS_DIR = DATA_DIR.resolve("tls");+ static final String NEW_HOST = "api.example.localhost.floci.io";++ @ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")+ int sslPort;++ @Inject+ TlsCertificateManager manager;++ @Test+ void ensureHostIsVisibleToTheNextHandshakeAndResetTakesItBack() throws Exception {+ X509Certificate boot = peerLeaf();+ assertFalse(sans(boot).contains(NEW_HOST), "precondition: the boot leaf does not cover " + NEW_HOST);+ assertThrows(SSLHandshakeException.class, this::handshakeVerifyingNewHost,+ "precondition: a client verifying the new name rejects the boot leaf");+ assertEquals(200, healthOverHttpsAsLocalhost(), "the configured name is served before");++ manager.ensureHost(NEW_HOST);++ X509Certificate extended = peerLeaf();+ Set<String> sans = sans(extended);+ assertTrue(sans.contains(NEW_HOST), sans.toString());+ assertTrue(sans.contains("localhost"), "configured names are still served: " + sans);+ assertEquals(boot.getPublicKey(), extended.getPublicKey(), "same key pair across the reload");+ handshakeVerifyingNewHost();+ assertEquals(200, healthOverHttpsAsLocalhost(), "the configured name is still served after the swap");++ given().when().post("/_floci/state/reset").then().statusCode(200);++ Set<String> afterReset = sans(peerLeaf());+ assertFalse(afterReset.contains(NEW_HOST), "reset drops the learned name: " + afterReset);+ assertTrue(afterReset.contains("localhost"), afterReset.toString());+ assertThrows(SSLHandshakeException.class, this::handshakeVerifyingNewHost, "reset: the new name is rejected again");+ assertEquals(200, healthOverHttpsAsLocalhost(), "the configured name is served after reset");+ }++ /** The leaf the server presents for SNI {@code NEW_HOST}, with no identity check. */+ private X509Certificate peerLeaf() throws Exception {+ return handshake(false);+ }++ /** A handshake as an SDK would do it: SNI {@code NEW_HOST} and RFC 6125 identity verification. */+ private void handshakeVerifyingNewHost() throws Exception {+ handshake(true);+ }++ /**+ * Connects by IP so the JDK has no peer host of its own and verifies the certificate against+ * the SNI name; the fixture leaf carries no {@code 127.0.0.1} SAN, so nothing else can match.+ */+ private X509Certificate handshake(boolean verifyIdentity) throws Exception {+ try (SSLSocket socket = (SSLSocket) trustOnlyTheCa().getSocketFactory().createSocket()) {+ socket.connect(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), sslPort), 5000);+ SSLParameters params = socket.getSSLParameters();+ params.setServerNames(List.of(new SNIHostName(NEW_HOST)));+ if (verifyIdentity) {+ params.setEndpointIdentificationAlgorithm("HTTPS");+ }+ socket.setSSLParameters(params);+ socket.startHandshake();+ return (X509Certificate) socket.getSession().getPeerCertificates()[0];+ }+ }++ /** A plain HTTPS client with the JDK's default hostname verifier, for the configured name. */+ private int healthOverHttpsAsLocalhost() throws Exception {+ HttpsURLConnection connection = (HttpsURLConnection) URI.create(+ "https://localhost:" + sslPort + "/_floci/health").toURL().openConnection();+ connection.setSSLSocketFactory(trustOnlyTheCa().getSocketFactory());+ try {+ return connection.getResponseCode();+ } finally {+ connection.disconnect();+ }+ }++ private static SSLContext trustOnlyTheCa() throws Exception {+ KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());+ trust.load(null, null);+ trust.setCertificateEntry("floci", FlociCertificateAuthority.loadOrCreate(TLS_DIR).certificate());+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());+ tmf.init(trust);+ SSLContext ctx = SSLContext.getInstance("TLS");+ ctx.init(null, tmf.getTrustManagers(), null);+ return ctx;+ }++ private static Set<String> sans(X509Certificate leaf) throws Exception {+ Set<String> sans = new TreeSet<>();+ for (List<?> entry : leaf.getSubjectAlternativeNames()) {+ sans.add(String.valueOf(entry.get(1)));+ }+ return sans;+ }++ /**+ * Boots with TLS on and a CA-issued leaf like the one TlsConfigSource writes. TlsConfigSource+ * itself reads system properties, not profile overrides, so the profile lays the files down+ * and points the TLS registry's default entry at them. The wildcard covers one label only+ * (RFC 6125), so the three-label name is genuinely uncovered before ensureHost.+ */+ public static final class Profile implements QuarkusTestProfile {++ static {+ try {+ Files.createDirectories(TLS_DIR);+ for (String name : List.of("floci-server.crt", "floci-server.key", "floci-server.metadata.json")) {+ Files.deleteIfExists(TLS_DIR.resolve(name));+ }+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);+ List<String> sans = List.of("localhost", "*.localhost.floci.io");+ var leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);+ Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());+ Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());+ Files.writeString(TLS_DIR.resolve("floci-server.metadata.json"),+ new ObjectMapper().writeValueAsString(CertificateMetadata.create(sans, "dev")));+ } catch (IOException e) {+ throw new IllegalStateException("could not prepare the TLS fixtures", e);+ }+ }++ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of(+ "floci.tls.enabled", "true",+ "floci.tls.self-signed", "true",+ "floci.tls.aws-https-port", "0",+ "floci.storage.persistent-path", DATA_DIR.toString(),+ "quarkus.tls.key-store.pem.0.cert", TLS_DIR.resolve("floci-server.crt").toString(),+ "quarkus.tls.key-store.pem.0.key", TLS_DIR.resolve("floci-server.key").toString(),+ "quarkus.http.insecure-requests", "enabled");+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsIntegrationTest.javaindex 5b0aad37b2..4217697d1a 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsIntegrationTest.java@@ -131,7 +131,7 @@ class TlsIntegrationTest {Security.addProvider(new BouncyCastleProvider());}CertificateGenerator gen = new CertificateGenerator();- CertificateGenerator.GeneratedCertificate cert = gen.generateCertificate(+ CertificateGenerator.GeneratedCertificate cert = gen.generateSelfSignedCertificate("localhost", List.of("localhost", "127.0.0.1"), KeyAlgorithm.RSA_2048);Files.writeString(CERT_FILE, cert.certificatePem());Files.writeString(KEY_FILE, cert.privateKeyPem());diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.javaindex e47374850a..549b2a08e5 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java@@ -116,7 +116,7 @@ class TlsUserCertIntegrationTest {Security.addProvider(new BouncyCastleProvider());}CertificateGenerator gen = new CertificateGenerator();- CertificateGenerator.GeneratedCertificate cert = gen.generateCertificate(+ CertificateGenerator.GeneratedCertificate cert = gen.generateSelfSignedCertificate("localhost", List.of("localhost", "127.0.0.1"), KeyAlgorithm.RSA_2048);Files.writeString(CERT_FILE, cert.certificatePem());Files.writeString(KEY_FILE, cert.privateKeyPem());diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmImportExportTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmImportExportTest.javaindex 3456ad0708..7efef80e4c 100644--- a/src/test/java/io/github/hectorvent/floci/services/acm/AcmImportExportTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmImportExportTest.java@@ -1,9 +1,9 @@package io.github.hectorvent.floci.services.acm;+import io.github.hectorvent.floci.config.FlociCertificateAuthority;import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;import io.quarkus.test.junit.QuarkusTest;-import jakarta.inject.Inject;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.MethodOrderer;import org.junit.jupiter.api.Order;@@ -11,6 +11,7 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestInstance;import org.junit.jupiter.api.TestMethodOrder;+import java.nio.file.Files;import java.util.Base64;import java.util.List;@@ -24,29 +25,29 @@ class AcmImportExportTest {private static final String ACM_CONTENT_TYPE = "application/x-amz-json-1.1";- @Inject- CertificateGenerator certificateGenerator;-- // Generated test certificate data+ // A server certificate from a CA that is not Floci's, with that CA as its chain: what a user importsprivate String validTestCertificate;private String validTestPrivateKey;+ private String validTestChain;private String importedCertificateArn;private String exportableCertificateArn;@BeforeAll- void setupTestCertificates() {+ void setupTestCertificates() throws Exception {RestAssuredJsonUtils.configureAwsContentTypes();- // Generate a valid test certificate using CertificateGenerator- CertificateGenerator.GeneratedCertificate generated = certificateGenerator.generateCertificate(+ FlociCertificateAuthority otherCa = FlociCertificateAuthority.loadOrCreate(Files.createTempDirectory("acm-import-ca"));+ CertificateGenerator.GeneratedCertificate generated = otherCa.issueServerCertificate("test-import.example.com",List.of("www.test-import.example.com"),- KeyAlgorithm.RSA_2048+ KeyAlgorithm.RSA_2048,+ null);validTestCertificate = generated.certificatePem().replace("\r\n", "\n");validTestPrivateKey = generated.privateKeyPem().replace("\r\n", "\n");+ validTestChain = otherCa.caPem().replace("\r\n", "\n");}// ==================== ImportCertificate Tests ====================@@ -57,6 +58,7 @@ class AcmImportExportTest {// Escape newlines for JSONString certJson = validTestCertificate.replace("\n", "\\n");String keyJson = validTestPrivateKey.replace("\n", "\\n");+ String chainJson = validTestChain.replace("\n", "\\n");importedCertificateArn = given().header("X-Amz-Target", "CertificateManager.ImportCertificate")@@ -64,9 +66,10 @@ class AcmImportExportTest {.body("""{"Certificate": "%s",- "PrivateKey": "%s"+ "PrivateKey": "%s",+ "CertificateChain": "%s"}- """.formatted(certJson, keyJson))+ """.formatted(certJson, keyJson, chainJson)).when().post("/").then()@@ -98,6 +101,22 @@ class AcmImportExportTest {.body("Certificate.KeyAlgorithm", equalTo("RSA-2048")).body("Certificate.Serial", matchesPattern("([0-9a-f]{2}:)+[0-9a-f]{2}")).body("Certificate.SignatureAlgorithm", matchesPattern("SHA[0-9]+WITH[A-Z]+"));++ // An import keeps the certificate and the chain exactly as uploaded+ given()+ .header("X-Amz-Target", "CertificateManager.GetCertificate")+ .contentType(ACM_CONTENT_TYPE)+ .body("""+ {+ "CertificateArn": "%s"+ }+ """.formatted(importedCertificateArn))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Certificate", equalTo(validTestCertificate))+ .body("CertificateChain", equalTo(validTestChain));}@Test@@ -193,6 +212,7 @@ class AcmImportExportTest {@Order(11)void exportCertificate() {String passphrase = Base64.getEncoder().encodeToString("testpassphrase".getBytes());+ String localCa = given().when().get("/_floci/ca.pem").then().statusCode(200).extract().asString();given().header("X-Amz-Target", "CertificateManager.ExportCertificate")@@ -208,6 +228,7 @@ class AcmImportExportTest {.then().statusCode(200).body("Certificate", startsWith("-----BEGIN CERTIFICATE-----"))+ .body("CertificateChain", equalTo(localCa)).body("PrivateKey", startsWith("-----BEGIN ENCRYPTED PRIVATE KEY-----"));}diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmInUseByTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmInUseByTest.javaindex 7068fc106d..b6ad0a507f 100644--- a/src/test/java/io/github/hectorvent/floci/services/acm/AcmInUseByTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmInUseByTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.acm;+import io.github.hectorvent.floci.config.FlociCertificateAuthority;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.storage.InMemoryStorage;@@ -9,7 +10,9 @@ import org.bouncycastle.jce.provider.BouncyCastleProvider;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;+import java.nio.file.Path;import java.security.Security;import java.util.List;import java.util.Map;@@ -33,6 +36,9 @@ class AcmInUseByTest {private static CertificateGenerator generator;private AcmService service;+ @TempDir+ Path tempDir;+@BeforeAllstatic void registerProvider() {if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {@@ -45,7 +51,8 @@ class AcmInUseByTest {void setUp() {RegionResolver regionResolver = mock(RegionResolver.class);when(regionResolver.getAccountId()).thenReturn("000000000000");- service = new AcmService(new InMemoryStorage<>(), generator, regionResolver, 0);+ service = new AcmService(new InMemoryStorage<>(), generator,+ FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")), regionResolver, 0);}private String requestCertificate() {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.javaindex 8da953f962..34cbf8d195 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@@ -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.MethodOrderer;import org.junit.jupiter.api.Order;@@ -9,8 +10,21 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestInstance;import org.junit.jupiter.api.TestMethodOrder;+import java.io.ByteArrayInputStream;+import java.nio.charset.StandardCharsets;+import java.security.cert.CertPathValidator;+import java.security.cert.CertificateFactory;+import java.security.cert.PKIXParameters;+import java.security.cert.TrustAnchor;+import java.security.cert.X509Certificate;+import java.security.interfaces.ECPublicKey;+import java.security.interfaces.RSAPublicKey;+import java.util.List;+import java.util.Set;+import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.*;+import static org.junit.jupiter.api.Assertions.assertEquals;@QuarkusTest@TestMethodOrder(MethodOrderer.OrderAnnotation.class)@@ -19,6 +33,7 @@ class AcmIntegrationTest {private static final String ACM_CONTENT_TYPE = "application/x-amz-json-1.1";private static String createdCertificateArn;+ private static String ecCertificateArn;@BeforeAllstatic void configureRestAssured() {@@ -107,7 +122,7 @@ class AcmIntegrationTest {@Test@Order(5)void requestCertificateWithKeyAlgorithm() {- given()+ ecCertificateArn = given().header("X-Amz-Target", "CertificateManager.RequestCertificate").contentType(ACM_CONTENT_TYPE).body("""@@ -120,7 +135,8 @@ class AcmIntegrationTest {.post("/").then().statusCode(200)- .body("CertificateArn", startsWith("arn:aws:acm:"));+ .body("CertificateArn", startsWith("arn:aws:acm:"))+ .extract().jsonPath().getString("CertificateArn");}@Test@@ -224,7 +240,7 @@ class AcmIntegrationTest {.body("Certificate.Type", equalTo("AMAZON_ISSUED")).body("Certificate.Serial", notNullValue()).body("Certificate.Subject", startsWith("CN="))- .body("Certificate.Issuer", notNullValue())+ .body("Certificate.Issuer", equalTo("CN=Floci Local CA")).body("Certificate.KeyAlgorithm", equalTo("RSA-2048")).body("Certificate.NotBefore", notNullValue()).body("Certificate.NotAfter", notNullValue());@@ -252,21 +268,14 @@ class AcmIntegrationTest {@Test@Order(12)- void getCertificate() {- given()- .header("X-Amz-Target", "CertificateManager.GetCertificate")- .contentType(ACM_CONTENT_TYPE)- .body("""- {- "CertificateArn": "%s"- }- """.formatted(createdCertificateArn))- .when()- .post("/")- .then()- .statusCode(200)- .body("Certificate", startsWith("-----BEGIN CERTIFICATE-----"))- .body("CertificateChain", startsWith("-----BEGIN CERTIFICATE-----"));+ void getCertificate() throws Exception {+ var response = getCertificatePems(createdCertificateArn);++ X509Certificate leaf = assertLeafChainsToLocalCa(response.getString("Certificate"),+ response.getString("CertificateChain"));+ assertEquals("RSA", leaf.getPublicKey().getAlgorithm());+ assertEquals(2048, ((RSAPublicKey) leaf.getPublicKey()).getModulus().bitLength(),+ "RSA_2048 is the default KeyAlgorithm");}// ==================== User Story 2: ListCertificates ====================@@ -324,6 +333,41 @@ class AcmIntegrationTest {.body("CertificateSummaryList", notNullValue());}+ @Test+ @Order(16)+ void privateCertificateChainsToTheSameCa() throws Exception {+ String arn = given()+ .header("X-Amz-Target", "CertificateManager.RequestCertificate")+ .contentType(ACM_CONTENT_TYPE)+ .body("""+ {+ "DomainName": "internal.example.com",+ "CertificateAuthorityArn": "arn:aws:acm-pca:us-east-1:000000000000:certificate-authority/11111111-2222-3333-4444-555555555555"+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().jsonPath().getString("CertificateArn");++ var response = getCertificatePems(arn);++ assertLeafChainsToLocalCa(response.getString("Certificate"), response.getString("CertificateChain"));+ }++ @Test+ @Order(17)+ void ecCertificateKeepsItsKeyAlgorithmAndChainsToTheSameCa() throws Exception {+ var response = getCertificatePems(ecCertificateArn);++ X509Certificate leaf = assertLeafChainsToLocalCa(response.getString("Certificate"),+ response.getString("CertificateChain"));+ assertEquals("EC", leaf.getPublicKey().getAlgorithm(), "the requested KeyAlgorithm is honoured");+ assertEquals(256, ((ECPublicKey) leaf.getPublicKey()).getParams().getCurve().getField().getFieldSize(),+ "EC_prime256v1 is a P-256 key");+ }+// ==================== User Story 5: Tagging ====================@Test@@ -695,4 +739,48 @@ class AcmIntegrationTest {.statusCode(400).body("__type", equalTo("UnsupportedOperation"));}++ private static JsonPath getCertificatePems(String certificateArn) {+ return given()+ .header("X-Amz-Target", "CertificateManager.GetCertificate")+ .contentType(ACM_CONTENT_TYPE)+ .body("""+ {+ "CertificateArn": "%s"+ }+ """.formatted(certificateArn))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().jsonPath();+ }++ /**+ * Certificate is a TLS server leaf, CertificateChain is exactly the local CA served at+ * /_floci/ca.pem, and the pair builds a PKIX path with that CA as the only trust anchor: what a+ * client that pins Certificate plus CertificateChain does, so a signature check alone is not enough.+ */+ private static X509Certificate assertLeafChainsToLocalCa(String leafPem, String chainPem) throws Exception {+ CertificateFactory factory = CertificateFactory.getInstance("X.509");+ X509Certificate leaf = parse(factory, leafPem);+ X509Certificate chain = parse(factory, chainPem);+ String servedCa = given().when().get("/_floci/ca.pem").then().statusCode(200).extract().asString();++ assertEquals(servedCa.strip(), chainPem.strip(), "CertificateChain must be the local CA PEM");+ assertEquals(chain.getSubjectX500Principal(), leaf.getIssuerX500Principal());+ assertEquals(-1, leaf.getBasicConstraints(), "a leaf, not a CA");+ assertEquals(List.of("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.2"), leaf.getExtendedKeyUsage(),+ "serverAuth and clientAuth, as DescribeCertificate advertises");++ PKIXParameters params = new PKIXParameters(Set.of(new TrustAnchor(chain, null)));+ params.setRevocationEnabled(false);+ CertPathValidator.getInstance("PKIX").validate(factory.generateCertPath(List.of(leaf)), params);+ return leaf;+ }++ private static X509Certificate parse(CertificateFactory factory, String pem) throws Exception {+ return (X509Certificate) factory.generateCertificate(+ new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII)));+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmPaginationTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmPaginationTest.javaindex c5a8b5916d..69caab71b0 100644--- a/src/test/java/io/github/hectorvent/floci/services/acm/AcmPaginationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmPaginationTest.java@@ -91,7 +91,9 @@ class AcmPaginationTest {Set<String> allArns = new HashSet<>();String nextToken = null;int pageCount = 0;- int maxPages = 10; // Safety limit+ // Safety limit against a NextToken that never ends. The store is shared with every other ACM+ // test class in the JVM, so the real page count grows with the suite.+ int maxPages = 200;do {String body = nextToken == nulldiff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmRevokeCertificateGuardTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmRevokeCertificateGuardTest.javaindex 6cd51e7cc3..ad1cbaf3b2 100644--- a/src/test/java/io/github/hectorvent/floci/services/acm/AcmRevokeCertificateGuardTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmRevokeCertificateGuardTest.java@@ -27,7 +27,7 @@ class AcmRevokeCertificateGuardTest {@Testvoid revokeCertificateRejectsImportedCertificateWithoutExportEnabled() {- CertificateGenerator.GeneratedCertificate generated = certificateGenerator.generateCertificate(+ CertificateGenerator.GeneratedCertificate generated = certificateGenerator.generateSelfSignedCertificate("revoke-guard-imported.example.com", List.of(), KeyAlgorithm.RSA_2048);String certJson = generated.certificatePem().replace("\r\n", "\n").replace("\n", "\\n");String keyJson = generated.privateKeyPem().replace("\r\n", "\n").replace("\n", "\\n");diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/AcmServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/AcmServicePersistenceTest.javaindex f610ce64ca..af816a49af 100644--- a/src/test/java/io/github/hectorvent/floci/services/acm/AcmServicePersistenceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmServicePersistenceTest.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.acm;import com.fasterxml.jackson.core.type.TypeReference;+import io.github.hectorvent.floci.config.FlociCertificateAuthority;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.storage.PersistentStorage;import io.github.hectorvent.floci.core.storage.StorageBackend;@@ -19,6 +20,7 @@ import java.util.Map;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;@@ -63,6 +65,8 @@ class AcmServicePersistenceTest {assertEquals("example.com", loaded.getDomainName());assertEquals(List.of("example.com", "www.example.com"), loaded.getSubjectAlternativeNames());assertEquals("test", loaded.getTags().get("Env"));+ assertTrue(loaded.getCertificateChain().startsWith("-----BEGIN CERTIFICATE-----"), "the CA chain is persisted");+ assertEquals(cert.getCertificateChain(), loaded.getCertificateChain());}private AcmService newService(Path dir) {@@ -70,7 +74,8 @@ class AcmServicePersistenceTest {when(regionResolver.getAccountId()).thenReturn("000000000000");StorageBackend<String, Certificate> store = load(dir, "acm-certificates.json");- return new AcmService(store, generator, regionResolver, 0);+ return new AcmService(store, generator, FlociCertificateAuthority.loadOrCreate(dir.resolve("tls")),+ regionResolver, 0);}private StorageBackend<String, Certificate> load(Path dir, String file) {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.javanew file mode 100644index 0000000000..aea7e1aeaf--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/acm/AcmServiceTest.java@@ -0,0 +1,246 @@+package io.github.hectorvent.floci.services.acm;++import io.github.hectorvent.floci.config.FlociCertificateAuthority;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+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.KeyAlgorithm;+import io.github.hectorvent.floci.services.acm.model.ValidationMethod;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.EnumSource;++import java.math.BigInteger;+import java.nio.charset.StandardCharsets;+import java.nio.file.Path;+import java.security.cert.CertPathValidator;+import java.security.cert.CertificateFactory;+import java.security.cert.PKIXParameters;+import java.security.cert.TrustAnchor;+import java.security.cert.X509Certificate;+import java.security.interfaces.ECPublicKey;+import java.security.interfaces.RSAPublicKey;+import java.util.ArrayList;+import java.util.Base64;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;+import java.util.concurrent.TimeUnit;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * The issuance path of {@link AcmService} against a real local CA and no Quarkus: every+ * certificate the service issues chains to that CA, whatever the key algorithm, type or+ * validation state, and its metadata is read from the certificate rather than from the request.+ */+class AcmServiceTest {++ private static final String REGION = "us-east-1";+ private static final String PCA_ARN =+ "arn:aws:acm-pca:us-east-1:000000000000:certificate-authority/11111111-2222-3333-4444-555555555555";+ private static final List<String> SERVER_AND_CLIENT_AUTH = List.of("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.2");++ @TempDir+ Path tempDir;++ private FlociCertificateAuthority ca;+ private CertificateGenerator generator;+ private AcmService service;++ @BeforeEach+ void setUp() {+ ca = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls"));+ generator = new CertificateGenerator();+ service = newService(0);+ }++ private AcmService newService(int validationWaitSeconds) {+ RegionResolver regionResolver = mock(RegionResolver.class);+ when(regionResolver.getAccountId()).thenReturn("000000000000");+ return new AcmService(new InMemoryStorage<>(), generator, ca, regionResolver, validationWaitSeconds);+ }++ @ParameterizedTest+ @EnumSource(KeyAlgorithm.class)+ void issuesALeafOfTheRequestedAlgorithmSignedByTheLocalCa(KeyAlgorithm algorithm) throws Exception {+ Certificate cert = service.requestCertificate("api.example.test", List.of("*.example.test"),+ ValidationMethod.DNS, null, algorithm, null, null, Map.of(), REGION);++ X509Certificate leaf = assertChainsToTheCa(cert);+ assertEquals(CertificateType.AMAZON_ISSUED, cert.getType());+ assertEquals(CertificateStatus.ISSUED, cert.getStatus());+ assertEquals(algorithm, cert.getKeyAlgorithm());+ assertEquals(algorithm.getAlgorithm(), leaf.getPublicKey().getAlgorithm());+ if (leaf.getPublicKey() instanceof RSAPublicKey rsa) {+ assertEquals(algorithm.getKeySize(), rsa.getModulus().bitLength());+ } else {+ assertEquals(algorithm.getKeySize(),+ ((ECPublicKey) leaf.getPublicKey()).getParams().getCurve().getField().getFieldSize());+ }+ assertEquals(List.of("api.example.test", "*.example.test"), cert.getSubjectAlternativeNames());+ assertEquals(List.of("api.example.test", "*.example.test"),+ leaf.getSubjectAlternativeNames().stream().map(san -> san.get(1)).toList());+ }++ @Test+ void privateCertificateChainsToTheSameCaAndIsIssuedAtOnce() throws Exception {+ Certificate cert = newService(30).requestCertificate("internal.example.test", null, ValidationMethod.DNS,+ null, null, PCA_ARN, null, null, REGION);++ assertChainsToTheCa(cert);+ assertEquals(CertificateType.PRIVATE, cert.getType());+ assertEquals(CertificateStatus.ISSUED, cert.getStatus(), "a private certificate waits for no validation");+ assertEquals(KeyAlgorithm.RSA_2048, cert.getKeyAlgorithm(), "the default algorithm");+ assertEquals(List.of("SUCCESS"),+ cert.getDomainValidationOptions().stream().map(DomainValidation::validationStatus).toList());+ }++ @Test+ void pendingValidationCertificateAlreadyHoldsItsLeafAndChain() throws Exception {+ Certificate cert = newService(30).requestCertificate("pending.example.test", List.of(),+ ValidationMethod.EMAIL, null, KeyAlgorithm.RSA_2048, null, null, null, REGION);++ assertEquals(CertificateStatus.PENDING_VALIDATION, cert.getStatus());+ assertNull(cert.getIssuedAt());+ assertChainsToTheCa(cert);+ }++ @Test+ void anIdempotentReplayReturnsTheSameCertificateInsteadOfIssuingAnother() {+ Certificate first = service.requestCertificate("same.example.test", List.of(), ValidationMethod.DNS,+ "token-1", KeyAlgorithm.RSA_2048, null, null, null, REGION);++ Certificate replay = service.requestCertificate("same.example.test", List.of(), ValidationMethod.DNS,+ "token-1", KeyAlgorithm.RSA_2048, null, null, null, REGION);++ assertEquals(first.getArn(), replay.getArn());+ assertEquals(first.getCertificateBody(), replay.getCertificateBody(), "no second leaf is minted");+ assertEquals(1, service.listCertificates(null, null, REGION, 100, null).certificates().size());+ AwsException refused = assertThrows(AwsException.class, () -> service.requestCertificate(+ "same.example.test", List.of(), ValidationMethod.DNS, "token-1", KeyAlgorithm.EC_prime256v1,+ null, null, null, REGION));+ assertEquals("IdempotencyException", refused.getErrorCode());+ }++ @Test+ void anImportKeepsTheUploadedChainAndAnImportWithoutOneHasNone() {+ FlociCertificateAuthority otherCa = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("other-ca"));+ CertificateGenerator.GeneratedCertificate leaf = otherCa.issueServerCertificate(+ "imported.example.test", List.of(), KeyAlgorithm.RSA_2048, null);++ Certificate withChain = service.importCertificate(leaf.certificatePem(), leaf.privateKeyPem(),+ otherCa.caPem(), null, null, REGION);+ Certificate withoutChain = service.importCertificate(leaf.certificatePem(), leaf.privateKeyPem(),+ null, null, null, REGION);++ assertEquals(CertificateType.IMPORTED, withChain.getType());+ assertEquals(otherCa.caPem(), withChain.getCertificateChain(), "an import keeps the chain it was given");+ assertEquals(otherCa.certificate().getSubjectX500Principal().getName(), withChain.getIssuer());+ assertEquals(leaf.certificatePem(), withChain.getCertificateBody());+ assertNull(withoutChain.getCertificateChain());+ }++ @Test+ void exportReturnsTheStoredChainForPrivateAndForExportEnabledPublicCertificates() {+ String passphrase = Base64.getEncoder().encodeToString("abcd1234".getBytes(StandardCharsets.US_ASCII));+ Certificate privateCert = service.requestCertificate("export-private.example.test", null,+ ValidationMethod.DNS, null, null, PCA_ARN, null, null, REGION);+ Certificate publicCert = service.requestCertificate("export-public.example.test", null,+ ValidationMethod.DNS, null, null, null, new CertificateOptions(null, "ENABLED"), null, REGION);+ Certificate ecCert = service.requestCertificate("export-ec.example.test", null, ValidationMethod.DNS, null,+ KeyAlgorithm.EC_prime256v1, PCA_ARN, null, null, REGION);++ Certificate exportedPrivate = service.exportCertificate(privateCert.getArn(), passphrase, REGION);+ Certificate exportedPublic = service.exportCertificate(publicCert.getArn(), passphrase, REGION);+ Certificate exportedEc = service.exportCertificate(ecCert.getArn(), passphrase, REGION);++ assertEquals(privateCert.getCertificateBody(), exportedPrivate.getCertificateBody());+ assertEquals(ca.caPem(), exportedPrivate.getCertificateChain());+ assertEquals(ca.caPem(), exportedPublic.getCertificateChain());+ assertEquals(ca.caPem(), exportedEc.getCertificateChain());+ assertTrue(exportedPrivate.getPrivateKey().startsWith("-----BEGIN ENCRYPTED PRIVATE KEY-----"));+ assertTrue(exportedEc.getPrivateKey().startsWith("-----BEGIN ENCRYPTED PRIVATE KEY-----"),+ "an EC private key is exportable too");+ }++ @Test+ void concurrentRequestsEachGetTheirOwnCertificateChainedToTheCa() throws Exception {+ int threads = 16;+ ExecutorService pool = Executors.newFixedThreadPool(threads);+ CountDownLatch start = new CountDownLatch(1);+ List<Future<Certificate>> futures = new ArrayList<>();+ try {+ for (int i = 0; i < threads; i++) {+ String domain = "burst-" + i + ".example.test";+ futures.add(pool.submit(() -> {+ start.await();+ return service.requestCertificate(domain, List.of(), ValidationMethod.DNS, null,+ KeyAlgorithm.RSA_2048, null, null, null, REGION);+ }));+ }+ start.countDown();++ Set<String> arns = new HashSet<>();+ Set<String> serials = new HashSet<>();+ for (Future<Certificate> future : futures) {+ Certificate cert = future.get(60, TimeUnit.SECONDS);+ assertChainsToTheCa(cert);+ arns.add(cert.getArn());+ serials.add(cert.getSerial());+ }+ assertEquals(threads, arns.size(), "every request gets its own ARN");+ assertEquals(threads, serials.size(), "every leaf gets its own serial");+ assertEquals(threads, service.listCertificates(null, null, REGION, 100, null).certificates().size());+ } finally {+ pool.shutdownNow();+ }+ }++ /**+ * The certificate is a server leaf issued by the CA, the chain is exactly the CA's PEM, the pair+ * builds a PKIX path with that chain as the only trust anchor, the stored private key belongs to+ * the leaf, and every metadata field equals what the certificate itself says.+ */+ private X509Certificate assertChainsToTheCa(Certificate cert) throws Exception {+ X509Certificate leaf = generator.parseCertificate(cert.getCertificateBody());+ assertEquals(ca.caPem(), cert.getCertificateChain(), "CertificateChain is the CA PEM");+ assertEquals(ca.certificate().getSubjectX500Principal(), leaf.getIssuerX500Principal());+ assertTrue(ca.isIssuedByUs(leaf), "signed by the CA key");+ assertEquals(-1, leaf.getBasicConstraints(), "a leaf, not a CA");+ assertEquals(SERVER_AND_CLIENT_AUTH, leaf.getExtendedKeyUsage());++ X509Certificate anchor = generator.parseCertificate(cert.getCertificateChain());+ PKIXParameters params = new PKIXParameters(Set.of(new TrustAnchor(anchor, null)));+ params.setRevocationEnabled(false);+ CertPathValidator.getInstance("PKIX").validate(+ CertificateFactory.getInstance("X.509").generateCertPath(List.of(leaf)), params);++ assertTrue(CertificateGenerator.isPair(generator.parsePrivateKey(cert.getPrivateKey()), leaf.getPublicKey()),+ "the stored private key matches the certificate");+ assertEquals(leaf.getSubjectX500Principal().getName(), cert.getSubject());+ assertEquals(ca.certificate().getSubjectX500Principal().getName(), cert.getIssuer());+ assertEquals(leaf.getSerialNumber(), new BigInteger(cert.getSerial().replace(":", ""), 16));+ assertEquals(leaf.getNotBefore().toInstant(), cert.getNotBefore());+ assertEquals(leaf.getNotAfter().toInstant(), cert.getNotAfter());+ assertEquals("SHA512WITHRSA", cert.getSignatureAlgorithm(), "the RSA CA's signature, whatever the leaf key");+ return leaf;+ }+}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.javaindex 6576fba7d6..1db19d77ea 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@@ -193,20 +193,28 @@ class CertificateGeneratorIssuerTest {}@Test- void existingSelfSignedAndAcmStylePathsAreUnchanged() throws Exception {+ void existingSelfSignedPathIsUnchanged() throws Exception {var 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);assertNull(ss.getExtendedKeyUsage(), "the self-signed trust anchor carries no EKU, as before");+ assertEquals(selfSigned.subject(), selfSigned.issuer());+ assertTrue(selfSigned.serial().matches("([0-9a-f]{2}:)+[0-9a-f]{2}"));ss.verify(ss.getPublicKey());+ }- var acmStyle = generator.generateCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);- X509Certificate acm = generator.parseCertificate(acmStyle.certificatePem());- assertTrue(acm.getIssuerX500Principal().getName().contains("Amazon"));- assertEquals(-1, acm.getBasicConstraints());- assertEquals("CN=Amazon,OU=Server CA 1B,O=Amazon,C=US", acmStyle.issuer());- assertTrue(acmStyle.serial().matches("([0-9a-f]{2}:)+[0-9a-f]{2}"));+ @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);++ 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");+ assertTrue(CertificateGenerator.isPair(generator.parsePrivateKey(ec.privateKeyPem()),+ generator.parseCertificate(ec.certificatePem()).getPublicKey()), "the EC key reads back and matches");}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSanTypeTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSanTypeTest.javaindex b6702cb7a3..2b1df09451 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@@ -37,7 +37,7 @@ class CertificateGeneratorSanTypeTest {@Testvoid ipv4AddressEncodedAsIpAddressSanType() throws Exception {- var cert = generator.generateCertificate(+ var cert = generator.generateSelfSignedCertificate("localhost",List.of("localhost", "192.168.1.100"),KeyAlgorithm.RSA_2048);@@ -56,7 +56,7 @@ class CertificateGeneratorSanTypeTest {@Testvoid ipv6LoopbackEncodedAsIpAddressSanType() throws Exception {- var cert = generator.generateCertificate(+ var cert = generator.generateSelfSignedCertificate("localhost",List.of("localhost", "0.0.0.0", "::1"),KeyAlgorithm.RSA_2048);@@ -81,7 +81,7 @@ class CertificateGeneratorSanTypeTest {@Testvoid dnsNamesEncodedAsDnsNameSanType() throws Exception {- var cert = generator.generateCertificate(+ var cert = generator.generateSelfSignedCertificate("localhost",List.of("myhost.example.com", "floci"),KeyAlgorithm.RSA_2048);@@ -106,7 +106,7 @@ class CertificateGeneratorSanTypeTest {@Testvoid wildcardEncodedAsDnsNameSanType() throws Exception {- var cert = generator.generateCertificate(+ var cert = generator.generateSelfSignedCertificate("localhost",List.of("localhost", "*.localhost"),KeyAlgorithm.RSA_2048);@@ -123,7 +123,7 @@ class CertificateGeneratorSanTypeTest {@Testvoid mixedIpsAndDnsNamesEncodedCorrectly() throws Exception {- var cert = generator.generateCertificate(+ var cert = generator.generateSelfSignedCertificate("localhost",List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost", "floci", "10.0.0.5"),KeyAlgorithm.RSA_2048);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.javaindex f35677acf2..07ee42c845 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@@ -10,18 +10,12 @@ import java.security.cert.X509Certificate;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.assertTrue;/**- * Verifies the distinction between the two certificate flavors:- * <ul>- * <li>{@code generateCertificate} mimics an ACM-issued cert (cosmetic Amazon issuer, not a CA)- * — unchanged legacy behavior, not verifiable as a trust anchor.</li>- * <li>{@code generateSelfSignedCertificate} is genuinely self-signed (issuer == subject) and a- * CA, so a client that trusts it can verify a TLS connection presenting it. This is what- * lets Floci's HTTPS endpoint be trusted by Lambda containers (CDK cfn-response callbacks).</li>- * </ul>+ * {@code generateSelfSignedCertificate} is genuinely self-signed (issuer == subject) and a CA, so+ * a client that trusts it can verify a TLS connection presenting it. Leaves that clients must+ * validate are issued by a CA through {@code generateIssuedCertificate} instead.*/class CertificateGeneratorSelfSignedTest {@@ -51,18 +45,4 @@ class CertificateGeneratorSelfSignedTest {// Sanity: the self-signature verifies against the cert's own public key.cert.verify(cert.getPublicKey());}-- @Test- void acmStyleCertificateKeepsCosmeticAmazonIssuerAndIsNotACa() throws Exception {- var generated = generator.generateCertificate(- "localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);-- X509Certificate cert = generator.parseCertificate(generated.certificatePem());-- assertNotEquals(cert.getSubjectX500Principal(), cert.getIssuerX500Principal(),- "ACM-style cert keeps a cosmetic Amazon issuer distinct from the subject");- assertTrue(cert.getIssuerX500Principal().getName().contains("Amazon"),- "ACM-style issuer should still be the Amazon CA DN");- assertEquals(-1, cert.getBasicConstraints(), "ACM-style leaf cert must not be a CA");- }}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDomainEnsureHostIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDomainEnsureHostIntegrationTest.javanew file mode 100644index 0000000000..72df98cd15--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDomainEnsureHostIntegrationTest.java@@ -0,0 +1,69 @@+package io.github.hectorvent.floci.services.apigateway;++import io.github.hectorvent.floci.config.TlsCertificateManager;+import io.quarkus.test.InjectMock;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;++/**+ * CreateDomainName hands the new hostname to the TLS certificate manager on the real wire path,+ * so a client that verifies the domain's name over HTTPS is served without a restart. The+ * manager is mocked: what it does with the name is its own test's business.+ */+@QuarkusTest+class ApiGatewayDomainEnsureHostIntegrationTest {++ @InjectMock+ TlsCertificateManager certificateManager;++ @Test+ void regionalDomainRegistersTheHostnameForTls() {+ String domain = "api-" + System.nanoTime() + ".dev.localhost.floci.io";++ given()+ .contentType(ContentType.JSON)+ .body("{\"domainName\":\"" + domain + "\","+ + "\"regionalCertificateArn\":\"arn:aws:acm:us-east-1:000000000000:certificate/abc\","+ + "\"endpointConfiguration\":{\"types\":[\"REGIONAL\"]}}")+ .when().post("/domainnames")+ .then()+ .statusCode(201);++ verify(certificateManager).ensureHost(domain);+ }++ @Test+ void edgeDomainRegistersTheHostnameForTls() {+ String domain = "edge-" + System.nanoTime() + ".dev.localhost.floci.io";++ given()+ .contentType(ContentType.JSON)+ .body("{\"domainName\":\"" + domain + "\","+ + "\"certificateArn\":\"arn:aws:acm:us-east-1:000000000000:certificate/abc\","+ + "\"endpointConfiguration\":{\"types\":[\"EDGE\"]}}")+ .when().post("/domainnames")+ .then()+ .statusCode(201);++ verify(certificateManager).ensureHost(domain);+ }++ @Test+ void rejectedCreateRegistersNothing() {+ given()+ .contentType(ContentType.JSON)+ .body("{\"domainName\":\"private-" + System.nanoTime() + ".dev.localhost.floci.io\","+ + "\"endpointConfiguration\":{\"types\":[\"PRIVATE\"]}}")+ .when().post("/domainnames")+ .then()+ .statusCode(400);++ verify(certificateManager, never()).ensureHost(anyString());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDomainTlsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDomainTlsServiceTest.javanew file mode 100644index 0000000000..03c7e56f66--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDomainTlsServiceTest.java@@ -0,0 +1,148 @@+package io.github.hectorvent.floci.services.apigateway;++import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.config.TlsCertificateManager;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Map;+import java.util.concurrent.atomic.AtomicBoolean;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.doAnswer;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.verifyNoMoreInteractions;+import static org.mockito.Mockito.when;++/**+ * The contract between CreateDomainName and the TLS certificate manager: the exact domain name+ * is handed over once, after the domain is stored and with no service lock held, and never for a+ * request AWS would reject. Later operations on the domain do not register anything again.+ */+class ApiGatewayDomainTlsServiceTest {++ private static final String REGION = "us-east-1";+ private static final String CERTIFICATE_ARN = "arn:aws:acm:us-east-1:000000000000:certificate/abc";++ private TlsCertificateManager certificateManager;+ private ApiGatewayService service;++ @BeforeEach+ void setUp() {+ StorageFactory storageFactory = mock(StorageFactory.class);+ when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));+ certificateManager = mock(TlsCertificateManager.class);+ service = new ApiGatewayService(storageFactory, mock(EmulatorConfig.class), certificateManager);+ }++ private static Map<String, Object> regional(String domain) {+ return Map.of("domainName", domain, "regionalCertificateArn", CERTIFICATE_ARN,+ "endpointConfiguration", Map.of("types", List.of("REGIONAL")));+ }++ @Test+ void createHandsTheExactDomainNameOverOnce() {+ service.createDomainName(REGION, regional("api.dev.localhost.floci.io"));++ verify(certificateManager).ensureHost("api.dev.localhost.floci.io");+ verifyNoMoreInteractions(certificateManager);+ }++ @Test+ void wildcardDomainIsHandedOverAsApiGatewaySpellsIt() {+ service.createDomainName(REGION, regional("*.dev.localhost.floci.io"));++ verify(certificateManager).ensureHost("*.dev.localhost.floci.io");+ }++ @Test+ void edgeDomainIsHandedOverToo() {+ service.createDomainName(REGION, Map.of("domainName", "edge.dev.localhost.floci.io",+ "certificateArn", CERTIFICATE_ARN, "endpointConfiguration", Map.of("types", List.of("EDGE"))));++ verify(certificateManager).ensureHost("edge.dev.localhost.floci.io");+ }++ @Test+ void domainIsStoredBeforeTheCertificateIsExtended() {+ doAnswer(invocation -> {+ assertNotNull(service.getDomainName(REGION, "api.dev.localhost.floci.io"),+ "GetDomainName must already find the domain while the certificate reloads");+ return null;+ }).when(certificateManager).ensureHost(anyString());++ service.createDomainName(REGION, regional("api.dev.localhost.floci.io"));++ verify(certificateManager).ensureHost("api.dev.localhost.floci.io");+ }++ @Test+ void duplicateNameIsRejectedBeforeTheHook() {+ service.createDomainName(REGION, regional("api.dev.localhost.floci.io"));++ AwsException failure = assertThrows(AwsException.class,+ () -> service.createDomainName("eu-west-1", regional("api.dev.localhost.floci.io")));++ assertEquals("BadRequestException", failure.getErrorCode());+ verify(certificateManager).ensureHost("api.dev.localhost.floci.io");+ verifyNoMoreInteractions(certificateManager);+ }++ @Test+ void privateEndpointTypeIsRejectedBeforeTheHook() {+ assertThrows(AwsException.class, () -> service.createDomainName(REGION, Map.of(+ "domainName", "private.dev.localhost.floci.io",+ "endpointConfiguration", Map.of("types", List.of("PRIVATE")))));++ verifyNoInteractions(certificateManager);+ }++ @Test+ void laterOperationsOnTheDomainRegisterNothingAgain() {+ service.createDomainName(REGION, regional("api.dev.localhost.floci.io"));++ service.updateDomainName(REGION, "api.dev.localhost.floci.io",+ List.of(Map.of("op", "replace", "path", "/securityPolicy", "value", "TLS_1_0")));+ service.getDomainName(REGION, "api.dev.localhost.floci.io");+ service.deleteDomainName(REGION, "api.dev.localhost.floci.io");++ verify(certificateManager).ensureHost("api.dev.localhost.floci.io");+ verifyNoMoreInteractions(certificateManager);+ }++ /**+ * The reissue blocks until the HTTPS listener has switched certificates. A second create that+ * arrives meanwhile must not queue behind it, so the hook runs outside the uniqueness lock.+ */+ @Test+ void noServiceLockIsHeldWhileTheCertificateReloads() throws Exception {+ AtomicBoolean nested = new AtomicBoolean();+ Thread[] concurrent = new Thread[1];+ doAnswer(invocation -> {+ if (nested.compareAndSet(false, true)) {+ concurrent[0] = new Thread(() -> service.createDomainName(REGION, regional("other.dev.localhost.floci.io")));+ concurrent[0].start();+ concurrent[0].join(5000);+ assertFalse(concurrent[0].isAlive(), "a create must not wait for another create's TLS reload");+ }+ return null;+ }).when(certificateManager).ensureHost(anyString());++ service.createDomainName(REGION, regional("api.dev.localhost.floci.io"));++ verify(certificateManager).ensureHost("api.dev.localhost.floci.io");+ verify(certificateManager).ensureHost("other.dev.localhost.floci.io");+ assertNotNull(service.getDomainName(REGION, "other.dev.localhost.floci.io"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCustomDomainEnsureHostIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCustomDomainEnsureHostIntegrationTest.javanew file mode 100644index 0000000000..fd259b39e6--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCustomDomainEnsureHostIntegrationTest.java@@ -0,0 +1,170 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.github.hectorvent.floci.config.TlsCertificateManager;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.InjectMock;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.specification.RequestSpecification;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.fail;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoMoreInteractions;++/**+ * A stack that creates the three custom domain types hands every domain to the TLS certificate+ * manager through the same service methods the API uses. A rename replaces the domain, so the+ * new name is registered too; an in-place update and the stack delete register nothing.+ */+@QuarkusTest+class CfnCustomDomainEnsureHostIntegrationTest {++ private static final String CFN_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";+ private static final String STACK = "custom-domain-ensure-host-cfn-it";+ private static final String SUFFIX = ".ensure-host-cfn-it.localhost.floci.io";+ private static final String API_DOMAIN = "api" + SUFFIX;+ private static final String RENAMED_API_DOMAIN = "gateway" + SUFFIX;+ private static final String IOT_DOMAIN = "iot" + SUFFIX;+ private static final String AUTH_DOMAIN = "auth" + SUFFIX;++ private static final String TEMPLATE = """+ {+ "Parameters": {+ "ApiDomainName": {"Type": "String"},+ "IotStatus": {"Type": "String", "Default": "ENABLED"}+ },+ "Resources": {+ "Cert": {+ "Type": "AWS::CertificateManager::Certificate",+ "Properties": {"DomainName": "*%1$s", "ValidationMethod": "DNS"}+ },+ "ApiDomain": {+ "Type": "AWS::ApiGateway::DomainName",+ "Properties": {+ "DomainName": {"Ref": "ApiDomainName"},+ "EndpointConfiguration": {"Types": ["REGIONAL"]},+ "RegionalCertificateArn": {"Ref": "Cert"}+ }+ },+ "IotDomain": {+ "Type": "AWS::IoT::DomainConfiguration",+ "Properties": {+ "DomainConfigurationName": "ensure-host-cfn-it",+ "DomainName": "%2$s",+ "ServerCertificateArns": [{"Ref": "Cert"}],+ "DomainConfigurationStatus": {"Ref": "IotStatus"}+ }+ },+ "Pool": {+ "Type": "AWS::Cognito::UserPool",+ "Properties": {"UserPoolName": "ensure-host-cfn-it-pool"}+ },+ "AuthDomain": {+ "Type": "AWS::Cognito::UserPoolDomain",+ "Properties": {+ "Domain": "%3$s",+ "UserPoolId": {"Ref": "Pool"},+ "CustomDomainConfig": {"CertificateArn": {"Fn::GetAtt": ["Cert", "CertificateArn"]}}+ }+ }+ }+ }+ """.formatted(SUFFIX, IOT_DOMAIN, AUTH_DOMAIN);++ @InjectMock+ TlsCertificateManager certificateManager;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void stackRegistersEveryCustomDomainAndAReplacementButNotAnInPlaceUpdateOrTheDelete() throws Exception {+ cloudFormation("CreateStack", Map.of("ApiDomainName", API_DOMAIN));+ awaitStackStatus("CREATE_COMPLETE");++ verify(certificateManager).ensureHost(API_DOMAIN);+ verify(certificateManager).ensureHost(IOT_DOMAIN);+ verify(certificateManager).ensureHost(AUTH_DOMAIN);+ verifyNoMoreInteractions(certificateManager);++ cloudFormation("UpdateStack", Map.of("ApiDomainName", API_DOMAIN, "IotStatus", "DISABLED"));+ awaitStackStatus("UPDATE_COMPLETE");++ verifyNoMoreInteractions(certificateManager);++ cloudFormation("UpdateStack", Map.of("ApiDomainName", RENAMED_API_DOMAIN, "IotStatus", "DISABLED"));+ awaitStackStatus("UPDATE_COMPLETE");++ verify(certificateManager).ensureHost(RENAMED_API_DOMAIN);+ verifyNoMoreInteractions(certificateManager);++ cloudFormation("DeleteStack", Map.of());+ awaitStackDeleted();++ verifyNoMoreInteractions(certificateManager);+ }++ private static void cloudFormation(String action, Map<String, String> parameters) {+ RequestSpecification request = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", action)+ .formParam("StackName", STACK);+ if (!"DeleteStack".equals(action)) {+ request.formParam("TemplateBody", TEMPLATE);+ }+ int index = 1;+ for (Map.Entry<String, String> parameter : parameters.entrySet()) {+ request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());+ request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());+ index++;+ }+ request.when().post("/").then().statusCode(200);+ }++ private static String describeStack() {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", STACK)+ .when().post("/").then().extract().asString();+ }++ /** Stack operations run on a background executor; wait for the terminal status. */+ private static void awaitStackStatus(String expected) throws InterruptedException {+ String body = "";+ for (int i = 0; i < 200; i++) {+ body = describeStack();+ if (body.contains("<StackStatus>" + expected + "</StackStatus>")) {+ return;+ }+ if (body.contains("FAILED</StackStatus>") || body.contains("ROLLBACK_COMPLETE</StackStatus>")) {+ fail("stack did not reach " + expected + ": " + body);+ }+ Thread.sleep(50);+ }+ fail("stack did not reach " + expected + " within the timeout: " + body);+ }++ private static void awaitStackDeleted() throws InterruptedException {+ for (int i = 0; i < 200; i++) {+ String body = describeStack();+ if (body.contains("does not exist")) {+ return;+ }+ if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {+ fail("stack delete failed: " + body);+ }+ Thread.sleep(50);+ }+ fail("stack " + STACK + " was not deleted within the timeout");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoDomainEnsureHostIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoDomainEnsureHostIntegrationTest.javanew file mode 100644index 0000000000..5fcc82eaaf--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoDomainEnsureHostIntegrationTest.java@@ -0,0 +1,108 @@+package io.github.hectorvent.floci.services.cognito;++import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.config.TlsCertificateManager;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.InjectMock;+import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;++/**+ * CreateUserPoolDomain hands a custom domain to the TLS certificate manager on the real wire+ * path. A prefix domain lives under {@code auth.<region>.amazoncognito.com} on AWS, a name Floci+ * does not serve, so it is left alone. The certificate must be an issued ACM certificate, as on+ * AWS, so each custom domain requests one first.+ */+@QuarkusTest+class CognitoDomainEnsureHostIntegrationTest {++ private static final String UNKNOWN_CERTIFICATE_ARN =+ "arn:aws:acm:us-east-1:000000000000:certificate/00000000-0000-0000-0000-000000000000";++ @InjectMock+ TlsCertificateManager certificateManager;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void customDomainRegistersTheHostnameForTls() throws Exception {+ String poolId = createPool();+ String domain = "auth-" + System.nanoTime() + ".dev.localhost.floci.io";++ cognitoJson("CreateUserPoolDomain", """+ {+ "Domain": "%s",+ "UserPoolId": "%s",+ "CustomDomainConfig": {"CertificateArn": "%s"}+ }+ """.formatted(domain, poolId, requestCertificate(domain)));++ verify(certificateManager).ensureHost(domain);+ }++ @Test+ void certificateUnknownToAcmRegistersNothing() throws Exception {+ String poolId = createPool();++ cognitoAction("CreateUserPoolDomain", """+ {+ "Domain": "nocert-%s.dev.localhost.floci.io",+ "UserPoolId": "%s",+ "CustomDomainConfig": {"CertificateArn": "%s"}+ }+ """.formatted(System.nanoTime(), poolId, UNKNOWN_CERTIFICATE_ARN))+ .then()+ .statusCode(400);++ verify(certificateManager, never()).ensureHost(anyString());+ }++ @Test+ void prefixDomainRegistersNothing() throws Exception {+ String poolId = createPool();++ cognitoJson("CreateUserPoolDomain", """+ {+ "Domain": "prefix-%s",+ "UserPoolId": "%s"+ }+ """.formatted(System.nanoTime(), poolId));++ verify(certificateManager, never()).ensureHost(anyString());+ }++ @Test+ void rejectedCreateRegistersNothing() {+ cognitoAction("CreateUserPoolDomain", """+ {+ "Domain": "orphan-%s.dev.localhost.floci.io",+ "UserPoolId": "us-east-1_missing",+ "CustomDomainConfig": {"CertificateArn": "%s"}+ }+ """.formatted(System.nanoTime(), UNKNOWN_CERTIFICATE_ARN))+ .then()+ .statusCode(400);++ verify(certificateManager, never()).ensureHost(anyString());+ }++ private static String requestCertificate(String domain) throws Exception {+ return RestAssuredJsonUtils.awsActionJson("CertificateManager", "RequestCertificate",+ "{\"DomainName\": \"" + domain + "\", \"ValidationMethod\": \"DNS\"}").path("CertificateArn").asText();+ }++ private static String createPool() throws Exception {+ JsonNode pool = cognitoJson("CreateUserPool", "{\"PoolName\": \"EnsureHostPool\"}");+ return pool.path("UserPool").path("Id").asText();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoDomainTlsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoDomainTlsServiceTest.javanew file mode 100644index 0000000000..25272d05ea--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoDomainTlsServiceTest.java@@ -0,0 +1,203 @@+package io.github.hectorvent.floci.services.cognito;++import io.github.hectorvent.floci.config.TlsCertificateManager;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import io.github.hectorvent.floci.services.acm.AcmService;+import io.github.hectorvent.floci.services.acm.model.Certificate;+import io.github.hectorvent.floci.services.acm.model.CertificateStatus;+import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.HashMap;+import java.util.Map;+import java.util.concurrent.atomic.AtomicBoolean;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doAnswer;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.verifyNoMoreInteractions;+import static org.mockito.Mockito.when;++/**+ * The contract between CreateUserPoolDomain and the TLS certificate manager: a custom domain is+ * handed over once, after it is stored and with no service lock held; a prefix domain, a rejected+ * request and every later operation register nothing. The test-only constructor without a manager keeps working. A+ * certificate ACM does not know, or has not issued, is refused before the hook, as on AWS.+ */+class CognitoDomainTlsServiceTest {++ private static final String REGION = "us-east-1";+ private static final String CERTIFICATE_ARN = "arn:aws:acm:us-east-1:000000000000:certificate/abc";+ private static final Map<String, Object> CUSTOM = Map.of("CertificateArn", CERTIFICATE_ARN);++ private final RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");+ private final TlsCertificateManager certificateManager = mock(TlsCertificateManager.class);+ private final AcmService acmService = mock(AcmService.class);+ private CognitoService service;+ private String poolId;++ @BeforeEach+ void setUp() {+ // Every certificate exists and is issued unless a test says otherwise.+ when(acmService.describeCertificate(anyString(), eq(REGION))).thenAnswer(invocation -> {+ Certificate certificate = new Certificate();+ certificate.setArn(invocation.getArgument(0));+ certificate.setStatus(CertificateStatus.ISSUED);+ return certificate;+ });+ service = new CognitoService(+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ "http://localhost:4566", regionResolver, null, acmService, null, null, certificateManager);+ poolId = service.createUserPool(Map.of("PoolName", "tls-pool"), REGION).getId();+ }++ @Test+ void customDomainIsHandedOverOnce() {+ UserPoolDomain created = service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null);++ assertTrue(created.isCustomDomain());+ verify(certificateManager).ensureHost("auth.dev.localhost.floci.io");+ verifyNoMoreInteractions(certificateManager);+ }++ @Test+ void prefixDomainRegistersNothing() {+ service.createUserPoolDomain("my-prefix", poolId, null, null);++ verifyNoInteractions(certificateManager);+ }++ @Test+ void customDomainWithoutACertificateIsRejectedBeforeTheHook() {+ Map<String, Object> noCertificate = new HashMap<>();+ noCertificate.put("CertificateArn", null);++ AwsException failure = assertThrows(AwsException.class,+ () -> service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, noCertificate, null));++ assertEquals("InvalidParameterException", failure.getErrorCode());+ verifyNoInteractions(certificateManager);+ }++ @Test+ void certificateUnknownToAcmIsRejectedBeforeTheHook() {+ when(acmService.describeCertificate(anyString(), eq(REGION)))+ .thenThrow(new AwsException("ResourceNotFoundException", "no such certificate", 400));++ AwsException failure = assertThrows(AwsException.class,+ () -> service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null));++ assertEquals("InvalidParameterException", failure.getErrorCode());+ verifyNoInteractions(certificateManager);+ }++ @Test+ void certificateNotYetIssuedIsRejectedBeforeTheHook() {+ when(acmService.describeCertificate(anyString(), eq(REGION))).thenAnswer(invocation -> {+ Certificate pending = new Certificate();+ pending.setArn(invocation.getArgument(0));+ pending.setStatus(CertificateStatus.PENDING_VALIDATION);+ return pending;+ });++ assertThrows(AwsException.class,+ () -> service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null));++ verifyNoInteractions(certificateManager);+ }++ @Test+ void unknownPoolIsRejectedBeforeTheHook() {+ assertThrows(AwsException.class,+ () -> service.createUserPoolDomain("auth.dev.localhost.floci.io", "us-east-1_missing", CUSTOM, null));++ verifyNoInteractions(certificateManager);+ }++ @Test+ void duplicateDomainIsRejectedBeforeTheHook() {+ service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null);+ String otherPool = service.createUserPool(Map.of("PoolName", "other-pool"), REGION).getId();++ AwsException failure = assertThrows(AwsException.class,+ () -> service.createUserPoolDomain("auth.dev.localhost.floci.io", otherPool, CUSTOM, null));++ assertEquals("InvalidParameterException", failure.getErrorCode());+ verify(certificateManager).ensureHost("auth.dev.localhost.floci.io");+ verifyNoMoreInteractions(certificateManager);+ }++ @Test+ void domainIsStoredBeforeTheCertificateIsExtended() {+ doAnswer(invocation -> {+ assertNotNull(service.describeUserPoolDomain("auth.dev.localhost.floci.io"),+ "DescribeUserPoolDomain must already find the domain while the certificate reloads");+ return null;+ }).when(certificateManager).ensureHost(anyString());++ service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null);++ verify(certificateManager).ensureHost("auth.dev.localhost.floci.io");+ }++ @Test+ void laterOperationsOnTheDomainRegisterNothingAgain() {+ service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null);++ service.updateUserPoolDomain("auth.dev.localhost.floci.io", poolId,+ Map.of("CertificateArn", CERTIFICATE_ARN + "-renewed"), 2);+ service.describeUserPoolDomain("auth.dev.localhost.floci.io");+ service.deleteUserPoolDomain("auth.dev.localhost.floci.io", poolId);++ verify(certificateManager).ensureHost("auth.dev.localhost.floci.io");+ verifyNoMoreInteractions(certificateManager);+ }++ /** The reissue blocks on the HTTPS listener; a concurrent create must not queue behind it. */+ @Test+ void noServiceLockIsHeldWhileTheCertificateReloads() throws Exception {+ String otherPool = service.createUserPool(Map.of("PoolName", "other-pool"), REGION).getId();+ AtomicBoolean nested = new AtomicBoolean();+ Thread[] concurrent = new Thread[1];+ doAnswer(invocation -> {+ if (nested.compareAndSet(false, true)) {+ concurrent[0] = new Thread(() -> service.createUserPoolDomain("other.dev.localhost.floci.io", otherPool, CUSTOM, null));+ concurrent[0].start();+ concurrent[0].join(5000);+ assertFalse(concurrent[0].isAlive(), "a create must not wait for another create's TLS reload");+ }+ return null;+ }).when(certificateManager).ensureHost(anyString());++ service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null);++ verify(certificateManager).ensureHost("auth.dev.localhost.floci.io");+ verify(certificateManager).ensureHost("other.dev.localhost.floci.io");+ assertNotNull(service.describeUserPoolDomain("other.dev.localhost.floci.io"));+ }++ @Test+ void constructorWithoutAManagerStillCreatesCustomDomains() {+ CognitoService bare = new CognitoService(+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),+ new InMemoryStorage<>(), new InMemoryStorage<>(), "http://localhost:4566", regionResolver, null, acmService);+ String pool = bare.createUserPool(Map.of("PoolName", "bare-pool"), REGION).getId();++ UserPoolDomain created = bare.createUserPoolDomain("auth.dev.localhost.floci.io", pool, CUSTOM, null);++ assertTrue(created.isCustomDomain());+ assertNotNull(created.getCloudFrontDistribution());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.javaindex ae763ae448..d98410fde4 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cognito;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.config.TlsCertificateManager;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.common.ReservedTags;@@ -1410,7 +1411,8 @@ class CognitoServiceTest {null,acmService,verificationCodeService,- messageDispatcher+ messageDispatcher,+ mock(TlsCertificateManager.class));UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");@@ -1450,7 +1452,8 @@ class CognitoServiceTest {null,acmService,verificationCodeService,- messageDispatcher+ messageDispatcher,+ mock(TlsCertificateManager.class));UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");@@ -2921,7 +2924,8 @@ class CognitoServiceTest {null,acmService,verificationCodeService,- messageDispatcher+ messageDispatcher,+ mock(TlsCertificateManager.class));}}@@ -3508,7 +3512,7 @@ class CognitoServiceTest {CognitoService ambiguous = new CognitoService(new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), domains, new InMemoryStorage<>(), new InMemoryStorage<>(),new InMemoryStorage<>(), new InMemoryStorage<>(), "http://localhost:4566", regionResolver, null,- acmService, null, null);+ acmService, null, null, mock(TlsCertificateManager.class));assertTrue(ambiguous.findCustomDomain("auth.dup.localhost.floci.io").isEmpty());}diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationEnsureHostIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationEnsureHostIntegrationTest.javanew file mode 100644index 0000000000..1a75703e2a--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationEnsureHostIntegrationTest.java@@ -0,0 +1,76 @@+package io.github.hectorvent.floci.services.iot;++import io.github.hectorvent.floci.config.TlsCertificateManager;+import io.quarkus.test.InjectMock;+import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;++/**+ * CreateDomainConfiguration hands a customer-managed domain name to the TLS certificate manager+ * on the real wire path. A configuration without a domain name describes the account's default+ * endpoint, which Floci already serves, so nothing is registered for it.+ */+@QuarkusTest+class IotDomainConfigurationEnsureHostIntegrationTest {++ private static final String CERTIFICATE_ARN =+ "arn:aws:acm:us-east-1:000000000000:certificate/11111111-1111-1111-1111-111111111111";++ @InjectMock+ TlsCertificateManager certificateManager;++ @Test+ void customerManagedDomainRegistersTheHostnameForTls() {+ String domain = "iot-" + System.nanoTime() + ".dev.localhost.floci.io";++ given()+ .contentType("application/json")+ .body("""+ {+ "domainName": "%s",+ "serverCertificateArns": ["%s"]+ }+ """.formatted(domain, CERTIFICATE_ARN))+ .when()+ .post("/domainConfigurations/ensure-host-" + System.nanoTime())+ .then()+ .statusCode(200);++ verify(certificateManager).ensureHost(domain);+ }++ @Test+ void endpointTypeConfigurationWithoutADomainNameRegistersNothing() {+ given()+ .contentType("application/json")+ .body("{}")+ .when()+ .post("/domainConfigurations/ensure-host-endpoint-" + System.nanoTime())+ .then()+ .statusCode(200);++ verify(certificateManager, never()).ensureHost(anyString());+ }++ @Test+ void rejectedCreateRegistersNothing() {+ given()+ .contentType("application/json")+ .body("""+ {+ "domainName": "no-cert-%s.dev.localhost.floci.io"+ }+ """.formatted(System.nanoTime()))+ .when()+ .post("/domainConfigurations/ensure-host-no-cert-" + System.nanoTime())+ .then()+ .statusCode(400);++ verify(certificateManager, never()).ensureHost(anyString());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationServiceTest.javaindex 7d0e84fa33..87fa327a15 100644--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationServiceTest.java@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.config.TlsCertificateManager;import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.storage.InMemoryStorage;@@ -39,7 +40,8 @@ class IotDomainConfigurationServiceTest {private final ObjectMapper mapper = new ObjectMapper();private final IotDomainConfigurationService service = new IotDomainConfigurationService(- new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"), endpointConfig());+ new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"), endpointConfig(),+ mock(TlsCertificateManager.class));private static EmulatorConfig endpointConfig() {EmulatorConfig config = mock(EmulatorConfig.class);diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationTlsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationTlsServiceTest.javanew file mode 100644index 0000000000..e92a23699d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotDomainConfigurationTlsServiceTest.java@@ -0,0 +1,147 @@+package io.github.hectorvent.floci.services.iot;++import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.config.TlsCertificateManager;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.InMemoryStorage;+import org.junit.jupiter.api.Test;++import java.util.concurrent.atomic.AtomicBoolean;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.doAnswer;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.verifyNoMoreInteractions;+import static org.mockito.Mockito.when;++/**+ * The contract between CreateDomainConfiguration and the TLS certificate manager: a+ * customer-managed domain name is handed over once, after the configuration is stored and with+ * no service lock held; an ENDPOINT configuration, the AWS-managed configurations, a rejected+ * request and every later operation register nothing.+ */+class IotDomainConfigurationTlsServiceTest {++ private static final String REGION = "us-east-1";+ private static final String CERTIFICATE_ARN =+ "arn:aws:acm:us-east-1:000000000000:certificate/11111111-1111-1111-1111-111111111111";++ private final ObjectMapper mapper = new ObjectMapper();+ private final TlsCertificateManager certificateManager = mock(TlsCertificateManager.class);+ private final IotDomainConfigurationService service = new IotDomainConfigurationService(+ new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"), endpointConfig(), certificateManager);++ private static EmulatorConfig endpointConfig() {+ EmulatorConfig config = mock(EmulatorConfig.class);+ when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");+ return config;+ }++ private ObjectNode customDomain(String domainName) {+ ObjectNode request = mapper.createObjectNode().put("domainName", domainName);+ request.putArray("serverCertificateArns").add(CERTIFICATE_ARN);+ return request;+ }++ @Test+ void customerManagedDomainIsHandedOverOnce() {+ service.createDomainConfiguration("iot", customDomain("iot.dev.localhost.floci.io"), REGION);++ verify(certificateManager).ensureHost("iot.dev.localhost.floci.io");+ verifyNoMoreInteractions(certificateManager);+ }++ @Test+ void endpointConfigurationRegistersNothing() {+ service.createDomainConfiguration("endpoint", mapper.createObjectNode(), REGION);+ service.createDomainConfiguration("null-body", null, REGION);++ verifyNoInteractions(certificateManager);+ }++ @Test+ void awsManagedConfigurationsRegisterNothing() {+ assertEquals("AWS_MANAGED", service.describeDomainConfiguration("iot:Data-ATS", REGION).getDomainType());++ verifyNoInteractions(certificateManager);+ }++ @Test+ void domainWithoutACertificateIsRejectedBeforeTheHook() {+ AwsException failure = assertThrows(AwsException.class, () -> service.createDomainConfiguration(+ "no-cert", mapper.createObjectNode().put("domainName", "iot.dev.localhost.floci.io"), REGION));++ assertEquals("InvalidRequestException", failure.getErrorCode());+ verifyNoInteractions(certificateManager);+ }++ @Test+ void duplicateNameIsRejectedBeforeTheHook() {+ service.createDomainConfiguration("iot", customDomain("iot.dev.localhost.floci.io"), REGION);++ AwsException failure = assertThrows(AwsException.class,+ () -> service.createDomainConfiguration("iot", customDomain("again.dev.localhost.floci.io"), REGION));++ assertEquals("ResourceAlreadyExistsException", failure.getErrorCode());+ verify(certificateManager).ensureHost("iot.dev.localhost.floci.io");+ verifyNoMoreInteractions(certificateManager);+ }++ @Test+ void configurationIsStoredBeforeTheCertificateIsExtended() {+ doAnswer(invocation -> {+ assertNotNull(service.describeDomainConfiguration("iot", REGION),+ "DescribeDomainConfiguration must already find the configuration while the certificate reloads");+ return null;+ }).when(certificateManager).ensureHost(anyString());++ service.createDomainConfiguration("iot", customDomain("iot.dev.localhost.floci.io"), REGION);++ verify(certificateManager).ensureHost("iot.dev.localhost.floci.io");+ }++ @Test+ void laterOperationsOnTheConfigurationRegisterNothingAgain() {+ service.createDomainConfiguration("iot", customDomain("iot.dev.localhost.floci.io"), REGION);++ service.updateDomainConfiguration("iot",+ mapper.createObjectNode().put("domainConfigurationStatus", "DISABLED"), REGION);+ service.describeDomainConfiguration("iot", REGION);+ service.deleteDomainConfiguration("iot", REGION);++ verify(certificateManager).ensureHost("iot.dev.localhost.floci.io");+ verifyNoMoreInteractions(certificateManager);+ }++ /** The reissue blocks on the HTTPS listener; a concurrent create must not queue behind it. */+ @Test+ void noServiceLockIsHeldWhileTheCertificateReloads() throws Exception {+ AtomicBoolean nested = new AtomicBoolean();+ Thread[] concurrent = new Thread[1];+ doAnswer(invocation -> {+ if (nested.compareAndSet(false, true)) {+ concurrent[0] = new Thread(() -> service.createDomainConfiguration(+ "other", customDomain("other.dev.localhost.floci.io"), REGION));+ concurrent[0].start();+ concurrent[0].join(5000);+ assertFalse(concurrent[0].isAlive(), "a create must not wait for another create's TLS reload");+ }+ return null;+ }).when(certificateManager).ensureHost(anyString());++ service.createDomainConfiguration("iot", customDomain("iot.dev.localhost.floci.io"), REGION);++ verify(certificateManager).ensureHost("iot.dev.localhost.floci.io");+ verify(certificateManager).ensureHost("other.dev.localhost.floci.io");+ assertNotNull(service.describeDomainConfiguration("other", REGION));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCaTrustTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCaTrustTest.javaindex 86e896420a..8d40f484b0 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCaTrustTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCaTrustTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.lambda.launcher;+import io.github.hectorvent.floci.config.FlociCertificateAuthority;import io.github.hectorvent.floci.services.acm.CertificateGenerator;import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;import org.bouncycastle.jce.provider.BouncyCastleProvider;@@ -84,9 +85,7 @@ class ContainerLauncherCaTrustTest {void resolveCaCertPath_acceptsButWarnsForUserLeafCert() throws Exception {// A leaf/server cert (issuer != subject, not a CA) is still accepted so trust injection// proceeds; the warning is logged. Here we assert it is accepted and is NOT a self-signed CA.- Path leaf = writeCert(tempDir.resolve("leaf.crt"),- new CertificateGenerator().generateCertificate(- "floci-leaf", List.of(), KeyAlgorithm.RSA_2048).certificatePem());+ Path leaf = writeLeaf("leaf.crt", "floci-leaf");Optional<Path> resolved = ContainerLauncher.resolveFlociCaCertPath(true, Optional.of(leaf.toString()), tempDir.toString());@@ -127,9 +126,7 @@ class ContainerLauncherCaTrustTest {@Testvoid isSelfSignedCaCertificate_falseForLeafCert() throws Exception {- Path leaf = writeCert(tempDir.resolve("leaf2.crt"),- new CertificateGenerator().generateCertificate(- "floci-leaf2", List.of(), KeyAlgorithm.RSA_2048).certificatePem());+ Path leaf = writeLeaf("leaf2.crt", "floci-leaf2");assertFalse(ContainerLauncher.isSelfSignedCaCertificate(leaf));}@@ -144,4 +141,11 @@ class ContainerLauncherCaTrustTest {private static Path writeCert(Path path, String pem) throws Exception {return Files.writeString(path, pem);}++ /** A server leaf issued by a throwaway CA: its issuer differs from its subject and it is not a CA. */+ private Path writeLeaf(String fileName, String commonName) throws Exception {+ FlociCertificateAuthority throwawayCa = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("throwaway-ca"));+ return writeCert(tempDir.resolve(fileName),+ throwawayCa.issueServerCertificate(commonName, List.of(), KeyAlgorithm.RSA_2048, null).certificatePem());+ }}