diff --git a/compatibility-tests/compat-terraform/test/rds-snapshot-tags-tf/main.tf b/compatibility-tests/compat-terraform/test/rds-snapshot-tags-tf/main.tf new file mode 100644 index 0000000000..d1e44d1e4a --- /dev/null +++ b/compatibility-tests/compat-terraform/test/rds-snapshot-tags-tf/main.tf @@ -0,0 +1,35 @@ +# Verifies aws_db_snapshot tags round-trip through CreateDBSnapshot/TagResource/DescribeDBSnapshots +# instead of TagResource rejecting the snapshot ARN outright ("not yet implemented by Floci"). + +resource "aws_db_instance" "source" { + identifier = "floci-rds-snapshot-tags-source" + engine = "postgres" + engine_version = "16" + instance_class = "db.t3.micro" + allocated_storage = 20 + username = "app" + password = "changeme123!" + skip_final_snapshot = true +} + +variable "owner_tag" { + type = string + default = "platform" +} + +resource "aws_db_snapshot" "test" { + db_instance_identifier = aws_db_instance.source.identifier + db_snapshot_identifier = "floci-rds-snapshot-tags-snap" + + tags = { + owner = var.owner_tag + } +} + +output "db_snapshot_arn" { + value = aws_db_snapshot.test.db_snapshot_arn +} + +output "owner_tag" { + value = aws_db_snapshot.test.tags["owner"] +} diff --git a/compatibility-tests/compat-terraform/test/rds-snapshot-tags-tf/provider.tf b/compatibility-tests/compat-terraform/test/rds-snapshot-tags-tf/provider.tf new file mode 100644 index 0000000000..7a84fefbc5 --- /dev/null +++ b/compatibility-tests/compat-terraform/test/rds-snapshot-tags-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 { + rds = var.endpoint + } +} diff --git a/compatibility-tests/compat-terraform/test/rds_snapshot_tags.bats b/compatibility-tests/compat-terraform/test/rds_snapshot_tags.bats new file mode 100644 index 0000000000..32704aa865 --- /dev/null +++ b/compatibility-tests/compat-terraform/test/rds_snapshot_tags.bats @@ -0,0 +1,85 @@ +#!/usr/bin/env bats +# RDS DB Snapshot Tagging Compatibility Test +# +# TagResource/UntagResource used to reject a snapshot ARN outright ("not yet implemented by +# Floci"), and CreateDBSnapshot silently dropped its Tags parameter. This verifies aws_db_snapshot +# can apply with tags, that DescribeDBSnapshots reads them back (both DBSnapshotArn and TagList), +# that a second plan is clean, and that changing a tag updates in place rather than replacing. + +setup_file() { + load 'test_helper/common-setup' + + SNAP_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/rds-snapshot-tags-tf" && pwd)" + cd "$SNAP_TF_DIR" + + echo "# === RDS Snapshot Tagging Test ===" >&3 + echo "# Endpoint: $FLOCI_ENDPOINT" >&3 + echo "# Config: $SNAP_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' + + SNAP_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/rds-snapshot-tags-tf" && pwd)" + cd "$SNAP_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' + SNAP_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/rds-snapshot-tags-tf" && pwd)" +} + +@test "RDS snapshot tags: apply reports a snapshot ARN pinned to the provider's region" { + ARN=$(terraform -chdir="$SNAP_TF_DIR" output -raw db_snapshot_arn) + OWNER=$(terraform -chdir="$SNAP_TF_DIR" output -raw owner_tag) + # Exact match, not a wildcard: us-east-1 is also the default region, so a wildcard here would miss a regression. + assert_equal "$ARN" "arn:aws:rds:us-east-1:000000000000:snapshot:floci-rds-snapshot-tags-snap" + assert_equal "$OWNER" "platform" +} + +@test "RDS snapshot tags: DescribeDBSnapshots reads the tag back" { + run aws_cmd rds describe-db-snapshots --db-snapshot-identifier floci-rds-snapshot-tags-snap \ + --query "DBSnapshots[0].TagList[?Key=='owner'].Value | [0]" --output text + assert_success + assert_output "platform" +} + +@test "RDS snapshot tags: second plan reports no changes" { + cd "$SNAP_TF_DIR" + run terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color -detailed-exitcode + assert_success + assert_output --partial "No changes" +} + +@test "RDS snapshot tags: changing a tag updates in place, not a replacement" { + cd "$SNAP_TF_DIR" + run terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -var="owner_tag=data-team" \ + -input=false -auto-approve -no-color + assert_success + assert_output --partial "1 changed" + refute_output --partial "1 destroyed" + + run aws_cmd rds describe-db-snapshots --db-snapshot-identifier floci-rds-snapshot-tags-snap \ + --query "DBSnapshots[0].TagList[?Key=='owner'].Value | [0]" --output text + assert_success + assert_output "data-team" +} diff --git a/docs/services/rds.md b/docs/services/rds.md index 857edb3342..e12bebfeff 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -45,6 +45,8 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou | `CreateDBSnapshot` | Create a snapshot of a DB instance | | `RestoreDBInstanceFromDBSnapshot` | Create a new DB instance from a snapshot | | `DescribeDBSnapshots` | List DB instance snapshots | +| `DescribeDBSnapshotAttributes` | Return a snapshot's `restore` attribute (accounts authorized to copy/restore it) | +| `ModifyDBSnapshotAttribute` | Add or remove accounts authorized to copy/restore a snapshot | | `DescribeDBProxies` | List DB proxies | | `CreateDBProxy` | Create a DB proxy | | `ModifyDBProxy` | Update mutable DB proxy authentication, logging, timeout, TLS, role, and security-group settings | @@ -74,6 +76,19 @@ usual default, a 30-minute window starting where the given one ends); a window g checked against the instance's other window. Modifications apply immediately — `PendingModifiedValues` is not modeled. +!!! note "DB snapshot tagging and lifecycle" + + `CreateDBSnapshot` accepts `Tags`, and `TagResource`/`UntagResource`/`ListTagsForResource` + work against a snapshot's ARN like they do for other tagged resource types. + `DescribeDBSnapshotAttributes`/`ModifyDBSnapshotAttribute` are modeled as plain in-memory + state (no real cross-account sharing). `DeleteDBSnapshot` is not implemented, so a snapshot + persists for the life of the account; Terraform's `aws_db_snapshot` can be created but not + destroyed. Snapshots are region-scoped like DB instances and clusters: `DBSnapshotArn` reflects + the request's signed region, and a snapshot is only visible to `Describe`/`Tag` calls signed + for that same region. Aurora cluster snapshots and RDS reserved instances aren't modeled at + all (`DescribeDBClusterSnapshots` always returns an empty list, and there's no + reserved-instance API), so tagging doesn't apply to either. + ## Configuration | Variable | Default | Description | diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java index 9ae843bb99..8e4717051b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java @@ -95,9 +95,11 @@ public class RdsQueryHandler { case "DescribeOptionGroups" -> handleDescribeOptionGroups(params, region); case "ModifyOptionGroup" -> handleModifyOptionGroup(params, region); case "DeleteOptionGroup" -> handleDeleteOptionGroup(params, region); - case "CreateDBSnapshot" -> handleCreateDbSnapshot(params); - case "RestoreDBInstanceFromDBSnapshot" -> handleRestoreDbInstanceFromDbSnapshot(params); - case "DescribeDBSnapshots" -> handleDescribeDbSnapshots(params); + case "CreateDBSnapshot" -> handleCreateDbSnapshot(params, region); + case "RestoreDBInstanceFromDBSnapshot" -> handleRestoreDbInstanceFromDbSnapshot(params, region); + case "DescribeDBSnapshots" -> handleDescribeDbSnapshots(params, region); + case "DescribeDBSnapshotAttributes" -> handleDescribeDbSnapshotAttributes(params, region); + case "ModifyDBSnapshotAttribute" -> handleModifyDbSnapshotAttribute(params, region); case "DescribeDBProxies" -> handleDescribeDbProxies(params, region); case "CreateDBProxy" -> handleCreateDbProxy(params, region); case "ModifyDBProxy" -> handleModifyDbProxy(params, region); @@ -1054,9 +1056,7 @@ public class RdsQueryHandler { return settings; } - // ── Snapshots & Proxies (not modeled — empty lists) ─────────────────────── - - private Response handleCreateDbSnapshot(MultivaluedMap params) { + private Response handleCreateDbSnapshot(MultivaluedMap params, String region) { String snapshotId = params.getFirst("DBSnapshotIdentifier"); String instanceId = params.getFirst("DBInstanceIdentifier"); if (snapshotId == null || snapshotId.isBlank()) { @@ -1066,7 +1066,8 @@ public class RdsQueryHandler { return AwsQueryResponse.error("InvalidParameterValue", "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400); } try { - io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = service.createDbSnapshot(snapshotId, instanceId); + io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = + service.createDbSnapshot(snapshotId, instanceId, parseTags(params), region); String result = dbSnapshotXml(snapshot); return Response.ok(AwsQueryResponse.envelope("CreateDBSnapshot", AwsNamespaces.RDS, result)).build(); } catch (AwsException e) { @@ -1074,7 +1075,7 @@ public class RdsQueryHandler { } } - private Response handleRestoreDbInstanceFromDbSnapshot(MultivaluedMap params) { + private Response handleRestoreDbInstanceFromDbSnapshot(MultivaluedMap params, String region) { String instanceId = params.getFirst("DBInstanceIdentifier"); String snapshotId = params.getFirst("DBSnapshotIdentifier"); if (instanceId == null || instanceId.isBlank()) { @@ -1099,7 +1100,7 @@ public class RdsQueryHandler { java.util.Map tags = parseTags(params); try { - DbInstance instance = service.restoreDbInstanceFromDbSnapshot(instanceId, snapshotId, dbInstanceClass, availabilityZone, multiAz, dbSubnetGroupName, vpcSecurityGroupIds, tags); + DbInstance instance = service.restoreDbInstanceFromDbSnapshot(instanceId, snapshotId, dbInstanceClass, availabilityZone, multiAz, dbSubnetGroupName, vpcSecurityGroupIds, tags, region); String result = dbInstanceXml(instance); return Response.ok(AwsQueryResponse.envelope("RestoreDBInstanceFromDBSnapshot", AwsNamespaces.RDS, result)).build(); } catch (AwsException e) { @@ -1107,11 +1108,12 @@ public class RdsQueryHandler { } } - private Response handleDescribeDbSnapshots(MultivaluedMap params) { + private Response handleDescribeDbSnapshots(MultivaluedMap params, String region) { String snapshotId = params.getFirst("DBSnapshotIdentifier"); String instanceId = params.getFirst("DBInstanceIdentifier"); try { - Collection result = service.describeDbSnapshots(snapshotId, instanceId); + Collection result = + service.describeDbSnapshots(snapshotId, instanceId, region); XmlBuilder xml = new XmlBuilder().start("DBSnapshots"); for (io.github.hectorvent.floci.services.rds.model.DbSnapshot s : result) { xml.raw(dbSnapshotXml(s)); @@ -1123,6 +1125,33 @@ public class RdsQueryHandler { } } + private Response handleDescribeDbSnapshotAttributes(MultivaluedMap params, String region) { + String snapshotId = params.getFirst("DBSnapshotIdentifier"); + try { + io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = + service.describeDbSnapshotAttributes(snapshotId, region); + String result = dbSnapshotAttributesResultXml(snapshot); + return Response.ok(AwsQueryResponse.envelope( + "DescribeDBSnapshotAttributes", AwsNamespaces.RDS, result)).build(); + } catch (AwsException e) { + return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus()); + } + } + + private Response handleModifyDbSnapshotAttribute(MultivaluedMap params, String region) { + String snapshotId = params.getFirst("DBSnapshotIdentifier"); + String attributeName = params.getFirst("AttributeName"); + try { + io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = service.modifyDbSnapshotAttribute( + snapshotId, attributeName, memberList(params, "ValuesToAdd"), memberList(params, "ValuesToRemove"), region); + String result = dbSnapshotAttributesResultXml(snapshot); + return Response.ok(AwsQueryResponse.envelope( + "ModifyDBSnapshotAttribute", AwsNamespaces.RDS, result)).build(); + } catch (AwsException e) { + return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus()); + } + } + private Response handleDescribeDbProxies(MultivaluedMap params, String region) { XmlBuilder xml = new XmlBuilder().start("DBProxies"); for (DbProxy p : service.listDbProxies(params.getFirst("DBProxyName"), region)) { @@ -1446,9 +1475,25 @@ public class RdsQueryHandler { .elem("Port", s.getPort()) .elem("IAMDatabaseAuthenticationEnabled", s.isIamDatabaseAuthenticationEnabled()); if (s.getDbiResourceId() != null) xml.elem("DbiResourceId", s.getDbiResourceId()); + if (s.getDbSnapshotArn() != null) xml.elem("DBSnapshotArn", s.getDbSnapshotArn()); + xml.start("TagList"); + writeTags(xml, s.getTags()); + xml.end("TagList"); return xml.end("DBSnapshot").build(); } + private String dbSnapshotAttributesResultXml(io.github.hectorvent.floci.services.rds.model.DbSnapshot s) { + XmlBuilder xml = new XmlBuilder().start("DBSnapshotAttributesResult") + .elem("DBSnapshotIdentifier", s.getDbSnapshotIdentifier()); + xml.start("DBSnapshotAttributes").start("DBSnapshotAttribute") + .elem("AttributeName", "restore"); + xml.start("AttributeValues"); + s.getRestoreAccountIds().forEach(id -> xml.elem("AttributeValue", id)); + xml.end("AttributeValues"); + xml.end("DBSnapshotAttribute").end("DBSnapshotAttributes"); + return xml.end("DBSnapshotAttributesResult").build(); + } + private String dbInstanceInnerXml(DbInstance i) { DbEndpoint ep = i.getEndpoint(); String engineStr = instanceEngine(i); @@ -1980,6 +2025,7 @@ public class RdsQueryHandler { case "SubnetIds" -> quoted + "(\\.member|\\.SubnetIdentifier)?\\.\\d+"; case "VpcSecurityGroupIds" -> quoted + "(\\.member|\\.VpcSecurityGroupId)?\\.\\d+"; case "OptionsToRemove" -> quoted + "(\\.member|\\.OptionName)?\\.\\d+"; + case "ValuesToAdd", "ValuesToRemove" -> quoted + "(\\.member|\\.AttributeValue)?\\.\\d+"; default -> { // Option configurations nest their membership lists under an indexed prefix, // so the alternate member names have to be matched on the suffix. diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java index 1085b86dcd..70e54795e9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java @@ -756,11 +756,22 @@ public class RdsService implements Resettable, ResourceProvider { } public DbSnapshot createDbSnapshot(String snapshotId, String instanceId) { - if (snapshots.get(snapshotId).isPresent()) { + return createDbSnapshot(snapshotId, instanceId, Map.of(), regionResolver.getDefaultRegion()); + } + + public DbSnapshot createDbSnapshot(String snapshotId, String instanceId, Map tags) { + return createDbSnapshot(snapshotId, instanceId, tags, regionResolver.getDefaultRegion()); + } + + public synchronized DbSnapshot createDbSnapshot(String snapshotId, String instanceId, + Map tags, String region) { + String effectiveRegion = effectiveRegion(region); + String accountId = currentAccountId(); + if (findSnapshotForScope(accountId, effectiveRegion, snapshotId) != null) { throw new AwsException("DBSnapshotAlreadyExists", "DBSnapshot " + snapshotId + " already exists.", 400); } - DbInstance instance = getDbInstance(instanceId); + DbInstance instance = getDbInstance(instanceId, effectiveRegion); if (instance.getEngine() != DatabaseEngine.POSTGRES) { throw new AwsException("InvalidDBInstanceState", "Operation CreateDBSnapshot is not supported for engine " + instance.getEngine() + ".", 400); @@ -772,6 +783,8 @@ public class RdsService implements Resettable, ResourceProvider { instance.getCreatedAt(), instance.getEndpoint() != null ? instance.getEndpoint().port() : instance.getProxyPort(), instance.isIamDatabaseAuthenticationEnabled(), instance.getDbiResourceId(), instance.getDbInstanceClass()); snapshot.setDbName(instance.getDbName()); + snapshot.setTags(tags != null ? new java.util.LinkedHashMap<>(tags) : new java.util.LinkedHashMap<>()); + snapshot.setDbSnapshotArn(regionResolver.buildArn("rds", effectiveRegion, "snapshot:" + snapshotId)); String sqlDump = ""; if (!config.services().rds().mock()) { @@ -782,17 +795,26 @@ public class RdsService implements Resettable, ResourceProvider { throw new AwsException("InvalidDBInstanceState", "Failed to create snapshot: " + e.getMessage(), 400); } } - snapshotData.put(snapshotId, sqlDump); - snapshots.put(snapshotId, snapshot); + snapshotData.put(dbResourceKey(effectiveRegion, snapshotId), sqlDump); + putSnapshotForScope(accountId, effectiveRegion, snapshotId, snapshot); return snapshot; } public DbInstance restoreDbInstanceFromDbSnapshot(String instanceId, String snapshotId, String dbInstanceClass, String availabilityZone, boolean multiAz, String dbSubnetGroupName, java.util.List vpcSecurityGroupIds, java.util.Map tags) { - DbSnapshot snapshot = snapshots.get(snapshotId) + return restoreDbInstanceFromDbSnapshot(instanceId, snapshotId, dbInstanceClass, availabilityZone, + multiAz, dbSubnetGroupName, vpcSecurityGroupIds, tags, regionResolver.getDefaultRegion()); + } + + public DbInstance restoreDbInstanceFromDbSnapshot(String instanceId, String snapshotId, String dbInstanceClass, + String availabilityZone, boolean multiAz, String dbSubnetGroupName, + java.util.List vpcSecurityGroupIds, + java.util.Map tags, String region) { + String effectiveRegion = effectiveRegion(region); + DbSnapshot snapshot = Optional.ofNullable(findSnapshotForScope(currentAccountId(), effectiveRegion, snapshotId)) .orElseThrow(() -> new AwsException("DBSnapshotNotFound", "DBSnapshot " + snapshotId + " not found.", 404)); - String sqlDump = snapshotData.get(snapshotId) + String sqlDump = snapshotData.get(dbResourceKey(effectiveRegion, snapshotId)) .orElseThrow(() -> new AwsException("DBSnapshotNotFound", "DBSnapshot data for " + snapshotId + " not found.", 404)); String targetClass = (dbInstanceClass != null && !dbInstanceClass.isBlank()) ? dbInstanceClass : snapshot.getDbInstanceClass(); @@ -824,8 +846,14 @@ public class RdsService implements Resettable, ResourceProvider { } public Collection describeDbSnapshots(String snapshotId, String instanceId) { + return describeDbSnapshots(snapshotId, instanceId, regionResolver.getDefaultRegion()); + } + + public Collection describeDbSnapshots(String snapshotId, String instanceId, String region) { + String effectiveRegion = effectiveRegion(region); + String accountId = currentAccountId(); if (snapshotId != null && !snapshotId.isBlank()) { - DbSnapshot snapshot = snapshots.get(snapshotId) + DbSnapshot snapshot = Optional.ofNullable(findSnapshotForScope(accountId, effectiveRegion, snapshotId)) .orElseThrow(() -> new AwsException("DBSnapshotNotFound", "DBSnapshot " + snapshotId + " not found.", 404)); if (instanceId != null && !instanceId.isBlank()) { if (instanceId.equals(snapshot.getDbInstanceIdentifier())) { @@ -837,7 +865,10 @@ public class RdsService implements Resettable, ResourceProvider { return List.of(snapshot); } - List allSnapshots = snapshots.scan(k -> true); + List allSnapshots = snapshots.scan(k -> true).stream() + .filter(s -> hasRdsResourceIdentity(s.getDbSnapshotArn(), accountId, effectiveRegion, + "snapshot", s.getDbSnapshotIdentifier())) + .toList(); if (instanceId != null && !instanceId.isBlank()) { return allSnapshots.stream() .filter(s -> instanceId.equals(s.getDbInstanceIdentifier())) @@ -846,6 +877,46 @@ public class RdsService implements Resettable, ResourceProvider { return allSnapshots; } + public DbSnapshot describeDbSnapshotAttributes(String snapshotId) { + return describeDbSnapshotAttributes(snapshotId, regionResolver.getDefaultRegion()); + } + + public DbSnapshot describeDbSnapshotAttributes(String snapshotId, String region) { + return Optional.ofNullable(findSnapshotForScope(currentAccountId(), effectiveRegion(region), snapshotId)) + .orElseThrow(() -> new AwsException("DBSnapshotNotFound", + "DBSnapshot " + snapshotId + " not found.", 404)); + } + + public DbSnapshot modifyDbSnapshotAttribute(String snapshotId, String attributeName, + List valuesToAdd, List valuesToRemove) { + return modifyDbSnapshotAttribute(snapshotId, attributeName, valuesToAdd, valuesToRemove, + regionResolver.getDefaultRegion()); + } + + public synchronized DbSnapshot modifyDbSnapshotAttribute(String snapshotId, String attributeName, + List valuesToAdd, List valuesToRemove, + String region) { + String effectiveRegion = effectiveRegion(region); + String accountId = currentAccountId(); + DbSnapshot snapshot = Optional.ofNullable(findSnapshotForScope(accountId, effectiveRegion, snapshotId)) + .orElseThrow(() -> new AwsException("DBSnapshotNotFound", + "DBSnapshot " + snapshotId + " not found.", 404)); + if (!"restore".equals(attributeName)) { + throw new AwsException("InvalidParameterValue", + "AttributeName must be restore.", 400); + } + List updated = new java.util.ArrayList<>(snapshot.getRestoreAccountIds()); + if (valuesToAdd != null) { + valuesToAdd.stream().filter(v -> !updated.contains(v)).forEach(updated::add); + } + if (valuesToRemove != null) { + updated.removeAll(valuesToRemove); + } + snapshot.setRestoreAccountIds(updated); + putSnapshotForScope(accountId, effectiveRegion, snapshotId, snapshot); + return snapshot; + } + public Map listTagsForResource(String resourceName) { return listTagsForResource(resourceName, resourceRegionOrDefault(resourceName)); } @@ -951,6 +1022,16 @@ public class RdsService implements Resettable, ResourceProvider { currentAccountId(), effectiveRegion, resourceId, group); }); } + case "snapshot" -> { + DbSnapshot snapshot = Optional.ofNullable( + findSnapshotForScope(currentAccountId(), effectiveRegion, resourceId)) + .orElseThrow(() -> new AwsException("DBSnapshotNotFound", + "DBSnapshot " + resourceId + " not found.", 404)); + yield new TagHandle(snapshot.getTags(), updated -> { + snapshot.setTags(updated); + putSnapshotForScope(currentAccountId(), effectiveRegion, resourceId, snapshot); + }); + } case "db-proxy" -> { DbProxy proxy = proxies.scan(k -> true).stream() .filter(candidate -> effectiveRegion.equals(regionFromArn(candidate.getDbProxyArn()))) @@ -5316,6 +5397,41 @@ public class RdsService implements Resettable, ResourceProvider { } } + private synchronized DbSnapshot findSnapshotForScope(String accountId, String region, String snapshotId) { + String effectiveAccountId = accountId != null ? accountId : currentAccountId(); + String effectiveRegion = effectiveRegion(region); + String key = dbResourceKey(effectiveRegion, snapshotId); + java.util.function.Predicate owner = snapshot -> hasRdsResourceIdentity( + snapshot.getDbSnapshotArn(), effectiveAccountId, effectiveRegion, "snapshot", snapshotId); + if (snapshots instanceof AccountAwareStorageBackend aware) { + return aware.getForAccountMigratingLegacyKeys( + effectiveAccountId, key, List.of(snapshotId), owner) + .filter(owner) + .orElse(null); + } + + Optional canonical = snapshots.get(key).filter(owner); + if (canonical.isPresent()) { + snapshots.get(snapshotId).filter(owner).ifPresent(ignored -> snapshots.delete(snapshotId)); + return canonical.get(); + } + Optional legacy = snapshots.get(snapshotId).filter(owner); + if (legacy.isPresent()) { + snapshots.put(key, legacy.get()); + snapshots.delete(snapshotId); + } + return legacy.orElse(null); + } + + private void putSnapshotForScope(String accountId, String region, String snapshotId, DbSnapshot snapshot) { + String key = dbResourceKey(region, snapshotId); + if (snapshots instanceof AccountAwareStorageBackend aware) { + aware.putForAccount(accountId, key, snapshot); + } else { + snapshots.put(key, snapshot); + } + } + private synchronized DbSubnetGroup findSubnetGroupForScope( String accountId, String region, String groupName) { String effectiveRegion = effectiveRegion(region); diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbSnapshot.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbSnapshot.java index b8ebef937e..c627571bc0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbSnapshot.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbSnapshot.java @@ -3,13 +3,16 @@ package io.github.hectorvent.floci.services.rds.model; 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 DbSnapshot { private String dbSnapshotIdentifier; + private String dbSnapshotArn; private String dbInstanceIdentifier; private Instant snapshotCreateTime; private DatabaseEngine engine; @@ -27,6 +30,8 @@ public class DbSnapshot { private String dbName; private String dbInstanceClass; private Map tags = new LinkedHashMap<>(); + /** Account IDs authorized to copy/restore this snapshot; the "restore" DBSnapshotAttribute. */ + private List restoreAccountIds = new ArrayList<>(); public DbSnapshot() {} @@ -55,6 +60,9 @@ public class DbSnapshot { public String getDbSnapshotIdentifier() { return dbSnapshotIdentifier; } public void setDbSnapshotIdentifier(String dbSnapshotIdentifier) { this.dbSnapshotIdentifier = dbSnapshotIdentifier; } + public String getDbSnapshotArn() { return dbSnapshotArn; } + public void setDbSnapshotArn(String dbSnapshotArn) { this.dbSnapshotArn = dbSnapshotArn; } + public String getDbInstanceIdentifier() { return dbInstanceIdentifier; } public void setDbInstanceIdentifier(String dbInstanceIdentifier) { this.dbInstanceIdentifier = dbInstanceIdentifier; } @@ -100,6 +108,11 @@ public class DbSnapshot { public Map getTags() { return tags; } public void setTags(Map tags) { this.tags = tags; } + public List getRestoreAccountIds() { return restoreAccountIds; } + public void setRestoreAccountIds(List restoreAccountIds) { + this.restoreAccountIds = restoreAccountIds != null ? restoreAccountIds : new ArrayList<>(); + } + public String getDbName() { return dbName; } public void setDbName(String dbName) { this.dbName = dbName; } diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java index 4ff76d3d80..1a046a3df8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java @@ -1108,7 +1108,7 @@ class RdsQueryHandlerTest { snapshot.setDbSnapshotIdentifier("mysnap"); snapshot.setDbInstanceIdentifier("mydb"); snapshot.setEngine(io.github.hectorvent.floci.services.rds.model.DatabaseEngine.POSTGRES); - when(service.describeDbSnapshots("mysnap", "mydb")).thenReturn(List.of(snapshot)); + when(service.describeDbSnapshots(eq("mysnap"), eq("mydb"), isNull())).thenReturn(List.of(snapshot)); MultivaluedMap p = params(); p.add("DBSnapshotIdentifier", "mysnap"); @@ -1771,11 +1771,15 @@ class RdsQueryHandlerTest { snapshot.setDbSnapshotIdentifier("mysnap"); snapshot.setDbInstanceIdentifier("mydb"); snapshot.setEngine(io.github.hectorvent.floci.services.rds.model.DatabaseEngine.POSTGRES); - when(service.createDbSnapshot("mysnap", "mydb")).thenReturn(snapshot); + snapshot.setTags(Map.of("owner", "platform")); + when(service.createDbSnapshot(eq("mysnap"), eq("mydb"), eq(Map.of("owner", "platform")), isNull())) + .thenReturn(snapshot); MultivaluedMap p = params(); p.add("DBSnapshotIdentifier", "mysnap"); p.add("DBInstanceIdentifier", "mydb"); + p.add("Tags.Tag.1.Key", "owner"); + p.add("Tags.Tag.1.Value", "platform"); Response response = handler.handle("CreateDBSnapshot", p); assertEquals(200, response.getStatus()); @@ -1784,12 +1788,53 @@ class RdsQueryHandlerTest { assertTrue(body.contains("mysnap")); assertTrue(body.contains("mydb")); assertTrue(body.contains("postgres")); + assertTrue(body.contains("owner")); + assertTrue(body.contains("platform")); + } + + @Test + void describeDbSnapshotAttributes_returnsRestoreAttribute() { + io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = new io.github.hectorvent.floci.services.rds.model.DbSnapshot(); + snapshot.setDbSnapshotIdentifier("mysnap"); + snapshot.setRestoreAccountIds(List.of("111111111111")); + when(service.describeDbSnapshotAttributes(eq("mysnap"), isNull())).thenReturn(snapshot); + + MultivaluedMap p = params(); + p.add("DBSnapshotIdentifier", "mysnap"); + Response response = handler.handle("DescribeDBSnapshotAttributes", p); + + assertEquals(200, response.getStatus()); + String body = (String) response.getEntity(); + assertTrue(body.contains("restore")); + assertTrue(body.contains("111111111111")); + } + + @Test + void modifyDbSnapshotAttribute_passesValuesToAddAndRemove() { + io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = new io.github.hectorvent.floci.services.rds.model.DbSnapshot(); + snapshot.setDbSnapshotIdentifier("mysnap"); + snapshot.setRestoreAccountIds(List.of("222222222222")); + when(service.modifyDbSnapshotAttribute(eq("mysnap"), eq("restore"), + eq(List.of("222222222222")), eq(List.of("111111111111")), isNull())).thenReturn(snapshot); + + MultivaluedMap p = params(); + p.add("DBSnapshotIdentifier", "mysnap"); + p.add("AttributeName", "restore"); + p.add("ValuesToAdd.AttributeValue.1", "222222222222"); + p.add("ValuesToRemove.AttributeValue.1", "111111111111"); + Response response = handler.handle("ModifyDBSnapshotAttribute", p); + + assertEquals(200, response.getStatus()); + String body = (String) response.getEntity(); + assertTrue(body.contains("222222222222")); + verify(service).modifyDbSnapshotAttribute(eq("mysnap"), eq("restore"), + eq(List.of("222222222222")), eq(List.of("111111111111")), isNull()); } @Test void restoreDbInstanceFromDbSnapshot_success() { DbInstance instance = makeInstance("mydb"); - when(service.restoreDbInstanceFromDbSnapshot(eq("mydb"), eq("mysnap"), eq("db.t3.large"), eq("us-east-1a"), eq(true), eq("my-subnets"), eq(List.of("sg-123")), eq(Map.of("Env", "Prod")))) + when(service.restoreDbInstanceFromDbSnapshot(eq("mydb"), eq("mysnap"), eq("db.t3.large"), eq("us-east-1a"), eq(true), eq("my-subnets"), eq(List.of("sg-123")), eq(Map.of("Env", "Prod")), isNull())) .thenReturn(instance); MultivaluedMap p = params(); diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java index 6f2ce1b781..90cd36aff1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java @@ -1316,8 +1316,13 @@ class RdsServiceTest { rdsService.listTagsForResource("arn:aws:rds:us-east-1:123456789012:pg:some-parameter-group")); assertEquals("DBParameterGroupNotFound", absentGroup.getErrorCode()); - AwsException unsupportedType = assertThrows(AwsException.class, () -> + // Snapshots are tagged now too, so an absent one is a missing resource as well. + AwsException absentSnapshot = assertThrows(AwsException.class, () -> rdsService.listTagsForResource("arn:aws:rds:us-east-1:123456789012:snapshot:some-snapshot")); + assertEquals("DBSnapshotNotFound", absentSnapshot.getErrorCode()); + + AwsException unsupportedType = assertThrows(AwsException.class, () -> + rdsService.listTagsForResource("arn:aws:rds:us-east-1:123456789012:ri:some-reserved-instance")); assertEquals("InvalidParameterValue", unsupportedType.getErrorCode()); // The type is valid on real AWS; the message must present this as a Floci limitation. assertTrue(unsupportedType.getMessage().contains("not yet implemented by Floci")); @@ -2781,9 +2786,67 @@ class RdsServiceTest { assertEquals("mydb", snapshot.getDbInstanceIdentifier()); assertEquals(DatabaseEngine.POSTGRES, snapshot.getEngine()); assertEquals("available", snapshot.getStatus()); + assertEquals("arn:aws:rds:us-east-1:123456789012:snapshot:mysnap", snapshot.getDbSnapshotArn()); verify(containerManager).createPostgresSnapshot(any(), eq("admin")); } + @Test + void createDbSnapshotStoresTagsGivenAtCreation() { + rdsService.createDbInstance("mydb", "postgres", "13", + "admin", "password", "dbname", "db.t3.micro", + 20, false, null, null, null, null, false); + when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("MOCK_DUMP_DATA"); + + io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = + rdsService.createDbSnapshot("mysnap", "mydb", Map.of("owner", "platform")); + + assertEquals(Map.of("owner", "platform"), snapshot.getTags()); + assertEquals(Map.of("owner", "platform"), + rdsService.listTagsForResource(snapshot.getDbSnapshotArn())); + } + + @Test + void dbSnapshotTagsRoundTripAndMutateByArn() { + rdsService.createDbInstance("mydb", "postgres", "13", + "admin", "password", "dbname", "db.t3.micro", + 20, false, null, null, null, null, false); + when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("MOCK_DUMP_DATA"); + io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = + rdsService.createDbSnapshot("mysnap", "mydb"); + + rdsService.addTagsToResource(snapshot.getDbSnapshotArn(), Map.of("Name", "mysnap")); + assertEquals(Map.of("Name", "mysnap"), + rdsService.listTagsForResource(snapshot.getDbSnapshotArn())); + + rdsService.removeTagsFromResource(snapshot.getDbSnapshotArn(), List.of("Name")); + assertEquals(Map.of(), rdsService.listTagsForResource(snapshot.getDbSnapshotArn())); + } + + @Test + void dbSnapshotArnAndTagsAreScopedToTheRequestRegion() { + rdsService.createDbInstance("mydb", "postgres", "13", "admin", "password", "dbname", + "db.t3.micro", 20, false, null, null, null, null, false, false, null, + Map.of(), "us-west-2"); + when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("MOCK_DUMP_DATA"); + + io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = + rdsService.createDbSnapshot("mysnap", "mydb", Map.of("owner", "west-team"), "us-west-2"); + + assertEquals("arn:aws:rds:us-west-2:123456789012:snapshot:mysnap", snapshot.getDbSnapshotArn()); + + // Reachable and taggable through the region it was created in. + assertEquals(1, rdsService.describeDbSnapshots("mysnap", null, "us-west-2").size()); + assertEquals(Map.of("owner", "west-team"), + rdsService.listTagsForResource(snapshot.getDbSnapshotArn(), "us-west-2")); + rdsService.addTagsToResource(snapshot.getDbSnapshotArn(), Map.of("Name", "west-snap"), "us-west-2"); + assertEquals(Map.of("owner", "west-team", "Name", "west-snap"), + rdsService.listTagsForResource(snapshot.getDbSnapshotArn(), "us-west-2")); + + // A different region must not see or resolve another region's snapshot. + assertThrows(AwsException.class, () -> rdsService.describeDbSnapshots("mysnap", null, "us-east-1")); + assertTrue(rdsService.describeDbSnapshots(null, null, "us-east-1").isEmpty()); + } + @Test void createDbSnapshotThrowsOnDumpFailure() { rdsService.createDbInstance("mydb", "postgres", "13", @@ -2868,6 +2931,42 @@ class RdsServiceTest { assertEquals("snap1", inst1Result.iterator().next().getDbSnapshotIdentifier()); } + @Test + void describeDbSnapshotAttributesDefaultsToNoSharedAccounts() { + rdsService.createDbInstance("mydb", "postgres", "13", + "admin", "password", "dbname", "db.t3.micro", + 20, false, null, null, null, null, false); + when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("MOCK_DUMP_DATA"); + rdsService.createDbSnapshot("mysnap", "mydb"); + + io.github.hectorvent.floci.services.rds.model.DbSnapshot snapshot = + rdsService.describeDbSnapshotAttributes("mysnap"); + assertEquals(List.of(), snapshot.getRestoreAccountIds()); + + assertThrows(AwsException.class, () -> rdsService.describeDbSnapshotAttributes("missing-snap")); + } + + @Test + void modifyDbSnapshotAttributeAddsAndRemovesRestoreAccountIds() { + rdsService.createDbInstance("mydb", "postgres", "13", + "admin", "password", "dbname", "db.t3.micro", + 20, false, null, null, null, null, false); + when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("MOCK_DUMP_DATA"); + rdsService.createDbSnapshot("mysnap", "mydb"); + + io.github.hectorvent.floci.services.rds.model.DbSnapshot added = rdsService.modifyDbSnapshotAttribute( + "mysnap", "restore", List.of("111111111111", "222222222222"), List.of()); + assertEquals(List.of("111111111111", "222222222222"), added.getRestoreAccountIds()); + + io.github.hectorvent.floci.services.rds.model.DbSnapshot removed = rdsService.modifyDbSnapshotAttribute( + "mysnap", "restore", List.of(), List.of("111111111111")); + assertEquals(List.of("222222222222"), removed.getRestoreAccountIds()); + + AwsException badAttribute = assertThrows(AwsException.class, () -> + rdsService.modifyDbSnapshotAttribute("mysnap", "share", List.of("333333333333"), List.of())); + assertEquals("InvalidParameterValue", badAttribute.getErrorCode()); + } + @Test void failedInstanceRestoreClearsRuntimeStateAndReleasesItsEndpointPort() { InMemoryStorage instances = new InMemoryStorage<>(); diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index 4ad9b40298..ca8496125c 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -265,7 +265,7 @@ services: doc: docs/services/rds.md sources: - { path: src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java, mode: switch } - exclude_actions: [SubnetIds, VpcSecurityGroupIds, OptionsToRemove] + exclude_actions: [SubnetIds, VpcSecurityGroupIds, OptionsToRemove, ValuesToAdd, ValuesToRemove] - service: redshift doc: docs/services/redshift.md sources: