diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsForceSslCompatTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsForceSslCompatTest.java new file mode 100644 index 0000000000..0572088171 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsForceSslCompatTest.java @@ -0,0 +1,83 @@ +package com.floci.test; + +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.rds.RdsClient; +import software.amazon.awssdk.services.rds.model.ApplyMethod; +import software.amazon.awssdk.services.rds.model.Parameter; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Properties; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("RDS rds.force_ssl") +class RdsForceSslCompatTest { + + private static final String USERNAME = "admin"; + private static final String PASSWORD = "secret123"; + private static final String DATABASE = "app"; + + @Test + @DisplayName("rds.force_ssl=1 refuses a plaintext connection and accepts TLS") + void forceSslRefusesPlaintextConnections() throws Exception { + Assumptions.assumeFalse(TestFixtures.isRealAws(), "Connects through the Floci proxy host with test credentials"); + String group = TestFixtures.uniqueName("force-ssl"); + String instanceId = TestFixtures.uniqueName("rds-force-ssl"); + try (RdsClient rds = TestFixtures.rdsClient()) { + rds.createDBParameterGroup(r -> r.dbParameterGroupName(group) + .dbParameterGroupFamily("postgres16") + .description("force ssl")); + try { + rds.modifyDBParameterGroup(r -> r.dbParameterGroupName(group) + .parameters(Parameter.builder() + .parameterName("rds.force_ssl") + .parameterValue("1") + .applyMethod(ApplyMethod.IMMEDIATE) + .build())); + + int port = rds.createDBInstance(r -> r + .dbInstanceIdentifier(instanceId) + .dbInstanceClass("db.t3.micro") + .engine("postgres") + .masterUsername(USERNAME) + .masterUserPassword(PASSWORD) + .dbName(DATABASE) + .allocatedStorage(20) + .dbParameterGroupName(group)).dbInstance().endpoint().port(); + + try { + try (Connection connection = TestFixtures.awaitJdbcConnection(url(port), properties("require"))) { + assertThat(connection.isValid(5)).isTrue(); + } + assertThatThrownBy(() -> DriverManager.getConnection(url(port), properties("disable")).close()) + .isInstanceOfSatisfying(SQLException.class, + e -> assertThat(e.getSQLState()).isEqualTo("28000")) + .hasMessageContaining("no pg_hba.conf entry") + .hasMessageContaining("no encryption"); + } finally { + rds.deleteDBInstance(r -> r.dbInstanceIdentifier(instanceId).skipFinalSnapshot(true)); + } + } finally { + rds.deleteDBParameterGroup(r -> r.dbParameterGroupName(group)); + } + } + } + + private static String url(int port) { + return "jdbc:postgresql://" + TestFixtures.proxyHost() + ":" + port + "/" + DATABASE; + } + + private static Properties properties(String sslMode) { + Properties properties = new Properties(); + properties.setProperty("user", USERNAME); + properties.setProperty("password", PASSWORD); + properties.setProperty("sslmode", sslMode); + properties.setProperty("connectTimeout", "5"); + return properties; + } +} diff --git a/docs/services/rds.md b/docs/services/rds.md index 7966aa1ce6..088f084fec 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -691,10 +691,22 @@ one only Aurora has, is skipped with a warning in the database log. A formula va `require_secure_transport` and `skip_grant_tables`, which would lock out Floci's proxy (it talks to the server without TLS). When the server refuses a value and stops, the instance, or every member of the cluster, reports `incompatible-parameters` and Floci logs the server's error; correct -the group and reboot to start it again. A PostgreSQL or Aurora PostgreSQL database takes one value -from its groups, layered and applied the same way: `rds.logical_replication` of `1` starts the -server with `wal_level=logical`, as on RDS. Its other parameter group values, and those of SQL -Server, are not applied yet. +the group and reboot to start it again. A PostgreSQL or Aurora PostgreSQL database takes two values +from its groups. `rds.logical_replication` of `1`, layered and applied the same way, starts the +server with `wal_level=logical`, as on RDS. `rds.force_ssl` is described below. Its other parameter +group values, and those of SQL Server, are not applied yet. + +With `rds.force_ssl` set to `1` in a PostgreSQL instance's DB parameter group, or in an Aurora +PostgreSQL cluster's DB cluster parameter group, the auth proxy refuses a connection that does not +negotiate TLS, as AWS does, with `FATAL: no pg_hba.conf entry for host "...", user "...", +database "...", no encryption` (SQLSTATE `28000`). The value is read for each new connection, so +a change to the group applies without a reboot, as the parameter is dynamic on AWS. Floci keeps no +pending-reboot state, so a change made with `ApplyMethod=pending-reboot`, or a newly associated +group, also applies from the next connection, where AWS waits for a reboot. An Aurora cluster and +its members read the value from the DB cluster parameter group only. Floci's +default parameter groups hold no values, so a database without the override accepts plaintext +connections even where AWS's default groups set `rds.force_ssl` to `1`: RDS for PostgreSQL 15 and +later, and Aurora PostgreSQL 17 and later (Aurora PostgreSQL 16 and earlier default to `0`). ## Option Groups @@ -1316,7 +1328,8 @@ 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. +`rds.endpointHost` resolves to. A PostgreSQL database whose parameter group sets `rds.force_ssl` +to `1` refuses connections that do not negotiate TLS; see [Parameter groups](#parameter-groups). 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 diff --git a/src/main/java/io/floci/aws/services/rds/RdsService.java b/src/main/java/io/floci/aws/services/rds/RdsService.java index 1d7c13c65f..9a6762ccb1 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsService.java +++ b/src/main/java/io/floci/aws/services/rds/RdsService.java @@ -72,6 +72,7 @@ import io.floci.aws.services.rds.proxy.RdsProxyManager; import io.floci.aws.services.resourcegroupstagging.ResourceGroupsTaggingService; import io.floci.aws.services.secretsmanager.SecretsManagerService; import io.floci.aws.services.secretsmanager.model.Secret; +import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -244,6 +245,8 @@ public class RdsService implements Resettable, ResourceProvider { "MYSQL_NATIVE_PASSWORD", "MYSQL_CACHING_SHA2_PASSWORD", "POSTGRES_SCRAM_SHA_256", "POSTGRES_MD5", "SQL_SERVER_AUTHENTICATION"); + private static final String RDS_RESOURCE_RELAY_PREFIX = "rds-resource:"; + public RdsService(RdsContainerManager containerManager, RdsProxyManager proxyManager, Ec2Service ec2Service, @@ -498,6 +501,11 @@ public class RdsService implements Resettable, ResourceProvider { this.clusterAutomatedBackups = new InMemoryStorage<>(); } + @PostConstruct + void registerForceSslPolicy() { + proxyManager.forceSslWhen(this::relayForcesSsl); + } + public void restorePersistedRuntime() { Map persistedPortOwners = reservePersistedProxyPorts(); restoreClusters(persistedPortOwners); @@ -11147,7 +11155,38 @@ public class RdsService implements Resettable, ResourceProvider { if (identity == null || identity.isBlank()) { identity = currentAccountId() + ":" + resourceId; } - return "rds-resource:" + identity; + return RDS_RESOURCE_RELAY_PREFIX + identity; + } + + private boolean relayForcesSsl(String relayKey) { + if (!relayKey.startsWith(RDS_RESOURCE_RELAY_PREFIX)) { + return false; + } + String arn = relayKey.substring(RDS_RESOURCE_RELAY_PREFIX.length()); + return AwsArnUtils.resourceIfArnFor(arn, "rds") + .map(resource -> relayEngineParameters(arn, resource)) + .map(parameters -> "1".equals(parameters.get("rds.force_ssl"))) + .orElse(false); + } + + private Map relayEngineParameters(String arn, String resource) { + String accountId = accountIdFromArn(arn); + String region = effectiveRegion(regionResolver.regionOf(arn)); + DbCluster cluster; + if (resource.startsWith("cluster:")) { + cluster = findClusterForScope(accountId, region, resource.substring("cluster:".length())); + } else { + DbInstance instance = findInstanceByArnOrNull(accountId, region, arn); + if (instance == null) { + return Map.of(); + } + if (instance.getDbClusterIdentifier() == null) { + return instanceEngineParameters(instance); + } + cluster = findClusterForScope(accountId, region, instance.getDbClusterIdentifier()); + } + return cluster == null ? Map.of() + : clusterEngineParameters(accountId, region, cluster.getParameterGroupName()); } private Collection allClusters() { diff --git a/src/main/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandler.java b/src/main/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandler.java index f9cc3a3621..39071b8dd3 100644 --- a/src/main/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandler.java +++ b/src/main/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandler.java @@ -31,7 +31,8 @@ import java.util.function.BiConsumer; * *

Flow: *

    - *
  1. Read client StartupMessage (handles PostgreSQL SSL negotiation) + *
  2. Read client StartupMessage (handles PostgreSQL SSL negotiation), refusing one sent + * without TLS when {@code rds.force_ssl} requires it *
  3. Challenge client with AuthenticationCleartextPassword *
  4. Read client password *
  5. Validate (IAM SigV4 or plain password) @@ -208,12 +209,26 @@ public class PostgresProtocolHandler { boolean forwardStartupParameters, boolean databaseIamAuthentication, StartupObserver startupObserver, SessionRoleHandover roleHandover) throws IOException { + return authenticate(client, backendConnector, masterUsername, masterPassword, dbName, + iamEnabled, sigV4, binding, tlsCertificates, passwordValidator, handshakeTimeoutMillis, + forwardStartupParameters, databaseIamAuthentication, startupObserver, roleHandover, false); + } + + public static AuthenticatedSession authenticate(Socket client, BackendConnector backendConnector, + String masterUsername, String masterPassword, String dbName, + boolean iamEnabled, RdsSigV4Validator sigV4, + RdsProxyBinding binding, RdsProxyTlsCertificates tlsCertificates, + PasswordValidator passwordValidator, int handshakeTimeoutMillis, + boolean forwardStartupParameters, boolean databaseIamAuthentication, + StartupObserver startupObserver, + SessionRoleHandover roleHandover, + boolean requireSsl) throws IOException { client.setSoTimeout(handshakeTimeoutMillis); // Phase 1: Read client startup message (possibly preceded by SSL request) StartupMessage startup = readStartupMessage(client, backendConnector, databaseIamAuthentication, - tlsCertificates, handshakeTimeoutMillis); + tlsCertificates, handshakeTimeoutMillis, requireSsl); if (startup == null) { closeQuietly(client); return null; @@ -609,7 +624,7 @@ public class PostgresProtocolHandler { private static StartupMessage readStartupMessage(Socket socket, BackendConnector backendConnector, boolean forwardCancel, RdsProxyTlsCertificates tlsCertificates, - int handshakeTimeoutMillis) throws IOException { + int handshakeTimeoutMillis, boolean requireSsl) throws IOException { Socket currentSocket = socket; while (true) { InputStream in = currentSocket.getInputStream(); @@ -645,10 +660,15 @@ public class PostgresProtocolHandler { } Map params = PostgresWire.startupParameters(startup.body()); - return new StartupMessage(currentSocket, - params.getOrDefault("user", "postgres"), - params.get("database"), - params); + String user = params.getOrDefault("user", "postgres"); + if (requireSsl && !(currentSocket instanceof SSLSocket)) { + sendErrorResponse(out, "FATAL", "28000", "no pg_hba.conf entry for host \"" + + currentSocket.getInetAddress().getHostAddress() + "\", user \"" + user + + "\", database \"" + params.getOrDefault("database", user) + "\", no encryption"); + out.flush(); + return null; + } + return new StartupMessage(currentSocket, user, params.get("database"), params); } } diff --git a/src/main/java/io/floci/aws/services/rds/proxy/RdsAuthProxy.java b/src/main/java/io/floci/aws/services/rds/proxy/RdsAuthProxy.java index db79ac6e69..60c2662340 100644 --- a/src/main/java/io/floci/aws/services/rds/proxy/RdsAuthProxy.java +++ b/src/main/java/io/floci/aws/services/rds/proxy/RdsAuthProxy.java @@ -11,6 +11,7 @@ import java.net.ServerSocket; import java.net.Socket; import java.time.Duration; import java.util.concurrent.Semaphore; +import java.util.function.BooleanSupplier; /** * TCP auth proxy for a single RDS DB instance or cluster. @@ -45,6 +46,7 @@ public class RdsAuthProxy { private final int backendConnectTimeoutMillis; private final Semaphore connectionPermits; private final RdsBackendGate backendGate; + private final BooleanSupplier forceSsl; private volatile boolean running; private ServerSocket serverSocket; @@ -123,6 +125,24 @@ public class RdsAuthProxy { int maxConnections, RdsProxyBinding binding, MySqlProtocolHandler.IamUserChecker iamUserChecker, RdsBackendGate backendGate, EndpointKind endpointKind) { + this(instanceId, backendHost, backendPort, backendEndpointResolver, backendRuntimeId, + engine, iamEnabled, masterUsername, masterPassword, dbName, sigV4, + tlsCertificates, passwordValidator, handshakeTimeoutMillis, + backendConnectTimeoutMillis, maxConnections, binding, iamUserChecker, + backendGate, endpointKind, () -> false); + } + + public RdsAuthProxy(String instanceId, String backendHost, int backendPort, + BackendEndpointResolver backendEndpointResolver, String backendRuntimeId, + DatabaseEngine engine, boolean iamEnabled, + String masterUsername, String masterPassword, String dbName, + RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates, + MasterPasswordCheck passwordValidator, + int handshakeTimeoutMillis, int backendConnectTimeoutMillis, + int maxConnections, RdsProxyBinding binding, + MySqlProtocolHandler.IamUserChecker iamUserChecker, + RdsBackendGate backendGate, EndpointKind endpointKind, + BooleanSupplier forceSsl) { if (backendRuntimeId == null || backendRuntimeId.isBlank()) { throw new IllegalArgumentException("RDS backend runtime ID is required"); } @@ -146,6 +166,7 @@ public class RdsAuthProxy { this.backendConnectTimeoutMillis = backendConnectTimeoutMillis; this.connectionPermits = new Semaphore(Math.max(1, maxConnections)); this.backendGate = backendGate; + this.forceSsl = forceSsl; } public void start(int proxyPort) throws IOException { @@ -268,7 +289,8 @@ public class RdsAuthProxy { session = PostgresProtocolHandler.authenticate( client, connector, masterUsername, masterPassword, dbName, iamEnabled, sigV4, binding, tlsCertificates, authAdapter, - handshakeTimeoutMillis, true, endpointKind == EndpointKind.DATABASE); + handshakeTimeoutMillis, true, endpointKind == EndpointKind.DATABASE, + (user, database, parameters) -> { }, null, forceSsl.getAsBoolean()); if (session != null) { PostgresProtocolHandler.bridge(session); } diff --git a/src/main/java/io/floci/aws/services/rds/proxy/RdsProxyManager.java b/src/main/java/io/floci/aws/services/rds/proxy/RdsProxyManager.java index f771575cde..31f6ca6469 100644 --- a/src/main/java/io/floci/aws/services/rds/proxy/RdsProxyManager.java +++ b/src/main/java/io/floci/aws/services/rds/proxy/RdsProxyManager.java @@ -14,6 +14,7 @@ import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Predicate; /** * Registry of all active RDS auth proxies. One proxy per DB instance or cluster. @@ -30,6 +31,7 @@ public class RdsProxyManager { private final RdsContainerManager containerManager; private final ConcurrentHashMap proxies = new ConcurrentHashMap<>(); private final ConcurrentHashMap pendingFailedStarts = new ConcurrentHashMap<>(); + private volatile Predicate forceSsl = instanceId -> false; @Inject public RdsProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates, @@ -107,7 +109,8 @@ public class RdsProxyManager { engine, iamEnabled, masterUsername, masterPassword, dbName, sigV4Validator, tlsCertificates, passwordValidator, rdsConfig.proxyHandshakeTimeoutMillis(), rdsConfig.proxyBackendConnectTimeoutMillis(), rdsConfig.proxyMaxConnections(), - binding, username -> binding != null, backendGate, endpointKind); + binding, username -> binding != null, backendGate, endpointKind, + () -> forceSsl.test(instanceId)); try { proxy.start(proxyPort); } catch (IOException e) { @@ -152,6 +155,10 @@ public class RdsProxyManager { } } + public void forceSslWhen(Predicate forceSsl) { + this.forceSsl = forceSsl; + } + public synchronized void updateMasterPassword(String instanceId, String newPassword) { RdsAuthProxy proxy = proxies.get(instanceId); if (proxy != null) { diff --git a/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java b/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java index 74ec68355f..5d0c567301 100644 --- a/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java +++ b/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java @@ -438,6 +438,66 @@ class PostgresProtocolHandlerTest { } } + @Test + void forceSslRefusesPlaintextStartupBeforeContactingTheBackend() throws Exception { + try (ServerSocket clientServer = new ServerSocket(0); + Socket ourClient = connectTestSocket("localhost", clientServer.getLocalPort()); + Socket proxyClient = acceptTestSocket(clientServer)) { + + AtomicReference outcome = new AtomicReference<>(); + Thread authThread = Thread.ofVirtual().start(() -> outcome.set(authenticateRequiringSsl(proxyClient))); + + DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream()); + writeStartup(clientOut, "dbadmin", "appdb"); + DataInputStream clientIn = new DataInputStream(ourClient.getInputStream()); + Map error = readErrorResponse(clientIn); + + assertEquals("FATAL", error.get('S')); + assertEquals("28000", error.get('C')); + assertEquals("no pg_hba.conf entry for host \"" + ourClient.getLocalAddress().getHostAddress() + + "\", user \"dbadmin\", database \"appdb\", no encryption", error.get('M')); + assertEquals(-1, clientIn.read(), "the proxy closes the refused connection"); + authThread.join(5_000); + assertFalse(authThread.isAlive(), "authThread did not terminate"); + assertEquals("no session", outcome.get()); + } + } + + @Test + void forceSslAcceptsStartupOverTls() throws Exception { + try (ServerSocket clientServer = new ServerSocket(0); + Socket ourClient = connectTestSocket("localhost", clientServer.getLocalPort()); + Socket proxyClient = acceptTestSocket(clientServer)) { + + Thread authThread = Thread.ofVirtual().start(() -> authenticateRequiringSsl(proxyClient)); + + DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream()); + writeSslRequest(clientOut); + assertEquals('S', new DataInputStream(ourClient.getInputStream()).readUnsignedByte()); + try (SSLSocket sslClient = trustedClientSocket(ourClient)) { + sslClient.startHandshake(); + writeStartup(new DataOutputStream(sslClient.getOutputStream()), "dbadmin", "appdb"); + readCleartextPasswordChallenge(new DataInputStream(sslClient.getInputStream())); + } finally { + authThread.join(5_000); + assertFalse(authThread.isAlive(), "authThread did not terminate"); + } + } + } + + private Object authenticateRequiringSsl(Socket proxyClient) { + try { + PostgresProtocolHandler.AuthenticatedSession session = PostgresProtocolHandler.authenticate( + proxyClient, NEVER_CONNECT, "dbadmin", "adminpass", "postgres", + false, testSigV4Validator(), testBinding(), testTlsCertificates(), + (user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000, + true, true, (user, database, parameters) -> { }, null, true); + return session == null ? "no session" : session; + } catch (IOException e) { + return e; + } + } + @Test void acceptsPostgresSslRequestAndContinuesStartup() throws Exception { AtomicReference backendDatabase = new AtomicReference<>(); diff --git a/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresForceSslIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresForceSslIntegrationTest.java new file mode 100644 index 0000000000..ddbccf641c --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresForceSslIntegrationTest.java @@ -0,0 +1,181 @@ +package io.floci.aws.services.rds.proxy; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; + +import static io.floci.aws.testing.RdsRequests.assumeDocker; +import static io.floci.aws.testing.RdsRequests.createPostgresInstance; +import static io.floci.aws.testing.RdsRequests.deleteInstance; +import static io.floci.aws.testing.RdsRequests.rds; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@QuarkusTest +@Tag("docker") +class RdsPostgresForceSslIntegrationTest { + + private static final String MASTER_USER = "master"; + private static final String MASTER_PASSWORD = "Master123!"; + + @BeforeEach + void checkDocker() throws InterruptedException { + assumeDocker(); + } + + @BeforeEach + void registerPostgresDriver() throws ClassNotFoundException { + Class.forName("org.postgresql.Driver"); + } + + @Test + void instanceParameterGroupForceSslFollowsGroupChangesOnARunningInstance() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String group = "force-ssl-" + suffix; + String dbId = "force-ssl-" + suffix; + createInstanceParameterGroup(group, "postgres16"); + try { + int port = createPostgresInstance(dbId, MASTER_USER, MASTER_PASSWORD, false, group); + + assertThat(selectOne(port, "disable"), equalTo(1)); + + setInstanceForceSsl(group, "1"); + assertPlaintextRefused(port); + assertThat(selectOne(port, "require"), equalTo(1)); + + setInstanceForceSsl(group, "0"); + assertThat(selectOne(port, "disable"), equalTo(1)); + } finally { + deleteInstance(dbId); + deleteInstanceParameterGroup(group); + } + } + + @ParameterizedTest + @ValueSource(strings = {"test", "222222222222"}) + void auroraClusterParameterGroupForceSslRefusesPlaintextOnClusterAndMemberEndpoints(String accessKey) + throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String clusterGroup = "force-ssl-cpg-" + suffix; + String memberGroup = "force-ssl-mpg-" + suffix; + String clusterId = "force-ssl-cluster-" + suffix; + String memberId = clusterId + "-member"; + rds("CreateDBClusterParameterGroup", accessKey) + .formParam("DBClusterParameterGroupName", clusterGroup) + .formParam("DBParameterGroupFamily", "aurora-postgresql16") + .formParam("Description", "force ssl") + .when().post("/").then().statusCode(200); + createInstanceParameterGroup(memberGroup, "aurora-postgresql16", accessKey); + try { + rds("ModifyDBClusterParameterGroup", accessKey) + .formParam("DBClusterParameterGroupName", clusterGroup) + .formParam("Parameters.member.1.ParameterName", "rds.force_ssl") + .formParam("Parameters.member.1.ParameterValue", "1") + .formParam("Parameters.member.1.ApplyMethod", "immediate") + .when().post("/").then().statusCode(200); + setInstanceForceSsl(memberGroup, "0", accessKey); + int clusterPort = rds("CreateDBCluster", accessKey) + .formParam("DBClusterIdentifier", clusterId) + .formParam("Engine", "aurora-postgresql") + .formParam("DBClusterParameterGroupName", clusterGroup) + .formParam("MasterUsername", MASTER_USER) + .formParam("MasterUserPassword", MASTER_PASSWORD) + .when().post("/").then().statusCode(200).extract().xmlPath() + .getInt("CreateDBClusterResponse.CreateDBClusterResult.DBCluster.Port"); + int memberPort = rds("CreateDBInstance", accessKey) + .formParam("DBInstanceIdentifier", memberId) + .formParam("DBClusterIdentifier", clusterId) + .formParam("DBInstanceClass", "db.r5.large") + .formParam("Engine", "aurora-postgresql") + .formParam("DBParameterGroupName", memberGroup) + .when().post("/").then().statusCode(200).extract().xmlPath() + .getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port"); + + assertPlaintextRefused(clusterPort); + assertThat(selectOne(clusterPort, "require"), equalTo(1)); + assertPlaintextRefused(memberPort); + assertThat(selectOne(memberPort, "require"), equalTo(1)); + } finally { + rds("DeleteDBInstance", accessKey) + .formParam("DBInstanceIdentifier", memberId) + .formParam("SkipFinalSnapshot", "true") + .when().post("/"); + rds("DeleteDBCluster", accessKey) + .formParam("DBClusterIdentifier", clusterId) + .formParam("SkipFinalSnapshot", "true") + .when().post("/"); + rds("DeleteDBClusterParameterGroup", accessKey) + .formParam("DBClusterParameterGroupName", clusterGroup) + .when().post("/"); + deleteInstanceParameterGroup(memberGroup, accessKey); + } + } + + private static void createInstanceParameterGroup(String group, String family) { + createInstanceParameterGroup(group, family, "test"); + } + + private static void createInstanceParameterGroup(String group, String family, String accessKey) { + rds("CreateDBParameterGroup", accessKey) + .formParam("DBParameterGroupName", group) + .formParam("DBParameterGroupFamily", family) + .formParam("Description", "force ssl") + .when().post("/").then().statusCode(200); + } + + private static void deleteInstanceParameterGroup(String group) { + deleteInstanceParameterGroup(group, "test"); + } + + private static void deleteInstanceParameterGroup(String group, String accessKey) { + rds("DeleteDBParameterGroup", accessKey) + .formParam("DBParameterGroupName", group) + .when().post("/"); + } + + private static void setInstanceForceSsl(String group, String value) { + setInstanceForceSsl(group, value, "test"); + } + + private static void setInstanceForceSsl(String group, String value, String accessKey) { + rds("ModifyDBParameterGroup", accessKey) + .formParam("DBParameterGroupName", group) + .formParam("Parameters.member.1.ParameterName", "rds.force_ssl") + .formParam("Parameters.member.1.ParameterValue", value) + .formParam("Parameters.member.1.ApplyMethod", "immediate") + .when().post("/").then().statusCode(200); + } + + private static void assertPlaintextRefused(int port) { + SQLException refused = assertThrows(SQLException.class, () -> selectOne(port, "disable")); + assertThat(refused.getSQLState(), equalTo("28000")); + assertThat(refused.getMessage(), containsString("no pg_hba.conf entry")); + assertThat(refused.getMessage(), containsString("no encryption")); + } + + private static int selectOne(int port, String sslMode) throws SQLException { + Properties properties = new Properties(); + properties.setProperty("user", MASTER_USER); + properties.setProperty("password", MASTER_PASSWORD); + properties.setProperty("sslmode", sslMode); + try (Connection connection = DriverManager.getConnection( + "jdbc:postgresql://127.0.0.1:" + port + "/postgres", properties); + Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery("SELECT 1")) { + result.next(); + return result.getInt(1); + } + } +} diff --git a/src/test/java/io/floci/aws/testing/RdsRequests.java b/src/test/java/io/floci/aws/testing/RdsRequests.java index a36fd452a1..ff023ba132 100644 --- a/src/test/java/io/floci/aws/testing/RdsRequests.java +++ b/src/test/java/io/floci/aws/testing/RdsRequests.java @@ -29,8 +29,12 @@ public final class RdsRequests { private RdsRequests() {} public static RequestSpecification rds(String action) { + return rds(action, "test"); + } + + public static RequestSpecification rds(String action, String accessKey) { return given().header("Authorization", - "AWS4-HMAC-SHA256 Credential=test/20261011/us-east-1/rds/aws4_request") + "AWS4-HMAC-SHA256 Credential=" + accessKey + "/20261011/us-east-1/rds/aws4_request") .contentType(URLENC).formParam("Action", action).formParam("Version", "2014-10-31"); } @@ -97,7 +101,16 @@ public final class RdsRequests { /** Creates a PostgreSQL instance with database {@code appdb} and returns its endpoint port. */ public static int createPostgresInstance(String id, String masterUsername, String masterPassword, boolean iamDatabaseAuthentication) { - return rds("CreateDBInstance") + return createPostgresInstance(id, masterUsername, masterPassword, iamDatabaseAuthentication, null); + } + + /** + * Creates a PostgreSQL instance with database {@code appdb}, in DB parameter group + * {@code parameterGroupName} unless it is null, and returns its endpoint port. + */ + public static int createPostgresInstance(String id, String masterUsername, String masterPassword, + boolean iamDatabaseAuthentication, String parameterGroupName) { + RequestSpecification request = rds("CreateDBInstance") .formParam("DBInstanceIdentifier", id) .formParam("Engine", "postgres") .formParam("MasterUsername", masterUsername) @@ -105,7 +118,11 @@ public final class RdsRequests { .formParam("DBName", "appdb") .formParam("AllocatedStorage", "20") .formParam("DBInstanceClass", "db.t3.micro") - .formParam("EnableIAMDatabaseAuthentication", iamDatabaseAuthentication) + .formParam("EnableIAMDatabaseAuthentication", iamDatabaseAuthentication); + if (parameterGroupName != null) { + request.formParam("DBParameterGroupName", parameterGroupName); + } + return request .when().post("/").then().statusCode(200) .extract().xmlPath() .getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port");