diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java index b989b1b07f..33592de3a6 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java @@ -57,6 +57,7 @@ import software.amazon.awssdk.services.rds.model.OptionGroupNotFoundException; import software.amazon.awssdk.services.rds.model.OptionSetting; import software.amazon.awssdk.services.rds.model.RdsException; import software.amazon.awssdk.services.rds.model.RegisterDbProxyTargetsResponse; +import software.amazon.awssdk.services.rds.model.ResourceNotFoundException; import software.amazon.awssdk.services.rds.model.Tag; import software.amazon.awssdk.services.rds.model.UpgradeTarget; import software.amazon.awssdk.services.rds.model.ValidStorageOptions; @@ -764,6 +765,32 @@ class RdsControlPlaneTest { } } + @Test + @DisplayName("Data API endpoint: enable, describe and disable on an Aurora cluster") + void sdkTogglesTheDataApiEndpoint() { + String clusterName = TestFixtures.uniqueName("rds-data-api"); + try { + String arn = rds.createDBCluster(b -> b + .dbClusterIdentifier(clusterName) + .engine("aurora-postgresql") + .engineVersion("16.3") + .masterUsername("admin") + .masterUserPassword("data-api-secret")).dbCluster().dbClusterArn(); + assertThat(rds.enableHttpEndpoint(b -> b.resourceArn(arn)).httpEndpointEnabled()).isTrue(); + assertThat(rds.describeDBClusters(b -> b.dbClusterIdentifier(clusterName)) + .dbClusters().get(0).httpEndpointEnabled()).isTrue(); + assertThat(rds.disableHttpEndpoint(b -> b.resourceArn(arn)).httpEndpointEnabled()).isFalse(); + assertThatThrownBy(() -> rds.enableHttpEndpoint(b -> b.resourceArn(arn + "-missing"))) + .isInstanceOf(ResourceNotFoundException.class); + } finally { + try { + rds.deleteDBCluster(b -> b.dbClusterIdentifier(clusterName).skipFinalSnapshot(true)); + } catch (Exception e) { + LOG.log(Level.WARNING, "Failed to clean up RDS cluster " + clusterName, e); + } + } + } + @Test @DisplayName("IAM role associations: add, describe and remove for a cluster and an instance") void sdkRoundTripsIamRoleAssociations() { diff --git a/docs/services/index.md b/docs/services/index.md index 4162e57638..3f4f5483b3 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -63,7 +63,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Amazon Data Lifecycle Manager](dlm.md) | `/policies`, `/policies/{policyId}`, `/tags/{resourceArn}` | REST JSON | 8 | | [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 30 | | [MemoryDB](memorydb.md) | `POST /` + `X-Amz-Target: AmazonMemoryDB.*` + TCP proxy | JSON 1.1 + RESP | 13 | -| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 98 | +| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 100 | | [RDS Data API](rds-data.md) | `/Execute`, `/BeginTransaction`, `/CommitTransaction`, `/RollbackTransaction` | REST JSON | 4 | | [Timestream for InfluxDB](timestream-influxdb.md) | `POST /` + `X-Amz-Target: AmazonTimestreamInfluxDB.*` + InfluxDB container | JSON 1.0 + InfluxDB HTTP | 24 | | [MSK](msk.md) | `/v1/clusters/...`, `/api/v2/clusters/...` + Redpanda broker | REST JSON + Kafka | 8 | diff --git a/docs/services/rds-data.md b/docs/services/rds-data.md index c91af02dda..f41c079408 100644 --- a/docs/services/rds-data.md +++ b/docs/services/rds-data.md @@ -47,7 +47,7 @@ The deprecated `ExecuteSql` operation is recognized at `POST /ExecuteSql` and re - SQL errors are returned as `DatabaseErrorException` so AWS SDK callers can handle database failures with normal AWS error decoding. - If `secretArn` points to a local Secrets Manager secret with JSON credentials (`username` or `user`, plus `password`), those credentials are used. A missing or unavailable secret returns `SecretsErrorException`; malformed or incomplete credentials return `InvalidSecretException`. Floci does not fall back to the resolved RDS resource's master credentials when a secret ARN was supplied. - `formatRecordsAs=JSON`, `formattedRecords`, and `resultSetOptions` are not implemented yet, and `ExecuteStatement` requests asking for those result modes return `BadRequestException`. They are `ExecuteStatement`-only fields in the AWS API, so `BatchExecuteStatement` — whose input is limited to `resourceArn`, `secretArn`, `sql`, `database`, `schema`, `parameterSets`, and `transactionId` — ignores them as AWS does rather than rejecting them. -- RDS `HttpEndpointEnabled` control-plane gating is not modeled locally; availability is controlled by `FLOCI_SERVICES_RDS_DATA_ENABLED` and whether the target local RDS resource is running. +- RDS records a cluster's `HttpEndpointEnabled` (`EnableHttpEndpoint` / `DisableHttpEndpoint`, see [RDS](rds.md#data-api-endpoint)), but the Data API does not check it: availability is controlled by `FLOCI_SERVICES_RDS_DATA_ENABLED` and whether the target local RDS resource is running. ## Configuration diff --git a/docs/services/rds.md b/docs/services/rds.md index a0b737877b..35fb26bbf3 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -71,6 +71,8 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou | `DescribeDBClusterEndpoints` | List a cluster's built-in writer and reader endpoints and its custom endpoints, with the four documented filters | | `ModifyDBClusterEndpoint` | Change a custom endpoint's type or member list | | `DeleteDBClusterEndpoint` | Delete a custom endpoint | +| `EnableHttpEndpoint` | Turn on an Aurora cluster's Data API endpoint by ARN; see [Data API endpoint](#data-api-endpoint) | +| `DisableHttpEndpoint` | Turn off a cluster's Data API endpoint by ARN | | `AddRoleToDBCluster` | Associate an IAM role with a cluster, optionally for a feature; see [IAM role associations](#iam-role-associations) | | `RemoveRoleFromDBCluster` | Remove a role from a cluster | | `AddRoleToDBInstance` | Associate an IAM role with an instance for a feature | @@ -616,6 +618,19 @@ Custom endpoints are modelled, not routed: a custom endpoint reports the cluster reachable, but connections through it go where the cluster endpoint sends them rather than being spread across the chosen members. +## Data API endpoint + +`EnableHttpEndpoint` and `DisableHttpEndpoint` turn a cluster's Data API endpoint on and off by the +cluster's ARN, and `DescribeDBClusters` reports it as `HttpEndpointEnabled`. `CreateDBCluster` and +`ModifyDBCluster` take `EnableHttpEndpoint` too, as does the `AWS::RDS::DBCluster` CloudFormation +property, so Terraform's `enable_http_endpoint` and CDK's `enableDataApi` read back what they set. + +The Data API is offered for Aurora PostgreSQL and Aurora MySQL clusters, so turning it on for any +other engine is `InvalidParameterCombination` (a create checks before the cluster exists); turning +it off is always accepted. An ARN that names no cluster in the caller's account and Region is +`ResourceNotFoundFault`, and a cluster that is not available is `InvalidResourceStateFault`. The flag +is recorded and reported only: the Data API (`rds-data`) does not refuse a cluster with it off. + ## IAM role associations `AddRoleToDBCluster` and `AddRoleToDBInstance` associate an IAM role with an available cluster or diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index 2c51c20fb1..b77cc68471 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -566,6 +566,7 @@ public class AwsQueryController { "AddTagsToResource", "ListTagsForResource", "RemoveTagsFromResource", "CreateDBCluster", "DescribeDBClusters", "DeleteDBCluster", "ModifyDBCluster", "AddRoleToDBCluster", "RemoveRoleFromDBCluster", "AddRoleToDBInstance", "RemoveRoleFromDBInstance", + "EnableHttpEndpoint", "DisableHttpEndpoint", "DescribeGlobalClusters", "CreateDBParameterGroup", "DescribeDBParameterGroups", "DeleteDBParameterGroup", "ModifyDBParameterGroup", "DescribeDBParameters", diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java index d1b21b36de..1a3b1d5714 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/RdsCfnProvisioner.java @@ -442,6 +442,11 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { if (!roles.isEmpty()) { rdsService.validateClusterRoleAssociations(id, resolveOptional(props, "Engine", engine), roles); } + boolean httpEndpoint = parseStrictBoolProp(props, "EnableHttpEndpoint", engine); + if (httpEndpoint) { + // Refused before a new cluster exists, rather than leaving one behind. + RdsService.requireDataApiEngine(resolveOptional(props, "Engine", engine)); + } boolean created = cluster == null; if (cluster != null) { cluster = rdsService.modifyDbCluster( @@ -470,6 +475,10 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { false, null, engineMode, storageEncrypted); } cluster = reconcileClusterRoles(r, cluster, roles, created, ctx.isUpdate(), region); + // EnableHttpEndpoint updates with no interruption; a template that leaves it out wants it off. + if (httpEndpoint != cluster.isHttpEndpointEnabled()) { + cluster = rdsService.setHttpEndpoint(region, cluster.getDbClusterIdentifier(), httpEndpoint); + } r.setPhysicalId(cluster.getDbClusterIdentifier()); r.getAttributes().put("DBClusterIdentifier", cluster.getDbClusterIdentifier()); if (cluster.getEndpoint() != null) { @@ -1063,6 +1072,29 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { } } + /** + * A Boolean property read strictly: absent, or resolving to {@code AWS::NoValue}, is false; true + * and false (in any case, as JSON booleans or strings) are themselves; anything else is a + * {@code ValidationError} rather than a silent false. + */ + private boolean parseStrictBoolProp(JsonNode props, String name, CloudFormationTemplateEngine engine) { + if (props == null || !props.has(name)) { + return false; + } + JsonNode value = engine.resolveNodeOmittingNoValue(props.get(name)); + if (value == null || value.isMissingNode() || value.isNull()) { + return false; + } + if (value.isBoolean()) { + return value.booleanValue(); + } + String text = value.asText(); + if ("true".equalsIgnoreCase(text) || "false".equalsIgnoreCase(text)) { + return Boolean.parseBoolean(text); + } + throw new AwsException("ValidationError", name + " must be true or false, not " + text + ".", 400); + } + private boolean parseBoolProp(JsonNode props, String name, CloudFormationTemplateEngine engine) { return Boolean.parseBoolean(resolveOptional(props, name, engine)); } diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java index ab8a345c59..27a8aba9e7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java @@ -113,6 +113,8 @@ public class RdsQueryHandler { case "DescribeDBClusterEndpoints" -> handleDescribeDbClusterEndpoints(params, region); case "ModifyDBClusterEndpoint" -> handleModifyDbClusterEndpoint(params, region); case "DeleteDBClusterEndpoint" -> handleDeleteDbClusterEndpoint(params, region); + case "EnableHttpEndpoint" -> handleSetHttpEndpoint("EnableHttpEndpoint", params, region, true); + case "DisableHttpEndpoint" -> handleSetHttpEndpoint("DisableHttpEndpoint", params, region, false); case "AddRoleToDBCluster" -> handleAddRoleToDbCluster(params, region); case "RemoveRoleFromDBCluster" -> handleRemoveRoleFromDbCluster(params, region); case "AddRoleToDBInstance" -> handleAddRoleToDbInstance(params, region); @@ -368,6 +370,16 @@ public class RdsQueryHandler { new XmlBuilder().raw(eventSubscriptionXml(subscription)).build())).build(); } + private Response handleSetHttpEndpoint(String action, MultivaluedMap params, String region, + boolean enabled) { + DbCluster cluster = service.setHttpEndpointByArn(region, params.getFirst("ResourceArn"), enabled); + String result = new XmlBuilder() + .elem("ResourceArn", cluster.getDbClusterArn()) + .elem("HttpEndpointEnabled", cluster.isHttpEndpointEnabled()) + .build(); + return Response.ok(AwsQueryResponse.envelope(action, AwsNamespaces.RDS, result)).build(); + } + private Response handleAddRoleToDbCluster(MultivaluedMap params, String region) { service.addRoleToDbCluster(region, params.getFirst("DBClusterIdentifier"), params.getFirst("RoleArn"), params.getFirst("FeatureName")); @@ -1180,6 +1192,12 @@ public class RdsQueryHandler { try { List associatedRoles = parseAssociatedRoles(params); service.validateClusterRoleAssociations(id, engine, associatedRoles); + boolean enableHttpEndpoint = Boolean.TRUE.equals(parseOptionalBoolean(params, "EnableHttpEndpoint")); + String globalCluster = params.getFirst("GlobalClusterIdentifier"); + if (enableHttpEndpoint && (globalCluster == null || globalCluster.isBlank())) { + // A global cluster's members take its Aurora engine; any other create names its own. + RdsService.requireDataApiEngine(engine); + } Double serverlessV2Min = parseDoubleParam(params, "ServerlessV2ScalingConfiguration.MinCapacity"); Double serverlessV2Max = parseDoubleParam(params, "ServerlessV2ScalingConfiguration.MaxCapacity"); Integer serverlessV2SecondsUntilAutoPause = parseIntegerParam( @@ -1222,6 +1240,9 @@ public class RdsQueryHandler { throw e; } } + if (enableHttpEndpoint) { + cluster = service.setHttpEndpoint(region, id, true); + } String result = dbClusterXml(cluster); return Response.ok(AwsQueryResponse.envelope("CreateDBCluster", AwsNamespaces.RDS, result)).build(); } catch (AwsException e) { @@ -1331,9 +1352,16 @@ public class RdsQueryHandler { Double serverlessV2Max = parseDoubleParam(params, "ServerlessV2ScalingConfiguration.MaxCapacity"); Integer serverlessV2SecondsUntilAutoPause = parseIntegerParam( params, "ServerlessV2ScalingConfiguration.SecondsUntilAutoPause"); + Boolean enableHttpEndpoint = parseOptionalBoolean(params, "EnableHttpEndpoint"); + if (Boolean.TRUE.equals(enableHttpEndpoint)) { + RdsService.requireDataApiEngine(service.getDbCluster(id, region).getEngineIdentifier()); + } DbCluster cluster = service.modifyDbCluster(id, newPassword, iamEnabled, serverlessV2Min, serverlessV2Max, serverlessV2SecondsUntilAutoPause, manageMasterUserPassword, masterUserSecretKmsKeyId, region); + if (enableHttpEndpoint != null) { + cluster = service.setHttpEndpoint(region, id, enableHttpEndpoint); + } String result = dbClusterXml(cluster); return Response.ok(AwsQueryResponse.envelope("ModifyDBCluster", AwsNamespaces.RDS, result)).build(); } catch (AwsException e) { @@ -2918,6 +2946,7 @@ public class RdsQueryHandler { .elem("LatestRestorableTime", Instant.now().toString()); } xml.elem("IAMDatabaseAuthenticationEnabled", c.isIamDatabaseAuthenticationEnabled()) + .elem("HttpEndpointEnabled", c.isHttpEndpointEnabled()) .elem("MultiAZ", c.isMultiAz()) .elem("StorageEncrypted", c.isStorageEncrypted()) .elem("AvailabilityZone", c.getAvailabilityZone() != null ? c.getAvailabilityZone() : config.defaultAvailabilityZone()) diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java index 4fc7bcce93..38b0c7f6ce 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java @@ -2213,18 +2213,30 @@ public class RdsService implements Resettable, ResourceProvider { if (!source.startsWith("arn:")) { return source; } + return clusterIdFromArn(source, region, + () -> new AwsException("InvalidParameterValue", "Invalid DB cluster identifier: " + source, 400), + () -> new AwsException("DBClusterNotFoundFault", "DB cluster " + source + " not found.", 404)); + } + + /** + * The cluster identifier an RDS cluster ARN names. An ARN that does not parse or is not an RDS + * cluster ARN raises {@code malformed}; one for another account or Region names no cluster here + * and raises {@code elsewhere}. Each caller supplies the errors its API documents. + */ + private String clusterIdFromArn(String source, String region, Supplier malformed, + Supplier elsewhere) { AwsArnUtils.Arn arn; try { arn = AwsArnUtils.parse(source); - } catch (IllegalArgumentException malformed) { - throw new AwsException("InvalidParameterValue", "Invalid DB cluster identifier: " + source, 400); + } catch (IllegalArgumentException e) { + throw malformed.get(); } String resource = arn.resource(); if (!"rds".equals(arn.service()) || !resource.startsWith("cluster:")) { - throw new AwsException("InvalidParameterValue", "Invalid DB cluster identifier: " + source, 400); + throw malformed.get(); } if (!region.equals(arn.region()) || !currentAccountId().equals(arn.accountId())) { - throw new AwsException("DBClusterNotFoundFault", "DB cluster " + source + " not found.", 404); + throw elsewhere.get(); } return resource.substring("cluster:".length()); } @@ -9753,6 +9765,67 @@ public class RdsService implements Resettable, ResourceProvider { return subscription; } + // ── Data API endpoint ───────────────────────────────────────────────────── + + /** + * Turns a cluster's Data API endpoint on or off by the cluster's ARN, as EnableHttpEndpoint and + * DisableHttpEndpoint do. An ARN that names no cluster here is {@code ResourceNotFoundFault}, a + * cluster that is not available {@code InvalidResourceStateFault}. The flag is recorded and + * reported; the Data API does not consult it. + */ + public synchronized DbCluster setHttpEndpointByArn(String region, String resourceArn, boolean enabled) { + requireParameter(resourceArn, "ResourceArn"); + String effectiveRegion = effectiveRegion(region); + DbCluster cluster = clusterForResourceArn(resourceArn, effectiveRegion); + if (cluster.getStatus() != null && cluster.getStatus() != DbInstanceStatus.AVAILABLE) { + throw new AwsException("InvalidResourceStateFault", + "DB cluster " + cluster.getDbClusterIdentifier() + " is not in available state.", 400); + } + return setHttpEndpoint(effectiveRegion, cluster, enabled); + } + + /** Sets the flag on a cluster named by identifier, for CreateDBCluster, ModifyDBCluster and CloudFormation. */ + public synchronized DbCluster setHttpEndpoint(String region, String clusterId, boolean enabled) { + String effectiveRegion = effectiveRegion(region); + return setHttpEndpoint(effectiveRegion, getDbCluster(clusterId, effectiveRegion), enabled); + } + + private DbCluster setHttpEndpoint(String effectiveRegion, DbCluster cluster, boolean enabled) { + if (enabled) { + requireDataApiEngine(engineName(cluster)); + } + cluster.setHttpEndpointEnabled(enabled); + putClusterForScope(currentAccountId(), effectiveRegion, cluster.getDbClusterIdentifier(), cluster); + LOG.infov("Data API endpoint {0} for DB cluster {1}", enabled ? "enabled" : "disabled", + cluster.getDbClusterIdentifier()); + return RESPONSE_COPIER.convertValue(cluster, DbCluster.class); + } + + private static final Set DATA_API_ENGINES = Set.of("aurora-postgresql", "aurora-mysql"); + + /** + * The Data API is offered for Aurora PostgreSQL and Aurora MySQL only, so turning it on for any + * other engine is refused; a create checks this before the cluster exists. + */ + public static void requireDataApiEngine(String engine) { + String name = engine == null ? "postgres" : engine.toLowerCase(Locale.ROOT); + if (!DATA_API_ENGINES.contains(name)) { + throw new AwsException("InvalidParameterCombination", "The Data API (HTTP endpoint) is available for " + + "Aurora PostgreSQL and Aurora MySQL DB clusters only, not for engine " + name + ".", 400); + } + } + + private DbCluster clusterForResourceArn(String resourceArn, String region) { + Supplier notFound = () -> new AwsException("ResourceNotFoundFault", + "The specified resource ARN " + resourceArn + " doesn't refer to an existing DB cluster.", 404); + DbCluster cluster = findClusterForScope(currentAccountId(), region, + clusterIdFromArn(resourceArn, region, notFound, notFound)); + if (cluster == null || !resourceArn.equals(cluster.getDbClusterArn())) { + throw notFound.get(); + } + return cluster; + } + // ── IAM role associations ───────────────────────────────────────────────── /** diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java index f6715cfd2a..b8d11b85a1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java @@ -22,6 +22,7 @@ public class DbCluster { private DbEndpoint endpoint; private DbEndpoint readerEndpoint; private boolean iamDatabaseAuthenticationEnabled; + private boolean httpEndpointEnabled; private List dbClusterMembers = new ArrayList<>(); // The member that holds the writer role. Null on a cluster persisted before the role was // modelled, in which case the first member is the writer, as it always was reported. @@ -118,6 +119,10 @@ public class DbCluster { this.iamDatabaseAuthenticationEnabled = iamDatabaseAuthenticationEnabled; } + /** Whether the Data API endpoint is on; EnableHttpEndpoint and DisableHttpEndpoint set it. */ + public boolean isHttpEndpointEnabled() { return httpEndpointEnabled; } + public void setHttpEndpointEnabled(boolean httpEndpointEnabled) { this.httpEndpointEnabled = httpEndpointEnabled; } + public List getDbClusterMembers() { return dbClusterMembers; } public void setDbClusterMembers(List dbClusterMembers) { this.dbClusterMembers = dbClusterMembers; } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java index d390956598..734c46b75f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java @@ -232,6 +232,61 @@ class RdsCfnProvisionerTest { null, null, null, false, null, null, false); } + @Test + void dbClusterEnableHttpEndpointIsAppliedOnCreateAndUpdate() { + createDbClusterEchoesRequestedId(); + DbCluster enabled = mock(DbCluster.class); + when(enabled.getDbClusterIdentifier()).thenReturn("dataapi"); + when(enabled.isHttpEndpointEnabled()).thenReturn(true); + when(rdsService.setHttpEndpoint("us-east-1", "dataapi", true)).thenReturn(enabled); + + StackResource r = provision("Cluster", "AWS::RDS::DBCluster", """ + {"DBClusterIdentifier":"dataapi","Engine":"aurora-postgresql","EnableHttpEndpoint":true} + """); + assertEquals("CREATE_COMPLETE", r.getStatus()); + verify(rdsService).setHttpEndpoint("us-east-1", "dataapi", true); + + // An update that leaves the property out turns the endpoint off again. + when(rdsService.getDbCluster("dataapi")).thenReturn(enabled); + when(rdsService.modifyDbCluster(eq("dataapi"), any(), any(), any(), any(), any(), any())).thenReturn(enabled); + DbCluster disabled = mock(DbCluster.class); + when(disabled.getDbClusterIdentifier()).thenReturn("dataapi"); + when(rdsService.setHttpEndpoint("us-east-1", "dataapi", false)).thenReturn(disabled); + provisionExisting("Cluster", "AWS::RDS::DBCluster", """ + {"DBClusterIdentifier":"dataapi","Engine":"aurora-postgresql"} + """, "us-east-1", "dataapi", Map.of("DBClusterIdentifier", "dataapi")); + verify(rdsService).setHttpEndpoint("us-east-1", "dataapi", false); + } + + @Test + void aMalformedEnableHttpEndpointFailsInsteadOfTurningTheEndpointOff() { + DbCluster enabled = mock(DbCluster.class); + when(enabled.getDbClusterIdentifier()).thenReturn("dataapi"); + when(enabled.isHttpEndpointEnabled()).thenReturn(true); + when(rdsService.getDbCluster("dataapi")).thenReturn(enabled); + when(rdsService.modifyDbCluster(eq("dataapi"), any(), any(), any(), any(), any(), any())).thenReturn(enabled); + + StackResource r = provisionExisting("Cluster", "AWS::RDS::DBCluster", """ + {"DBClusterIdentifier":"dataapi","Engine":"aurora-postgresql","EnableHttpEndpoint":"yes"} + """, "us-east-1", "dataapi", Map.of("DBClusterIdentifier", "dataapi")); + + assertEquals("CREATE_FAILED", r.getStatus()); + assertTrue(r.getStatusReason().contains("EnableHttpEndpoint must be true or false"), r.getStatusReason()); + verify(rdsService, never()).setHttpEndpoint(any(), any(), anyBoolean()); + verify(rdsService, never()).modifyDbCluster(any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void dbClusterEnableHttpEndpointOnANonAuroraEngineFailsBeforeCreating() { + StackResource r = provision("Cluster", "AWS::RDS::DBCluster", """ + {"DBClusterIdentifier":"dataapi","Engine":"postgres","EnableHttpEndpoint":true} + """); + assertEquals("CREATE_FAILED", r.getStatus()); + assertTrue(r.getStatusReason().contains("Aurora"), r.getStatusReason()); + verify(rdsService, never()).createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(), + any(), any(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), any(), any(), anyBoolean()); + } + @Test void provisionsDbClusterInStackRegion() { DbCluster cluster = mock(DbCluster.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsHttpEndpointIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsHttpEndpointIntegrationTest.java new file mode 100644 index 0000000000..498a14d342 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsHttpEndpointIntegrationTest.java @@ -0,0 +1,156 @@ +package io.github.hectorvent.floci.services.rds; + +import io.github.hectorvent.floci.testing.RdsMockProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static io.restassured.http.ContentType.URLENC; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; + +/** + * The Data API switch: {@code EnableHttpEndpoint} and {@code DisableHttpEndpoint} by cluster ARN, + * {@code EnableHttpEndpoint} on {@code CreateDBCluster} and {@code ModifyDBCluster}, and + * {@code HttpEndpointEnabled} on {@code DBCluster}. + */ +@QuarkusTest +@TestProfile(RdsMockProfile.class) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class RdsHttpEndpointIntegrationTest { + + private static final String CLUSTER = "data-api-cluster"; + private static final String ARN = "arn:aws:rds:us-east-1:000000000000:cluster:" + CLUSTER; + private static final String DESCRIBED = + "DescribeDBClustersResponse.DescribeDBClustersResult.DBClusters.DBCluster.HttpEndpointEnabled"; + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261015/us-east-1/rds/aws4_request, " + + "SignedHeaders=content-type;host, Signature=test"; + + private static RequestSpecification query(String action) { + return given().header("Authorization", AUTH) + .contentType(URLENC) + .formParam("Action", action) + .formParam("Version", "2014-10-31"); + } + + private static RequestSpecification createCluster(String id, String engine) { + return query("CreateDBCluster") + .formParam("DBClusterIdentifier", id) + .formParam("Engine", engine) + .formParam("MasterUsername", "admin") + .formParam("MasterUserPassword", "password123"); + } + + private static void expectFlag(String clusterId, String value) { + query("DescribeDBClusters").formParam("DBClusterIdentifier", clusterId) + .when().post("/").then().statusCode(200) + .body(DESCRIBED, equalTo(value)); + } + + @Test + @Order(1) + void aNewClusterHasTheEndpointOff() { + createCluster(CLUSTER, "aurora-postgresql") + .when().post("/").then().statusCode(200) + .body(containsString("false")); + } + + @Test + @Order(2) + void enableAndDisableByClusterArn() { + query("EnableHttpEndpoint").formParam("ResourceArn", ARN) + .when().post("/").then().statusCode(200) + .body("EnableHttpEndpointResponse.EnableHttpEndpointResult.ResourceArn", equalTo(ARN)) + .body("EnableHttpEndpointResponse.EnableHttpEndpointResult.HttpEndpointEnabled", equalTo("true")); + expectFlag(CLUSTER, "true"); + + query("DisableHttpEndpoint").formParam("ResourceArn", ARN) + .when().post("/").then().statusCode(200) + .body("DisableHttpEndpointResponse.DisableHttpEndpointResult.HttpEndpointEnabled", equalTo("false")); + expectFlag(CLUSTER, "false"); + } + + @Test + @Order(3) + void createAndModifyTakeEnableHttpEndpoint() { + createCluster("data-api-at-create", "aurora-mysql").formParam("EnableHttpEndpoint", "true") + .when().post("/").then().statusCode(200) + .body(containsString("true")); + expectFlag("data-api-at-create", "true"); + + query("ModifyDBCluster").formParam("DBClusterIdentifier", "data-api-at-create") + .formParam("EnableHttpEndpoint", "false") + .when().post("/").then().statusCode(200); + expectFlag("data-api-at-create", "false"); + // A modify that leaves the parameter out leaves the flag as it is. + query("ModifyDBCluster").formParam("DBClusterIdentifier", CLUSTER) + .formParam("EnableHttpEndpoint", "true") + .when().post("/").then().statusCode(200); + query("ModifyDBCluster").formParam("DBClusterIdentifier", CLUSTER) + .formParam("EnableIAMDatabaseAuthentication", "true") + .when().post("/").then().statusCode(200); + expectFlag(CLUSTER, "true"); + } + + @Test + @Order(4) + void anArnThatNamesNoClusterHereIsNotFound() { + for (String arn : new String[] { + "arn:aws:rds:us-east-1:000000000000:cluster:no-such-cluster", + "arn:aws:rds:us-east-1:000000000000:db:" + CLUSTER, + "arn:aws:rds:eu-west-1:000000000000:cluster:" + CLUSTER, + "arn:aws:rds:us-east-1:111111111111:cluster:" + CLUSTER, + "not-an-arn"}) { + query("EnableHttpEndpoint").formParam("ResourceArn", arn) + .when().post("/").then().statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("ResourceNotFoundFault")); + } + query("EnableHttpEndpoint") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("MissingParameter")); + } + + @Test + @Order(5) + void aStoppedClusterIsInTheWrongState() { + query("StopDBCluster").formParam("DBClusterIdentifier", CLUSTER) + .when().post("/").then().statusCode(200); + query("DisableHttpEndpoint").formParam("ResourceArn", ARN) + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidResourceStateFault")); + query("StartDBCluster").formParam("DBClusterIdentifier", CLUSTER) + .when().post("/").then().statusCode(200); + } + + @Test + @Order(6) + void onlyAuroraClustersTakeTheDataApi() { + createCluster("data-api-postgres", "postgres").formParam("EnableHttpEndpoint", "true") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidParameterCombination")); + query("DescribeDBClusters").formParam("DBClusterIdentifier", "data-api-postgres") + .when().post("/").then().statusCode(404); + + createCluster("data-api-postgres", "postgres") + .when().post("/").then().statusCode(200); + query("EnableHttpEndpoint") + .formParam("ResourceArn", "arn:aws:rds:us-east-1:000000000000:cluster:data-api-postgres") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidParameterCombination")); + query("ModifyDBCluster").formParam("DBClusterIdentifier", "data-api-postgres") + .formParam("EnableHttpEndpoint", "true") + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidParameterCombination")); + // Turning it off is never refused. + query("DisableHttpEndpoint") + .formParam("ResourceArn", "arn:aws:rds:us-east-1:000000000000:cluster:data-api-postgres") + .when().post("/").then().statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java index 9ec48cad11..95064fe529 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java @@ -3240,6 +3240,16 @@ class RdsServiceTest { assertNull(RdsEngineCatalog.featureNamesForEngine(null)); } + @Test + void theDataApiTakesOnlyTheAuroraEngines() { + RdsService.requireDataApiEngine("aurora-postgresql"); + RdsService.requireDataApiEngine("AURORA-MYSQL"); + for (String engine : new String[] {"aurora", "aurora-serverless", "aurora-postgresql-limitless", "postgres", null}) { + AwsException refused = assertThrows(AwsException.class, () -> RdsService.requireDataApiEngine(engine)); + assertEquals("InvalidParameterCombination", refused.getErrorCode(), String.valueOf(engine)); + } + } + @Test void engineVersionsSortNumericallyForUpgradeTargets() { RdsEngineCatalog.EngineVersion pg163 = RdsEngineCatalog.VERSIONS.stream() diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/model/DbClusterPersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/model/DbClusterPersistenceTest.java index 58d33a1d05..43fcb860bf 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/model/DbClusterPersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/model/DbClusterPersistenceTest.java @@ -12,6 +12,7 @@ import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -88,5 +89,24 @@ class DbClusterPersistenceTest { reader.load(); assertTrue(reader.get("legacy-cluster").orElseThrow().getAssociatedRoles().isEmpty()); + assertFalse(reader.get("legacy-cluster").orElseThrow().isHttpEndpointEnabled()); + } + + @Test + void httpEndpointFlagPersistsAcrossInstances(@TempDir Path directory) { + Path file = directory.resolve("rds-clusters.json"); + DbCluster cluster = new DbCluster(); + cluster.setDbClusterIdentifier("data-api-cluster"); + cluster.setHttpEndpointEnabled(true); + + PersistentStorage writer = new PersistentStorage<>( + file, new TypeReference>() {}); + writer.put(cluster.getDbClusterIdentifier(), cluster); + + PersistentStorage reader = new PersistentStorage<>( + file, new TypeReference>() {}); + reader.load(); + + assertTrue(reader.get("data-api-cluster").orElseThrow().isHttpEndpointEnabled()); } }