Skip to content

armgit / floci

Public Imported from GitHub
0

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

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

Mario Toffia024bfa0a5c5d
diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh
index c74ea5c2d9..455c9bd015 100755
--- a/.github/ci/prefetch-images.sh
+++ b/.github/ci/prefetch-images.sh
@@ -20,4 +20,5 @@ grep -q '/elasticache/' "$SHARD_FILE" && { pull valkey/valkey:8; pull memcached:
grep -q '/memorydb/' "$SHARD_FILE" && pull valkey/valkey:8
grep -q '/ecr/' "$SHARD_FILE" && pull registry:2
grep -q '/ec2/' "$SHARD_FILE" && { pull busybox:stable; pull alpine:latest; }
+grep -q '/common/docker/' "$SHARD_FILE" && pull public.ecr.aws/docker/library/python:3.12-alpine
exit 0
diff --git a/docs/configuration/tls.md b/docs/configuration/tls.md
index 64a58a8fad..970b9b0efa 100644
--- a/docs/configuration/tls.md
+++ b/docs/configuration/tls.md
@@ -8,7 +8,7 @@ Floci supports optional TLS, enabling `https://` for all REST/JSON/Query endpoin
docker run -e FLOCI_TLS_ENABLED=true -p 4566:4566 floci/floci:latest
```
-Then point your SDK at `https://localhost:4566` and trust Floci's local CA in the processes that talk to it. Every certificate Floci issues (its HTTPS endpoint, IoT device certificates, and in a later release ACM certificates) chains to that one CA:
+Then point your SDK at `https://localhost:4566` and trust Floci's local CA in the processes that talk to it. Every certificate Floci issues (its HTTPS endpoint, every ACM certificate and every IoT device certificate) chains to that one CA:
```bash
curl -s http://localhost:4566/_floci/ca.pem -o floci-root-ca.pem
@@ -85,6 +85,18 @@ services:
The generated certificate will include `floci` in its SANs, so TLS validation succeeds when `app` connects to `https://floci:4566`. Fetch `ca.pem` from Floci into `app` (an entrypoint `curl`, or a shared volume mounted from `{persistent-path}/tls/`) so the bundle path above exists.
+### Custom Domains Learned at Runtime
+
+A wildcard SAN matches one label only, so `*.localhost.floci.io` covers `api.localhost.floci.io` but not `api.dev.localhost.floci.io`. For names like that, Floci can add an exact hostname to the server certificate while it runs: the certificate is reissued by the local CA with the same key and the new name, and the HTTPS listener switches to it at once. No restart, no new CA, nothing new for clients to trust. Learned names are recorded in `{persistent-path}/tls/floci-server.metadata.json`, so they survive restarts and a regeneration after a `FLOCI_HOSTNAME` change; `POST /_floci/state/reset` drops them.
+
+Only a name under a local suffix is accepted: `localhost`, `localhost.floci.io`, `localhost.localstack.cloud`, `FLOCI_HOSTNAME`, the `FLOCI_BASE_URL` host, and every `FLOCI_DNS_EXTRA_SUFFIXES` entry. Any other name is refused with a warning, so a Floci certificate can never cover a public name. This only applies to the generated certificate; a user-provided one is never changed.
+
+Names are added by the custom domain operations: API Gateway `CreateDomainName`, IoT Core `CreateDomainConfiguration` with a `domainName`, and Cognito `CreateUserPoolDomain` with a `CustomDomainConfig`. The AWS operation succeeds either way; a name outside the local suffixes, or a reissue that fails, is logged as a warning.
+
+### Containers Floci Launches
+
+Every container Floci launches, from Lambda functions and ECS or Batch tasks to the Docker backends behind RDS, ElastiCache, MWAA and Flink, and the Kubernetes Lambda pods, receives `/etc/floci-ca-bundle.pem`: the public root CAs the Floci JVM trusts, followed by the Floci CA (or your certificate file when you provide one). `SSL_CERT_FILE`, `CURL_CA_BUNDLE`, `REQUESTS_CA_BUNDLE`, `NODE_EXTRA_CA_CERTS` and `AWS_CA_BUNDLE` point at it, so curl, Python, Node.js, Go, the AWS CLI and the AWS SDKs that read `AWS_CA_BUNDLE` reach both Floci and public HTTPS sites with no setup in the workload. A variable you set on the function or task definition wins over the injected one. The JVM ignores all of these variables, so a Java workload still needs its own trust store, as shown under SDK Configuration Examples. The bundle is written to `{persistent-path}/tls/floci-ca-bundle.pem` at startup; when it is missing, or when an image has no `/etc` to copy it into, the container starts without the variables and Floci logs a warning.
+
## User-Provided Certificates
To use your own certificate (e.g., from a corporate CA or mkcert):
@@ -99,7 +111,7 @@ docker run \
floci/floci:latest
```
-When custom certificate paths are provided, `FLOCI_TLS_SELF_SIGNED` is ignored and the HTTPS server uses your certificate; no server certificate is generated. `GET /_floci/ca.pem` then returns a PEM bundle: your certificate file first, then Floci's local CA, which is created on first use and signs the certificates Floci itself issues (IoT device certificates). Put the CA or the full chain in your certificate file if clients fetch their trust anchor from Floci; a bare leaf only lets them pin that one certificate.
+When custom certificate paths are provided, `FLOCI_TLS_SELF_SIGNED` is ignored and the HTTPS server uses your certificate; no server certificate is generated. `GET /_floci/ca.pem` then returns a PEM bundle: the certificates in your certificate file first (a private key kept in that file is never served), then Floci's local CA, which is created on first use and signs the certificates Floci itself issues (IoT device certificates). Put the CA or the full chain in your certificate file if clients fetch their trust anchor from Floci; a bare leaf only lets them pin that one certificate.
## WebSocket (wss://)
diff --git a/docs/services/lambda.md b/docs/services/lambda.md
index 368cd602ce..998c99256c 100644
--- a/docs/services/lambda.md
+++ b/docs/services/lambda.md
@@ -375,7 +375,7 @@ rules:
- apiGroups: [""]
resources: ["pods/log"]
verbs: ["get", "watch"]
- # Only needed when FLOCI_TLS_ENABLED=true (CA cert is shared via a ConfigMap)
+ # Only needed when FLOCI_TLS_ENABLED=true (the CA bundle is shared via a ConfigMap)
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["create", "get", "update", "patch"]
diff --git a/src/main/java/io/github/hectorvent/floci/config/ContainerCaBundle.java b/src/main/java/io/github/hectorvent/floci/config/ContainerCaBundle.java
new file mode 100644
index 0000000000..cdbec36f56
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/config/ContainerCaBundle.java
@@ -0,0 +1,187 @@
+package io.github.hectorvent.floci.config;
+
+import org.bouncycastle.cert.X509CertificateHolder;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.openssl.PEMParser;
+import org.jboss.logging.Logger;
+
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509TrustManager;
+import java.io.IOException;
+import java.io.StringReader;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * The CA bundle Floci hands to every container it launches, so the workload inside can call Floci
+ * over HTTPS (custom domains included) from any runtime without trusting anything by hand.
+ *
+ * <p>The bundle is the JVM's default trust anchors followed by Floci's own trust anchor: the local
+ * CA, or the user-provided certificate file in custom-certificate mode. Carrying the public roots
+ * is what makes it safe to point the <em>replacing</em> variables ({@code SSL_CERT_FILE},
+ * {@code CURL_CA_BUNDLE}, {@code REQUESTS_CA_BUNDLE}) at it: the workload still reaches public
+ * HTTPS endpoints. {@code NODE_EXTRA_CA_CERTS} appends to Node's roots and {@code AWS_CA_BUNDLE}
+ * only applies to AWS SDK and CLI traffic, so both are harmless with the same file.
+ *
+ * <p>Written by {@link TlsConfigSource} at boot; copied into containers by the Docker lifecycle
+ * manager and mounted from a ConfigMap by the Kubernetes Lambda launcher. Plain class because the
+ * config source runs before CDI exists.
+ */
+public final class ContainerCaBundle {
+
+ private static final Logger LOG = Logger.getLogger(ContainerCaBundle.class);
+
+ public static final String FILE_NAME = "floci-ca-bundle.pem";
+ public static final String CONTAINER_DIR = "/etc";
+ public static final String CONTAINER_PATH = CONTAINER_DIR + "/" + FILE_NAME;
+
+ static final List<String> ENV_KEYS = List.of(
+ "SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "NODE_EXTRA_CA_CERTS", "AWS_CA_BUNDLE");
+
+ /** A missing bundle is a boot-time condition, so it is worth one WARN per process, not one per container. */
+ private static final AtomicBoolean MISSING_BUNDLE_WARNED = new AtomicBoolean();
+
+ private ContainerCaBundle() {
+ }
+
+ /**
+ * Writes {@code tlsDir/floci-ca-bundle.pem}: the JVM's trust anchors, then every certificate in
+ * {@code trustAnchorFile}. 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, so a container created during a boot never
+ * reads a half-written bundle, even when two Floci processes share the directory.
+ *
+ * @throws IllegalArgumentException when the anchor file holds no certificate
+ * @throws IllegalStateException when the JVM has no trust anchors at all: a bundle without
+ * public roots would cut containers off from public HTTPS
+ */
+ public static Path write(Path tlsDir, Path trustAnchorFile) throws IOException, GeneralSecurityException {
+ List<X509Certificate> anchors = parseCertificates(Files.readString(trustAnchorFile));
+ if (anchors.isEmpty()) {
+ throw new IllegalArgumentException(trustAnchorFile + " holds no certificate");
+ }
+ List<X509Certificate> roots = systemRoots();
+ if (roots.isEmpty()) {
+ throw new IllegalStateException("the JVM has no default trust anchors");
+ }
+ StringBuilder pem = new StringBuilder();
+ for (X509Certificate root : roots) {
+ pem.append(toPem(root));
+ }
+ for (X509Certificate anchor : anchors) {
+ pem.append(toPem(anchor));
+ }
+ Files.createDirectories(tlsDir);
+ Path target = tlsDir.resolve(FILE_NAME);
+ Path temp = tlsDir.resolve(FILE_NAME + "." + UUID.randomUUID() + ".tmp");
+ try {
+ Files.writeString(temp, pem.toString());
+ Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
+ } catch (AtomicMoveNotSupportedException e) {
+ Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
+ } finally {
+ Files.deleteIfExists(temp);
+ }
+ LOG.debugv("TLS: container CA bundle {0} holds {1} public roots and {2} Floci anchor(s)",
+ target, roots.size(), anchors.size());
+ return target;
+ }
+
+ /**
+ * The bundle on the Floci host, or empty when TLS is off or the boot did not manage to write
+ * it. Looks in the directory the bootstrap used, next to the CA.
+ */
+ public static Optional<Path> hostPath(EmulatorConfig config) {
+ if (!config.tls().enabled()) {
+ return Optional.empty();
+ }
+ Path bundle = FlociCertificateAuthorityProducer.tlsDir(config).resolve(FILE_NAME);
+ if (!Files.isReadable(bundle)) {
+ if (MISSING_BUNDLE_WARNED.compareAndSet(false, true)) {
+ LOG.warnv("TLS is enabled but {0} is missing; containers launched now will not trust Floci HTTPS", bundle);
+ } else {
+ LOG.debugv("Container CA bundle {0} still missing", bundle);
+ }
+ return Optional.empty();
+ }
+ MISSING_BUNDLE_WARNED.set(false);
+ return Optional.of(bundle);
+ }
+
+ /**
+ * The certificate blocks of a PEM text, re-encoded one after the other; a private key or any
+ * other PEM object in the text is dropped. What Floci hands out from a user-provided certificate
+ * file, for the bundle and for {@code GET /_floci/ca.pem}, goes through here.
+ */
+ public static String certificatePem(String pem) throws IOException, GeneralSecurityException {
+ StringBuilder certificates = new StringBuilder();
+ for (X509Certificate certificate : parseCertificates(pem)) {
+ certificates.append(toPem(certificate));
+ }
+ return certificates.toString();
+ }
+
+ /** The {@code KEY=value} entries that make each runtime read {@link #CONTAINER_PATH}. */
+ public static List<String> env() {
+ return appendEnv(null);
+ }
+
+ /**
+ * {@code env} followed by {@link #env()}, skipping every key the caller already set (with or
+ * without a value), so a value from a function or task definition always wins.
+ */
+ public static List<String> appendEnv(List<String> env) {
+ List<String> merged = new ArrayList<>(env == null ? List.of() : env);
+ for (String key : ENV_KEYS) {
+ if (merged.stream().noneMatch(entry -> entry.equals(key) || entry.startsWith(key + "="))) {
+ merged.add(key + "=" + CONTAINER_PATH);
+ }
+ }
+ return merged;
+ }
+
+ /** Every trust anchor the running JVM accepts by default. */
+ private static List<X509Certificate> systemRoots() throws GeneralSecurityException {
+ TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ factory.init((KeyStore) null);
+ List<X509Certificate> roots = new ArrayList<>();
+ for (var manager : factory.getTrustManagers()) {
+ if (manager instanceof X509TrustManager x509) {
+ roots.addAll(List.of(x509.getAcceptedIssuers()));
+ }
+ }
+ return roots;
+ }
+
+ /** The certificates in a PEM text, in order; keys and any other PEM object are skipped. */
+ private static List<X509Certificate> parseCertificates(String pem) throws IOException, GeneralSecurityException {
+ List<X509Certificate> certificates = new ArrayList<>();
+ JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
+ try (PEMParser parser = new PEMParser(new StringReader(pem))) {
+ for (Object object = parser.readObject(); object != null; object = parser.readObject()) {
+ if (object instanceof X509CertificateHolder holder) {
+ certificates.add(converter.getCertificate(holder));
+ }
+ }
+ }
+ return certificates;
+ }
+
+ private static String toPem(X509Certificate certificate) throws CertificateEncodingException {
+ return "-----BEGIN CERTIFICATE-----\n"
+ + Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(certificate.getEncoded())
+ + "\n-----END CERTIFICATE-----\n";
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityProducer.java b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityProducer.java
index 61ac97195a..2b732580d2 100644
--- a/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityProducer.java
+++ b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityProducer.java
@@ -32,9 +32,10 @@ public class FlociCertificateAuthorityProducer {
/**
* The one TLS directory. {@link TlsConfigSource} runs before CDI and resolves
* {@code floci.storage.persistent-path} from system properties and environment only; when it
- * laid down the CA, every CDI consumer must use exactly that directory, or a persistent path set
+ * ran with TLS on, every CDI consumer must use exactly that directory, or a persistent path set
* in application.yml alone would produce a second CA (served leaf signed by one, ca.pem from
- * the other). With TLS off the bootstrap never ran and the configured path is the only truth.
+ * the other) and lose the container CA bundle it wrote there. With TLS off the bootstrap laid
+ * nothing down and the configured path is the only truth.
*/
static Path tlsDir(EmulatorConfig config) {
Path fromBootstrap = TlsConfigSource.resolvedTlsDir();
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 17dd82782d..a0091e46cc 100644
--- a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java
+++ b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java
@@ -35,6 +35,10 @@ import java.util.Set;
* trust the CA ({@code floci-root-ca.crt}, or {@code GET /_floci/ca.pem}), never the leaf.
*
* <p>
+ * It also writes {@link ContainerCaBundle}, the trust bundle every container Floci launches
+ * receives, next to the certificates.
+ *
+ * <p>
* Both HTTP and HTTPS are served simultaneously (LocalStack parity).
*/
public class TlsConfigSource implements ConfigSource {
@@ -59,9 +63,11 @@ public class TlsConfigSource implements ConfigSource {
private final Map<String, String> properties = new HashMap<>();
/**
- * The directory the most recent bootstrap used for CA and leaf, or null when that bootstrap did
- * not run the self-signed branch (TLS off, or a user-provided certificate). Reset on every
- * construction so a later boot in the same JVM never sees a stale value.
+ * The TLS directory the most recent bootstrap used, or null when that bootstrap ran with TLS
+ * off. With a user-provided certificate it holds the container CA bundle and, once
+ * {@code GET /_floci/ca.pem} is called, the local CA; in self-signed mode the CA and the leaf
+ * as well. Reset on every construction so a later boot in the same JVM never sees a stale
+ * value.
*/
static Path resolvedTlsDir() {
return resolvedTlsDir;
@@ -79,17 +85,20 @@ public class TlsConfigSource implements ConfigSource {
String keyPath = resolveProperty("floci.tls.key-path", "");
String selfSigned = resolveProperty("floci.tls.self-signed", "true");
String persistentPath = resolveProperty("floci.storage.persistent-path", "./data");
+ Path tlsDir = Path.of(persistentPath, TLS_DIR);
+ resolvedTlsDir = tlsDir;
+ Path trustAnchor;
if (!certPath.isBlank() && !keyPath.isBlank()) {
validateFileExists(certPath, "TLS certificate");
validateFileExists(keyPath, "TLS private key");
LOG.infov("TLS: using user-provided certificate: {0}", certPath);
+ trustAnchor = Path.of(certPath);
} else if ("true".equalsIgnoreCase(selfSigned)) {
- Path tlsDir = Path.of(persistentPath, TLS_DIR);
- resolvedTlsDir = tlsDir;
Path certFile = tlsDir.resolve(SERVER_CERT_NAME);
Path keyFile = tlsDir.resolve(SERVER_KEY_NAME);
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
+ trustAnchor = ca.certificatePath();
if (Files.exists(certFile) && Files.exists(keyFile)) {
List<String> currentHostnames = new ArrayList<>(DEFAULT_SAN_HOSTNAMES);
@@ -116,6 +125,8 @@ public class TlsConfigSource implements ConfigSource {
+ "Set FLOCI_TLS_CERT_PATH + FLOCI_TLS_KEY_PATH, or enable FLOCI_TLS_SELF_SIGNED.");
}
+ writeContainerCaBundle(tlsDir, trustAnchor);
+
// The default entry of the Quarkus TLS registry. The HTTP server reads it when no
// quarkus.http.tls-configuration-name is set, and the registry can reload it at runtime.
properties.put("quarkus.tls.key-store.pem.0.cert", certPath);
@@ -246,6 +257,19 @@ public class TlsConfigSource implements ConfigSource {
return sans;
}
+ /**
+ * Containers Floci launches get this bundle copied in (Docker) or mounted (Kubernetes). A
+ * failure here must not stop Floci: log it, and containers simply will not trust Floci HTTPS
+ * until a boot manages to write it.
+ */
+ private static void writeContainerCaBundle(Path tlsDir, Path trustAnchor) {
+ try {
+ ContainerCaBundle.write(tlsDir, trustAnchor);
+ } catch (Exception e) {
+ LOG.warnv(e, "TLS: could not write the container CA bundle under {0}: {1}", tlsDir, e.getMessage());
+ }
+ }
+
private static void validateFileExists(String path, String description) {
if (!Files.isReadable(Path.of(path))) {
throw new IllegalStateException(
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
index df85b6c83d..6c40680e45 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.core.common.docker;
+import io.github.hectorvent.floci.config.ContainerCaBundle;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
import com.github.dockerjava.api.DockerClient;
@@ -21,9 +22,15 @@ import com.github.dockerjava.api.model.Ports;
import com.github.dockerjava.core.command.WaitContainerResultCallback;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.jboss.logging.Logger;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.Closeable;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -121,8 +128,25 @@ public class ContainerLifecycleManager {
private String create(ContainerSpec spec, String resolvedImage, String platform) {
LOG.debugv("Creating container from spec: image={0}, name={1}", spec.image(), spec.name());
+ // Built once: a dynamic port binding allocates its host port here.
HostConfig hostConfig = buildHostConfig(spec);
+ Optional<Path> caBundle = ContainerCaBundle.hostPath(config);
+ if (caBundle.isEmpty()) {
+ return createContainer(spec, resolvedImage, platform, hostConfig, spec.env());
+ }
+ String containerId = createContainer(spec, resolvedImage, platform, hostConfig,
+ ContainerCaBundle.appendEnv(spec.env()));
+ if (copyCaBundle(containerId, caBundle.get())) {
+ return containerId;
+ }
+ // SSL_CERT_FILE and friends replace the image's trust store, so they must never name a
+ // file that is not there. Start over without them: the container keeps its own trust.
+ dockerClient.removeContainerCmd(containerId).withForce(true).exec();
+ return createContainer(spec, resolvedImage, platform, hostConfig, spec.env());
+ }
+ private String createContainer(ContainerSpec spec, String resolvedImage, String platform,
+ HostConfig hostConfig, List<String> env) {
CreateContainerCmd createCmd = dockerClient.createContainerCmd(resolvedImage)
.withHostConfig(hostConfig);
@@ -136,8 +160,8 @@ public class ContainerLifecycleManager {
if (spec.user() != null && !spec.user().isBlank()) {
createCmd.withUser(spec.user());
}
- if (spec.env() != null && !spec.env().isEmpty()) {
- createCmd.withEnv(spec.env());
+ if (env != null && !env.isEmpty()) {
+ createCmd.withEnv(env);
}
if (spec.cmd() != null && !spec.cmd().isEmpty()) {
createCmd.withCmd(spec.cmd());
@@ -162,6 +186,38 @@ public class ContainerLifecycleManager {
return containerId;
}
+ /**
+ * Copies the CA bundle into the created, not yet started, container so runtimes that read
+ * {@code SSL_CERT_FILE} and friends at init find it. 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.
+ * Returns false, after logging why, when the copy failed; an image without {@code /etc} is the
+ * expected reason, and the caller then recreates the container without the trust variables.
+ */
+ private boolean copyCaBundle(String containerId, Path bundle) {
+ try {
+ byte[] content = Files.readAllBytes(bundle);
+ ByteArrayOutputStream archive = new ByteArrayOutputStream(content.length + 1024);
+ try (TarArchiveOutputStream tar = new TarArchiveOutputStream(archive)) {
+ TarArchiveEntry entry = new TarArchiveEntry(ContainerCaBundle.FILE_NAME);
+ entry.setSize(content.length);
+ tar.putArchiveEntry(entry);
+ tar.write(content);
+ tar.closeArchiveEntry();
+ }
+ dockerClient.copyArchiveToContainerCmd(containerId)
+ .withRemotePath(ContainerCaBundle.CONTAINER_DIR)
+ .withTarInputStream(new ByteArrayInputStream(archive.toByteArray()))
+ .exec();
+ LOG.debugv("Copied the CA bundle into container {0} at {1}", containerId, ContainerCaBundle.CONTAINER_PATH);
+ return true;
+ } catch (Exception e) {
+ LOG.warnv(e, "Could not copy the CA bundle into container {0}; creating it again without the trust "
+ + "variables, so it keeps its own trust store and will not trust Floci HTTPS: {1}",
+ containerId, e.getMessage());
+ return false;
+ }
+ }
+
/**
* Starts a previously created container and resolves its endpoints.
*
diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoController.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoController.java
index d4ae5ab52a..611a69ddbc 100644
--- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoController.java
+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoController.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.lifecycle;
+import io.github.hectorvent.floci.config.ContainerCaBundle;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
@@ -18,6 +19,7 @@ import jakarta.ws.rs.POST;
import java.io.IOException;
import java.nio.file.Files;
+import java.security.GeneralSecurityException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
@@ -105,22 +107,21 @@ public class EmulatorInfoController {
* The PEM a client needs to trust Floci. With the default configuration that is the local root
* CA alone: it signs the HTTPS certificate and every certificate Floci issues. With a
* user-provided certificate ({@code floci.tls.cert-path}) the HTTPS endpoint is signed by that
- * certificate's issuer instead, so the response is a bundle: the user certificate file first
- * (the same file the Lambda launcher mounts into containers), then the local CA, which still
- * signs what Floci itself issues. Trust the file once ({@code AWS_CA_BUNDLE},
+ * certificate's issuer instead, so the response is a bundle: the certificates in the user
+ * certificate file first (never a private key that file may also hold), then the local CA,
+ * which still signs what Floci itself issues. Trust the file once ({@code AWS_CA_BUNDLE},
* {@code NODE_EXTRA_CA_CERTS}, a keychain) and both validate.
*/
@GET
@Path("/ca.pem")
@Produces(MediaType.TEXT_PLAIN)
- public String caPem() throws IOException {
+ public String caPem() throws IOException, GeneralSecurityException {
String localCa = certificateAuthority.caPem();
Optional<String> userCertificate = userCertificatePath();
if (userCertificate.isEmpty()) {
return localCa;
}
- String userPem = Files.readString(java.nio.file.Path.of(userCertificate.get()));
- return userPem.endsWith("\n") ? userPem + localCa : userPem + "\n" + localCa;
+ return ContainerCaBundle.certificatePem(Files.readString(java.nio.file.Path.of(userCertificate.get()))) + localCa;
}
/** Set when TLS serves a user-provided certificate, the same condition {@code TlsConfigSource} applies. */
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 a2a1cbce3d..ccbd440290 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
@@ -41,8 +41,6 @@ import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
@@ -97,18 +95,6 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
return configured;
}
- /**
- * In-container location of Floci's CA certificate, injected when TLS is enabled so the
- * container trusts Floci's HTTPS endpoint through the local CA. {@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";
- /** Shared with the kubernetes executor, which mounts the CA ConfigMap at the same path. */
- public static final String FLOCI_CA_CONTAINER_PATH = FLOCI_CA_DIR + "/" + FLOCI_CA_FILE_NAME;
- /** Root CA produced by {@code FlociCertificateAuthority} under {persistent-path}/tls/. */
- private static final String LOCAL_CA_CERT_NAME = io.github.hectorvent.floci.config.FlociCertificateAuthority.CA_CERT_NAME;
-
private static final DateTimeFormatter LOG_STREAM_DATE_FMT = DateTimeFormatter.ofPattern("yyyy/MM/dd");
private final ContainerBuilder containerBuilder;
@@ -228,13 +214,6 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
String lambdaRegion = extractRegionFromArn(fn.getFunctionArn(), config.defaultRegion());
String lambdaAccountId = AwsArnUtils.accountOrDefault(fn.getFunctionArn(), config.defaultAccountId());
- // When TLS is on, the container must trust Floci's local CA 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);
@@ -258,7 +237,6 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
env.addAll(awsEnv.sdkBaselineEnv(lambdaRegion,
awsConfigPath.isPresent() ? Optional.of("/opt/aws-config") : Optional.empty(),
roleCredentials, lambdaAccountId));
- env.addAll(flociCaEnv(flociCaCert));
if (fn.getEnvironment() != null) {
boolean hasExecutionRoleCredentials = roleCredentials.isPresent();
boolean userDefinesFullCredentialTriad = definesFullCredentialTriad(fn.getEnvironment());
@@ -424,15 +402,6 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
}
}
- // 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.
- // An if-block rather than ifPresent(...) because containerId is assigned along the
- // code-volume path and so is not effectively final for a lambda capture.
- if (flociCaCert.isPresent()) {
- copyFileToContainer(dockerClient, containerId, flociCaCert.get(),
- FLOCI_CA_DIR, FLOCI_CA_FILE_NAME, fn.getFunctionName());
- }
-
// Now start the container with code in place
lifecycleManager.startCreated(containerId, spec);
@@ -1369,83 +1338,6 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
}
}
- /**
- * 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 Floci's local root CA 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. Floci's local CA 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.
- */
- public 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", LOCAL_CA_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).
- */
- public 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) {
return AwsArnUtils.regionOrDefault(arn, defaultRegion);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java
index 039da5f0b9..fc502bd5fb 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncher.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.lambda.launcher.kubernetes;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import io.github.hectorvent.floci.config.ContainerCaBundle;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
@@ -169,11 +170,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
var codeDownloadUrl = imagePackage ? null : codeDownloadUrl(fn, region);
var layerUrls = imagePackage ? List.<String>of() : layerDownloadUrls(fn, region);
- var caCert = config.tls().enabled()
- ? ContainerLauncher.resolveFlociCaCertPath(true, config.tls().certPath(),
- config.storage().persistentPath())
- : Optional.<Path>empty();
- var caConfigMap = caCert.map(cert -> ensureCaConfigMap(namespace, cert));
+ var caConfigMap = ContainerCaBundle.hostPath(config).map(bundle -> ensureCaConfigMap(namespace, bundle));
var env = new ArrayList<String>();
env.add("AWS_LAMBDA_RUNTIME_API=" + addressResolver.resolve() + ":" + runtimeApiServer.getPort());
@@ -188,7 +185,6 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
}
env.addAll(awsEnv.sdkBaselineEnv(region, Optional.empty(), addressResolver.flociBaseUrl(),
Optional.empty(), AwsArnUtils.accountOrDefault(fn.getFunctionArn(), config.defaultAccountId())));
- env.addAll(ContainerLauncher.flociCaEnv(caCert));
if (fn.getEnvironment() != null) {
// Same all-or-nothing rule as ContainerLauncher: this launcher never has
// execution-role credentials, so the function's own Environment may only supply
@@ -208,7 +204,9 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
fn.getImageConfigCommand(), fn.getImageConfigWorkingDirectory())
: null;
- var pod = podSpecFactory.buildPod(podName, fn.getFunctionName(), image, env,
+ // After the function's own variables, so a value it sets wins, as in the docker launcher.
+ var podEnv = caConfigMap.isPresent() ? ContainerCaBundle.appendEnv(env) : env;
+ var pod = podSpecFactory.buildPod(podName, fn.getFunctionName(), image, podEnv,
codeDownloadUrl, layerUrls, isProvidedRuntime(fn.getRuntime()),
imagePackage ? null : fn.getHandler(), imageConfig, fn.getMemorySize(), caConfigMap);
@@ -514,15 +512,16 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
}
/**
- * Publishes Floci's CA cert as a ConfigMap so pods can trust Floci's HTTPS endpoint.
- * Applied once per process; the cert cannot rotate within a Floci lifetime.
+ * Publishes the CA bundle as a ConfigMap so pods can trust Floci's HTTPS endpoint and still
+ * reach public HTTPS. Applied once per process; the bundle is written at boot and does not
+ * change within a Floci lifetime.
*/
- private String ensureCaConfigMap(String namespace, Path caCertPath) {
+ private String ensureCaConfigMap(String namespace, Path bundle) {
if (caConfigMapApplied.get()) {
return CA_CONFIG_MAP_NAME;
}
try {
- var pem = Files.readString(caCertPath);
+ var pem = Files.readString(bundle);
var nodes = JsonNodeFactory.instance;
var labels = nodes.objectNode();
LambdaPodSpecFactory.managedPodSelector().forEach(labels::put);
@@ -535,7 +534,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
caConfigMapApplied.set(true);
return CA_CONFIG_MAP_NAME;
} catch (Exception e) {
- throw new RuntimeException("Could not publish Floci CA cert ConfigMap '" + CA_CONFIG_MAP_NAME
+ throw new RuntimeException("Could not publish the Floci CA bundle ConfigMap '" + CA_CONFIG_MAP_NAME
+ "' in namespace " + namespace + ": " + e.getMessage(), e);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/LambdaPodSpecFactory.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/LambdaPodSpecFactory.java
index 5d848385d9..e8fe985658 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/LambdaPodSpecFactory.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/LambdaPodSpecFactory.java
@@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.lambda.launcher.kubernetes;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.config.ContainerCaBundle;
import io.github.hectorvent.floci.config.EmulatorConfig;
-import io.github.hectorvent.floci.services.lambda.launcher.ContainerLauncher;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -60,7 +60,7 @@ public class LambdaPodSpecFactory {
* @param providedRuntime whether the runtime is provided.* (bootstrap needs an exec bit)
* @param handlerOrNull function handler used as the runtime container arg (Zip functions)
* @param imageConfig Image-package-type entrypoint/command/workingdir; empty lists/null when unset
- * @param caConfigMapName ConfigMap holding Floci's CA cert, mounted at /etc/floci-ca.crt when present
+ * @param caConfigMapName ConfigMap holding the CA bundle, mounted at /etc/floci-ca-bundle.pem when present
*/
public ObjectNode buildPod(String podName,
String functionName,
@@ -100,7 +100,7 @@ public class LambdaPodSpecFactory {
.set("configMap", nodes.objectNode().put("name", cm)));
runtimeMounts.add(nodes.objectNode()
.put("name", "floci-ca")
- .put("mountPath", ContainerLauncher.FLOCI_CA_CONTAINER_PATH)
+ .put("mountPath", ContainerCaBundle.CONTAINER_PATH)
.put("subPath", KubernetesPodLauncher.CA_CONFIG_MAP_KEY)
.put("readOnly", true));
});
diff --git a/src/test/java/io/github/hectorvent/floci/config/ContainerCaBundleTest.java b/src/test/java/io/github/hectorvent/floci/config/ContainerCaBundleTest.java
new file mode 100644
index 0000000000..42f366413d
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/config/ContainerCaBundleTest.java
@@ -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;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java
index cdb6b4867d..a73560c08d 100644
--- a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java
+++ b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java
@@ -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
diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceContainerCaBundleTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceContainerCaBundleTest.java
new file mode 100644
index 0000000000..5a79702e9c
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceContainerCaBundleTest.java
@@ -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");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java
index 549b2a08e5..17d12bf547 100644
--- a/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java
@@ -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);
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerCaBundleDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerCaBundleDockerIntegrationTest.java
new file mode 100644
index 0000000000..7f24e6e091
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerCaBundleDockerIntegrationTest.java
@@ -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");
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerCaBundleTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerCaBundleTest.java
new file mode 100644
index 0000000000..f1c96f62cd
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerCaBundleTest.java
@@ -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();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerLabelsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerLabelsTest.java
index c64a54de07..347737fb5a 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerLabelsTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerLabelsTest.java
@@ -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));
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
index fcc888ced5..16df4daef2 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
@@ -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()
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 51425743d5..9d6eb13d9c 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
@@ -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());
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
deleted file mode 100644
index 8d40f484b0..0000000000
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCaTrustTest.java
+++ /dev/null
@@ -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());
- }
-}
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 03b831a5f9..ca7b9f9193 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
@@ -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());
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncherTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncherTest.java
index 3886a0beb5..f1f1a03ebd 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncherTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/KubernetesPodLauncherTest.java
@@ -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;
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/LambdaPodSpecFactoryTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/LambdaPodSpecFactoryTest.java
index ee5012fdea..799b8ce7d9 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/LambdaPodSpecFactoryTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/kubernetes/LambdaPodSpecFactoryTest.java
@@ -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);
});