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

* feat(lambda): trust Floci's TLS cert and serve HTTPS on 443 for CDK callbacks

CDK/CloudFormation custom resources (LogRetention, the provider framework,
AwsCustomResource, ...) PUT their result to the cfn-response ResponseURL using
aws-cdk-lib's bundled cfn-response code. That code parses only the URL's hostname
and path and then calls require("https").request(...) — it ignores the scheme and
port. So even though Floci hands the resource an http://...:4566 ResponseURL, the
callback always goes to https://<host>:443. Against Floci that fails — so every
custom resource rolls back, even though its own AWS SDK calls (on 4566) succeed.

This makes Floci reachable, and trusted, where the callback actually connects,
without touching the CDK-owned handler:

- TlsProxyServer binds the same protocol-detecting handler on a configurable
  floci.tls.aws-https-port (default 443, 0 to disable, deduped against the public
  port) in addition to the public Floci port. The first byte still selects the
  HTTP (4510) or HTTPS (4511) backend, so 443 serves both like the main port.

- CertificateGenerator gains generateSelfSignedCertificate(): a genuinely
  self-signed cert (issuer == subject, CA:true, keyCertSign) that can be a trust
  anchor. The existing generateCertificate() is unchanged — it still stamps the
  cosmetic Amazon issuer DN for ACM realism, which is NOT verifiable as an anchor.
  TlsConfigSource now uses the self-signed variant for Floci's HTTPS cert and
  regenerates legacy non-self-signed certs on upgrade.

- ContainerLauncher, when TLS is enabled, copies Floci's CA certificate into each
  Lambda container at /etc/floci-ca.crt and sets NODE_EXTRA_CA_CERTS, AWS_CA_BUNDLE,
  SSL_CERT_FILE and REQUESTS_CA_BUNDLE so the container trusts Floci's HTTPS
  endpoint. NODE_EXTRA_CA_CERTS adds to Node's built-in CAs, so public TLS still
  works.

All behaviors are gated on floci.tls.enabled (default false); non-TLS setups are
unchanged.

* fix(tls): guard TlsConfig access in launcher tests and soften 443 bind log

CI surfaced 18 NPEs in the existing ContainerLauncherTest and LambdaImageConfigTest:
ContainerLauncher.launch() now reads config.tls().enabled(), but those tests mock
EmulatorConfig without stubbing tls() (returns null). Fixes:
- launch() short-circuits so cert-path/storage config is only read when TLS is enabled.
- Both tests stub config.tls() with a TlsConfig whose enabled() is false.
- TlsProxyServer logs a failed bind of the extra AWS-HTTPS port (443, privileged) at
  WARN instead of ERROR — it is expected and non-fatal in unprivileged envs (CI/test);
  the public port still errors loudly.

* fix(tls): don't replace the Lambda's CA bundle; warn on a non-CA cert

flociCaEnv set SSL_CERT_FILE and REQUESTS_CA_BUNDLE to Floci's cert, which
REPLACE the OpenSSL / Python-requests trust store with only that cert — so a
Lambda's external HTTPS calls (curl, openssl, requests/botocore) to anything but
Floci failed certificate verification. Inject only the appending/AWS-scoped vars:
NODE_EXTRA_CA_CERTS (adds to Node's CAs) and AWS_CA_BUNDLE (AWS-SDK traffic is
redirected to Floci via AWS_ENDPOINT_URL anyway).

resolveFlociCaCertPath injects the resolved cert into containers as a trust
anchor (CA). A user-supplied floci.tls.cert-path pointing at a leaf/server cert
only pins that exact certificate; document that and log a warning when the
configured cert is not a self-signed CA (issuer != subject or no BasicConstraints
CA:true), via the new isSelfSignedCaCertificate helper.

Updates ContainerLauncherCaTrustTest for the trimmed env set and adds coverage
for self-signed-CA vs leaf-cert detection.
This commit is contained in:
Alex Banna authored and GitHub committed 2026-07-01 21:29:05 -05:00
1 parent dec3b6366e
commit 6223fc4a02
12 files changed
+653 -44

No files matched your search

@@ -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();
}
}
}
@@ -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");
}
}
@@ -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; }
};
}
};
@@ -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());
@@ -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);
}
}
@@ -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());