feat(emr): have the JVMs in EMR containers trust Floci's CA (#6926)

With TLS on, every container Floci launches gets the CA bundle and the
SSL_CERT_FILE family of variables, but the JVM reads none of them. So
in the docker runner mode a Spark job's own SDK clients that ignore
AWS_ENDPOINT_URL, the AWS SDK for Java 1.x's or an older 2.x's,
failed with "PKIX path building failed" against Floci's HTTPS, even
with FLOCI_DNS_SPOOF_AWS_ENDPOINTS sending AWS's endpoint names to
Floci. A job could only reach Floci over its HTTP endpoint.

Floci now also writes the bundle's certificates as a PKCS12 trust
store at boot, floci-ca-bundle.p12 beside the bundle. A launcher whose
workload is Java can copy it into a container before the container
starts (ContainerLifecycleManager.copyJavaTrustStore) and point the
container's JVMs at it through JAVA_TOOL_OPTIONS, with a shell line
that does so only when the file is there. The store has no password
and the line gives only its path, so a trust store a job or an image
names itself replaces Floci's, with that store's own type and
password. EMR Serverless job runs and EMR steps copy it into the
driver's container ahead of spark-submit or the step's command, and
the bootstrap actions' container gets it for its actions, then drops
it before the image is kept. Other services' containers are unchanged.

JAVA_TOOL_OPTIONS rather than spark.driver.extraJavaOptions, since
setting that key would replace what the image's spark-defaults.conf
gives it, and a job's own value would drop Floci's. Each JVM prints
"Picked up JAVA_TOOL_OPTIONS: ..." on its standard error, as the docs
now say.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-29 07:50:46 -05:00
1 parent c4ae11c414
commit c9bc1e7cb8
13 files changed
+472 -47

No files matched your search

@@ -9,8 +9,10 @@ import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -36,7 +38,9 @@ import java.util.concurrent.atomic.AtomicBoolean;
* 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.
* 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.
*
* <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
@@ -53,6 +57,25 @@ public final class ContainerCaBundle {
static final List<String> ENV_KEYS = List.of(
"SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "NODE_EXTRA_CA_CERTS", "AWS_CA_BUNDLE");
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;
/**
* 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
* job or an image names then replaces Floci's whole, and its own type and password, or none, apply to it.
*/
public static final String JAVA_TRUST_OPTIONS = "-Djavax.net.ssl.trustStore=" + JAVA_TRUST_STORE_PATH;
/**
* 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.
*/
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";
/** 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();
@@ -87,21 +110,26 @@ public final class ContainerCaBundle {
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);
}
Path target = replace(tlsDir.resolve(FILE_NAME), pem.toString().getBytes(StandardCharsets.UTF_8));
LOG.debugv("TLS: container CA bundle {0} holds {1} public roots and {2} Floci anchor(s)",
target, roots.size(), anchors.size());
return target;
}
/**
* Writes the certificates of {@code bundle}, the file {@link #write} returned, to a PKCS12 trust store
* beside it, {@code floci-ca-bundle.p12}, which a JVM given {@link #JAVA_TRUST_OPTIONS} trusts, swapped in
* as the bundle is. It has no password, so its certificates are neither encrypted nor under a MAC, and a
* JVM reads them with no password or any.
*
* @throws CertificateException when the bundle holds no certificate
*/
public static Path writeJavaTrustStore(Path bundle) throws IOException, GeneralSecurityException {
ByteArrayOutputStream content = new ByteArrayOutputStream();
trustStore(bundle).store(content, null);
return replace(bundle.resolveSibling(JAVA_TRUST_STORE_FILE_NAME), content.toByteArray());
}
/**
* 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.
@@ -124,6 +152,18 @@ public final class ContainerCaBundle {
return Optional.of(bundle);
}
/**
* The trust store {@link #writeJavaTrustStore} wrote on the Floci host, or empty when TLS is off or the
* boot did not manage to write it.
*/
public static Optional<Path> javaTrustStoreHostPath(EmulatorConfig config) {
if (!config.tls().enabled()) {
return Optional.empty();
}
Path trustStore = FlociCertificateAuthorityProducer.tlsDir(config).resolve(JAVA_TRUST_STORE_FILE_NAME);
return Files.isReadable(trustStore) ? Optional.of(trustStore) : Optional.empty();
}
/**
* 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
@@ -189,6 +229,13 @@ public final class ContainerCaBundle {
/** The trust managers of {@link #sslContext(Path)}, over exactly the certificates in {@code bundle}. */
static TrustManager[] trustManagers(Path bundle) throws IOException, GeneralSecurityException {
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(trustStore(bundle));
return factory.getTrustManagers();
}
/** A PKCS12 key store of exactly the certificates in {@code bundle}, each a trusted entry. */
private static KeyStore trustStore(Path bundle) throws IOException, GeneralSecurityException {
List<X509Certificate> certificates = parseCertificates(Files.readString(bundle));
if (certificates.isEmpty()) {
throw new CertificateException(bundle + " holds no certificate");
@@ -198,9 +245,21 @@ public final class ContainerCaBundle {
for (int i = 0; i < certificates.size(); i++) {
trustStore.setCertificateEntry("anchor-" + i, certificates.get(i));
}
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(trustStore);
return factory.getTrustManagers();
return trustStore;
}
/** Puts {@code content} at {@code target} through a temporary file swapped in, as {@link #write} says. */
private static Path replace(Path target, byte[] content) throws IOException {
Path temp = target.resolveSibling(target.getFileName() + "." + UUID.randomUUID() + ".tmp");
try {
Files.write(temp, content);
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException e) {
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(temp);
}
return target;
}
/** Every trust anchor the running JVM accepts by default. */
@@ -417,15 +417,23 @@ public class TlsConfigSource implements ConfigSource {
}
/**
* 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.
* Containers Floci launches get this bundle copied in (Docker) or mounted (Kubernetes), and
* those whose workload is Java its trust store too. 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) {
Path bundle;
try {
ContainerCaBundle.write(tlsDir, trustAnchor);
bundle = ContainerCaBundle.write(tlsDir, trustAnchor);
} catch (Exception e) {
LOG.warnv(e, "TLS: could not write the container CA bundle under {0}: {1}", tlsDir, e.getMessage());
return;
}
try {
ContainerCaBundle.writeJavaTrustStore(bundle);
} catch (Exception e) {
LOG.warnv(e, "TLS: could not write the containers' Java trust store under {0}: {1}", tlsDir,
e.getMessage());
}
}
@@ -34,6 +34,7 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -367,10 +368,7 @@ public class ContainerLifecycleManager {
*/
private boolean copyCaBundle(String containerId, Path bundle) {
try {
byte[] content = Files.readAllBytes(bundle);
RetryingTarCopier.copyBytes(dockerClient, containerId, ContainerCaBundle.CONTAINER_DIR,
ContainerCaBundle.FILE_NAME, content, 0644,
RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, archiveRetryBackoffMillis);
copyIntoContainerDir(containerId, bundle, ContainerCaBundle.FILE_NAME);
LOG.debugv("Copied the CA bundle into container {0} at {1}", containerId, ContainerCaBundle.CONTAINER_PATH);
return true;
} catch (Exception e) {
@@ -381,6 +379,35 @@ public class ContainerLifecycleManager {
}
}
/**
* Copies the CA bundle's Java trust store into {@code containerId}, before it starts, 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
* 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.
*/
public boolean copyJavaTrustStore(String containerId) {
Optional<Path> trustStore = ContainerCaBundle.javaTrustStoreHostPath(config);
if (trustStore.isEmpty()) {
return false;
}
try {
copyIntoContainerDir(containerId, trustStore.get(), ContainerCaBundle.JAVA_TRUST_STORE_FILE_NAME);
return true;
} catch (Exception e) {
LOG.warnv("Could not copy the Java trust store into container {0}, whose JVMs keep the image's trust"
+ " store and will not trust Floci HTTPS: {1}", containerId, e.getMessage());
return false;
}
}
// Copies a file of the CA bundle's to the container's ContainerCaBundle.CONTAINER_DIR as name, readable by
// any user, so a non-root USER can read it.
private void copyIntoContainerDir(String containerId, Path file, String name) throws IOException {
RetryingTarCopier.copyBytes(dockerClient, containerId, ContainerCaBundle.CONTAINER_DIR, name,
Files.readAllBytes(file), 0644, RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, archiveRetryBackoffMillis);
}
/**
* Confirms a name-conflicting container is the one THIS create() call produced, not a stale or
* differently-owned container, and not one from a genuinely concurrent create() sharing the same
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.emr;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Image;
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.ContainerTeardown;
@@ -47,7 +48,8 @@ import java.util.zip.GZIPOutputStream;
* runs its command as it is, and what it leaves in that home is the {@code hadoop} user's. Each action's
* script is read from Floci's S3 as the cluster's account and runs through {@code docker exec}, with the
* credentials of the cluster's EC2 instance profile in its environment alone, so that they never become
* part of the image.
* part of the image. With TLS on, the JVMs an action starts trust Floci's CA, through the Java trust store
* copied in once the container is up, which goes before the image is kept.
*/
@ApplicationScoped
public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
@@ -71,8 +73,10 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
" esac",
"done",
"exec env \"$@\"");
// What each action runs as root: $1 is its script, and the rest that script's arguments.
// What each action runs as root: $1 is its script, and the rest that script's arguments. The JVMs it starts
// trust Floci's CA once the container has its trust store.
private static final String ACTION_COMMAND = String.join("\n",
ContainerCaBundle.JAVA_TRUST_SHELL_LINE,
"mkdir -p /tmp/floci-bin",
"cat > /tmp/floci-bin/sudo <<'SUDO'",
SUDO,
@@ -87,9 +91,10 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
"code=$?",
"chown -R hadoop:hadoop /home/hadoop",
"exit $code");
// Run once every action has: what only the actions needed goes before the image is kept.
private static final String CLEANUP_COMMAND = "rm -f /tmp/floci-bin/sudo /tmp/floci-bootstrap-action-*;"
+ " rmdir /tmp/floci-bin";
// Run once every action has: what only the actions needed goes before the image is kept, the trust store
// included, which each step's container gets afresh.
private static final String CLEANUP_COMMAND = "rm -f /tmp/floci-bin/sudo /tmp/floci-bootstrap-action-* "
+ ContainerCaBundle.JAVA_TRUST_STORE_PATH + "; rmdir /tmp/floci-bin";
// The bootstraps inside run(); a stop for one not here comes after its container has gone, and is dropped.
private final ContainerLaunches launches = new ContainerLaunches();
@@ -136,7 +141,9 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
.build();
String containerId = lifecycleManager.createAndStart(spec).containerId();
launch.started(containerId);
// A stop, a reset or a shutdown while the image was pulled is read now the container is up.
// In before the first action, for the actions' 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.
if (launch.stopRequested() || cancelled.getAsBoolean()) {
return Outcome.halted();
}
@@ -5,6 +5,7 @@ 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;
@@ -45,9 +46,10 @@ import java.util.zip.GZIPOutputStream;
* supplies at run time, which the public image lacks, so the runner starts {@code spark-submit} itself,
* in local mode: the container holds the driver and its executors. The container reaches Floci as the
* other containers Floci launches do, with the run's execution role as its credentials, and S3A, which
* takes {@code s3://} on every release, is pointed at Floci's S3. The driver's output goes to Floci's log and,
* while it runs, to the run's CloudWatch log streams, when it has some; once it ends, its standard output
* and error go, gzipped, to the run's log folder in Floci's S3, when it has one.
* takes {@code s3://} on every release, is pointed at Floci's S3. With TLS on, every JVM in the container
* trusts Floci's CA, through the Java trust store copied in before it starts. The driver's output goes to
* Floci's log and, while it runs, to the run's CloudWatch log streams, when it has some; once it ends, its
* standard output and error go, gzipped, to the run's log folder in Floci's S3, when it has one.
*/
@ApplicationScoped
public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardown {
@@ -55,11 +57,17 @@ 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.
// 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.
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",
@@ -141,10 +149,12 @@ 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) {
container.withEntrypoint(List.of(SPARK_SUBMIT)).withCmd(sparkSubmitArguments(job, endpoint));
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);
} 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));
@@ -156,12 +166,16 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo
.withLogRotation()
.withLabels(labels)
.build();
String containerId = lifecycleManager.createAndStart(spec).containerId();
String containerId = lifecycleManager.create(spec);
launch.started(containerId);
// A stop, a reset or a shutdown while the image was pulled is read now the driver has a container.
// 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()) {
return Outcome.halted();
}
lifecycleManager.startCreated(containerId, spec);
logHandle = attachLog(containerId, job);
progress.started();
Outcome outcome = awaitEnd(containerId, job, launch, progress);