Light, fluffy, and always free - The AWS Local Emulator alternative
feat(tls): a local root CA that signs Floci's server certificate (#3078)
Mario Toffia3c6c005ff1a0
diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.mdindex 763d6de196..36360fd5fb 100644--- a/docs/configuration/advanced/application-yml.md+++ b/docs/configuration/advanced/application-yml.md@@ -95,7 +95,7 @@ floci:enabled: false # FLOCI_TLS_ENABLED — enable HTTPS on all endpoints# cert-path: "" # FLOCI_TLS_CERT_PATH — PEM certificate file path# key-path: "" # FLOCI_TLS_KEY_PATH — PEM private key file path- self-signed: true # FLOCI_TLS_SELF_SIGNED — auto-generate cert when no paths provided+ self-signed: true # FLOCI_TLS_SELF_SIGNED: auto-generate a cert signed by the local CA when no paths providedprotocols:max-request-size: 2048 # FLOCI_PROTOCOLS_MAX_REQUEST_SIZE — max HTTP request body size in MB (legacy: floci.max-request-size / FLOCI_MAX_REQUEST_SIZE)diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.mdindex a408ecebf8..2617f81dac 100644--- a/docs/configuration/environment-variables.md+++ b/docs/configuration/environment-variables.md@@ -42,7 +42,7 @@ Floci is configured exclusively through environment variables. Every option belo| `FLOCI_TLS_ENABLED` | `false` | Enable TLS/HTTPS on all endpoints (HTTP remains available simultaneously) || `FLOCI_TLS_CERT_PATH` | _(none)_ | Path to a PEM certificate file. When set, disables auto-generation || `FLOCI_TLS_KEY_PATH` | _(none)_ | Path to a PEM private key file. Required when `FLOCI_TLS_CERT_PATH` is set |-| `FLOCI_TLS_SELF_SIGNED` | `true` | Auto-generate and persist a self-signed certificate when no cert/key paths are provided |+| `FLOCI_TLS_SELF_SIGNED` | `true` | Auto-generate and persist a server certificate signed by Floci's local CA when no cert/key paths are provided |See [TLS / HTTPS](./tls.md) for SDK configuration examples and WebSocket (`wss://`) support.diff --git a/docs/configuration/tls.md b/docs/configuration/tls.mdindex 65b964ba18..0feb0828be 100644--- a/docs/configuration/tls.md+++ b/docs/configuration/tls.md@@ -8,20 +8,39 @@ Floci supports optional TLS, enabling `https://` for all REST/JSON/Query endpoindocker run -e FLOCI_TLS_ENABLED=true -p 4566:4566 floci/floci:latest```-Then point your SDK at `https://localhost:4566`. Since the certificate is self-signed, disable TLS verification in your client:+Then point your SDK at `https://localhost:4566` and trust Floci's local CA in the processes that talk to it. Every certificate Floci issues (its HTTPS endpoint, and in later releases ACM and IoT device certificates) chains to that one CA:```bash-# AWS CLI-aws --endpoint-url https://localhost:4566 --no-verify-ssl sts get-caller-identity+curl -s http://localhost:4566/_floci/ca.pem -o floci-root-ca.pem-# Node.js-NODE_TLS_REJECT_UNAUTHORIZED=0 node app.js+# AWS CLI and every AWS SDK+export AWS_CA_BUNDLE=$PWD/floci-root-ca.pem+aws --endpoint-url https://localhost:4566 sts get-caller-identity-# Python (boto3)-import boto3-client = boto3.client('sts', endpoint_url='https://localhost:4566', verify=False)+# Node.js (appends to the built-in roots)+export NODE_EXTRA_CA_CERTS=$PWD/floci-root-ca.pem++# curl, Python, Go on Linux (replaces the default roots for that process only)+export SSL_CERT_FILE=$PWD/floci-root-ca.pem+```++Prefer these per-process variables, and scope them to the shell or the tool (a `.envrc`, a compose `environment:` block) that needs them. They cannot affect anything else on the machine.++The download above is plain HTTP and carries no proof of who sent it, which is fine on loopback and nowhere else. For a client on another host, or over a network you do not control, copy the file out of band instead: read `{persistent-path}/tls/floci-root-ca.crt` from Floci's volume, or `docker cp` it out of the container. Either way, compare the fingerprint before trusting it. Floci logs it at startup as `TLS: ... SHA256 fingerprint AB:CD:...`, and the file's fingerprint is:++```bash+openssl x509 -in floci-root-ca.pem -noout -fingerprint -sha256+```++Installing the CA into the operating system trust store (macOS `security add-trusted-cert`, Linux `update-ca-certificates`) also works and is what Safari, Chrome and Go on macOS need, but understand what it does: every process on the machine then trusts anything signed by the key in `{persistent-path}/tls/floci-root-ca.key`. Keep that file private, treat the CA as a dev-machine secret, and remove it from the store when you stop using Floci:++```bash+# macOS login keychain; remove later with: security delete-certificate -c "Floci Local CA"+security add-trusted-cert -r trustRoot -k ~/Library/Keychains/login.keychain-db floci-root-ca.pem```+Disabling verification (`--no-verify-ssl`, `verify=False`, `NODE_TLS_REJECT_UNAUTHORIZED=0`) still works but is no longer needed.+## Configuration| Environment Variable | Default | Description |@@ -29,22 +48,24 @@ client = boto3.client('sts', endpoint_url='https://localhost:4566', verify=False| `FLOCI_TLS_ENABLED` | `false` | Enable TLS/HTTPS on the server || `FLOCI_TLS_CERT_PATH` | *(unset)* | Path to PEM certificate file || `FLOCI_TLS_KEY_PATH` | *(unset)* | Path to PEM private key file |-| `FLOCI_TLS_SELF_SIGNED` | `true` | Auto-generate a self-signed certificate when no cert/key paths provided |+| `FLOCI_TLS_SELF_SIGNED` | `true` | Auto-generate a server certificate signed by Floci's local CA when no cert/key paths provided |-## Self-Signed Certificate+## Local CA and Server Certificate-When `FLOCI_TLS_ENABLED=true` and no custom certificate is provided, Floci auto-generates a self-signed certificate at startup. The certificate:+When `FLOCI_TLS_ENABLED=true` and no custom certificate is provided, Floci keeps a local root CA at `{persistent-path}/tls/floci-root-ca.crt` (key `floci-root-ca.key`, owner-only) and issues its server certificate `floci-server.crt` from it at startup. The server certificate:- Is persisted to `{persistent-path}/tls/` and reused across restarts- Includes `localhost`, `127.0.0.1`, `0.0.0.0`, `*.localhost`, `localhost.floci.io`,`*.localhost.floci.io`, `*.execute-api.localhost.floci.io`, and`*.execute-api.localhost.localstack.cloud` as Subject Alternative Names (SANs)- Automatically includes custom hostnames from `FLOCI_HOSTNAME` and `FLOCI_BASE_URL` in the SANs-- Is regenerated when hostname configuration changes between restarts+- Is regenerated when hostname configuration changes between restarts, or when it was not issued by the current CA++The CA is created once and never rotates on its own. If its files are missing, corrupt or do not match each other, Floci generates a new CA, logs a warning, and reissues the server certificate; clients then need the new `ca.pem`.### Custom Hostname Support-If you set `FLOCI_HOSTNAME` or use a custom host in `FLOCI_BASE_URL`, the self-signed certificate automatically includes those hostnames in its SANs. This is essential for Docker Compose setups where containers reference Floci by service name:+If you set `FLOCI_HOSTNAME` or use a custom host in `FLOCI_BASE_URL`, the server certificate automatically includes those hostnames in its SANs. This is essential for Docker Compose setups where containers reference Floci by service name:```yamlservices:@@ -59,10 +80,10 @@ services:app:environment:AWS_ENDPOINT_URL: "https://floci:4566"- NODE_TLS_REJECT_UNAUTHORIZED: "0"+ AWS_CA_BUNDLE: /floci/floci-root-ca.pem```-The generated certificate will include `floci` in its SANs, so TLS validation succeeds when `app` connects to `https://floci:4566`.+The generated certificate will include `floci` in its SANs, so TLS validation succeeds when `app` connects to `https://floci:4566`. Fetch `ca.pem` from Floci into `app` (an entrypoint `curl`, or a shared volume mounted from `{persistent-path}/tls/`) so the bundle path above exists.## User-Provided Certificates@@ -78,7 +99,7 @@ docker run \floci/floci:latest```-When custom certificate paths are provided, `FLOCI_TLS_SELF_SIGNED` is ignored and no self-signed certificate is generated.+When custom certificate paths are provided, `FLOCI_TLS_SELF_SIGNED` is ignored and the HTTPS server uses your certificate; no server certificate is generated. `GET /_floci/ca.pem` then returns a PEM bundle: your certificate file first, then Floci's local CA, which is created on first use and is the CA that will sign the certificates Floci itself issues (IoT device certificates, in a follow-up). Put the CA or the full chain in your certificate file if clients fetch their trust anchor from Floci; a bare leaf only lets them pin that one certificate.## WebSocket (wss://)@@ -88,23 +109,26 @@ When TLS is enabled, WebSocket connections automatically use `wss://`:wss://localhost:4566/ws/{apiId}/{stage}```-No additional configuration is needed — Vert.x handles TLS at the transport layer transparently.+No additional configuration is needed: Vert.x handles TLS at the transport layer transparently.## SDK Configuration Examples+With `AWS_CA_BUNDLE` set as in Quick Start, no SDK needs code changes. The examples below trust the CA in code instead, for processes whose environment you do not control.+### AWS SDK for JavaScript v3```typescriptimport { STSClient } from '@aws-sdk/client-sts';import { NodeHttpHandler } from '@smithy/node-http-handler';import https from 'node:https';+import { readFileSync } from 'node:fs';const client = new STSClient({endpoint: 'https://localhost:4566',region: 'us-east-1',credentials: { accessKeyId: 'test', secretAccessKey: 'test' },requestHandler: new NodeHttpHandler({- httpsAgent: new https.Agent({ rejectUnauthorized: false }),+ httpsAgent: new https.Agent({ ca: readFileSync('floci-root-ca.pem') }),}),});```@@ -112,7 +136,7 @@ const client = new STSClient({Or set the environment variable globally:```bash-NODE_TLS_REJECT_UNAUTHORIZED=0 npx vitest run+NODE_EXTRA_CA_CERTS=$PWD/floci-root-ca.pem npx vitest run```### AWS SDK for Java v2@@ -120,14 +144,18 @@ NODE_TLS_REJECT_UNAUTHORIZED=0 npx vitest run```javaSdkHttpClient httpClient = ApacheHttpClient.builder().tlsTrustManagersProvider(() -> {- TrustManager[] trustAll = new TrustManager[]{- new X509TrustManager() {- public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }- public void checkClientTrusted(X509Certificate[] certs, String authType) {}- public void checkServerTrusted(X509Certificate[] certs, String authType) {}- }- };- return trustAll;+ try {+ var ca = CertificateFactory.getInstance("X.509")+ .generateCertificate(Files.newInputStream(Path.of("floci-root-ca.pem")));+ var trust = KeyStore.getInstance(KeyStore.getDefaultType());+ trust.load(null, null);+ trust.setCertificateEntry("floci", ca);+ var factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());+ factory.init(trust);+ return factory.getTrustManagers();+ } catch (Exception e) {+ throw new IllegalStateException(e);+ }}).build();@@ -145,7 +173,7 @@ import boto3client = boto3.client('sts',endpoint_url='https://localhost:4566',- verify=False, # Disable TLS verification for self-signed cert+ verify='floci-root-ca.pem', # or export AWS_CA_BUNDLEregion_name='us-east-1',aws_access_key_id='test',aws_secret_access_key='test',@@ -156,7 +184,7 @@ client = boto3.client(| Certificate type | Verification disabled? | Why ||-----------------|----------------------|-----|-| Floci self-signed (default) | **Yes** — `NODE_TLS_REJECT_UNAUTHORIZED=0`, `verify=False`, etc. | The self-signed CA is not in your system's trust store |+| Floci local CA (default) | **No**, once you trust `floci-root-ca.crt` (`GET /_floci/ca.pem`) | One CA covers the HTTPS endpoint and every certificate Floci issues || `mkcert` with local CA installed | **No** | `mkcert -install` adds its root CA to the OS trust store || Corporate/internal CA already trusted | **No** | Your OS or JVM already trusts the issuing CA || Public CA (Let's Encrypt, etc.) | **No** | Trusted by default in all runtimes |@@ -166,13 +194,19 @@ In short: you only need to disable verification when the certificate's issuer is## Troubleshooting**Certificate errors after changing `FLOCI_HOSTNAME`.**-Floci detects hostname configuration changes and regenerates the certificate automatically. If you still see errors, delete the `{persistent-path}/tls/` directory and restart.+Floci detects hostname configuration changes and regenerates the server certificate automatically. If you still see errors, delete the `{persistent-path}/tls/` directory and restart. That also creates a new CA, so re-download `ca.pem`.-**`DEPTH_ZERO_SELF_SIGNED_CERT` in Node.js.**-This only happens with self-signed certificates. Set `NODE_TLS_REJECT_UNAUTHORIZED=0` or configure a custom HTTPS agent that skips verification. If you use `mkcert` and ran `mkcert -install`, this error should not occur.+**`UNABLE_TO_GET_ISSUER_CERT_LOCALLY` or `DEPTH_ZERO_SELF_SIGNED_CERT` in Node.js.**+The process does not trust the Floci CA yet. Set `NODE_EXTRA_CA_CERTS` to `ca.pem` or pass it as the agent's `ca` option as shown above.**Java `SSLHandshakeException: PKIX path building failed`.**-For self-signed certificates: configure a trust-all TrustManager as shown above, or import the certificate into your JVM's truststore with `keytool -importcert`. For user-provided certificates from a trusted CA, this should not occur.+Import `ca.pem` into the trust store the client uses (`keytool -importcert -file floci-root-ca.pem -alias floci -cacerts`, or a `TrustManager` built from it as shown above). For user-provided certificates from a trusted CA, this should not occur.++**`Go: x509: certificate signed by unknown authority` on macOS.**+Go on macOS ignores `SSL_CERT_FILE` and reads the keychain. Pin the CA in code with `x509.NewCertPool().AppendCertsFromPEM` (the AWS SDK for Go honours `AWS_CA_BUNDLE` regardless), or add it to the login keychain as shown in Quick Start.++**I regenerated `{persistent-path}/tls/`.**+That created a new CA. Re-download `/_floci/ca.pem` wherever you installed the old one.**Certificate doesn't include my custom hostname.**Ensure `FLOCI_HOSTNAME` or `FLOCI_BASE_URL` is set *before* Floci starts. The certificate is generated during startup. Check the logs for `TLS: detected custom hostnames: [...]`.diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 252e4b0695..1f9f7d84d5 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -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();diff --git a/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.javanew file mode 100644index 0000000000..dccedc25f6--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java@@ -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());+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityProducer.java b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityProducer.javanew file mode 100644index 0000000000..61ac97195a--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityProducer.java@@ -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);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.javaindex f8dd8e6161..c4ad2cc968 100644--- a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java+++ b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java@@ -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 changedif (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());-- LOG.infov("TLS: generated self-signed certificate: {0}", certFile);+ FlociCertificateAuthority.writePrivateKey(keyFile, generated.privateKeyPem());- // 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 regenerationif (!Files.exists(metadataFile)) {diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoController.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoController.javaindex c03f688c87..d4ae5ab52a 100644--- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoController.java+++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoController.java@@ -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;@Injectpublic 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() {diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.javaindex cb1cdcd2a0..a2a1cbce3d 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java@@ -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: eachdiff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex c70045243c..4494f5da78 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -216,7 +216,7 @@ floci:enabled: false # FLOCI_TLS_ENABLED (default: false)# cert-path: "" # FLOCI_TLS_CERT_PATH (PEM certificate file)# key-path: "" # FLOCI_TLS_KEY_PATH (PEM private key file)- self-signed: true # FLOCI_TLS_SELF_SIGNED — auto-generate a self-signed cert if no cert-path provided+ self-signed: true # FLOCI_TLS_SELF_SIGNED: auto-generate a server cert signed by Floci's local CA if no cert-path providedaws-https-port: 443 # FLOCI_TLS_AWS_HTTPS_PORT — also bind 443 so CDK cfn-response/AWS-on-443 callbacks reach Floci (0 disables)protocols:diff --git a/src/test/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityProducerTest.java b/src/test/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityProducerTest.javanew file mode 100644index 0000000000..d1eaa78367--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityProducerTest.java@@ -0,0 +1,59 @@+package io.github.hectorvent.floci.config;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++import java.nio.file.Path;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * The producer must hand beans the directory the config bootstrap used, and only fall back to the+ * configured persistent path when the bootstrap laid nothing down.+ */+class FlociCertificateAuthorityProducerTest {++ @TempDir+ Path tempDir;++ @AfterEach+ void clearBootstrap() {+ System.clearProperty("floci.tls.enabled");+ System.clearProperty("floci.tls.self-signed");+ System.clearProperty("floci.storage.persistent-path");+ new TlsConfigSource();+ }++ private static EmulatorConfig configWithPersistentPath(String path) {+ EmulatorConfig config = mock(EmulatorConfig.class);+ EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);+ when(config.storage()).thenReturn(storage);+ when(storage.persistentPath()).thenReturn(path);+ return config;+ }++ @Test+ void usesTheBootstrapDirectoryWhenTheBootstrapIssuedTheLeaf() {+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());+ new TlsConfigSource();++ Path dir = FlociCertificateAuthorityProducer.tlsDir(configWithPersistentPath("/elsewhere/from/yaml"));++ assertEquals(tempDir.resolve("tls"), dir, "one directory for the served leaf and ca.pem, or two CAs would exist");+ }++ @Test+ void fallsBackToTheConfiguredPathWhenTlsIsOff() {+ System.setProperty("floci.tls.enabled", "false");+ new TlsConfigSource();++ Path dir = FlociCertificateAuthorityProducer.tlsDir(configWithPersistentPath(tempDir.toString()));++ assertEquals(tempDir.resolve("tls"), dir);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityTest.java b/src/test/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityTest.javanew file mode 100644index 0000000000..65c0efd925--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/FlociCertificateAuthorityTest.java@@ -0,0 +1,189 @@+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.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;++import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.attribute.PosixFilePermission;+import java.nio.file.attribute.PosixFilePermissions;+import java.security.cert.X509Certificate;+import java.util.List;+import java.util.Set;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++class FlociCertificateAuthorityTest {++ @TempDir+ Path tempDir;++ @Test+ void createsCaFilesWithOwnerOnlyKey() throws Exception {+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);++ assertTrue(Files.exists(tempDir.resolve("floci-root-ca.crt")));+ assertTrue(Files.exists(tempDir.resolve("floci-root-ca.key")));+ assertEquals(tempDir.resolve("floci-root-ca.crt"), ca.certificatePath());+ assertTrue(ca.certificate().getBasicConstraints() >= 0, "CA must be cA=true");+ assertTrue(ca.certificate().getKeyUsage()[5], "CA must assert keyCertSign");+ assertEquals(ca.certificate().getSubjectX500Principal(), ca.certificate().getIssuerX500Principal());+ assertEquals("CN=Floci Local CA", ca.certificate().getSubjectX500Principal().getName());+ assertTrue(ca.caPem().startsWith("-----BEGIN CERTIFICATE-----"));+ assertEquals(Files.readString(tempDir.resolve("floci-root-ca.crt")), ca.caPem(), "caPem is the file's bytes");+ assertTrue(ca.fingerprint().matches("([0-9A-F]{2}:){31}[0-9A-F]{2}"), ca.fingerprint());+ assertEquals(ca.fingerprint(), FlociCertificateAuthority.loadOrCreate(tempDir).fingerprint());++ Set<PosixFilePermission> keyPerms = Files.getPosixFilePermissions(tempDir.resolve("floci-root-ca.key"));+ assertEquals(PosixFilePermissions.fromString("rw-------"), keyPerms);+ assertEquals(PosixFilePermissions.fromString("rwx------"), Files.getPosixFilePermissions(tempDir));+ }++ @Test+ void createsTheDirectoryWhenMissing() {+ Path tlsDir = tempDir.resolve("nested").resolve("tls");++ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);++ assertTrue(Files.exists(tlsDir.resolve("floci-root-ca.key")));+ assertTrue(ca.isIssuedByUs(parse(ca.issueClientCertificate("device").certificatePem())));+ }++ @Test+ void reloadsTheSameCaAcrossRestarts() throws Exception {+ FlociCertificateAuthority first = FlociCertificateAuthority.loadOrCreate(tempDir);+ Files.setPosixFilePermissions(tempDir.resolve("floci-root-ca.key"), PosixFilePermissions.fromString("rw-r--r--"));++ FlociCertificateAuthority second = FlociCertificateAuthority.loadOrCreate(tempDir);++ assertEquals(first.certificate(), second.certificate());+ assertEquals(first.key(), second.key());+ assertEquals(first.caPem(), second.caPem());+ assertEquals(PosixFilePermissions.fromString("rw-------"),+ Files.getPosixFilePermissions(tempDir.resolve("floci-root-ca.key")), "permissions are re-tightened on load");+ }++ @Test+ void corruptCaIsRegeneratedNotSilentlyKept() throws Exception {+ FlociCertificateAuthority first = FlociCertificateAuthority.loadOrCreate(tempDir);+ Files.writeString(tempDir.resolve("floci-root-ca.crt"), "-----BEGIN CERTIFICATE-----\nnope\n-----END CERTIFICATE-----\n");++ FlociCertificateAuthority second = FlociCertificateAuthority.loadOrCreate(tempDir);++ assertNotEquals(first.certificate(), second.certificate());+ assertTrue(second.certificate().getBasicConstraints() >= 0);+ assertEquals(second.caPem(), Files.readString(tempDir.resolve("floci-root-ca.crt")));+ }++ @Test+ void keyThatDoesNotMatchTheCertificateIsRegenerated() throws Exception {+ FlociCertificateAuthority first = FlociCertificateAuthority.loadOrCreate(tempDir);+ var stranger = new CertificateGenerator().generateCaCertificate("Other CA");+ Files.writeString(tempDir.resolve("floci-root-ca.key"), stranger.privateKeyPem());++ FlociCertificateAuthority second = FlociCertificateAuthority.loadOrCreate(tempDir);++ assertNotEquals(first.certificate(), second.certificate(), "a pair that cannot sign must not be kept");+ assertTrue(second.isIssuedByUs(parse(second.issueClientCertificate("device").certificatePem())));+ }++ @Test+ void expiredCaIsRegenerated() throws Exception {+ CertificateGenerator gen = new CertificateGenerator();+ java.security.KeyPair keyPair = java.security.KeyPairGenerator.getInstance("RSA").generateKeyPair();+ var dn = new org.bouncycastle.asn1.x500.X500Name("CN=" + FlociCertificateAuthority.COMMON_NAME);+ X509Certificate expired = gen.signCertificate(dn, keyPair.getPublic(), dn, keyPair.getPrivate(), List.of(),+ true, null, -1);+ Files.writeString(tempDir.resolve("floci-root-ca.crt"), gen.toPem(expired));+ Files.writeString(tempDir.resolve("floci-root-ca.key"), gen.toPem(keyPair.getPrivate()));++ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);++ assertNotEquals(expired, ca.certificate(), "an expired trust anchor is useless and must be replaced");+ ca.certificate().checkValidity();+ }++ @Test+ void missingKeyFileRegeneratesThePair() throws Exception {+ FlociCertificateAuthority first = FlociCertificateAuthority.loadOrCreate(tempDir);+ Files.delete(tempDir.resolve("floci-root-ca.key"));++ FlociCertificateAuthority second = FlociCertificateAuthority.loadOrCreate(tempDir);++ assertNotEquals(first.certificate(), second.certificate(), "a certificate without its key cannot sign");+ assertTrue(Files.exists(tempDir.resolve("floci-root-ca.key")));+ assertEquals(second.caPem(), Files.readString(tempDir.resolve("floci-root-ca.crt")));+ }++ @Test+ void aLeafInPlaceOfTheCaIsRegenerated() throws Exception {+ var leaf = new CertificateGenerator().generateCertificate("localhost", List.of(), KeyAlgorithm.RSA_2048);+ Files.writeString(tempDir.resolve("floci-root-ca.crt"), leaf.certificatePem());+ Files.writeString(tempDir.resolve("floci-root-ca.key"), leaf.privateKeyPem());++ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);++ assertTrue(ca.certificate().getBasicConstraints() >= 0, "must be a CA again");+ assertEquals(ca.certificate().getSubjectX500Principal(), ca.certificate().getIssuerX500Principal());+ }++ @Test+ void signsAServerLeafThatVerifiesAgainstTheCa() throws Exception {+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);++ CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate(+ "localhost", List.of("localhost", "*.localhost.floci.io"), KeyAlgorithm.RSA_2048, null);+ X509Certificate cert = parse(leaf.certificatePem());++ cert.verify(ca.certificate().getPublicKey());+ assertEquals(ca.certificate().getSubjectX500Principal(), cert.getIssuerX500Principal());+ assertEquals(-1, cert.getBasicConstraints());+ assertEquals(List.of("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.2"), cert.getExtendedKeyUsage());+ assertEquals(List.of("localhost", "*.localhost.floci.io"),+ cert.getSubjectAlternativeNames().stream().map(san -> san.get(1)).toList());+ assertTrue(ca.isIssuedByUs(cert));+ }++ @Test+ void signsAClientLeafWithClientAuthOnly() throws Exception {+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);++ X509Certificate cert = parse(ca.issueClientCertificate("AWS IoT Certificate").certificatePem());++ cert.verify(ca.certificate().getPublicKey());+ assertEquals("CN=AWS IoT Certificate", cert.getSubjectX500Principal().getName());+ assertEquals(List.of("1.3.6.1.5.5.7.3.2"), cert.getExtendedKeyUsage());+ assertTrue(ca.isIssuedByUs(cert));+ }++ @Test+ void aSelfSignedLeafIsNotOurs() {+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);+ var stranger = new CertificateGenerator().generateSelfSignedCertificate(+ "localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);++ assertFalse(ca.isIssuedByUs(parse(stranger.certificatePem())));+ }++ @Test+ void aLeafNamingOurCaButSignedByAnotherKeyIsNotOurs() {+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);+ var impostor = new CertificateGenerator().generateCaCertificate(FlociCertificateAuthority.COMMON_NAME);+ var generator = new CertificateGenerator();+ var forged = generator.generateIssuedCertificate("localhost", List.of(), KeyAlgorithm.RSA_2048, null,+ new CertificateGenerator.Issuer(parse(impostor.certificatePem()),+ generator.parsePrivateKey(impostor.privateKeyPem())),+ CertificateGenerator.LeafUsage.SERVER);++ assertFalse(ca.isIssuedByUs(parse(forged.certificatePem())), "same issuer name, wrong signature");+ }++ private static X509Certificate parse(String pem) {+ return new CertificateGenerator().parseCertificate(pem);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.javaindex 582992d0b0..f75ddba2ef 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java@@ -13,6 +13,7 @@ import org.junit.jupiter.params.provider.MethodSource;import java.nio.file.Files;import java.nio.file.Path;+import java.nio.file.attribute.PosixFilePermissions;import java.security.Security;import java.security.cert.X509Certificate;import java.util.*;@@ -67,7 +68,7 @@ class TlsCertificateHostnameTest {new TlsConfigSource();// Assert- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");assertTrue(Files.exists(certFile), "Certificate file should exist");X509Certificate cert = parseCertificate(certFile);@@ -91,7 +92,7 @@ class TlsCertificateHostnameTest {new TlsConfigSource();// Assert- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");X509Certificate cert = parseCertificate(certFile);List<String> sans = extractSansFromCertificate(cert);@@ -111,7 +112,7 @@ class TlsCertificateHostnameTest {new TlsConfigSource();// Assert- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");X509Certificate cert = parseCertificate(certFile);List<String> sans = extractSansFromCertificate(cert);@@ -132,7 +133,7 @@ class TlsCertificateHostnameTest {new TlsConfigSource();// Assert- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");X509Certificate cert = parseCertificate(certFile);List<String> sans = extractSansFromCertificate(cert);@@ -154,7 +155,7 @@ class TlsCertificateHostnameTest {new TlsConfigSource();- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");X509Certificate initialCert = parseCertificate(certFile);List<String> initialSans = extractSansFromCertificate(initialCert);assertTrue(initialSans.contains("host1"), "Initial certificate should contain 'host1'");@@ -183,9 +184,9 @@ class TlsCertificateHostnameTest {Path tlsDir = tempDir.resolve("tls");Files.createDirectories(tlsDir);- Path certFile = tlsDir.resolve("floci-selfsigned.crt");- Path keyFile = tlsDir.resolve("floci-selfsigned.key");- Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");+ Path certFile = tlsDir.resolve("floci-server.crt");+ Path keyFile = tlsDir.resolve("floci-server.key");+ Path metadataFile = tlsDir.resolve("floci-server.metadata.json");// Generate certificate without metadataCertificateGenerator gen = new CertificateGenerator();@@ -224,7 +225,7 @@ class TlsCertificateHostnameTest {new TlsConfigSource();// Assert- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");X509Certificate cert = parseCertificate(certFile);List<String> sans = extractSansFromCertificate(cert);@@ -249,7 +250,7 @@ class TlsCertificateHostnameTest {new TlsConfigSource();// Assert- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");X509Certificate cert = parseCertificate(certFile);List<String> sans = extractSansFromCertificate(cert);@@ -291,7 +292,7 @@ class TlsCertificateHostnameTest {new TlsConfigSource();// Assert: No self-signed certificate generated- Path selfSignedCert = tempDir.resolve("tls/floci-selfsigned.crt");+ Path selfSignedCert = tempDir.resolve("tls/floci-server.crt");assertFalse(Files.exists(selfSignedCert),"Self-signed certificate should not be generated when user provides certificates");}@@ -310,7 +311,7 @@ class TlsCertificateHostnameTest {// AssertPath tlsDir = tempDir.resolve("tls");if (Files.exists(tlsDir)) {- assertFalse(Files.exists(tlsDir.resolve("floci-selfsigned.crt")),+ assertFalse(Files.exists(tlsDir.resolve("floci-server.crt")),"No certificate should be created when TLS is disabled");}}@@ -327,9 +328,9 @@ class TlsCertificateHostnameTest {new TlsConfigSource();- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();- String initialMetadata = Files.readString(tempDir.resolve("tls/floci-selfsigned.metadata.json"));+ String initialMetadata = Files.readString(tempDir.resolve("tls/floci-server.metadata.json"));Thread.sleep(100);@@ -338,7 +339,7 @@ class TlsCertificateHostnameTest {// Assert: Certificate reused (not regenerated)long newModifiedTime = Files.getLastModifiedTime(certFile).toMillis();- String newMetadata = Files.readString(tempDir.resolve("tls/floci-selfsigned.metadata.json"));+ String newMetadata = Files.readString(tempDir.resolve("tls/floci-server.metadata.json"));assertEquals(initialModifiedTime, newModifiedTime,"Certificate should be reused when configuration unchanged");@@ -346,6 +347,135 @@ class TlsCertificateHostnameTest {"Metadata should be unchanged");}+ // ==================== Local CA Tests ====================++ @Test+ void serverCertificateIsIssuedByTheLocalCa() throws Exception {+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());++ TlsConfigSource source = new TlsConfigSource();++ Path tlsDir = tempDir.resolve("tls");+ X509Certificate ca = parseCertificate(tlsDir.resolve("floci-root-ca.crt"));+ X509Certificate leaf = parseCertificate(tlsDir.resolve("floci-server.crt"));+ leaf.verify(ca.getPublicKey());+ assertEquals(ca.getSubjectX500Principal(), leaf.getIssuerX500Principal());+ assertEquals(-1, leaf.getBasicConstraints(), "server leaf must not be a CA");+ assertEquals(List.of("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.2"), leaf.getExtendedKeyUsage());++ assertEquals(tlsDir.resolve("floci-server.crt").toAbsolutePath().toString(),+ source.getValue("quarkus.tls.key-store.pem.0.cert"));+ assertEquals(tlsDir.resolve("floci-server.key").toAbsolutePath().toString(),+ source.getValue("quarkus.tls.key-store.pem.0.key"));+ assertNull(source.getValue("quarkus.http.ssl.certificate.files"), "legacy key no longer published");+ assertNull(source.getValue("quarkus.http.ssl.certificate.key-files"), "legacy key no longer published");+ assertEquals(PosixFilePermissions.fromString("rw-------"),+ Files.getPosixFilePermissions(tlsDir.resolve("floci-server.key")));+ assertEquals(tlsDir, TlsConfigSource.resolvedTlsDir());+ }++ @Test+ void resolvedTlsDirIsClearedByABootThatDoesNotIssueALeaf() throws Exception {+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());+ new TlsConfigSource();+ assertEquals(tempDir.resolve("tls"), TlsConfigSource.resolvedTlsDir());++ System.setProperty("floci.tls.enabled", "false");+ new TlsConfigSource();+ assertNull(TlsConfigSource.resolvedTlsDir(), "TLS off: nothing was laid down");++ Path userCert = tempDir.resolve("user.crt");+ Path userKey = tempDir.resolve("user.key");+ var user = new CertificateGenerator().generateCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);+ Files.writeString(userCert, user.certificatePem());+ Files.writeString(userKey, user.privateKeyPem());+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.cert-path", userCert.toString());+ System.setProperty("floci.tls.key-path", userKey.toString());+ new TlsConfigSource();+ assertNull(TlsConfigSource.resolvedTlsDir(), "user certificate: nothing was laid down");+ }++ @Test+ void legacySelfSignedLeafIsReplacedByCaIssuedOne() throws Exception {+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());+ Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));+ CertificateGenerator gen = new CertificateGenerator();+ // The exact SAN list TlsConfigSource would compute for this configuration, so only the+ // issuer check can trigger regeneration here.+ List<String> sans = List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",+ "localhost.floci.io", "*.localhost.floci.io", "*.execute-api.localhost.floci.io",+ "*.execute-api.localhost.localstack.cloud", "host.docker.internal");+ var legacy = gen.generateSelfSignedCertificate("localhost", sans, KeyAlgorithm.RSA_2048);+ Files.writeString(tlsDir.resolve("floci-server.crt"), legacy.certificatePem());+ Files.writeString(tlsDir.resolve("floci-server.key"), legacy.privateKeyPem());+ Files.writeString(tlsDir.resolve("floci-server.metadata.json"),+ new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(+ CertificateMetadata.create(sans, "dev")));++ new TlsConfigSource();++ X509Certificate ca = parseCertificate(tlsDir.resolve("floci-root-ca.crt"));+ X509Certificate leaf = parseCertificate(tlsDir.resolve("floci-server.crt"));+ assertEquals(ca.getSubjectX500Principal(), leaf.getIssuerX500Principal());+ assertNotEquals(legacy.certificatePem(), Files.readString(tlsDir.resolve("floci-server.crt")));+ }++ @Test+ void expiredServerLeafIsReissued() throws Exception {+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());+ Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);+ CertificateGenerator gen = new CertificateGenerator();+ List<String> sans = List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",+ "localhost.floci.io", "*.localhost.floci.io", "*.execute-api.localhost.floci.io",+ "*.execute-api.localhost.localstack.cloud", "host.docker.internal");+ java.security.KeyPair keyPair = java.security.KeyPairGenerator.getInstance("RSA").generateKeyPair();+ // Issued by the current CA with a validity that ended a day ago: only the expiry check can trigger.+ X509Certificate expired = gen.signCertificate(new org.bouncycastle.asn1.x500.X500Name("CN=localhost"),+ keyPair.getPublic(), org.bouncycastle.asn1.x500.X500Name.getInstance(+ ca.certificate().getSubjectX500Principal().getEncoded()), ca.key(), sans, false,+ CertificateGenerator.LeafUsage.SERVER, -1);+ Files.writeString(tlsDir.resolve("floci-server.crt"), gen.toPem(expired));+ Files.writeString(tlsDir.resolve("floci-server.key"), gen.toPem(keyPair.getPrivate()));+ Files.writeString(tlsDir.resolve("floci-server.metadata.json"),+ new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(CertificateMetadata.create(sans, "dev")));+ assertTrue(ca.isIssuedByUs(expired), "the expired leaf is ours, so only validity can reject it");++ new TlsConfigSource();++ X509Certificate leaf = parseCertificate(tlsDir.resolve("floci-server.crt"));+ leaf.checkValidity();+ assertNotEquals(expired.getSerialNumber(), leaf.getSerialNumber());+ assertTrue(ca.isIssuedByUs(leaf));+ }++ @Test+ void leafSignedByAPreviousCaIsReplacedWhenTheCaChanges() throws Exception {+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());+ new TlsConfigSource();+ Path tlsDir = tempDir.resolve("tls");+ String firstLeaf = Files.readString(tlsDir.resolve("floci-server.crt"));+ Files.delete(tlsDir.resolve("floci-root-ca.key"));++ new TlsConfigSource();++ X509Certificate ca = parseCertificate(tlsDir.resolve("floci-root-ca.crt"));+ X509Certificate leaf = parseCertificate(tlsDir.resolve("floci-server.crt"));+ assertNotEquals(firstLeaf, Files.readString(tlsDir.resolve("floci-server.crt")));+ leaf.verify(ca.getPublicKey());+ }+// ==================== Helper Methods ====================private X509Certificate parseCertificate(Path certFile) throws Exception {diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.javaindex 2be14011fa..a8f90998d5 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.java@@ -59,7 +59,7 @@ class TlsConfigSourceCertificateGenerationTest {new TlsConfigSource();// Assert- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");assertTrue(Files.exists(certFile), "Certificate file should exist");List<String> sans = extractSansFromCertificate(certFile);@@ -81,7 +81,7 @@ class TlsConfigSourceCertificateGenerationTest {new TlsConfigSource();// Assert- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");assertTrue(Files.exists(certFile), "Certificate file should exist");List<String> sans = extractSansFromCertificate(certFile);@@ -103,7 +103,7 @@ class TlsConfigSourceCertificateGenerationTest {new TlsConfigSource();// Assert- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");assertTrue(Files.exists(certFile), "Certificate file should exist");List<String> sans = extractSansFromCertificate(certFile);@@ -124,7 +124,7 @@ class TlsConfigSourceCertificateGenerationTest {new TlsConfigSource();// Assert- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");assertTrue(Files.exists(certFile), "Certificate file should exist");List<String> sans = extractSansFromCertificate(certFile);@@ -147,7 +147,7 @@ class TlsConfigSourceCertificateGenerationTest {new TlsConfigSource();// Assert- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");assertTrue(Files.exists(certFile), "Certificate file should exist");List<String> sans = extractSansFromCertificate(certFile);@@ -183,7 +183,7 @@ class TlsConfigSourceCertificateGenerationTest {new TlsConfigSource();// Assert- Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls/floci-server.crt");assertTrue(Files.exists(certFile), "Certificate file should exist");List<String> sans = extractSansFromCertificate(certFile);@@ -205,7 +205,7 @@ class TlsConfigSourceCertificateGenerationTest {new TlsConfigSource();// Assert- Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");assertTrue(Files.exists(metadataFile), "Metadata file should exist");String json = Files.readString(metadataFile);diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateReuseTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateReuseTest.javaindex 5db4c3f619..a0a8ba459f 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateReuseTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateReuseTest.java@@ -57,8 +57,8 @@ class TlsConfigSourceCertificateReuseTest {new TlsConfigSource();Path tlsDir = tempDir.resolve("tls");- Path certFile = tlsDir.resolve("floci-selfsigned.crt");- Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");+ Path certFile = tlsDir.resolve("floci-server.crt");+ Path metadataFile = tlsDir.resolve("floci-server.metadata.json");// Verify initial certificate and metadata existassertTrue(Files.exists(certFile), "Initial certificate should be generated");@@ -107,8 +107,8 @@ class TlsConfigSourceCertificateReuseTest {new TlsConfigSource();Path tlsDir = tempDir.resolve("tls");- Path certFile = tlsDir.resolve("floci-selfsigned.crt");- Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");+ Path certFile = tlsDir.resolve("floci-server.crt");+ Path metadataFile = tlsDir.resolve("floci-server.metadata.json");// Verify initial certificate and metadata existassertTrue(Files.exists(certFile), "Initial certificate should be generated");@@ -150,8 +150,8 @@ class TlsConfigSourceCertificateReuseTest {new TlsConfigSource();Path tlsDir = tempDir.resolve("tls");- Path certFile = tlsDir.resolve("floci-selfsigned.crt");- Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");+ Path certFile = tlsDir.resolve("floci-server.crt");+ Path metadataFile = tlsDir.resolve("floci-server.metadata.json");// Verify initial certificate and metadata existassertTrue(Files.exists(certFile), "Initial certificate should be generated");@@ -195,7 +195,7 @@ class TlsConfigSourceCertificateReuseTest {// First boot: generate the certificate.new TlsConfigSource();- Path certFile = tempDir.resolve("tls").resolve("floci-selfsigned.crt");+ Path certFile = tempDir.resolve("tls").resolve("floci-server.crt");assertTrue(Files.exists(certFile), "Initial certificate should be generated");long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();String initialCert = Files.readString(certFile);@@ -236,8 +236,8 @@ class TlsConfigSourceCertificateReuseTest {new TlsConfigSource();Path tlsDir = tempDir.resolve("tls");- Path certFile = tlsDir.resolve("floci-selfsigned.crt");- Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");+ Path certFile = tlsDir.resolve("floci-server.crt");+ Path metadataFile = tlsDir.resolve("floci-server.metadata.json");// Verify initial certificate and metadata existassertTrue(Files.exists(certFile), "Initial certificate should be generated");diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataComparisonTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataComparisonTest.javaindex 0ae7008f40..ddd545efad 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataComparisonTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataComparisonTest.java@@ -167,7 +167,7 @@ class TlsConfigSourceMetadataComparisonTest {Files.createDirectories(tlsDir);// Create malformed metadata file- Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");+ Path metadataFile = tlsDir.resolve("floci-server.metadata.json");Files.writeString(metadataFile, "{ invalid json }");List<String> currentHostnames = List.of("localhost", "127.0.0.1");@@ -186,7 +186,7 @@ class TlsConfigSourceMetadataComparisonTest {Files.createDirectories(tlsDir);// Create metadata with null hostnames field- Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");+ Path metadataFile = tlsDir.resolve("floci-server.metadata.json");String json = "{\"generatedAt\":\"" + Instant.now().toString() + "\",\"flociVersion\":\"dev\"}";Files.writeString(metadataFile, json);@@ -223,7 +223,7 @@ class TlsConfigSourceMetadataComparisonTest {* Helper method to create a metadata file with specified hostnames.*/private void createMetadataFile(Path tlsDir, List<String> hostnames) throws IOException {- Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");+ Path metadataFile = tlsDir.resolve("floci-server.metadata.json");CertificateMetadata metadata = CertificateMetadata.create(hostnames, "dev");ObjectMapper objectMapper = new ObjectMapper();diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataPersistenceTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataPersistenceTest.javaindex 1f51b561b7..39ffe437f6 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataPersistenceTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceMetadataPersistenceTest.java@@ -53,7 +53,7 @@ class TlsConfigSourceMetadataPersistenceTest {new TlsConfigSource();// Assert- Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");assertTrue(Files.exists(metadataFile),"Metadata file should be created after certificate generation");}@@ -67,7 +67,7 @@ class TlsConfigSourceMetadataPersistenceTest {new TlsConfigSource();// Assert- Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");CertificateMetadata metadata = readMetadata(metadataFile);assertNotNull(metadata.getHostnames(), "Hostnames should not be null");@@ -99,7 +99,7 @@ class TlsConfigSourceMetadataPersistenceTest {new TlsConfigSource();// Assert- Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");CertificateMetadata metadata = readMetadata(metadataFile);assertTrue(metadata.getHostnames().contains("floci"),@@ -118,7 +118,7 @@ class TlsConfigSourceMetadataPersistenceTest {new TlsConfigSource();// Assert- Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");CertificateMetadata metadata = readMetadata(metadataFile);assertTrue(metadata.getHostnames().contains("myhost"),@@ -138,7 +138,7 @@ class TlsConfigSourceMetadataPersistenceTest {new TlsConfigSource();// Assert- Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");CertificateMetadata metadata = readMetadata(metadataFile);assertTrue(metadata.getHostnames().contains("newhost"),@@ -156,7 +156,7 @@ class TlsConfigSourceMetadataPersistenceTest {new TlsConfigSource();// Assert- Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");CertificateMetadata metadata = readMetadata(metadataFile);assertNotNull(metadata.getGeneratedAt(),@@ -174,7 +174,7 @@ class TlsConfigSourceMetadataPersistenceTest {new TlsConfigSource();// Assert- Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");CertificateMetadata metadata = readMetadata(metadataFile);assertNotNull(metadata.getFlociVersion(),@@ -196,7 +196,7 @@ class TlsConfigSourceMetadataPersistenceTest {new TlsConfigSource();// Assert- Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");CertificateMetadata metadata = readMetadata(metadataFile);assertNotNull(metadata.getFlociVersion(),@@ -212,7 +212,7 @@ class TlsConfigSourceMetadataPersistenceTest {new TlsConfigSource();// Assert- Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");+ Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");String json = Files.readString(metadataFile);assertFalse(json.isBlank(), "Metadata file should not be empty");diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsLocalCaIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsLocalCaIntegrationTest.javanew file mode 100644index 0000000000..8e388328cc--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/TlsLocalCaIntegrationTest.java@@ -0,0 +1,125 @@+package io.github.hectorvent.floci.config;++import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import org.eclipse.microprofile.config.inject.ConfigProperty;+import org.junit.jupiter.api.Test;++import javax.net.ssl.HttpsURLConnection;+import javax.net.ssl.SSLContext;+import javax.net.ssl.SSLHandshakeException;+import javax.net.ssl.TrustManagerFactory;+import java.io.ByteArrayInputStream;+import java.io.IOException;+import java.net.URI;+import java.nio.charset.StandardCharsets;+import java.nio.file.Files;+import java.nio.file.Path;+import java.security.KeyStore;+import java.security.cert.Certificate;+import java.security.cert.CertificateFactory;+import java.security.cert.X509Certificate;+import java.util.List;+import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;++/**+ * Boots the HTTP server on the TLS registry keys {@code TlsConfigSource} publishes, with a leaf+ * issued by the local CA, and proves a client that trusts only {@code GET /_floci/ca.pem} completes+ * a handshake. A file assertion cannot show that Quarkus read the registry entry or that the served+ * chain is the CA's; only a handshake can.+ */+@QuarkusTest+@TestProfile(TlsLocalCaIntegrationTest.LocalCaProfile.class)+class TlsLocalCaIntegrationTest {++ @ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")+ int testSslPort;++ @Test+ void handshakeSucceedsTrustingOnlyTheServedCa() throws Exception {+ String caPem = given().when().get("/_floci/ca.pem").then().statusCode(200).extract().asString();+ X509Certificate ca = parse(caPem);++ HttpsURLConnection connection = open(trustOnly(ca));+ assertEquals(200, connection.getResponseCode());+ Certificate[] served = connection.getServerCertificates();+ X509Certificate leaf = (X509Certificate) served[0];+ assertEquals(ca.getSubjectX500Principal(), leaf.getIssuerX500Principal());+ assertEquals(-1, leaf.getBasicConstraints());+ leaf.verify(ca.getPublicKey());+ connection.disconnect();+ }++ @Test+ void handshakeFailsTrustingAnotherCa() throws Exception {+ X509Certificate stranger = FlociCertificateAuthority.loadOrCreate(+ Files.createTempDirectory("floci-stranger-ca")).certificate();++ HttpsURLConnection connection = open(trustOnly(stranger));+ assertThrows(SSLHandshakeException.class, connection::getResponseCode);+ }++ private HttpsURLConnection open(SSLContext sslContext) throws IOException {+ HttpsURLConnection connection = (HttpsURLConnection) URI.create(+ "https://localhost:" + testSslPort + "/_floci/health").toURL().openConnection();+ connection.setSSLSocketFactory(sslContext.getSocketFactory());+ return connection;+ }++ private static SSLContext trustOnly(X509Certificate ca) throws Exception {+ KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());+ trust.load(null, null);+ trust.setCertificateEntry("floci-ca", ca);+ TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());+ factory.init(trust);+ SSLContext context = SSLContext.getInstance("TLS");+ context.init(null, factory.getTrustManagers(), null);+ return context;+ }++ private static X509Certificate parse(String pem) throws Exception {+ return (X509Certificate) CertificateFactory.getInstance("X.509")+ .generateCertificate(new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII)));+ }++ /**+ * Lays down what {@code TlsConfigSource} would: a CA under {persistent-path}/tls and a leaf+ * issued by it, published as the registry's default key store. The persistent path is the+ * same directory, so the CDI producer behind {@code /_floci/ca.pem} loads the same CA.+ */+ public static final class LocalCaProfile implements QuarkusTestProfile {++ private static final Path DATA_DIR = Path.of("target", "floci-tls-local-ca-test").toAbsolutePath();+ private static final Path TLS_DIR = DATA_DIR.resolve("tls");+ private static final Path CERT_FILE = TLS_DIR.resolve("floci-server.crt");+ private static final Path KEY_FILE = TLS_DIR.resolve("floci-server.key");++ static {+ try {+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);+ var leaf = ca.issueServerCertificate("localhost", List.of("localhost", "127.0.0.1"),+ KeyAlgorithm.RSA_2048, null);+ Files.writeString(CERT_FILE, leaf.certificatePem());+ Files.writeString(KEY_FILE, leaf.privateKeyPem());+ } catch (IOException e) {+ throw new IllegalStateException("Failed to prepare the local CA test files", e);+ }+ }++ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of(+ "floci.storage.persistent-path", DATA_DIR.toString(),+ "quarkus.tls.key-store.pem.0.cert", CERT_FILE.toString(),+ "quarkus.tls.key-store.pem.0.key", KEY_FILE.toString(),+ "quarkus.http.insecure-requests", "enabled"+ );+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.javaindex 288f5826da..e47374850a 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsUserCertIntegrationTest.java@@ -58,6 +58,31 @@ class TlsUserCertIntegrationTest {.body("edition", is("community"));}+ @Test+ void caPemReturnsTheUserCertificateFollowedByTheLocalCa() throws Exception {+ String pem = given()+ .when()+ .get("/_floci/ca.pem")+ .then()+ .statusCode(200)+ .contentType(org.hamcrest.Matchers.startsWith("text/plain"))+ .extract().asString();++ String userPem = Files.readString(UserCertProfile.CERT_FILE);+ org.junit.jupiter.api.Assertions.assertTrue(pem.startsWith(userPem),+ "the user certificate, which signs the HTTPS endpoint, comes first");+ var bundle = java.security.cert.CertificateFactory.getInstance("X.509")+ .generateCertificates(new java.io.ByteArrayInputStream(pem.getBytes(java.nio.charset.StandardCharsets.US_ASCII)))+ .stream().map(java.security.cert.X509Certificate.class::cast).toList();+ org.junit.jupiter.api.Assertions.assertEquals(2, bundle.size(), "user certificate plus the local CA");+ java.security.cert.X509Certificate localCa = bundle.get(1);+ org.junit.jupiter.api.Assertions.assertTrue(localCa.getBasicConstraints() >= 0, "the local CA is a CA");+ org.junit.jupiter.api.Assertions.assertEquals("CN=Floci Local CA", localCa.getSubjectX500Principal().getName());+ org.junit.jupiter.api.Assertions.assertEquals(Files.readString(+ Path.of("/tmp/floci-tls-usercert-test-data/tls/floci-root-ca.crt")), pem.substring(userPem.length()).stripLeading(),+ "the local CA served is the one on disk");+ }+@Testvoid ssmPutParameterOverHttps() {given()@@ -74,7 +99,7 @@ class TlsUserCertIntegrationTest {public static final class UserCertProfile implements QuarkusTestProfile {private static final Path CERT_DIR = Path.of("/tmp/floci-tls-usercert-test");- private static final Path CERT_FILE = CERT_DIR.resolve("user-test.crt");+ static final Path CERT_FILE = CERT_DIR.resolve("user-test.crt");private static final Path KEY_FILE = CERT_DIR.resolve("user-test.key");static {diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoControllerIntegrationTest.javaindex 367e7340f8..17ff460910 100644--- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoControllerIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorInfoControllerIntegrationTest.java@@ -105,6 +105,24 @@ class EmulatorInfoControllerIntegrationTest {given().when().get(path).then().statusCode(200).contentType("application/json");}+ @ParameterizedTest+ @ValueSource(strings = {"/_floci/ca.pem", "/_localstack/ca.pem"})+ void caPem_returnsTheLocalCaAsPlainText(String path) throws Exception {+ String pem = given()+ .when().get(path)+ .then()+ .statusCode(200)+ .contentType(startsWith("text/plain"))+ .extract().body().asString();++ var cert = (java.security.cert.X509Certificate) java.security.cert.CertificateFactory.getInstance("X.509")+ .generateCertificate(new java.io.ByteArrayInputStream(pem.getBytes(java.nio.charset.StandardCharsets.US_ASCII)));+ assertTrue(cert.getBasicConstraints() >= 0, "must be a CA certificate");+ assertEquals(cert.getSubjectX500Principal(), cert.getIssuerX500Principal());+ assertEquals(pem, given().when().get("/_floci/ca.pem").then().extract().body().asString(),+ "the same CA on every call");+ }+@ParameterizedTest@ValueSource(strings = {"/_floci/state/reset", "/_localstack/state/reset", "/_floci/state/nuke", "/_localstack/state/nuke"})void stateReset_returnsOkOnAllPaths(String path) {diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCaTrustTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCaTrustTest.javaindex 40b57bbb11..86e896420a 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCaTrustTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherCaTrustTest.java@@ -20,7 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;/*** Unit tests for {@link ContainerLauncher}'s Floci CA-trust injection helpers. These are pure* (no Docker / Quarkus): they cover where the CA cert is resolved from and which environment- * variables get injected so a Lambda container trusts Floci's self-signed HTTPS endpoint.+ * variables get injected so a Lambda container trusts Floci's HTTPS endpoint through the local CA.*/class ContainerLauncherCaTrustTest {@@ -41,9 +41,9 @@ class ContainerLauncherCaTrustTest {}@Test- void resolveCaCertPath_selfSignedUnderPersistentPath() throws Exception {+ void resolveCaCertPath_localCaUnderPersistentPath() throws Exception {Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));- Path cert = Files.writeString(tlsDir.resolve("floci-selfsigned.crt"), "PEM");+ Path cert = Files.writeString(tlsDir.resolve("floci-root-ca.crt"), "PEM");Optional<Path> resolved =ContainerLauncher.resolveFlociCaCertPath(true, Optional.empty(), tempDir.toString());@@ -64,9 +64,9 @@ class ContainerLauncherCaTrustTest {}@Test- void resolveCaCertPath_blankUserCertFallsBackToSelfSigned() throws Exception {+ void resolveCaCertPath_blankUserCertFallsBackToLocalCa() throws Exception {Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));- Path cert = Files.writeString(tlsDir.resolve("floci-selfsigned.crt"), "PEM");+ Path cert = Files.writeString(tlsDir.resolve("floci-root-ca.crt"), "PEM");Optional<Path> resolved =ContainerLauncher.resolveFlociCaCertPath(true, Optional.of(" "), tempDir.toString());