feat(dms): add replication subnet group lifecycle and tagging (#3630)

* feat(dms): add replication subnet group lifecycle

AWS DMS was entirely absent, so every terraform-aws-data-storage example
using aws_dms_replication_subnet_group failed at plan with
UnknownOperationException.

Adds a minimal dms service on AWS JSON 1.1 (X-Amz-Target prefix
AmazonDMSv20160101.) implementing CreateReplicationSubnetGroup,
DescribeReplicationSubnetGroups and DeleteReplicationSubnetGroup.
Subnets are resolved against the emulated EC2 service, so the VpcId and
Availability Zones a group reports are the ones its subnets actually
have, and AWS's own rules are enforced: the identifier is stored
lowercase, "default" is reserved, subnets must share a VPC, and a group
must cover at least two Availability Zones.

Tagging actions and replication instances, endpoints and tasks are out
of scope and still report UnknownOperationException.

* feat(dms): add resource tagging for replication subnet groups

Terraform's aws_dms_replication_subnet_group reads tags back through
ListTagsForResource, so without the tagging trio the resource could be
created but never read cleanly.

Adds ListTagsForResource, AddTagsToResource and RemoveTagsFromResource,
and stores the Tags member of CreateReplicationSubnetGroup with the
group. DMS does not return a subnet group ARN from describe, so the
provider builds arn:aws:dms:<region>:<account>:subgrp:<id> client side;
Floci parses that form back to the stored group and rejects anything
else, including another account's ARN, with ResourceNotFoundFault.

* fix(dms): address review findings

Emit IsReadOnly on ReplicationSubnetGroup, the one member of the model's
seven the response was missing. It is always false: a read-only group is
one DMS manages for a zero-ETL integration, which Floci does not emulate.

Fault a cross-Region ARN the way a cross-account one already faulted.
Storage is keyed by the caller's Region, so honouring an eu-west-1 ARN
from a us-east-1 caller silently reached the caller's own group of that
name rather than the one named.

Reject a subnet with no Availability Zone as InvalidSubnet. Set.copyOf
rejects nulls, so such a subnet raised a NullPointerException and
surfaced as a 500 instead of a client error.

Adds the user-realistic minimum-AZ case: two subnets sharing one AZ,
which the previous tests did not cover because they passed one subnet.

* fix(dms): reject wrongly-typed tag, filter and arn-list members

A present member of the wrong JSON type was coerced rather than
rejected. asText() on an object yields the empty string, so a tag whose
Value was an object stored an empty value and reported success; a
Filters or ResourceArnList member that was not a list was ignored
outright, which turned a filtered describe into an unfiltered one.

Every string member now answers SerializationException when it is
present with another JSON type, matching what AWS returns when a
json-1.1 member will not deserialize, and matching how Kinesis, Cognito
and KMS already report the same class of error here. An absent member
stays a parameter error: missing and mistyped are different faults.

* fix(dms): paginate DescribeReplicationSubnetGroups and validate the description

DescribeReplicationSubnetGroups returned every matching group in one response and
ignored both MaxRecords and Marker, so an SDK or Terraform paginator diverged from a
live account as soon as more than one page of groups existed.

Page through the shared opaque-cursor helper, keyed on the group identifier, so a
Marker stays resumable across groups created or deleted between requests. MaxRecords
defaults to 100 and is rejected outside the documented 20 to 100 range rather than
clamped, with the InvalidParameterValueException a live account answers. Marker is
emitted only while a further page remains: an SDK paginator treats any Marker as "ask
again", so one on the final page loops forever.

ReplicationSubnetGroupDescription now also enforces the model's printable-character
constraint, so a value carrying a control character such as 0x01 is rejected instead
of persisted.

* docs(dms): describe the Marker as the opaque cursor it is

* fix(test): DmsTest must compile at the sdk-test-java module's Java 17 target

List.getFirst() is a Java 21 SequencedCollection method. The main project
compiles at 21, but compatibility-tests/sdk-test-java pins source/target 17, and
DmsTest was the only file in that module using getFirst() -- so the native arm64
sdk-test-java image failed to build and every test in it was skipped.

This was not caught earlier because the previous head of this PR had no CI
rollup at all; the merge that made the branch mergeable is what first ran the
job. Replaced with get(0), which is what the rest of the module uses.

* style(test): import Objects and Collectors instead of naming them inline

AGENTS.md asks for imports rather than inline fully-qualified names.
DmsServiceTest had two: java.util.Objects::nonNull and
java.util.stream.Collectors.toMap. Neither was imported; both now are.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-21 19:45:01 -04:00
1 parent 09b1dc0803
commit 532bae5525
19 files changed
+1945 -3

No files matched your search

@@ -792,6 +792,12 @@ public interface EmulatorConfig {
CodeGuruReviewerServiceConfig codegurureviewer();
CodeArtifactServiceConfig codeartifact();
MarketplaceServiceConfig marketplace();
DmsServiceConfig dms();
}
interface DmsServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface CodeArtifactServiceConfig {
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.cloudhsmv2.CloudHsmV2JsonHandler;
import io.github.hectorvent.floci.services.codebuild.CodeBuildJsonHandler;
import io.github.hectorvent.floci.services.codedeploy.CodeDeployJsonHandler;
import io.github.hectorvent.floci.services.codepipeline.CodePipelineJsonHandler;
import io.github.hectorvent.floci.services.dms.DmsJsonHandler;
import io.github.hectorvent.floci.services.ecr.EcrJsonHandler;
import io.github.hectorvent.floci.services.transfer.TransferHandler;
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
@@ -141,6 +142,7 @@ public class AwsJson11Controller {
private final MarketplaceEntitlementController marketplaceEntitlementController;
private final MarketplaceMeteringController marketplaceMeteringController;
private final SageMakerJsonHandler sageMakerJsonHandler;
private final DmsJsonHandler dmsJsonHandler;
@Inject
public AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
@@ -195,7 +197,8 @@ public class AwsJson11Controller {
ServiceQuotasJsonHandler serviceQuotasJsonHandler,
MarketplaceEntitlementController marketplaceEntitlementController,
MarketplaceMeteringController marketplaceMeteringController,
SageMakerJsonHandler sageMakerJsonHandler) {
SageMakerJsonHandler sageMakerJsonHandler,
DmsJsonHandler dmsJsonHandler) {
this.objectMapper = objectMapper;
this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
this.catalog = catalog;
@@ -255,6 +258,7 @@ public class AwsJson11Controller {
this.marketplaceEntitlementController = marketplaceEntitlementController;
this.marketplaceMeteringController = marketplaceMeteringController;
this.sageMakerJsonHandler = sageMakerJsonHandler;
this.dmsJsonHandler = dmsJsonHandler;
}
@POST
@@ -367,6 +371,7 @@ public class AwsJson11Controller {
yield marketplaceMeteringController.handle(action, request, region);
}
case "sagemaker" -> sageMakerJsonHandler.handle(action, request, region);
case "dms" -> dmsJsonHandler.handle(action, request, region);
default -> null;
};
// catalog.matchTarget is protocol-agnostic: a JSON 1.0 target
@@ -733,7 +733,11 @@ public class ResolvedServiceCatalog {
"marketplace", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON, ServiceProtocol.JSON, ServiceProtocol.CBOR),
Set.of("AWSMPCommerceService_v20200301.", "AWSMPEntitlementService.", "AWSMPMeteringService."), Set.of("aws-marketplace"), Set.of("AWS Marketplace Entitlement Service"),
Set.of(MarketplaceCatalogController.class, MarketplaceDeploymentController.class, MarketplaceReportingController.class, MarketplaceDiscoveryController.class))
Set.of(MarketplaceCatalogController.class, MarketplaceDeploymentController.class, MarketplaceReportingController.class, MarketplaceDiscoveryController.class)),
descriptor("dms", "dms", config.services().dms().enabled(), true,
"dms", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("AmazonDMSv20160101."), Set.of("dms"), Set.of(), Set.of())
));
}
@@ -0,0 +1,100 @@
package io.github.hectorvent.floci.services.dms;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.services.dms.model.ReplicationSubnetGroup;
import io.github.hectorvent.floci.services.dms.model.ResourceTag;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
@ApplicationScoped
public class DmsJsonHandler {
private final DmsService service;
private final ObjectMapper objectMapper;
@Inject
public DmsJsonHandler(DmsService service, ObjectMapper objectMapper) {
this.service = service;
this.objectMapper = objectMapper;
}
public Response handle(String action, JsonNode request, String region) {
return switch (action) {
case "CreateReplicationSubnetGroup" -> {
ObjectNode response = objectMapper.createObjectNode();
response.set("ReplicationSubnetGroup",
subnetGroup(service.createReplicationSubnetGroup(request, region)));
yield Response.ok(response).build();
}
case "DescribeReplicationSubnetGroups" -> {
PaginatedResult<ReplicationSubnetGroup> page =
service.describeReplicationSubnetGroups(request, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode items = response.putArray("ReplicationSubnetGroups");
page.items().forEach(group -> items.add(subnetGroup(group)));
// Marker is present only while another page remains: an SDK paginator treats any
// Marker at all as "ask again", so emitting one on the final page loops forever.
if (page.nextToken() != null) {
response.put("Marker", page.nextToken());
}
yield Response.ok(response).build();
}
case "DeleteReplicationSubnetGroup" -> {
service.deleteReplicationSubnetGroup(request, region);
yield Response.ok(objectMapper.createObjectNode()).build();
}
case "ListTagsForResource" -> {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode tagList = response.putArray("TagList");
service.listTagsForResource(request, region).forEach(tag -> tagList.add(tagNode(tag)));
yield Response.ok(response).build();
}
case "AddTagsToResource" -> {
service.addTagsToResource(request, region);
yield Response.ok(objectMapper.createObjectNode()).build();
}
case "RemoveTagsFromResource" -> {
service.removeTagsFromResource(request, region);
yield Response.ok(objectMapper.createObjectNode()).build();
}
default -> null;
};
}
private ObjectNode tagNode(ResourceTag tag) {
ObjectNode node = objectMapper.createObjectNode();
node.put("Key", tag.key());
node.put("Value", tag.value());
if (tag.resourceArn() != null) {
node.put("ResourceArn", tag.resourceArn());
}
return node;
}
private ObjectNode subnetGroup(ReplicationSubnetGroup group) {
ObjectNode node = objectMapper.createObjectNode();
node.put("ReplicationSubnetGroupIdentifier", group.getReplicationSubnetGroupIdentifier());
node.put("ReplicationSubnetGroupDescription", group.getReplicationSubnetGroupDescription());
node.put("VpcId", group.getVpcId());
node.put("SubnetGroupStatus", group.getSubnetGroupStatus());
ArrayNode subnets = node.putArray("Subnets");
group.getSubnetIds().forEach(subnetId -> {
ObjectNode subnet = subnets.addObject();
subnet.put("SubnetIdentifier", subnetId);
subnet.putObject("SubnetAvailabilityZone")
.put("Name", group.getSubnetAvailabilityZones().get(subnetId));
subnet.put("SubnetStatus", "Active");
});
ArrayNode networkTypes = node.putArray("SupportedNetworkTypes");
group.getSupportedNetworkTypes().forEach(networkTypes::add);
// Always false: a read-only group is one DMS manages for a zero-ETL integration, which
// Floci does not emulate, so every group here is caller-owned and modifiable.
node.put("IsReadOnly", false);
return node;
}
}
@@ -0,0 +1,456 @@
package io.github.hectorvent.floci.services.dms;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.dms.model.ReplicationSubnetGroup;
import io.github.hectorvent.floci.services.dms.model.ResourceTag;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.regex.Pattern;
@ApplicationScoped
public class DmsService implements Resettable {
private static final Pattern SUBNET_GROUP_IDENTIFIER = Pattern.compile("[A-Za-z0-9._-]+");
private static final String SUBNET_GROUP_ID_FILTER = "replication-subnet-group-id";
private static final int MINIMUM_AVAILABILITY_ZONES = 2;
private static final String SUBNET_GROUP_ARN_RESOURCE_TYPE = "subgrp";
private static final int DEFAULT_MAX_RECORDS = 100;
private static final int MINIMUM_MAX_RECORDS = 20;
private static final int MAXIMUM_MAX_RECORDS = 100;
private static final Set<String> RESERVED_TAG_PREFIXES = Set.of("aws:", "dms:");
private final AccountAwareStorageBackend<ReplicationSubnetGroup> subnetGroups;
private final Ec2Service ec2Service;
private final RegionResolver regionResolver;
@Inject
public DmsService(StorageFactory storageFactory, Ec2Service ec2Service, RegionResolver regionResolver) {
this.subnetGroups = storageFactory.create("dms", "dms-replication-subnet-groups.json",
new TypeReference<Map<String, ReplicationSubnetGroup>>() {});
this.ec2Service = ec2Service;
this.regionResolver = regionResolver;
}
public synchronized ReplicationSubnetGroup createReplicationSubnetGroup(JsonNode request, String region) {
String identifier = requireIdentifier(request);
String description = requireDescription(request);
List<String> subnetIds = requireSubnetIds(request);
if (subnetGroups.get(storageKey(region, identifier)).isPresent()) {
throw new AwsException("ResourceAlreadyExistsFault",
"The resource you are attempting to create already exists.", 400);
}
ReplicationSubnetGroup group = buildSubnetGroup(identifier, description, subnetIds, region);
group.setTags(readTags(request.get("Tags")));
subnetGroups.put(storageKey(region, identifier), group);
return group;
}
/**
* Pages by identifier through the shared opaque-cursor helper, so {@code Marker} stays
* resumable when a group is created or deleted between requests. DMS documents a default
* {@code MaxRecords} of 100 and a valid range of 20 to 100, and rejects a value outside that
* range rather than clamping it.
*/
public PaginatedResult<ReplicationSubnetGroup> describeReplicationSubnetGroups(JsonNode request, String region) {
Integer maxRecords = maxRecords(request);
String marker = text(request, "Marker");
List<String> requestedIdentifiers = identifierFilters(request);
List<ReplicationSubnetGroup> matching;
if (!requestedIdentifiers.isEmpty()) {
matching = requestedIdentifiers.stream()
.map(identifier -> subnetGroups.get(storageKey(region, identifier))
.orElseThrow(() -> notFound(identifier)))
.toList();
} else {
matching = subnetGroups.scan(key -> key.startsWith(region + "::"));
}
return Pagination.paginate(matching, ReplicationSubnetGroup::getReplicationSubnetGroupIdentifier,
maxRecords, marker, DEFAULT_MAX_RECORDS, MAXIMUM_MAX_RECORDS,
"InvalidParameterValueException");
}
public synchronized void deleteReplicationSubnetGroup(JsonNode request, String region) {
String identifier = requireIdentifier(request);
String key = storageKey(region, identifier);
if (subnetGroups.get(key).isEmpty()) {
throw notFound(identifier);
}
subnetGroups.delete(key);
}
public List<ResourceTag> listTagsForResource(JsonNode request, String region) {
List<String> arnList = arnList(request);
if (!arnList.isEmpty()) {
List<ResourceTag> tags = new ArrayList<>();
for (String arn : arnList) {
resolveByArn(arn, region).getTags()
.forEach((key, value) -> tags.add(new ResourceTag(arn, key, value)));
}
return tags;
}
String resourceArn = requireResourceArn(request);
return resolveByArn(resourceArn, region).getTags().entrySet().stream()
.map(entry -> new ResourceTag(null, entry.getKey(), entry.getValue()))
.toList();
}
public synchronized void addTagsToResource(JsonNode request, String region) {
String resourceArn = requireResourceArn(request);
JsonNode tagsNode = request == null ? null : request.get("Tags");
if (tagsNode == null || tagsNode.isNull()) {
throw invalidParameter("The parameter Tags must be provided.");
}
Map<String, String> added = readTags(tagsNode);
updateTags(resourceArn, region, tags -> tags.putAll(added));
}
public synchronized void removeTagsFromResource(JsonNode request, String region) {
String resourceArn = requireResourceArn(request);
JsonNode keysNode = request == null ? null : request.get("TagKeys");
if (keysNode == null || keysNode.isNull()) {
throw invalidParameter("The parameter TagKeys must be provided.");
}
List<String> keys = stringList(keysNode, "TagKeys");
updateTags(resourceArn, region, tags -> keys.forEach(tags::remove));
}
@Override
public void clear() {
subnetGroups.clear();
}
private ReplicationSubnetGroup buildSubnetGroup(String identifier, String description,
List<String> subnetIds, String region) {
Map<String, Subnet> resolved = new LinkedHashMap<>();
ec2Service.describeSubnets(region, subnetIds, Map.of())
.forEach(subnet -> resolved.put(subnet.getSubnetId(), subnet));
List<String> requested = subnetIds.stream().distinct().toList();
List<String> missing = requested.stream().filter(id -> !resolved.containsKey(id)).toList();
if (!missing.isEmpty()) {
throw new AwsException("InvalidSubnet",
"The subnet provided is invalid: " + missing + ".", 400);
}
// Response order follows the request rather than storage iteration order, so a describe
// that follows a create returns the same subnet ordering every time.
Map<String, String> availabilityZones = new LinkedHashMap<>();
for (String subnetId : requested) {
String availabilityZone = resolved.get(subnetId).getAvailabilityZone();
if (availabilityZone == null) {
throw new AwsException("InvalidSubnet",
"Subnet " + subnetId + " has no Availability Zone.", 400);
}
availabilityZones.put(subnetId, availabilityZone);
}
String vpcId = resolved.get(requested.getFirst()).getVpcId();
boolean sameVpc = resolved.values().stream()
.map(Subnet::getVpcId)
.filter(Objects::nonNull)
.allMatch(vpcId::equals);
if (!sameVpc) {
throw new AwsException("InvalidSubnet",
"The subnets provided for replication subnet group " + identifier
+ " belong to more than one VPC.", 400);
}
if (Set.copyOf(availabilityZones.values()).size() < MINIMUM_AVAILABILITY_ZONES) {
throw new AwsException("ReplicationSubnetGroupDoesNotCoverEnoughAZs",
"The replication subnet group does not cover enough Availability Zones (AZs)."
+ " Edit the replication subnet group and add more AZs.", 400);
}
ReplicationSubnetGroup group = new ReplicationSubnetGroup();
group.setReplicationSubnetGroupIdentifier(identifier);
group.setReplicationSubnetGroupDescription(description);
group.setVpcId(vpcId);
group.setSubnetGroupStatus("Complete");
group.setSubnetIds(requested);
group.setSubnetAvailabilityZones(availabilityZones);
group.setSupportedNetworkTypes(List.of("IPV4"));
return group;
}
/**
* AWS stores the identifier as a lowercase string, so every lookup normalises the same way:
* a group created as "MyGroup" is described and deleted as "mygroup".
*/
private static String requireIdentifier(JsonNode request) {
String value = text(request, "ReplicationSubnetGroupIdentifier");
if (value == null || value.isBlank()) {
throw invalidParameter("The parameter ReplicationSubnetGroupIdentifier must be provided"
+ " and must not be blank.");
}
String identifier = value.toLowerCase(Locale.ROOT);
if (identifier.length() > 255 || !SUBNET_GROUP_IDENTIFIER.matcher(identifier).matches()) {
throw invalidParameter("ReplicationSubnetGroupIdentifier must contain no more than 255"
+ " alphanumeric characters, periods, underscores, or hyphens.");
}
if ("default".equals(identifier)) {
throw invalidParameter("ReplicationSubnetGroupIdentifier must not be \"default\".");
}
return identifier;
}
/**
* A description carrying a control character such as 0x01 is rejected here rather than
* persisted, per the review of the upstream PR; AWS rejects non-printable control characters
* in this member. Blank and absent stay the same parameter error they were.
*/
private static String requireDescription(JsonNode request) {
String description = text(request, "ReplicationSubnetGroupDescription");
if (description == null || description.isBlank()) {
throw invalidParameter("The parameter ReplicationSubnetGroupDescription must be provided"
+ " and must not be blank.");
}
if (description.chars().anyMatch(Character::isISOControl)) {
throw invalidParameter("The parameter ReplicationSubnetGroupDescription must contain only"
+ " printable characters.");
}
return description;
}
/**
* {@code MaxRecords} is modelled as an integer, so a non-integer value is a serialization error
* rather than a parameter one. A value outside 20 to 100 is rejected, not clamped, which is
* what a live account does.
*/
private static Integer maxRecords(JsonNode request) {
JsonNode node = request == null ? null : request.get("MaxRecords");
if (node == null || node.isNull()) {
return null;
}
if (!node.isIntegralNumber() || !node.canConvertToInt()) {
throw serialization("MaxRecords must be an integer.");
}
int value = node.intValue();
if (value < MINIMUM_MAX_RECORDS || value > MAXIMUM_MAX_RECORDS) {
throw invalidParameter("Invalid value " + value + " for MaxRecords. Must be between "
+ MINIMUM_MAX_RECORDS + " and " + MAXIMUM_MAX_RECORDS + ".");
}
return value;
}
private static List<String> requireSubnetIds(JsonNode request) {
JsonNode node = request == null ? null : request.get("SubnetIds");
if (node == null || node.isNull()) {
throw invalidParameter("The parameter SubnetIds must be provided and must not be empty.");
}
if (!node.isArray()) {
throw serialization("SubnetIds must be a list of strings.");
}
if (node.isEmpty()) {
throw invalidParameter("The parameter SubnetIds must be provided and must not be empty.");
}
List<String> subnetIds = stringList(node, "SubnetIds");
if (subnetIds.stream().anyMatch(String::isBlank)) {
throw invalidParameter("The parameter SubnetIds must contain subnet identifiers.");
}
return subnetIds;
}
private static List<String> identifierFilters(JsonNode request) {
JsonNode filters = request == null ? null : request.get("Filters");
if (filters == null || filters.isNull()) {
return List.of();
}
if (!filters.isArray()) {
throw serialization("Filters must be a list of Name and Values pairs.");
}
List<String> identifiers = new ArrayList<>();
for (JsonNode filter : filters) {
if (!filter.isObject()) {
throw serialization("Filters must be a list of Name and Values pairs.");
}
String name = text(filter, "Name");
if (!SUBNET_GROUP_ID_FILTER.equals(name)) {
throw invalidParameter("Invalid filter: " + name + ".");
}
JsonNode values = filter.get("Values");
if (values == null || values.isNull()) {
throw invalidParameter("The filter " + SUBNET_GROUP_ID_FILTER + " must have values.");
}
if (!values.isArray()) {
throw serialization("Filter Values must be a list of strings.");
}
if (values.isEmpty()) {
throw invalidParameter("The filter " + SUBNET_GROUP_ID_FILTER + " must have values.");
}
stringList(values, "Filter Values")
.forEach(value -> identifiers.add(value.toLowerCase(Locale.ROOT)));
}
return identifiers;
}
private static AwsException notFound(String identifier) {
return new AwsException("ResourceNotFoundFault",
"Replication subnet group " + identifier + " not found.", 400);
}
private static AwsException invalidParameter(String message) {
return new AwsException("InvalidParameterValueException", message, 400);
}
/**
* Reads a string member. Absent or explicitly null yields null; a member of any other JSON type
* is a SerializationException, which is what AWS returns when a json-1.1 member will not
* deserialize to its modelled type. Coercing it instead (asText on an object yields "") would
* silently store a wrong value.
*/
private static String text(JsonNode request, String field) {
JsonNode node = request == null ? null : request.get(field);
if (node == null || node.isNull()) {
return null;
}
if (!node.isTextual()) {
throw serialization(field + " must be a string.");
}
return node.textValue();
}
private static List<String> stringList(JsonNode array, String field) {
if (!array.isArray()) {
throw serialization(field + " must be a list of strings.");
}
List<String> values = new ArrayList<>();
for (JsonNode element : array) {
if (!element.isTextual()) {
throw serialization(field + " must be a list of strings.");
}
values.add(element.textValue());
}
return values;
}
private static AwsException serialization(String message) {
return new AwsException("SerializationException", message, 400);
}
private static String storageKey(String region, String identifier) {
return region + "::" + identifier;
}
private void updateTags(String resourceArn, String region,
Consumer<Map<String, String>> mutation) {
String key = subnetGroupKeyForArn(resourceArn, region);
ReplicationSubnetGroup group = subnetGroups.get(key).orElseThrow(() -> notFoundForArn(resourceArn));
Map<String, String> tags = new LinkedHashMap<>(group.getTags());
mutation.accept(tags);
group.setTags(tags);
subnetGroups.put(key, group);
}
private ReplicationSubnetGroup resolveByArn(String resourceArn, String region) {
return subnetGroups.get(subnetGroupKeyForArn(resourceArn, region))
.orElseThrow(() -> notFoundForArn(resourceArn));
}
/**
* DescribeReplicationSubnetGroups does not return an ARN, so Terraform builds
* {@code arn:aws:dms:<region>:<account>:subgrp:<id>} itself and tags against that. Anything
* that is not such an ARN names no DMS resource Floci holds, which is a ResourceNotFoundFault
* rather than a parameter error.
*
* <p>An ARN naming another account or another Region is treated the same way. Tagging is not a
* cross-account or cross-Region operation on AWS, and here it cannot be one either: storage is
* scoped to the caller's account and keyed by the caller's Region, so honouring a foreign ARN
* would silently reach the caller's own group of that name instead of the one named.
*/
private String subnetGroupKeyForArn(String resourceArn, String callerRegion) {
AwsArnUtils.Arn arn;
try {
arn = AwsArnUtils.parse(resourceArn);
} catch (IllegalArgumentException e) {
throw notFoundForArn(resourceArn);
}
String[] resource = arn.resource().split(":", 2);
if (!"dms".equals(arn.service()) || resource.length != 2
|| !SUBNET_GROUP_ARN_RESOURCE_TYPE.equals(resource[0]) || resource[1].isBlank()) {
throw notFoundForArn(resourceArn);
}
if (!arn.accountId().isBlank() && !arn.accountId().equals(regionResolver.getAccountId())) {
throw notFoundForArn(resourceArn);
}
if (arn.region() != null && !arn.region().isBlank() && !arn.region().equals(callerRegion)) {
throw notFoundForArn(resourceArn);
}
return storageKey(callerRegion, resource[1].toLowerCase(Locale.ROOT));
}
private static List<String> arnList(JsonNode request) {
JsonNode node = request == null ? null : request.get("ResourceArnList");
if (node == null || node.isNull()) {
return List.of();
}
if (!node.isArray()) {
throw serialization("ResourceArnList must be a list of strings.");
}
return stringList(node, "ResourceArnList");
}
private static String requireResourceArn(JsonNode request) {
String resourceArn = text(request, "ResourceArn");
if (resourceArn == null || resourceArn.isBlank()) {
throw invalidParameter("The parameter ResourceArn must be provided and must not be blank.");
}
return resourceArn;
}
private static Map<String, String> readTags(JsonNode node) {
Map<String, String> tags = new LinkedHashMap<>();
if (node == null || node.isNull()) {
return tags;
}
if (!node.isArray()) {
throw serialization("Tags must be a list of Key and Value pairs.");
}
for (JsonNode element : node) {
if (!element.isObject()) {
throw serialization("Tags must be a list of Key and Value pairs.");
}
String key = text(element, "Key");
String value = text(element, "Value");
if (key == null || key.isEmpty() || key.length() > 128 || isReserved(key)) {
throw invalidParameter("Tag keys must be 1-128 characters and must not start with"
+ " \"aws:\" or \"dms:\".");
}
String tagValue = value == null ? "" : value;
if (tagValue.length() > 256 || isReserved(tagValue)) {
throw invalidParameter("Tag values must be at most 256 characters and must not start"
+ " with \"aws:\" or \"dms:\".");
}
tags.put(key, tagValue);
}
return tags;
}
private static boolean isReserved(String value) {
return RESERVED_TAG_PREFIXES.stream().anyMatch(value::startsWith);
}
private static AwsException notFoundForArn(String resourceArn) {
return new AwsException("ResourceNotFoundFault",
"Resource " + resourceArn + " not found.", 400);
}
}
@@ -0,0 +1,95 @@
package io.github.hectorvent.floci.services.dms.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReplicationSubnetGroup {
private String replicationSubnetGroupIdentifier;
private String replicationSubnetGroupDescription;
private String vpcId;
private String subnetGroupStatus = "Complete";
private List<String> subnetIds = new ArrayList<>();
private Map<String, String> subnetAvailabilityZones = new LinkedHashMap<>();
private List<String> supportedNetworkTypes = new ArrayList<>();
private Map<String, String> tags = new LinkedHashMap<>();
public ReplicationSubnetGroup() {
}
public String getReplicationSubnetGroupIdentifier() {
return replicationSubnetGroupIdentifier;
}
public void setReplicationSubnetGroupIdentifier(String replicationSubnetGroupIdentifier) {
this.replicationSubnetGroupIdentifier = replicationSubnetGroupIdentifier;
}
public String getReplicationSubnetGroupDescription() {
return replicationSubnetGroupDescription;
}
public void setReplicationSubnetGroupDescription(String replicationSubnetGroupDescription) {
this.replicationSubnetGroupDescription = replicationSubnetGroupDescription;
}
public String getVpcId() {
return vpcId;
}
public void setVpcId(String vpcId) {
this.vpcId = vpcId;
}
public String getSubnetGroupStatus() {
return subnetGroupStatus;
}
public void setSubnetGroupStatus(String subnetGroupStatus) {
this.subnetGroupStatus = subnetGroupStatus;
}
public List<String> getSubnetIds() {
return List.copyOf(subnetIds);
}
public void setSubnetIds(List<String> subnetIds) {
this.subnetIds = subnetIds != null ? new ArrayList<>(subnetIds) : new ArrayList<>();
}
public Map<String, String> getSubnetAvailabilityZones() {
return Map.copyOf(subnetAvailabilityZones);
}
public void setSubnetAvailabilityZones(Map<String, String> subnetAvailabilityZones) {
this.subnetAvailabilityZones = subnetAvailabilityZones != null
? new LinkedHashMap<>(subnetAvailabilityZones)
: new LinkedHashMap<>();
}
public List<String> getSupportedNetworkTypes() {
return List.copyOf(supportedNetworkTypes);
}
public void setSupportedNetworkTypes(List<String> supportedNetworkTypes) {
this.supportedNetworkTypes = supportedNetworkTypes != null
? new ArrayList<>(supportedNetworkTypes)
: new ArrayList<>();
}
public Map<String, String> getTags() {
return Collections.unmodifiableMap(new LinkedHashMap<>(tags));
}
public void setTags(Map<String, String> tags) {
this.tags = tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>();
}
}
@@ -0,0 +1,9 @@
package io.github.hectorvent.floci.services.dms.model;
/**
* One tag as DMS returns it from {@code ListTagsForResource}. {@code resourceArn} is null for a
* single-ARN request and set when the caller passed {@code ResourceArnList}, which is the only
* form where AWS documents the field as part of the response.
*/
public record ResourceTag(String resourceArn, String key, String value) {
}