diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index bfc0323bf2..140cd23072 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -475,6 +475,7 @@ These services spawn Docker containers. They require access to the Docker socket | `FLOCI_SERVICES_RDS_MOCK` | `false` | When `true`, DB clusters and instances are created instantly without a real container or auth proxy (API only) | | `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` | `7001` | First port in the RDS proxy range | | `FLOCI_SERVICES_RDS_PROXY_MAX_PORT` | `7099` | Last port in the RDS proxy range | +| `FLOCI_SERVICES_RDS_ADVERTISE_REQUESTED_PORT` | `false` | Report the requested `Port` instead of the proxy port in `Describe*` | | `FLOCI_SERVICES_RDS_ENDPOINT_HOST` | _(auto-detected)_ | Hostname advertised in RDS endpoints; when set in Docker, Floci advertises each proxy's published host port | | `FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING` | `true` | Refuse a PostgreSQL IAM auth token generated for another hostname, port or region than the endpoint publishes, as RDS does; set `false` to accept such tokens. MySQL and MariaDB always refuse them | | `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Default PostgreSQL Docker image | diff --git a/docs/services/rds.md b/docs/services/rds.md index a5545c01fe..af1d87099c 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -302,6 +302,7 @@ they belong to, as the model requires. An omitted `Enabled` activates the subscr | `FLOCI_SERVICES_RDS_MOCK` | `false` | `true` = metadata only (no Docker container or auth proxy) | | `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` | `7001` | First host port in the RDS proxy range | | `FLOCI_SERVICES_RDS_PROXY_MAX_PORT` | `7099` | Last host port in the RDS proxy range | +| `FLOCI_SERVICES_RDS_ADVERTISE_REQUESTED_PORT` | `false` | `true` = `Describe*` reports the requested `Port` instead of the proxy port; connect via the proxy port | | `FLOCI_SERVICES_RDS_ENDPOINT_HOST` | _(auto-detected)_ | Hostname advertised in RDS endpoints; when set in Docker, Floci advertises each proxy's published host port | | `FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING` | `true` | Refuse a PostgreSQL IAM auth token generated for another hostname, port or region than the endpoint publishes, as RDS does; set `false` to accept such tokens. MySQL and MariaDB always refuse them | | `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Docker image for PostgreSQL instances | @@ -328,6 +329,13 @@ host port; for example, requesting `5432` with the default `7001`-`7099` range returns a port in that range. Ports outside AWS's valid `1150`-`65535` interval are rejected. +Set `FLOCI_SERVICES_RDS_ADVERTISE_REQUESTED_PORT=true` to make `Describe*` report the requested `Port` +instead (for example so Terraform's `port` does not show a diff). The proxy still listens in the proxy +range, so connect to that port; a restore without `Port` reports the proxy port. With the flag on, IAM +authentication tokens bind to the advertised port, while the managed master-user secret carries the +connectable (proxy) port. A cluster member created without its own `Port` reports its cluster's +requested port, as AWS does. + When Docker publishes RDS proxy ports dynamically, set `FLOCI_SERVICES_RDS_ENDPOINT_HOST` to the hostname used by clients. Floci inspects its own container through the Docker socket and returns the corresponding published port from `DescribeDBInstances` and `DescribeDBClusters`. Leave the setting diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 1b1631b9d9..2936908eae 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -2022,6 +2022,11 @@ public interface EmulatorConfig { @WithDefault("7099") int proxyMaxPort(); + /** When true, Describe* reports the Port a client requested instead of the proxy port. + * The proxy still listens in the proxy port range; connect there. */ + @WithDefault("false") + boolean advertiseRequestedPort(); + /** Empty when Floci should adapt its built-in image to the requested engine version. */ Optional defaultPostgresImage(); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/SecretTargetAttachmentCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SecretTargetAttachmentCfnProvisioner.java index 277de4d243..b3baf8ddd7 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/SecretTargetAttachmentCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SecretTargetAttachmentCfnProvisioner.java @@ -274,7 +274,8 @@ public class SecretTargetAttachmentCfnProvisioner implements CfnResourceProvisio return new SecretTargetConnection( instance.getEngine().name().toLowerCase(Locale.ROOT), instance.getEndpoint().address(), - instance.getEndpoint().port(), + // Where clients connect, which differs from the endpoint while it advertises the requested Port. + rdsService.connectablePort(instance), instance.getDbName(), "dbInstanceIdentifier", instance.getDbInstanceIdentifier()); @@ -293,7 +294,7 @@ public class SecretTargetAttachmentCfnProvisioner implements CfnResourceProvisio return new SecretTargetConnection( cluster.getEngine().name().toLowerCase(Locale.ROOT), cluster.getEndpoint().address(), - cluster.getEndpoint().port(), + rdsService.connectablePort(cluster), cluster.getDatabaseName(), "dbClusterIdentifier", cluster.getDbClusterIdentifier()); 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 a9be26eada..ce9f164fc6 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsService.java +++ b/src/main/java/io/floci/aws/services/rds/RdsService.java @@ -918,11 +918,16 @@ public class RdsService implements Resettable, ResourceProvider { DbEndpoint endpoint; DbInstance instance; + // A cluster member reports its cluster's port, as AWS does, unless it asks for its own. + Integer advertisedPort = requestedPort != null || publicationCluster == null + ? requestedPort : publicationCluster.getRequestedPort(); try { - endpoint = mock ? new DbEndpoint("localhost", proxyPort) : proxyEndpoint(proxyPort); + endpoint = advertised(mock ? new DbEndpoint("localhost", proxyPort) : proxyEndpoint(proxyPort), + advertisedPort); instance = new DbInstance(id, engine, engineVersion, masterUsername, masterPassword, dbName, dbInstanceClass, allocatedStorage, DbInstanceStatus.CREATING, endpoint, iamEnabled, paramGroupName, dbClusterIdentifier, Instant.now(), proxyPort); + instance.setRequestedPort(advertisedPort); instance.setOptionGroupName(optionGroupName); instance.setDbSubnetGroupName(dbSubnetGroupName); instance.setContainerId(containerId); @@ -3705,7 +3710,7 @@ public class RdsService implements Resettable, ResourceProvider { instance.setManagedSecretCleanupRequired(false); } - private static String managedMasterSecretString(DbInstance instance) { + private String managedMasterSecretString(DbInstance instance) { try { return JSON.writeValueAsString(Map.of( "username", instance.getMasterUsername(), @@ -3714,7 +3719,7 @@ public class RdsService implements Resettable, ResourceProvider { ? instance.getEngineIdentifier().toLowerCase() : instance.getEngine().name().toLowerCase(), "host", instance.getEndpoint().address(), - "port", instance.getEndpoint().port(), + "port", connectablePort(instance), "dbname", instance.getDbName() == null ? "" : instance.getDbName(), "dbInstanceIdentifier", instance.getDbInstanceIdentifier())); } catch (JsonProcessingException e) { @@ -3851,11 +3856,11 @@ public class RdsService implements Resettable, ResourceProvider { cluster.setMasterUserSecretKmsKeyId(kmsKeyId); } - private static String managedMasterSecretString(DbCluster cluster) { + private String managedMasterSecretString(DbCluster cluster) { return managedMasterSecretString(cluster, cluster.getMasterPassword()); } - private static String managedMasterSecretString(DbCluster cluster, String password) { + private String managedMasterSecretString(DbCluster cluster, String password) { try { return JSON.writeValueAsString(Map.of( "username", cluster.getMasterUsername(), @@ -3864,7 +3869,7 @@ public class RdsService implements Resettable, ResourceProvider { ? cluster.getEngineIdentifier().toLowerCase() : cluster.getEngine().name().toLowerCase(), "host", cluster.getEndpoint().address(), - "port", cluster.getEndpoint().port(), + "port", connectablePort(cluster), "dbname", cluster.getDatabaseName() == null ? "" : cluster.getDatabaseName(), "dbClusterIdentifier", cluster.getDbClusterIdentifier())); } catch (JsonProcessingException e) { @@ -5261,7 +5266,7 @@ public class RdsService implements Resettable, ResourceProvider { if (relayEndpoint == null) { relayPort = allocateProxyPort(); allocatedRelayPort = true; - relayEndpoint = proxyEndpoint(relayPort); + relayEndpoint = advertised(proxyEndpoint(relayPort), instance.getRequestedPort()); } proxyManager.startProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id), backendIdentity.runtimeId(), @@ -5387,7 +5392,7 @@ public class RdsService implements Resettable, ResourceProvider { if (relayEndpoint == null) { relayPort = allocateProxyPort(); allocatedRelayPort = true; - relayEndpoint = proxyEndpoint(relayPort); + relayEndpoint = advertised(proxyEndpoint(relayPort), cluster.getRequestedPort()); } proxyManager.startProxy(rdsResourceRelayKey(cluster.getDbClusterArn(), id), cluster.getDbClusterArn(), @@ -5820,10 +5825,12 @@ public class RdsService implements Resettable, ResourceProvider { if (manageMasterUserPassword && (masterPassword == null || masterPassword.isBlank())) { masterPassword = generatedMasterPassword(); } - DbEndpoint endpoint = mock ? new DbEndpoint("localhost", proxyPort) : proxyEndpoint(proxyPort); + DbEndpoint endpoint = advertised(mock ? new DbEndpoint("localhost", proxyPort) : proxyEndpoint(proxyPort), + requestedPort); DbCluster cluster = new DbCluster(id, engine, engineVersion, masterUsername, masterPassword, databaseName, DbInstanceStatus.AVAILABLE, endpoint, endpoint, iamEnabled, new ArrayList<>(), paramGroupName, Instant.now(), proxyPort); + cluster.setRequestedPort(requestedPort); cluster.setEngineIdentifier(effectiveEngineName(engineParam).toLowerCase(Locale.ROOT)); cluster.setEngineMode(engineMode != null && !engineMode.isBlank() ? engineMode : "provisioned"); cluster.setStorageEncrypted(storageEncrypted); @@ -9263,6 +9270,42 @@ public class RdsService implements Resettable, ResourceProvider { usedPorts.remove(port); } + /** + * With {@code advertise-requested-port} on, reports the Port the client asked for instead of the + * proxy port. The proxy still listens on its own port; real clients connect there. + */ + private DbEndpoint advertised(DbEndpoint endpoint, Integer requestedPort) { + return advertises(requestedPort) ? new DbEndpoint(endpoint.address(), requestedPort) : endpoint; + } + + private boolean advertises(Integer requestedPort) { + return requestedPort != null && config.services().rds().advertiseRequestedPort(); + } + + /** + * The port a client connects to {@code instance} on, which a connection secret must carry: its endpoint's, unless + * the endpoint advertises the requested Port, which nothing listens on. + */ + public int connectablePort(DbInstance instance) { + return advertises(instance.getRequestedPort()) + ? connectablePort(instance.getProxyPort()) : instance.getEndpoint().port(); + } + + /** {@link #connectablePort(DbInstance)} for a cluster. */ + public int connectablePort(DbCluster cluster) { + return advertises(cluster.getRequestedPort()) + ? connectablePort(cluster.getProxyPort()) : cluster.getEndpoint().port(); + } + + private int connectablePort(int proxyPort) { + return config.services().rds().mock() ? proxyPort : proxyEndpoint(proxyPort).port(); + } + + /** The port an endpoint on {@code proxyPort} reports under the current setting. */ + private int reportedPort(int proxyPort, Integer requestedPort) { + return advertises(requestedPort) ? requestedPort : connectablePort(proxyPort); + } + private DbEndpoint proxyEndpoint(int proxyPort) { Optional endpointHost = config.services().rds().endpointHost() .filter(host -> !host.isBlank()); @@ -9951,7 +9994,17 @@ public class RdsService implements Resettable, ResourceProvider { persistedPortOwners, cluster.getDbClusterArn(), cluster.getProxyPort()); if (port != cluster.getProxyPort()) { cluster.setProxyPort(port); - DbEndpoint endpoint = proxyEndpoint(port); + DbEndpoint endpoint = advertised(proxyEndpoint(port), cluster.getRequestedPort()); + cluster.setEndpoint(endpoint); + cluster.setReaderEndpoint(endpoint); + putClusterForScope(accountIdFromArn(cluster.getDbClusterArn()), + regionFromArn(cluster.getDbClusterArn()), cluster.getDbClusterIdentifier(), cluster); + } else if (cluster.getEndpoint() != null + && cluster.getEndpoint().port() != reportedPort(port, cluster.getRequestedPort())) { + // advertise-requested-port changed across the restart: report the port it names now, at the + // address clients know. + DbEndpoint endpoint = new DbEndpoint(cluster.getEndpoint().address(), + reportedPort(port, cluster.getRequestedPort())); cluster.setEndpoint(endpoint); cluster.setReaderEndpoint(endpoint); putClusterForScope(accountIdFromArn(cluster.getDbClusterArn()), @@ -9975,14 +10028,15 @@ public class RdsService implements Resettable, ResourceProvider { portReserved = true; cluster.setProxyPort(proxyPort); if (config.services().rds().mock()) { - cluster.setEndpoint(new DbEndpoint("localhost", proxyPort)); - cluster.setReaderEndpoint(new DbEndpoint("localhost", proxyPort)); + DbEndpoint mockEndpoint = advertised(new DbEndpoint("localhost", proxyPort), cluster.getRequestedPort()); + cluster.setEndpoint(mockEndpoint); + cluster.setReaderEndpoint(mockEndpoint); cluster.setStatus(DbInstanceStatus.AVAILABLE); putClusterForScope(accountId, clusterRegion, cluster.getDbClusterIdentifier(), cluster); continue; } - DbEndpoint endpoint = proxyEndpoint(proxyPort); + DbEndpoint endpoint = advertised(proxyEndpoint(proxyPort), cluster.getRequestedPort()); cluster.setEndpoint(endpoint); cluster.setReaderEndpoint(endpoint); String image = imageForEngine(cluster.getEngine(), cluster.getEngineVersion()); @@ -10066,7 +10120,15 @@ public class RdsService implements Resettable, ResourceProvider { persistedPortOwners, instance.getDbInstanceArn(), instance.getProxyPort()); if (port != instance.getProxyPort()) { instance.setProxyPort(port); - instance.setEndpoint(proxyEndpoint(port)); + instance.setEndpoint(advertised(proxyEndpoint(port), instance.getRequestedPort())); + putInstanceForScope(accountIdFromArn(instance.getDbInstanceArn()), + regionFromArn(instance.getDbInstanceArn()), instance.getDbInstanceIdentifier(), instance); + } else if (instance.getEndpoint() != null + && instance.getEndpoint().port() != reportedPort(port, instance.getRequestedPort())) { + // advertise-requested-port changed across the restart: report the port it names now, at the + // address clients know. + instance.setEndpoint(new DbEndpoint(instance.getEndpoint().address(), + reportedPort(port, instance.getRequestedPort()))); putInstanceForScope(accountIdFromArn(instance.getDbInstanceArn()), regionFromArn(instance.getDbInstanceArn()), instance.getDbInstanceIdentifier(), instance); } @@ -10097,13 +10159,13 @@ public class RdsService implements Resettable, ResourceProvider { portReserved = true; instance.setProxyPort(proxyPort); if (config.services().rds().mock()) { - instance.setEndpoint(new DbEndpoint("localhost", proxyPort)); + instance.setEndpoint(advertised(new DbEndpoint("localhost", proxyPort), instance.getRequestedPort())); instance.setStatus(DbInstanceStatus.AVAILABLE); putInstanceForScope(accountId, instanceRegion, instance.getDbInstanceIdentifier(), instance); continue; } - instance.setEndpoint(proxyEndpoint(proxyPort)); + instance.setEndpoint(advertised(proxyEndpoint(proxyPort), instance.getRequestedPort())); String backendHost; int backendPort; if (clusterId != null && !clusterId.isBlank()) { @@ -12723,10 +12785,14 @@ public class RdsService implements Resettable, ResourceProvider { DbEndpoint blueEndpoint = blue.getEndpoint(); int bluePort = blue.getProxyPort(); + // The Port an endpoint advertises moves with it, so a rebuilt endpoint keeps reporting it. + Integer blueRequestedPort = blue.getRequestedPort(); blue.setEndpoint(green.getEndpoint()); blue.setProxyPort(green.getProxyPort()); + blue.setRequestedPort(green.getRequestedPort()); green.setEndpoint(blueEndpoint); green.setProxyPort(bluePort); + green.setRequestedPort(blueRequestedPort); // Blue moves off its ARN first, so it is free when green takes it. deleteInstanceForScope(accountId, effectiveRegion, blueId); diff --git a/src/main/java/io/floci/aws/services/rds/model/DbCluster.java b/src/main/java/io/floci/aws/services/rds/model/DbCluster.java index aee422eda3..54bf1f3cdb 100644 --- a/src/main/java/io/floci/aws/services/rds/model/DbCluster.java +++ b/src/main/java/io/floci/aws/services/rds/model/DbCluster.java @@ -42,6 +42,7 @@ public class DbCluster { private String masterUserSecretKmsKeyId; private Instant createdAt; private int proxyPort; + private Integer requestedPort; private Map tags = new LinkedHashMap<>(); private List associatedRoles = new ArrayList<>(); private String engineMode; @@ -189,6 +190,9 @@ public class DbCluster { public int getProxyPort() { return proxyPort; } public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } + public Integer getRequestedPort() { return requestedPort; } + public void setRequestedPort(Integer requestedPort) { this.requestedPort = requestedPort; } + public List getAssociatedRoles() { return associatedRoles; } public void setAssociatedRoles(List associatedRoles) { this.associatedRoles = associatedRoles != null ? new ArrayList<>(associatedRoles) : new ArrayList<>(); diff --git a/src/main/java/io/floci/aws/services/rds/model/DbInstance.java b/src/main/java/io/floci/aws/services/rds/model/DbInstance.java index a71b1df1f7..956f020942 100644 --- a/src/main/java/io/floci/aws/services/rds/model/DbInstance.java +++ b/src/main/java/io/floci/aws/services/rds/model/DbInstance.java @@ -75,6 +75,7 @@ public class DbInstance { private List associatedRoles = new ArrayList<>(); private Instant createdAt; private int proxyPort; + private Integer requestedPort; // Read replication links, kept on both ends the way DescribeDBInstances reports them: a // replica names its source, a source lists its replicas, by identifier within a Region and // by ARN across Regions. Null and empty on a standalone. The status is the "read @@ -288,6 +289,9 @@ public class DbInstance { public int getProxyPort() { return proxyPort; } public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; } + public Integer getRequestedPort() { return requestedPort; } + public void setRequestedPort(Integer requestedPort) { this.requestedPort = requestedPort; } + public String getDockerVolumeName() { return dockerVolumeName; } public void setDockerVolumeName(String dockerVolumeName) { this.dockerVolumeName = dockerVolumeName; } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 302e1f4a5c..7258a0eb60 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -604,6 +604,7 @@ floci: mock: false # FLOCI_SERVICES_RDS_MOCK — true = metadata only, no Docker (useful for CI) proxy-base-port: 7001 proxy-max-port: 7099 + # advertise-requested-port: false # FLOCI_SERVICES_RDS_ADVERTISE_REQUESTED_PORT; true = Describe* reports the requested Port, not the proxy port # endpoint-host: localhost # Hostname clients use; enables published-port translation in Docker # iam-token-endpoint-binding: true # FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING; false accepts PostgreSQL IAM tokens generated for another hostname or port # Omit image overrides to adapt Floci's built-in images to EngineVersion. diff --git a/src/test/java/io/floci/aws/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java index 898b7a2efc..f59e12f6d8 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/SecretTargetAttachmentCfnProvisionerTest.java @@ -67,6 +67,11 @@ class SecretTargetAttachmentCfnProvisionerTest { docDbService = mock(DocDbService.class); when(secretsManagerService.claimTargetAttachment(any(), any(), any())).thenReturn(true); when(secretsManagerService.canManageTargetAttachment(any(), any(), any())).thenReturn(true); + // Where clients connect, which is the endpoint's own port unless it advertises the requested Port. + when(rdsService.connectablePort(any(DbInstance.class))) + .thenAnswer(invocation -> invocation.getArgument(0).getEndpoint().port()); + when(rdsService.connectablePort(any(DbCluster.class))) + .thenAnswer(invocation -> invocation.getArgument(0).getEndpoint().port()); provisioner = CfnProvisionerFixture.builder() .secretsManager(secretsManagerService) .objectMapper(mapper) @@ -123,6 +128,30 @@ class SecretTargetAttachmentCfnProvisionerTest { SECRET_ARN, "stack/Attachment", REGION); } + @Test + void anAttachedSecretCarriesThePortClientsConnectToRatherThanTheAdvertisedOne() throws Exception { + stubSecretValues("{\"username\":\"admin\",\"password\":\"secret\"}"); + DbInstance instance = dbInstance(); + DbCluster cluster = new DbCluster(); + cluster.setDbClusterIdentifier("cluster"); + cluster.setEngine(DatabaseEngine.MYSQL); + cluster.setEndpoint(new DbEndpoint("cluster.local", 3306)); + when(rdsService.getDbInstance("database", REGION)).thenReturn(instance); + when(rdsService.getDbCluster("cluster", REGION)).thenReturn(cluster); + // The endpoints advertise the requested 5432 and 3306; the proxies listen on 7001 and 7002. + when(rdsService.connectablePort(instance)).thenReturn(7001); + when(rdsService.connectablePort(cluster)).thenReturn(7002); + + provision(instanceProperties()); + provision(properties("AWS::RDS::DBCluster", "cluster")); + + ArgumentCaptor values = ArgumentCaptor.forClass(String.class); + verify(secretsManagerService, Mockito.times(2)).putSecretValue( + eq(SECRET_ARN), values.capture(), isNull(), isNull(), eq(REGION), isNull()); + assertEquals(7001, mapper.readTree(values.getAllValues().get(0)).path("port").asInt()); + assertEquals(7002, mapper.readTree(values.getAllValues().get(1)).path("port").asInt()); + } + @Test void dbClusterAttachmentUsesClusterConnectionFields() throws Exception { stubSecretValues("{\"username\":\"admin\",\"password\":\"secret\"}"); diff --git a/src/test/java/io/floci/aws/services/rds/RdsAdvertiseRequestedPortIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsAdvertiseRequestedPortIntegrationTest.java new file mode 100644 index 0000000000..416ba9170d --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/RdsAdvertiseRequestedPortIntegrationTest.java @@ -0,0 +1,52 @@ +package io.floci.aws.services.rds; + +import io.floci.aws.testing.RdsAdvertisePortProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static io.floci.aws.testing.RdsRequests.rds; +import static org.hamcrest.Matchers.containsString; + +/** With advertise-requested-port on, Describe* reports the Port the client asked for. */ +@QuarkusTest +@TestProfile(RdsAdvertisePortProfile.class) +class RdsAdvertiseRequestedPortIntegrationTest { + + @AfterEach + void cleanUp() { + rds("DeleteDBInstance").formParam("DBInstanceIdentifier", "adv-instance") + .formParam("SkipFinalSnapshot", "true").when().post("/"); + rds("DeleteDBCluster").formParam("DBClusterIdentifier", "adv-cluster") + .formParam("SkipFinalSnapshot", "true").when().post("/"); + } + + @Test + void instanceAndClusterDescribeReportRequestedPort() { + rds("CreateDBInstance") + .formParam("DBInstanceIdentifier", "adv-instance") + .formParam("Engine", "postgres") + .formParam("DBInstanceClass", "db.t3.micro") + .formParam("AllocatedStorage", "20") + .formParam("MasterUsername", "admin") + .formParam("MasterUserPassword", "password123") + .formParam("Port", "5432") + .when().post("/").then().statusCode(200); + rds("DescribeDBInstances").formParam("DBInstanceIdentifier", "adv-instance") + .when().post("/").then().statusCode(200) + .body(containsString("5432")); + + rds("CreateDBCluster") + .formParam("DBClusterIdentifier", "adv-cluster") + .formParam("Engine", "aurora-mysql") + .formParam("MasterUsername", "admin") + .formParam("MasterUserPassword", "password123") + .formParam("Port", "3306") + .when().post("/").then().statusCode(200) + .body(containsString("3306")); + rds("DescribeDBClusters").formParam("DBClusterIdentifier", "adv-cluster") + .when().post("/").then().statusCode(200) + .body(containsString("3306")); + } +} diff --git a/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java b/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java index 0c4fefec04..845835dcf3 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java @@ -27,6 +27,7 @@ import io.floci.aws.services.rds.container.RdsBackendGate; import io.floci.aws.services.rds.container.RdsContainerHandle; import io.floci.aws.services.rds.container.RdsContainerManager; import io.floci.aws.services.rds.export.SnapshotExportSource; +import io.floci.aws.services.rds.model.BlueGreenDeployment; import io.floci.aws.services.rds.model.DatabaseEngine; import io.floci.aws.services.rds.model.DbCluster; import io.floci.aws.services.rds.model.DbClusterEndpoint; @@ -1870,6 +1871,232 @@ class RdsServiceTest { assertThrows(AwsException.class, () -> rdsService.getDbInstance("protected-db")); } + @Test + void advertiseRequestedPortReportsRequestedInstancePortAndKeepsProxyInRange() { + when(rdsConfig.advertiseRequestedPort()).thenReturn(true); + + DbInstance instance = createInstanceWithPort("advertised", 5432); + + assertEquals(5432, instance.getEndpoint().port()); + assertTrue(instance.getProxyPort() >= 7000 && instance.getProxyPort() <= 7099); + assertEquals(5432, rdsService.getDbInstance("advertised").getEndpoint().port()); + } + + @Test + void advertiseRequestedPortReportsRequestedClusterPort() { + when(rdsConfig.advertiseRequestedPort()).thenReturn(true); + + rdsService.createDbCluster("advertised-cluster", "aurora-mysql", "8.0", "admin", "password", + "dbname", false, null, null, null, false, null, null, null, null, false, null, + null, false, 3306); + + DbCluster cluster = rdsService.getDbCluster("advertised-cluster"); + assertEquals(3306, cluster.getEndpoint().port()); + assertEquals(3306, cluster.getReaderEndpoint().port()); + assertTrue(cluster.getProxyPort() >= 7000 && cluster.getProxyPort() <= 7099); + } + + @Test + void requestedPortOutsideProxyRangeIsReportedAsProxyPortWhenFlagOff() { + DbInstance instance = createInstanceWithPort("not-advertised", 5432); + + assertEquals(instance.getProxyPort(), instance.getEndpoint().port()); + } + + /** Each restore branch rebuilds the endpoint, so each one needs its own run. */ + @ParameterizedTest + @CsvSource({"false,AVAILABLE", "true,AVAILABLE", "false,STOPPED"}) + void advertisedRequestedPortSurvivesRestartThroughJsonStorage( + boolean mock, DbInstanceStatus status, @TempDir Path tempDir) { + when(rdsConfig.advertiseRequestedPort()).thenReturn(true); + when(rdsConfig.mock()).thenReturn(mock); + Path instanceFile = tempDir.resolve("instances.json"); + Path clusterFile = tempDir.resolve("clusters.json"); + PersistentStorage instances = + new PersistentStorage<>(instanceFile, new TypeReference>() {}); + PersistentStorage clusters = + new PersistentStorage<>(clusterFile, new TypeReference>() {}); + RdsService first = newService(containerManager, proxyManager, instances, clusters, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + first.createDbInstance("restart-instance", "postgres", "13", "admin", "password", + "dbname", "db.t3.micro", 20, false, null, null, null, null, false, false, null, + Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults(), null, 5432); + first.createDbCluster("restart-cluster", "aurora-mysql", "8.0", "admin", "password", + "dbname", false, null, null, null, false, null, null, null, null, false, null, + null, false, 3306); + DbInstance instance = first.getDbInstance("restart-instance"); + DbCluster cluster = first.getDbCluster("restart-cluster"); + instance.setStatus(status); + cluster.setStatus(status); + if (status == DbInstanceStatus.STOPPED) { + // A stopped record only has its endpoint rebuilt when its port is no longer claimable, + // as with a record that has no port. + instance.setProxyPort(0); + cluster.setProxyPort(0); + } + instances.put("us-east-1::restart-instance", instance); + clusters.put("us-east-1::restart-cluster", cluster); + + // Fresh storage objects read back from disk, so only what the JSON carries survives. + PersistentStorage reloadedInstances = + new PersistentStorage<>(instanceFile, new TypeReference>() {}); + reloadedInstances.load(); + PersistentStorage reloadedClusters = + new PersistentStorage<>(clusterFile, new TypeReference>() {}); + reloadedClusters.load(); + assertEquals(5432, reloadedInstances.get("us-east-1::restart-instance").orElseThrow().getRequestedPort()); + RdsService restarted = newService(containerManager, proxyManager, reloadedInstances, + reloadedClusters, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + restarted.restorePersistedRuntime(); + + assertEquals(5432, restarted.getDbInstance("restart-instance").getEndpoint().port()); + assertEquals(3306, restarted.getDbCluster("restart-cluster").getEndpoint().port()); + assertEquals(3306, restarted.getDbCluster("restart-cluster").getReaderEndpoint().port()); + } + + @Test + void managedSecretCarriesTheConnectablePortNotTheAdvertisedOne() { + when(rdsConfig.advertiseRequestedPort()).thenReturn(true); + SecretsManagerService secretsManager = mock(SecretsManagerService.class); + when(secretsManager.createSecret(any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new Secret()); + RdsService service = newService(containerManager, proxyManager, + new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), secretsManager); + + DbInstance instance = service.createDbInstance("secret-instance", "postgres", "13", "admin", + null, "dbname", "db.t3.micro", 20, false, null, null, null, null, false, true, null, + Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults(), null, 5432); + DbCluster cluster = service.createDbCluster("secret-cluster", "aurora-mysql", "8.0", "admin", + null, "dbname", false, null, null, null, false, null, null, null, null, true, null, + null, false, 3306); + + ArgumentCaptor secretString = ArgumentCaptor.forClass(String.class); + verify(secretsManager, times(2)).createSecret(any(), secretString.capture(), any(), any(), + any(), any(), any(), any()); + assertEquals(5432, instance.getEndpoint().port()); + assertEquals(3306, cluster.getEndpoint().port()); + assertTrue(secretString.getAllValues().get(0).contains("\"port\":" + instance.getProxyPort())); + assertTrue(secretString.getAllValues().get(1).contains("\"port\":" + cluster.getProxyPort())); + } + + @Test + void clusterMemberReportsTheClusterRequestedPort() { + when(rdsConfig.advertiseRequestedPort()).thenReturn(true); + rdsService.createDbCluster("member-cluster", "aurora-mysql", "8.0", "admin", "password", + "dbname", false, null, null, null, false, null, null, null, null, false, null, + null, false, 3306); + + DbInstance member = rdsService.createDbInstance("member", "aurora-mysql", "8.0", null, null, + "dbname", "db.r5.large", 20, false, null, null, "member-cluster", null, false, false, + null, Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults(), null, null); + + assertEquals(3306, member.getEndpoint().port()); + } + + @Test + void theAdvertisedPortFollowsTheEndpointThroughABlueGreenSwitchoverAndARestart(@TempDir Path tempDir) { + when(rdsConfig.advertiseRequestedPort()).thenReturn(true); + when(rdsConfig.mock()).thenReturn(true); + Path instanceFile = tempDir.resolve("instances.json"); + PersistentStorage instances = + new PersistentStorage<>(instanceFile, new TypeReference>() {}); + RdsService service = newService(containerManager, proxyManager, instances, new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + DbInstance blue = service.createDbInstance("bg-blue", "postgres", "16.3", "admin", "password", + "dbname", "db.t3.micro", 20, false, null, null, null, null, false, false, null, + Map.of(), List.of(), null, null, true, + new DbInstanceSettings(null, null, 1, null, null, null), null, 5432); + BlueGreenDeployment deployment = service.createBlueGreenDeployment( + new RdsService.BlueGreenDeploymentRequest("bg", blue.getDbInstanceArn(), "17.4", null, null, null, + null, null, Map.of()), "us-east-1"); + + service.switchoverBlueGreenDeployment(deployment.getBlueGreenDeploymentIdentifier(), null, "us-east-1"); + assertEquals(5432, service.getDbInstance("bg-blue").getEndpoint().port()); + + PersistentStorage reloaded = + new PersistentStorage<>(instanceFile, new TypeReference>() {}); + reloaded.load(); + RdsService restarted = newService(containerManager, proxyManager, reloaded, new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + restarted.restorePersistedRuntime(); + + DbInstance production = restarted.getDbInstance("bg-blue"); + assertEquals("17.4", production.getEngineVersion()); + assertEquals(5432, production.getEndpoint().port(), "the upgraded instance keeps the blue Port"); + DbInstance retired = restarted.getDbInstance("bg-blue-old1"); + assertEquals(retired.getProxyPort(), retired.getEndpoint().port(), + "the old blue keeps the endpoint green had, which asked for no Port"); + } + + @Test + void theConnectablePortIsTheProxysOnlyWhileTheEndpointAdvertisesTheRequestedPort() { + DbInstance plain = createInstanceWithPort("plain", 5432); + assertEquals(plain.getEndpoint().port(), rdsService.connectablePort(plain)); + + when(rdsConfig.advertiseRequestedPort()).thenReturn(true); + DbInstance advertising = createInstanceWithPort("advertising", 5432); + DbCluster cluster = rdsService.createDbCluster("advertising-cluster", "aurora-mysql", "8.0", "admin", + "password", "dbname", false, null, null, null, false, null, null, null, null, false, null, + null, false, 3306); + + assertEquals(5432, advertising.getEndpoint().port()); + assertEquals(advertising.getProxyPort(), rdsService.connectablePort(advertising)); + assertEquals(3306, cluster.getEndpoint().port()); + assertEquals(cluster.getProxyPort(), rdsService.connectablePort(cluster)); + } + + /** A stopped record keeps its proxy port across a restart, and must still follow a changed setting. */ + @ParameterizedTest + @CsvSource({"true,false", "false,true"}) + void aStoppedDatabaseFollowsTheSettingAcrossARestart(boolean before, boolean after, @TempDir Path tempDir) { + when(rdsConfig.advertiseRequestedPort()).thenReturn(before); + Path instanceFile = tempDir.resolve("instances.json"); + Path clusterFile = tempDir.resolve("clusters.json"); + PersistentStorage instances = + new PersistentStorage<>(instanceFile, new TypeReference>() {}); + PersistentStorage clusters = + new PersistentStorage<>(clusterFile, new TypeReference>() {}); + RdsService first = newService(containerManager, proxyManager, instances, clusters, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + DbInstance instance = first.createDbInstance("stopped-instance", "postgres", "13", "admin", "password", + "dbname", "db.t3.micro", 20, false, null, null, null, null, false, false, null, + Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults(), null, 5432); + DbCluster cluster = first.createDbCluster("stopped-cluster", "aurora-mysql", "8.0", "admin", "password", + "dbname", false, null, null, null, false, null, null, null, null, false, null, + null, false, 3306); + instance.setStatus(DbInstanceStatus.STOPPED); + cluster.setStatus(DbInstanceStatus.STOPPED); + instances.put("us-east-1::stopped-instance", instance); + clusters.put("us-east-1::stopped-cluster", cluster); + int instanceProxyPort = instance.getProxyPort(); + int clusterProxyPort = cluster.getProxyPort(); + + when(rdsConfig.advertiseRequestedPort()).thenReturn(after); + PersistentStorage reloadedInstances = + new PersistentStorage<>(instanceFile, new TypeReference>() {}); + reloadedInstances.load(); + PersistentStorage reloadedClusters = + new PersistentStorage<>(clusterFile, new TypeReference>() {}); + reloadedClusters.load(); + RdsService restarted = newService(containerManager, proxyManager, reloadedInstances, reloadedClusters, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + restarted.restorePersistedRuntime(); + + DbInstance stoppedInstance = restarted.getDbInstance("stopped-instance"); + DbCluster stoppedCluster = restarted.getDbCluster("stopped-cluster"); + assertEquals(instanceProxyPort, stoppedInstance.getProxyPort(), "the proxy port was reclaimed unchanged"); + assertEquals(after ? 5432 : instanceProxyPort, stoppedInstance.getEndpoint().port()); + assertEquals(after ? 3306 : clusterProxyPort, stoppedCluster.getEndpoint().port()); + assertEquals(after ? 3306 : clusterProxyPort, stoppedCluster.getReaderEndpoint().port()); + } + + private DbInstance createInstanceWithPort(String id, int port) { + return rdsService.createDbInstance(id, "postgres", "13", "admin", "password", + "dbname", "db.t3.micro", 20, false, null, null, null, null, false, false, null, + Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults(), null, port); + } + @Test void failedInstanceStorageDeleteRetainsRecordAndPortForRetry() { when(rdsConfig.proxyMaxPort()).thenReturn(7000); @@ -8227,6 +8454,34 @@ class RdsServiceTest { assertEquals(0, failed.getProxyPort()); } + @Test + void retryOfEndpointlessInstanceAndClusterAdvertisesTheRequestedPort() { + when(rdsConfig.advertiseRequestedPort()).thenReturn(true); + InMemoryStorage instances = new InMemoryStorage<>(); + InMemoryStorage clusters = new InMemoryStorage<>(); + DbInstance instance = persistedInstance("legacy", "123456789012", "secret", 7000); + instance.setStatus(DbInstanceStatus.FAILED); + instance.setEndpoint(null); + instance.setProxyPort(0); + instance.setRequestedPort(5432); + instances.put("legacy", instance); + DbCluster cluster = persistedCluster("123456789012", "secret", 7000); + cluster.setStatus(DbInstanceStatus.FAILED); + cluster.setEndpoint(null); + cluster.setReaderEndpoint(null); + cluster.setProxyPort(0); + cluster.setRequestedPort(3306); + clusters.put("cluster1", cluster); + RdsContainerManager manager = mock(RdsContainerManager.class); + when(manager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(new RdsContainerHandle("recovered-container", "arn", "legacy", "127.0.0.1", 15432)); + RdsService service = newService(manager, mock(RdsProxyManager.class), instances, clusters, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + + assertEquals(5432, service.ensureInstanceBackend("legacy", "us-east-1").getEndpoint().port()); + assertEquals(3306, service.ensureClusterBackend("cluster1", "us-east-1").getEndpoint().port()); + } + @Test void failedStartupBackendRetriesOnItsRetainedEndpoint() { InMemoryStorage instances = new InMemoryStorage<>(); diff --git a/src/test/java/io/floci/aws/testing/RdsAdvertisePortProfile.java b/src/test/java/io/floci/aws/testing/RdsAdvertisePortProfile.java new file mode 100644 index 0000000000..06ff872642 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/RdsAdvertisePortProfile.java @@ -0,0 +1,15 @@ +package io.floci.aws.testing; + +import io.quarkus.test.junit.QuarkusTestProfile; + +import java.util.Map; + +/** Mocks the RDS container layer and reports the requested Port instead of the proxy port. */ +public class RdsAdvertisePortProfile implements QuarkusTestProfile { + + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.rds.mock", "true", + "floci.services.rds.advertise-requested-port", "true"); + } +}