diff --git a/.github/ci/prefetch-images.sh b/.github/ci/prefetch-images.sh index 2286266fea..fd7176ba89 100755 --- a/.github/ci/prefetch-images.sh +++ b/.github/ci/prefetch-images.sh @@ -78,6 +78,8 @@ starts EcsImagePullDockerIntegrationTest && [ -n "$REGISTRY_IMAGE" ] && pull "$R PYTHON_ALPINE_IMAGE="$(test_image PYTHON_ALPINE)" starts ContainerCaBundleDockerIntegrationTest EcsCredentialsProxyDockerIntegrationTest SageMakerDockerIntegrationTest \ && [ -n "$PYTHON_ALPINE_IMAGE" ] && pull "$PYTHON_ALPINE_IMAGE" +CORRETTO_8_IMAGE="$(test_image CORRETTO_8)" +starts ContainerCaBundleDockerIntegrationTest && [ -n "$CORRETTO_8_IMAGE" ] && pull "$CORRETTO_8_IMAGE" # The Firelens test names the log router image itself rather than taking it from config. FLUENT_BIT_IMAGE="$(test_image FLUENT_BIT)" starts EcsContainerManagerFirelensDockerIntegrationTest && [ -n "$FLUENT_BIT_IMAGE" ] && pull "$FLUENT_BIT_IMAGE" diff --git a/docs/configuration/tls.md b/docs/configuration/tls.md index d6a64de4a8..15c2dd5bcc 100644 --- a/docs/configuration/tls.md +++ b/docs/configuration/tls.md @@ -107,7 +107,7 @@ Names are added by the custom domain operations: API Gateway `CreateDomainName`, ### 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. Floci writes one beside the bundle, `{persistent-path}/tls/floci-ca-bundle.p12` (PKCS12, no password), with the same certificates; EMR steps and bootstrap actions and EMR Serverless job runs in the `docker` runner mode get it at `/etc/floci-ca-bundle.p12`, and every JVM in them uses it through `JAVA_TOOL_OPTIONS`, which gives only its path (`-Djavax.net.ssl.trustStore`), so a trust store a job names itself replaces it, with that store's own type and password. 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. Floci trusts the same bundle when it fetches a JWT issuer's keys for an HTTP API authorizer or an AppSync OIDC provider, so an issuer it serves itself, a Cognito user pool for one, verifies over HTTPS. +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. Floci writes one beside the bundle, `{persistent-path}/tls/floci-ca-bundle.p12` (PKCS12, no password), with the same certificates. Lambda functions on a Java runtime or from a container image (in Docker), ECS tasks, Batch jobs, Flink applications, and EMR steps, bootstrap actions and EMR Serverless job runs in the `docker` runner mode get it at `/etc/floci-ca-bundle.p12`, and every JVM in them uses it through `JAVA_TOOL_OPTIONS`, saying so on its standard error (`Picked up JAVA_TOOL_OPTIONS: ...`). Floci's option gives only the store's path (`-Djavax.net.ssl.trustStore`) and comes ahead of the options the function, task or image sets, so a trust store a workload names itself replaces it, with that store's own type and password. 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. Floci trusts the same bundle when it fetches a JWT issuer's keys for an HTTP API authorizer or an AppSync OIDC provider, so an issuer it serves itself, a Cognito user pool for one, verifies over HTTPS. ## User-Provided Certificates diff --git a/src/main/java/io/github/hectorvent/floci/config/ContainerCaBundle.java b/src/main/java/io/github/hectorvent/floci/config/ContainerCaBundle.java index 7278e67267..5a60e2c1ff 100644 --- a/src/main/java/io/github/hectorvent/floci/config/ContainerCaBundle.java +++ b/src/main/java/io/github/hectorvent/floci/config/ContainerCaBundle.java @@ -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}. * *

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 appendJavaTrustEnv(List env, List imageEnv) { + List 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, diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java index 9197f06349..943f484c9c 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java @@ -178,6 +178,7 @@ public class ContainerBuilder { private final Map 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 ); } } 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 6e6574f45b..3f7cfbacbd 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 @@ -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 env = ContainerCaBundle.appendEnv(spec.env()); + Path javaTrustStore = null; + if (spec.javaTrustStore()) { + Optional trustStore = ContainerCaBundle.javaTrustStoreHostPath(config); + Optional> 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> 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. * diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java index 8d324dfcf9..9fea05c1b8 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java @@ -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 linkLocalIps, Map 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 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 env, + List cmd, + List entrypoint, + Long memoryBytes, + Map portBindings, + List loopbackPortBindings, + List exposedPorts, + String networkMode, + List mounts, + List binds, + List volumesFrom, + List extraHosts, + Map labels, + LogConfig logConfig, + boolean privileged, + String cgroupnsMode, + List dnsServers, + String workingDir, + String user, + List groupAdd, + List deviceRequests, + Long nanoCpus, + Integer cpuShares, + boolean readonlyRootfs, + List linkLocalIps, + Map 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); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/batch/BatchDockerRunner.java b/src/main/java/io/github/hectorvent/floci/services/batch/BatchDockerRunner.java index 70eb1ebf26..1cb704e6ae 100644 --- a/src/main/java/io/github/hectorvent/floci/services/batch/BatchDockerRunner.java +++ b/src/main/java/io/github/hectorvent/floci/services/batch/BatchDockerRunner.java @@ -104,6 +104,7 @@ public class BatchDockerRunner implements ContainerTeardown { .withHostDockerInternalOnLinux() .withEmbeddedDns() .withLogRotation() + .withJavaTrustStore() .withLabels(ContainerStorageHelper.resourceIdentityLabels( "batch", job.getJobId(), job.getAccountId(), job.getRegion())); diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java index 92253483e2..b339da6c96 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java @@ -404,6 +404,7 @@ public class EcsContainerManager { // own loopback. .withHostDockerInternalOnLinux() .withEmbeddedDns() + .withJavaTrustStore() .withLabels(ContainerStorageHelper.resourceIdentityLabels( "ecs", taskId, regionResolver.getAccountId(), region)) .withLabels(ownerLabels()); diff --git a/src/main/java/io/github/hectorvent/floci/services/emr/EmrBootstrapRunner.java b/src/main/java/io/github/hectorvent/floci/services/emr/EmrBootstrapRunner.java index db274e95b9..58c6565a46 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emr/EmrBootstrapRunner.java +++ b/src/main/java/io/github/hectorvent/floci/services/emr/EmrBootstrapRunner.java @@ -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()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java index b0576f991d..3e46451f7e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java @@ -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 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()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java index 49c3fcd1c3..8c846d946d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManager.java @@ -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)) 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 fffd566e4b..b2cdfb2b6c 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 @@ -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"; diff --git a/src/test/java/io/github/hectorvent/floci/config/ContainerCaBundleTest.java b/src/test/java/io/github/hectorvent/floci/config/ContainerCaBundleTest.java index 885ddff24b..3bdb940ead 100644 --- a/src/test/java/io/github/hectorvent/floci/config/ContainerCaBundleTest.java +++ b/src/test/java/io/github/hectorvent/floci/config/ContainerCaBundleTest.java @@ -267,6 +267,32 @@ class ContainerCaBundleTest { assertEquals(ContainerCaBundle.env(), ContainerCaBundle.appendEnv(List.of())); } + // Options after Floci's win, so a trust store they name replaces it, as the JVM test below shows. + @Test + void appendJavaTrustEnvPutsFlocisOptionAheadOfTheContainersOwnWhichReplacesTheImages() { + assertEquals(List.of("FOO=bar", "JAVA_TOOL_OPTIONS=" + ContainerCaBundle.JAVA_TRUST_OPTIONS + " -Xss2m"), + ContainerCaBundle.appendJavaTrustEnv(List.of("FOO=bar", "JAVA_TOOL_OPTIONS=-Xss2m"), + List.of("JAVA_TOOL_OPTIONS=-Dimage=1"))); + } + + @Test + void appendJavaTrustEnvPutsFlocisOptionAheadOfTheImagesLastWhenTheContainerSetsNone() { + assertEquals(List.of("FOO=bar", "JAVA_TOOL_OPTIONS=" + ContainerCaBundle.JAVA_TRUST_OPTIONS + " -Dimage=2"), + ContainerCaBundle.appendJavaTrustEnv(List.of("FOO=bar"), + List.of("PATH=/bin", "JAVA_TOOL_OPTIONS=-Dimage=1", "JAVA_TOOL_OPTIONS=-Dimage=2"))); + } + + @Test + void appendJavaTrustEnvGivesFlocisOptionAloneWhenNothingElseIsSet() { + List alone = List.of("JAVA_TOOL_OPTIONS=" + ContainerCaBundle.JAVA_TRUST_OPTIONS); + + assertEquals(alone, ContainerCaBundle.appendJavaTrustEnv(List.of(), List.of("PATH=/bin"))); + assertEquals(alone, ContainerCaBundle.appendJavaTrustEnv(List.of("JAVA_TOOL_OPTIONS="), List.of())); + // A bare key unsets the image's value, so none is kept. + assertEquals(alone, ContainerCaBundle.appendJavaTrustEnv(List.of("JAVA_TOOL_OPTIONS"), + List.of("JAVA_TOOL_OPTIONS=-Dimage=1"))); + } + @Test void theJavaTrustStoreHoldsEveryCertificateOfTheBundleAsATrustedEntry() throws Exception { Path tlsDir = tempDir.resolve("tls"); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java index 93d177eb17..1d7d94677d 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java @@ -12,6 +12,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -116,6 +117,14 @@ class ContainerBuilderTest { assertEquals("host", spec.cgroupnsMode()); } + @Test + void withJavaTrustStoreRecordsThatTheContainersJvmsTrustFlocisCa() { + TestFixture fixture = new TestFixture(); + + assertTrue(fixture.builder.newContainer("alpine").withJavaTrustStore().build().javaTrustStore()); + assertFalse(fixture.builder.newContainer("alpine").build().javaTrustStore()); + } + @Test void withUserAndGroupAddRoundTripIntoSpec() { TestFixture fixture = new TestFixture(); 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 index 8bd55f58bc..d951fdd53f 100644 --- 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 @@ -34,7 +34,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; * 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. + * would. A JVM ignores that variable, so a Java container that asks for the trust store makes + * the same two calls on Corretto 8, the JVM of Lambda's oldest Java runtime: it reads the PKCS12 + * store through {@code JAVA_TOOL_OPTIONS}, and that store replaces the JDK's own. Skipped without + * a Docker daemon, like the other {@code *DockerIntegrationTest} classes. */ @QuarkusTest @TestProfile(ContainerCaBundleDockerIntegrationTest.Profile.class) @@ -89,6 +92,55 @@ class ContainerCaBundleDockerIntegrationTest { .withEntrypoint(List.of("python3", "-c", script)) .build(); + assertExitsCleanly(spec); + } + + @Test + void javaContainerAskingForTheTrustStoreTrustsFlociAndPublicRootsKeepingItsOwnOptions() { + String probe = """ + import java.net.HttpURLConnection; + import java.net.URL; + + public class Probe { + public static void main(String[] args) throws Exception { + check(200, status("https://host.docker.internal:%d/_floci/ca.pem")); + // Any status will do: a handshake the store cannot verify throws instead. + status("https://public.ecr.aws/"); + check("/etc/floci-ca-bundle.p12", System.getProperty("javax.net.ssl.trustStore")); + check("kept", System.getProperty("floci.probe")); + System.out.println("ok"); + } + + static int status(String url) throws Exception { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setConnectTimeout(20000); + connection.setReadTimeout(20000); + return connection.getResponseCode(); + } + + static void check(Object expected, Object actual) { + if (!expected.equals(actual)) { + throw new AssertionError("expected " + expected + ", got " + actual); + } + } + } + """.formatted(testSslPort); + + ContainerSpec spec = containerBuilder.newContainer(TestImages.CORRETTO_8) + .withName("floci-java-trust-store-test-" + Long.toString(System.nanoTime(), 36)) + .withHostDockerInternalOnLinux() + // The task's own option, which Floci's has to join rather than replace. + .withEnv("JAVA_TOOL_OPTIONS", "-Dfloci.probe=kept") + .withEnv("PROBE_SOURCE", probe) + .withJavaTrustStore() + .withEntrypoint(List.of("sh", "-c", "printf '%s' \"$PROBE_SOURCE\" > /tmp/Probe.java" + + " && javac -d /tmp /tmp/Probe.java && java -cp /tmp Probe")) + .build(); + + assertExitsCleanly(spec); + } + + private void assertExitsCleanly(ContainerSpec spec) { ContainerLifecycleManager.ContainerInfo info = lifecycle.createAndStart(spec); try { Integer status = dockerClient.waitContainerCmd(info.containerId()) @@ -127,10 +179,11 @@ class ContainerCaBundleDockerIntegrationTest { /** * 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. + * container dials, the bundle and its Java trust store. 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 { @@ -146,7 +199,7 @@ class ContainerCaBundleDockerIntegrationTest { 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()); + ContainerCaBundle.writeJavaTrustStore(ContainerCaBundle.write(TLS_DIR, ca.certificatePath())); } catch (IOException | GeneralSecurityException e) { throw new IllegalStateException("Failed to prepare the TLS test files", e); } 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 index b61f4489e3..956bc1d354 100644 --- 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 @@ -4,8 +4,12 @@ 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.InspectImageCmd; +import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.api.command.RemoveContainerCmd; import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.ContainerConfig; +import io.github.hectorvent.floci.config.ContainerCaBundle; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.config.TlsConfigSource; import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService; @@ -317,11 +321,146 @@ class ContainerLifecycleManagerCaBundleTest { assertFalse(manager().copyJavaTrustStore("container-id")); } + @Test + void aSpecAskingForTheJavaTrustStoreGetsItBesideTheBundleWithJavaToolOptionsAheadOfTheImages() throws Exception { + when(tlsConfig.enabled()).thenReturn(true); + writeBundle(); + byte[] trustStore = writeJavaTrustStore(); + CreateContainerCmd createCmd = stubCreateContainer(); + stubImageEnv("PATH=/usr/bin", "JAVA_TOOL_OPTIONS=-Dimage=1"); + List archives = stubCopies(); + + assertEquals("container-id", manager().create(javaSpecWithEnv(List.of("FOO=bar")))); + + List expected = new ArrayList<>(List.of("FOO=bar")); + expected.addAll(ContainerCaBundle.env()); + expected.add("JAVA_TOOL_OPTIONS=-Djavax.net.ssl.trustStore=/etc/floci-ca-bundle.p12 -Dimage=1"); + assertEquals(expected, capturedEnv(createCmd)); + assertEquals(2, archives.size()); + assertBundleArchive(new ByteArrayInputStream(archives.get(0))); + assertSingleFileArchive(new ByteArrayInputStream(archives.get(1)), "floci-ca-bundle.p12", trustStore); + } + + @Test + void aSpecThatDoesNotAskLeavesItsJvmsOnTheImagesTrustStore() throws Exception { + when(tlsConfig.enabled()).thenReturn(true); + writeBundle(); + writeJavaTrustStore(); + CreateContainerCmd createCmd = stubCreateContainer(); + List archives = stubCopies(); + + manager().create(specWithEnv(List.of("FOO=bar"))); + + assertTrue(capturedEnv(createCmd).stream().noneMatch(entry -> entry.startsWith("JAVA_TOOL_OPTIONS"))); + assertEquals(1, archives.size()); + verify(dockerClient, never()).inspectImageCmd(anyString()); + } + + @Test + void withoutATrustStoreFromTheBootASpecAskingForOneGetsTheBundleAlone() throws Exception { + when(tlsConfig.enabled()).thenReturn(true); + writeBundle(); + CreateContainerCmd createCmd = stubCreateContainer(); + List archives = stubCopies(); + + manager().create(javaSpecWithEnv(List.of("FOO=bar"))); + + assertEquals(6, capturedEnv(createCmd).size()); + assertEquals(1, archives.size()); + verify(dockerClient, never()).inspectImageCmd(anyString()); + } + + @Test + void anImageWhoseEnvironmentCannotBeReadKeepsItsJvmsOnItsOwnTrustStore() throws Exception { + // Floci's JAVA_TOOL_OPTIONS would replace the image's, which it could not read to keep. + when(tlsConfig.enabled()).thenReturn(true); + writeBundle(); + writeJavaTrustStore(); + CreateContainerCmd createCmd = stubCreateContainer(); + InspectImageCmd inspectCmd = mock(InspectImageCmd.class); + when(dockerClient.inspectImageCmd("busybox:stable")).thenReturn(inspectCmd); + when(inspectCmd.exec()).thenThrow(new NotFoundException("No such image")); + List archives = stubCopies(); + + manager().create(javaSpecWithEnv(List.of("FOO=bar"))); + + List env = capturedEnv(createCmd); + assertEquals(6, env.size()); + assertTrue(env.containsAll(ContainerCaBundle.env())); + assertEquals(1, archives.size()); + } + + @Test + void aTrustStoreThatCannotBeCopiedRecreatesTheContainerWithoutAnyTrustVariables() throws Exception { + // JAVA_TOOL_OPTIONS must never name a trust store that is not there: the JVM would trust nothing. + when(tlsConfig.enabled()).thenReturn(true); + writeBundle(); + writeJavaTrustStore(); + 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); + stubImageEnv(); + CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF); + when(dockerClient.copyArchiveToContainerCmd("container-id")).thenReturn(copyCmd); + // The bundle goes in; its trust store does not. + when(copyCmd.exec()).thenAnswer(copied -> null) + .thenThrow(new NotFoundException("Could not find the file /etc")); + RemoveContainerCmd removeCmd = mock(RemoveContainerCmd.class, RETURNS_SELF); + when(dockerClient.removeContainerCmd("container-id")).thenReturn(removeCmd); + + assertEquals("container-id-2", manager().create(javaSpecWithEnv(List.of("FOO=bar")))); + + verify(removeCmd).exec(); + @SuppressWarnings("unchecked") + ArgumentCaptor> env = ArgumentCaptor.forClass((Class>) (Class) List.class); + verify(createCmd, times(2)).withEnv(env.capture()); + assertEquals(7, 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, never()).copyArchiveToContainerCmd("container-id-2"); + } + private Path writeBundle() throws Exception { Path tlsDir = Files.createDirectories(tempDir.resolve("tls")); return Files.writeString(tlsDir.resolve("floci-ca-bundle.pem"), BUNDLE_PEM); } + private byte[] writeJavaTrustStore() throws Exception { + byte[] trustStore = {0x30, (byte) 0x82, 0x01, 0x02}; + Files.write(Files.createDirectories(tempDir.resolve("tls")).resolve("floci-ca-bundle.p12"), trustStore); + return trustStore; + } + + private void stubImageEnv(String... env) { + InspectImageCmd inspectCmd = mock(InspectImageCmd.class); + when(dockerClient.inspectImageCmd("busybox:stable")).thenReturn(inspectCmd); + InspectImageResponse image = mock(InspectImageResponse.class); + when(inspectCmd.exec()).thenReturn(image); + ContainerConfig imageConfig = mock(ContainerConfig.class); + when(image.getConfig()).thenReturn(imageConfig); + when(imageConfig.getEnv()).thenReturn(env); + } + + // Every archive copied into "container-id", in the order they went in. + private List stubCopies() { + CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF); + when(dockerClient.copyArchiveToContainerCmd("container-id")).thenReturn(copyCmd); + List streams = new ArrayList<>(); + when(copyCmd.withTarInputStream(any(InputStream.class))).thenAnswer(invocation -> { + streams.add(invocation.getArgument(0)); + return copyCmd; + }); + List archives = new ArrayList<>(); + when(copyCmd.exec()).thenAnswer(invocation -> { + archives.add(streams.getLast().readAllBytes()); + return null; + }); + return archives; + } + private static void assertBundleArchive(InputStream stream) throws IOException { assertSingleFileArchive(stream, "floci-ca-bundle.pem", BUNDLE_PEM.getBytes(StandardCharsets.UTF_8)); } @@ -347,6 +486,13 @@ class ContainerLifecycleManagerCaBundleTest { List.of(), List.of(), List.of(), Map.of(), null, false, null, List.of(), null, null, List.of()); } + // As ContainerBuilder.Builder.withJavaTrustStore() builds it. + private static ContainerSpec javaSpecWithEnv(List env) { + return new ContainerSpec("busybox:stable", null, env, 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, true); + } + private CreateContainerCmd stubCreateContainer() { CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF); when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd); diff --git a/src/test/java/io/github/hectorvent/floci/services/batch/BatchDockerRunnerTest.java b/src/test/java/io/github/hectorvent/floci/services/batch/BatchDockerRunnerTest.java index 5e681033ad..30a3e58157 100644 --- a/src/test/java/io/github/hectorvent/floci/services/batch/BatchDockerRunnerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/batch/BatchDockerRunnerTest.java @@ -111,6 +111,8 @@ class BatchDockerRunnerTest { "io.floci.resource-id", "job-1", "io.floci.account", "000000000000", "io.floci.region", "us-east-1")); + // A job's JVMs trust Floci's CA as well. + verify(builder).withJavaTrustStore(); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerAwsBaselineTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerAwsBaselineTest.java index 5221abd0ec..a91be1fac5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerAwsBaselineTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerAwsBaselineTest.java @@ -127,6 +127,19 @@ class EcsContainerManagerAwsBaselineTest { assertTrue(env.contains("APP_ONLY=1")); } + @Test + void aTaskContainersJvmsTrustFlocisCa() { + TaskDefinition taskDef = new TaskDefinition(); + taskDef.setFamily("test-family"); + taskDef.setContainerDefinitions(List.of(containerDef("app", "app:latest", List.of()))); + EcsTask task = new EcsTask(); + task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123"); + + manager.startTask(task, taskDef, null, "us-east-1"); + + verify(builder).withJavaTrustStore(); + } + @Test void runTaskOverrideWinsOverBaseline() { ContainerDefinition app = containerDef("app", "app:latest", List.of()); diff --git a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java index a66d7628c5..4f3440ff45 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java @@ -6,7 +6,6 @@ import com.github.dockerjava.api.exception.InternalServerErrorException; 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.AwsException; import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; @@ -136,16 +135,16 @@ class EmrServerlessSparkRunnerTest { runner(builder).run(job(Duration.ZERO), progress); verify(builder).newContainer("public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest"); - // bash -c runs Floci's wrapper with "floci" as its $0 and spark-submit and its arguments as "$@". - verify(spec).withEntrypoint(List.of("/bin/bash", "-c", - ContainerCaBundle.JAVA_TRUST_SHELL_LINE + "\nexec \"$@\"", "floci")); - verify(spec).withCmd(argThat((List cmd) -> "/usr/lib/spark/bin/spark-submit".equals(cmd.getFirst()) - && List.of("--master", "local[*]").equals(cmd.subList(1, 3)) + verify(spec).withEntrypoint(List.of("/usr/lib/spark/bin/spark-submit")); + verify(spec).withCmd(argThat((List cmd) -> List.of("--master", "local[*]").equals(cmd.subList(0, 2)) && "s3://bucket/jobs/app.jar".equals(cmd.getLast()))); verify(spec).withName(ContainerStorageHelper.dockerName(config, "emr-serverless-00f0000000000001")); verify(spec).withDockerNetwork(Optional.of("floci-network")); verify(spec).withLabels(argThat(labels -> "emr-serverless".equals(labels.get(ContainerStorageHelper.SERVICE_LABEL)))); + // Its JVMs trust Floci's CA, the trust store going in with the CA bundle as the container is created. + verify(spec).withJavaTrustStore(); + verify(lifecycle, never()).copyJavaTrustStore(anyString()); } @Test @@ -160,23 +159,14 @@ class EmrServerlessSparkRunnerTest { // bash -c runs Floci's wrapper with "floci" as its $0 and the command as "$@". verify(spec).withEntrypoint(argThat(entrypoint -> entrypoint.size() == 4 && entrypoint.subList(0, 2).equals(List.of("/bin/bash", "-c")) - && entrypoint.get(2).startsWith(ContainerCaBundle.JAVA_TRUST_SHELL_LINE + "\n") && entrypoint.get(2).contains("export SPARK_CONF_DIR=") && entrypoint.get(2).endsWith("exec \"$@\"") && "floci".equals(entrypoint.get(3)))); verify(spec).withCmd(command); verify(spec).withEnv(eq("FLOCI_SPARK_DEFAULTS"), argThat(file -> file.startsWith("spark.master local[*]\n") && file.endsWith("\nspark.executor.cores 4"))); - } - - @Test - void theJavaTrustStoreGoesIntoTheDriversContainerBeforeItStarts() { - runner().run(job(Duration.ZERO), progress); - - InOrder order = inOrder(lifecycle); - order.verify(lifecycle).create(any()); - order.verify(lifecycle).copyJavaTrustStore("driver"); - order.verify(lifecycle).startCreated(eq("driver"), any()); + verify(spec, never()).withEntrypoint(List.of("/usr/lib/spark/bin/spark-submit")); + verify(spec).withJavaTrustStore(); } @Test @@ -287,13 +277,14 @@ class EmrServerlessSparkRunnerTest { } @Test - void aRunStoppedWhileTheTrustStoreIsCopiedNeverStartsItsDriver() { + void aRunStoppedWhileItsContainerIsCreatedNeverStartsItsDriver() { EmrServerlessSparkRunner runner = runner(); SparkJobRunner.Job job = job(Duration.ZERO); - // The copy can wait on Docker, and a stop only marks the run. - when(lifecycle.copyJavaTrustStore("driver")).thenAnswer(copy -> { + // The create pulls the image and copies the trust store in, either of which can wait on Docker, and a + // stop only marks the run. + when(lifecycle.create(any())).thenAnswer(creating -> { runner.stop(job.runId()); - return true; + return "driver"; }); SparkJobRunner.Outcome outcome = runner.run(job, progress); @@ -304,24 +295,6 @@ class EmrServerlessSparkRunnerTest { verify(lifecycle).stopAndRemove("driver", null, 0); } - @Test - void aRunCancelledWhileTheTrustStoreIsCopiedNeverStartsItsDriver() { - EmrServerlessSparkRunner runner = runner(); - AtomicBoolean cancelled = new AtomicBoolean(); - when(progress.cancelled()).thenAnswer(look -> cancelled.get()); - when(lifecycle.copyJavaTrustStore("driver")).thenAnswer(copy -> { - cancelled.set(true); - return true; - }); - - SparkJobRunner.Outcome outcome = runner.run(job(Duration.ZERO), progress); - - assertTrue(outcome.stopped()); - verify(progress, never()).started(); - verify(lifecycle, never()).startCreated(anyString(), any()); - verify(lifecycle).stopAndRemove("driver", null, 0); - } - @Test void aRunningDriverWhoseRunIsGoneIsStoppedAtTheNextLook() { EmrServerlessSparkRunner runner = runner(); diff --git a/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManagerTest.java index 834e63b799..3251ff1d20 100644 --- a/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/kinesisanalytics/container/FlinkContainerManagerTest.java @@ -372,6 +372,9 @@ class FlinkContainerManagerTest { "FLINK_PROPERTIES=jobmanager.rpc.address: localhost\ntaskmanager.numberOfTaskSlots: 3")); assertEquals("container:jm-id", tmSpec.networkMode()); verify(awsEnv).sdkBaselineEnv("us-west-2", Optional.empty()); + // Both JVMs trust Floci's CA, as the job's SDK clients need for Floci over HTTPS. + assertTrue(jmSpec.javaTrustStore()); + assertTrue(tmSpec.javaTrustStore()); } @Test 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 f8e63c9624..2e130da94c 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 @@ -580,6 +580,31 @@ class ContainerLauncherTest { spec.labels()); } + @ParameterizedTest + @CsvSource({"java21, true", "java8.al2, true", "java17, true", "nodejs20.x, false", "python3.13, false", + "provided.al2023, false"}) + void launchFunction_hasTheJvmsOfAJavaRuntimeTrustFlocisCa(String runtime, boolean javaTrustStore) + throws Exception { + Path codePath = Files.createDirectory(tempDir.resolve("code")); + + LambdaFunction fn = new LambdaFunction(); + fn.setFunctionName("runtime-fn"); + fn.setRuntime(runtime); + fn.setHandler("index.handler"); + fn.setCodeLocalPath(codePath.toString()); + + launcher.launch(fn); + + assertEquals(javaTrustStore, captureRealContainerSpec().javaTrustStore()); + } + + @Test + void launchFunction_hasTheJvmsOfAContainerImageTrustFlocisCa() { + launcher.launch(imageFunction()); + + assertTrue(captureRealContainerSpec().javaTrustStore()); + } + @Test void launchFunction_createsWithoutBindMountsOrVolume_forSmallCode() throws Exception { Path codePath = Files.createDirectory(tempDir.resolve("code")); diff --git a/src/test/java/io/github/hectorvent/floci/testing/TestImages.java b/src/test/java/io/github/hectorvent/floci/testing/TestImages.java index 02428666a1..f4bf7f2ba6 100644 --- a/src/test/java/io/github/hectorvent/floci/testing/TestImages.java +++ b/src/test/java/io/github/hectorvent/floci/testing/TestImages.java @@ -27,6 +27,9 @@ public final class TestImages { public static final String PYTHON_ALPINE = "python:3.12-alpine"; + /** Corretto 8, the JVM of Lambda's oldest Java runtime, as a JDK so a test compiles its probe in the container. */ + public static final String CORRETTO_8 = "amazoncorretto:8-alpine-jdk"; + public static final String PGBOUNCER = "edoburu/pgbouncer:v1.24.0-p1"; /** The same image AWS publishes at {@code public.ecr.aws/aws-observability/aws-for-fluent-bit:3}. */