From a7be2dd299e07313ca3853b670e2cba5b97ac835 Mon Sep 17 00:00:00 2001 From: Kurt McAlpine Date: Sat, 5 Sep 2026 01:45:29 +1200 Subject: [PATCH] feat(neptune): support the Terraform aws_neptune_cluster read-back contract (#3017) * feat(neptune): support the Terraform aws_neptune_cluster read-back contract The Terraform AWS provider's aws_neptune_cluster resource reads back every DBCluster field after create and update, and treats a mismatch on a ForceNew attribute as a replacement. Against Floci the resource could not converge: StorageEncrypted was hardcoded to true against the provider's default of false, AvailabilityZones was emitted as a singular element that SDK parsers drop, BackupRetentionPeriod and the other settings were never stored, and tag calls on a Neptune ARN never reached the Neptune store. CreateDBCluster and ModifyDBCluster now store the settings a request carries (NeptuneClusterSettings, modelled on DocDbClusterSettings) and DescribeDBClusters reads them back with the AWS defaults otherwise: AvailabilityZones, BackupRetentionPeriod, PreferredBackupWindow, PreferredMaintenanceWindow, DBSubnetGroup, DBClusterParameterGroup, VpcSecurityGroups, StorageEncrypted, KmsKeyId, StorageType, DeletionProtection, CopyTagsToSnapshot, EnabledCloudwatchLogsExports, ReplicationSourceIdentifier, ServerlessV2ScalingConfiguration, AssociatedRoles and ClusterCreateTime. StorageEncrypted defaults to false as on AWS. Also: - A requested Port is honoured when it is free inside the proxy range, so Terraform's default port of 8182 matches the first cluster. - DeleteDBCluster refuses a cluster with DeletionProtection enabled with InvalidParameterCombination, as on AWS. - DBClusterMembers uses the DBClusterMember element the Neptune API model declares; the previous member element was dropped by SDK parsers. - New actions: AddRoleToDBCluster, RemoveRoleFromDBCluster, DescribeGlobalClusters (empty list), ListTagsForResource, AddTagsToResource and RemoveTagsFromResource. Tags are accepted on CreateDBCluster and CreateDBInstance, and the rds credential scope routes a Neptune ARN ResourceName to the Neptune handler. Verified against hashicorp/aws 6.62.0 with terraform apply, a clean re-plan, an update covering retention, protection, log exports, security groups, iam_roles and tags, a destroy blocked by deletion protection, and a destroy after disabling it. * test(compat): cover aws_neptune_cluster in the Terraform and Java SDK suites Adds a dedicated Terraform fixture and bats test that applies an aws_neptune_cluster, checks the read-back through terraform output and the AWS CLI, checks tags through ListTagsForResource, and asserts a clean re-plan. Extends the Java SDK NeptuneTest with tags, IAM roles, modify settings, deletion protection and cluster members, so a real SDK parser covers the new DBCluster fields. * fix(neptune): infer the rds service for the DBCluster role actions Unsigned Query requests resolve their service from the action name, and AddRoleToDBCluster and RemoveRoleFromDBCluster were missing from the RDS action set, so they fell through to the SQS default instead of reaching the Neptune handler. * feat(neptune): read back the settings Terraform's aws_neptune_cluster_instance manages DescribeDBInstances omitted AutoMinorVersionUpgrade, PromotionTier, PubliclyAccessible, the parameter and subnet groups and the windows, ModifyDBInstance ignored them, StorageEncrypted was hardcoded to true, and every cluster member was reported as the writer, so the provider issued a ModifyDBInstance on every apply. NeptuneInstanceSettings, modelled on NeptuneClusterSettings, stores what a request carries and DescribeDBInstances reads it back with the AWS defaults otherwise; StorageEncrypted, KmsKeyId and StorageType are the cluster's. The first member of a cluster is its writer and deleting it promotes the next. Covered by unit, integration and Java SDK tests and a Terraform compat fixture with a writer and a reader instance. --------- Co-authored-by: kurtmc <2661907+kurtmc@users.noreply.github.com> --- .../test/neptune-cluster-instance-tf/main.tf | 69 ++++ .../neptune-cluster-instance-tf/provider.tf | 28 ++ .../test/neptune-cluster-tf/main.tf | 38 +++ .../test/neptune-cluster-tf/provider.tf | 28 ++ .../test/neptune_cluster.bats | 90 +++++ .../test/neptune_cluster_instance.bats | 115 +++++++ .../test/java/com/floci/test/NeptuneTest.java | 147 +++++++- docs/services/index.md | 2 +- docs/services/neptune.md | 36 +- .../floci/core/common/AwsQueryController.java | 9 +- .../services/neptune/NeptuneQueryHandler.java | 321 +++++++++++++++++- .../services/neptune/NeptuneService.java | 191 ++++++++++- .../neptune/model/NeptuneCluster.java | 91 +++++ .../neptune/model/NeptuneClusterSettings.java | 149 ++++++++ .../neptune/model/NeptuneInstance.java | 44 +++ .../model/NeptuneInstanceSettings.java | 64 ++++ ...NeptuneClusterSettingsIntegrationTest.java | 306 +++++++++++++++++ ...eptuneInstanceSettingsIntegrationTest.java | 196 +++++++++++ .../services/neptune/NeptuneServiceTest.java | 211 ++++++++++++ 19 files changed, 2100 insertions(+), 35 deletions(-) create mode 100644 compatibility-tests/compat-terraform/test/neptune-cluster-instance-tf/main.tf create mode 100644 compatibility-tests/compat-terraform/test/neptune-cluster-instance-tf/provider.tf create mode 100644 compatibility-tests/compat-terraform/test/neptune-cluster-tf/main.tf create mode 100644 compatibility-tests/compat-terraform/test/neptune-cluster-tf/provider.tf create mode 100644 compatibility-tests/compat-terraform/test/neptune_cluster.bats create mode 100644 compatibility-tests/compat-terraform/test/neptune_cluster_instance.bats create mode 100644 src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneClusterSettings.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneInstanceSettings.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneClusterSettingsIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneInstanceSettingsIntegrationTest.java diff --git a/compatibility-tests/compat-terraform/test/neptune-cluster-instance-tf/main.tf b/compatibility-tests/compat-terraform/test/neptune-cluster-instance-tf/main.tf new file mode 100644 index 0000000000..7f41869a8e --- /dev/null +++ b/compatibility-tests/compat-terraform/test/neptune-cluster-instance-tf/main.tf @@ -0,0 +1,69 @@ +resource "aws_neptune_cluster" "cluster" { + cluster_identifier = "floci-tf-neptune-instances" + engine = "neptune" + port = 8183 + skip_final_snapshot = true + apply_immediately = true +} + +resource "aws_neptune_cluster_instance" "writer" { + identifier = "floci-tf-neptune-writer" + cluster_identifier = aws_neptune_cluster.cluster.id + instance_class = "db.r5.large" + engine = "neptune" + port = 8183 + apply_immediately = true + + tags = { + Name = "floci-tf-neptune-writer" + } +} + +resource "aws_neptune_cluster_instance" "reader" { + identifier = "floci-tf-neptune-reader" + cluster_identifier = aws_neptune_cluster.cluster.id + instance_class = "db.r5.large" + engine = "neptune" + port = 8183 + promotion_tier = 2 + auto_minor_version_upgrade = false + apply_immediately = true + + depends_on = [aws_neptune_cluster_instance.writer] +} + +output "writer_arn" { + value = aws_neptune_cluster_instance.writer.arn +} + +output "writer_endpoint" { + value = aws_neptune_cluster_instance.writer.endpoint +} + +output "writer_port" { + value = aws_neptune_cluster_instance.writer.port +} + +output "writer_is_writer" { + value = aws_neptune_cluster_instance.writer.writer +} + +output "writer_storage_encrypted" { + value = aws_neptune_cluster_instance.writer.storage_encrypted +} + +output "writer_parameter_group_name" { + value = aws_neptune_cluster_instance.writer.neptune_parameter_group_name +} + +output "writer_auto_minor_version_upgrade" { + value = aws_neptune_cluster_instance.writer.auto_minor_version_upgrade +} + +output "reader_is_writer" { + value = aws_neptune_cluster_instance.reader.writer +} + +output "reader_promotion_tier" { + value = aws_neptune_cluster_instance.reader.promotion_tier +} diff --git a/compatibility-tests/compat-terraform/test/neptune-cluster-instance-tf/provider.tf b/compatibility-tests/compat-terraform/test/neptune-cluster-instance-tf/provider.tf new file mode 100644 index 0000000000..06442884b1 --- /dev/null +++ b/compatibility-tests/compat-terraform/test/neptune-cluster-instance-tf/provider.tf @@ -0,0 +1,28 @@ +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 6.0" + } + } +} + +variable "endpoint" { + type = string + default = "http://localhost:4566" +} + +provider "aws" { + region = "us-east-1" + access_key = "test" + secret_key = "test" + + skip_credentials_validation = true + skip_metadata_api_check = true + skip_requesting_account_id = true + s3_use_path_style = true + + endpoints { + neptune = var.endpoint + } +} diff --git a/compatibility-tests/compat-terraform/test/neptune-cluster-tf/main.tf b/compatibility-tests/compat-terraform/test/neptune-cluster-tf/main.tf new file mode 100644 index 0000000000..303bab928f --- /dev/null +++ b/compatibility-tests/compat-terraform/test/neptune-cluster-tf/main.tf @@ -0,0 +1,38 @@ +resource "aws_neptune_cluster" "cluster" { + cluster_identifier = "floci-tf-neptune" + engine = "neptune" + backup_retention_period = 5 + preferred_backup_window = "07:00-09:00" + iam_database_authentication_enabled = true + deletion_protection = false + skip_final_snapshot = true + apply_immediately = true + + tags = { + Name = "floci-tf-neptune" + } +} + +output "cluster_arn" { + value = aws_neptune_cluster.cluster.arn +} + +output "cluster_resource_id" { + value = aws_neptune_cluster.cluster.cluster_resource_id +} + +output "endpoint" { + value = aws_neptune_cluster.cluster.endpoint +} + +output "port" { + value = aws_neptune_cluster.cluster.port +} + +output "storage_encrypted" { + value = aws_neptune_cluster.cluster.storage_encrypted +} + +output "parameter_group_name" { + value = aws_neptune_cluster.cluster.neptune_cluster_parameter_group_name +} diff --git a/compatibility-tests/compat-terraform/test/neptune-cluster-tf/provider.tf b/compatibility-tests/compat-terraform/test/neptune-cluster-tf/provider.tf new file mode 100644 index 0000000000..06442884b1 --- /dev/null +++ b/compatibility-tests/compat-terraform/test/neptune-cluster-tf/provider.tf @@ -0,0 +1,28 @@ +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 6.0" + } + } +} + +variable "endpoint" { + type = string + default = "http://localhost:4566" +} + +provider "aws" { + region = "us-east-1" + access_key = "test" + secret_key = "test" + + skip_credentials_validation = true + skip_metadata_api_check = true + skip_requesting_account_id = true + s3_use_path_style = true + + endpoints { + neptune = var.endpoint + } +} diff --git a/compatibility-tests/compat-terraform/test/neptune_cluster.bats b/compatibility-tests/compat-terraform/test/neptune_cluster.bats new file mode 100644 index 0000000000..2056608bd3 --- /dev/null +++ b/compatibility-tests/compat-terraform/test/neptune_cluster.bats @@ -0,0 +1,90 @@ +#!/usr/bin/env bats +# Neptune Cluster Compatibility Test + +setup_file() { + load 'test_helper/common-setup' + + NEPTUNE_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/neptune-cluster-tf" && pwd)" + cd "$NEPTUNE_TF_DIR" + + echo "# === Neptune Cluster Test ===" >&3 + echo "# Endpoint: $FLOCI_ENDPOINT" >&3 + echo "# Config: $NEPTUNE_TF_DIR" >&3 + + rm -rf .terraform .terraform.lock.hcl terraform.tfstate* 2>/dev/null || true + + echo "# --- terraform init ---" >&3 + run terraform init -input=false -no-color + if [ "$status" -ne 0 ]; then + echo "# terraform init failed: $output" >&3 + return 1 + fi + + echo "# --- terraform apply ---" >&3 + run terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color + if [ "$status" -ne 0 ]; then + echo "# terraform apply failed: $output" >&3 + return 1 + fi +} + +teardown_file() { + load 'test_helper/common-setup' + + NEPTUNE_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/neptune-cluster-tf" && pwd)" + cd "$NEPTUNE_TF_DIR" + + terraform destroy -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color || true + rm -rf .terraform .terraform.lock.hcl terraform.tfstate* 2>/dev/null || true +} + +setup() { + load 'test_helper/common-setup' + NEPTUNE_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/neptune-cluster-tf" && pwd)" +} + +@test "Neptune cluster: terraform reads back the attributes it manages" { + run terraform -chdir="$NEPTUNE_TF_DIR" output -raw storage_encrypted + assert_success + assert_output "false" + + run terraform -chdir="$NEPTUNE_TF_DIR" output -raw parameter_group_name + assert_success + assert_output "default.neptune1.3" + + run terraform -chdir="$NEPTUNE_TF_DIR" output -raw port + assert_success + assert_output "8182" + + run terraform -chdir="$NEPTUNE_TF_DIR" output -raw cluster_arn + assert_success + assert_output --partial ":cluster:floci-tf-neptune" +} + +@test "Neptune cluster: describe reports the configured settings" { + run aws_cmd neptune describe-db-clusters --db-cluster-identifier floci-tf-neptune + assert_success + [ "$(json_get "$output" '.DBClusters[0].Engine')" = "neptune" ] + [ "$(json_get "$output" '.DBClusters[0].Status')" = "available" ] + [ "$(json_get "$output" '.DBClusters[0].BackupRetentionPeriod')" = "5" ] + [ "$(json_get "$output" '.DBClusters[0].PreferredBackupWindow')" = "07:00-09:00" ] + [ "$(json_get "$output" '.DBClusters[0].StorageEncrypted')" = "false" ] + [ "$(json_get "$output" '.DBClusters[0].DeletionProtection')" = "false" ] + [ "$(json_get "$output" '.DBClusters[0].IAMDatabaseAuthenticationEnabled')" = "true" ] + [ "$(json_get "$output" '.DBClusters[0].DBClusterParameterGroup')" = "default.neptune1.3" ] + [ "$(json_get "$output" '.DBClusters[0].AvailabilityZones | length')" = "1" ] +} + +@test "Neptune cluster: tags round-trip through ListTagsForResource" { + arn=$(terraform -chdir="$NEPTUNE_TF_DIR" output -raw cluster_arn) + run aws_cmd neptune list-tags-for-resource --resource-name "$arn" + assert_success + [ "$(json_get "$output" '.TagList[] | select(.Key == "Name") | .Value')" = "floci-tf-neptune" ] +} + +@test "Neptune cluster: re-plan after apply is clean" { + cd "$NEPTUNE_TF_DIR" + run terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color -detailed-exitcode + assert_success + assert_output --partial "No changes" +} diff --git a/compatibility-tests/compat-terraform/test/neptune_cluster_instance.bats b/compatibility-tests/compat-terraform/test/neptune_cluster_instance.bats new file mode 100644 index 0000000000..58dfca8197 --- /dev/null +++ b/compatibility-tests/compat-terraform/test/neptune_cluster_instance.bats @@ -0,0 +1,115 @@ +#!/usr/bin/env bats +# Neptune Cluster Instance Compatibility Test + +setup_file() { + load 'test_helper/common-setup' + + NEPTUNE_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/neptune-cluster-instance-tf" && pwd)" + cd "$NEPTUNE_TF_DIR" + + echo "# === Neptune Cluster Instance Test ===" >&3 + echo "# Endpoint: $FLOCI_ENDPOINT" >&3 + echo "# Config: $NEPTUNE_TF_DIR" >&3 + + rm -rf .terraform .terraform.lock.hcl terraform.tfstate* 2>/dev/null || true + + echo "# --- terraform init ---" >&3 + run terraform init -input=false -no-color + if [ "$status" -ne 0 ]; then + echo "# terraform init failed: $output" >&3 + return 1 + fi + + echo "# --- terraform apply ---" >&3 + run terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color + if [ "$status" -ne 0 ]; then + echo "# terraform apply failed: $output" >&3 + return 1 + fi +} + +teardown_file() { + load 'test_helper/common-setup' + + NEPTUNE_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/neptune-cluster-instance-tf" && pwd)" + cd "$NEPTUNE_TF_DIR" + + terraform destroy -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color || true + rm -rf .terraform .terraform.lock.hcl terraform.tfstate* 2>/dev/null || true +} + +setup() { + load 'test_helper/common-setup' + NEPTUNE_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/neptune-cluster-instance-tf" && pwd)" +} + +@test "Neptune cluster instance: terraform reads back the attributes it manages" { + run terraform -chdir="$NEPTUNE_TF_DIR" output -raw writer_is_writer + assert_success + assert_output "true" + + run terraform -chdir="$NEPTUNE_TF_DIR" output -raw reader_is_writer + assert_success + assert_output "false" + + run terraform -chdir="$NEPTUNE_TF_DIR" output -raw writer_storage_encrypted + assert_success + assert_output "false" + + run terraform -chdir="$NEPTUNE_TF_DIR" output -raw writer_parameter_group_name + assert_success + assert_output "default.neptune1.3" + + run terraform -chdir="$NEPTUNE_TF_DIR" output -raw writer_port + assert_success + assert_output "8183" + + run terraform -chdir="$NEPTUNE_TF_DIR" output -raw writer_auto_minor_version_upgrade + assert_success + assert_output "true" + + run terraform -chdir="$NEPTUNE_TF_DIR" output -raw reader_promotion_tier + assert_success + assert_output "2" + + run terraform -chdir="$NEPTUNE_TF_DIR" output -raw writer_endpoint + assert_success + assert_output --partial ":8183" +} + +@test "Neptune cluster instance: describe reports the configured settings" { + run aws_cmd neptune describe-db-instances --db-instance-identifier floci-tf-neptune-reader + assert_success + [ "$(json_get "$output" '.DBInstances[0].DBClusterIdentifier')" = "floci-tf-neptune-instances" ] + [ "$(json_get "$output" '.DBInstances[0].DBInstanceClass')" = "db.r5.large" ] + [ "$(json_get "$output" '.DBInstances[0].DBInstanceStatus')" = "available" ] + [ "$(json_get "$output" '.DBInstances[0].Endpoint.Port')" = "8183" ] + [ "$(json_get "$output" '.DBInstances[0].PromotionTier')" = "2" ] + [ "$(json_get "$output" '.DBInstances[0].AutoMinorVersionUpgrade')" = "false" ] + [ "$(json_get "$output" '.DBInstances[0].PubliclyAccessible')" = "false" ] + [ "$(json_get "$output" '.DBInstances[0].StorageEncrypted')" = "false" ] + [ "$(json_get "$output" '.DBInstances[0].DBSubnetGroup.DBSubnetGroupName')" = "default" ] + [ "$(json_get "$output" '.DBInstances[0].DBParameterGroups[0].DBParameterGroupName')" = "default.neptune1.3" ] +} + +@test "Neptune cluster instance: tags round-trip through ListTagsForResource" { + arn=$(terraform -chdir="$NEPTUNE_TF_DIR" output -raw writer_arn) + run aws_cmd neptune list-tags-for-resource --resource-name "$arn" + assert_success + [ "$(json_get "$output" '.TagList[] | select(.Key == "Name") | .Value')" = "floci-tf-neptune-writer" ] +} + +@test "Neptune cluster instance: the cluster reports exactly one writer" { + run aws_cmd neptune describe-db-clusters --db-cluster-identifier floci-tf-neptune-instances + assert_success + [ "$(json_get "$output" '.DBClusters[0].DBClusterMembers | length')" = "2" ] + [ "$(json_get "$output" '[.DBClusters[0].DBClusterMembers[] | select(.IsClusterWriter)] | length')" = "1" ] + [ "$(json_get "$output" '.DBClusters[0].DBClusterMembers[] | select(.IsClusterWriter) | .DBInstanceIdentifier')" = "floci-tf-neptune-writer" ] +} + +@test "Neptune cluster instance: re-plan after apply is clean" { + cd "$NEPTUNE_TF_DIR" + run terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color -detailed-exitcode + assert_success + assert_output --partial "No changes" +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/NeptuneTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/NeptuneTest.java index 6c49b4077a..6a070b5ff9 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/NeptuneTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/NeptuneTest.java @@ -8,6 +8,8 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import software.amazon.awssdk.services.neptune.NeptuneClient; +import software.amazon.awssdk.services.neptune.model.AddRoleToDbClusterRequest; +import software.amazon.awssdk.services.neptune.model.AddTagsToResourceRequest; import software.amazon.awssdk.services.neptune.model.CreateDbClusterRequest; import software.amazon.awssdk.services.neptune.model.CreateDbInstanceRequest; import software.amazon.awssdk.services.neptune.model.DeleteDbClusterRequest; @@ -15,11 +17,16 @@ import software.amazon.awssdk.services.neptune.model.DeleteDbInstanceRequest; import software.amazon.awssdk.services.neptune.model.DescribeDbClustersRequest; import software.amazon.awssdk.services.neptune.model.DescribeDbInstancesRequest; import software.amazon.awssdk.services.neptune.model.InvalidDbClusterStateException; +import software.amazon.awssdk.services.neptune.model.ListTagsForResourceRequest; import software.amazon.awssdk.services.neptune.model.ModifyDbClusterRequest; import software.amazon.awssdk.services.neptune.model.ModifyDbInstanceRequest; - +import software.amazon.awssdk.services.neptune.model.NeptuneException; +import software.amazon.awssdk.services.neptune.model.RemoveRoleFromDbClusterRequest; +import software.amazon.awssdk.services.neptune.model.RemoveTagsFromResourceRequest; +import software.amazon.awssdk.services.neptune.model.Tag; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.tuple; @DisplayName("Neptune Cluster and Instance Management") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @@ -58,6 +65,7 @@ class NeptuneTest { var response = neptune.createDBCluster(CreateDbClusterRequest.builder() .dbClusterIdentifier(CLUSTER_ID) .engine("neptune") + .tags(Tag.builder().key("Name").value(CLUSTER_ID).build()) .build()); var cluster = response.dbCluster(); @@ -66,6 +74,14 @@ class NeptuneTest { assertThat(cluster.status()).isEqualTo("available"); assertThat(cluster.dbClusterArn()).startsWith("arn:aws:neptune:"); assertThat(cluster.port()).isGreaterThan(0); + assertThat(cluster.storageEncrypted()).isFalse(); + assertThat(cluster.backupRetentionPeriod()).isEqualTo(1); + assertThat(cluster.availabilityZones()).hasSize(1); + assertThat(cluster.dbClusterParameterGroup()).isEqualTo("default.neptune1.3"); + assertThat(cluster.dbSubnetGroup()).isEqualTo("default"); + assertThat(cluster.deletionProtection()).isFalse(); + assertThat(cluster.preferredBackupWindow()).isNotBlank(); + assertThat(cluster.preferredMaintenanceWindow()).isNotBlank(); } @Test @@ -106,13 +122,88 @@ class NeptuneTest { @Test @Order(5) - @DisplayName("CreateDBInstance returns valid instance descriptor") + @DisplayName("Tags round-trip through ListTagsForResource, AddTagsToResource and RemoveTagsFromResource") + void tagsRoundTrip() { + String arn = neptune.describeDBClusters(DescribeDbClustersRequest.builder() + .dbClusterIdentifier(CLUSTER_ID).build()).dbClusters().get(0).dbClusterArn(); + + var created = neptune.listTagsForResource(ListTagsForResourceRequest.builder().resourceName(arn).build()); + assertThat(created.tagList()).containsExactly(Tag.builder().key("Name").value(CLUSTER_ID).build()); + + neptune.addTagsToResource(AddTagsToResourceRequest.builder() + .resourceName(arn) + .tags(Tag.builder().key("team").value("graph").build()) + .build()); + neptune.removeTagsFromResource(RemoveTagsFromResourceRequest.builder() + .resourceName(arn) + .tagKeys("Name") + .build()); + + var updated = neptune.listTagsForResource(ListTagsForResourceRequest.builder().resourceName(arn).build()); + assertThat(updated.tagList()).containsExactly(Tag.builder().key("team").value("graph").build()); + } + + @Test + @Order(6) + @DisplayName("AddRoleToDBCluster and RemoveRoleFromDBCluster maintain AssociatedRoles") + void rolesRoundTrip() { + String roleArn = "arn:aws:iam::000000000000:role/" + CLUSTER_ID; + + neptune.addRoleToDBCluster(AddRoleToDbClusterRequest.builder() + .dbClusterIdentifier(CLUSTER_ID).roleArn(roleArn).build()); + var withRole = neptune.describeDBClusters(DescribeDbClustersRequest.builder() + .dbClusterIdentifier(CLUSTER_ID).build()).dbClusters().get(0); + assertThat(withRole.associatedRoles()).hasSize(1); + assertThat(withRole.associatedRoles().get(0).roleArn()).isEqualTo(roleArn); + assertThat(withRole.associatedRoles().get(0).status()).isEqualTo("ACTIVE"); + + neptune.removeRoleFromDBCluster(RemoveRoleFromDbClusterRequest.builder() + .dbClusterIdentifier(CLUSTER_ID).roleArn(roleArn).build()); + var withoutRole = neptune.describeDBClusters(DescribeDbClustersRequest.builder() + .dbClusterIdentifier(CLUSTER_ID).build()).dbClusters().get(0); + assertThat(withoutRole.associatedRoles()).isEmpty(); + } + + @Test + @Order(7) + @DisplayName("ModifyDBCluster applies backup and protection settings and protection blocks delete") + void modifySettingsAndDeletionProtection() { + var modified = neptune.modifyDBCluster(ModifyDbClusterRequest.builder() + .dbClusterIdentifier(CLUSTER_ID) + .backupRetentionPeriod(7) + .deletionProtection(true) + .build()).dbCluster(); + assertThat(modified.backupRetentionPeriod()).isEqualTo(7); + assertThat(modified.deletionProtection()).isTrue(); + + assertThatThrownBy(() -> neptune.deleteDBCluster(DeleteDbClusterRequest.builder() + .dbClusterIdentifier(CLUSTER_ID) + .skipFinalSnapshot(true) + .build())) + .isInstanceOf(NeptuneException.class) + .hasMessageContaining("deletion protection"); + + var unprotected = neptune.modifyDBCluster(ModifyDbClusterRequest.builder() + .dbClusterIdentifier(CLUSTER_ID) + .deletionProtection(false) + .build()).dbCluster(); + assertThat(unprotected.deletionProtection()).isFalse(); + assertThat(unprotected.backupRetentionPeriod()).isEqualTo(7); + } + + @Test + @Order(15) + @DisplayName("CreateDBInstance returns the descriptor Terraform's aws_neptune_cluster_instance reads back") void createInstance() { var response = neptune.createDBInstance(CreateDbInstanceRequest.builder() .dbInstanceIdentifier(INSTANCE_ID) .dbClusterIdentifier(CLUSTER_ID) .dbInstanceClass("db.r5.large") .engine("neptune") + .autoMinorVersionUpgrade(true) + .promotionTier(0) + .publiclyAccessible(false) + .tags(Tag.builder().key("Name").value(INSTANCE_ID).build()) .build()); var instance = response.dbInstance(); @@ -120,10 +211,23 @@ class NeptuneTest { assertThat(instance.dbClusterIdentifier()).isEqualTo(CLUSTER_ID); assertThat(instance.dbInstanceStatus()).isEqualTo("available"); assertThat(instance.dbInstanceArn()).startsWith("arn:aws:neptune:"); + assertThat(instance.autoMinorVersionUpgrade()).isTrue(); + assertThat(instance.promotionTier()).isZero(); + assertThat(instance.publiclyAccessible()).isFalse(); + assertThat(instance.storageEncrypted()).isFalse(); + assertThat(instance.availabilityZone()).isNotBlank(); + assertThat(instance.preferredBackupWindow()).isNotBlank(); + assertThat(instance.preferredMaintenanceWindow()).isNotBlank(); + assertThat(instance.instanceCreateTime()).isNotNull(); + assertThat(instance.dbSubnetGroup().dbSubnetGroupName()).isEqualTo("default"); + assertThat(instance.dbParameterGroups()).hasSize(1); + assertThat(instance.dbParameterGroups().get(0).dbParameterGroupName()).startsWith("default.neptune"); + assertThat(instance.endpoint().port()).isEqualTo(neptune.describeDBClusters(DescribeDbClustersRequest.builder() + .dbClusterIdentifier(CLUSTER_ID).build()).dbClusters().get(0).port()); } @Test - @Order(6) + @Order(16) @DisplayName("DescribeDBInstances returns created instance") void describeInstances() { var response = neptune.describeDBInstances(DescribeDbInstancesRequest.builder() @@ -132,22 +236,47 @@ class NeptuneTest { assertThat(response.dbInstances()).hasSize(1); assertThat(response.dbInstances().get(0).dbInstanceIdentifier()).isEqualTo(INSTANCE_ID); + assertThat(response.dbInstances().get(0).promotionTier()).isZero(); + + var cluster = neptune.describeDBClusters(DescribeDbClustersRequest.builder() + .dbClusterIdentifier(CLUSTER_ID).build()).dbClusters().get(0); + assertThat(cluster.dbClusterMembers()).hasSize(1); + assertThat(cluster.dbClusterMembers().get(0).dbInstanceIdentifier()).isEqualTo(INSTANCE_ID); + assertThat(cluster.dbClusterMembers().get(0).isClusterWriter()).isTrue(); + + var tags = neptune.listTagsForResource(ListTagsForResourceRequest.builder() + .resourceName(response.dbInstances().get(0).dbInstanceArn()).build()).tagList(); + assertThat(tags).extracting(Tag::key, Tag::value).containsExactly(tuple("Name", INSTANCE_ID)); } @Test - @Order(7) - @DisplayName("ModifyDBInstance updates instance class") + @Order(17) + @DisplayName("ModifyDBInstance updates the settings Terraform changes in place") void modifyInstance() { var response = neptune.modifyDBInstance(ModifyDbInstanceRequest.builder() .dbInstanceIdentifier(INSTANCE_ID) .dbInstanceClass("db.r5.xlarge") + .autoMinorVersionUpgrade(false) + .promotionTier(3) + .preferredMaintenanceWindow("sun:05:00-sun:06:00") + .applyImmediately(true) .build()); - assertThat(response.dbInstance().dbInstanceClass()).isEqualTo("db.r5.xlarge"); + var instance = response.dbInstance(); + assertThat(instance.dbInstanceClass()).isEqualTo("db.r5.xlarge"); + assertThat(instance.autoMinorVersionUpgrade()).isFalse(); + assertThat(instance.promotionTier()).isEqualTo(3); + assertThat(instance.preferredMaintenanceWindow()).isEqualTo("sun:05:00-sun:06:00"); + assertThat(instance.publiclyAccessible()).isFalse(); + + var described = neptune.describeDBInstances(DescribeDbInstancesRequest.builder() + .dbInstanceIdentifier(INSTANCE_ID).build()).dbInstances().get(0); + assertThat(described.promotionTier()).isEqualTo(3); + assertThat(described.autoMinorVersionUpgrade()).isFalse(); } @Test - @Order(8) + @Order(18) @DisplayName("DeleteDBCluster fails when instances still exist") void deleteClusterWithInstancesFails() { assertThatThrownBy(() -> @@ -159,7 +288,7 @@ class NeptuneTest { } @Test - @Order(9) + @Order(19) @DisplayName("DeleteDBInstance removes instance") void deleteInstance() { neptune.deleteDBInstance(DeleteDbInstanceRequest.builder() @@ -168,7 +297,7 @@ class NeptuneTest { } @Test - @Order(10) + @Order(20) @DisplayName("DeleteDBCluster removes cluster after instances are gone") void deleteCluster() { neptune.deleteDBCluster(DeleteDbClusterRequest.builder() diff --git a/docs/services/index.md b/docs/services/index.md index 706573d4e5..cc60092b45 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -54,7 +54,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Athena](athena.md) | `POST /` + `X-Amz-Target: AmazonAthena.*` | JSON 1.1 | 4 | | [Glue](glue.md) | `POST /` + `X-Amz-Target: AWSGlue.*` | JSON 1.1 | 38 | | [Lake Formation](lakeformation.md) | `POST /` | REST JSON | 16 | -| [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 8 | +| [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 14 | | [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 8 | | [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire | 21 | | [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 24 | diff --git a/docs/services/neptune.md b/docs/services/neptune.md index e8eeb17821..bb5b3526c9 100644 --- a/docs/services/neptune.md +++ b/docs/services/neptune.md @@ -24,16 +24,48 @@ The proxy is a transparent byte relay, so the host-facing proxy port range is un | Action | Description | | --- | --- | -| `CreateDBCluster` | Create a Neptune cluster and start a Gremlin Server container | +| `CreateDBCluster` | Create a Neptune cluster (tags, placement, backup, protection and log-export settings included) and start a graph database container | | `DescribeDBClusters` | List clusters and their connection details | | `DeleteDBCluster` | Stop and remove a cluster | -| `ModifyDBCluster` | Update cluster settings | +| `ModifyDBCluster` | Update cluster settings, including deletion protection, backup retention, log exports and security groups | +| `AddRoleToDBCluster` | Associate an IAM role with a cluster (listed under `AssociatedRoles`) | +| `RemoveRoleFromDBCluster` | Disassociate an IAM role from a cluster | +| `DescribeGlobalClusters` | Always an empty list; global clusters are not modelled | | `CreateDBInstance` | Add an instance to a cluster | | `DescribeDBInstances` | List instances | | `DeleteDBInstance` | Remove an instance from a cluster | | `ModifyDBInstance` | Update instance settings | +| `ListTagsForResource` | List the tags on a cluster or instance by ARN | +| `AddTagsToResource` | Add or overwrite tags on a cluster or instance | +| `RemoveTagsFromResource` | Remove tags from a cluster or instance by key | +## Terraform and the `aws_neptune_cluster` resource + +`DescribeDBClusters` returns every field the Terraform AWS provider's `aws_neptune_cluster` resource reads back, with the values the request set and the AWS defaults otherwise, so a `terraform plan` straight after `terraform apply` reports no changes: + +- `StorageEncrypted` defaults to `false`, as on AWS; pass `StorageEncrypted=true` (and optionally `KmsKeyId`) to encrypt. +- `AvailabilityZones` echoes the requested zones and otherwise contains the emulator's default zone. +- `BackupRetentionPeriod` (default 1), `PreferredBackupWindow`, `PreferredMaintenanceWindow`, `DBSubnetGroup` (default `default`), `DBClusterParameterGroup` (default `default.neptune.` for the engine version), `DeletionProtection`, `CopyTagsToSnapshot`, `StorageType`, `EnabledCloudwatchLogsExports`, `VpcSecurityGroups`, `ServerlessV2ScalingConfiguration` and `AssociatedRoles` are all stored and read back. +- Deleting a cluster with `DeletionProtection` enabled fails with `InvalidParameterCombination`, as on AWS. +- Tags given on create are readable through `ListTagsForResource`, and the provider's tag updates go through `AddTagsToResource` and `RemoveTagsFromResource`. +- `DescribeGlobalClusters` answers with an empty list, which is what the provider's read needs when the cluster is not part of a global cluster. + +### The `aws_neptune_cluster_instance` resource + +`DescribeDBInstances` reads back the fields the provider's `aws_neptune_cluster_instance` resource manages, so an instance plan is clean after apply too: + +- `AutoMinorVersionUpgrade` (default `true`), `PromotionTier` (default `1`), `PubliclyAccessible` (default `false`), `AvailabilityZone`, `DBParameterGroups` (default `default.neptune.`), `DBSubnetGroup` (default `default`), `PreferredBackupWindow` and `PreferredMaintenanceWindow` are stored on create, updated by `ModifyDBInstance` and read back. +- `StorageEncrypted`, `KmsKeyId` and `StorageType` are the cluster's values. +- The first instance created in a cluster is the writer in `DBClusterMembers`; later instances are readers, and deleting the writer promotes the next member. +- Instance tags are readable through `ListTagsForResource` with the instance ARN. + +An instance answers on its cluster's port. Terraform's instance `port` attribute defaults to `8182`, so set it to the cluster's port when the cluster does not use `8182`. + +### Port + +A requested `Port` is honoured when it is free and inside the proxy port range (`8182`-`8282` by default); otherwise the cluster gets the next free port in the range and `DescribeDBClusters` reports that port. Terraform's `port` attribute defaults to `8182`, so the first cluster is a clean match. For a second cluster set `port` explicitly (for example `port = 8183`) so the plan stays clean, because two clusters cannot share one host port. + ## Configuration | Variable | Default | Description | 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 c772653a50..8d56c718b8 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 @@ -302,8 +302,9 @@ public class AwsQueryController { case "elasticache" -> elastiCacheQueryHandler.handle(action, formParams, region); case "rds" -> { // Neptune signs requests with "rds" credential scope (same wire protocol). - // Route to Neptune when Engine=neptune (create ops) or when the cluster/instance - // already exists in Neptune storage (describe/modify/delete ops). + // Route to Neptune when Engine=neptune (create ops), when the cluster/instance + // already exists in Neptune storage (describe/modify/delete ops), or when a + // tagging ResourceName is a Neptune ARN. String engine = formParams.getFirst("Engine"); String clusterId = formParams.getFirst("DBClusterIdentifier"); String instanceId = formParams.getFirst("DBInstanceIdentifier"); @@ -315,7 +316,8 @@ public class AwsQueryController { if ("neptune".equalsIgnoreCase(engine) || neptuneService.hasCluster(clusterId) - || neptuneService.hasInstance(instanceId)) { + || neptuneService.hasInstance(instanceId) + || neptuneService.hasResourceWithArn(formParams.getFirst("ResourceName"))) { yield neptuneQueryHandler.handle(action, formParams); } @@ -518,6 +520,7 @@ public class AwsQueryController { "CreateDBSubnetGroup", "DescribeDBSubnetGroups", "ModifyDBSubnetGroup", "DeleteDBSubnetGroup", "AddTagsToResource", "ListTagsForResource", "RemoveTagsFromResource", "CreateDBCluster", "DescribeDBClusters", "DeleteDBCluster", "ModifyDBCluster", + "AddRoleToDBCluster", "RemoveRoleFromDBCluster", "DescribeGlobalClusters", "CreateDBParameterGroup", "DescribeDBParameterGroups", "DeleteDBParameterGroup", "ModifyDBParameterGroup", "DescribeDBParameters", diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneQueryHandler.java index 6df619ceba..37433b9aaa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneQueryHandler.java @@ -4,17 +4,27 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.AwsNamespaces; import io.github.hectorvent.floci.core.common.AwsQueryResponse; +import io.github.hectorvent.floci.core.common.BackupWindows; import io.github.hectorvent.floci.core.common.XmlBuilder; import io.github.hectorvent.floci.services.neptune.model.NeptuneCluster; +import io.github.hectorvent.floci.services.neptune.model.NeptuneClusterSettings; import io.github.hectorvent.floci.services.neptune.model.NeptuneInstance; +import io.github.hectorvent.floci.services.neptune.model.NeptuneInstanceSettings; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; +import java.util.Set; @ApplicationScoped public class NeptuneQueryHandler { @@ -38,10 +48,16 @@ public class NeptuneQueryHandler { case "DescribeDBClusters" -> handleDescribeDbClusters(params); case "DeleteDBCluster" -> handleDeleteDbCluster(params); case "ModifyDBCluster" -> handleModifyDbCluster(params); + case "AddRoleToDBCluster" -> handleAddRoleToDbCluster(params); + case "RemoveRoleFromDBCluster" -> handleRemoveRoleFromDbCluster(params); + case "DescribeGlobalClusters" -> handleDescribeGlobalClusters(params); case "CreateDBInstance" -> handleCreateDbInstance(params); case "DescribeDBInstances"-> handleDescribeDbInstances(params); case "DeleteDBInstance" -> handleDeleteDbInstance(params); case "ModifyDBInstance" -> handleModifyDbInstance(params); + case "ListTagsForResource" -> handleListTagsForResource(params); + case "AddTagsToResource" -> handleAddTagsToResource(params); + case "RemoveTagsFromResource" -> handleRemoveTagsFromResource(params); default -> AwsQueryResponse.error("UnsupportedOperation", "Operation " + action + " is not supported by Neptune.", AwsNamespaces.RDS, 400); }; @@ -64,7 +80,8 @@ public class NeptuneQueryHandler { String engineVersion = params.getFirst("EngineVersion"); boolean iamEnabled = "true".equalsIgnoreCase(params.getFirst("EnableIAMDatabaseAuthentication")); - NeptuneCluster cluster = service.createDbCluster(id, engineVersion, iamEnabled); + NeptuneCluster cluster = service.createDbCluster(id, engineVersion, iamEnabled, + clusterSettings(params, true), parseTags(params)); return Response.ok(AwsQueryResponse.envelope("CreateDBCluster", AwsNamespaces.RDS, clusterXml(cluster))).build(); } @@ -143,11 +160,59 @@ public class NeptuneQueryHandler { String iamStr = params.getFirst("EnableIAMDatabaseAuthentication"); Boolean iamEnabled = iamStr != null ? Boolean.parseBoolean(iamStr) : null; - NeptuneCluster cluster = service.modifyDbCluster(id, engineVersion, iamEnabled); + NeptuneCluster cluster = service.modifyDbCluster(id, engineVersion, iamEnabled, + clusterSettings(params, false)); return Response.ok(AwsQueryResponse.envelope("ModifyDBCluster", AwsNamespaces.RDS, clusterXml(cluster))).build(); } + private Response handleAddRoleToDbCluster(MultivaluedMap params) { + String id = params.getFirst("DBClusterIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400); + } + service.addRoleToDbCluster(id, params.getFirst("RoleArn")); + return Response.ok(AwsQueryResponse.envelopeNoResult("AddRoleToDBCluster", AwsNamespaces.RDS)).build(); + } + + private Response handleRemoveRoleFromDbCluster(MultivaluedMap params) { + String id = params.getFirst("DBClusterIdentifier"); + if (id == null || id.isBlank()) { + return AwsQueryResponse.error("InvalidParameterValue", + "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400); + } + service.removeRoleFromDbCluster(id, params.getFirst("RoleArn")); + return Response.ok(AwsQueryResponse.envelopeNoResult("RemoveRoleFromDBCluster", AwsNamespaces.RDS)).build(); + } + + private Response handleDescribeGlobalClusters(MultivaluedMap params) { + String maxRecords = params.getFirst("MaxRecords"); + if (maxRecords != null && !maxRecords.isBlank()) { + int max = -1; + try { + max = Integer.parseInt(maxRecords.trim()); + } catch (NumberFormatException e) { + LOG.debugv("Non-numeric MaxRecords {0} on DescribeGlobalClusters", maxRecords); + } + if (max < 20 || max > 100) { + throw new AwsException("InvalidParameterValue", + "Invalid value " + maxRecords + " for MaxRecords. Must be between 20 and 100", 400); + } + } + String identifier = params.getFirst("GlobalClusterIdentifier"); + if (identifier != null && !identifier.isBlank()) { + throw new AwsException("GlobalClusterNotFoundFault", + "Global cluster '" + identifier + "' not found", 404); + } + String marker = params.getFirst("Marker"); + if (marker != null && !marker.isBlank()) { + throw new AwsException("InvalidParameterValue", "The request token is invalid.", 400); + } + XmlBuilder xml = new XmlBuilder().start("GlobalClusters").end("GlobalClusters"); + return Response.ok(AwsQueryResponse.envelope("DescribeGlobalClusters", AwsNamespaces.RDS, xml.build())).build(); + } + // ── Instances ───────────────────────────────────────────────────────────── private Response handleCreateDbInstance(MultivaluedMap params) { @@ -166,7 +231,7 @@ public class NeptuneQueryHandler { boolean iamEnabled = "true".equalsIgnoreCase(params.getFirst("EnableIAMDatabaseAuthentication")); NeptuneInstance instance = service.createDbInstance(id, dbClusterIdentifier, - dbInstanceClass, engineVersion, iamEnabled); + dbInstanceClass, engineVersion, iamEnabled, instanceSettings(params, true), parseTags(params)); return Response.ok(AwsQueryResponse.envelope("CreateDBInstance", AwsNamespaces.RDS, instanceXml(instance))).build(); } @@ -217,11 +282,144 @@ public class NeptuneQueryHandler { String iamStr = params.getFirst("EnableIAMDatabaseAuthentication"); Boolean iamEnabled = iamStr != null ? Boolean.parseBoolean(iamStr) : null; - NeptuneInstance instance = service.modifyDbInstance(id, dbInstanceClass, iamEnabled); + NeptuneInstance instance = service.modifyDbInstance(id, dbInstanceClass, iamEnabled, + instanceSettings(params, false)); return Response.ok(AwsQueryResponse.envelope("ModifyDBInstance", AwsNamespaces.RDS, instanceXml(instance))).build(); } + // ── Tags ────────────────────────────────────────────────────────────────── + + private Response handleListTagsForResource(MultivaluedMap params) { + Map tags = service.listTagsForResource(params.getFirst("ResourceName")); + XmlBuilder xml = new XmlBuilder().start("TagList"); + tags.forEach((key, value) -> xml.start("Tag").elem("Key", key).elem("Value", value).end("Tag")); + xml.end("TagList"); + return Response.ok(AwsQueryResponse.envelope("ListTagsForResource", AwsNamespaces.RDS, xml.build())).build(); + } + + private Response handleAddTagsToResource(MultivaluedMap params) { + service.addTagsToResource(params.getFirst("ResourceName"), parseTags(params)); + return Response.ok(AwsQueryResponse.envelopeNoResult("AddTagsToResource", AwsNamespaces.RDS)).build(); + } + + private Response handleRemoveTagsFromResource(MultivaluedMap params) { + service.removeTagsFromResource(params.getFirst("ResourceName"), tagKeys(params)); + return Response.ok(AwsQueryResponse.envelopeNoResult("RemoveTagsFromResource", AwsNamespaces.RDS)).build(); + } + + // ── Request parsing ─────────────────────────────────────────────────────── + + private static NeptuneClusterSettings clusterSettings(MultivaluedMap params, boolean create) { + return new NeptuneClusterSettings( + create ? listParam(params, "AvailabilityZones", "AvailabilityZone") : null, + create ? optionalInt(params.getFirst("Port")) : null, + optionalInt(params.getFirst("BackupRetentionPeriod")), + params.getFirst("PreferredBackupWindow"), + params.getFirst("PreferredMaintenanceWindow"), + create ? params.getFirst("DBSubnetGroupName") : null, + params.getFirst("DBClusterParameterGroupName"), + listParam(params, "VpcSecurityGroupIds", "VpcSecurityGroupId"), + create ? optionalBoolean(params.getFirst("StorageEncrypted")) : null, + create ? params.getFirst("KmsKeyId") : null, + params.getFirst("StorageType"), + optionalBoolean(params.getFirst("DeletionProtection")), + optionalBoolean(params.getFirst("CopyTagsToSnapshot")), + create ? listParam(params, "EnableCloudwatchLogsExports", "member") + : listParam(params, "CloudwatchLogsExportConfiguration.EnableLogTypes", "member"), + create ? null : listParam(params, "CloudwatchLogsExportConfiguration.DisableLogTypes", "member"), + create ? params.getFirst("ReplicationSourceIdentifier") : null, + optionalDouble(params.getFirst("ServerlessV2ScalingConfiguration.MinCapacity")), + optionalDouble(params.getFirst("ServerlessV2ScalingConfiguration.MaxCapacity"))); + } + + private static NeptuneInstanceSettings instanceSettings(MultivaluedMap params, boolean create) { + return new NeptuneInstanceSettings( + create ? params.getFirst("AvailabilityZone") : null, + optionalBoolean(params.getFirst("AutoMinorVersionUpgrade")), + optionalInt(params.getFirst("PromotionTier")), + create ? optionalBoolean(params.getFirst("PubliclyAccessible")) : null, + params.getFirst("DBParameterGroupName"), + create ? params.getFirst("DBSubnetGroupName") : null, + params.getFirst("PreferredBackupWindow"), + params.getFirst("PreferredMaintenanceWindow")); + } + + private static List listParam(MultivaluedMap params, String name, String memberName) { + Set prefixes = new LinkedHashSet<>(List.of(name + "." + memberName + ".", name + ".member.")); + for (String prefix : prefixes) { + List values = new ArrayList<>(); + for (int i = 1; ; i++) { + String value = params.getFirst(prefix + i); + if (value == null) { + break; + } + if (!value.isBlank()) { + values.add(value); + } + } + if (!values.isEmpty()) { + return values; + } + } + return params.containsKey(name) ? new ArrayList<>() : null; + } + + private static Map parseTags(MultivaluedMap params) { + Map tags = new LinkedHashMap<>(); + for (String prefix : List.of("Tags.Tag", "Tags.member", "Tag")) { + for (int i = 1; ; i++) { + String key = params.getFirst(prefix + "." + i + ".Key"); + if (key == null) { + break; + } + String value = params.getFirst(prefix + "." + i + ".Value"); + tags.put(key, value == null ? "" : value); + } + } + return tags; + } + + private static List tagKeys(MultivaluedMap params) { + List keys = new ArrayList<>(); + for (String prefix : List.of("TagKeys.member", "TagKeys.TagKey", "TagKeys")) { + for (int i = 1; ; i++) { + String key = params.getFirst(prefix + "." + i); + if (key == null) { + break; + } + keys.add(key); + } + } + return keys; + } + + private static Boolean optionalBoolean(String value) { + return value == null ? null : !"false".equalsIgnoreCase(value.trim()); + } + + private static Integer optionalInt(String value) { + if (value == null || value.isBlank()) { + return null; + } + try { + return Integer.parseInt(value.trim()); + } catch (NumberFormatException e) { + throw new AwsException("InvalidParameterValue", "Value " + value + " is not a valid integer.", 400); + } + } + + private static Double optionalDouble(String value) { + if (value == null || value.isBlank()) { + return null; + } + try { + return Double.parseDouble(value.trim()); + } catch (NumberFormatException e) { + throw new AwsException("InvalidParameterValue", "Value " + value + " is not a valid number.", 400); + } + } + // ── XML builders ────────────────────────────────────────────────────────── private String clusterXml(NeptuneCluster c) { @@ -239,17 +437,72 @@ public class NeptuneQueryHandler { .elem("Port", c.getPort()) .elem("IAMDatabaseAuthenticationEnabled", c.isIamDatabaseAuthenticationEnabled()) .elem("MultiAZ", false) - .elem("StorageEncrypted", true) - .elem("AvailabilityZone", config.defaultAvailabilityZone()) + .elem("StorageEncrypted", c.isStorageEncrypted()) + .elem("KmsKeyId", c.getKmsKeyId()) + .elem("StorageType", c.getStorageType()) + .elem("DBSubnetGroup", c.getDbSubnetGroupName() != null ? c.getDbSubnetGroupName() : "default") + .elem("DBClusterParameterGroup", c.getDbClusterParameterGroupName() != null + ? c.getDbClusterParameterGroupName() + : "default." + NeptuneService.parameterGroupFamily(c.getEngineVersion())) + .elem("BackupRetentionPeriod", c.getBackupRetentionPeriod()) + .elem("PreferredBackupWindow", c.getPreferredBackupWindow() != null + ? c.getPreferredBackupWindow() : BackupWindows.DEFAULT_BACKUP_WINDOW) + .elem("PreferredMaintenanceWindow", c.getPreferredMaintenanceWindow() != null + ? c.getPreferredMaintenanceWindow() : BackupWindows.DEFAULT_MAINTENANCE_WINDOW) + .elem("DeletionProtection", c.isDeletionProtection()) + .elem("CopyTagsToSnapshot", c.isCopyTagsToSnapshot()) + .elem("ReplicationSourceIdentifier", c.getReplicationSourceIdentifier()) .elem("DbClusterResourceId", c.getDbClusterResourceId()) - .elem("DBClusterArn", c.getDbClusterArn()) - .start("DBClusterMembers"); - if (c.getDbClusterMembers() != null) { - for (String memberId : c.getDbClusterMembers()) { - xml.start("member") + .elem("DBClusterArn", c.getDbClusterArn()); + if (c.getCreatedAt() != null) { + xml.elem("ClusterCreateTime", + DateTimeFormatter.ISO_INSTANT.format(c.getCreatedAt().truncatedTo(ChronoUnit.MILLIS))); + } + xml.start("AvailabilityZones"); + List zones = c.getAvailabilityZones(); + if (zones.isEmpty()) { + xml.elem("AvailabilityZone", config.defaultAvailabilityZone()); + } else { + zones.forEach(zone -> xml.elem("AvailabilityZone", zone)); + } + xml.end("AvailabilityZones") + .start("EnabledCloudwatchLogsExports"); + c.getEnabledCloudwatchLogsExports().forEach(logType -> xml.elem("member", logType)); + xml.end("EnabledCloudwatchLogsExports") + .start("AssociatedRoles"); + for (String roleArn : c.getAssociatedRoleArns()) { + xml.start("DBClusterRole") + .elem("RoleArn", roleArn) + .elem("Status", "ACTIVE") + .end("DBClusterRole"); + } + xml.end("AssociatedRoles") + .start("VpcSecurityGroups"); + for (String groupId : c.getVpcSecurityGroupIds()) { + xml.start("VpcSecurityGroupMembership") + .elem("VpcSecurityGroupId", groupId) + .elem("Status", "active") + .end("VpcSecurityGroupMembership"); + } + xml.end("VpcSecurityGroups"); + if (c.getServerlessV2MinCapacity() != null || c.getServerlessV2MaxCapacity() != null) { + xml.start("ServerlessV2ScalingConfiguration"); + if (c.getServerlessV2MinCapacity() != null) { + xml.elem("MinCapacity", String.valueOf(c.getServerlessV2MinCapacity())); + } + if (c.getServerlessV2MaxCapacity() != null) { + xml.elem("MaxCapacity", String.valueOf(c.getServerlessV2MaxCapacity())); + } + xml.end("ServerlessV2ScalingConfiguration"); + } + xml.start("DBClusterMembers"); + List members = c.getDbClusterMembers(); + if (members != null) { + for (String memberId : members) { + xml.start("DBClusterMember") .elem("DBInstanceIdentifier", memberId) - .elem("IsClusterWriter", true) - .end("member"); + .elem("IsClusterWriter", memberId.equals(members.get(0))) + .end("DBClusterMember"); } } xml.end("DBClusterMembers"); @@ -261,7 +514,16 @@ public class NeptuneQueryHandler { } private String instanceInnerXml(NeptuneInstance i) { - return new XmlBuilder() + NeptuneCluster cluster = service.findDbCluster(i.getDbClusterIdentifier()).orElse(null); + String backupWindow = i.getPreferredBackupWindow() != null ? i.getPreferredBackupWindow() + : cluster != null && cluster.getPreferredBackupWindow() != null ? cluster.getPreferredBackupWindow() + : BackupWindows.DEFAULT_BACKUP_WINDOW; + String subnetGroup = i.getDbSubnetGroupName() != null ? i.getDbSubnetGroupName() + : cluster != null && cluster.getDbSubnetGroupName() != null ? cluster.getDbSubnetGroupName() + : "default"; + String parameterGroup = i.getDbParameterGroupName() != null ? i.getDbParameterGroupName() + : "default." + NeptuneService.parameterGroupFamily(i.getEngineVersion()); + XmlBuilder xml = new XmlBuilder() .elem("DBInstanceIdentifier", i.getDbInstanceIdentifier()) .elem("DBClusterIdentifier", i.getDbClusterIdentifier()) .elem("DBInstanceClass", i.getDbInstanceClass()) @@ -274,11 +536,34 @@ public class NeptuneQueryHandler { .end("Endpoint") .elem("IAMDatabaseAuthenticationEnabled", i.isIamDatabaseAuthenticationEnabled()) .elem("MultiAZ", false) - .elem("StorageEncrypted", true) - .elem("AvailabilityZone", config.defaultAvailabilityZone()) + .elem("AutoMinorVersionUpgrade", i.isAutoMinorVersionUpgrade()) + .elem("PromotionTier", i.getPromotionTier()) + .elem("PubliclyAccessible", i.isPubliclyAccessible()) + .elem("StorageEncrypted", cluster != null && cluster.isStorageEncrypted()) + .elem("KmsKeyId", cluster != null ? cluster.getKmsKeyId() : null) + .elem("StorageType", cluster != null ? cluster.getStorageType() : null) + .elem("AvailabilityZone", i.getAvailabilityZone() != null + ? i.getAvailabilityZone() : config.defaultAvailabilityZone()) + .elem("PreferredBackupWindow", backupWindow) + .elem("PreferredMaintenanceWindow", i.getPreferredMaintenanceWindow() != null + ? i.getPreferredMaintenanceWindow() : BackupWindows.DEFAULT_MAINTENANCE_WINDOW) .elem("DbiResourceId", i.getDbiResourceId()) - .elem("DBInstanceArn", i.getDbInstanceArn()) - .build(); + .elem("DBInstanceArn", i.getDbInstanceArn()); + if (i.getCreatedAt() != null) { + xml.elem("InstanceCreateTime", + DateTimeFormatter.ISO_INSTANT.format(i.getCreatedAt().truncatedTo(ChronoUnit.MILLIS))); + } + xml.start("DBSubnetGroup") + .elem("DBSubnetGroupName", subnetGroup) + .elem("SubnetGroupStatus", "Complete") + .end("DBSubnetGroup") + .start("DBParameterGroups") + .start("DBParameterGroup") + .elem("DBParameterGroupName", parameterGroup) + .elem("ParameterApplyStatus", "in-sync") + .end("DBParameterGroup") + .end("DBParameterGroups"); + return xml.build(); } private static String extractFilterValue(MultivaluedMap params, String filterName) { diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneService.java b/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneService.java index 85406e6e0e..a6bf0629f9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneService.java +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/NeptuneService.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.neptune; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.StorageBackend; @@ -9,8 +10,10 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerHandle; import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerManager; import io.github.hectorvent.floci.services.neptune.model.NeptuneCluster; +import io.github.hectorvent.floci.services.neptune.model.NeptuneClusterSettings; import io.github.hectorvent.floci.services.neptune.model.NeptuneDbType; import io.github.hectorvent.floci.services.neptune.model.NeptuneInstance; +import io.github.hectorvent.floci.services.neptune.model.NeptuneInstanceSettings; import io.github.hectorvent.floci.services.neptune.proxy.NeptuneProxyManager; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -19,10 +22,14 @@ import org.jboss.logging.Logger; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; @ApplicationScoped public class NeptuneService { @@ -57,13 +64,19 @@ public class NeptuneService { // ── Clusters ────────────────────────────────────────────────────────────── public NeptuneCluster createDbCluster(String id, String engineVersion, boolean iamEnabled) { + return createDbCluster(id, engineVersion, iamEnabled, NeptuneClusterSettings.defaults(), Map.of()); + } + + public NeptuneCluster createDbCluster(String id, String engineVersion, boolean iamEnabled, + NeptuneClusterSettings settings, Map tags) { + settings.validate(); if (clusters.get(id).isPresent()) { throw new AwsException("DBClusterAlreadyExistsFault", "Neptune cluster " + id + " already exists.", 400); } // Open the try immediately after reserving the port so config reads below can't leak it. - int proxyPort = allocateProxyPort(); + int proxyPort = allocateProxyPort(settings.port()); NeptuneContainerHandle handle = null; boolean provisioned = false; try { @@ -104,6 +117,10 @@ public class NeptuneService { cluster.setCreatedAt(Instant.now()); cluster.setDbClusterMembers(new ArrayList<>()); cluster.setProxyPort(proxyPort); + settings.applyTo(cluster); + if (tags != null && !tags.isEmpty()) { + cluster.setTags(tags); + } if (handle != null) { cluster.setContainerId(handle.getContainerId()); @@ -182,6 +199,16 @@ public class NeptuneService { return instances.get(id).isPresent(); } + public boolean hasResourceWithArn(String arn) { + if (arn == null || !arn.startsWith("arn:")) { + return false; + } + return clusters.scan(k -> true).stream() + .anyMatch(c -> arn.equalsIgnoreCase(c.getDbClusterArn())) + || instances.scan(k -> true).stream() + .anyMatch(i -> arn.equalsIgnoreCase(i.getDbInstanceArn())); + } + public Collection listDbClusters(String filterId) { if (filterId != null && !filterId.isBlank()) { // The db-cluster-id filter accepts ARNs as well as identifiers. Match the @@ -199,6 +226,12 @@ public class NeptuneService { } public NeptuneCluster modifyDbCluster(String id, String engineVersion, Boolean iamEnabled) { + return modifyDbCluster(id, engineVersion, iamEnabled, NeptuneClusterSettings.unchanged()); + } + + public NeptuneCluster modifyDbCluster(String id, String engineVersion, Boolean iamEnabled, + NeptuneClusterSettings settings) { + settings.validate(); NeptuneCluster cluster = getDbCluster(id); if (engineVersion != null && !engineVersion.isBlank()) { cluster.setEngineVersion(engineVersion); @@ -206,6 +239,7 @@ public class NeptuneService { if (iamEnabled != null) { cluster.setIamDatabaseAuthenticationEnabled(iamEnabled); } + settings.applyTo(cluster); clusters.put(id, cluster); LOG.infov("Neptune cluster {0} modified", id); return cluster; @@ -216,6 +250,10 @@ public class NeptuneService { new AwsException("DBClusterNotFoundFault", "Neptune cluster " + id + " not found.", 404)); + if (cluster.isDeletionProtection()) { + throw new AwsException("InvalidParameterCombination", + "Cannot delete protected Cluster, please disable deletion protection and try again.", 400); + } if (cluster.getDbClusterMembers() != null && !cluster.getDbClusterMembers().isEmpty()) { throw new AwsException("InvalidDBClusterStateFault", "Cannot delete Neptune cluster " + id + " — it still has DB instances.", 400); @@ -237,11 +275,69 @@ public class NeptuneService { LOG.infov("Neptune cluster {0} deleted", id); } + public NeptuneCluster addRoleToDbCluster(String id, String roleArn) { + if (roleArn == null || roleArn.isBlank()) { + throw new AwsException("InvalidParameterValue", "RoleArn is required.", 400); + } + NeptuneCluster cluster = getDbCluster(id); + if (cluster.getAssociatedRoleArns().contains(roleArn)) { + throw new AwsException("DBClusterRoleAlreadyExists", + "Role ARN " + roleArn + " is already associated with Neptune cluster " + id + ".", 400); + } + cluster.getAssociatedRoleArns().add(roleArn); + clusters.put(id, cluster); + LOG.infov("Role {0} added to Neptune cluster {1}", roleArn, id); + return cluster; + } + + public NeptuneCluster removeRoleFromDbCluster(String id, String roleArn) { + NeptuneCluster cluster = getDbCluster(id); + if (roleArn == null || !cluster.getAssociatedRoleArns().remove(roleArn)) { + throw new AwsException("DBClusterRoleNotFound", + "Role ARN " + roleArn + " is not associated with Neptune cluster " + id + ".", 404); + } + clusters.put(id, cluster); + LOG.infov("Role {0} removed from Neptune cluster {1}", roleArn, id); + return cluster; + } + + public static String parameterGroupFamily(String engineVersion) { + String version = engineVersion == null || engineVersion.isBlank() ? ENGINE_VERSION_DEFAULT : engineVersion.trim(); + String[] parts = version.split("\\."); + int major; + int minor; + try { + major = Integer.parseInt(parts[0]); + minor = parts.length > 1 ? Integer.parseInt(parts[1]) : 0; + } catch (NumberFormatException e) { + return parameterGroupFamily(ENGINE_VERSION_DEFAULT); + } + if (major == 1 && minor < 2) { + return "neptune1"; + } + return "neptune" + major + "." + minor; + } + // ── Instances ───────────────────────────────────────────────────────────── public NeptuneInstance createDbInstance(String id, String dbClusterIdentifier, String dbInstanceClass, String engineVersion, boolean iamEnabled) { + return createDbInstance(id, dbClusterIdentifier, dbInstanceClass, engineVersion, iamEnabled, Map.of()); + } + + public NeptuneInstance createDbInstance(String id, String dbClusterIdentifier, + String dbInstanceClass, String engineVersion, + boolean iamEnabled, Map tags) { + return createDbInstance(id, dbClusterIdentifier, dbInstanceClass, engineVersion, iamEnabled, + NeptuneInstanceSettings.defaults(), tags); + } + + public NeptuneInstance createDbInstance(String id, String dbClusterIdentifier, + String dbInstanceClass, String engineVersion, + boolean iamEnabled, NeptuneInstanceSettings settings, + Map tags) { + settings.validate(); if (instances.get(id).isPresent()) { throw new AwsException("DBInstanceAlreadyExists", "Neptune instance " + id + " already exists.", 400); @@ -263,6 +359,10 @@ public class NeptuneService { instance.setDbiResourceId("db-" + UUID.randomUUID().toString() .replace("-", "").substring(0, 24).toUpperCase()); instance.setCreatedAt(Instant.now()); + settings.applyTo(instance); + if (tags != null && !tags.isEmpty()) { + instance.setTags(tags); + } cluster.getDbClusterMembers().add(id); clusters.put(dbClusterIdentifier, cluster); @@ -272,6 +372,10 @@ public class NeptuneService { return instance; } + public Optional findDbCluster(String id) { + return id == null ? Optional.empty() : clusters.get(id); + } + public NeptuneInstance getDbInstance(String id) { return instances.get(id).orElseThrow(() -> new AwsException("DBInstanceNotFound", @@ -293,6 +397,12 @@ public class NeptuneService { } public NeptuneInstance modifyDbInstance(String id, String dbInstanceClass, Boolean iamEnabled) { + return modifyDbInstance(id, dbInstanceClass, iamEnabled, NeptuneInstanceSettings.unchanged()); + } + + public NeptuneInstance modifyDbInstance(String id, String dbInstanceClass, Boolean iamEnabled, + NeptuneInstanceSettings settings) { + settings.validate(); NeptuneInstance instance = getDbInstance(id); if (dbInstanceClass != null && !dbInstanceClass.isBlank()) { instance.setDbInstanceClass(dbInstanceClass); @@ -300,6 +410,7 @@ public class NeptuneService { if (iamEnabled != null) { instance.setIamDatabaseAuthenticationEnabled(iamEnabled); } + settings.applyTo(instance); instances.put(id, instance); LOG.infov("Neptune instance {0} modified", id); return instance; @@ -321,15 +432,91 @@ public class NeptuneService { LOG.infov("Neptune instance {0} deleted", id); } + // ── Tags ────────────────────────────────────────────────────────────────── + + private record TagTarget(Map tags, Consumer> save) {} + + public Map listTagsForResource(String resourceName) { + return Collections.unmodifiableMap(new LinkedHashMap<>(resolveTagTarget(resourceName).tags())); + } + + public synchronized void addTagsToResource(String resourceName, Map tags) { + updateTags(resourceName, current -> current.putAll(tags)); + } + + public synchronized void removeTagsFromResource(String resourceName, Collection tagKeys) { + updateTags(resourceName, current -> tagKeys.forEach(current::remove)); + } + + private void updateTags(String resourceName, Consumer> change) { + TagTarget target = resolveTagTarget(resourceName); + Map updated = new LinkedHashMap<>(target.tags()); + change.accept(updated); + target.save().accept(updated); + } + + private TagTarget resolveTagTarget(String resourceName) { + if (resourceName == null || resourceName.isBlank()) { + throw new AwsException("InvalidParameterValue", "ResourceName is required.", 400); + } + AwsArnUtils.Arn arn; + try { + arn = AwsArnUtils.parse(resourceName); + } catch (IllegalArgumentException malformed) { + throw new AwsException("InvalidParameterValue", "Invalid resource name: " + resourceName, 400); + } + String resource = arn.resource(); + int separator = resource.indexOf(':'); + if (separator < 0) { + throw new AwsException("InvalidParameterValue", "Invalid resource name: " + resourceName, 400); + } + String type = resource.substring(0, separator); + String id = resource.substring(separator + 1); + return switch (type) { + case "cluster" -> { + NeptuneCluster cluster = clusters.scan(k -> true).stream() + .filter(c -> resourceName.equalsIgnoreCase(c.getDbClusterArn())) + .findFirst() + .orElseThrow(() -> new AwsException("DBClusterNotFoundFault", + "Neptune cluster " + id + " not found.", 404)); + yield new TagTarget(cluster.getTags(), updated -> { + cluster.setTags(updated); + clusters.put(cluster.getDbClusterIdentifier(), cluster); + }); + } + case "db" -> { + NeptuneInstance instance = instances.scan(k -> true).stream() + .filter(i -> resourceName.equalsIgnoreCase(i.getDbInstanceArn())) + .findFirst() + .orElseThrow(() -> new AwsException("DBInstanceNotFound", + "Neptune instance " + id + " not found.", 404)); + yield new TagTarget(instance.getTags(), updated -> { + instance.setTags(updated); + instances.put(instance.getDbInstanceIdentifier(), instance); + }); + } + default -> throw new AwsException("InvalidParameterValue", + "Tagging for resource type '" + type + "' is not supported by Neptune in Floci: " + resourceName, 400); + }; + } + // ── Helpers ─────────────────────────────────────────────────────────────── private String resolveEndpointHost() { return config.hostname().orElse("localhost"); } - private int allocateProxyPort() { + private int allocateProxyPort(Integer requested) { int base = config.services().neptune().proxyBasePort(); int max = config.services().neptune().proxyMaxPort(); + if (requested != null && requested >= base && requested <= max && usedPorts.add(requested)) { + return requested; + } + if (requested != null) { + LOG.infov("Requested Neptune port {0} is outside the proxy range {1}-{2} or already in use; " + + "allocating the next free proxy port instead", + String.valueOf(requested), String.valueOf(base), String.valueOf(max)); + } for (int port = base; port <= max; port++) { if (usedPorts.add(port)) { return port; diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneCluster.java b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneCluster.java index 3ac251ef65..679b933ac0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneCluster.java +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneCluster.java @@ -4,7 +4,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; @RegisterForReflection public class NeptuneCluster { @@ -19,6 +21,24 @@ public class NeptuneCluster { private String dbClusterArn; private String dbClusterResourceId; private List dbClusterMembers = new ArrayList<>(); + private List availabilityZones = new ArrayList<>(); + private int backupRetentionPeriod = 1; + private String preferredBackupWindow; + private String preferredMaintenanceWindow; + private String dbSubnetGroupName; + private String dbClusterParameterGroupName; + private List vpcSecurityGroupIds = new ArrayList<>(); + private boolean storageEncrypted; + private String kmsKeyId; + private String storageType; + private boolean deletionProtection; + private boolean copyTagsToSnapshot; + private List enabledCloudwatchLogsExports = new ArrayList<>(); + private List associatedRoleArns = new ArrayList<>(); + private String replicationSourceIdentifier; + private Double serverlessV2MinCapacity; + private Double serverlessV2MaxCapacity; + private Map tags = new LinkedHashMap<>(); private Instant createdAt; // Docker / proxy runtime fields — persisted so cleanup works across restarts @@ -63,6 +83,77 @@ public class NeptuneCluster { this.dbClusterMembers = dbClusterMembers != null ? new ArrayList<>(dbClusterMembers) : new ArrayList<>(); } + public List getAvailabilityZones() { return availabilityZones; } + public void setAvailabilityZones(List availabilityZones) { + this.availabilityZones = availabilityZones != null ? new ArrayList<>(availabilityZones) : new ArrayList<>(); + } + + public int getBackupRetentionPeriod() { return backupRetentionPeriod; } + public void setBackupRetentionPeriod(int backupRetentionPeriod) { this.backupRetentionPeriod = backupRetentionPeriod; } + + public String getPreferredBackupWindow() { return preferredBackupWindow; } + public void setPreferredBackupWindow(String preferredBackupWindow) { this.preferredBackupWindow = preferredBackupWindow; } + + public String getPreferredMaintenanceWindow() { return preferredMaintenanceWindow; } + public void setPreferredMaintenanceWindow(String preferredMaintenanceWindow) { + this.preferredMaintenanceWindow = preferredMaintenanceWindow; + } + + public String getDbSubnetGroupName() { return dbSubnetGroupName; } + public void setDbSubnetGroupName(String dbSubnetGroupName) { this.dbSubnetGroupName = dbSubnetGroupName; } + + public String getDbClusterParameterGroupName() { return dbClusterParameterGroupName; } + public void setDbClusterParameterGroupName(String dbClusterParameterGroupName) { + this.dbClusterParameterGroupName = dbClusterParameterGroupName; + } + + public List getVpcSecurityGroupIds() { return vpcSecurityGroupIds; } + public void setVpcSecurityGroupIds(List vpcSecurityGroupIds) { + this.vpcSecurityGroupIds = vpcSecurityGroupIds != null ? new ArrayList<>(vpcSecurityGroupIds) : new ArrayList<>(); + } + + public boolean isStorageEncrypted() { return storageEncrypted; } + public void setStorageEncrypted(boolean storageEncrypted) { this.storageEncrypted = storageEncrypted; } + + public String getKmsKeyId() { return kmsKeyId; } + public void setKmsKeyId(String kmsKeyId) { this.kmsKeyId = kmsKeyId; } + + public String getStorageType() { return storageType; } + public void setStorageType(String storageType) { this.storageType = storageType; } + + public boolean isDeletionProtection() { return deletionProtection; } + public void setDeletionProtection(boolean deletionProtection) { this.deletionProtection = deletionProtection; } + + public boolean isCopyTagsToSnapshot() { return copyTagsToSnapshot; } + public void setCopyTagsToSnapshot(boolean copyTagsToSnapshot) { this.copyTagsToSnapshot = copyTagsToSnapshot; } + + public List getEnabledCloudwatchLogsExports() { return enabledCloudwatchLogsExports; } + public void setEnabledCloudwatchLogsExports(List enabledCloudwatchLogsExports) { + this.enabledCloudwatchLogsExports = enabledCloudwatchLogsExports != null + ? new ArrayList<>(enabledCloudwatchLogsExports) : new ArrayList<>(); + } + + public List getAssociatedRoleArns() { return associatedRoleArns; } + public void setAssociatedRoleArns(List associatedRoleArns) { + this.associatedRoleArns = associatedRoleArns != null ? new ArrayList<>(associatedRoleArns) : new ArrayList<>(); + } + + public String getReplicationSourceIdentifier() { return replicationSourceIdentifier; } + public void setReplicationSourceIdentifier(String replicationSourceIdentifier) { + this.replicationSourceIdentifier = replicationSourceIdentifier; + } + + public Double getServerlessV2MinCapacity() { return serverlessV2MinCapacity; } + public void setServerlessV2MinCapacity(Double serverlessV2MinCapacity) { this.serverlessV2MinCapacity = serverlessV2MinCapacity; } + + public Double getServerlessV2MaxCapacity() { return serverlessV2MaxCapacity; } + public void setServerlessV2MaxCapacity(Double serverlessV2MaxCapacity) { this.serverlessV2MaxCapacity = serverlessV2MaxCapacity; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { + this.tags = tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>(); + } + public Instant getCreatedAt() { return createdAt; } public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneClusterSettings.java b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneClusterSettings.java new file mode 100644 index 0000000000..2273400920 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneClusterSettings.java @@ -0,0 +1,149 @@ +package io.github.hectorvent.floci.services.neptune.model; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.BackupWindows; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * The settings of a Neptune cluster as a request carries them: a null member is one the request + * left out, which means the AWS default on create and no change on modify. + */ +@RegisterForReflection +public record NeptuneClusterSettings(List availabilityZones, + Integer port, + Integer backupRetentionPeriod, + String preferredBackupWindow, + String preferredMaintenanceWindow, + String dbSubnetGroupName, + String dbClusterParameterGroupName, + List vpcSecurityGroupIds, + Boolean storageEncrypted, + String kmsKeyId, + String storageType, + Boolean deletionProtection, + Boolean copyTagsToSnapshot, + List enableLogTypes, + List disableLogTypes, + String replicationSourceIdentifier, + Double serverlessV2MinCapacity, + Double serverlessV2MaxCapacity) { + + public static final Set STORAGE_TYPES = Set.of("standard", "iopt1"); + public static final Set LOG_TYPES = Set.of("audit", "slowquery"); + + public static NeptuneClusterSettings defaults() { + return new NeptuneClusterSettings(null, null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null); + } + + public static NeptuneClusterSettings unchanged() { + return defaults(); + } + + public void validate() { + if (kmsKeyId != null && !kmsKeyId.isBlank() && !Boolean.TRUE.equals(storageEncrypted)) { + throw new AwsException("InvalidParameterCombination", + "You cannot specify KMS key for unencrypted clusters.", 400); + } + if (port != null && (port < 1150 || port > 65535)) { + throw new AwsException("InvalidParameterValue", + "Invalid port: " + port + ". Port must be between 1150 and 65535.", 400); + } + if (backupRetentionPeriod != null && (backupRetentionPeriod < 1 || backupRetentionPeriod > 35)) { + throw new AwsException("InvalidParameterValue", "Invalid backup retention period: " + + backupRetentionPeriod + ". Retention period must be between 1 and 35.", 400); + } + if (preferredBackupWindow != null) { + BackupWindows.parseBackupWindow(preferredBackupWindow); + } + if (preferredMaintenanceWindow != null) { + BackupWindows.parseMaintenanceWindow(preferredMaintenanceWindow); + } + if (storageType != null && !storageType.isBlank() && !STORAGE_TYPES.contains(storageType)) { + throw new AwsException("InvalidParameterValue", + "Invalid storage type: " + storageType + ". Valid values are standard and iopt1.", 400); + } + if (serverlessV2MinCapacity != null && serverlessV2MaxCapacity != null + && serverlessV2MinCapacity > serverlessV2MaxCapacity) { + throw new AwsException("InvalidParameterCombination", + "ServerlessV2ScalingConfiguration MinCapacity must not exceed MaxCapacity.", 400); + } + requireKnownLogTypes(enableLogTypes); + requireKnownLogTypes(disableLogTypes); + } + + private static void requireKnownLogTypes(List logTypes) { + if (logTypes == null) { + return; + } + for (String logType : logTypes) { + if (!LOG_TYPES.contains(logType)) { + throw new AwsException("InvalidParameterValue", + "Invalid log type: " + logType + ". Valid values are audit and slowquery.", 400); + } + } + } + + public void applyTo(NeptuneCluster cluster) { + if (availabilityZones != null && !availabilityZones.isEmpty()) { + cluster.setAvailabilityZones(availabilityZones); + } + if (backupRetentionPeriod != null) { + cluster.setBackupRetentionPeriod(backupRetentionPeriod); + } + if (preferredBackupWindow != null && !preferredBackupWindow.isBlank()) { + cluster.setPreferredBackupWindow(preferredBackupWindow); + } + if (preferredMaintenanceWindow != null && !preferredMaintenanceWindow.isBlank()) { + cluster.setPreferredMaintenanceWindow(BackupWindows.lowerCase(preferredMaintenanceWindow)); + } + if (dbSubnetGroupName != null && !dbSubnetGroupName.isBlank()) { + cluster.setDbSubnetGroupName(dbSubnetGroupName); + } + if (dbClusterParameterGroupName != null && !dbClusterParameterGroupName.isBlank()) { + cluster.setDbClusterParameterGroupName(dbClusterParameterGroupName); + } + if (vpcSecurityGroupIds != null) { + cluster.setVpcSecurityGroupIds(vpcSecurityGroupIds); + } + if (storageEncrypted != null) { + cluster.setStorageEncrypted(storageEncrypted); + } + if (kmsKeyId != null && !kmsKeyId.isBlank()) { + cluster.setKmsKeyId(kmsKeyId); + } + if (storageType != null && !storageType.isBlank()) { + cluster.setStorageType(storageType); + } + if (deletionProtection != null) { + cluster.setDeletionProtection(deletionProtection); + } + if (copyTagsToSnapshot != null) { + cluster.setCopyTagsToSnapshot(copyTagsToSnapshot); + } + if (enableLogTypes != null || disableLogTypes != null) { + Set logTypes = new LinkedHashSet<>(cluster.getEnabledCloudwatchLogsExports()); + if (disableLogTypes != null) { + logTypes.removeAll(disableLogTypes); + } + if (enableLogTypes != null) { + logTypes.addAll(enableLogTypes); + } + cluster.setEnabledCloudwatchLogsExports(new ArrayList<>(logTypes)); + } + if (replicationSourceIdentifier != null && !replicationSourceIdentifier.isBlank()) { + cluster.setReplicationSourceIdentifier(replicationSourceIdentifier); + } + if (serverlessV2MinCapacity != null) { + cluster.setServerlessV2MinCapacity(serverlessV2MinCapacity); + } + if (serverlessV2MaxCapacity != null) { + cluster.setServerlessV2MaxCapacity(serverlessV2MaxCapacity); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneInstance.java b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneInstance.java index 3fe1c9e0f3..326598d622 100644 --- a/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneInstance.java +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneInstance.java @@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.neptune.model; import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; @RegisterForReflection public class NeptuneInstance { @@ -17,6 +19,15 @@ public class NeptuneInstance { private boolean iamDatabaseAuthenticationEnabled; private String dbInstanceArn; private String dbiResourceId; + private String availabilityZone; + private boolean autoMinorVersionUpgrade = true; + private int promotionTier = 1; + private boolean publiclyAccessible; + private String dbParameterGroupName; + private String dbSubnetGroupName; + private String preferredBackupWindow; + private String preferredMaintenanceWindow; + private Map tags = new LinkedHashMap<>(); private Instant createdAt; public NeptuneInstance() {} @@ -53,6 +64,39 @@ public class NeptuneInstance { public String getDbiResourceId() { return dbiResourceId; } public void setDbiResourceId(String dbiResourceId) { this.dbiResourceId = dbiResourceId; } + public Map getTags() { return tags; } + public void setTags(Map tags) { + this.tags = tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>(); + } + public Instant getCreatedAt() { return createdAt; } public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } + + public String getAvailabilityZone() { return availabilityZone; } + public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; } + + public boolean isAutoMinorVersionUpgrade() { return autoMinorVersionUpgrade; } + public void setAutoMinorVersionUpgrade(boolean autoMinorVersionUpgrade) { + this.autoMinorVersionUpgrade = autoMinorVersionUpgrade; + } + + public int getPromotionTier() { return promotionTier; } + public void setPromotionTier(int promotionTier) { this.promotionTier = promotionTier; } + + public boolean isPubliclyAccessible() { return publiclyAccessible; } + public void setPubliclyAccessible(boolean publiclyAccessible) { this.publiclyAccessible = publiclyAccessible; } + + public String getDbParameterGroupName() { return dbParameterGroupName; } + public void setDbParameterGroupName(String dbParameterGroupName) { this.dbParameterGroupName = dbParameterGroupName; } + + public String getDbSubnetGroupName() { return dbSubnetGroupName; } + public void setDbSubnetGroupName(String dbSubnetGroupName) { this.dbSubnetGroupName = dbSubnetGroupName; } + + public String getPreferredBackupWindow() { return preferredBackupWindow; } + public void setPreferredBackupWindow(String preferredBackupWindow) { this.preferredBackupWindow = preferredBackupWindow; } + + public String getPreferredMaintenanceWindow() { return preferredMaintenanceWindow; } + public void setPreferredMaintenanceWindow(String preferredMaintenanceWindow) { + this.preferredMaintenanceWindow = preferredMaintenanceWindow; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneInstanceSettings.java b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneInstanceSettings.java new file mode 100644 index 0000000000..6dbdd1eefe --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/model/NeptuneInstanceSettings.java @@ -0,0 +1,64 @@ +package io.github.hectorvent.floci.services.neptune.model; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.BackupWindows; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public record NeptuneInstanceSettings(String availabilityZone, + Boolean autoMinorVersionUpgrade, + Integer promotionTier, + Boolean publiclyAccessible, + String dbParameterGroupName, + String dbSubnetGroupName, + String preferredBackupWindow, + String preferredMaintenanceWindow) { + + public static NeptuneInstanceSettings defaults() { + return new NeptuneInstanceSettings(null, null, null, null, null, null, null, null); + } + + public static NeptuneInstanceSettings unchanged() { + return defaults(); + } + + public void validate() { + if (promotionTier != null && (promotionTier < 0 || promotionTier > 15)) { + throw new AwsException("InvalidParameterValue", "Invalid promotion tier: " + promotionTier + + ". Promotion tier must be between 0 and 15.", 400); + } + if (preferredBackupWindow != null && !preferredBackupWindow.isBlank()) { + BackupWindows.parseBackupWindow(preferredBackupWindow); + } + if (preferredMaintenanceWindow != null && !preferredMaintenanceWindow.isBlank()) { + BackupWindows.parseMaintenanceWindow(preferredMaintenanceWindow); + } + } + + public void applyTo(NeptuneInstance instance) { + if (availabilityZone != null && !availabilityZone.isBlank()) { + instance.setAvailabilityZone(availabilityZone); + } + if (autoMinorVersionUpgrade != null) { + instance.setAutoMinorVersionUpgrade(autoMinorVersionUpgrade); + } + if (promotionTier != null) { + instance.setPromotionTier(promotionTier); + } + if (publiclyAccessible != null) { + instance.setPubliclyAccessible(publiclyAccessible); + } + if (dbParameterGroupName != null && !dbParameterGroupName.isBlank()) { + instance.setDbParameterGroupName(dbParameterGroupName); + } + if (dbSubnetGroupName != null && !dbSubnetGroupName.isBlank()) { + instance.setDbSubnetGroupName(dbSubnetGroupName); + } + if (preferredBackupWindow != null && !preferredBackupWindow.isBlank()) { + instance.setPreferredBackupWindow(preferredBackupWindow); + } + if (preferredMaintenanceWindow != null && !preferredMaintenanceWindow.isBlank()) { + instance.setPreferredMaintenanceWindow(BackupWindows.lowerCase(preferredMaintenanceWindow)); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneClusterSettingsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneClusterSettingsIntegrationTest.java new file mode 100644 index 0000000000..613199f1a0 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneClusterSettingsIntegrationTest.java @@ -0,0 +1,306 @@ +package io.github.hectorvent.floci.services.neptune; + +import io.quarkus.test.junit.QuarkusTest; +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 org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class NeptuneClusterSettingsIntegrationTest { + + private static final String FORM = "application/x-www-form-urlencoded"; + private static final String ID = "tf-neptune-settings"; + private static final String INSTANCE_ID = "tf-neptune-settings-db"; + private static final String ARN = "arn:aws:neptune:us-east-1:000000000000:cluster:" + ID; + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/neptune-load"; + + private static RequestSpecification signedAs(String service, String action) { + return given() + .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260903/us-east-1/" + service + + "/aws4_request, SignedHeaders=content-type;host, Signature=test") + .contentType(FORM) + .formParam("Action", action); + } + + private static RequestSpecification rds(String action) { + return signedAs("rds", action); + } + + @Test + @Order(1) + void createEchoesEverySettingTerraformSends() { + rds("CreateDBCluster") + .formParam("DBClusterIdentifier", ID) + .formParam("Engine", "neptune") + .formParam("Port", "8200") + .formParam("StorageEncrypted", "false") + .formParam("DeletionProtection", "true") + .formParam("CopyTagsToSnapshot", "false") + .formParam("BackupRetentionPeriod", "7") + .formParam("AvailabilityZones.AvailabilityZone.1", "us-east-1a") + .formParam("AvailabilityZones.AvailabilityZone.2", "us-east-1b") + .formParam("EnableCloudwatchLogsExports.member.1", "audit") + .formParam("VpcSecurityGroupIds.VpcSecurityGroupId.1", "sg-11111111") + .formParam("PreferredBackupWindow", "03:00-04:00") + .formParam("PreferredMaintenanceWindow", "Sun:05:00-Sun:06:00") + .formParam("ServerlessV2ScalingConfiguration.MinCapacity", "2.5") + .formParam("ServerlessV2ScalingConfiguration.MaxCapacity", "16") + .formParam("Tags.Tag.1.Key", "Name") + .formParam("Tags.Tag.1.Value", ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString("8200")) + .body(containsString("false")) + .body(containsString("true")) + .body(containsString("false")) + .body(containsString("7")) + .body(containsString("us-east-1a" + + "us-east-1b")) + .body(containsString("audit")) + .body(containsString("sg-11111111")) + .body(containsString("03:00-04:00")) + .body(containsString("sun:05:00-sun:06:00")) + .body(containsString("2.5" + + "16.0")) + .body(containsString("default.neptune1.3")) + .body(containsString("default")) + .body(containsString("")) + .body(containsString("" + ARN + "")); + } + + @Test + @Order(2) + void describeOnTheRdsScopeReadsTheSameSettingsBack() { + rds("DescribeDBClusters") + .formParam("DBClusterIdentifier", ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString("8200")) + .body(containsString("false")) + .body(containsString("true")) + .body(containsString("7")) + .body(containsString("us-east-1b")) + .body(containsString("")); + } + + @Test + @Order(3) + void tagsRoundTripThroughTheRdsScopeByNeptuneArn() { + rds("ListTagsForResource") + .formParam("ResourceName", ARN) + .when().post("/") + .then() + .statusCode(200) + .body(containsString("Name" + ID + "")); + + rds("AddTagsToResource") + .formParam("ResourceName", ARN) + .formParam("Tags.Tag.1.Key", "team") + .formParam("Tags.Tag.1.Value", "graph") + .when().post("/") + .then() + .statusCode(200) + .body(containsString("teamgraph")) + .body(not(containsString("Name"))); + } + + @Test + @Order(4) + void tagsForAForeignArnAreNotFound() { + signedAs("neptune", "ListTagsForResource") + .formParam("ResourceName", ARN.replace("us-east-1", "eu-west-1")) + .when().post("/") + .then() + .statusCode(404) + .body(containsString("DBClusterNotFoundFault")); + } + + @Test + @Order(5) + void rolesAreAssociatedAndListedOnTheCluster() { + rds("AddRoleToDBCluster") + .formParam("DBClusterIdentifier", ID) + .formParam("RoleArn", ROLE_ARN) + .when().post("/") + .then() + .statusCode(200) + .body(containsString("" + ROLE_ARN + + "ACTIVE")); + + rds("RemoveRoleFromDBCluster") + .formParam("DBClusterIdentifier", ID) + .formParam("RoleArn", ROLE_ARN) + .when().post("/") + .then() + .statusCode(200); + + rds("RemoveRoleFromDBCluster") + .formParam("DBClusterIdentifier", ID) + .formParam("RoleArn", ROLE_ARN) + .when().post("/") + .then() + .statusCode(404) + .body(containsString("DBClusterRoleNotFound")); + } + + @Test + @Order(6) + void unsignedRoleActionsRouteToNeptune() { + given().contentType(FORM).formParam("Action", "AddRoleToDBCluster") + .formParam("DBClusterIdentifier", ID) + .formParam("RoleArn", ROLE_ARN) + .when().post("/") + .then() + .statusCode(200) + .body(containsString("" + ROLE_ARN + "")); + + given().contentType(FORM).formParam("Action", "RemoveRoleFromDBCluster") + .formParam("DBClusterIdentifier", ID) + .formParam("RoleArn", ROLE_ARN) + .when().post("/") + .then() + .statusCode(200); + } + + @Test + @Order(7) + void describeGlobalClustersIsEmptyOnBothScopes() { + signedAs("neptune", "DescribeGlobalClusters") + .when().post("/") + .then() + .statusCode(200) + .body(containsString("")); + + rds("DescribeGlobalClusters") + .when().post("/") + .then() + .statusCode(200) + .body(containsString("")); + } + + @Test + @Order(8) + void deleteIsRefusedWhileDeletionProtectionIsOn() { + rds("DeleteDBCluster") + .formParam("DBClusterIdentifier", ID) + .formParam("SkipFinalSnapshot", "true") + .when().post("/") + .then() + .statusCode(400) + .body(containsString("InvalidParameterCombination")); + } + + @Test + @Order(9) + void modifyAppliesTheChangedSettingsOnly() { + rds("ModifyDBCluster") + .formParam("DBClusterIdentifier", ID) + .formParam("ApplyImmediately", "true") + .formParam("AllowMajorVersionUpgrade", "false") + .formParam("DeletionProtection", "false") + .formParam("BackupRetentionPeriod", "3") + .formParam("CloudwatchLogsExportConfiguration.EnableLogTypes.member.1", "slowquery") + .formParam("CloudwatchLogsExportConfiguration.DisableLogTypes.member.1", "audit") + .formParam("VpcSecurityGroupIds", "") + .when().post("/") + .then() + .statusCode(200) + .body(containsString("false")) + .body(containsString("3")) + .body(containsString("slowquery")) + .body(containsString("")) + .body(containsString("8200")) + .body(containsString("03:00-04:00")); + } + + @Test + @Order(10) + void clusterMembersUseTheDbClusterMemberElement() { + rds("CreateDBInstance") + .formParam("DBInstanceIdentifier", INSTANCE_ID) + .formParam("DBClusterIdentifier", ID) + .formParam("DBInstanceClass", "db.r5.large") + .formParam("Engine", "neptune") + .when().post("/") + .then() + .statusCode(200); + + rds("DescribeDBClusters") + .formParam("DBClusterIdentifier", ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString("" + INSTANCE_ID + + "true")); + + rds("DeleteDBInstance") + .formParam("DBInstanceIdentifier", INSTANCE_ID) + .when().post("/") + .then() + .statusCode(200); + } + + @Test + @Order(11) + void deleteSucceedsOnceDeletionProtectionIsOff() { + rds("DeleteDBCluster") + .formParam("DBClusterIdentifier", ID) + .formParam("SkipFinalSnapshot", "true") + .when().post("/") + .then() + .statusCode(200) + .body(containsString(ID)); + + rds("DescribeDBClusters") + .formParam("DBClusterIdentifier", ID) + .when().post("/") + .then() + .statusCode(404) + .body(containsString("DBClusterNotFoundFault")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneInstanceSettingsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneInstanceSettingsIntegrationTest.java new file mode 100644 index 0000000000..eb8e525633 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneInstanceSettingsIntegrationTest.java @@ -0,0 +1,196 @@ +package io.github.hectorvent.floci.services.neptune; + +import io.quarkus.test.junit.QuarkusTest; +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 org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class NeptuneInstanceSettingsIntegrationTest { + + private static final String FORM = "application/x-www-form-urlencoded"; + private static final String CLUSTER_ID = "tf-neptune-instances"; + private static final String WRITER_ID = "tf-neptune-instances-writer"; + private static final String READER_ID = "tf-neptune-instances-reader"; + private static final String WRITER_ARN = "arn:aws:neptune:us-east-1:000000000000:db:" + WRITER_ID; + + private static RequestSpecification rds(String action) { + return given() + .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260904/us-east-1/rds" + + "/aws4_request, SignedHeaders=content-type;host, Signature=test") + .contentType(FORM) + .formParam("Action", action); + } + + @Test + @Order(1) + void createEchoesEverySettingTerraformSends() { + rds("CreateDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .formParam("Engine", "neptune") + .formParam("Port", "8211") + .when().post("/") + .then() + .statusCode(200); + + rds("CreateDBInstance") + .formParam("DBInstanceIdentifier", WRITER_ID) + .formParam("DBClusterIdentifier", CLUSTER_ID) + .formParam("DBInstanceClass", "db.r5.large") + .formParam("Engine", "neptune") + .formParam("AutoMinorVersionUpgrade", "true") + .formParam("PromotionTier", "0") + .formParam("PubliclyAccessible", "false") + .formParam("Tags.Tag.1.Key", "Name") + .formParam("Tags.Tag.1.Value", WRITER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString("db.r5.large")) + .body(containsString("8211")) + .body(containsString("true")) + .body(containsString("0")) + .body(containsString("false")) + .body(containsString("false")) + .body(containsString("default")) + .body(containsString("default.neptune1.3")) + .body(containsString("04:00-06:00")) + .body(containsString("mon:00:00-mon:03:00")) + .body(containsString("")); + } + + @Test + @Order(2) + void describeReadsTheSameSettingsBack() { + rds("DescribeDBInstances") + .formParam("DBInstanceIdentifier", WRITER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString("true")) + .body(containsString("0")) + .body(containsString("false")) + .body(containsString("false")) + .body(containsString("default.neptune1.3")) + .body(containsString("")); + } + + @Test + @Order(3) + void modifyAppliesTheChangedSettingsOnly() { + rds("ModifyDBInstance") + .formParam("DBInstanceIdentifier", WRITER_ID) + .formParam("AutoMinorVersionUpgrade", "false") + .formParam("PromotionTier", "5") + .formParam("DBParameterGroupName", "tuned") + .formParam("PreferredMaintenanceWindow", "Sun:05:00-Sun:06:00") + .formParam("ApplyImmediately", "true") + .when().post("/") + .then() + .statusCode(200) + .body(containsString("false")) + .body(containsString("5")) + .body(containsString("tuned")) + .body(containsString("sun:05:00-sun:06:00")) + .body(containsString("db.r5.large")) + .body(containsString("false")); + } + + @Test + @Order(4) + void tagsRoundTripThroughTheInstanceArn() { + rds("AddTagsToResource") + .formParam("ResourceName", WRITER_ARN) + .formParam("Tags.Tag.1.Key", "env") + .formParam("Tags.Tag.1.Value", "test") + .when().post("/") + .then() + .statusCode(200); + + rds("ListTagsForResource") + .formParam("ResourceName", WRITER_ARN) + .when().post("/") + .then() + .statusCode(200) + .body(containsString("Name" + WRITER_ID + "")) + .body(containsString("envtest")); + + rds("RemoveTagsFromResource") + .formParam("ResourceName", WRITER_ARN) + .formParam("TagKeys.member.1", "env") + .when().post("/") + .then() + .statusCode(200); + + rds("ListTagsForResource") + .formParam("ResourceName", WRITER_ARN) + .when().post("/") + .then() + .statusCode(200) + .body(not(containsString("env"))); + } + + @Test + @Order(5) + void onlyTheFirstMemberIsTheClusterWriter() { + rds("CreateDBInstance") + .formParam("DBInstanceIdentifier", READER_ID) + .formParam("DBClusterIdentifier", CLUSTER_ID) + .formParam("DBInstanceClass", "db.r5.large") + .formParam("Engine", "neptune") + .formParam("PromotionTier", "2") + .when().post("/") + .then() + .statusCode(200) + .body(containsString("2")); + + rds("DescribeDBClusters") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString("" + WRITER_ID + + "true")) + .body(containsString("" + READER_ID + + "false")); + } + + @Test + @Order(6) + void deletingTheWriterPromotesTheNextMember() { + rds("DeleteDBInstance") + .formParam("DBInstanceIdentifier", WRITER_ID) + .when().post("/") + .then() + .statusCode(200); + + rds("DescribeDBClusters") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .when().post("/") + .then() + .statusCode(200) + .body(containsString("" + READER_ID + + "true")) + .body(not(containsString(WRITER_ID))); + + rds("DeleteDBInstance") + .formParam("DBInstanceIdentifier", READER_ID) + .when().post("/") + .then() + .statusCode(200); + + rds("DeleteDBCluster") + .formParam("DBClusterIdentifier", CLUSTER_ID) + .formParam("SkipFinalSnapshot", "true") + .when().post("/") + .then() + .statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneServiceTest.java index 8cabad6ac8..6f961bc63a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/neptune/NeptuneServiceTest.java @@ -8,15 +8,21 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerHandle; import io.github.hectorvent.floci.services.neptune.container.NeptuneContainerManager; import io.github.hectorvent.floci.services.neptune.model.NeptuneCluster; +import io.github.hectorvent.floci.services.neptune.model.NeptuneClusterSettings; import io.github.hectorvent.floci.services.neptune.model.NeptuneDbType; import io.github.hectorvent.floci.services.neptune.model.NeptuneInstance; +import io.github.hectorvent.floci.services.neptune.model.NeptuneInstanceSettings; import io.github.hectorvent.floci.services.neptune.proxy.NeptuneProxyManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.List; +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.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -201,4 +207,209 @@ class NeptuneServiceTest { service.deleteDbCluster("no-docker-cluster"); verify(containerManager, never()).stop(any()); } + + private static NeptuneClusterSettings settings(Integer port, Integer backupRetentionPeriod, + Boolean deletionProtection, List vpcSecurityGroupIds, + List enableLogTypes, List disableLogTypes) { + return new NeptuneClusterSettings(null, port, backupRetentionPeriod, null, null, null, null, + vpcSecurityGroupIds, null, null, null, deletionProtection, null, enableLogTypes, disableLogTypes, + null, null, null); + } + + @Test + void createDbClusterStoresEverySettingAndTheTags() { + NeptuneClusterSettings requested = new NeptuneClusterSettings( + List.of("us-east-1a", "us-east-1b"), null, 7, "03:00-04:00", "Sun:05:00-Sun:06:00", + "my-subnets", "my-params", List.of("sg-1"), false, null, "iopt1", true, true, + List.of("audit"), null, null, 2.5, 8.0); + + NeptuneCluster c = service.createDbCluster("settings", "1.3.2.1", false, requested, Map.of("Name", "settings")); + + assertEquals(List.of("us-east-1a", "us-east-1b"), c.getAvailabilityZones()); + assertEquals(7, c.getBackupRetentionPeriod()); + assertEquals("03:00-04:00", c.getPreferredBackupWindow()); + assertEquals("sun:05:00-sun:06:00", c.getPreferredMaintenanceWindow()); + assertEquals("my-subnets", c.getDbSubnetGroupName()); + assertEquals("my-params", c.getDbClusterParameterGroupName()); + assertEquals(List.of("sg-1"), c.getVpcSecurityGroupIds()); + assertFalse(c.isStorageEncrypted()); + assertEquals("iopt1", c.getStorageType()); + assertTrue(c.isDeletionProtection()); + assertTrue(c.isCopyTagsToSnapshot()); + assertEquals(List.of("audit"), c.getEnabledCloudwatchLogsExports()); + assertEquals(Double.valueOf(2.5), c.getServerlessV2MinCapacity()); + assertEquals(Double.valueOf(8.0), c.getServerlessV2MaxCapacity()); + assertEquals(Map.of("Name", "settings"), c.getTags()); + } + + @Test + void storageEncryptedDefaultsToFalseLikeAws() { + NeptuneCluster c = service.createDbCluster("plain", "1.3.2.1", false); + assertFalse(c.isStorageEncrypted()); + assertEquals(1, c.getBackupRetentionPeriod()); + assertTrue(c.getAvailabilityZones().isEmpty()); + assertTrue(c.getTags().isEmpty()); + } + + @Test + void requestedPortIsHonouredWhenFreeInTheProxyRangeAndFallsBackOtherwise() { + assertEquals(18190, service.createDbCluster("p1", "1.3.2.1", false, + settings(18190, null, null, null, null, null), Map.of()).getPort()); + assertEquals(18182, service.createDbCluster("p2", "1.3.2.1", false, + settings(18190, null, null, null, null, null), Map.of()).getPort()); + assertEquals(18183, service.createDbCluster("p3", "1.3.2.1", false, + settings(9999, null, null, null, null, null), Map.of()).getPort()); + + service.deleteDbCluster("p1"); + assertEquals(18190, service.createDbCluster("p4", "1.3.2.1", false, + settings(18190, null, null, null, null, null), Map.of()).getPort()); + } + + @Test + void invalidSettingsAreRejectedBeforeAPortIsReserved() { + AwsException e = assertThrows(AwsException.class, () -> service.createDbCluster("bad", "1.3.2.1", false, + settings(null, 99, null, null, null, null), Map.of())); + assertEquals("InvalidParameterValue", e.getErrorCode()); + assertEquals(18182, service.createDbCluster("good", "1.3.2.1", false).getPort()); + } + + @Test + void deleteIsRefusedWhileDeletionProtectionIsOn() { + service.createDbCluster("protected", "1.3.2.1", false, + settings(null, null, true, null, null, null), Map.of()); + + AwsException e = assertThrows(AwsException.class, () -> service.deleteDbCluster("protected")); + assertEquals("InvalidParameterCombination", e.getErrorCode()); + assertTrue(service.hasCluster("protected")); + + service.modifyDbCluster("protected", null, null, settings(null, null, false, null, null, null)); + service.deleteDbCluster("protected"); + assertFalse(service.hasCluster("protected")); + } + + @Test + void modifyMergesLogExportsAndClearsSecurityGroupsWithAnEmptyList() { + service.createDbCluster("logs", "1.3.2.1", false, + settings(null, null, null, List.of("sg-1"), List.of("audit"), null), Map.of()); + + NeptuneCluster c = service.modifyDbCluster("logs", null, null, + settings(null, 3, null, List.of(), List.of("slowquery"), List.of("audit"))); + + assertEquals(List.of("slowquery"), c.getEnabledCloudwatchLogsExports()); + assertTrue(c.getVpcSecurityGroupIds().isEmpty()); + assertEquals(3, c.getBackupRetentionPeriod()); + + NeptuneCluster unchanged = service.modifyDbCluster("logs", null, null, NeptuneClusterSettings.unchanged()); + assertEquals(List.of("slowquery"), unchanged.getEnabledCloudwatchLogsExports()); + assertEquals(3, unchanged.getBackupRetentionPeriod()); + } + + @Test + void rolesAreAssociatedOnceAndRemovedByArn() { + service.createDbCluster("roles", "1.3.2.1", false); + String roleArn = "arn:aws:iam::000000000000:role/neptune-load"; + + assertEquals(List.of(roleArn), service.addRoleToDbCluster("roles", roleArn).getAssociatedRoleArns()); + assertEquals("DBClusterRoleAlreadyExists", + assertThrows(AwsException.class, () -> service.addRoleToDbCluster("roles", roleArn)).getErrorCode()); + + assertTrue(service.removeRoleFromDbCluster("roles", roleArn).getAssociatedRoleArns().isEmpty()); + assertEquals("DBClusterRoleNotFound", + assertThrows(AwsException.class, () -> service.removeRoleFromDbCluster("roles", roleArn)).getErrorCode()); + } + + @Test + void tagsAreResolvedByTheExactArnOnly() { + NeptuneCluster c = service.createDbCluster("tagged", "1.3.2.1", false, + NeptuneClusterSettings.defaults(), Map.of("env", "test")); + String arn = c.getDbClusterArn(); + + assertTrue(service.hasResourceWithArn(arn)); + assertEquals(Map.of("env", "test"), service.listTagsForResource(arn)); + + service.addTagsToResource(arn, Map.of("team", "graph")); + service.removeTagsFromResource(arn, List.of("env", "absent")); + assertEquals(Map.of("team", "graph"), service.listTagsForResource(arn)); + + String foreign = arn.replace("us-east-1", "eu-west-1"); + assertFalse(service.hasResourceWithArn(foreign)); + assertEquals("DBClusterNotFoundFault", + assertThrows(AwsException.class, () -> service.listTagsForResource(foreign)).getErrorCode()); + assertEquals("InvalidParameterValue", + assertThrows(AwsException.class, () -> service.listTagsForResource("tagged")).getErrorCode()); + + NeptuneInstance instance = service.createDbInstance("tagged-db", "tagged", null, null, false, + Map.of("role", "writer")); + assertTrue(service.hasResourceWithArn(instance.getDbInstanceArn())); + assertEquals(Map.of("role", "writer"), service.listTagsForResource(instance.getDbInstanceArn())); + } + + @Test + void parameterGroupFamilyFollowsTheEngineMajorAndMinor() { + assertEquals("neptune1", NeptuneService.parameterGroupFamily("1.0.5.1")); + assertEquals("neptune1", NeptuneService.parameterGroupFamily("1.1.1.0")); + assertEquals("neptune1.2", NeptuneService.parameterGroupFamily("1.2.1.0")); + assertEquals("neptune1.3", NeptuneService.parameterGroupFamily("1.3.2.1")); + assertEquals("neptune1.4", NeptuneService.parameterGroupFamily("1.4.5.1")); + assertEquals("neptune1.3", NeptuneService.parameterGroupFamily(null)); + assertEquals("neptune1.3", NeptuneService.parameterGroupFamily("latest")); + } + + // --- Instance settings the Terraform aws_neptune_cluster_instance resource reads back --- + + @Test + void createDbInstanceStoresTheRequestedSettingsAndAwsDefaultsOtherwise() { + service.createDbCluster("instance-settings", "1.3.2.1", false); + + NeptuneInstance requested = service.createDbInstance("with-settings", "instance-settings", + "db.r5.large", null, false, + new NeptuneInstanceSettings("us-east-1b", false, 0, true, "custom-params", "custom-subnets", + "07:00-08:00", "Sun:05:00-Sun:06:00"), + Map.of("Name", "with-settings")); + assertEquals("us-east-1b", requested.getAvailabilityZone()); + assertFalse(requested.isAutoMinorVersionUpgrade()); + assertEquals(0, requested.getPromotionTier()); + assertTrue(requested.isPubliclyAccessible()); + assertEquals("custom-params", requested.getDbParameterGroupName()); + assertEquals("custom-subnets", requested.getDbSubnetGroupName()); + assertEquals("07:00-08:00", requested.getPreferredBackupWindow()); + assertEquals("sun:05:00-sun:06:00", requested.getPreferredMaintenanceWindow()); + assertEquals("with-settings", requested.getTags().get("Name")); + + NeptuneInstance defaults = service.createDbInstance("bare", "instance-settings", "db.r5.large", null, false); + assertTrue(defaults.isAutoMinorVersionUpgrade()); + assertEquals(1, defaults.getPromotionTier()); + assertFalse(defaults.isPubliclyAccessible()); + assertNull(defaults.getAvailabilityZone()); + assertNull(defaults.getDbParameterGroupName()); + assertNull(defaults.getPreferredMaintenanceWindow()); + } + + @Test + void modifyDbInstanceAppliesOnlyTheSettingsTheRequestCarries() { + service.createDbCluster("instance-modify", "1.3.2.1", false); + service.createDbInstance("to-modify", "instance-modify", "db.r5.large", null, false, + new NeptuneInstanceSettings(null, true, 2, null, null, null, null, null), Map.of()); + + NeptuneInstance modified = service.modifyDbInstance("to-modify", null, null, + new NeptuneInstanceSettings(null, false, null, null, "tuned", null, null, "Mon:02:00-Mon:03:00")); + + assertFalse(modified.isAutoMinorVersionUpgrade()); + assertEquals(2, modified.getPromotionTier(), "An omitted PromotionTier must keep its value"); + assertEquals("tuned", modified.getDbParameterGroupName()); + assertEquals("mon:02:00-mon:03:00", modified.getPreferredMaintenanceWindow()); + assertEquals("db.r5.large", modified.getDbInstanceClass(), "An omitted DBInstanceClass must keep its value"); + } + + @Test + void instanceSettingsRejectAPromotionTierOutsideTheAwsRange() { + service.createDbCluster("instance-invalid", "1.3.2.1", false); + + AwsException ex = assertThrows(AwsException.class, () -> service.createDbInstance("bad-tier", + "instance-invalid", "db.r5.large", null, false, + new NeptuneInstanceSettings(null, null, 16, null, null, null, null, null), Map.of())); + + assertEquals("InvalidParameterValue", ex.getErrorCode()); + assertFalse(service.hasInstance("bad-tier"), "A rejected create must not leave an instance behind"); + } }