diff --git a/docs/services/rds.md b/docs/services/rds.md index 91bd66a613..40cbc361e1 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -845,31 +845,45 @@ password in cleartext, MySQL sends a scramble, so the proxy would have to drive ## TLS / SSL -The RDS auth proxy terminates TLS itself (the backend container stays plaintext) using a -self-signed CA whose Subject Alternative Names cover every advertised host Floci has handed -out for a DB instance, cluster, or RDS Proxy — the Docker bridge IP, `host.docker.internal`, -`localhost`, or whatever `rds.endpointHost` resolves to. The CA is persisted at -`{storage.persistent-path}/tls/rds-ca.crt` and grows its SAN list as new hosts appear, so the -same root survives restarts and works for every local database, not just the one that -generated it. +The RDS auth proxy terminates TLS itself (the backend container stays plaintext). It presents +a non-CA server certificate followed by Floci's shared root CA, so strict TLS +clients can validate an end-entity certificate rather than being asked to accept a CA as a server. +The server certificate's Subject Alternative Names cover every advertised DB instance, cluster, +or RDS Proxy host: the Docker bridge IP, `host.docker.internal`, `localhost`, or whatever +`rds.endpointHost` resolves to. -Floci logs the certificate path (and the `PGSSLROOTCERT` hint) the first time it generates or -loads it: +The shared CA is the same one used by ACM, IoT, and EKS. It is persisted at +`{storage.persistent-path}/tls/floci-root-ca.crt`, with its owner-only private key in +`floci-root-ca.key`. The server certificate is issued in memory on startup and when a new host +appears, and renewed before expiry during TLS use; its SAN list is recorded in `rds-ca.metadata.json`. +Renewal preserves the CA and SANs. If the CA itself expires, the proxy refuses new TLS use +rather than silently changing client trust; restart to regenerate the unusable CA and trust its replacement. +The shared CA certificate and key do not change during SAN growth or restarts. Missing or +corrupt SAN metadata is rebuilt without replacing a valid +CA. An invalid or unusable CA/key pair is replaced with a warning; only then must clients trust +the replacement CA again. + +The proxy also writes the shared root certificate to `tls/rds-ca.crt`, preserving existing +`PGSSLROOTCERT` and MySQL `--ssl-ca` paths. This compatibility copy is refreshed when the proxy +initializes, even if the old RDS certificate is expired or corrupt. The unused `rds-ca.key` +is removed; the shared CA key and existing `rds-ca.metadata.json` SAN list are retained. +The shared certificate is also available from `GET /_floci/ca.pem`. + +The proxy logs the shared certificate path when it first issues a server certificate: ``` -RDS proxy TLS: CA cert at ./data/tls/rds-ca.crt -RDS proxy TLS: for sslmode=verify-full set PGSSLROOTCERT=./data/tls/rds-ca.crt +RDS proxy TLS: for sslmode=verify-full set PGSSLROOTCERT=./data/tls/floci-root-ca.crt ``` Because the SAN matches the address you actually connect to, `verify-full` (the same level -Aurora enforces in AWS) works locally too — no need to fall back to `sslmode=disable` just to +Aurora enforces in AWS) works locally too, without falling back to `sslmode=disable` just to exercise the same connection-string settings you use in production: ```bash # PostgreSQL -PGSSLROOTCERT=./data/tls/rds-ca.crt psql "host=localhost port=7001 user=admin sslmode=verify-full" +PGSSLROOTCERT=./data/tls/floci-root-ca.crt psql "host=localhost port=7001 user=admin sslmode=verify-full" # MySQL / MariaDB mysql -h 127.0.0.1 -P 7002 -u root -psecret123 \ - --ssl-mode=VERIFY_IDENTITY --ssl-ca=./data/tls/rds-ca.crt + --ssl-mode=VERIFY_IDENTITY --ssl-ca=./data/tls/floci-root-ca.crt ``` diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java index 4131ac9fda..4a34f2e1e9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java @@ -2,7 +2,7 @@ package io.github.hectorvent.floci.services.rds.proxy; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.CertificateMetadata; -import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.config.FlociCertificateAuthority; import io.github.hectorvent.floci.config.FlociVersion; import io.github.hectorvent.floci.core.common.Pem; import io.github.hectorvent.floci.services.acm.CertificateGenerator; @@ -16,28 +16,30 @@ import javax.net.ssl.SSLContext; 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.nio.file.StandardCopyOption; import java.security.KeyStore; import java.security.PrivateKey; import java.security.SecureRandom; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; +import java.util.Date; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** - * Owns the RDS auth proxy's self-signed CA certificate: a single trust anchor shared by every - * proxied Postgres/MySQL instance, cluster, and RDS Proxy target, whose Subject Alternative Names - * grow to cover every advertised host Floci has handed out (Docker bridge IP, {@code - * host.docker.internal}, a configured {@code rds.endpointHost}, etc.). + * Owns the RDS auth proxy's in-memory server certificate signed by Floci's shared root CA. + * The server certificate's SANs cover every advertised Postgres/MySQL host. * - *

Persisted at {@code {persistent-path}/tls/rds-ca.{crt,key}} (plus a metadata file recording - * the current SAN list) so the same root survives restarts — a client only has to trust it once + *

The shared CA persists at {@code {persistent-path}/tls/floci-root-ca.{crt,key}}. The + * {@code rds-ca.crt} compatibility copy preserves existing client paths, and + * {@code rds-ca.metadata.json} records the current SAN list. A client trusts the shared CA once * (e.g. {@code sslmode=verify-full sslrootcert=}) to keep working across every local - * database and every restart, as long as the advertised host doesn't change. + * database and every restart, including when advertised hosts change. */ @ApplicationScoped public class RdsProxyTlsCertificates { @@ -45,47 +47,48 @@ public class RdsProxyTlsCertificates { private static final Logger LOG = Logger.getLogger(RdsProxyTlsCertificates.class); private static final List DEFAULT_SANS = List.of("localhost", "127.0.0.1"); - private static final String CERT_NAME = "rds-ca.crt"; - private static final String KEY_NAME = "rds-ca.key"; private static final String METADATA_NAME = "rds-ca.metadata.json"; - private static final String TLS_DIR = "tls"; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - private final EmulatorConfig config; + private final FlociCertificateAuthority certificateAuthority; private final CertificateGenerator certificateGenerator; + private final Clock clock; private final Object lock = new Object(); - private volatile SSLContext sslContext; - private volatile Set currentSans = Set.of(); - private volatile KeyPair currentKeyPair; + private volatile ServerCertificate current; + + private record ServerCertificate(SSLContext context, Set sans, Instant notAfter) { + } @Inject - public RdsProxyTlsCertificates(EmulatorConfig config, CertificateGenerator certificateGenerator) { - this.config = config; + public RdsProxyTlsCertificates(FlociCertificateAuthority certificateAuthority, CertificateGenerator certificateGenerator) { + this(certificateAuthority, certificateGenerator, Clock.systemUTC()); + } + + RdsProxyTlsCertificates(FlociCertificateAuthority certificateAuthority, CertificateGenerator certificateGenerator, + Clock clock) { + this.certificateAuthority = certificateAuthority; this.certificateGenerator = certificateGenerator; + this.clock = clock; } /** - * Ensures {@code host} is covered by the current CA's SAN list, reissuing the certificate - * (and re-persisting it) if it is a genuinely new host. Reissuing reuses the existing key pair - * rather than minting a new one, so a client that already trusts a prior copy of this CA (e.g. - * one it copied into its own trust store) keeps validating connections after the SAN list - * grows — only the SAN extension and serial change, not the signing key. Cheap no-op once a - * host is known. + * Ensures {@code host} is covered by the server certificate, issuing a new leaf when needed. + * The persisted CA is unchanged, so existing client trust stores continue to work. */ public void ensureHost(String host) { if (host == null || host.isBlank()) { return; } ensureInitialized(); - if (currentSans.contains(host)) { + if (current.sans().contains(host)) { return; } synchronized (lock) { - if (currentSans.contains(host)) { + if (current.sans().contains(host)) { return; } - Set updated = new LinkedHashSet<>(currentSans); + Set updated = new LinkedHashSet<>(current.sans()); updated.add(host); regenerate(updated); } @@ -93,86 +96,99 @@ public class RdsProxyTlsCertificates { /** * Returns the current TLS server context. Handlers should call this per-handshake rather than - * caching it themselves — {@link #ensureHost(String)} can swap it out at any time. + * caching it themselves; {@link #ensureHost(String)} can swap it out at any time. */ public SSLContext sslContext() { ensureInitialized(); - return sslContext; + return current.context(); } private void ensureInitialized() { - if (sslContext != null) { + if (!needsRenewal()) { return; } synchronized (lock) { - if (sslContext != null) { + if (!needsRenewal()) { + return; + } + if (current != null) { + regenerate(current.sans()); return; } Path tlsDir = tlsDir(); - Path certFile = tlsDir.resolve(CERT_NAME); - Path keyFile = tlsDir.resolve(KEY_NAME); + Set sans = new LinkedHashSet<>(DEFAULT_SANS); Path metadataFile = tlsDir.resolve(METADATA_NAME); - if (Files.exists(certFile) && Files.exists(keyFile) && Files.exists(metadataFile)) { + if (Files.exists(metadataFile)) { try { - List persistedSans = readMetadata(metadataFile); - loadExisting(certFile, keyFile, persistedSans); - // Re-harden on every load: earlier Floci versions wrote this key world-readable, - // so an existing install must be tightened too, not just newly generated ones. - restrictToOwnerOnly(tlsDir, "rwx------"); - restrictToOwnerOnly(keyFile, "rw-------"); - LOG.infov("RDS proxy TLS: reusing existing CA cert: {0} (SANs: {1})", - certFile, persistedSans); - logTrustHint(certFile); - return; - } catch (Exception e) { - LOG.warnv(e, "RDS proxy TLS: failed to load existing CA cert ({0}); regenerating", - e.getMessage()); + sans.addAll(readMetadata(metadataFile)); + } catch (IOException e) { + LOG.warnv(e, "RDS proxy TLS: invalid SAN metadata at {0}; keeping the CA and using default hosts", + metadataFile); + } + } + refreshLegacyCaFiles(); + regenerate(sans); + logTrustHint(certificateAuthority.certificatePath()); + } + } + + private void refreshLegacyCaFiles() { + Path temporary = null; + try { + Path tlsDir = tlsDir(); + temporary = Files.createTempFile(tlsDir, "rds-ca-", ".tmp"); + Files.writeString(temporary, certificateAuthority.caPem()); + // Replace the path itself, never a legacy symlink's target or a shared inode. + Files.move(temporary, tlsDir.resolve("rds-ca.crt"), + StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + Files.deleteIfExists(tlsDir.resolve("rds-ca.key")); + } catch (IOException e) { + throw new IllegalStateException("Failed to refresh RDS proxy TLS CA compatibility files", e); + } finally { + if (temporary != null) { + try { + Files.deleteIfExists(temporary); + } catch (IOException e) { + LOG.warnv(e, "RDS proxy TLS: could not remove temporary CA file {0}", temporary); } } - regenerate(new LinkedHashSet<>(DEFAULT_SANS)); } } private void regenerate(Set sans) { try { Path tlsDir = tlsDir(); - Files.createDirectories(tlsDir); - restrictToOwnerOnly(tlsDir, "rwx------"); List sanList = new ArrayList<>(sans); - - KeyPair keyPair = this.currentKeyPair; - CertificateGenerator.GeneratedCertificate generated = keyPair != null - ? certificateGenerator.generateSelfSignedCertificate( - "localhost", sanList, KeyAlgorithm.RSA_2048, keyPair) - : certificateGenerator.generateSelfSignedCertificate( - "localhost", sanList, KeyAlgorithm.RSA_2048); - - Path certFile = tlsDir.resolve(CERT_NAME); - Path keyFile = tlsDir.resolve(KEY_NAME); - Files.writeString(certFile, generated.certificatePem()); - Files.writeString(keyFile, generated.privateKeyPem()); - restrictToOwnerOnly(keyFile, "rw-------"); - writeMetadata(tlsDir.resolve(METADATA_NAME), sanList); - + Instant now = clock.instant(); + certificateAuthority.certificate().checkValidity(Date.from(now)); + Instant notAfter = now.plus(365, ChronoUnit.DAYS); + if (certificateAuthority.certificate().getNotAfter().toInstant().isBefore(notAfter)) { + notAfter = certificateAuthority.certificate().getNotAfter().toInstant(); + } + CertificateGenerator.GeneratedCertificate generated = certificateGenerator.generateIssuedCertificate( + "localhost", sanList, KeyAlgorithm.RSA_2048, null, certificateAuthority.issuer(), + CertificateGenerator.LeafUsage.SERVER, notAfter); X509Certificate certificate = Pem.parseCertificate(generated.certificatePem()); PrivateKey privateKey = Pem.parsePrivateKey(generated.privateKeyPem()); - this.sslContext = buildSslContext(certificate, privateKey); - this.currentSans = Set.copyOf(sans); - this.currentKeyPair = new KeyPair(certificate.getPublicKey(), privateKey); - - LOG.infov("RDS proxy TLS: generated CA cert at {0}", certFile); - logTrustHint(certFile); + SSLContext context = buildSslContext(certificate, privateKey); + writeMetadata(tlsDir.resolve(METADATA_NAME), sanList); + current = new ServerCertificate(context, Set.copyOf(sans), generated.notAfter()); } catch (Exception e) { throw new IllegalStateException("Failed to generate RDS proxy TLS certificate", e); } } - private void loadExisting(Path certFile, Path keyFile, List sans) throws Exception { - X509Certificate certificate = Pem.parseCertificate(Files.readString(certFile)); - PrivateKey privateKey = Pem.parsePrivateKey(Files.readString(keyFile)); - this.sslContext = buildSslContext(certificate, privateKey); - this.currentSans = new LinkedHashSet<>(sans); - this.currentKeyPair = new KeyPair(certificate.getPublicKey(), privateKey); + private boolean needsRenewal() { + ServerCertificate certificate = current; + if (certificate == null) { + return true; + } + Instant renewAt = certificate.notAfter(); + // A leaf capped at CA expiry cannot be extended without replacing the trust anchor. + if (renewAt.isBefore(certificateAuthority.certificate().getNotAfter().toInstant())) { + renewAt = renewAt.minusSeconds(60); + } + return !renewAt.isAfter(clock.instant()); } private SSLContext buildSslContext(X509Certificate certificate, PrivateKey privateKey) throws Exception { @@ -180,7 +196,7 @@ public class RdsProxyTlsCertificates { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null, password); keyStore.setKeyEntry("floci-rds-proxy", privateKey, password, - new java.security.cert.Certificate[]{certificate}); + new Certificate[]{certificate, certificateAuthority.certificate()}); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, password); @@ -191,24 +207,7 @@ public class RdsProxyTlsCertificates { } private Path tlsDir() { - return Path.of(config.storage().persistentPath(), TLS_DIR); - } - - /** - * Restricts {@code path} to owner-only access. This CA's private key is meant to be trusted by - * a developer's client tooling (e.g. {@code sslmode=verify-full}), so unlike Floci's other - * generated keys — which only let you impersonate an emulated resource — anyone who can read - * this one can mint a certificate for any host the developer's trust store now accepts. - * No-ops on filesystems without POSIX permissions (e.g. Windows) rather than failing. - */ - private static void restrictToOwnerOnly(Path path, String posixPermissions) { - try { - if (Files.getFileStore(path).supportsFileAttributeView(PosixFileAttributeView.class)) { - Files.setPosixFilePermissions(path, PosixFilePermissions.fromString(posixPermissions)); - } - } catch (IOException e) { - LOG.warnv(e, "RDS proxy TLS: failed to restrict permissions on {0}", path); - } + return certificateAuthority.certificatePath().getParent(); } private void logTrustHint(Path certFile) { @@ -218,9 +217,10 @@ public class RdsProxyTlsCertificates { private List readMetadata(Path metadataFile) throws IOException { CertificateMetadata metadata = OBJECT_MAPPER.readValue(metadataFile.toFile(), CertificateMetadata.class); - List hostnames = metadata.getHostnames(); - if (hostnames == null || hostnames.isEmpty()) { - throw new IOException("RDS proxy TLS metadata file has no hostnames: " + metadataFile); + List hostnames = metadata != null ? metadata.getHostnames() : null; + if (hostnames == null || hostnames.isEmpty() + || hostnames.stream().anyMatch(host -> host == null || host.isBlank())) { + throw new IOException("RDS proxy TLS metadata file has invalid hostnames: " + metadataFile); } return hostnames; } diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java index 719fe3d61c..d87a906230 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java @@ -1,6 +1,6 @@ package io.github.hectorvent.floci.services.rds.proxy; -import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.config.FlociCertificateAuthority; import io.github.hectorvent.floci.services.acm.CertificateGenerator; import io.github.hectorvent.floci.testutil.IamServiceTestHelper; import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper; @@ -37,8 +37,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; class MySqlProtocolHandlerTest { @@ -696,11 +694,8 @@ class MySqlProtocolHandlerTest { } private RdsProxyTlsCertificates testTlsCertificates() { - EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class); - when(storage.persistentPath()).thenReturn(tempDir.toString()); - EmulatorConfig config = mock(EmulatorConfig.class); - when(config.storage()).thenReturn(storage); - return new RdsProxyTlsCertificates(config, new CertificateGenerator()); + return new RdsProxyTlsCertificates(FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")), + new CertificateGenerator()); } private static RdsSigV4Validator testSigV4Validator() { diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java index 7cd524c4dd..c605481465 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java @@ -1,7 +1,8 @@ package io.github.hectorvent.floci.services.rds.proxy; -import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.config.FlociCertificateAuthority; import io.github.hectorvent.floci.services.acm.CertificateGenerator; +import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; import io.github.hectorvent.floci.testutil.IamServiceTestHelper; import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper; import org.junit.jupiter.api.Test; @@ -45,8 +46,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.junit.jupiter.api.Assertions.assertTrue; class PostgresProtocolHandlerTest { @@ -447,14 +447,32 @@ class PostgresProtocolHandlerTest { } @ParameterizedTest - @CsvSource({"172.17.0.5, true", "never-registered.example.com, false"}) - void hostnameVerificationRequiresRegisteredAdvertisedHost(String advertisedHost, boolean registered) throws Exception { + @CsvSource({"172.17.0.5, true, false", "never-registered.example.com, false, false", + "host.docker.internal, true, true", "never-registered.example.com, false, true"}) + void hostnameVerificationRequiresRegisteredAdvertisedHost(String advertisedHost, boolean registered, + boolean legacyCa) throws Exception { try (ServerSocket clientServer = new ServerSocket(0); Socket ourClient = new Socket("localhost", clientServer.getLocalPort()); Socket proxyClient = clientServer.accept()) { RdsProxyTlsCertificates tlsCertificates = testTlsCertificates(); + Path caCertFile = tempDir.resolve("tls/rds-ca.crt"); + if (legacyCa) { + CertificateGenerator.GeneratedCertificate legacy = new CertificateGenerator() + .generateSelfSignedCertificate("localhost", List.of("localhost", "172.17.0.5"), + KeyAlgorithm.RSA_2048); + Files.writeString(caCertFile.resolveSibling("rds-ca.crt"), legacy.certificatePem()); + Files.writeString(caCertFile.resolveSibling("rds-ca.key"), legacy.privateKeyPem()); + Files.writeString(caCertFile.resolveSibling("rds-ca.metadata.json"), + "{\"hostnames\":[\"localhost\",\"172.17.0.5\"]}"); + } tlsCertificates.ensureHost("172.17.0.5"); + Path trustedCaFile = Files.copy(caCertFile, tempDir.resolve("trusted-ca.crt")); + if (legacyCa) { + tlsCertificates.ensureHost("host.docker.internal"); + tlsCertificates = testTlsCertificates(); + } + RdsProxyTlsCertificates serverCertificates = tlsCertificates; AtomicReference authFailure = new AtomicReference<>(); Thread authThread = Thread.ofVirtual() @@ -464,7 +482,7 @@ class PostgresProtocolHandlerTest { PostgresProtocolHandler.authenticate( proxyClient, NEVER_CONNECT, "dbadmin", "adminpass", "postgres", - false, testSigV4Validator(), testBinding(), tlsCertificates, + false, testSigV4Validator(), testBinding(), serverCertificates, (user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000); } catch (IOException expected) { // Closing or rejecting TLS ends authentication before PostgreSQL startup. @@ -478,10 +496,19 @@ class PostgresProtocolHandlerTest { writeSslRequest(clientOut); assertEquals('S', clientIn.readUnsignedByte()); - Path caCertFile = tempDir.resolve("tls").resolve("rds-ca.crt"); - try (SSLSocket sslClient = verifyingClientSocket(ourClient, caCertFile, advertisedHost)) { + try (SSLSocket sslClient = verifyingClientSocket(ourClient, trustedCaFile, advertisedHost)) { if (registered) { sslClient.startHandshake(); + X509Certificate serverCertificate = (X509Certificate) + sslClient.getSession().getPeerCertificates()[0]; + assertEquals(-1, serverCertificate.getBasicConstraints(), + "strict TLS clients require an end-entity server certificate, not the trusted CA"); + assertTrue(serverCertificate.getExtendedKeyUsage().contains("1.3.6.1.5.5.7.3.1")); + assertEquals(2, sslClient.getSession().getPeerCertificates().length); + try (InputStream trustedCa = Files.newInputStream(trustedCaFile)) { + assertEquals(CertificateFactory.getInstance("X.509").generateCertificate(trustedCa), + sslClient.getSession().getPeerCertificates()[1]); + } } else { assertThrows(SSLHandshakeException.class, sslClient::startHandshake); } @@ -1877,11 +1904,8 @@ class PostgresProtocolHandlerTest { } private RdsProxyTlsCertificates testTlsCertificates() { - EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class); - when(storage.persistentPath()).thenReturn(tempDir.toString()); - EmulatorConfig config = mock(EmulatorConfig.class); - when(config.storage()).thenReturn(storage); - return new RdsProxyTlsCertificates(config, new CertificateGenerator()); + return new RdsProxyTlsCertificates(FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")), + new CertificateGenerator()); } /** diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxyBoundsTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxyBoundsTest.java index 66d4349834..fb6d59bd18 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxyBoundsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxyBoundsTest.java @@ -1,6 +1,6 @@ package io.github.hectorvent.floci.services.rds.proxy; -import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.config.FlociCertificateAuthority; import io.github.hectorvent.floci.services.acm.CertificateGenerator; import io.github.hectorvent.floci.services.rds.container.RdsBackendGate; import io.github.hectorvent.floci.services.rds.model.DatabaseEngine; @@ -23,7 +23,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; /** * Covers the connection bounds (handshake timeout, backend-connect deferral, permit pool) added @@ -145,11 +144,7 @@ class RdsAuthProxyBoundsTest { } private RdsProxyTlsCertificates realTls() { - // The real bean generates a self-signed cert on demand; no Docker or network needed. - EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class); - when(storage.persistentPath()).thenReturn(tempDir.toString()); - EmulatorConfig config = mock(EmulatorConfig.class); - when(config.storage()).thenReturn(storage); - return new RdsProxyTlsCertificates(config, new CertificateGenerator()); + return new RdsProxyTlsCertificates(FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")), + new CertificateGenerator()); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificatesTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificatesTest.java index dc633133d9..b00c938322 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificatesTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificatesTest.java @@ -1,10 +1,13 @@ package io.github.hectorvent.floci.services.rds.proxy; -import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.config.FlociCertificateAuthority; import io.github.hectorvent.floci.core.common.Pem; import io.github.hectorvent.floci.services.acm.CertificateGenerator; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; import javax.net.ssl.SSLContext; import java.nio.file.Files; @@ -12,13 +15,20 @@ import java.nio.file.Path; import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; +import java.security.cert.CertificateExpiredException; import java.security.cert.X509Certificate; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.Set; +import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.Mockito.mock; @@ -29,6 +39,52 @@ class RdsProxyTlsCertificatesTest { @TempDir Path tempDir; + @Test + void usesTheExistingSharedCaWithoutCreatingAnotherRdsAuthority() throws Exception { + FlociCertificateAuthority sharedCa = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")); + newCertificates().sslContext(); + + assertEquals(sharedCa.caPem(), Files.readString(sharedCa.certificatePath())); + assertEquals(sharedCa.caPem(), Files.readString(tempDir.resolve("tls/rds-ca.crt"))); + assertFalse(Files.exists(tempDir.resolve("tls/rds-ca.key"))); + } + + @Test + void legacyPathsCannotOverwriteOrDeleteTheSharedPrivateKeyThroughSymlinks() throws Exception { + FlociCertificateAuthority sharedCa = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")); + Path tlsDir = sharedCa.certificatePath().getParent(); + Path sharedKeyFile = tlsDir.resolve(FlociCertificateAuthority.CA_KEY_NAME); + String sharedKey = Files.readString(sharedKeyFile); + Path legacyCertificate = Files.createSymbolicLink(tlsDir.resolve("rds-ca.crt"), sharedKeyFile); + Path legacyKey = Files.createSymbolicLink(tlsDir.resolve("rds-ca.key"), sharedKeyFile); + + newCertificates().sslContext(); + + assertFalse(Files.isSymbolicLink(legacyCertificate)); + assertEquals(sharedCa.caPem(), Files.readString(legacyCertificate)); + assertFalse(Files.isSymbolicLink(legacyKey)); + assertEquals(sharedKey, Files.readString(sharedKeyFile)); + assertEquals(sharedCa.caPem(), Files.readString(sharedCa.certificatePath())); + } + + @Test + void aFailedLegacyCertificateWriteDoesNotPublishAnInitializedContext() throws Exception { + FlociCertificateAuthority sharedCa = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")); + Path legacyCertificate = Files.createDirectory(tempDir.resolve("tls/rds-ca.crt")); + Path obstruction = Files.writeString(legacyCertificate.resolve("keep"), "not a certificate"); + RdsProxyTlsCertificates certs = newCertificates(); + + assertThrows(IllegalStateException.class, certs::sslContext); + Files.delete(obstruction); + Files.delete(legacyCertificate); + assertDoesNotThrow(certs::sslContext); + + assertEquals(sharedCa.caPem(), Files.readString(legacyCertificate)); + try (Stream files = Files.list(legacyCertificate.getParent())) { + assertFalse(files.anyMatch(path -> path.getFileName().toString().endsWith(".tmp"))); + } + } + @Test void ensureHostIsIdempotentWhenHostAlreadyCovered() { RdsProxyTlsCertificates certs = newCertificates(); @@ -57,21 +113,20 @@ class RdsProxyTlsCertificatesTest { first.ensureHost("172.17.0.5"); first.ensureHost("host.docker.internal"); - Path certFile = tempDir.resolve("tls").resolve("rds-ca.crt"); - Path keyFile = tempDir.resolve("tls").resolve("rds-ca.key"); + Path certFile = tempDir.resolve("tls").resolve(FlociCertificateAuthority.CA_CERT_NAME); + Path keyFile = tempDir.resolve("tls").resolve(FlociCertificateAuthority.CA_KEY_NAME); Path metadataFile = tempDir.resolve("tls").resolve("rds-ca.metadata.json"); assertTrue(Files.exists(certFile)); assertTrue(Files.exists(keyFile)); assertTrue(Files.exists(metadataFile)); String persistedCertPem = Files.readString(certFile); - // A fresh instance (simulating a restart) backed by the same persistent path must reuse - // the same cert rather than regenerating — otherwise a user's trusted sslrootcert goes stale - // on every restart even when no new host has appeared. RdsProxyTlsCertificates reloaded = newCertificates(); + SSLContext reloadedContext = reloaded.sslContext(); reloaded.ensureHost("172.17.0.5"); reloaded.ensureHost("host.docker.internal"); + assertSame(reloadedContext, reloaded.sslContext(), "persisted hosts do not need registration again"); assertEquals(persistedCertPem, Files.readString(certFile)); } @@ -81,12 +136,12 @@ class RdsProxyTlsCertificatesTest { certs.ensureHost("172.17.0.5"); X509Certificate firstCertificate = Pem.parseCertificate( - Files.readString(tempDir.resolve("tls").resolve("rds-ca.crt"))); + Files.readString(tempDir.resolve("tls").resolve(FlociCertificateAuthority.CA_CERT_NAME))); certs.ensureHost("host.docker.internal"); X509Certificate secondCertificate = Pem.parseCertificate( - Files.readString(tempDir.resolve("tls").resolve("rds-ca.crt"))); + Files.readString(tempDir.resolve("tls").resolve(FlociCertificateAuthority.CA_CERT_NAME))); assertEquals(firstCertificate.getPublicKey(), secondCertificate.getPublicKey(), "growing the SAN list must reuse the existing key pair, not mint a new one, " @@ -104,7 +159,7 @@ class RdsProxyTlsCertificatesTest { RdsProxyTlsCertificates certs = newCertificates(); certs.ensureHost("172.17.0.5"); - Path keyFile = tlsDir.resolve("rds-ca.key"); + Path keyFile = tlsDir.resolve(FlociCertificateAuthority.CA_KEY_NAME); assertEquals(Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE), Files.getPosixFilePermissions(keyFile), "the CA private key must not be readable by anyone but the owner"); @@ -118,16 +173,125 @@ class RdsProxyTlsCertificatesTest { certs.ensureHost("172.17.0.5"); X509Certificate certificate = Pem.parseCertificate( - Files.readString(tempDir.resolve("tls").resolve("rds-ca.crt"))); + Files.readString(tempDir.resolve("tls").resolve(FlociCertificateAuthority.CA_CERT_NAME))); assertEquals(certificate.getIssuerX500Principal(), certificate.getSubjectX500Principal()); + assertTrue(certificate.getBasicConstraints() >= 0); + } + + @Test + void replacesAnExpiredLegacyCertificateAndRetainsItsSansWithoutChangingTheSharedCa() throws Exception { + FlociCertificateAuthority sharedCa = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")); + Path tlsDir = sharedCa.certificatePath().getParent(); + CertificateGenerator.GeneratedCertificate legacy = new CertificateGenerator() + .generateCaCertificate("Legacy RDS CA", Instant.now().minusSeconds(60)); + assertThrows(CertificateExpiredException.class, () -> Pem.parseCertificate(legacy.certificatePem()).checkValidity()); + Path certFile = tlsDir.resolve("rds-ca.crt"); + Path keyFile = tlsDir.resolve("rds-ca.key"); + Files.writeString(certFile, legacy.certificatePem()); + Files.writeString(keyFile, legacy.privateKeyPem()); + Files.writeString(tlsDir.resolve("rds-ca.metadata.json"), "{\"hostnames\":[\"localhost\",\"172.17.0.5\"]}"); + + RdsProxyTlsCertificates migrated = newCertificates(); + SSLContext migratedContext = migrated.sslContext(); + migrated.ensureHost("172.17.0.5"); + assertSame(migratedContext, migrated.sslContext(), "legacy SAN metadata is retained"); + migrated.ensureHost("host.docker.internal"); + newCertificates().ensureHost("host.docker.internal"); + + assertEquals(sharedCa.caPem(), Files.readString(sharedCa.certificatePath())); + assertEquals(sharedCa.caPem(), Files.readString(certFile)); + assertFalse(Files.exists(keyFile)); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = {"{", "null", "{\"hostnames\":[null]}", "{\"hostnames\":[\" \"]}", "{\"hostnames\":[]}"}) + void recoveringMetadataDoesNotReplaceAValidTrustAnchor(String metadata) throws Exception { + newCertificates().sslContext(); + Path tlsDir = tempDir.resolve("tls"); + Path certFile = tlsDir.resolve(FlociCertificateAuthority.CA_CERT_NAME); + String trustedCertificate = Files.readString(certFile); + if (metadata != null) { + Files.writeString(tlsDir.resolve("rds-ca.metadata.json"), metadata); + } else { + Files.delete(tlsDir.resolve("rds-ca.metadata.json")); + } + + newCertificates().sslContext(); + + assertEquals(trustedCertificate, Files.readString(certFile)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void removesAnUnusableLegacyCaKeyWithoutReplacingTheSharedTrustAnchor(boolean malformedKey) throws Exception { + FlociCertificateAuthority sharedCa = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")); + CertificateGenerator.GeneratedCertificate legacy = new CertificateGenerator().generateCaCertificate("Legacy RDS CA"); + Path certFile = tempDir.resolve("tls/rds-ca.crt"); + Path keyFile = tempDir.resolve("tls/rds-ca.key"); + Files.writeString(certFile, legacy.certificatePem()); + String replacementKey = malformedKey ? "not a private key" + : new CertificateGenerator().generateCaCertificate("Unrelated CA").privateKeyPem(); + Files.writeString(keyFile, replacementKey); + + newCertificates().sslContext(); + + assertEquals(sharedCa.caPem(), Files.readString(sharedCa.certificatePath())); + assertEquals(sharedCa.caPem(), Files.readString(certFile)); + assertFalse(Files.exists(keyFile)); + } + + @Test + void renewsAnExpiringLeafWithoutChangingTheCaOrRegisteringANewHost() throws Exception { + Clock clock = mock(Clock.class); + when(clock.instant()).thenAnswer(invocation -> Instant.now()); + RdsProxyTlsCertificates certs = newCertificates(clock); + certs.ensureHost("host.docker.internal"); + SSLContext previous = certs.sslContext(); + Path certFile = tempDir.resolve("tls").resolve(FlociCertificateAuthority.CA_CERT_NAME); + String trustedCa = Files.readString(certFile); + + when(clock.instant()).thenReturn(Instant.now().plus(365, ChronoUnit.DAYS).minusSeconds(30)); + SSLContext renewed = certs.sslContext(); + + assertNotSame(previous, renewed); + assertSame(renewed, certs.sslContext()); + certs.ensureHost("host.docker.internal"); + assertSame(renewed, certs.sslContext(), "renewal retains the previous SAN set"); + assertEquals(trustedCa, Files.readString(certFile)); + RdsProxyTlsCertificates reloaded = newCertificates(clock); + SSLContext reloadedContext = reloaded.sslContext(); + reloaded.ensureHost("host.docker.internal"); + assertSame(reloadedContext, reloaded.sslContext(), "renewal persists the previous SAN set"); + } + + @Test + void aLeafCappedAtCaExpiryDoesNotRenewContinuouslyOrRotateTheCa() throws Exception { + CertificateGenerator.GeneratedCertificate ca = new CertificateGenerator().generateCaCertificate( + "Short-lived CA", Instant.now().plusSeconds(60)); + Path tlsDir = Files.createDirectories(tempDir.resolve("tls")); + Path certFile = tlsDir.resolve(FlociCertificateAuthority.CA_CERT_NAME); + Files.writeString(certFile, ca.certificatePem()); + Files.writeString(tlsDir.resolve(FlociCertificateAuthority.CA_KEY_NAME), ca.privateKeyPem()); + Clock clock = mock(Clock.class); + when(clock.instant()).thenReturn(Instant.now()); + RdsProxyTlsCertificates certs = newCertificates(clock); + SSLContext context = certs.sslContext(); + + when(clock.instant()).thenReturn(ca.notAfter().minusSeconds(1)); + assertSame(context, certs.sslContext()); + when(clock.instant()).thenReturn(ca.notAfter().plusSeconds(1)); + assertThrows(IllegalStateException.class, certs::sslContext); + assertEquals(ca.certificatePem(), Files.readString(certFile)); } private RdsProxyTlsCertificates newCertificates() { - EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class); - when(storage.persistentPath()).thenReturn(tempDir.toString()); - EmulatorConfig config = mock(EmulatorConfig.class); - when(config.storage()).thenReturn(storage); - return new RdsProxyTlsCertificates(config, new CertificateGenerator()); + return newCertificates(Clock.systemUTC()); + } + + private RdsProxyTlsCertificates newCertificates(Clock clock) { + return new RdsProxyTlsCertificates(FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")), + new CertificateGenerator(), clock); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java index 97cd0d3233..35537ff78c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java @@ -1,6 +1,6 @@ package io.github.hectorvent.floci.services.redshift.proxy; -import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.config.FlociCertificateAuthority; import io.github.hectorvent.floci.services.acm.CertificateGenerator; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator; @@ -31,7 +31,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; class RedshiftAuthProxyTest { @@ -218,12 +217,8 @@ class RedshiftAuthProxyTest { } private RdsProxyTlsCertificates realTls() { - // The real bean generates a self-signed cert on demand; no Docker or network needed. - EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class); - when(storage.persistentPath()).thenReturn(tempDir.toString()); - EmulatorConfig config = mock(EmulatorConfig.class); - when(config.storage()).thenReturn(storage); - return new RdsProxyTlsCertificates(config, new CertificateGenerator()); + return new RdsProxyTlsCertificates(FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")), + new CertificateGenerator()); } private static boolean portAccepts(int port) {