feat(core): have the JVMs in Lambda, ECS, Batch and Flink containers trust Floci's CA (#6945)

With TLS on, Floci writes its CA bundle as a Java trust store too, but
only EMR's containers got it: a launcher had to copy it in with
ContainerLifecycleManager.copyJavaTrustStore and point its JVMs at it
with a shell line. So a Java Lambda function, ECS task, Batch job or
Flink application calling Floci over HTTPS still failed with "PKIX
path building failed" unless it brought a trust store of its own.

ContainerBuilder now has withJavaTrustStore(). For a container whose
spec asks for it, the lifecycle manager copies the trust store in
beside the CA bundle as it creates the container, and sets
JAVA_TOOL_OPTIONS to Floci's -Djavax.net.ssl.trustStore ahead of the
value the spec gives it, or the image's own when the spec sets none,
so a trust store the workload names itself still replaces Floci's. A
copy that fails creates the container again without any of the trust
variables, as a failed bundle copy already did, so JAVA_TOOL_OPTIONS
never names a file that is not there.

Lambda functions on a Java runtime or from a container image, ECS task
containers, Batch jobs, and Flink's JobManager and TaskManager ask for
it, and so do EMR steps and EMR Serverless job runs, whose
spark-submit starts directly again. The bootstrap actions' container
keeps the separate copy and the shell line, since it is kept as the
steps' image, which would keep a JAVA_TOOL_OPTIONS set at its
creation. Other containers are unchanged.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-29 18:04:46 -05:00
1 parent 62527ebaa8
commit 743bede481
22 files changed
+470 -81

No files matched your search

@@ -39,8 +39,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
* {@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. The JVM reads none
* of them, so the same certificates also go in a PKCS12 trust store, which a launcher whose workload is
* Java copies in beside the bundle and points its JVMs at.
* of them, so the same certificates also go in a PKCS12 trust store, which goes in beside the bundle for a
* container whose workload may be Java, its JVMs pointed at it through {@code JAVA_TOOL_OPTIONS}.
*
* <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
@@ -60,6 +60,8 @@ public final class ContainerCaBundle {
public static final String JAVA_TRUST_STORE_FILE_NAME = "floci-ca-bundle.p12";
public static final String JAVA_TRUST_STORE_PATH = CONTAINER_DIR + "/" + JAVA_TRUST_STORE_FILE_NAME;
private static final String JAVA_TOOL_OPTIONS = "JAVA_TOOL_OPTIONS";
/**
* The JVM option that makes a JVM trust what the trust store at {@link #JAVA_TRUST_STORE_PATH} holds: its
* path alone, as the store needs no password and the JVM reads it whatever store type it is told. A store a
@@ -71,7 +73,8 @@ public final class ContainerCaBundle {
* A shell line after which every JVM the shell starts trusts the bundle, through {@code JAVA_TOOL_OPTIONS},
* when the trust store is in the container, and only then, so a container without it keeps the image's
* trust. Options already in {@code JAVA_TOOL_OPTIONS} come after Floci's, so a trust store of their own
* wins.
* wins. For a container the trust store is copied into on its own rather than with the bundle, such as one
* kept as an image, which would keep a {@code JAVA_TOOL_OPTIONS} given at its creation.
*/
public static final String JAVA_TRUST_SHELL_LINE = "if [ -r " + JAVA_TRUST_STORE_PATH + " ]; then"
+ " export JAVA_TOOL_OPTIONS=\"" + JAVA_TRUST_OPTIONS + "${JAVA_TOOL_OPTIONS:+ $JAVA_TOOL_OPTIONS}\"; fi";
@@ -196,6 +199,41 @@ public final class ContainerCaBundle {
return merged;
}
/**
* {@code env} with {@code JAVA_TOOL_OPTIONS} opening with {@link #JAVA_TRUST_OPTIONS}: ahead of the value
* {@code env} gives it, or, when it gives none, ahead of the value in {@code imageEnv}, the image's own,
* which a container's value replaces. Options after Floci's win, so a trust store they name replaces it.
*/
public static List<String> appendJavaTrustEnv(List<String> env, List<String> imageEnv) {
List<String> merged = new ArrayList<>(env);
boolean set = false;
for (int i = 0; i < merged.size(); i++) {
if (isJavaToolOptions(merged.get(i))) {
merged.set(i, javaToolOptionsAfterFloci(merged.get(i)));
set = true;
}
}
if (!set) {
// The image's last entry is the one its containers get.
merged.add(javaToolOptionsAfterFloci(imageEnv.stream()
.filter(ContainerCaBundle::isJavaToolOptions)
.reduce((earlier, later) -> later)
.orElse(JAVA_TOOL_OPTIONS)));
}
return merged;
}
private static boolean isJavaToolOptions(String entry) {
return entry.equals(JAVA_TOOL_OPTIONS) || entry.startsWith(JAVA_TOOL_OPTIONS + "=");
}
// The JAVA_TOOL_OPTIONS entry with Floci's option ahead of the options in entry, which a bare key gives none.
private static String javaToolOptionsAfterFloci(String entry) {
String options = entry.length() > JAVA_TOOL_OPTIONS.length()
? entry.substring(JAVA_TOOL_OPTIONS.length() + 1) : "";
return JAVA_TOOL_OPTIONS + "=" + JAVA_TRUST_OPTIONS + (options.isBlank() ? "" : " " + options);
}
/**
* An SSL context that trusts what the bundle carries: the JVM's roots and Floci's own trust
* anchor. For Floci's own outbound HTTPS to a URL Floci serves, such as a Cognito pool's issuer,
@@ -178,6 +178,7 @@ public class ContainerBuilder {
private final Map<String, String> tmpfs = new HashMap<>();
private Long memorySwapBytes;
private Long memorySwappiness;
private boolean javaTrustStore;
Builder(String image, EmulatorConfig config, DockerHostResolver dockerHostResolver,
EmbeddedDnsServer embeddedDnsServer,
@@ -296,6 +297,16 @@ public class ContainerBuilder {
return this;
}
/**
* With TLS on, has the container's JVMs trust Floci's CA: the CA bundle's Java trust store goes in beside
* the bundle, and {@code JAVA_TOOL_OPTIONS} points at it, ahead of the options the container would have
* had, so a trust store they name replaces Floci's. For a container whose workload may be Java.
*/
public Builder withJavaTrustStore() {
this.javaTrustStore = true;
return this;
}
/**
* Adds a port binding from container port to a specific host port.
*/
@@ -779,7 +790,8 @@ public class ContainerBuilder {
Map.copyOf(portBindingHostIps),
init,
new LinuxOptions(List.copyOf(capAdd), List.copyOf(capDrop), List.copyOf(devices),
shmSizeBytes, Map.copyOf(tmpfs), memorySwapBytes, memorySwappiness)
shmSizeBytes, Map.copyOf(tmpfs), memorySwapBytes, memorySwappiness),
javaTrustStore
);
}
}
@@ -15,6 +15,7 @@ import com.github.dockerjava.api.exception.NotModifiedException;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.Capability;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.ContainerConfig;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.HostConfig;
@@ -222,13 +223,23 @@ public class ContainerLifecycleManager {
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())) {
List<String> env = ContainerCaBundle.appendEnv(spec.env());
Path javaTrustStore = null;
if (spec.javaTrustStore()) {
Optional<Path> trustStore = ContainerCaBundle.javaTrustStoreHostPath(config);
Optional<List<String>> imageEnv = trustStore.isPresent() ? imageEnv(resolvedImage) : Optional.empty();
if (imageEnv.isPresent()) {
javaTrustStore = trustStore.get();
env = ContainerCaBundle.appendJavaTrustEnv(env, imageEnv.get());
}
}
String containerId = createContainer(spec, resolvedImage, platform, hostConfig, env);
if (copyCaBundle(containerId, caBundle.get(), javaTrustStore)) {
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.
// SSL_CERT_FILE and friends replace the image's trust store, and so does JAVA_TOOL_OPTIONS
// the JVM's, so they must never name a file that is not there. Start over without them: the
// container keeps its own trust.
if (removeAnonymousVolumes) {
removeIfExistsStrict(containerId, true);
} else {
@@ -361,28 +372,35 @@ public class ContainerLifecycleManager {
/**
* 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.
* {@code SSL_CERT_FILE} and friends at init find it, and beside it the Java trust store, when
* {@code javaTrustStore} is not null, for the JVMs {@code JAVA_TOOL_OPTIONS} points at 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 a 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) {
private boolean copyCaBundle(String containerId, Path bundle, Path javaTrustStore) {
try {
copyIntoContainerDir(containerId, bundle, ContainerCaBundle.FILE_NAME);
LOG.debugv("Copied the CA bundle into container {0} at {1}", containerId, ContainerCaBundle.CONTAINER_PATH);
if (javaTrustStore != null) {
copyIntoContainerDir(containerId, javaTrustStore, ContainerCaBundle.JAVA_TRUST_STORE_FILE_NAME);
}
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}",
LOG.warnv(e, "Could not copy the CA bundle or its Java trust store 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;
}
}
/**
* Copies the CA bundle's Java trust store into {@code containerId}, before it starts, at
* Copies the CA bundle's Java trust store into {@code containerId} at
* {@link ContainerCaBundle#JAVA_TRUST_STORE_PATH}, for a container whose JVMs are then pointed at
* it, as {@link ContainerCaBundle#JAVA_TRUST_SHELL_LINE} does. Returns whether it is there: false
* it, as {@link ContainerCaBundle#JAVA_TRUST_SHELL_LINE} does, and whose spec does not ask for it,
* as {@link ContainerBuilder.Builder#withJavaTrustStore} does. Returns whether it is there: false
* when TLS is off, the boot wrote no trust store, or the copy failed, which is logged; the JVMs then
* keep the image's trust store.
*/
@@ -990,6 +1008,22 @@ public class ContainerLifecycleManager {
}
}
/**
* The environment {@code resolvedImage} gives its containers, empty, after logging why, when it could
* not be read.
*/
private Optional<List<String>> imageEnv(String resolvedImage) {
try {
ContainerConfig imageConfig = dockerClient.inspectImageCmd(resolvedImage).exec().getConfig();
String[] env = imageConfig == null ? null : imageConfig.getEnv();
return Optional.of(env == null ? List.of() : List.of(env));
} catch (Exception e) {
LOG.warnv("Could not read the environment of image {0}, so the JVMs in its container keep the image's"
+ " trust store and will not trust Floci HTTPS: {1}", resolvedImage, e.getMessage());
return Optional.empty();
}
}
/**
* Labels declared on an image, empty when they could not be read.
*
@@ -49,6 +49,8 @@ import java.util.regex.Pattern;
* images whose command does not handle SIGTERM itself
* @param linuxOptions Capabilities, devices, shared memory, tmpfs and swap
* ({@link LinuxOptions#NONE} = daemon defaults)
* @param javaTrustStore Whether, with TLS on, the container's JVMs trust Floci's CA: the CA bundle's Java trust
* store goes in beside the bundle, and {@code JAVA_TOOL_OPTIONS} points at it
*/
public record ContainerSpec(
String image,
@@ -80,7 +82,8 @@ public record ContainerSpec(
List<String> linkLocalIps,
Map<Integer, String> portBindingHostIps,
boolean init,
LinuxOptions linuxOptions
LinuxOptions linuxOptions,
boolean javaTrustStore
) {
private static final Pattern LINK_LOCAL_IPV4 = Pattern.compile("^169\\.254\\.(\\d{1,3})\\.(\\d{1,3})$");
private static final Set<String> NETWORKS_WITHOUT_ENDPOINT_IPAM = Set.of("bridge", "default", "host", "none");
@@ -103,7 +106,50 @@ public record ContainerSpec(
public ContainerSpec(String image) {
this(image, null, List.of(), null, null, null, Map.of(), List.of(), List.of(), null,
List.of(), List.of(), List.of(), List.of(), Map.of(), null, false, null, List.of(),
null, null, List.of(), List.of(), null, null, false, List.of(), Map.of(), false, LinuxOptions.NONE);
null, null, List.of(), List.of(), null, null, false, List.of(), Map.of(), false, LinuxOptions.NONE,
false);
}
/**
* Backward-compatible constructor that leaves the container's JVMs on the image's trust store, so callers
* that predate the Java trust store keep their existing behaviour.
*/
public ContainerSpec(
String image,
String name,
List<String> env,
List<String> cmd,
List<String> entrypoint,
Long memoryBytes,
Map<Integer, Integer> portBindings,
List<Integer> loopbackPortBindings,
List<Integer> exposedPorts,
String networkMode,
List<Mount> mounts,
List<Bind> binds,
List<VolumesFrom> volumesFrom,
List<String> extraHosts,
Map<String, String> labels,
LogConfig logConfig,
boolean privileged,
String cgroupnsMode,
List<String> dnsServers,
String workingDir,
String user,
List<String> groupAdd,
List<DeviceRequest> deviceRequests,
Long nanoCpus,
Integer cpuShares,
boolean readonlyRootfs,
List<String> linkLocalIps,
Map<Integer, String> portBindingHostIps,
boolean init,
LinuxOptions linuxOptions
) {
this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, loopbackPortBindings,
exposedPorts, networkMode, mounts, binds, volumesFrom, extraHosts, labels, logConfig,
privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd, deviceRequests,
nanoCpus, cpuShares, readonlyRootfs, linkLocalIps, portBindingHostIps, init, linuxOptions, false);
}
/**
@@ -104,6 +104,7 @@ public class BatchDockerRunner implements ContainerTeardown {
.withHostDockerInternalOnLinux()
.withEmbeddedDns()
.withLogRotation()
.withJavaTrustStore()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"batch", job.getJobId(), job.getAccountId(), job.getRegion()));
@@ -404,6 +404,7 @@ public class EcsContainerManager {
// own loopback.
.withHostDockerInternalOnLinux()
.withEmbeddedDns()
.withJavaTrustStore()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"ecs", taskId, regionResolver.getAccountId(), region))
.withLabels(ownerLabels());
@@ -141,7 +141,9 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
.build();
String containerId = lifecycleManager.createAndStart(spec).containerId();
launch.started(containerId);
// In before the first action, for the actions' JVMs to find it.
// In before the first action, for the actions' JVMs to find it. Not through the spec: the container is
// kept as an image, which would keep a JAVA_TOOL_OPTIONS given at its creation, naming a trust store
// the cleanup removes.
lifecycleManager.copyJavaTrustStore(containerId);
// A stop, a reset or a shutdown while the image was pulled or the trust store copied is read now.
if (launch.stopRequested() || cancelled.getAsBoolean()) {
@@ -5,7 +5,6 @@ import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import io.github.hectorvent.floci.config.ContainerCaBundle;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.common.RequestScopes;
@@ -57,17 +56,11 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
private static final Logger LOG = Logger.getLogger(EmrServerlessSparkRunner.class);
private static final String SPARK_SUBMIT = "/usr/lib/spark/bin/spark-submit";
private static final String SPARK_DEFAULTS_VARIABLE = "FLOCI_SPARK_DEFAULTS";
// spark-submit runs after this, its JVMs trusting Floci's CA once its trust store is in the container.
private static final String SPARK_SUBMIT_WRAPPER = String.join("\n",
ContainerCaBundle.JAVA_TRUST_SHELL_LINE,
"exec \"$@\"");
// A command runs after this sets up a Spark configuration of its own, so a spark-submit it starts runs
// locally on Floci's S3: the image's spark-defaults.conf names EMR Serverless's resource manager as its
// master, which a system property cannot override, so its master and that manager's lines give way to
// local mode, Floci's settings and the job's spark-defaults, passed in SPARK_DEFAULTS_VARIABLE. Its JVMs
// trust Floci's CA as spark-submit's do.
// local mode, Floci's settings and the job's spark-defaults, passed in SPARK_DEFAULTS_VARIABLE.
private static final String COMMAND_WRAPPER = String.join("\n",
ContainerCaBundle.JAVA_TRUST_SHELL_LINE,
"conf=/tmp/floci-spark-conf",
"mkdir -p \"$conf\"",
"cp -r /usr/lib/spark/conf/. \"$conf\" 2>/dev/null",
@@ -149,12 +142,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
image(job.imageTemplate(), job.releaseLabel()))
.withName(ContainerStorageHelper.dockerName(config, job.service() + "-" + job.runId()))
.withEnv(awsEnv.sdkBaselineEnv(job.region(), Optional.empty(), credentials, job.accountId()));
// bash -c's script gets "floci" as its $0, and spark-submit or the command as its arguments, "$@".
if (job.command() == null) {
List<String> submit = new ArrayList<>(List.of(SPARK_SUBMIT));
submit.addAll(sparkSubmitArguments(job, endpoint));
container.withEntrypoint(List.of("/bin/bash", "-c", SPARK_SUBMIT_WRAPPER, "floci")).withCmd(submit);
container.withEntrypoint(List.of(SPARK_SUBMIT)).withCmd(sparkSubmitArguments(job, endpoint));
} else {
// bash -c's script gets "floci" as its $0, and the command as its arguments, "$@".
container.withEntrypoint(List.of("/bin/bash", "-c", COMMAND_WRAPPER, "floci"))
.withCmd(job.command())
.withEnv(SPARK_DEFAULTS_VARIABLE, sparkDefaultsFile(job, endpoint));
@@ -165,11 +156,10 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
.withEmbeddedDns()
.withLogRotation()
.withLabels(labels)
.withJavaTrustStore()
.build();
String containerId = lifecycleManager.create(spec);
launch.started(containerId);
// In before the driver starts, for its JVMs to find it.
lifecycleManager.copyJavaTrustStore(containerId);
// A stop, a reset or a shutdown while the image was pulled or the trust store copied is read now,
// before the driver starts.
if (launch.stopRequested() || progress.cancelled()) {
@@ -167,6 +167,7 @@ public class FlinkContainerManager {
.withHostDockerInternalOnLinux()
.withEmbeddedDns()
.withLogRotation()
.withJavaTrustStore()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"kinesisanalytics", app.getApplicationName(),
app.getAccountId() != null ? app.getAccountId() : regionResolver.getAccountId(), region));
@@ -221,6 +222,7 @@ public class FlinkContainerManager {
.withEnv("FLINK_PROPERTIES", tmProps)
.withNetworkMode("container:" + jm.containerId())
.withLogRotation()
.withJavaTrustStore()
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"kinesisanalytics", app.getApplicationName(),
app.getAccountId() != null ? app.getAccountId() : regionResolver.getAccountId(), region))
@@ -298,6 +298,10 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
applyDockerFlags(specBuilder, dockerFlags);
specBuilder.withEmbeddedDns();
// A container image's runtime is its own, Java as likely as any.
if (isJavaRuntime(fn.getRuntime()) || "Image".equals(fn.getPackageType())) {
specBuilder.withJavaTrustStore();
}
// Inject extra hosts entries into the container if present. Split on the FIRST
// colon, mirroring docker --add-host: hostnames cannot contain colons, but IPv6
@@ -1354,6 +1358,10 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
return runtime != null && runtime.startsWith("provided");
}
private static boolean isJavaRuntime(String runtime) {
return runtime != null && runtime.startsWith("java");
}
/** Directory Lambda's real init system scans for extension binaries. */
private static final String EXTENSIONS_DIR = "/opt/extensions";