feat: serve custom domains over TLS as soon as they are created (#3086)

* feat(tls): record runtime-learned hostnames in the certificate metadata

* feat(tls): TlsCertificateManager.ensureHost grows the server certificate at runtime

Reissues the leaf from the local CA with the same key pair and the new SAN,
replaces certificate and metadata by atomic renames (the key file is never
rewritten), reloads the default TLS configuration and fires
CertificateUpdatedEvent so the HTTPS listener swaps immediately.
Names must be well-formed host names under a local suffix; anything else is
refused with a WARN and never throws.

* feat(tls): keep runtime-learned hostnames across a boot regeneration

* test(tls): ensureHost is visible to the next TLS handshake without a restart

* docs(tls): custom domains learned at runtime

* test(tls): pin the certificate contracts of a runtime reissue

The reissued leaf keeps the boot leaf's shape (subject, issuer, EKU, CA flag,
validity, new serial, configured names first), a wildcard covers exactly one
label, an IP allowed by the base URL becomes an iPAddress SAN, and a client
that verifies the server's identity for the new name (SNI plus RFC 6125
matching) fails before ensureHost, succeeds after it, and fails again after
reset, while the configured name keeps serving HTTPS throughout.

* fix(tls): retry a failed listener reload and keep served names across a boot

A name is known only once the HTTPS listener serves it: a reload that
returns false, a missing default TLS configuration or a failing listener
now leaves the in-memory state untouched, so the next ensureHost call for
that name writes and reloads again instead of reporting it as covered.

At boot, a SAN the served certificate carries beyond the metadata's
configured list is treated as learned, so a reissue whose metadata rename
did not complete cannot lose the name in a later regeneration.

The allow-list is checked after coverage, so a default SAN such as
host.docker.internal no longer logs a refusal on a no-op call.

Tests are split by concern: TlsCertificateManagerTest (reissue, reload,
reset, failure, races) and TlsCertificateManagerNameRulesTest over a
shared fixture; TlsConfigSourceLearnedHostnamesTest holds the boot paths.

* fix(tls): carry a name whose reload failed into later reissues and resets

The learned list now follows the files and the known set follows the
listener. A name written to disk but not yet served is kept by every
later reissue instead of being dropped when a second name is learned,
and a reset whose reload failed is retried by the next reset.

Two pre-existing em dashes in TlsConfigSource log messages replaced with
commas, as AGENTS.md asks.

* feat(acm): issue AMAZON_ISSUED and PRIVATE certificates from the local CA

RequestCertificate now returns a TLS server leaf (serverAuth and clientAuth)
signed by Floci's local root CA, and CertificateChain is that CA's PEM, the
same bytes GET /_floci/ca.pem serves. Certificate plus CertificateChain from
GetCertificate therefore build a chain that validates, as they do on AWS, for
both certificate types, and ExportCertificate returns the same chain. The
requested KeyAlgorithm is still honoured and DescribeCertificate reports the
CA as the issuer.

The bundled amazon-root-ca.pem and its startup check are gone: nothing Floci
issues chained to it, and the file was corrupt (its base64 payload could not
decode), so every GetCertificate handed out an unparsable chain.

AcmPaginationTest walks a store shared with every other ACM test class; its
page cap now leaves room for the suite to grow instead of failing once the
shared store passes fifty certificates.

* refactor(acm): drop the cosmetic Amazon issuer generator

CertificateGenerator.generateCertificate signed a leaf with its own key under a
CN=Amazon issuer DN that no client could ever verify. Its last production caller
now issues from the local CA, so the method and the DN are gone and the
self-signed builder no longer carries an issuer and CA flag that were always the
subject and true. Tests that only needed some certificate use the self-signed
generator; the ones that need a leaf that is not a CA issue it from a throwaway
CA.

* docs(acm): certificates chain to the local CA

Say that every issued certificate is signed by the local root CA, that
GetCertificate returns that CA as CertificateChain, and that trusting
/_floci/ca.pem once validates both the HTTPS endpoint and ACM certificates.

* test(acm): the SDK compatibility suite validates the certificate against its chain

GetCertificate's certificateChain() must contain the issuing CA and that CA
must verify certificate(), as on AWS. A chain that does not parse or does not
sign the leaf now fails the suite instead of passing a BEGIN CERTIFICATE check.

* docs(acm): say when the CA is created and what Issuer reports

ACM issuance now creates the local CA under {persistent-path}/tls/ on first
use, also with TLS off and in memory storage mode, and DescribeCertificate
reports the CA's name as Issuer where AWS reports Amazon. The CA javadoc no
longer calls ACM a later step.

* test(acm): pin key size, an imported chain and the persisted chain

The import fixture is now a server certificate from a throwaway CA, uploaded
with that CA as its chain, and GetCertificate must hand both back unchanged.
The RSA and EC chain tests also check the key size and curve, and the
persistence test checks the chain survives a restart.

* test(acm): the python compatibility suite verifies the certificate against its chain

The key-algorithm case checked the certificate's self-signature, which only
held while ACM certificates were signed by their own key under a cosmetic
issuer. On AWS, and now here, the signer is the issuing CA that GetCertificate
returns first in CertificateChain, so the case verifies that signature and the
issuer name instead.

* fix(acm): write EC private keys as PKCS#8 and classify keys by interface

JcaPEMWriter turned a JDK EC private key into a bare SEC1 structure with
no curve and no public half, which neither OpenSSL nor parsePrivateKey
could read, so every EC certificate stored an unusable key and
ExportCertificate on one failed. EC keys now go out as PKCS#8, RSA keys
stay PKCS#1 as AWS IoT hands them out, and a SEC1 key without a public
half parses through its private-key info.

Private keys are told apart by the ECKey interface rather than by name:
a BouncyCastle provider, when one is registered, names an EC key ECDSA.

* test(acm): AcmServiceTest pins issuance from the local CA

Service level, no Quarkus: every KeyAlgorithm yields a leaf of that key
signed by the CA with the CA PEM as chain and metadata read from the
certificate; PRIVATE is issued at once; a pending certificate already
holds its leaf and chain; an idempotent replay mints nothing; imports
keep their own chain; exports return the stored chain, also for EC
keys; sixteen concurrent requests each get their own valid certificate.

* feat(apigateway): serve a custom domain over TLS as soon as it is created

CreateDomainName hands the domain name to TlsCertificateManager.ensureHost
after the domain is stored, outside the uniqueness lock. The certificate
manager never throws, so the API response is unchanged.

* feat(iot): serve a customer-managed domain over TLS as soon as it is configured

CreateDomainConfiguration hands a customer-managed domain name to
TlsCertificateManager.ensureHost after the configuration is stored. A
configuration without a domain name describes the default endpoint and
registers nothing.

* feat(cognito): serve a custom domain over TLS as soon as it is created

CreateUserPoolDomain hands a custom domain to TlsCertificateManager.ensureHost
after the domain is stored. A prefix domain lives under amazoncognito.com on
AWS, a name Floci does not serve, and is left alone.

* docs: custom domains are served over TLS on creation

One sentence each in the API Gateway, IoT Core and Cognito pages, and the
TLS page now names the operations that add hostnames to the server
certificate.

* test(compat): custom domain reachable over TLS trusting only the ACM chain

RequestCertificate, CreateDomainName with regionalCertificateArn, then a TLS
handshake with SNI that trusts only the returned CertificateChain and
verifies the hostname. Probes for TLS on the endpoint host and port, because
the workflow hands the tests an http:// URL while Floci serves both, and
skips when the probe fails.

* docs(tls): say which ensureHost outcomes are logged as warnings

* test: pin the custom domain TLS hooks against the service contracts

Service tests for API Gateway, IoT Core and Cognito: the exact name is
handed over once, after the record is stored, with no service lock held
(a concurrent create must not wait for the TLS reload), and never for a
rejected request, an ENDPOINT configuration, an AWS-managed configuration,
a prefix domain or a later update or delete. A CloudFormation stack with
the three types registers every domain and a replacement, not an in-place
update or the delete. With TLS on, a client trusting only the ACM chain
reaches all three names by SNI with hostname verification, and a reset
takes them back.

* test(acm): build the InUseBy test service with the local CA

AcmInUseByTest landed on main with #3035 using the constructor that
predates the local CA; AcmService now takes the certificate authority
it issues from, so the test loads a throwaway CA in its temp directory
like AcmServiceTest does.

* test(cognito): request an issued ACM certificate in the custom domain TLS tests

Since #3035 a custom domain needs an issued ACM certificate, so the wire
test requests one and the service test stubs AcmService. Two new cases pin
that a certificate ACM does not know, or has not issued, is refused before
the hostname is registered.

* test(cognito): a concurrent create does not wait for the TLS reload

The custom domain hook sits after the domain lock #3095 introduced, so a
second create is not queued behind the HTTPS listener switch; pinned the
same way as for API Gateway and IoT Core. The routing test #3095 added
constructs the service with the certificate manager as well.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-05 22:05:40 -04:00
1 parent 1bf7494e99
commit 67bbd2cf13
49 files changed
+3317 -216

No files matched your search

@@ -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);
}
@Override
public int hashCode() {
return Objects.hash(hostnames, generatedAt, flociVersion);
return Objects.hash(hostnames, getLearnedHostnames(), generatedAt, flociVersion);
}
@Override
public String toString() {
return "CertificateMetadata{" +
"hostnames=" + hostnames +
", learnedHostnames=" + learnedHostnames +
", generatedAt='" + generatedAt + '\'' +
", flociVersion='" + flociVersion + '\'' +
'}';
@@ -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}.
*
@@ -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;
}
}
@@ -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);
@@ -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 {
@Inject
public 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 "";
}
}
}
@@ -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);
}
@@ -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;
// Constants
private 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;
}
@@ -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 {
@Inject
public 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;
}
@@ -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 {
@Inject
public 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;
}