Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(tls): serve HTTPS on 443 and trust Floci's cert in Lambda containers (#1595)

Alex Banna6223fc4a02ad
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index f4ea15a04b..6dd1a5d38b 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -1342,6 +1342,23 @@ public interface EmulatorConfig {
*/
@WithDefault("true")
boolean selfSigned();
+
+ /**
+ * Additional port the TLS proxy binds for AWS-style HTTPS traffic, alongside the
+ * public Floci {@link EmulatorConfig#port()}.
+ *
+ * <p>CDK/CloudFormation custom resources send their {@code cfn-response} callback with
+ * bundled code that hardcodes {@code https://} and ignores the port in the ResponseURL,
+ * so the PUT lands on the conventional 443 regardless of Floci's configured port. Binding
+ * 443 here (with the same HTTP/HTTPS protocol detection used on the main port) lets those
+ * callbacks — and any other client that assumes AWS lives on 443 — reach Floci.
+ *
+ * <p>Default {@code 443}. Set to {@code 0} to disable the extra binding (e.g. when Floci
+ * runs unprivileged or another process owns 443). When equal to {@link EmulatorConfig#port()}
+ * only a single listener is started. Env: FLOCI_TLS_AWS_HTTPS_PORT
+ */
+ @WithDefault("443")
+ int awsHttpsPort();
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java
index c14d86d0d5..e02467957c 100644
--- a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java
+++ b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java
@@ -12,6 +12,7 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
@@ -80,9 +81,10 @@ public class TlsConfigSource implements ConfigSource {
"localhost.floci.io", "*.localhost.floci.io"));
currentHostnames.addAll(customHostnames);
- // Check if hostname configuration has changed
- if (hostnameConfigChanged(tlsDir, currentHostnames)) {
- // Configuration changed or metadata missing - regenerate certificate
+ // Regenerate when the hostname config changed, or when the existing certificate
+ // is a legacy non-self-signed cert (issuer != subject) — those cannot serve as a
+ // trust anchor for clients that install them, so an upgrade must replace them.
+ if (hostnameConfigChanged(tlsDir, currentHostnames) || !isSelfSigned(certFile)) {
generateSelfSignedCert(tlsDir, certFile, keyFile);
} else {
// Configuration unchanged - reuse existing certificate
@@ -173,7 +175,7 @@ public class TlsConfigSource implements ConfigSource {
allSans.addAll(customHostnames);
CertificateGenerator gen = new CertificateGenerator();
- CertificateGenerator.GeneratedCertificate generated = gen.generateCertificate(
+ CertificateGenerator.GeneratedCertificate generated = gen.generateSelfSignedCertificate(
"localhost",
allSans,
KeyAlgorithm.RSA_2048);
@@ -197,6 +199,21 @@ public class TlsConfigSource implements ConfigSource {
}
}
+ /**
+ * Returns {@code true} if the certificate at {@code certFile} is genuinely self-signed
+ * (issuer == subject) and therefore usable as a trust anchor. Legacy Floci certs carried a
+ * cosmetic Amazon issuer DN and return {@code false} here, triggering regeneration on upgrade.
+ */
+ private boolean isSelfSigned(Path certFile) {
+ try {
+ X509Certificate cert = new CertificateGenerator().parseCertificate(Files.readString(certFile));
+ return cert.getIssuerX500Principal().equals(cert.getSubjectX500Principal());
+ } catch (Exception e) {
+ LOG.warnv("TLS: could not inspect existing certificate ({0}); regenerating", e.getMessage());
+ return false;
+ }
+ }
+
/**
* Extracts custom hostnames from FLOCI_HOSTNAME and FLOCI_BASE_URL configuration.
* Filters out default values like "localhost" and "127.0.0.1".
diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsProxyServer.java b/src/main/java/io/github/hectorvent/floci/config/TlsProxyServer.java
index f88406e8bb..84fade489f 100644
--- a/src/main/java/io/github/hectorvent/floci/config/TlsProxyServer.java
+++ b/src/main/java/io/github/hectorvent/floci/config/TlsProxyServer.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.config;
import io.quarkus.runtime.Startup;
+import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetServer;
@@ -11,6 +12,11 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
/**
* A TCP proxy server that enables HTTP and HTTPS on the same port (LocalStack parity).
*
@@ -26,6 +32,12 @@ import org.jboss.logging.Logger;
* behavior where both {@code http://localhost:4566} and {@code https://localhost:4566}
* work simultaneously.
*
+ * <p>The same protocol-detecting handler is also bound on the configurable
+ * {@code floci.tls.aws-https-port} (443 by default). CDK/CloudFormation custom-resource
+ * {@code cfn-response} callbacks hardcode {@code https://} and ignore the ResponseURL port,
+ * so they PUT to 443 regardless of Floci's configured port; binding 443 lets those callbacks
+ * reach Floci. The extra binding is skipped when the port is {@code 0} or equals the public port.
+ *
* <p>This bean is only active when {@code floci.tls.enabled=true}. When TLS is disabled,
* Quarkus serves HTTP directly on port 4566 and this proxy is not started.
*/
@@ -43,13 +55,22 @@ public class TlsProxyServer {
private final Vertx vertx;
private final EmulatorConfig config;
- private NetServer proxyServer;
+ private final int httpBackendPort;
+ private final int httpsBackendPort;
+ private final List<NetServer> proxyServers = new ArrayList<>();
private NetClient client;
@Inject
public TlsProxyServer(Vertx vertx, EmulatorConfig config) {
+ this(vertx, config, HTTP_BACKEND_PORT, HTTPS_BACKEND_PORT);
+ }
+
+ /** Visible for testing — lets tests point the proxy at backends on non-default ports. */
+ TlsProxyServer(Vertx vertx, EmulatorConfig config, int httpBackendPort, int httpsBackendPort) {
this.vertx = vertx;
this.config = config;
+ this.httpBackendPort = httpBackendPort;
+ this.httpsBackendPort = httpsBackendPort;
startIfTlsEnabled();
}
@@ -58,15 +79,57 @@ public class TlsProxyServer {
return;
}
- int publicPort = config.port();
- NetServerOptions options = new NetServerOptions()
- .setHost("0.0.0.0")
- .setPort(publicPort);
-
- proxyServer = vertx.createNetServer(options);
client = vertx.createNetClient();
+ Handler<NetSocket> connectHandler = buildConnectHandler();
+
+ for (int port : listenPorts()) {
+ NetServerOptions options = new NetServerOptions()
+ .setHost("0.0.0.0")
+ .setPort(port);
+ NetServer server = vertx.createNetServer(options);
+ server.connectHandler(connectHandler);
+ proxyServers.add(server);
+ server.listen().onComplete(ar -> {
+ if (ar.succeeded()) {
+ LOG.infov("TLS proxy: listening on port {0} (HTTP→{1}, HTTPS→{2})",
+ String.valueOf(port), String.valueOf(httpBackendPort), String.valueOf(httpsBackendPort));
+ } else if (port == config.port()) {
+ LOG.errorv("TLS proxy: failed to start on public port {0}: {1}",
+ String.valueOf(port), ar.cause().getMessage());
+ } else {
+ // The extra AWS-HTTPS port (443 by default) is privileged; binding it fails in
+ // unprivileged environments (e.g. CI/test). Non-fatal — HTTPS on that port is
+ // simply unavailable. Set floci.tls.aws-https-port=0 to skip the attempt.
+ LOG.warnv("TLS proxy: could not bind AWS-HTTPS port {0} ({1}); HTTPS on {0} unavailable. "
+ + "Binding privileged ports needs elevated privileges — set floci.tls.aws-https-port=0 to disable.",
+ String.valueOf(port), ar.cause().getMessage());
+ }
+ });
+ }
+ }
+
+ /**
+ * The set of ports the proxy listens on: always the public Floci {@link EmulatorConfig#port()},
+ * plus {@code floci.tls.aws-https-port} (443 by default) so AWS-style HTTPS callbacks reach
+ * Floci. Deduplicated (a coinciding aws-https-port yields a single listener); a non-positive
+ * aws-https-port disables the extra binding.
+ */
+ Set<Integer> listenPorts() {
+ Set<Integer> ports = new LinkedHashSet<>();
+ ports.add(config.port());
+ int awsHttpsPort = config.tls().awsHttpsPort();
+ if (awsHttpsPort > 0) {
+ ports.add(awsHttpsPort);
+ }
+ return ports;
+ }
- proxyServer.connectHandler(frontSocket -> {
+ /**
+ * Builds the shared connect handler that peeks the first byte to detect TLS and pipes the
+ * connection to the matching backend. A single instance is reused across all listen ports.
+ */
+ private Handler<NetSocket> buildConnectHandler() {
+ return frontSocket -> {
// Pause incoming data until we've peeked at the first byte
frontSocket.pause();
@@ -79,9 +142,9 @@ public class TlsProxyServer {
// Inspect first byte to determine protocol
int backendPort;
if (buffer.length() > 0 && buffer.getByte(0) == TLS_HANDSHAKE) {
- backendPort = HTTPS_BACKEND_PORT;
+ backendPort = httpsBackendPort;
} else {
- backendPort = HTTP_BACKEND_PORT;
+ backendPort = httpBackendPort;
}
// Connect to the appropriate backend
@@ -108,23 +171,13 @@ public class TlsProxyServer {
// Resume to receive the first buffer
frontSocket.resume();
- });
-
- proxyServer.listen().onComplete(ar -> {
- if (ar.succeeded()) {
- LOG.infov("TLS proxy: listening on port {0} (HTTP→{1}, HTTPS→{2})",
- String.valueOf(publicPort), String.valueOf(HTTP_BACKEND_PORT), String.valueOf(HTTPS_BACKEND_PORT));
- } else {
- LOG.errorv("TLS proxy: failed to start on port {0}: {1}",
- String.valueOf(publicPort), ar.cause().getMessage());
- }
- });
+ };
}
@PreDestroy
void stop() {
- if (proxyServer != null) {
- proxyServer.close();
+ for (NetServer server : proxyServers) {
+ server.close();
}
if (client != null) {
client.close();
diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java b/src/main/java/io/github/hectorvent/floci/services/acm/CertificateGenerator.java
index 0d031b94e3..859f861e53 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
@@ -73,13 +73,33 @@ public class CertificateGenerator {
) {}
/**
- * Generates a self-signed X.509 certificate for local emulation.
+ * 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);
+ }
+
+ /**
+ * 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
+ * verify a TLS connection that presents it. Used for Floci's own HTTPS server certificate so
+ * that containers (e.g. Lambdas making CDK {@code cfn-response} callbacks over HTTPS) can trust
+ * 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);
+ }
+
+ private GeneratedCertificate buildCertificate(String domainName, List<String> sans, KeyAlgorithm keyAlgorithm,
+ String issuerDn, boolean asCa) {
try {
KeyPair keyPair = generateKeyPair(keyAlgorithm);
@@ -90,7 +110,7 @@ public class CertificateGenerator {
BigInteger serial = new BigInteger(128, SECURE_RANDOM);
String subjectDn = "CN=" + domainName;
- X500Name issuer = new X500Name(ISSUER_DN);
+ X500Name issuer = new X500Name(issuerDn);
X500Name subject = new X500Name(subjectDn);
String signatureAlgorithm = keyAlgorithm.getAlgorithm().equals("EC")
@@ -119,22 +139,20 @@ public class CertificateGenerator {
GeneralNames generalNames = new GeneralNames(sanList.toArray(new GeneralName[0]));
certBuilder.addExtension(Extension.subjectAlternativeName, false, generalNames);
- // Add Key Usage
- certBuilder.addExtension(
- Extension.keyUsage,
- true,
- new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)
- );
+ // Add Key Usage — a trust-anchor self-signed cert also needs keyCertSign so it can
+ // act as its own issuer; an ACM-style leaf only needs digitalSignature/keyEncipherment.
+ int keyUsageBits = KeyUsage.digitalSignature | KeyUsage.keyEncipherment;
+ if (asCa) {
+ keyUsageBits |= KeyUsage.keyCertSign;
+ }
+ certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsageBits));
- // Add Basic Constraints (not a CA)
- certBuilder.addExtension(
- Extension.basicConstraints,
- true,
- new BasicConstraints(false)
- );
+ // Add Basic Constraints — a trust anchor must be a CA so clients accept it as one.
+ certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(asCa));
- // Self-signed certificate for local emulation - signed with subject's own private key
- // Real AWS ACM certificates are signed by Amazon's CA hierarchy
+ // Signed with the subject's own private key. For generateCertificate() the issuer DN is
+ // a cosmetic Amazon DN (mimicking ACM); for generateSelfSignedCertificate() issuer ==
+ // subject, so the cert is a valid self-signed trust anchor.
ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(keyPair.getPrivate());
@@ -154,7 +172,7 @@ public class CertificateGenerator {
notBefore,
notAfter,
subjectDn,
- ISSUER_DN,
+ issuerDn,
signatureAlgorithm
);
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java
index ce2e548e82..991108fbc4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java
@@ -24,9 +24,12 @@ import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import java.io.Closeable;
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
@@ -51,6 +54,17 @@ public class ContainerLauncher {
private static final String TASK_DIR = "/var/task";
private static final String RUNTIME_DIR = "/var/runtime";
+ /**
+ * In-container location of Floci's CA certificate, injected when TLS is enabled so the
+ * container trusts Floci's self-signed HTTPS endpoint. {@code /etc} exists in every Lambda
+ * base image, so no directory needs to be created.
+ */
+ private static final String FLOCI_CA_DIR = "/etc";
+ private static final String FLOCI_CA_FILE_NAME = "floci-ca.crt";
+ private static final String FLOCI_CA_CONTAINER_PATH = FLOCI_CA_DIR + "/" + FLOCI_CA_FILE_NAME;
+ /** Self-signed cert filename produced by {@code TlsConfigSource} under {persistent-path}/tls/. */
+ private static final String SELF_SIGNED_CERT_NAME = "floci-selfsigned.crt";
+
private static final DateTimeFormatter LOG_STREAM_DATE_FMT = DateTimeFormatter.ofPattern("yyyy/MM/dd");
private final ContainerBuilder containerBuilder;
@@ -158,6 +172,13 @@ public class ContainerLauncher {
String flociEndpoint = reachableEndpoint.baseUrl();
String flociHostname = java.net.URI.create(flociEndpoint).getHost();
+ // When TLS is on, the container must trust Floci's self-signed cert so HTTPS callbacks
+ // to Floci succeed (e.g. a CDK custom resource's cfn-response, which hardcodes https://).
+ // Short-circuit when TLS is off so cert-path/storage config isn't read needlessly.
+ Optional<Path> flociCaCert = config.tls().enabled()
+ ? resolveFlociCaCertPath(true, config.tls().certPath(), config.storage().persistentPath())
+ : Optional.empty();
+
// Build env vars
List<String> env = new ArrayList<>();
env.add("AWS_LAMBDA_RUNTIME_API=" + runtimeApiEndpoint);
@@ -191,6 +212,7 @@ public class ContainerLauncher {
env.add("FLOCI_HOSTNAME=" + flociHostname);
env.add("FLOCI_ENDPOINT=" + flociEndpoint);
env.add("AWS_ENDPOINT_URL=" + flociEndpoint);
+ env.addAll(flociCaEnv(flociCaCert));
if (fn.getEnvironment() != null) {
fn.getEnvironment().forEach((k, v) -> env.add(k + "=" + v));
}
@@ -279,6 +301,12 @@ public class ContainerLauncher {
}
}
+ // 4. Copy Floci's CA cert so the container trusts Floci's HTTPS endpoint (TLS mode).
+ // Placed before start so NODE_EXTRA_CA_CERTS et al. resolve at runtime init.
+ flociCaCert.ifPresent(certPath ->
+ copyFileToContainer(dockerClient, containerId, certPath,
+ FLOCI_CA_DIR, FLOCI_CA_FILE_NAME, fn.getFunctionName()));
+
// Now start the container with code in place
lifecycleManager.startCreated(containerId, spec);
@@ -376,6 +404,83 @@ public class ContainerLauncher {
return runtime != null && runtime.startsWith("provided");
}
+ /**
+ * Resolves the host path of Floci's CA certificate to inject into Lambda containers, or
+ * empty when TLS is disabled or no readable certificate exists. Mirrors {@code TlsConfigSource}:
+ * a user-provided {@code floci.tls.cert-path} wins; otherwise the self-signed cert under
+ * {@code {persistent-path}/tls/}.
+ *
+ * <p>The resolved certificate is injected into containers as a <em>trust anchor</em> (CA), so it
+ * should be a self-signed CA certificate. The auto-generated Floci cert is one; a user-supplied
+ * {@code floci.tls.cert-path} that points at a leaf/server certificate is accepted but only pins
+ * that exact certificate (it cannot validate a chain it signs), so a warning is logged.
+ */
+ static Optional<Path> resolveFlociCaCertPath(boolean tlsEnabled, Optional<String> userCertPath,
+ String persistentPath) {
+ if (!tlsEnabled) {
+ return Optional.empty();
+ }
+ Optional<String> trimmedUserPath = userCertPath.filter(s -> !s.isBlank());
+ Path certPath = trimmedUserPath
+ .map(Path::of)
+ .orElseGet(() -> Path.of(persistentPath, "tls", SELF_SIGNED_CERT_NAME));
+ if (!Files.isReadable(certPath)) {
+ LOG.warnv("TLS enabled but Floci CA certificate not readable at {0}; "
+ + "Lambda containers will not trust Floci HTTPS callbacks", certPath);
+ return Optional.empty();
+ }
+ if (trimmedUserPath.isPresent() && !isSelfSignedCaCertificate(certPath)) {
+ LOG.warnv("Configured floci.tls.cert-path {0} is not a self-signed CA certificate; it is "
+ + "injected into Lambda containers as a trust anchor (CA), which only validates "
+ + "this exact certificate and not a chain it signs. Provide a self-signed CA "
+ + "certificate for reliable HTTPS callbacks.", certPath);
+ }
+ return Optional.of(certPath);
+ }
+
+ /**
+ * Returns {@code true} only if {@code certPath} holds a genuinely self-signed CA certificate
+ * (issuer == subject and BasicConstraints {@code CA:true}) — the form usable as a trust anchor.
+ * A leaf/server certificate, or one that cannot be read/parsed as X.509, returns {@code false}.
+ */
+ static boolean isSelfSignedCaCertificate(Path certPath) {
+ try (InputStream in = Files.newInputStream(certPath)) {
+ X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
+ .generateCertificate(in);
+ boolean selfSigned = cert.getSubjectX500Principal().equals(cert.getIssuerX500Principal());
+ boolean isCa = cert.getBasicConstraints() >= 0; // -1 == not a CA
+ return selfSigned && isCa;
+ } catch (Exception e) {
+ LOG.debugv("Could not inspect TLS certificate {0} for CA suitability: {1}",
+ certPath, e.getMessage());
+ return false;
+ }
+ }
+
+ /**
+ * Environment entries that make the container <em>add</em> Floci's CA to its trust, without
+ * replacing the system trust store (which would break the Lambda's external HTTPS calls):
+ * <ul>
+ * <li>{@code NODE_EXTRA_CA_CERTS} appends Floci's cert to Node's built-in CAs, so public TLS
+ * from the Lambda still works; and</li>
+ * <li>{@code AWS_CA_BUNDLE} is scoped to AWS SDK/CLI traffic, which Floci redirects to its own
+ * endpoint via {@code AWS_ENDPOINT_URL} — so pointing it at Floci's cert only affects
+ * calls that already target Floci.</li>
+ * </ul>
+ * {@code SSL_CERT_FILE} and {@code REQUESTS_CA_BUNDLE} are deliberately <em>not</em> set: each
+ * <em>replaces</em> the entire OpenSSL / Python-requests trust store with only Floci's cert,
+ * which breaks every external HTTPS call (curl, openssl, requests/botocore) the Lambda makes.
+ * Returns an empty list when no CA cert is available (TLS off).
+ */
+ static List<String> flociCaEnv(Optional<Path> caCert) {
+ if (caCert.isEmpty()) {
+ return List.of();
+ }
+ return List.of(
+ "NODE_EXTRA_CA_CERTS=" + FLOCI_CA_CONTAINER_PATH,
+ "AWS_CA_BUNDLE=" + FLOCI_CA_CONTAINER_PATH);
+ }
+
private static String extractRegionFromArn(String arn, String defaultRegion) {
if (arn == null) {
return defaultRegion;
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index dc42dca5fd..0f3e6d55d5 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -155,6 +155,7 @@ floci:
# cert-path: "" # FLOCI_TLS_CERT_PATH (PEM certificate file)
# key-path: "" # FLOCI_TLS_KEY_PATH (PEM private key file)
self-signed: true # FLOCI_TLS_SELF_SIGNED — auto-generate a self-signed cert if no cert-path provided
+ aws-https-port: 443 # FLOCI_TLS_AWS_HTTPS_PORT — also bind 443 so CDK cfn-response/AWS-on-443 callbacks reach Floci (0 disables)
docker:
log-max-size: "10m"
diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerTest.java
new file mode 100644
index 0000000000..7a663c8dec
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerTest.java
@@ -0,0 +1,176 @@
+package io.github.hectorvent.floci.config;
+
+import io.vertx.core.Vertx;
+import io.vertx.core.net.NetServer;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests for {@link TlsProxyServer}'s multi-port binding and first-byte protocol detection.
+ *
+ * <p>Uses ephemeral ports for the public port, the AWS-HTTPS port, and the stub HTTP/HTTPS
+ * backends, so nothing privileged (443) is bound and the test never collides with a running
+ * Floci. The stub backends simply emit a marker on connect; the proxy pipes it back, letting
+ * the test assert which backend a given first byte was routed to.
+ */
+class TlsProxyServerTest {
+
+ /** TLS ClientHello content type — the first byte the proxy keys protocol detection on. */
+ private static final byte TLS_HANDSHAKE = 0x16;
+
+ private Vertx vertx;
+ private TlsProxyServer proxy;
+ private NetServer httpBackend;
+ private NetServer httpsBackend;
+
+ @BeforeEach
+ void setUp() {
+ vertx = Vertx.vertx();
+ }
+
+ @AfterEach
+ void tearDown() {
+ if (proxy != null) {
+ proxy.stop();
+ }
+ closeBackend(httpBackend);
+ closeBackend(httpsBackend);
+ vertx.close();
+ }
+
+ private static EmulatorConfig configWith(boolean tlsEnabled, int publicPort, int awsHttpsPort) {
+ EmulatorConfig config = mock(EmulatorConfig.class);
+ EmulatorConfig.TlsConfig tls = mock(EmulatorConfig.TlsConfig.class);
+ when(config.port()).thenReturn(publicPort);
+ when(config.tls()).thenReturn(tls);
+ when(tls.enabled()).thenReturn(tlsEnabled);
+ when(tls.awsHttpsPort()).thenReturn(awsHttpsPort);
+ return config;
+ }
+
+ @Test
+ void listenPorts_includesPublicAndAwsHttpsPort() {
+ proxy = new TlsProxyServer(vertx, configWith(false, 4566, 443), 4510, 4511);
+ assertEquals(Set.of(4566, 443), proxy.listenPorts());
+ }
+
+ @Test
+ void listenPorts_dropsAwsHttpsPortWhenZero() {
+ proxy = new TlsProxyServer(vertx, configWith(false, 4566, 0), 4510, 4511);
+ assertEquals(Set.of(4566), proxy.listenPorts());
+ }
+
+ @Test
+ void listenPorts_dedupesWhenAwsHttpsPortEqualsPublic() {
+ proxy = new TlsProxyServer(vertx, configWith(false, 4566, 4566), 4510, 4511);
+ assertEquals(Set.of(4566), proxy.listenPorts());
+ }
+
+ @Test
+ @Timeout(20)
+ void bindsBothPorts_andRoutesByFirstByte() throws Exception {
+ int httpBe = freePort();
+ int httpsBe = freePort();
+ int publicPort = freePort();
+ int awsHttpsPort = freePort();
+ httpBackend = startMarkerBackend(httpBe, "PLAIN");
+ httpsBackend = startMarkerBackend(httpsBe, "TLS");
+
+ proxy = new TlsProxyServer(vertx, configWith(true, publicPort, awsHttpsPort), httpBe, httpsBe);
+
+ // Public port: TLS ClientHello → HTTPS backend; anything else → HTTP backend.
+ assertEquals("TLS", roundTrip(publicPort, TLS_HANDSHAKE));
+ assertEquals("PLAIN", roundTrip(publicPort, (byte) 'G'));
+ // AWS-HTTPS port: same protocol detection as the public port.
+ assertEquals("TLS", roundTrip(awsHttpsPort, TLS_HANDSHAKE));
+ assertEquals("PLAIN", roundTrip(awsHttpsPort, (byte) 'G'));
+ }
+
+ @Test
+ @Timeout(20)
+ void tlsDisabled_bindsNothing() throws Exception {
+ int publicPort = freePort();
+ proxy = new TlsProxyServer(vertx, configWith(false, publicPort, 443), 4510, 4511);
+ assertFalse(portAccepts(publicPort), "no proxy should listen when TLS is disabled");
+ }
+
+ // ---- helpers ----
+
+ private NetServer startMarkerBackend(int port, String marker) throws Exception {
+ NetServer server = vertx.createNetServer();
+ server.connectHandler(sock -> sock.write(marker));
+ CompletableFuture<Void> started = new CompletableFuture<>();
+ server.listen(port, "127.0.0.1").onComplete(ar -> {
+ if (ar.succeeded()) {
+ started.complete(null);
+ } else {
+ started.completeExceptionally(ar.cause());
+ }
+ });
+ started.get(5, TimeUnit.SECONDS);
+ return server;
+ }
+
+ private String roundTrip(int proxyPort, byte firstByte) throws Exception {
+ awaitListening(proxyPort);
+ try (Socket sock = new Socket("127.0.0.1", proxyPort)) {
+ sock.getOutputStream().write(new byte[]{firstByte});
+ sock.getOutputStream().flush();
+ byte[] buf = new byte[64];
+ int n = sock.getInputStream().read(buf);
+ assertTrue(n > 0, "expected a marker response from the backend");
+ return new String(buf, 0, n, StandardCharsets.UTF_8);
+ }
+ }
+
+ private void awaitListening(int port) throws Exception {
+ long deadline = System.currentTimeMillis() + 10_000;
+ while (System.currentTimeMillis() < deadline) {
+ try (Socket s = new Socket("127.0.0.1", port)) {
+ return;
+ } catch (IOException e) {
+ Thread.sleep(50);
+ }
+ }
+ fail("port " + port + " not listening within timeout");
+ }
+
+ private boolean portAccepts(int port) throws Exception {
+ // Give any (unexpected) async bind a brief chance to come up, then probe once.
+ Thread.sleep(500);
+ try (Socket s = new Socket("127.0.0.1", port)) {
+ return true;
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ private static void closeBackend(NetServer server) {
+ if (server != null) {
+ server.close();
+ }
+ }
+
+ private static int freePort() throws IOException {
+ try (ServerSocket s = new ServerSocket(0)) {
+ return s.getLocalPort();
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSelfSignedTest.java b/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSelfSignedTest.java
new file mode 100644
index 0000000000..f35677acf2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/acm/CertificateGeneratorSelfSignedTest.java
@@ -0,0 +1,68 @@
+package io.github.hectorvent.floci.services.acm;
+
+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.security.Security;
+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>
+ */
+class CertificateGeneratorSelfSignedTest {
+
+ private static CertificateGenerator generator;
+
+ @BeforeAll
+ static void setup() {
+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
+ Security.addProvider(new BouncyCastleProvider());
+ }
+ generator = new CertificateGenerator();
+ }
+
+ @Test
+ void selfSignedCertificateIsItsOwnIssuerAndACa() throws Exception {
+ var generated = generator.generateSelfSignedCertificate(
+ "localhost", List.of("localhost", "localhost.floci.io"), KeyAlgorithm.RSA_2048);
+
+ X509Certificate cert = generator.parseCertificate(generated.certificatePem());
+
+ assertEquals(cert.getSubjectX500Principal(), cert.getIssuerX500Principal(),
+ "self-signed cert must have issuer == subject so it is a valid trust anchor");
+ assertTrue(cert.getBasicConstraints() >= 0, "self-signed cert must be marked as a CA");
+ assertTrue(cert.getKeyUsage() != null && cert.getKeyUsage()[5],
+ "self-signed cert must assert keyCertSign so it can be its own issuer");
+
+ // 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/eventbridge/EventBridgeSchedulerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
index 75bfd2a5d4..9d1b2b0aab 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
@@ -328,6 +328,7 @@ class EventBridgeSchedulerIntegrationTest {
@Override public Optional<String> certPath() { return Optional.empty(); }
@Override public Optional<String> keyPath() { return Optional.empty(); }
@Override public boolean selfSigned() { return true; }
+ @Override public int awsHttpsPort() { return 443; }
};
}
};
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java
index 896b9a9197..a93f35fd54 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java
@@ -238,6 +238,9 @@ class LambdaImageConfigTest {
when(docker.logMaxSize()).thenReturn("10m");
when(docker.logMaxFile()).thenReturn("3");
when(config.baseUrl()).thenReturn("http://localhost:4566");
+ EmulatorConfig.TlsConfig tls = mock(EmulatorConfig.TlsConfig.class);
+ when(config.tls()).thenReturn(tls);
+ lenient().when(tls.enabled()).thenReturn(false);
lenient().when(config.hostname()).thenReturn(Optional.empty());
when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty());
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.java
new file mode 100644
index 0000000000..40b57bbb11
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCaTrustTest.java
@@ -0,0 +1,147 @@
+package io.github.hectorvent.floci.services.lambda.launcher;
+
+import io.github.hectorvent.floci.services.acm.CertificateGenerator;
+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.junit.jupiter.api.BeforeAll;
+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.Security;
+import java.util.List;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Unit tests for {@link ContainerLauncher}'s Floci CA-trust injection helpers. These are pure
+ * (no Docker / Quarkus): they cover where the CA cert is resolved from and which environment
+ * variables get injected so a Lambda container trusts Floci's self-signed HTTPS endpoint.
+ */
+class ContainerLauncherCaTrustTest {
+
+ @TempDir
+ Path tempDir;
+
+ @BeforeAll
+ static void registerBouncyCastle() {
+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
+ Security.addProvider(new BouncyCastleProvider());
+ }
+ }
+
+ @Test
+ void resolveCaCertPath_emptyWhenTlsDisabled() {
+ assertTrue(ContainerLauncher.resolveFlociCaCertPath(false, Optional.empty(), tempDir.toString())
+ .isEmpty());
+ }
+
+ @Test
+ void resolveCaCertPath_selfSignedUnderPersistentPath() throws Exception {
+ Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));
+ Path cert = Files.writeString(tlsDir.resolve("floci-selfsigned.crt"), "PEM");
+
+ Optional<Path> resolved =
+ ContainerLauncher.resolveFlociCaCertPath(true, Optional.empty(), tempDir.toString());
+
+ assertEquals(cert, resolved.orElseThrow());
+ }
+
+ @Test
+ void resolveCaCertPath_userProvidedCertWins() throws Exception {
+ Path userCert = writeCert(tempDir.resolve("user.crt"),
+ new CertificateGenerator().generateSelfSignedCertificate(
+ "floci-user", List.of(), KeyAlgorithm.RSA_2048).certificatePem());
+
+ Optional<Path> resolved = ContainerLauncher.resolveFlociCaCertPath(
+ true, Optional.of(userCert.toString()), tempDir.toString());
+
+ assertEquals(userCert, resolved.orElseThrow());
+ }
+
+ @Test
+ void resolveCaCertPath_blankUserCertFallsBackToSelfSigned() throws Exception {
+ Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));
+ Path cert = Files.writeString(tlsDir.resolve("floci-selfsigned.crt"), "PEM");
+
+ Optional<Path> resolved =
+ ContainerLauncher.resolveFlociCaCertPath(true, Optional.of(" "), tempDir.toString());
+
+ assertEquals(cert, resolved.orElseThrow());
+ }
+
+ @Test
+ void resolveCaCertPath_emptyWhenCertMissing() {
+ assertTrue(ContainerLauncher.resolveFlociCaCertPath(true, Optional.empty(), tempDir.toString())
+ .isEmpty());
+ }
+
+ @Test
+ 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());
+
+ Optional<Path> resolved = ContainerLauncher.resolveFlociCaCertPath(
+ true, Optional.of(leaf.toString()), tempDir.toString());
+
+ assertEquals(leaf, resolved.orElseThrow());
+ assertFalse(ContainerLauncher.isSelfSignedCaCertificate(leaf));
+ }
+
+ @Test
+ void caEnv_emptyWhenNoCert() {
+ assertTrue(ContainerLauncher.flociCaEnv(Optional.empty()).isEmpty());
+ }
+
+ @Test
+ void caEnv_onlySetsAppendingAndAwsScopedVars() {
+ List<String> env = ContainerLauncher.flociCaEnv(Optional.of(Path.of("/host/floci-selfsigned.crt")));
+
+ // Only NODE_EXTRA_CA_CERTS (appends to Node's CAs) and AWS_CA_BUNDLE (AWS-SDK-scoped, redirected
+ // to Floci) are injected — never SSL_CERT_FILE / REQUESTS_CA_BUNDLE, which would replace the
+ // whole trust store and break the Lambda's external HTTPS.
+ assertEquals(List.of(
+ "NODE_EXTRA_CA_CERTS=/etc/floci-ca.crt",
+ "AWS_CA_BUNDLE=/etc/floci-ca.crt"), env);
+ assertFalse(env.stream().anyMatch(e -> e.startsWith("SSL_CERT_FILE=")),
+ "SSL_CERT_FILE replaces the OpenSSL trust store and must not be set");
+ assertFalse(env.stream().anyMatch(e -> e.startsWith("REQUESTS_CA_BUNDLE=")),
+ "REQUESTS_CA_BUNDLE replaces the requests trust store and must not be set");
+ }
+
+ @Test
+ void isSelfSignedCaCertificate_trueForSelfSignedCa() throws Exception {
+ Path ca = writeCert(tempDir.resolve("ca.crt"),
+ new CertificateGenerator().generateSelfSignedCertificate(
+ "floci-ca", List.of(), KeyAlgorithm.RSA_2048).certificatePem());
+
+ assertTrue(ContainerLauncher.isSelfSignedCaCertificate(ca));
+ }
+
+ @Test
+ void isSelfSignedCaCertificate_falseForLeafCert() throws Exception {
+ Path leaf = writeCert(tempDir.resolve("leaf2.crt"),
+ new CertificateGenerator().generateCertificate(
+ "floci-leaf2", List.of(), KeyAlgorithm.RSA_2048).certificatePem());
+
+ assertFalse(ContainerLauncher.isSelfSignedCaCertificate(leaf));
+ }
+
+ @Test
+ void isSelfSignedCaCertificate_falseForNonCertContent() throws Exception {
+ Path garbage = Files.writeString(tempDir.resolve("garbage.crt"), "not a certificate");
+
+ assertFalse(ContainerLauncher.isSelfSignedCaCertificate(garbage));
+ }
+
+ private static Path writeCert(Path path, String pem) throws Exception {
+ return Files.writeString(path, pem);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java
index 08f31e56af..144d881981 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java
@@ -70,6 +70,9 @@ class ContainerLauncherTest {
when(docker.logMaxSize()).thenReturn("10m");
when(docker.logMaxFile()).thenReturn("3");
when(config.baseUrl()).thenReturn("http://localhost:4566");
+ EmulatorConfig.TlsConfig tls = mock(EmulatorConfig.TlsConfig.class);
+ when(config.tls()).thenReturn(tls);
+ lenient().when(tls.enabled()).thenReturn(false);
lenient().when(config.defaultRegion()).thenReturn("us-east-1");
lenient().when(config.hostname()).thenReturn(Optional.empty());