mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(docker): containers Floci launches trust the Floci CA (#3091)
* feat(tls): write a CA bundle for launched containers at boot
Containers Floci launches need to trust Floci's HTTPS endpoint from any runtime
without losing access to public HTTPS. A bundle that carries the JVM's public
roots followed by Floci's trust anchor makes that possible: the variables that
replace a runtime's trust store (SSL_CERT_FILE and friends) can then point at
it safely.
ContainerCaBundle writes {persistent-path}/tls/floci-ca-bundle.pem from the
JVM's default trust anchors plus the certificates in the anchor file: the local
CA, or the user-provided certificate file in custom-certificate mode. Only
certificates are copied out of that file, so a combined certificate-and-key
file never leaks its key into a container. The file is swapped in atomically
from a uniquely named temporary file. TlsConfigSource writes it in both
certificate modes; a failure is logged and never stops the boot.
hostPath(config) resolves the bundle in the directory the bootstrap used, so a
persistent path set only in application.yml cannot point it elsewhere, and
appendEnv(env) adds SSL_CERT_FILE, CURL_CA_BUNDLE, REQUESTS_CA_BUNDLE,
NODE_EXTRA_CA_CERTS and AWS_CA_BUNDLE without overriding a key the caller set.
The bootstrap now records its TLS directory in every TLS-on mode, not only when
it issues the leaf, so the CA producer and the bundle lookup read from the
directory the boot wrote to even when a persistent path is set in
application.yml alone. A missing bundle is reported once per process.
* feat(docker): every launched container gets the CA bundle and the trust variables
ContainerLifecycleManager.create is the single path every emulator-created
container passes through, so injecting trust there covers Lambda, ECS, MWAA,
Flink, RDS, ElastiCache, Batch and the rest at once.
With TLS on and the bundle present, create appends the five trust variables
after the spec's own environment (a value from a task or function definition
wins) and copies the bundle to /etc/floci-ca-bundle.pem in the created, not
yet started, container. A copy rather than a bind mount, because when Floci
itself runs in Docker its persistent path is not a host path the daemon can
mount. A failed copy is logged with its consequence and the container still
starts. With TLS off, or without a bundle, nothing changes.
* refactor(lambda): take container CA trust from the lifecycle manager bundle
The Lambda launcher no longer resolves, copies or announces the CA itself: the
lifecycle manager does that for every container. Its append-only policy
(NODE_EXTRA_CA_CERTS and AWS_CA_BUNDLE only, never SSL_CERT_FILE) existed
because a bare CA would have cut a function off from public HTTPS; the bundle
carries the public roots, so the policy and the test that guarded it go.
The Kubernetes launcher publishes the bundle in its ConfigMap instead of the
bare CA, mounts it at /etc/floci-ca-bundle.pem, and appends the trust
variables after the function's own environment so a function value wins, as
in the Docker launcher.
* test(docker): a launched container trusts Floci and public roots through the bundle
The unit tests pin the variables and the copy, not that a runtime reading them
actually trusts Floci and still reaches public HTTPS. A python:3.12-alpine
container launched through the lifecycle manager, with the image's own root
directory pointed away so only the bundle can supply roots, fetches
https://host.docker.internal:<port>/_floci/ca.pem and https://public.ecr.aws/
with no setup of its own. Skipped without a Docker daemon, like the other
*DockerIntegrationTest classes; the image is prefetched in CI with the
others.
* docs(tls): containers Floci launches trust the Floci CA
Describe the bundle every launched container receives, the five variables that
point at it, that a value set on the function or task definition wins, and
that the JVM ignores these variables so a Java workload still needs its own
trust store.
* fix(docker): recreate a container without the trust variables when the bundle cannot be copied
SSL_CERT_FILE, CURL_CA_BUNDLE and REQUESTS_CA_BUNDLE replace a runtime's trust
store, so a container whose bundle copy failed (an image without /etc) used to
start pointing them at a file that was not there, and lost every HTTPS
connection instead of only the ones to Floci. The lifecycle manager now removes
that container and creates it again without the variables, so it keeps the
image's own trust store. The host configuration, and with it any dynamic host
port, is built once and reused.
* fix(tls): serve only the certificate blocks of a user-provided file from ca.pem
In custom-certificate mode GET /_floci/ca.pem returned the configured
certificate file byte for byte, so a combined certificate-and-key file, the
form OpenSSL tooling produces, handed the server's private key to any caller.
The endpoint now goes through the same certificate-only parsing the container
bundle uses. TlsUserCertIntegrationTest boots on a combined file and asserts
the response holds the user certificate and the local CA and no key.
* test(cloudformation): wait for DeleteStack to finish before asserting on deleted resources
DeleteStack hands the work to an executor and answers at once. Seven tests in
CloudFormationIntegrationTest asserted on the deleted resources right after the
answer; one of them, deleteStack_ecs_leavesNoOrphans, failed shard 1 of this
pull request's CI 44 ms later with the cluster still ACTIVE, while the same
shard had passed on the previous push.
A shared awaitStackDeleted polls DescribeStacks until the stack reports
DELETE_COMPLETE or no longer exists, fails on DELETE_FAILED or after ten
seconds, and replaces the three inline copies of that loop as well.
* docs(tls): restore the learned-hostnames section and the ACM wording that #3079 dropped
#3079's docs commit (dc3e9ee6a) was written against a tls.md that predated
#3086 and, once squashed onto main, removed the "Custom Domains Learned at
Runtime" section #3086 had added and reworded the intro to place ACM
certificates "in a later release", although AcmService has issued them from
the local CA since #3086. Both are restored here, next to the new section,
because a separate PR would conflict with this one on the same lines.
This commit is contained in:
1 parent
d45c64545d
commit
024bfa0a5c
24 files changed
+1143
-367
No files matched your search
@@ -0,0 +1,187 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import org.bouncycastle.cert.X509CertificateHolder;
|
||||
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
|
||||
import org.bouncycastle.openssl.PEMParser;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.cert.CertificateEncodingException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* The CA bundle Floci hands to every container it launches, so the workload inside can call Floci
|
||||
* over HTTPS (custom domains included) from any runtime without trusting anything by hand.
|
||||
*
|
||||
* <p>The bundle is the JVM's default trust anchors followed by Floci's own trust anchor: the local
|
||||
* CA, or the user-provided certificate file in custom-certificate mode. Carrying the public roots
|
||||
* is what makes it safe to point the <em>replacing</em> variables ({@code SSL_CERT_FILE},
|
||||
* {@code CURL_CA_BUNDLE}, {@code REQUESTS_CA_BUNDLE}) at it: the workload still reaches public
|
||||
* HTTPS endpoints. {@code NODE_EXTRA_CA_CERTS} appends to Node's roots and {@code AWS_CA_BUNDLE}
|
||||
* only applies to AWS SDK and CLI traffic, so both are harmless with the same file.
|
||||
*
|
||||
* <p>Written by {@link TlsConfigSource} at boot; copied into containers by the Docker lifecycle
|
||||
* manager and mounted from a ConfigMap by the Kubernetes Lambda launcher. Plain class because the
|
||||
* config source runs before CDI exists.
|
||||
*/
|
||||
public final class ContainerCaBundle {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ContainerCaBundle.class);
|
||||
|
||||
public static final String FILE_NAME = "floci-ca-bundle.pem";
|
||||
public static final String CONTAINER_DIR = "/etc";
|
||||
public static final String CONTAINER_PATH = CONTAINER_DIR + "/" + FILE_NAME;
|
||||
|
||||
static final List<String> ENV_KEYS = List.of(
|
||||
"SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "NODE_EXTRA_CA_CERTS", "AWS_CA_BUNDLE");
|
||||
|
||||
/** A missing bundle is a boot-time condition, so it is worth one WARN per process, not one per container. */
|
||||
private static final AtomicBoolean MISSING_BUNDLE_WARNED = new AtomicBoolean();
|
||||
|
||||
private ContainerCaBundle() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes {@code tlsDir/floci-ca-bundle.pem}: the JVM's trust anchors, then every certificate in
|
||||
* {@code trustAnchorFile}. Only certificates are copied out of that file, so a combined
|
||||
* certificate-and-key file never leaks its key into a container. The file is swapped in
|
||||
* atomically from a uniquely named temporary file, so a container created during a boot never
|
||||
* reads a half-written bundle, even when two Floci processes share the directory.
|
||||
*
|
||||
* @throws IllegalArgumentException when the anchor file holds no certificate
|
||||
* @throws IllegalStateException when the JVM has no trust anchors at all: a bundle without
|
||||
* public roots would cut containers off from public HTTPS
|
||||
*/
|
||||
public static Path write(Path tlsDir, Path trustAnchorFile) throws IOException, GeneralSecurityException {
|
||||
List<X509Certificate> anchors = parseCertificates(Files.readString(trustAnchorFile));
|
||||
if (anchors.isEmpty()) {
|
||||
throw new IllegalArgumentException(trustAnchorFile + " holds no certificate");
|
||||
}
|
||||
List<X509Certificate> roots = systemRoots();
|
||||
if (roots.isEmpty()) {
|
||||
throw new IllegalStateException("the JVM has no default trust anchors");
|
||||
}
|
||||
StringBuilder pem = new StringBuilder();
|
||||
for (X509Certificate root : roots) {
|
||||
pem.append(toPem(root));
|
||||
}
|
||||
for (X509Certificate anchor : anchors) {
|
||||
pem.append(toPem(anchor));
|
||||
}
|
||||
Files.createDirectories(tlsDir);
|
||||
Path target = tlsDir.resolve(FILE_NAME);
|
||||
Path temp = tlsDir.resolve(FILE_NAME + "." + UUID.randomUUID() + ".tmp");
|
||||
try {
|
||||
Files.writeString(temp, pem.toString());
|
||||
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException e) {
|
||||
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
} finally {
|
||||
Files.deleteIfExists(temp);
|
||||
}
|
||||
LOG.debugv("TLS: container CA bundle {0} holds {1} public roots and {2} Floci anchor(s)",
|
||||
target, roots.size(), anchors.size());
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* The bundle on the Floci host, or empty when TLS is off or the boot did not manage to write
|
||||
* it. Looks in the directory the bootstrap used, next to the CA.
|
||||
*/
|
||||
public static Optional<Path> hostPath(EmulatorConfig config) {
|
||||
if (!config.tls().enabled()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Path bundle = FlociCertificateAuthorityProducer.tlsDir(config).resolve(FILE_NAME);
|
||||
if (!Files.isReadable(bundle)) {
|
||||
if (MISSING_BUNDLE_WARNED.compareAndSet(false, true)) {
|
||||
LOG.warnv("TLS is enabled but {0} is missing; containers launched now will not trust Floci HTTPS", bundle);
|
||||
} else {
|
||||
LOG.debugv("Container CA bundle {0} still missing", bundle);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
MISSING_BUNDLE_WARNED.set(false);
|
||||
return Optional.of(bundle);
|
||||
}
|
||||
|
||||
/**
|
||||
* The certificate blocks of a PEM text, re-encoded one after the other; a private key or any
|
||||
* other PEM object in the text is dropped. What Floci hands out from a user-provided certificate
|
||||
* file, for the bundle and for {@code GET /_floci/ca.pem}, goes through here.
|
||||
*/
|
||||
public static String certificatePem(String pem) throws IOException, GeneralSecurityException {
|
||||
StringBuilder certificates = new StringBuilder();
|
||||
for (X509Certificate certificate : parseCertificates(pem)) {
|
||||
certificates.append(toPem(certificate));
|
||||
}
|
||||
return certificates.toString();
|
||||
}
|
||||
|
||||
/** The {@code KEY=value} entries that make each runtime read {@link #CONTAINER_PATH}. */
|
||||
public static List<String> env() {
|
||||
return appendEnv(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code env} followed by {@link #env()}, skipping every key the caller already set (with or
|
||||
* without a value), so a value from a function or task definition always wins.
|
||||
*/
|
||||
public static List<String> appendEnv(List<String> env) {
|
||||
List<String> merged = new ArrayList<>(env == null ? List.of() : env);
|
||||
for (String key : ENV_KEYS) {
|
||||
if (merged.stream().noneMatch(entry -> entry.equals(key) || entry.startsWith(key + "="))) {
|
||||
merged.add(key + "=" + CONTAINER_PATH);
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
/** Every trust anchor the running JVM accepts by default. */
|
||||
private static List<X509Certificate> systemRoots() throws GeneralSecurityException {
|
||||
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
factory.init((KeyStore) null);
|
||||
List<X509Certificate> roots = new ArrayList<>();
|
||||
for (var manager : factory.getTrustManagers()) {
|
||||
if (manager instanceof X509TrustManager x509) {
|
||||
roots.addAll(List.of(x509.getAcceptedIssuers()));
|
||||
}
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
/** The certificates in a PEM text, in order; keys and any other PEM object are skipped. */
|
||||
private static List<X509Certificate> parseCertificates(String pem) throws IOException, GeneralSecurityException {
|
||||
List<X509Certificate> certificates = new ArrayList<>();
|
||||
JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
|
||||
try (PEMParser parser = new PEMParser(new StringReader(pem))) {
|
||||
for (Object object = parser.readObject(); object != null; object = parser.readObject()) {
|
||||
if (object instanceof X509CertificateHolder holder) {
|
||||
certificates.add(converter.getCertificate(holder));
|
||||
}
|
||||
}
|
||||
}
|
||||
return certificates;
|
||||
}
|
||||
|
||||
private static String toPem(X509Certificate certificate) throws CertificateEncodingException {
|
||||
return "-----BEGIN CERTIFICATE-----\n"
|
||||
+ Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(certificate.getEncoded())
|
||||
+ "\n-----END CERTIFICATE-----\n";
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -32,9 +32,10 @@ public class FlociCertificateAuthorityProducer {
|
||||
/**
|
||||
* The one TLS directory. {@link TlsConfigSource} runs before CDI and resolves
|
||||
* {@code floci.storage.persistent-path} from system properties and environment only; when it
|
||||
* laid down the CA, every CDI consumer must use exactly that directory, or a persistent path set
|
||||
* ran with TLS on, every CDI consumer must use exactly that directory, or a persistent path set
|
||||
* in application.yml alone would produce a second CA (served leaf signed by one, ca.pem from
|
||||
* the other). With TLS off the bootstrap never ran and the configured path is the only truth.
|
||||
* the other) and lose the container CA bundle it wrote there. With TLS off the bootstrap laid
|
||||
* nothing down and the configured path is the only truth.
|
||||
*/
|
||||
static Path tlsDir(EmulatorConfig config) {
|
||||
Path fromBootstrap = TlsConfigSource.resolvedTlsDir();
|
||||
|
||||
@@ -35,6 +35,10 @@ import java.util.Set;
|
||||
* trust the CA ({@code floci-root-ca.crt}, or {@code GET /_floci/ca.pem}), never the leaf.
|
||||
*
|
||||
* <p>
|
||||
* It also writes {@link ContainerCaBundle}, the trust bundle every container Floci launches
|
||||
* receives, next to the certificates.
|
||||
*
|
||||
* <p>
|
||||
* Both HTTP and HTTPS are served simultaneously (LocalStack parity).
|
||||
*/
|
||||
public class TlsConfigSource implements ConfigSource {
|
||||
@@ -59,9 +63,11 @@ public class TlsConfigSource implements ConfigSource {
|
||||
private final Map<String, String> properties = new HashMap<>();
|
||||
|
||||
/**
|
||||
* The directory the most recent bootstrap used for CA and leaf, or null when that bootstrap did
|
||||
* not run the self-signed branch (TLS off, or a user-provided certificate). Reset on every
|
||||
* construction so a later boot in the same JVM never sees a stale value.
|
||||
* The TLS directory the most recent bootstrap used, or null when that bootstrap ran with TLS
|
||||
* off. With a user-provided certificate it holds the container CA bundle and, once
|
||||
* {@code GET /_floci/ca.pem} is called, the local CA; in self-signed mode the CA and the leaf
|
||||
* as well. Reset on every construction so a later boot in the same JVM never sees a stale
|
||||
* value.
|
||||
*/
|
||||
static Path resolvedTlsDir() {
|
||||
return resolvedTlsDir;
|
||||
@@ -79,17 +85,20 @@ public class TlsConfigSource implements ConfigSource {
|
||||
String keyPath = resolveProperty("floci.tls.key-path", "");
|
||||
String selfSigned = resolveProperty("floci.tls.self-signed", "true");
|
||||
String persistentPath = resolveProperty("floci.storage.persistent-path", "./data");
|
||||
Path tlsDir = Path.of(persistentPath, TLS_DIR);
|
||||
resolvedTlsDir = tlsDir;
|
||||
|
||||
Path trustAnchor;
|
||||
if (!certPath.isBlank() && !keyPath.isBlank()) {
|
||||
validateFileExists(certPath, "TLS certificate");
|
||||
validateFileExists(keyPath, "TLS private key");
|
||||
LOG.infov("TLS: using user-provided certificate: {0}", certPath);
|
||||
trustAnchor = Path.of(certPath);
|
||||
} else if ("true".equalsIgnoreCase(selfSigned)) {
|
||||
Path tlsDir = Path.of(persistentPath, TLS_DIR);
|
||||
resolvedTlsDir = tlsDir;
|
||||
Path certFile = tlsDir.resolve(SERVER_CERT_NAME);
|
||||
Path keyFile = tlsDir.resolve(SERVER_KEY_NAME);
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
|
||||
trustAnchor = ca.certificatePath();
|
||||
|
||||
if (Files.exists(certFile) && Files.exists(keyFile)) {
|
||||
List<String> currentHostnames = new ArrayList<>(DEFAULT_SAN_HOSTNAMES);
|
||||
@@ -116,6 +125,8 @@ public class TlsConfigSource implements ConfigSource {
|
||||
+ "Set FLOCI_TLS_CERT_PATH + FLOCI_TLS_KEY_PATH, or enable FLOCI_TLS_SELF_SIGNED.");
|
||||
}
|
||||
|
||||
writeContainerCaBundle(tlsDir, trustAnchor);
|
||||
|
||||
// The default entry of the Quarkus TLS registry. The HTTP server reads it when no
|
||||
// quarkus.http.tls-configuration-name is set, and the registry can reload it at runtime.
|
||||
properties.put("quarkus.tls.key-store.pem.0.cert", certPath);
|
||||
@@ -246,6 +257,19 @@ public class TlsConfigSource implements ConfigSource {
|
||||
return sans;
|
||||
}
|
||||
|
||||
/**
|
||||
* Containers Floci launches get this bundle copied in (Docker) or mounted (Kubernetes). A
|
||||
* failure here must not stop Floci: log it, and containers simply will not trust Floci HTTPS
|
||||
* until a boot manages to write it.
|
||||
*/
|
||||
private static void writeContainerCaBundle(Path tlsDir, Path trustAnchor) {
|
||||
try {
|
||||
ContainerCaBundle.write(tlsDir, trustAnchor);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "TLS: could not write the container CA bundle under {0}: {1}", tlsDir, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateFileExists(String path, String description) {
|
||||
if (!Files.isReadable(Path.of(path))) {
|
||||
throw new IllegalStateException(
|
||||
|
||||
+58
-2
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import io.github.hectorvent.floci.config.ContainerCaBundle;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
@@ -21,9 +22,15 @@ import com.github.dockerjava.api.model.Ports;
|
||||
import com.github.dockerjava.core.command.WaitContainerResultCallback;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -121,8 +128,25 @@ public class ContainerLifecycleManager {
|
||||
private String create(ContainerSpec spec, String resolvedImage, String platform) {
|
||||
LOG.debugv("Creating container from spec: image={0}, name={1}", spec.image(), spec.name());
|
||||
|
||||
// Built once: a dynamic port binding allocates its host port here.
|
||||
HostConfig hostConfig = buildHostConfig(spec);
|
||||
Optional<Path> caBundle = ContainerCaBundle.hostPath(config);
|
||||
if (caBundle.isEmpty()) {
|
||||
return createContainer(spec, resolvedImage, platform, hostConfig, spec.env());
|
||||
}
|
||||
String containerId = createContainer(spec, resolvedImage, platform, hostConfig,
|
||||
ContainerCaBundle.appendEnv(spec.env()));
|
||||
if (copyCaBundle(containerId, caBundle.get())) {
|
||||
return containerId;
|
||||
}
|
||||
// SSL_CERT_FILE and friends replace the image's trust store, so they must never name a
|
||||
// file that is not there. Start over without them: the container keeps its own trust.
|
||||
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
|
||||
return createContainer(spec, resolvedImage, platform, hostConfig, spec.env());
|
||||
}
|
||||
|
||||
private String createContainer(ContainerSpec spec, String resolvedImage, String platform,
|
||||
HostConfig hostConfig, List<String> env) {
|
||||
CreateContainerCmd createCmd = dockerClient.createContainerCmd(resolvedImage)
|
||||
.withHostConfig(hostConfig);
|
||||
|
||||
@@ -136,8 +160,8 @@ public class ContainerLifecycleManager {
|
||||
if (spec.user() != null && !spec.user().isBlank()) {
|
||||
createCmd.withUser(spec.user());
|
||||
}
|
||||
if (spec.env() != null && !spec.env().isEmpty()) {
|
||||
createCmd.withEnv(spec.env());
|
||||
if (env != null && !env.isEmpty()) {
|
||||
createCmd.withEnv(env);
|
||||
}
|
||||
if (spec.cmd() != null && !spec.cmd().isEmpty()) {
|
||||
createCmd.withCmd(spec.cmd());
|
||||
@@ -162,6 +186,38 @@ public class ContainerLifecycleManager {
|
||||
return containerId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the CA bundle into the created, not yet started, container so runtimes that read
|
||||
* {@code SSL_CERT_FILE} and friends at init find it. A copy rather than a bind mount because
|
||||
* when Floci itself runs in Docker its persistent path is not a host path the daemon can mount.
|
||||
* Returns false, after logging why, when the copy failed; an image without {@code /etc} is the
|
||||
* expected reason, and the caller then recreates the container without the trust variables.
|
||||
*/
|
||||
private boolean copyCaBundle(String containerId, Path bundle) {
|
||||
try {
|
||||
byte[] content = Files.readAllBytes(bundle);
|
||||
ByteArrayOutputStream archive = new ByteArrayOutputStream(content.length + 1024);
|
||||
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(archive)) {
|
||||
TarArchiveEntry entry = new TarArchiveEntry(ContainerCaBundle.FILE_NAME);
|
||||
entry.setSize(content.length);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(content);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
dockerClient.copyArchiveToContainerCmd(containerId)
|
||||
.withRemotePath(ContainerCaBundle.CONTAINER_DIR)
|
||||
.withTarInputStream(new ByteArrayInputStream(archive.toByteArray()))
|
||||
.exec();
|
||||
LOG.debugv("Copied the CA bundle into container {0} at {1}", containerId, ContainerCaBundle.CONTAINER_PATH);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Could not copy the CA bundle into container {0}; creating it again without the trust "
|
||||
+ "variables, so it keeps its own trust store and will not trust Floci HTTPS: {1}",
|
||||
containerId, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a previously created container and resolves its endpoints.
|
||||
*
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.lifecycle;
|
||||
|
||||
import io.github.hectorvent.floci.config.ContainerCaBundle;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
|
||||
import io.github.hectorvent.floci.core.common.ServiceRegistry;
|
||||
@@ -18,6 +19,7 @@ import jakarta.ws.rs.POST;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -105,22 +107,21 @@ public class EmulatorInfoController {
|
||||
* The PEM a client needs to trust Floci. With the default configuration that is the local root
|
||||
* CA alone: it signs the HTTPS certificate and every certificate Floci issues. With a
|
||||
* user-provided certificate ({@code floci.tls.cert-path}) the HTTPS endpoint is signed by that
|
||||
* certificate's issuer instead, so the response is a bundle: the user certificate file first
|
||||
* (the same file the Lambda launcher mounts into containers), then the local CA, which still
|
||||
* signs what Floci itself issues. Trust the file once ({@code AWS_CA_BUNDLE},
|
||||
* certificate's issuer instead, so the response is a bundle: the certificates in the user
|
||||
* certificate file first (never a private key that file may also hold), then the local CA,
|
||||
* which still signs what Floci itself issues. Trust the file once ({@code AWS_CA_BUNDLE},
|
||||
* {@code NODE_EXTRA_CA_CERTS}, a keychain) and both validate.
|
||||
*/
|
||||
@GET
|
||||
@Path("/ca.pem")
|
||||
@Produces(MediaType.TEXT_PLAIN)
|
||||
public String caPem() throws IOException {
|
||||
public String caPem() throws IOException, GeneralSecurityException {
|
||||
String localCa = certificateAuthority.caPem();
|
||||
Optional<String> userCertificate = userCertificatePath();
|
||||
if (userCertificate.isEmpty()) {
|
||||
return localCa;
|
||||
}
|
||||
String userPem = Files.readString(java.nio.file.Path.of(userCertificate.get()));
|
||||
return userPem.endsWith("\n") ? userPem + localCa : userPem + "\n" + localCa;
|
||||
return ContainerCaBundle.certificatePem(Files.readString(java.nio.file.Path.of(userCertificate.get()))) + localCa;
|
||||
}
|
||||
|
||||
/** Set when TLS serves a user-provided certificate, the same condition {@code TlsConfigSource} applies. */
|
||||
|
||||
-108
@@ -41,8 +41,6 @@ import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
@@ -97,18 +95,6 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
return configured;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-container location of Floci's CA certificate, injected when TLS is enabled so the
|
||||
* container trusts Floci's HTTPS endpoint through the local CA. {@code /etc} exists in every Lambda
|
||||
* base image, so no directory needs to be created.
|
||||
*/
|
||||
private static final String FLOCI_CA_DIR = "/etc";
|
||||
private static final String FLOCI_CA_FILE_NAME = "floci-ca.crt";
|
||||
/** Shared with the kubernetes executor, which mounts the CA ConfigMap at the same path. */
|
||||
public static final String FLOCI_CA_CONTAINER_PATH = FLOCI_CA_DIR + "/" + FLOCI_CA_FILE_NAME;
|
||||
/** Root CA produced by {@code FlociCertificateAuthority} under {persistent-path}/tls/. */
|
||||
private static final String LOCAL_CA_CERT_NAME = io.github.hectorvent.floci.config.FlociCertificateAuthority.CA_CERT_NAME;
|
||||
|
||||
private static final DateTimeFormatter LOG_STREAM_DATE_FMT = DateTimeFormatter.ofPattern("yyyy/MM/dd");
|
||||
|
||||
private final ContainerBuilder containerBuilder;
|
||||
@@ -228,13 +214,6 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
String lambdaRegion = extractRegionFromArn(fn.getFunctionArn(), config.defaultRegion());
|
||||
String lambdaAccountId = AwsArnUtils.accountOrDefault(fn.getFunctionArn(), config.defaultAccountId());
|
||||
|
||||
// When TLS is on, the container must trust Floci's local CA so HTTPS callbacks
|
||||
// to Floci succeed (e.g. a CDK custom resource's cfn-response, which hardcodes https://).
|
||||
// Short-circuit when TLS is off so cert-path/storage config isn't read needlessly.
|
||||
Optional<Path> flociCaCert = config.tls().enabled()
|
||||
? resolveFlociCaCertPath(true, config.tls().certPath(), config.storage().persistentPath())
|
||||
: Optional.empty();
|
||||
|
||||
// Build env vars
|
||||
List<String> env = new ArrayList<>();
|
||||
env.add("AWS_LAMBDA_RUNTIME_API=" + runtimeApiEndpoint);
|
||||
@@ -258,7 +237,6 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
env.addAll(awsEnv.sdkBaselineEnv(lambdaRegion,
|
||||
awsConfigPath.isPresent() ? Optional.of("/opt/aws-config") : Optional.empty(),
|
||||
roleCredentials, lambdaAccountId));
|
||||
env.addAll(flociCaEnv(flociCaCert));
|
||||
if (fn.getEnvironment() != null) {
|
||||
boolean hasExecutionRoleCredentials = roleCredentials.isPresent();
|
||||
boolean userDefinesFullCredentialTriad = definesFullCredentialTriad(fn.getEnvironment());
|
||||
@@ -424,15 +402,6 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Copy Floci's CA cert so the container trusts Floci's HTTPS endpoint (TLS mode).
|
||||
// Placed before start so NODE_EXTRA_CA_CERTS et al. resolve at runtime init.
|
||||
// An if-block rather than ifPresent(...) because containerId is assigned along the
|
||||
// code-volume path and so is not effectively final for a lambda capture.
|
||||
if (flociCaCert.isPresent()) {
|
||||
copyFileToContainer(dockerClient, containerId, flociCaCert.get(),
|
||||
FLOCI_CA_DIR, FLOCI_CA_FILE_NAME, fn.getFunctionName());
|
||||
}
|
||||
|
||||
// Now start the container with code in place
|
||||
lifecycleManager.startCreated(containerId, spec);
|
||||
|
||||
@@ -1369,83 +1338,6 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the host path of Floci's CA certificate to inject into Lambda containers, or
|
||||
* empty when TLS is disabled or no readable certificate exists. Mirrors {@code TlsConfigSource}:
|
||||
* a user-provided {@code floci.tls.cert-path} wins; otherwise Floci's local root CA under
|
||||
* {@code {persistent-path}/tls/}.
|
||||
*
|
||||
* <p>The resolved certificate is injected into containers as a <em>trust anchor</em> (CA), so it
|
||||
* should be a self-signed CA certificate. Floci's local CA is one; a user-supplied
|
||||
* {@code floci.tls.cert-path} that points at a leaf/server certificate is accepted but only pins
|
||||
* that exact certificate (it cannot validate a chain it signs), so a warning is logged.
|
||||
*/
|
||||
public static Optional<Path> resolveFlociCaCertPath(boolean tlsEnabled, Optional<String> userCertPath,
|
||||
String persistentPath) {
|
||||
if (!tlsEnabled) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<String> trimmedUserPath = userCertPath.filter(s -> !s.isBlank());
|
||||
Path certPath = trimmedUserPath
|
||||
.map(Path::of)
|
||||
.orElseGet(() -> Path.of(persistentPath, "tls", LOCAL_CA_CERT_NAME));
|
||||
if (!Files.isReadable(certPath)) {
|
||||
LOG.warnv("TLS enabled but Floci CA certificate not readable at {0}; "
|
||||
+ "Lambda containers will not trust Floci HTTPS callbacks", certPath);
|
||||
return Optional.empty();
|
||||
}
|
||||
if (trimmedUserPath.isPresent() && !isSelfSignedCaCertificate(certPath)) {
|
||||
LOG.warnv("Configured floci.tls.cert-path {0} is not a self-signed CA certificate; it is "
|
||||
+ "injected into Lambda containers as a trust anchor (CA), which only validates "
|
||||
+ "this exact certificate and not a chain it signs. Provide a self-signed CA "
|
||||
+ "certificate for reliable HTTPS callbacks.", certPath);
|
||||
}
|
||||
return Optional.of(certPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true} only if {@code certPath} holds a genuinely self-signed CA certificate
|
||||
* (issuer == subject and BasicConstraints {@code CA:true}): the form usable as a trust anchor.
|
||||
* A leaf/server certificate, or one that cannot be read/parsed as X.509, returns {@code false}.
|
||||
*/
|
||||
static boolean isSelfSignedCaCertificate(Path certPath) {
|
||||
try (InputStream in = Files.newInputStream(certPath)) {
|
||||
X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
|
||||
.generateCertificate(in);
|
||||
boolean selfSigned = cert.getSubjectX500Principal().equals(cert.getIssuerX500Principal());
|
||||
boolean isCa = cert.getBasicConstraints() >= 0; // -1 == not a CA
|
||||
return selfSigned && isCa;
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not inspect TLS certificate {0} for CA suitability: {1}",
|
||||
certPath, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Environment entries that make the container <em>add</em> Floci's CA to its trust, without
|
||||
* replacing the system trust store (which would break the Lambda's external HTTPS calls):
|
||||
* <ul>
|
||||
* <li>{@code NODE_EXTRA_CA_CERTS} appends Floci's cert to Node's built-in CAs, so public TLS
|
||||
* from the Lambda still works; and</li>
|
||||
* <li>{@code AWS_CA_BUNDLE} is scoped to AWS SDK/CLI traffic, which Floci redirects to its own
|
||||
* endpoint via {@code AWS_ENDPOINT_URL}, so pointing it at Floci's cert only affects
|
||||
* calls that already target Floci.</li>
|
||||
* </ul>
|
||||
* {@code SSL_CERT_FILE} and {@code REQUESTS_CA_BUNDLE} are deliberately <em>not</em> set: each
|
||||
* <em>replaces</em> the entire OpenSSL / Python-requests trust store with only Floci's cert,
|
||||
* which breaks every external HTTPS call (curl, openssl, requests/botocore) the Lambda makes.
|
||||
* Returns an empty list when no CA cert is available (TLS off).
|
||||
*/
|
||||
public static List<String> flociCaEnv(Optional<Path> caCert) {
|
||||
if (caCert.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
return List.of(
|
||||
"NODE_EXTRA_CA_CERTS=" + FLOCI_CA_CONTAINER_PATH,
|
||||
"AWS_CA_BUNDLE=" + FLOCI_CA_CONTAINER_PATH);
|
||||
}
|
||||
|
||||
private static String extractRegionFromArn(String arn, String defaultRegion) {
|
||||
return AwsArnUtils.regionOrDefault(arn, defaultRegion);
|
||||
}
|
||||
|
||||
+11
-12
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.lambda.launcher.kubernetes;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import io.github.hectorvent.floci.config.ContainerCaBundle;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
@@ -169,11 +170,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
var codeDownloadUrl = imagePackage ? null : codeDownloadUrl(fn, region);
|
||||
var layerUrls = imagePackage ? List.<String>of() : layerDownloadUrls(fn, region);
|
||||
|
||||
var caCert = config.tls().enabled()
|
||||
? ContainerLauncher.resolveFlociCaCertPath(true, config.tls().certPath(),
|
||||
config.storage().persistentPath())
|
||||
: Optional.<Path>empty();
|
||||
var caConfigMap = caCert.map(cert -> ensureCaConfigMap(namespace, cert));
|
||||
var caConfigMap = ContainerCaBundle.hostPath(config).map(bundle -> ensureCaConfigMap(namespace, bundle));
|
||||
|
||||
var env = new ArrayList<String>();
|
||||
env.add("AWS_LAMBDA_RUNTIME_API=" + addressResolver.resolve() + ":" + runtimeApiServer.getPort());
|
||||
@@ -188,7 +185,6 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
}
|
||||
env.addAll(awsEnv.sdkBaselineEnv(region, Optional.empty(), addressResolver.flociBaseUrl(),
|
||||
Optional.empty(), AwsArnUtils.accountOrDefault(fn.getFunctionArn(), config.defaultAccountId())));
|
||||
env.addAll(ContainerLauncher.flociCaEnv(caCert));
|
||||
if (fn.getEnvironment() != null) {
|
||||
// Same all-or-nothing rule as ContainerLauncher: this launcher never has
|
||||
// execution-role credentials, so the function's own Environment may only supply
|
||||
@@ -208,7 +204,9 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
fn.getImageConfigCommand(), fn.getImageConfigWorkingDirectory())
|
||||
: null;
|
||||
|
||||
var pod = podSpecFactory.buildPod(podName, fn.getFunctionName(), image, env,
|
||||
// After the function's own variables, so a value it sets wins, as in the docker launcher.
|
||||
var podEnv = caConfigMap.isPresent() ? ContainerCaBundle.appendEnv(env) : env;
|
||||
var pod = podSpecFactory.buildPod(podName, fn.getFunctionName(), image, podEnv,
|
||||
codeDownloadUrl, layerUrls, isProvidedRuntime(fn.getRuntime()),
|
||||
imagePackage ? null : fn.getHandler(), imageConfig, fn.getMemorySize(), caConfigMap);
|
||||
|
||||
@@ -514,15 +512,16 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes Floci's CA cert as a ConfigMap so pods can trust Floci's HTTPS endpoint.
|
||||
* Applied once per process; the cert cannot rotate within a Floci lifetime.
|
||||
* Publishes the CA bundle as a ConfigMap so pods can trust Floci's HTTPS endpoint and still
|
||||
* reach public HTTPS. Applied once per process; the bundle is written at boot and does not
|
||||
* change within a Floci lifetime.
|
||||
*/
|
||||
private String ensureCaConfigMap(String namespace, Path caCertPath) {
|
||||
private String ensureCaConfigMap(String namespace, Path bundle) {
|
||||
if (caConfigMapApplied.get()) {
|
||||
return CA_CONFIG_MAP_NAME;
|
||||
}
|
||||
try {
|
||||
var pem = Files.readString(caCertPath);
|
||||
var pem = Files.readString(bundle);
|
||||
var nodes = JsonNodeFactory.instance;
|
||||
var labels = nodes.objectNode();
|
||||
LambdaPodSpecFactory.managedPodSelector().forEach(labels::put);
|
||||
@@ -535,7 +534,7 @@ public class KubernetesPodLauncher implements LambdaRuntimeLauncher {
|
||||
caConfigMapApplied.set(true);
|
||||
return CA_CONFIG_MAP_NAME;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Could not publish Floci CA cert ConfigMap '" + CA_CONFIG_MAP_NAME
|
||||
throw new RuntimeException("Could not publish the Floci CA bundle ConfigMap '" + CA_CONFIG_MAP_NAME
|
||||
+ "' in namespace " + namespace + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -3,8 +3,8 @@ package io.github.hectorvent.floci.services.lambda.launcher.kubernetes;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.ContainerCaBundle;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.ContainerLauncher;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -60,7 +60,7 @@ public class LambdaPodSpecFactory {
|
||||
* @param providedRuntime whether the runtime is provided.* (bootstrap needs an exec bit)
|
||||
* @param handlerOrNull function handler used as the runtime container arg (Zip functions)
|
||||
* @param imageConfig Image-package-type entrypoint/command/workingdir; empty lists/null when unset
|
||||
* @param caConfigMapName ConfigMap holding Floci's CA cert, mounted at /etc/floci-ca.crt when present
|
||||
* @param caConfigMapName ConfigMap holding the CA bundle, mounted at /etc/floci-ca-bundle.pem when present
|
||||
*/
|
||||
public ObjectNode buildPod(String podName,
|
||||
String functionName,
|
||||
@@ -100,7 +100,7 @@ public class LambdaPodSpecFactory {
|
||||
.set("configMap", nodes.objectNode().put("name", cm)));
|
||||
runtimeMounts.add(nodes.objectNode()
|
||||
.put("name", "floci-ca")
|
||||
.put("mountPath", ContainerLauncher.FLOCI_CA_CONTAINER_PATH)
|
||||
.put("mountPath", ContainerCaBundle.CONTAINER_PATH)
|
||||
.put("subPath", KubernetesPodLauncher.CA_CONFIG_MAP_KEY)
|
||||
.put("readOnly", true));
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user