feat(tls): a local root CA that signs Floci's server certificate (#3078)

* refactor(acm): one issuer-signing primitive in CertificateGenerator

buildCertificate always signed with the subject's own key. signCertificate now
takes the issuer DN and key explicitly; generateCaCertificate and
generateIssuedCertificate sit on top of it, with serverAuth or clientAuth EKU on
leaves. Existing public methods keep their signatures and output; metadata now
follows ACM: colon-separated hex serial and the certificate's real signature
algorithm in upper case.

* refactor(cloudhsmv2): sign emulated hardware certificates through CertificateGenerator

Deletes the private generateCert copy; the shared primitive also marks the two
CA levels of the chain as CAs, which the old code did not.

* refactor(acm): normalize imported certificate metadata and check issued key relationships

ImportCertificate now stores the serial as colon-separated hex and the
signature algorithm in upper case, the same shape generated certificates
report. generateIssuedCertificate verifies the leaf against the issuer's
certificate and refuses a supplied key pair whose halves do not match.

* refactor(acm): refuse a supplied key pair that is not of the requested algorithm

* refactor(acm): match a supplied EC key pair by named curve, not field size

* feat(tls): FlociCertificateAuthority, a persistent local root CA

Loads or creates {persistent-path}/tls/floci-root-ca.{crt,key} with an
owner-only key, signs serverAuth and clientAuth leaves through
CertificateGenerator, and regenerates with a WARN when the pair is corrupt,
expired, not a CA, or the key does not match the certificate. A CDI producer
exposes the same pair to beans, using the directory the config bootstrap used.

* feat(tls): issue the HTTPS server certificate from the local CA

The leaf is floci-server.{crt,key}, signed by floci-root-ca; a pre-CA
self-signed leaf, a leaf from a regenerated CA and an expired leaf are replaced
on boot. Published through quarkus.tls.key-store.pem.0.* so the TLS registry
owns it and can reload it. The server key is written owner-only.

* feat: serve the local CA at GET /_floci/ca.pem

TlsLocalCaIntegrationTest boots the HTTP server on the TLS registry keys and
completes a handshake trusting only the PEM this endpoint serves.

* fix(lambda): inject the local root CA into containers instead of the server leaf

The leaf will be reissued as SANs grow; pinning it would break after the first
reissue. The CA is stable.

* docs(tls): trust the local CA once instead of disabling verification

* feat(tls): create private key files owner-only and log why a CA was regenerated

* feat(tls): serve the user certificate from ca.pem in custom-cert mode, log the CA fingerprint

With floci.tls.cert-path set, GET /_floci/ca.pem returns that file, the same
file the Lambda launcher mounts, and creates no local CA. The CA's SHA-256
fingerprint is logged at startup so an out-of-band copy can be checked, and a
file system without POSIX permissions gets a WARN instead of a silent default.

* feat(tls): ca.pem is a bundle in custom-cert mode; clear the bootstrap directory on every boot

With a user-provided certificate the endpoint returns that file followed by
the local CA, so both the HTTPS endpoint and anything Floci issues validate
from one file. TlsConfigSource resets its resolved directory on construction
so a later boot in the same JVM with TLS off or a user certificate never
reuses a stale value.

* docs(lambda): drop two em-dashes from the CA trust javadoc

* test(tls): cover an expired leaf, an expired CA, a missing CA key and the producer's directory choice

* docs(tls): describe IoT device certificates as a follow-up of the local CA
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-05 15:35:30 -04:00
1 parent 4e05fdf582
commit 3c6c005ff1
21 files changed
+1019 -150

No files matched your search

@@ -2314,9 +2314,10 @@ public interface EmulatorConfig {
Optional<String> keyPath();
/**
* Auto-generate a self-signed certificate when no cert-path/key-path provided.
* The generated files are persisted to {@code {storage.persistent-path}/tls/}
* and reused across restarts. Env: FLOCI_TLS_SELF_SIGNED
* Auto-generate a server certificate when no cert-path/key-path is provided. The leaf is
* issued by Floci's local root CA; both live under {@code {storage.persistent-path}/tls/}
* and survive restarts. Clients trust the CA ({@code GET /_floci/ca.pem}), not the leaf.
* Env: FLOCI_TLS_SELF_SIGNED
*/
@WithDefault("true")
boolean selfSigned();
@@ -0,0 +1,196 @@
package io.github.hectorvent.floci.config;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.HexFormat;
import java.util.List;
/**
* Floci's one local root CA. Every certificate the emulator hands out that a client is expected
* to validate (the HTTPS server leaf, and later ACM and IoT device certificates) chains to it, so
* a developer trusts one file once: {@code {persistent-path}/tls/floci-root-ca.crt}, also served
* at {@code GET /_floci/ca.pem}.
*
* <p>Plain class on purpose: {@link TlsConfigSource} needs it before CDI exists. Beans get the
* same pair through {@link FlociCertificateAuthorityProducer}.
*/
public final class FlociCertificateAuthority {
private static final Logger LOG = Logger.getLogger(FlociCertificateAuthority.class);
public static final String CA_CERT_NAME = "floci-root-ca.crt";
public static final String CA_KEY_NAME = "floci-root-ca.key";
static final String COMMON_NAME = "Floci Local CA";
private final Path certificatePath;
private final X509Certificate certificate;
private final PrivateKey key;
private final String caPem;
private final CertificateGenerator generator;
private FlociCertificateAuthority(Path certificatePath, X509Certificate certificate, PrivateKey key,
String caPem, CertificateGenerator generator) {
this.certificatePath = certificatePath;
this.certificate = certificate;
this.key = key;
this.caPem = caPem;
this.generator = generator;
}
/**
* Loads the CA from {@code tlsDir}, or creates one when missing or unusable. A corrupt,
* expired or mismatched pair is regenerated with a WARN: every leaf issued before that moment
* stops validating, which is the correct outcome for a trust anchor nobody can use.
*/
public static FlociCertificateAuthority loadOrCreate(Path tlsDir) {
CertificateGenerator generator = new CertificateGenerator();
Path certFile = tlsDir.resolve(CA_CERT_NAME);
Path keyFile = tlsDir.resolve(CA_KEY_NAME);
try {
if (Files.exists(certFile) && Files.exists(keyFile)) {
try {
String pem = Files.readString(certFile);
X509Certificate cert = generator.parseCertificate(pem);
PrivateKey key = generator.parsePrivateKey(Files.readString(keyFile));
if (cert.getBasicConstraints() < 0) {
throw new IllegalStateException("not a CA certificate (BasicConstraints cA=false)");
}
cert.verify(cert.getPublicKey());
cert.checkValidity();
if (!CertificateGenerator.isPair(key, cert.getPublicKey())) {
throw new IllegalStateException("private key does not match the certificate");
}
restrictToOwnerOnly(tlsDir, "rwx------");
restrictToOwnerOnly(keyFile, "rw-------");
FlociCertificateAuthority ca = new FlociCertificateAuthority(certFile, cert, key, pem, generator);
LOG.infov("TLS: using local CA {0} ({1}), SHA256 fingerprint {2}", certFile,
cert.getSubjectX500Principal().getName(), ca.fingerprint());
return ca;
} catch (Exception e) {
LOG.warnv(e, "TLS: local CA at {0} is unusable ({1}); generating a new one. Clients that trusted "
+ "the old CA must re-import {2}", tlsDir, e.getMessage(), CA_CERT_NAME);
}
}
Files.createDirectories(tlsDir);
restrictToOwnerOnly(tlsDir, "rwx------");
CertificateGenerator.GeneratedCertificate generated = generator.generateCaCertificate(COMMON_NAME);
Files.writeString(certFile, generated.certificatePem());
writePrivateKey(keyFile, generated.privateKeyPem());
FlociCertificateAuthority ca = new FlociCertificateAuthority(certFile,
generator.parseCertificate(generated.certificatePem()),
generator.parsePrivateKey(generated.privateKeyPem()),
generated.certificatePem(), generator);
LOG.infov("TLS: generated local CA {0}, SHA256 fingerprint {1}. Trust it once: GET /_floci/ca.pem",
certFile, ca.fingerprint());
return ca;
} catch (IOException e) {
throw new IllegalStateException("Failed to create local CA under " + tlsDir, e);
}
}
public X509Certificate certificate() {
return certificate;
}
public PrivateKey key() {
return key;
}
/** PEM of the CA certificate, exactly the bytes on disk. */
public String caPem() {
return caPem;
}
public Path certificatePath() {
return certificatePath;
}
/**
* SHA-256 fingerprint of the CA certificate in the form {@code openssl x509 -fingerprint -sha256}
* prints, so a copy obtained out of band can be checked against the startup log.
*/
public String fingerprint() {
try {
return HexFormat.ofDelimiter(":").withUpperCase()
.formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded()));
} catch (Exception e) {
throw new IllegalStateException("Cannot fingerprint the CA certificate", e);
}
}
public CertificateGenerator.Issuer issuer() {
return new CertificateGenerator.Issuer(certificate, key);
}
/**
* A {@code serverAuth} leaf for {@code commonName} plus {@code sans}. {@code keyPair} null
* mints a new key of {@code keyAlgorithm}; passing the current pair keeps the public key
* across a SAN change, and it must be of {@code keyAlgorithm}.
*/
public CertificateGenerator.GeneratedCertificate issueServerCertificate(String commonName, List<String> sans,
KeyAlgorithm keyAlgorithm, KeyPair keyPair) {
return generator.generateIssuedCertificate(commonName, sans, keyAlgorithm, keyPair, issuer(),
CertificateGenerator.LeafUsage.SERVER);
}
/** A {@code clientAuth} leaf, for IoT device certificates. Always a fresh RSA 2048 key pair. */
public CertificateGenerator.GeneratedCertificate issueClientCertificate(String commonName) {
return generator.generateIssuedCertificate(commonName, List.of(), KeyAlgorithm.RSA_2048, null, issuer(),
CertificateGenerator.LeafUsage.CLIENT);
}
/** True when {@code cert} names this CA as issuer and its signature checks against our key. */
public boolean isIssuedByUs(X509Certificate cert) {
if (!certificate.getSubjectX500Principal().equals(cert.getIssuerX500Principal())) {
return false;
}
try {
cert.verify(certificate.getPublicKey());
return true;
} catch (Exception e) {
LOG.debugv("TLS: certificate names our CA but does not verify: {0}", e.getMessage());
return false;
}
}
/**
* Writes a private key so that, where the file system has POSIX permissions, no other user can
* read it at any point: the file is created owner-only before the first byte is written. A
* file system without POSIX permissions gets the platform default and a WARN.
*/
static void writePrivateKey(Path keyFile, String pem) throws IOException {
Files.deleteIfExists(keyFile);
if (Files.getFileAttributeView(keyFile.getParent(), PosixFileAttributeView.class) != null) {
Files.createFile(keyFile, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
} else {
LOG.warnv("TLS: {0} is written with the file system's default permissions because it has no POSIX "
+ "permissions; restrict it to your own account yourself", keyFile);
}
Files.writeString(keyFile, pem);
restrictToOwnerOnly(keyFile, "rw-------");
}
static void restrictToOwnerOnly(Path path, String posixPerms) {
PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class);
if (view == null) {
return;
}
try {
view.setPermissions(PosixFilePermissions.fromString(posixPerms));
} catch (IOException e) {
LOG.warnv("TLS: could not restrict permissions on {0}: {1}", path, e.getMessage());
}
}
}
@@ -0,0 +1,43 @@
package io.github.hectorvent.floci.config;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Inject;
import java.nio.file.Path;
/**
* Exposes {@link FlociCertificateAuthority} to CDI. {@link TlsConfigSource} may already have
* created the files during config bootstrap; this loads the same pair. Lazy, so a boot with TLS
* off and no caller of the CA never touches the disk.
*/
@ApplicationScoped
public class FlociCertificateAuthorityProducer {
static final String TLS_DIR = "tls";
private final EmulatorConfig config;
@Inject
public FlociCertificateAuthorityProducer(EmulatorConfig config) {
this.config = config;
}
@Produces
@ApplicationScoped
FlociCertificateAuthority certificateAuthority() {
return FlociCertificateAuthority.loadOrCreate(tlsDir(config));
}
/**
* 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
* 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.
*/
static Path tlsDir(EmulatorConfig config) {
Path fromBootstrap = TlsConfigSource.resolvedTlsDir();
return fromBootstrap != null ? fromBootstrap : Path.of(config.storage().persistentPath(), TLS_DIR);
}
}
@@ -30,9 +30,9 @@ import java.util.Set;
* would be too late.
*
* <p>
* When TLS is enabled with self-signed mode, the certificate is generated
* using the ACM {@link CertificateGenerator} and persisted under
* {@code {persistent-path}/tls/} for reuse across restarts.
* When TLS is enabled without a user certificate, the server certificate is a leaf issued by
* {@link FlociCertificateAuthority} and persisted under {@code {persistent-path}/tls/}. Clients
* trust the CA ({@code floci-root-ca.crt}, or {@code GET /_floci/ca.pem}), never the leaf.
*
* <p>
* Both HTTP and HTTPS are served simultaneously (LocalStack parity).
@@ -41,9 +41,9 @@ public class TlsConfigSource implements ConfigSource {
private static final Logger LOG = Logger.getLogger(TlsConfigSource.class);
private static final String SELF_SIGNED_CERT_NAME = "floci-selfsigned.crt";
private static final String SELF_SIGNED_KEY_NAME = "floci-selfsigned.key";
private static final String SELF_SIGNED_METADATA_NAME = "floci-selfsigned.metadata.json";
private static final String SERVER_CERT_NAME = "floci-server.crt";
private static final String SERVER_KEY_NAME = "floci-server.key";
private static final String SERVER_METADATA_NAME = "floci-server.metadata.json";
private static final String TLS_DIR = "tls";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@@ -54,9 +54,21 @@ public class TlsConfigSource implements ConfigSource {
"*.execute-api.localhost.floci.io",
"*.execute-api.localhost.localstack.cloud", "host.docker.internal");
private static volatile Path resolvedTlsDir;
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.
*/
static Path resolvedTlsDir() {
return resolvedTlsDir;
}
public TlsConfigSource() {
resolvedTlsDir = null;
String enabled = resolveProperty("floci.tls.enabled", "false");
if (!"true".equalsIgnoreCase(enabled)) {
LOG.debug("TLS disabled — TlsConfigSource inactive");
@@ -74,29 +86,26 @@ public class TlsConfigSource implements ConfigSource {
LOG.infov("TLS: using user-provided certificate: {0}", certPath);
} else if ("true".equalsIgnoreCase(selfSigned)) {
Path tlsDir = Path.of(persistentPath, TLS_DIR);
Path certFile = tlsDir.resolve(SELF_SIGNED_CERT_NAME);
Path keyFile = tlsDir.resolve(SELF_SIGNED_KEY_NAME);
resolvedTlsDir = tlsDir;
Path certFile = tlsDir.resolve(SERVER_CERT_NAME);
Path keyFile = tlsDir.resolve(SERVER_KEY_NAME);
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
// Check if certificate files exist and configuration hasn't changed
if (Files.exists(certFile) && Files.exists(keyFile)) {
// Extract current hostname configuration
List<String> customHostnames = extractCustomHostnames();
List<String> currentHostnames = new ArrayList<>();
currentHostnames.addAll(DEFAULT_SAN_HOSTNAMES);
currentHostnames.addAll(customHostnames);
// Regenerate when the hostname config changed, or when the existing certificate
// is a legacy non-self-signed cert (issuer != subject) — those cannot serve as a
// trust anchor for clients that install them, so an upgrade must replace them.
if (hostnameConfigChanged(tlsDir, currentHostnames) || !isSelfSigned(certFile)) {
generateSelfSignedCert(tlsDir, certFile, keyFile);
List<String> currentHostnames = new ArrayList<>(DEFAULT_SAN_HOSTNAMES);
currentHostnames.addAll(extractCustomHostnames());
// Regenerate when the hostname config changed, when the existing leaf was not
// issued by the current CA (a pre-CA self-signed cert, or the CA was regenerated),
// or when it is outside its validity window (the leaf lives 365 days, dev data
// directories longer).
if (hostnameConfigChanged(tlsDir, currentHostnames) || !isValidLocalLeaf(ca, certFile)) {
generateServerCert(tlsDir, certFile, keyFile, ca);
} else {
// Configuration unchanged - reuse existing certificate
LOG.infov("TLS: reusing existing self-signed certificate: {0}", certFile);
LOG.infov("TLS: reusing existing server certificate: {0}", certFile);
}
} else {
// Certificate files don't exist - generate new certificate
generateSelfSignedCert(tlsDir, certFile, keyFile);
generateServerCert(tlsDir, certFile, keyFile, ca);
}
certPath = certFile.toAbsolutePath().toString();
@@ -107,8 +116,10 @@ public class TlsConfigSource implements ConfigSource {
+ "Set FLOCI_TLS_CERT_PATH + FLOCI_TLS_KEY_PATH, or enable FLOCI_TLS_SELF_SIGNED.");
}
properties.put("quarkus.http.ssl.certificate.files", certPath);
properties.put("quarkus.http.ssl.certificate.key-files", keyPath);
// 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);
properties.put("quarkus.tls.key-store.pem.0.key", keyPath);
// When TLS is enabled, Quarkus HTTP and HTTPS run on internal ports.
// A TlsProxyServer (NetServer) listens on the public Floci port (4566)
// and does protocol detection to route HTTP and HTTPS to the correct backend.
@@ -162,31 +173,23 @@ public class TlsConfigSource implements ConfigSource {
return defaultValue;
}
private void generateSelfSignedCert(Path tlsDir, Path certFile, Path keyFile) {
private void generateServerCert(Path tlsDir, Path certFile, Path keyFile, FlociCertificateAuthority ca) {
try {
Files.createDirectories(tlsDir);
List<String> allSans = new ArrayList<>(DEFAULT_SAN_HOSTNAMES);
allSans.addAll(extractCustomHostnames());
// Extract custom hostnames and combine with defaults
List<String> customHostnames = extractCustomHostnames();
List<String> allSans = new ArrayList<>();
allSans.addAll(DEFAULT_SAN_HOSTNAMES);
allSans.addAll(customHostnames);
CertificateGenerator gen = new CertificateGenerator();
CertificateGenerator.GeneratedCertificate generated = gen.generateSelfSignedCertificate(
"localhost",
allSans,
KeyAlgorithm.RSA_2048);
CertificateGenerator.GeneratedCertificate generated = ca.issueServerCertificate("localhost", allSans,
KeyAlgorithm.RSA_2048, null);
Files.writeString(certFile, generated.certificatePem());
Files.writeString(keyFile, generated.privateKeyPem());
FlociCertificateAuthority.writePrivateKey(keyFile, generated.privateKeyPem());
LOG.infov("TLS: generated self-signed certificate: {0}", certFile);
// Persist metadata for change detection on restart
LOG.infov("TLS: generated server certificate {0} issued by {1}", certFile,
ca.certificate().getSubjectX500Principal().getName());
persistMetadata(tlsDir, allSans);
} catch (IOException e) {
throw new IllegalStateException("Failed to write self-signed TLS certificate", e);
throw new IllegalStateException("Failed to write TLS server certificate", e);
}
}
@@ -198,16 +201,21 @@ public class TlsConfigSource implements ConfigSource {
}
/**
* Returns {@code true} if the certificate at {@code certFile} is genuinely self-signed
* (issuer == subject) and therefore usable as a trust anchor. Legacy Floci certs carried a
* cosmetic Amazon issuer DN and return {@code false} here, triggering regeneration on upgrade.
* Returns {@code true} if the certificate at {@code certFile} was issued by the current local
* CA and is inside its validity window. A pre-CA self-signed leaf, a leaf from a regenerated
* CA, an expired leaf or an unreadable file all return {@code false} and are replaced.
*/
private boolean isSelfSigned(Path certFile) {
private boolean isValidLocalLeaf(FlociCertificateAuthority ca, Path certFile) {
try {
X509Certificate cert = new CertificateGenerator().parseCertificate(Files.readString(certFile));
return cert.getIssuerX500Principal().equals(cert.getSubjectX500Principal());
if (!ca.isIssuedByUs(cert)) {
LOG.infov("TLS: existing server certificate was not issued by the local CA; regenerating");
return false;
}
cert.checkValidity();
return true;
} catch (Exception e) {
LOG.warnv("TLS: could not inspect existing certificate ({0}); regenerating", e.getMessage());
LOG.warnv("TLS: existing server certificate unusable ({0}); regenerating", e.getMessage());
return false;
}
}
@@ -263,13 +271,13 @@ public class TlsConfigSource implements ConfigSource {
/**
* Persists certificate metadata to enable change detection on restart.
* Writes metadata to {tls-dir}/floci-selfsigned.metadata.json.
* Writes metadata to {tls-dir}/floci-server.metadata.json.
*
* @param tlsDir The TLS directory where metadata should be written
* @param hostnames List of hostnames included in the certificate SANs
*/
private void persistMetadata(Path tlsDir, List<String> hostnames) {
Path metadataFile = tlsDir.resolve(SELF_SIGNED_METADATA_NAME);
Path metadataFile = tlsDir.resolve(SERVER_METADATA_NAME);
try {
String version = resolveFlociVersion();
CertificateMetadata metadata = CertificateMetadata.create(hostnames, version);
@@ -306,7 +314,7 @@ public class TlsConfigSource implements ConfigSource {
* @return true if configuration changed or metadata missing, false if same
*/
private boolean hostnameConfigChanged(Path tlsDir, List<String> currentHostnames) {
Path metadataFile = tlsDir.resolve(SELF_SIGNED_METADATA_NAME);
Path metadataFile = tlsDir.resolve(SERVER_METADATA_NAME);
// If metadata doesn't exist, trigger regeneration
if (!Files.exists(metadataFile)) {
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.lifecycle;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook;
import jakarta.inject.Inject;
@@ -14,8 +16,11 @@ import io.github.hectorvent.floci.core.common.Resettable;
import jakarta.enterprise.inject.Instance;
import jakarta.ws.rs.POST;
import java.io.IOException;
import java.nio.file.Files;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
@Path("{prefix:(_floci|_localstack)}")
@Produces(MediaType.APPLICATION_JSON)
@@ -27,16 +32,22 @@ public class EmulatorInfoController {
private final StorageFactory storageFactory;
private final Instance<Resettable> resettables;
private final FlociCertificateAuthority certificateAuthority;
private final EmulatorConfig config;
@Inject
public EmulatorInfoController(ServiceRegistry serviceRegistry,
InitLifecycleState initLifecycleState,
StorageFactory storageFactory,
Instance<Resettable> resettables) {
Instance<Resettable> resettables,
FlociCertificateAuthority certificateAuthority,
EmulatorConfig config) {
this.serviceRegistry = serviceRegistry;
this.initLifecycleState = initLifecycleState;
this.storageFactory = storageFactory;
this.resettables = resettables;
this.certificateAuthority = certificateAuthority;
this.config = config;
this.version = resolveVersion();
}
@@ -90,6 +101,36 @@ public class EmulatorInfoController {
return Response.ok(Map.of()).build();
}
/**
* 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},
* {@code NODE_EXTRA_CA_CERTS}, a keychain) and both validate.
*/
@GET
@Path("/ca.pem")
@Produces(MediaType.TEXT_PLAIN)
public String caPem() throws IOException {
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;
}
/** Set when TLS serves a user-provided certificate, the same condition {@code TlsConfigSource} applies. */
private Optional<String> userCertificatePath() {
if (!config.tls().enabled() || config.tls().keyPath().filter(p -> !p.isBlank()).isEmpty()) {
return Optional.empty();
}
return config.tls().certPath().filter(p -> !p.isBlank());
}
@POST
@Path("/state/reset")
public Response reset() {
@@ -99,15 +99,15 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
/**
* In-container location of Floci's CA certificate, injected when TLS is enabled so the
* container trusts Floci's self-signed HTTPS endpoint. {@code /etc} exists in every Lambda
* 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;
/** Self-signed cert filename produced by {@code TlsConfigSource} under {persistent-path}/tls/. */
private static final String SELF_SIGNED_CERT_NAME = "floci-selfsigned.crt";
/** 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");
@@ -228,7 +228,7 @@ 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 self-signed cert so HTTPS callbacks
// 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()
@@ -1372,11 +1372,11 @@ 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 the self-signed cert under
* 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. The auto-generated Floci cert is one; a user-supplied
* 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.
*/
@@ -1388,7 +1388,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
Optional<String> trimmedUserPath = userCertPath.filter(s -> !s.isBlank());
Path certPath = trimmedUserPath
.map(Path::of)
.orElseGet(() -> Path.of(persistentPath, "tls", SELF_SIGNED_CERT_NAME));
.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);
@@ -1405,7 +1405,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
/**
* 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.
* (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) {
@@ -1429,7 +1429,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
* <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
* 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