feat(docker): containers Floci launches trust the Floci CA (#3091)

* feat(tls): write a CA bundle for launched containers at boot

Containers Floci launches need to trust Floci's HTTPS endpoint from any runtime
without losing access to public HTTPS. A bundle that carries the JVM's public
roots followed by Floci's trust anchor makes that possible: the variables that
replace a runtime's trust store (SSL_CERT_FILE and friends) can then point at
it safely.

ContainerCaBundle writes {persistent-path}/tls/floci-ca-bundle.pem from the
JVM's default trust anchors plus the certificates in the anchor file: the local
CA, or the user-provided certificate file in custom-certificate mode. Only
certificates are copied out of that file, so a combined certificate-and-key
file never leaks its key into a container. The file is swapped in atomically
from a uniquely named temporary file. TlsConfigSource writes it in both
certificate modes; a failure is logged and never stops the boot.

hostPath(config) resolves the bundle in the directory the bootstrap used, so a
persistent path set only in application.yml cannot point it elsewhere, and
appendEnv(env) adds SSL_CERT_FILE, CURL_CA_BUNDLE, REQUESTS_CA_BUNDLE,
NODE_EXTRA_CA_CERTS and AWS_CA_BUNDLE without overriding a key the caller set.

The bootstrap now records its TLS directory in every TLS-on mode, not only when
it issues the leaf, so the CA producer and the bundle lookup read from the
directory the boot wrote to even when a persistent path is set in
application.yml alone. A missing bundle is reported once per process.

* feat(docker): every launched container gets the CA bundle and the trust variables

ContainerLifecycleManager.create is the single path every emulator-created
container passes through, so injecting trust there covers Lambda, ECS, MWAA,
Flink, RDS, ElastiCache, Batch and the rest at once.

With TLS on and the bundle present, create appends the five trust variables
after the spec's own environment (a value from a task or function definition
wins) and copies the bundle to /etc/floci-ca-bundle.pem in the created, not
yet started, container. A copy rather than a bind mount, because when Floci
itself runs in Docker its persistent path is not a host path the daemon can
mount. A failed copy is logged with its consequence and the container still
starts. With TLS off, or without a bundle, nothing changes.

* refactor(lambda): take container CA trust from the lifecycle manager bundle

The Lambda launcher no longer resolves, copies or announces the CA itself: the
lifecycle manager does that for every container. Its append-only policy
(NODE_EXTRA_CA_CERTS and AWS_CA_BUNDLE only, never SSL_CERT_FILE) existed
because a bare CA would have cut a function off from public HTTPS; the bundle
carries the public roots, so the policy and the test that guarded it go.

The Kubernetes launcher publishes the bundle in its ConfigMap instead of the
bare CA, mounts it at /etc/floci-ca-bundle.pem, and appends the trust
variables after the function's own environment so a function value wins, as
in the Docker launcher.

* test(docker): a launched container trusts Floci and public roots through the bundle

The unit tests pin the variables and the copy, not that a runtime reading them
actually trusts Floci and still reaches public HTTPS. A python:3.12-alpine
container launched through the lifecycle manager, with the image's own root
directory pointed away so only the bundle can supply roots, fetches
https://host.docker.internal:<port>/_floci/ca.pem and https://public.ecr.aws/
with no setup of its own. Skipped without a Docker daemon, like the other
*DockerIntegrationTest classes; the image is prefetched in CI with the
others.

* docs(tls): containers Floci launches trust the Floci CA

Describe the bundle every launched container receives, the five variables that
point at it, that a value set on the function or task definition wins, and
that the JVM ignores these variables so a Java workload still needs its own
trust store.

* fix(docker): recreate a container without the trust variables when the bundle cannot be copied

SSL_CERT_FILE, CURL_CA_BUNDLE and REQUESTS_CA_BUNDLE replace a runtime's trust
store, so a container whose bundle copy failed (an image without /etc) used to
start pointing them at a file that was not there, and lost every HTTPS
connection instead of only the ones to Floci. The lifecycle manager now removes
that container and creates it again without the variables, so it keeps the
image's own trust store. The host configuration, and with it any dynamic host
port, is built once and reused.

* fix(tls): serve only the certificate blocks of a user-provided file from ca.pem

In custom-certificate mode GET /_floci/ca.pem returned the configured
certificate file byte for byte, so a combined certificate-and-key file, the
form OpenSSL tooling produces, handed the server's private key to any caller.
The endpoint now goes through the same certificate-only parsing the container
bundle uses. TlsUserCertIntegrationTest boots on a combined file and asserts
the response holds the user certificate and the local CA and no key.

* test(cloudformation): wait for DeleteStack to finish before asserting on deleted resources

DeleteStack hands the work to an executor and answers at once. Seven tests in
CloudFormationIntegrationTest asserted on the deleted resources right after the
answer; one of them, deleteStack_ecs_leavesNoOrphans, failed shard 1 of this
pull request's CI 44 ms later with the cluster still ACTIVE, while the same
shard had passed on the previous push.

A shared awaitStackDeleted polls DescribeStacks until the stack reports
DELETE_COMPLETE or no longer exists, fails on DELETE_FAILED or after ten
seconds, and replaces the three inline copies of that loop as well.

* docs(tls): restore the learned-hostnames section and the ACM wording that #3079 dropped

#3079's docs commit (dc3e9ee6a) was written against a tls.md that predated
#3086 and, once squashed onto main, removed the "Custom Domains Learned at
Runtime" section #3086 had added and reworded the intro to place ACM
certificates "in a later release", although AcmService has issued them from
the local CA since #3086. Both are restored here, next to the new section,
because a separate PR would conflict with this one on the same lines.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-06 14:57:08 -05:00
1 parent d45c64545d
commit 024bfa0a5c
24 files changed
+1143 -367

No files matched your search

@@ -0,0 +1,215 @@
package io.github.hectorvent.floci.config;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The CA bundle handed to every container Floci launches: the JVM's public roots followed by
* Floci's trust anchor, and the environment entries that make each runtime read it.
*/
class ContainerCaBundleTest {
@TempDir
Path tempDir;
@BeforeEach
@AfterEach
void forgetBootstrapTlsDir() {
// TlsConfigSource.resolvedTlsDir is static: a TLS-on bootstrap run by another test class
// in this JVM would otherwise steer hostPath() at that test's directory.
System.setProperty("floci.tls.enabled", "false");
new TlsConfigSource();
System.clearProperty("floci.tls.enabled");
}
@Test
void writeProducesTheSystemRootsFollowedByTheAnchor() throws Exception {
Path tlsDir = tempDir.resolve("tls");
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
Path bundle = ContainerCaBundle.write(tlsDir, ca.certificatePath());
assertEquals(tlsDir.resolve("floci-ca-bundle.pem"), bundle);
List<X509Certificate> certificates = parseAll(Files.readAllBytes(bundle));
assertTrue(certificates.size() > 50, "expected the JVM's public roots, got " + certificates.size());
assertEquals(ca.certificate(), certificates.get(certificates.size() - 1), "the Floci CA closes the bundle");
assertEquals(1, certificates.stream().filter(ca.certificate()::equals).count());
}
@Test
void writeIsIdempotent() throws Exception {
Path tlsDir = tempDir.resolve("tls");
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
byte[] first = Files.readAllBytes(ContainerCaBundle.write(tlsDir, ca.certificatePath()));
byte[] second = Files.readAllBytes(ContainerCaBundle.write(tlsDir, ca.certificatePath()));
assertTrue(java.util.Arrays.equals(first, second));
try (var files = Files.list(tlsDir)) {
assertTrue(files.noneMatch(file -> file.getFileName().toString().endsWith(".tmp")), "no temp file left behind");
}
}
@Test
void writeKeepsEveryCertificateOfAChainFileAndDropsPrivateKeys() throws Exception {
Path tlsDir = tempDir.resolve("tls");
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("floci", List.of("floci"),
KeyAlgorithm.RSA_2048, null);
Path chainFile = Files.writeString(tempDir.resolve("user-chain.pem"),
leaf.certificatePem() + leaf.privateKeyPem() + ca.caPem());
String bundle = Files.readString(ContainerCaBundle.write(tlsDir, chainFile));
assertFalse(bundle.contains("PRIVATE KEY"), "a private key must never reach a container");
List<X509Certificate> certificates = parseAll(bundle.getBytes());
int size = certificates.size();
assertEquals(ca.certificate(), certificates.get(size - 1));
assertEquals(new CertificateGenerator().parseCertificate(leaf.certificatePem()), certificates.get(size - 2));
}
@Test
void writeRefusesAnAnchorFileWithoutACertificate() throws Exception {
Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));
Path notACertificate = Files.writeString(tempDir.resolve("empty.pem"), "nothing to trust here\n");
assertThrows(IllegalArgumentException.class, () -> ContainerCaBundle.write(tlsDir, notACertificate));
assertFalse(Files.exists(tlsDir.resolve("floci-ca-bundle.pem")));
}
@Test
void hostPathIsEmptyWhenTlsIsOff() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.tls().enabled()).thenReturn(false);
when(config.storage().persistentPath()).thenReturn(tempDir.toString());
assertEquals(Optional.empty(), ContainerCaBundle.hostPath(config));
}
@Test
void hostPathIsEmptyWhenTheBootWriteDidNotHappen() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.tls().enabled()).thenReturn(true);
when(config.storage().persistentPath()).thenReturn(tempDir.toString());
assertEquals(Optional.empty(), ContainerCaBundle.hostPath(config));
}
@Test
void hostPathFindsTheBundleUnderTheConfiguredPersistentPath() throws Exception {
Path tlsDir = tempDir.resolve("tls");
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
Path bundle = ContainerCaBundle.write(tlsDir, ca.certificatePath());
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.tls().enabled()).thenReturn(true);
when(config.storage().persistentPath()).thenReturn(tempDir.toString());
assertEquals(Optional.of(bundle), ContainerCaBundle.hostPath(config));
}
@Test
void hostPathFollowsTheDirectoryTheBootstrapUsed() throws Exception {
// application.yml alone may name a persistent path the bootstrap never saw; the bundle
// lives where TlsConfigSource wrote it, next to the CA.
Path bootDir = tempDir.resolve("boot");
System.setProperty("floci.tls.enabled", "true");
System.setProperty("floci.tls.self-signed", "true");
System.setProperty("floci.storage.persistent-path", bootDir.toString());
try {
new TlsConfigSource();
} finally {
System.clearProperty("floci.tls.enabled");
System.clearProperty("floci.tls.self-signed");
System.clearProperty("floci.storage.persistent-path");
}
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.tls().enabled()).thenReturn(true);
when(config.storage().persistentPath()).thenReturn(tempDir.resolve("elsewhere").toString());
assertEquals(Optional.of(bootDir.resolve("tls").resolve("floci-ca-bundle.pem")),
ContainerCaBundle.hostPath(config));
}
@Test
void hostPathFollowsTheDirectoryOfAUserCertificateBoot() throws Exception {
Path bootDir = tempDir.resolve("boot");
CertificateGenerator.GeneratedCertificate user = new CertificateGenerator()
.generateSelfSignedCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);
Path userCert = Files.writeString(tempDir.resolve("user.crt"), user.certificatePem());
Path userKey = Files.writeString(tempDir.resolve("user.key"), user.privateKeyPem());
System.setProperty("floci.tls.enabled", "true");
System.setProperty("floci.tls.cert-path", userCert.toString());
System.setProperty("floci.tls.key-path", userKey.toString());
System.setProperty("floci.storage.persistent-path", bootDir.toString());
try {
new TlsConfigSource();
} finally {
System.clearProperty("floci.tls.enabled");
System.clearProperty("floci.tls.cert-path");
System.clearProperty("floci.tls.key-path");
System.clearProperty("floci.storage.persistent-path");
}
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.tls().enabled()).thenReturn(true);
when(config.storage().persistentPath()).thenReturn(tempDir.resolve("elsewhere").toString());
assertEquals(Optional.of(bootDir.resolve("tls").resolve("floci-ca-bundle.pem")),
ContainerCaBundle.hostPath(config));
}
@Test
void envPointsEveryRuntimeAtTheContainerPath() {
assertEquals(List.of(
"SSL_CERT_FILE=/etc/floci-ca-bundle.pem",
"CURL_CA_BUNDLE=/etc/floci-ca-bundle.pem",
"REQUESTS_CA_BUNDLE=/etc/floci-ca-bundle.pem",
"NODE_EXTRA_CA_CERTS=/etc/floci-ca-bundle.pem",
"AWS_CA_BUNDLE=/etc/floci-ca-bundle.pem"), ContainerCaBundle.env());
}
@Test
void appendEnvKeepsTheCallerEntriesFirstAndUnchanged() {
List<String> merged = ContainerCaBundle.appendEnv(List.of("FOO=bar", "SSL_CERT_FILE=/my/own.pem", "AWS_CA_BUNDLE"));
assertEquals(List.of("FOO=bar", "SSL_CERT_FILE=/my/own.pem", "AWS_CA_BUNDLE"), merged.subList(0, 3));
assertEquals(List.of(
"CURL_CA_BUNDLE=/etc/floci-ca-bundle.pem",
"REQUESTS_CA_BUNDLE=/etc/floci-ca-bundle.pem",
"NODE_EXTRA_CA_CERTS=/etc/floci-ca-bundle.pem"), merged.subList(3, merged.size()));
}
@Test
void appendEnvOfNothingIsTheTrustEnv() {
assertEquals(ContainerCaBundle.env(), ContainerCaBundle.appendEnv(null));
assertEquals(ContainerCaBundle.env(), ContainerCaBundle.appendEnv(List.of()));
}
private static List<X509Certificate> parseAll(byte[] pem) throws Exception {
List<X509Certificate> certificates = new ArrayList<>();
for (var certificate : CertificateFactory.getInstance("X.509").generateCertificates(new ByteArrayInputStream(pem))) {
certificates.add((X509Certificate) certificate);
}
return certificates;
}
}
@@ -377,7 +377,7 @@ class TlsCertificateHostnameTest {
}
@Test
void resolvedTlsDirIsClearedByABootThatDoesNotIssueALeaf() throws Exception {
void resolvedTlsDirFollowsEveryTlsOnBootAndIsClearedWhenTlsIsOff() throws Exception {
System.setProperty("floci.tls.enabled", "true");
System.setProperty("floci.tls.self-signed", "true");
System.setProperty("floci.storage.persistent-path", tempDir.toString());
@@ -397,7 +397,8 @@ class TlsCertificateHostnameTest {
System.setProperty("floci.tls.cert-path", userCert.toString());
System.setProperty("floci.tls.key-path", userKey.toString());
new TlsConfigSource();
assertNull(TlsConfigSource.resolvedTlsDir(), "user certificate: nothing was laid down");
assertEquals(tempDir.resolve("tls"), TlsConfigSource.resolvedTlsDir(),
"user certificate: the container CA bundle was laid down there");
}
@Test
@@ -0,0 +1,101 @@
package io.github.hectorvent.floci.config;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.junit.jupiter.api.AfterEach;
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.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link TlsConfigSource} writes the container CA bundle at boot, in both certificate modes, and
* a bundle that cannot be written never stops the boot.
*/
class TlsConfigSourceContainerCaBundleTest {
@TempDir
Path tempDir;
@AfterEach
void clearSystemProperties() {
System.clearProperty("floci.tls.enabled");
System.clearProperty("floci.tls.self-signed");
System.clearProperty("floci.tls.cert-path");
System.clearProperty("floci.tls.key-path");
System.clearProperty("floci.storage.persistent-path");
}
@Test
void selfSignedBootWritesTheBundleEndingWithTheLocalCa() throws Exception {
System.setProperty("floci.tls.enabled", "true");
System.setProperty("floci.tls.self-signed", "true");
System.setProperty("floci.storage.persistent-path", tempDir.toString());
new TlsConfigSource();
Path bundle = tempDir.resolve("tls/floci-ca-bundle.pem");
assertTrue(Files.exists(bundle), "bundle written at boot");
String pem = Files.readString(bundle).strip();
String caPem = Files.readString(tempDir.resolve("tls/floci-root-ca.crt")).strip();
assertTrue(pem.endsWith(caPem), "the local CA is the last entry");
assertTrue(pem.indexOf("-----BEGIN CERTIFICATE-----") < pem.lastIndexOf("-----BEGIN CERTIFICATE-----"),
"public roots precede the CA");
}
@Test
void userCertificateBootWritesTheBundleEndingWithThatCertificate() throws Exception {
Path userDir = Files.createDirectories(tempDir.resolve("user"));
CertificateGenerator.GeneratedCertificate generated = new CertificateGenerator()
.generateSelfSignedCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);
Path userCert = Files.writeString(userDir.resolve("user.crt"), generated.certificatePem());
Path userKey = Files.writeString(userDir.resolve("user.key"), generated.privateKeyPem());
System.setProperty("floci.tls.enabled", "true");
System.setProperty("floci.tls.cert-path", userCert.toString());
System.setProperty("floci.tls.key-path", userKey.toString());
System.setProperty("floci.storage.persistent-path", tempDir.toString());
new TlsConfigSource();
String pem = Files.readString(tempDir.resolve("tls/floci-ca-bundle.pem")).strip();
assertTrue(pem.endsWith(generated.certificatePem().strip()));
assertFalse(Files.exists(tempDir.resolve("tls/floci-root-ca.crt")), "custom-cert mode creates no CA");
assertEquals(tempDir.resolve("tls"), TlsConfigSource.resolvedTlsDir(), "CDI consumers look where the boot wrote");
}
@Test
void tlsOffWritesNoBundle() {
System.setProperty("floci.tls.enabled", "false");
System.setProperty("floci.storage.persistent-path", tempDir.toString());
new TlsConfigSource();
assertFalse(Files.exists(tempDir.resolve("tls")));
}
@Test
void aBundleThatCannotBeWrittenDoesNotStopTheBoot() throws Exception {
Path userDir = Files.createDirectories(tempDir.resolve("user"));
CertificateGenerator.GeneratedCertificate generated = new CertificateGenerator()
.generateSelfSignedCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);
Path userCert = Files.writeString(userDir.resolve("user.crt"), generated.certificatePem());
Path userKey = Files.writeString(userDir.resolve("user.key"), generated.privateKeyPem());
Path persistent = Files.createDirectories(tempDir.resolve("data"));
Files.writeString(persistent.resolve("tls"), "a file where the tls directory should be");
System.setProperty("floci.tls.enabled", "true");
System.setProperty("floci.tls.cert-path", userCert.toString());
System.setProperty("floci.tls.key-path", userKey.toString());
System.setProperty("floci.storage.persistent-path", persistent.toString());
TlsConfigSource source = new TlsConfigSource();
assertEquals(userCert.toString(), source.getValue("quarkus.tls.key-store.pem.0.cert"));
assertTrue(Files.isRegularFile(persistent.resolve("tls")), "the boot left the obstacle alone");
}
}
@@ -30,7 +30,8 @@ import static org.hamcrest.Matchers.is;
*
* <p>Generates a cert/key pair in the static initializer (before Quarkus starts),
* then configures the profile to use those paths for both floci config and
* Quarkus SSL properties.
* Quarkus SSL properties. The certificate file also carries the private key, the combined
* form OpenSSL tooling produces, so the tests prove that key never leaves the host.
*/
@QuarkusTest
@TestProfile(TlsUserCertIntegrationTest.UserCertProfile.class)
@@ -68,18 +69,20 @@ class TlsUserCertIntegrationTest {
.contentType(org.hamcrest.Matchers.startsWith("text/plain"))
.extract().asString();
String userPem = Files.readString(UserCertProfile.CERT_FILE);
org.junit.jupiter.api.Assertions.assertTrue(pem.startsWith(userPem),
"the user certificate, which signs the HTTPS endpoint, comes first");
org.junit.jupiter.api.Assertions.assertFalse(pem.contains("PRIVATE KEY"),
"the key stored next to the certificate must never be served");
var bundle = java.security.cert.CertificateFactory.getInstance("X.509")
.generateCertificates(new java.io.ByteArrayInputStream(pem.getBytes(java.nio.charset.StandardCharsets.US_ASCII)))
.stream().map(java.security.cert.X509Certificate.class::cast).toList();
org.junit.jupiter.api.Assertions.assertEquals(2, bundle.size(), "user certificate plus the local CA");
org.junit.jupiter.api.Assertions.assertEquals(
new CertificateGenerator().parseCertificate(Files.readString(UserCertProfile.CERT_FILE)), bundle.get(0),
"the user certificate, which signs the HTTPS endpoint, comes first");
java.security.cert.X509Certificate localCa = bundle.get(1);
org.junit.jupiter.api.Assertions.assertTrue(localCa.getBasicConstraints() >= 0, "the local CA is a CA");
org.junit.jupiter.api.Assertions.assertEquals("CN=Floci Local CA", localCa.getSubjectX500Principal().getName());
org.junit.jupiter.api.Assertions.assertEquals(Files.readString(
Path.of("/tmp/floci-tls-usercert-test-data/tls/floci-root-ca.crt")), pem.substring(userPem.length()).stripLeading(),
org.junit.jupiter.api.Assertions.assertTrue(pem.endsWith(Files.readString(
Path.of("/tmp/floci-tls-usercert-test-data/tls/floci-root-ca.crt"))),
"the local CA served is the one on disk");
}
@@ -107,9 +110,6 @@ class TlsUserCertIntegrationTest {
}
private static void generateCertIfNeeded() {
if (Files.exists(CERT_FILE) && Files.exists(KEY_FILE)) {
return;
}
try {
Files.createDirectories(CERT_DIR);
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
@@ -118,7 +118,7 @@ class TlsUserCertIntegrationTest {
CertificateGenerator gen = new CertificateGenerator();
CertificateGenerator.GeneratedCertificate cert = gen.generateSelfSignedCertificate(
"localhost", List.of("localhost", "127.0.0.1"), KeyAlgorithm.RSA_2048);
Files.writeString(CERT_FILE, cert.certificatePem());
Files.writeString(CERT_FILE, cert.certificatePem() + cert.privateKeyPem());
Files.writeString(KEY_FILE, cert.privateKeyPem());
} catch (IOException e) {
throw new RuntimeException("Failed to generate test cert", e);
@@ -0,0 +1,165 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.core.command.WaitContainerResultCallback;
import io.github.hectorvent.floci.config.ContainerCaBundle;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* A container Floci launches, with no setup of its own, calls Floci over HTTPS and a public
* HTTPS site. Python is the runtime because it honours {@code SSL_CERT_FILE}, the variable that
* replaces the trust store: the image's own root directory is pointed away, so if the bundle
* lacked the public roots the second call would fail, and if it lacked the Floci CA the first
* would. Skipped without a Docker daemon, like the other {@code *DockerIntegrationTest} classes.
*/
@QuarkusTest
@TestProfile(ContainerCaBundleDockerIntegrationTest.Profile.class)
class ContainerCaBundleDockerIntegrationTest {
private static final String IMAGE = "public.ecr.aws/docker/library/python:3.12-alpine";
@Inject
DockerClient dockerClient;
@Inject
ContainerBuilder containerBuilder;
@Inject
ContainerLifecycleManager lifecycle;
@Inject
ContainerDetector containerDetector;
@ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")
int testSslPort;
@BeforeEach
void requireDockerOnTheHost() {
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available");
Assumptions.assumeFalse(containerDetector.isRunningInContainer(),
"the container dials host.docker.internal, which only names a host-side Floci");
}
@Test
void launchedContainerTrustsFlociAndPublicRootsWithoutAnySetup() throws Exception {
String script = """
import os, urllib.request, urllib.error
bundle = "/etc/floci-ca-bundle.pem"
for var in ("SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "NODE_EXTRA_CA_CERTS", "AWS_CA_BUNDLE"):
assert os.environ.get(var) == bundle, (var, os.environ.get(var))
assert open(bundle).read().count("BEGIN CERTIFICATE") > 1, "bundle must hold public roots and the Floci CA"
ca = urllib.request.urlopen("https://host.docker.internal:%d/_floci/ca.pem", timeout=20).read()
assert b"BEGIN CERTIFICATE" in ca, ca[:80]
try:
urllib.request.urlopen("https://public.ecr.aws/", timeout=20).read()
except urllib.error.HTTPError:
pass
print("ok")
""".formatted(testSslPort);
ContainerSpec spec = containerBuilder.newContainer(IMAGE)
.withName("floci-ca-bundle-test-" + Long.toString(System.nanoTime(), 36))
.withHostDockerInternalOnLinux()
// Only the bundle may supply roots: the image's /etc/ssl/certs must not rescue the public call.
.withEnv("SSL_CERT_DIR", "/nonexistent")
.withEntrypoint(List.of("python3", "-c", script))
.build();
ContainerLifecycleManager.ContainerInfo info = lifecycle.createAndStart(spec);
try {
Integer status = dockerClient.waitContainerCmd(info.containerId())
.exec(new WaitContainerResultCallback())
.awaitStatusCode(120, TimeUnit.SECONDS);
assertEquals(0, status, () -> logs(info.containerId()));
} finally {
dockerClient.removeContainerCmd(info.containerId()).withForce(true).exec();
}
}
private String logs(String containerId) {
StringBuilder out = new StringBuilder();
try {
dockerClient.logContainerCmd(containerId).withStdOut(true).withStdErr(true)
.exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
out.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
}
}).awaitCompletion(10, TimeUnit.SECONDS);
} catch (Exception e) {
out.append("(could not read logs: ").append(e.getMessage()).append(')');
}
return out.toString();
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
return true;
} catch (Exception e) {
return false;
}
}
/**
* Lays down what a TLS-on boot writes: the local CA, a leaf whose SANs include the name the
* container dials, and the bundle. The bootstrap config source reads system properties and the
* environment, which a test profile does not set, so the files are prepared here and the
* registry keys point at them; {@code floci.tls.enabled} is what makes the lifecycle manager
* inject the bundle. Quarkus binds every interface so the container reaches the test port.
*/
public static final class Profile implements QuarkusTestProfile {
private static final Path DATA_DIR = Path.of("target", "floci-ca-bundle-docker-test").toAbsolutePath();
private static final Path TLS_DIR = DATA_DIR.resolve("tls");
private static final Path CERT_FILE = TLS_DIR.resolve("floci-server.crt");
private static final Path KEY_FILE = TLS_DIR.resolve("floci-server.key");
static {
try {
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);
var leaf = ca.issueServerCertificate("localhost",
List.of("localhost", "127.0.0.1", "host.docker.internal"), KeyAlgorithm.RSA_2048, null);
Files.writeString(CERT_FILE, leaf.certificatePem());
Files.writeString(KEY_FILE, leaf.privateKeyPem());
ContainerCaBundle.write(TLS_DIR, ca.certificatePath());
} catch (IOException | GeneralSecurityException e) {
throw new IllegalStateException("Failed to prepare the TLS test files", e);
}
}
@Override
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.tls.enabled", "true",
"floci.tls.aws-https-port", "0",
"floci.storage.persistent-path", DATA_DIR.toString(),
"quarkus.tls.key-store.pem.0.cert", CERT_FILE.toString(),
"quarkus.tls.key-store.pem.0.key", KEY_FILE.toString(),
"quarkus.http.insecure-requests", "enabled",
"quarkus.http.host", "0.0.0.0");
}
}
}
@@ -0,0 +1,240 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsConfigSource;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Every emulator-created container passes through {@link ContainerLifecycleManager#create}, so
* asserting the CA trust here covers Lambda, ECS, MWAA, Flink, RDS and the rest by construction.
*/
@ExtendWith(MockitoExtension.class)
class ContainerLifecycleManagerCaBundleTest {
private static final String BUNDLE_PEM = "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n";
@Mock DockerClient dockerClient;
@Mock ImageCacheService imageCacheService;
@Mock ContainerDetector containerDetector;
@Mock PortAllocator portAllocator;
@Mock EmulatorConfig config;
@Mock EmulatorConfig.DockerConfig dockerConfig;
@Mock EmulatorConfig.TlsConfig tlsConfig;
@Mock EmulatorConfig.StorageConfig storageConfig;
@TempDir Path tempDir;
@BeforeEach
void setUp() {
forgetBootstrapTlsDir();
lenient().when(config.docker()).thenReturn(dockerConfig);
lenient().when(dockerConfig.resourceNamespace()).thenReturn(Optional.empty());
lenient().when(config.tls()).thenReturn(tlsConfig);
lenient().when(config.storage()).thenReturn(storageConfig);
lenient().when(storageConfig.persistentPath()).thenReturn(tempDir.toString());
lenient().when(imageCacheService.ensureImageExists(any())).thenAnswer(invocation -> invocation.getArgument(0));
}
@AfterEach
void forgetBootstrapTlsDir() {
// TlsConfigSource.resolvedTlsDir is static: a TLS-on bootstrap run by another test class
// in this JVM would otherwise steer the bundle lookup at that test's directory.
System.setProperty("floci.tls.enabled", "false");
new TlsConfigSource();
System.clearProperty("floci.tls.enabled");
}
@Test
void tlsOnCopiesTheBundleAndAppendsTheTrustEnvAfterTheSpecEnv() throws Exception {
when(tlsConfig.enabled()).thenReturn(true);
Path bundle = writeBundle();
CreateContainerCmd createCmd = stubCreateContainer();
CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(dockerClient.copyArchiveToContainerCmd("container-id")).thenReturn(copyCmd);
assertEquals("container-id", manager().create(specWithEnv(List.of("FOO=bar"))));
List<String> env = capturedEnv(createCmd);
assertEquals(List.of("FOO=bar",
"SSL_CERT_FILE=/etc/floci-ca-bundle.pem",
"CURL_CA_BUNDLE=/etc/floci-ca-bundle.pem",
"REQUESTS_CA_BUNDLE=/etc/floci-ca-bundle.pem",
"NODE_EXTRA_CA_CERTS=/etc/floci-ca-bundle.pem",
"AWS_CA_BUNDLE=/etc/floci-ca-bundle.pem"), env);
verify(copyCmd).withRemotePath("/etc");
ArgumentCaptor<InputStream> tar = ArgumentCaptor.forClass(InputStream.class);
verify(copyCmd).withTarInputStream(tar.capture());
verify(copyCmd).exec();
try (TarArchiveInputStream in = new TarArchiveInputStream(tar.getValue())) {
TarArchiveEntry entry = in.getNextEntry();
assertEquals("floci-ca-bundle.pem", entry.getName());
assertEquals(0644, entry.getMode() & 0777, "world-readable, so a non-root USER can read it");
assertEquals(Files.readString(bundle), new String(in.readAllBytes(), StandardCharsets.UTF_8));
assertNull(in.getNextEntry(), "the archive holds only the bundle");
}
}
@Test
void specValuesWinOverTheInjectedEnv() throws Exception {
when(tlsConfig.enabled()).thenReturn(true);
writeBundle();
CreateContainerCmd createCmd = stubCreateContainer();
when(dockerClient.copyArchiveToContainerCmd("container-id"))
.thenReturn(mock(CopyArchiveToContainerCmd.class, RETURNS_SELF));
manager().create(specWithEnv(List.of("SSL_CERT_FILE=/my/own.pem", "NODE_EXTRA_CA_CERTS=")));
List<String> env = capturedEnv(createCmd);
assertEquals(1, env.stream().filter(e -> e.startsWith("SSL_CERT_FILE=")).count());
assertEquals(1, env.stream().filter(e -> e.startsWith("NODE_EXTRA_CA_CERTS=")).count());
assertTrue(env.contains("SSL_CERT_FILE=/my/own.pem"));
assertTrue(env.contains("NODE_EXTRA_CA_CERTS="));
assertTrue(env.contains("AWS_CA_BUNDLE=/etc/floci-ca-bundle.pem"));
}
@Test
void anEmptySpecEnvStillGetsTheTrustEnv() throws Exception {
when(tlsConfig.enabled()).thenReturn(true);
writeBundle();
CreateContainerCmd createCmd = stubCreateContainer();
when(dockerClient.copyArchiveToContainerCmd("container-id"))
.thenReturn(mock(CopyArchiveToContainerCmd.class, RETURNS_SELF));
manager().create(new ContainerSpec("busybox:stable"));
assertEquals(5, capturedEnv(createCmd).size());
}
@Test
void tlsOffLeavesTheContainerAlone() {
when(tlsConfig.enabled()).thenReturn(false);
CreateContainerCmd createCmd = stubCreateContainer();
manager().create(specWithEnv(List.of("FOO=bar")));
assertEquals(List.of("FOO=bar"), capturedEnv(createCmd));
verify(dockerClient, never()).copyArchiveToContainerCmd(anyString());
}
@Test
void tlsOffWithNoEnvSetsNoEnvAtAll() {
when(tlsConfig.enabled()).thenReturn(false);
CreateContainerCmd createCmd = stubCreateContainer();
manager().create(new ContainerSpec("busybox:stable"));
verify(createCmd, never()).withEnv(any(List.class));
verify(dockerClient, never()).copyArchiveToContainerCmd(anyString());
}
@Test
void aMissingBundleMeansNoEnvAndNoCopy() {
when(tlsConfig.enabled()).thenReturn(true);
CreateContainerCmd createCmd = stubCreateContainer();
manager().create(specWithEnv(List.of("FOO=bar")));
assertEquals(List.of("FOO=bar"), capturedEnv(createCmd));
verify(dockerClient, never()).copyArchiveToContainerCmd(anyString());
}
@Test
void aFailedCopyRecreatesTheContainerWithoutTheTrustVariables() throws Exception {
// SSL_CERT_FILE and friends replace the image's trust store, so they must never name a
// file that is not there: an image without /etc keeps its own trust instead.
when(tlsConfig.enabled()).thenReturn(true);
writeBundle();
CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF);
when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd);
CreateContainerResponse first = mock(CreateContainerResponse.class);
when(first.getId()).thenReturn("container-id");
CreateContainerResponse second = mock(CreateContainerResponse.class);
when(second.getId()).thenReturn("container-id-2");
when(createCmd.exec()).thenReturn(first, second);
CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(dockerClient.copyArchiveToContainerCmd("container-id")).thenReturn(copyCmd);
when(copyCmd.exec()).thenThrow(new NotFoundException("Could not find the file /etc in container"));
RemoveContainerCmd removeCmd = mock(RemoveContainerCmd.class, RETURNS_SELF);
when(dockerClient.removeContainerCmd("container-id")).thenReturn(removeCmd);
assertEquals("container-id-2", manager().create(specWithEnv(List.of("FOO=bar"))));
verify(removeCmd).withForce(true);
verify(removeCmd).exec();
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> env = ArgumentCaptor.forClass((Class<List<String>>) (Class<?>) List.class);
verify(createCmd, times(2)).withEnv(env.capture());
assertEquals(6, env.getAllValues().get(0).size(), "the first attempt carried the trust variables");
assertEquals(List.of("FOO=bar"), env.getAllValues().get(1), "the retry carries only the spec's own");
verify(dockerClient, times(1)).copyArchiveToContainerCmd(anyString());
verify(portAllocator, never()).allocateAny();
}
private Path writeBundle() throws Exception {
Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));
return Files.writeString(tlsDir.resolve("floci-ca-bundle.pem"), BUNDLE_PEM);
}
private ContainerLifecycleManager manager() {
return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, portAllocator, config);
}
private static ContainerSpec specWithEnv(List<String> env) {
return new ContainerSpec("busybox:stable", null, env, null, null, null, Map.of(), List.of(), null,
List.of(), List.of(), List.of(), Map.of(), null, false, null, List.of(), null, null, List.of());
}
private CreateContainerCmd stubCreateContainer() {
CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF);
when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd);
CreateContainerResponse response = mock(CreateContainerResponse.class);
when(response.getId()).thenReturn("container-id");
when(createCmd.exec()).thenReturn(response);
return createCmd;
}
@SuppressWarnings("unchecked")
private static List<String> capturedEnv(CreateContainerCmd createCmd) {
ArgumentCaptor<List<String>> env = ArgumentCaptor.forClass((Class<List<String>>) (Class<?>) List.class);
verify(createCmd).withEnv(env.capture());
return env.getValue();
}
}
@@ -63,9 +63,13 @@ class ContainerLifecycleManagerLabelsTest {
@Mock
EmulatorConfig.DockerConfig dockerConfig;
@Mock
EmulatorConfig.TlsConfig tlsConfig;
@BeforeEach
void setUp() {
lenient().when(config.docker()).thenReturn(dockerConfig);
lenient().when(config.tls()).thenReturn(tlsConfig);
lenient().when(dockerConfig.resourceNamespace()).thenReturn(Optional.empty());
lenient().when(imageCacheService.ensureImageExists(any()))
.thenAnswer(invocation -> invocation.getArgument(0));
@@ -80,6 +80,36 @@ class CloudFormationIntegrationTest {
}
}
/**
* DeleteStack answers before the stack is gone: the deletion runs on an executor. Waits until
* DescribeStacks reports DELETE_COMPLETE or no longer knows the stack, and fails on DELETE_FAILED
* or after ten seconds, so a test can assert on the deleted resources afterwards.
*/
private static void awaitStackDeleted(String stackNameOrArn) {
long deadline = System.currentTimeMillis() + 10_000;
while (System.currentTimeMillis() < deadline) {
String statusXml = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackNameOrArn)
.when()
.post("/")
.then()
.extract().body().asString();
assertThat(statusXml, not(containsString("<StackStatus>DELETE_FAILED</StackStatus>")));
if (statusXml.contains("<StackStatus>DELETE_COMPLETE</StackStatus>") || statusXml.contains("does not exist")) {
return;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AssertionError("Interrupted while waiting for stack " + stackNameOrArn + " to be deleted", e);
}
}
throw new AssertionError("Stack " + stackNameOrArn + " did not reach DELETE_COMPLETE within timeout");
}
private static String firstPhysicalResourceId(String xml) {
assertThat(xml, containsString("<PhysicalResourceId>"));
String startMarker = "<PhysicalResourceId>";
@@ -2006,26 +2036,7 @@ class CloudFormationIntegrationTest {
.then()
.statusCode(200);
long deadline = System.currentTimeMillis() + 10_000;
while (System.currentTimeMillis() < deadline) {
String statusXml = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", "cfn-1668-delete-stack")
.when()
.post("/")
.then()
.extract().body().asString();
assertThat(statusXml, not(containsString("<StackStatus>DELETE_FAILED</StackStatus>")));
if (statusXml.contains("<StackStatus>DELETE_COMPLETE</StackStatus>")
|| statusXml.contains("does not exist")) {
return;
}
Thread.sleep(200);
}
throw new AssertionError("Stack did not reach DELETE_COMPLETE within timeout");
awaitStackDeleted("cfn-1668-delete-stack");
}
// Regression: issue #1966. A resource removed outside CloudFormation must be treated as
@@ -2108,24 +2119,7 @@ class CloudFormationIntegrationTest {
.then()
.statusCode(200);
long deleteDeadline = System.currentTimeMillis() + 10_000;
while (System.currentTimeMillis() < deleteDeadline) {
String statusXml = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackArn)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
if (statusXml.contains("<StackStatus>DELETE_COMPLETE</StackStatus>")) {
return;
}
assertThat(statusXml, not(containsString("<StackStatus>DELETE_FAILED</StackStatus>")));
Thread.sleep(200);
}
throw new AssertionError("Stack did not reach DELETE_COMPLETE within timeout");
awaitStackDeleted(stackArn);
}
@Test
@@ -4766,22 +4760,7 @@ class CloudFormationIntegrationTest {
.then()
.statusCode(200);
// Wait for async stack deletion to complete
long deadline = System.currentTimeMillis() + 10_000;
while (System.currentTimeMillis() < deadline) {
String deleteStatus = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.extract().body().asString();
if (deleteStatus.contains("DELETE_COMPLETE") || deleteStatus.contains("does not exist")) {
break;
}
Thread.sleep(200);
}
awaitStackDeleted(stackName);
given()
.when()
@@ -6433,6 +6412,8 @@ class CloudFormationIntegrationTest {
.then()
.statusCode(200);
awaitStackDeleted(stackName);
// 6. Verify resources are deleted
given()
.header("X-Amz-Target", "AWSCognitoIdentityProviderService.DescribeUserPool")
@@ -7078,6 +7059,7 @@ class CloudFormationIntegrationTest {
.formParam("StackName", stackName)
.when().post("/")
.then().statusCode(200);
awaitStackDeleted(stackName);
given()
.formParam("Action", "DescribeSecurityGroups")
@@ -7168,6 +7150,8 @@ class CloudFormationIntegrationTest {
.then()
.statusCode(200);
awaitStackDeleted(stackName);
// Cluster is gone (deleted in reverse order, after the service)
given()
.header("X-Amz-Target", ECS_TARGET_PREFIX + "DescribeClusters")
@@ -7522,6 +7506,8 @@ class CloudFormationIntegrationTest {
.then()
.statusCode(200);
awaitStackDeleted(stackName);
// Load balancer is gone
given()
.formParam("Action", "DescribeLoadBalancers")
@@ -9861,6 +9847,7 @@ class CloudFormationIntegrationTest {
.post("/")
.then()
.statusCode(200);
awaitStackDeleted(stackName);
given().when().delete("/" + bucket + "/" + key).then().statusCode(204);
given().when().delete("/" + bucket).then().statusCode(204);
}
@@ -10726,6 +10713,7 @@ class CloudFormationIntegrationTest {
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200);
awaitStackDeleted(stackName);
String workingTemplate = """
{
@@ -11231,6 +11219,7 @@ class CloudFormationIntegrationTest {
.formParam("Action", "DeleteStack")
.formParam("StackName", "cfn-teardown-stack")
.when().post("/").then().statusCode(200);
awaitStackDeleted("cfn-teardown-stack");
// The rule is gone from the custom bus...
given()
@@ -240,9 +240,6 @@ 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());
@@ -1,151 +0,0 @@
package io.github.hectorvent.floci.services.lambda.launcher;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
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 HTTPS endpoint through the local CA.
*/
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_localCaUnderPersistentPath() throws Exception {
Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));
Path cert = Files.writeString(tlsDir.resolve("floci-root-ca.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_blankUserCertFallsBackToLocalCa() throws Exception {
Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));
Path cert = Files.writeString(tlsDir.resolve("floci-root-ca.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 = writeLeaf("leaf.crt", "floci-leaf");
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 = writeLeaf("leaf2.crt", "floci-leaf2");
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);
}
/** A server leaf issued by a throwaway CA: its issuer differs from its subject and it is not a CA. */
private Path writeLeaf(String fileName, String commonName) throws Exception {
FlociCertificateAuthority throwawayCa = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("throwaway-ca"));
return writeCert(tempDir.resolve(fileName),
throwawayCa.issueServerCertificate(commonName, List.of(), KeyAlgorithm.RSA_2048, null).certificatePem());
}
}
@@ -107,9 +107,6 @@ 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.defaultAccountId()).thenReturn("000000000000");
lenient().when(config.hostname()).thenReturn(Optional.empty());
@@ -6,6 +6,7 @@ import io.fabric8.kubernetes.api.model.PodStatusBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.server.mock.EnableKubernetesMockClient;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsConfigSource;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.services.lambda.LambdaLayerService;
@@ -19,12 +20,15 @@ import io.github.hectorvent.floci.services.s3.S3Service;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.URI;
import java.net.http.HttpClient;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.time.Duration;
@@ -62,6 +66,9 @@ import static org.mockito.Mockito.when;
class KubernetesPodLauncherTest {
KubernetesClient client;
@TempDir
Path tempDir;
private KubernetesApiClient apiClient;
private EmulatorConfig config;
private RuntimeApiServerFactory runtimeApiServerFactory;
@@ -446,4 +453,42 @@ class KubernetesPodLauncherTest {
private ContainerHandle handleFor(String podName) {
return new ContainerHandle(podName, "my-fn", runtimeApiServer, ContainerState.WARM);
}
@Test
void tlsOnPublishesTheCaBundleAsAConfigMapAndTheFunctionEnvWins() throws Exception {
String bundlePem = enableTlsWithBundle();
markPodPhaseInBackground("floci-lambda-my-fn-", "Running");
var fn = function();
fn.setEnvironment(Map.of("SSL_CERT_FILE", "/my/own.pem"));
var handle = launcher.launch(fn);
var configMap = client.configMaps().inNamespace("default").withName(KubernetesPodLauncher.CA_CONFIG_MAP_NAME).get();
assertThat(configMap.getData()).containsEntry(KubernetesPodLauncher.CA_CONFIG_MAP_KEY, bundlePem);
var env = client.pods().inNamespace("default").withName(handle.getContainerId()).get()
.getSpec().getContainers().getFirst().getEnv();
assertThat(env).extracting(EnvVar::getName, EnvVar::getValue).contains(
tuple("SSL_CERT_FILE", "/my/own.pem"),
tuple("CURL_CA_BUNDLE", "/etc/floci-ca-bundle.pem"),
tuple("REQUESTS_CA_BUNDLE", "/etc/floci-ca-bundle.pem"),
tuple("NODE_EXTRA_CA_CERTS", "/etc/floci-ca-bundle.pem"),
tuple("AWS_CA_BUNDLE", "/etc/floci-ca-bundle.pem"));
assertThat(env).extracting(EnvVar::getName).containsOnlyOnce("SSL_CERT_FILE");
}
/** TLS on with a bundle under {@link #tempDir}, the file the boot would have written; returns its PEM. */
private String enableTlsWithBundle() throws Exception {
System.setProperty("floci.tls.enabled", "false");
new TlsConfigSource(); // forgets the static directory a TLS-on bootstrap in another test class left behind
System.clearProperty("floci.tls.enabled");
var tls = mock(EmulatorConfig.TlsConfig.class);
var storage = mock(EmulatorConfig.StorageConfig.class);
when(config.tls()).thenReturn(tls);
when(tls.enabled()).thenReturn(true);
when(config.storage()).thenReturn(storage);
when(storage.persistentPath()).thenReturn(tempDir.toString());
String bundlePem = "-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n";
Files.writeString(Files.createDirectories(tempDir.resolve("tls")).resolve("floci-ca-bundle.pem"), bundlePem);
return bundlePem;
}
}
@@ -225,9 +225,9 @@ class LambdaPodSpecFactoryTest {
}
@Test
void tlsMountsCaCertAndStillDownloadsWithPlainWget() {
void tlsMountsTheCaBundleAndStillDownloadsWithPlainWget() {
// Downloads stay plain HTTP even in TLS mode (busybox wget cannot TLS-handshake
// with Floci); the CA mount is for SDK calls made from inside the function.
// with Floci); the CA bundle mount is for HTTPS calls made from inside the function.
when(tls.enabled()).thenReturn(true);
var pod = factory.buildPod("floci-lambda-my-fn-abc12345", "my-fn",
"public.ecr.aws/lambda/python:3.12",
@@ -245,7 +245,7 @@ class LambdaPodSpecFactoryTest {
assertThat(elements(elements(spec.path("containers")).getFirst().path("volumeMounts")))
.anySatisfy(volumeMount -> {
assertThat(volumeMount.path("name").asText()).isEqualTo("floci-ca");
assertThat(volumeMount.path("mountPath").asText()).isEqualTo("/etc/floci-ca.crt");
assertThat(volumeMount.path("mountPath").asText()).isEqualTo("/etc/floci-ca-bundle.pem");
assertThat(volumeMount.path("subPath").asText())
.isEqualTo(KubernetesPodLauncher.CA_CONFIG_MAP_KEY);
});