Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(tagging): implement Resource Groups Tagging API (#459)

Navaneesh Kumar2c25c108c175
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index d7eaa6990a..1a5ce8d17b 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -231,6 +231,7 @@ public interface EmulatorConfig {
AppConfigServiceConfig appconfig();
AppConfigDataServiceConfig appconfigdata();
EcrServiceConfig ecr();
+ ResourceGroupsTaggingServiceConfig tagging();
}
interface SsmServiceConfig {
@@ -460,6 +461,11 @@ public interface EmulatorConfig {
int defaultCpuUnits();
}
+ interface ResourceGroupsTaggingServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+ }
+
interface EcrServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
index e8cb72a67c..bbc66e1a25 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.services.ecr.EcrJsonHandler;
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
import io.github.hectorvent.floci.services.firehose.FirehoseJsonHandler;
import io.github.hectorvent.floci.services.glue.GlueJsonHandler;
+import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingJsonHandler;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2JsonHandler;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsHandler;
import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler;
@@ -54,6 +55,7 @@ public class AwsJson11Controller {
private final GlueJsonHandler glueJsonHandler;
private final AthenaJsonHandler athenaJsonHandler;
private final FirehoseJsonHandler firehoseJsonHandler;
+ private final ResourceGroupsTaggingJsonHandler resourceGroupsTaggingJsonHandler;
@Inject
public AwsJson11Controller(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
@@ -67,7 +69,8 @@ public class AwsJson11Controller {
AcmJsonHandler acmJsonHandler, EcsJsonHandler ecsJsonHandler,
EcrJsonHandler ecrJsonHandler, GlueJsonHandler glueJsonHandler,
AthenaJsonHandler athenaJsonHandler,
- FirehoseJsonHandler firehoseJsonHandler) {
+ FirehoseJsonHandler firehoseJsonHandler,
+ ResourceGroupsTaggingJsonHandler resourceGroupsTaggingJsonHandler) {
this.objectMapper = objectMapper;
this.catalog = catalog;
this.regionResolver = regionResolver;
@@ -85,6 +88,7 @@ public class AwsJson11Controller {
this.glueJsonHandler = glueJsonHandler;
this.athenaJsonHandler = athenaJsonHandler;
this.firehoseJsonHandler = firehoseJsonHandler;
+ this.resourceGroupsTaggingJsonHandler = resourceGroupsTaggingJsonHandler;
}
@POST
@@ -127,6 +131,7 @@ public class AwsJson11Controller {
case "glue" -> glueJsonHandler.handle(action, request, region);
case "athena" -> athenaJsonHandler.handle(action, request, region);
case "firehose" -> firehoseJsonHandler.handle(action, request, region);
+ case "tagging" -> resourceGroupsTaggingJsonHandler.handle(action, request, region);
default -> null;
};
// catalog.matchTarget is protocol-agnostic: a JSON 1.0 target
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index b340c6e6f8..5af5441b08 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -177,7 +177,11 @@ public class ResolvedServiceCatalog {
descriptor("ecr", "ecr", config.services().ecr().enabled(), true,
null, null, 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
- Set.of("AmazonEC2ContainerRegistry_V20150921."), Set.of("ecr"), Set.of(), Set.of())
+ Set.of("AmazonEC2ContainerRegistry_V20150921."), Set.of("ecr"), Set.of(), Set.of()),
+ descriptor("tagging", "tagging", config.services().tagging().enabled(), true,
+ null, null, 5000L, null, ServiceProtocol.JSON,
+ protocols(ServiceProtocol.JSON),
+ Set.of("ResourceGroupsTaggingAPI_20170126."), Set.of("tagging"), Set.of(), Set.of())
));
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingJsonHandler.java
new file mode 100644
index 0000000000..eef9e96d43
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingJsonHandler.java
@@ -0,0 +1,158 @@
+package io.github.hectorvent.floci.services.resourcegroupstagging;
+
+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.AwsErrorResponse;
+import io.github.hectorvent.floci.services.resourcegroupstagging.model.ResourceTagMapping;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Response;
+
+import java.util.*;
+
+@ApplicationScoped
+public class ResourceGroupsTaggingJsonHandler {
+
+ private final ResourceGroupsTaggingService service;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public ResourceGroupsTaggingJsonHandler(ResourceGroupsTaggingService service, ObjectMapper objectMapper) {
+ this.service = service;
+ this.objectMapper = objectMapper;
+ }
+
+ public Response handle(String action, JsonNode request, String region) {
+ return switch (action) {
+ case "GetResources" -> handleGetResources(request, region);
+ case "TagResources" -> handleTagResources(request, region);
+ case "UntagResources" -> handleUntagResources(request, region);
+ case "GetTagKeys" -> handleGetTagKeys(request, region);
+ case "GetTagValues" -> handleGetTagValues(request, region);
+ default -> Response.status(400)
+ .entity(new AwsErrorResponse("UnsupportedOperation",
+ "Operation " + action + " is not supported."))
+ .build();
+ };
+ }
+
+ // ─── GetResources ──────────────────────────────────────────────────────────
+
+ private Response handleGetResources(JsonNode request, String region) {
+ List<String> arnList = toStringList(request.path("ResourceARNList"));
+ List<ResourceGroupsTaggingService.TagFilter> tagFilters = parseTagFilters(request.path("TagFilters"));
+ List<String> resourceTypeFilters = toStringList(request.path("ResourceTypeFilters"));
+ String paginationToken = request.path("PaginationToken").asText(null);
+ int resourcesPerPage = request.path("ResourcesPerPage").asInt(0);
+
+ ResourceGroupsTaggingService.PageResult result = service.getResources(
+ arnList, tagFilters, resourceTypeFilters, paginationToken, resourcesPerPage, region);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode list = objectMapper.createArrayNode();
+ for (ResourceTagMapping mapping : result.items()) {
+ ObjectNode item = objectMapper.createObjectNode();
+ item.put("ResourceARN", mapping.getResourceArn());
+ item.set("Tags", tagsToArray(mapping.getTags()));
+ list.add(item);
+ }
+ response.set("ResourceTagMappingList", list);
+ response.put("PaginationToken", result.nextPaginationToken() != null ? result.nextPaginationToken() : "");
+ return Response.ok(response).build();
+ }
+
+ // ─── TagResources ──────────────────────────────────────────────────────────
+
+ private Response handleTagResources(JsonNode request, String region) {
+ List<String> arns = toStringList(request.path("ResourceARNList"));
+ Map<String, String> tags = new LinkedHashMap<>();
+ request.path("Tags").fields().forEachRemaining(e -> tags.put(e.getKey(), e.getValue().asText()));
+
+ service.tagResources(arns, tags, region);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ // FailedResourcesMap is empty on success
+ response.set("FailedResourcesMap", objectMapper.createObjectNode());
+ return Response.ok(response).build();
+ }
+
+ // ─── UntagResources ────────────────────────────────────────────────────────
+
+ private Response handleUntagResources(JsonNode request, String region) {
+ List<String> arns = toStringList(request.path("ResourceARNList"));
+ List<String> tagKeys = toStringList(request.path("TagKeys"));
+
+ service.untagResources(arns, tagKeys, region);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("FailedResourcesMap", objectMapper.createObjectNode());
+ return Response.ok(response).build();
+ }
+
+ // ─── GetTagKeys ────────────────────────────────────────────────────────────
+
+ private Response handleGetTagKeys(JsonNode request, String region) {
+ String paginationToken = request.path("PaginationToken").asText(null);
+ int maxResults = request.path("MaxResults").asInt(0);
+
+ ResourceGroupsTaggingService.PageResult result = service.getTagKeys(paginationToken, maxResults, region);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode keys = objectMapper.createArrayNode();
+ result.items().forEach(m -> keys.add(m.getResourceArn())); // ARN field repurposed for key string
+ response.set("TagKeys", keys);
+ response.put("PaginationToken", result.nextPaginationToken() != null ? result.nextPaginationToken() : "");
+ return Response.ok(response).build();
+ }
+
+ // ─── GetTagValues ──────────────────────────────────────────────────────────
+
+ private Response handleGetTagValues(JsonNode request, String region) {
+ String key = request.path("Key").asText();
+ String paginationToken = request.path("PaginationToken").asText(null);
+ int maxResults = request.path("MaxResults").asInt(0);
+
+ ResourceGroupsTaggingService.PageResult result = service.getTagValues(key, paginationToken, maxResults, region);
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode values = objectMapper.createArrayNode();
+ result.items().forEach(m -> values.add(m.getResourceArn())); // ARN field repurposed for value string
+ response.set("TagValues", values);
+ response.put("PaginationToken", result.nextPaginationToken() != null ? result.nextPaginationToken() : "");
+ return Response.ok(response).build();
+ }
+
+ // ─── Helpers ───────────────────────────────────────────────────────────────
+
+ private List<String> toStringList(JsonNode node) {
+ List<String> result = new ArrayList<>();
+ if (node != null && node.isArray()) {
+ node.forEach(n -> result.add(n.asText()));
+ }
+ return result;
+ }
+
+ private List<ResourceGroupsTaggingService.TagFilter> parseTagFilters(JsonNode node) {
+ List<ResourceGroupsTaggingService.TagFilter> result = new ArrayList<>();
+ if (node == null || !node.isArray()) return result;
+ for (JsonNode filter : node) {
+ String key = filter.path("Key").asText();
+ List<String> values = toStringList(filter.path("Values"));
+ result.add(new ResourceGroupsTaggingService.TagFilter(key, values));
+ }
+ return result;
+ }
+
+ private ArrayNode tagsToArray(Map<String, String> tags) {
+ ArrayNode arr = objectMapper.createArrayNode();
+ tags.forEach((k, v) -> {
+ ObjectNode tag = objectMapper.createObjectNode();
+ tag.put("Key", k);
+ tag.put("Value", v);
+ arr.add(tag);
+ });
+ return arr;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingService.java b/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingService.java
new file mode 100644
index 0000000000..38ad6f4d45
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingService.java
@@ -0,0 +1,186 @@
+package io.github.hectorvent.floci.services.resourcegroupstagging;
+
+import io.github.hectorvent.floci.services.resourcegroupstagging.model.ResourceTagMapping;
+import jakarta.enterprise.context.ApplicationScoped;
+
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.stream.Collectors;
+
+@ApplicationScoped
+public class ResourceGroupsTaggingService {
+
+ // region::arn → ResourceTagMapping
+ private final Map<String, ResourceTagMapping> store = new ConcurrentHashMap<>();
+
+ private String key(String region, String arn) {
+ return region + "::" + arn;
+ }
+
+ // ─── TagResources ──────────────────────────────────────────────────────────
+
+ public void tagResources(List<String> resourceArns, Map<String, String> tags, String region) {
+ for (String arn : resourceArns) {
+ store.computeIfAbsent(key(region, arn), k -> new ResourceTagMapping(arn))
+ .getTags().putAll(tags);
+ }
+ }
+
+ // ─── UntagResources ────────────────────────────────────────────────────────
+
+ public void untagResources(List<String> resourceArns, List<String> tagKeys, String region) {
+ for (String arn : resourceArns) {
+ ResourceTagMapping mapping = store.get(key(region, arn));
+ if (mapping != null) {
+ tagKeys.forEach(mapping.getTags()::remove);
+ }
+ }
+ }
+
+ // ─── GetResources ──────────────────────────────────────────────────────────
+
+ public record TagFilter(String key, List<String> values) {}
+
+ public record PageResult(List<ResourceTagMapping> items, String nextPaginationToken) {}
+
+ public PageResult getResources(List<String> resourceArnList,
+ List<TagFilter> tagFilters,
+ List<String> resourceTypeFilters,
+ String paginationToken,
+ int resourcesPerPage,
+ String region) {
+ List<ResourceTagMapping> all = store.values().stream()
+ .filter(m -> {
+ // Derive the region from the ARN (arn:aws:svc:region:acct:type/id)
+ String[] parts = m.getResourceArn().split(":", 6);
+ if (parts.length >= 4) {
+ String arnRegion = parts[3];
+ if (!arnRegion.isEmpty() && !arnRegion.equals(region)) return false;
+ }
+ return true;
+ })
+ .filter(m -> resourceArnList == null || resourceArnList.isEmpty()
+ || resourceArnList.contains(m.getResourceArn()))
+ .filter(m -> matchesTagFilters(m, tagFilters))
+ .filter(m -> matchesResourceTypeFilters(m, resourceTypeFilters))
+ .sorted(Comparator.comparing(ResourceTagMapping::getResourceArn))
+ .collect(Collectors.toList());
+
+ int offset = decodePaginationToken(paginationToken);
+ int pageSize = (resourcesPerPage > 0) ? resourcesPerPage : 100;
+ int end = Math.min(offset + pageSize, all.size());
+ List<ResourceTagMapping> page = all.subList(offset, end);
+ String nextToken = (end < all.size()) ? encodePaginationToken(end) : null;
+ return new PageResult(page, nextToken);
+ }
+
+ private boolean matchesTagFilters(ResourceTagMapping m, List<TagFilter> tagFilters) {
+ if (tagFilters == null || tagFilters.isEmpty()) return true;
+ Map<String, String> tags = m.getTags();
+ for (TagFilter filter : tagFilters) {
+ String tagValue = tags.get(filter.key());
+ if (tagValue == null) return false;
+ if (!filter.values().isEmpty() && !filter.values().contains(tagValue)) return false;
+ }
+ return true;
+ }
+
+ private boolean matchesResourceTypeFilters(ResourceTagMapping m, List<String> resourceTypeFilters) {
+ if (resourceTypeFilters == null || resourceTypeFilters.isEmpty()) return true;
+ // ARN: arn:aws:<service>:<region>:<account>:<type>/<id> or arn:aws:<service>:::...
+ String arn = m.getResourceArn();
+ String[] parts = arn.split(":", 6);
+ if (parts.length < 3) return false;
+ String service = parts[2];
+ // resource part is parts[5]: "type/id" or just "type"
+ String resourcePart = parts.length >= 6 ? parts[5] : "";
+ String resourceType = resourcePart.contains("/")
+ ? resourcePart.substring(0, resourcePart.indexOf('/'))
+ : resourcePart;
+ // filter format is "service:resourceType" (e.g. "ec2:instance")
+ for (String filter : resourceTypeFilters) {
+ String[] filterParts = filter.split(":", 2);
+ if (filterParts.length == 2) {
+ if (filterParts[0].equalsIgnoreCase(service)
+ && filterParts[1].equalsIgnoreCase(resourceType)) {
+ return true;
+ }
+ } else {
+ if (filterParts[0].equalsIgnoreCase(service)) return true;
+ }
+ }
+ return false;
+ }
+
+ // ─── GetTagKeys ────────────────────────────────────────────────────────────
+
+ public PageResult getTagKeys(String paginationToken, int maxResults, String region) {
+ List<String> keys = store.values().stream()
+ .filter(m -> {
+ String[] parts = m.getResourceArn().split(":", 6);
+ if (parts.length >= 4) {
+ String arnRegion = parts[3];
+ if (!arnRegion.isEmpty() && !arnRegion.equals(region)) return false;
+ }
+ return true;
+ })
+ .flatMap(m -> m.getTags().keySet().stream())
+ .distinct()
+ .sorted()
+ .collect(Collectors.toList());
+
+ int offset = decodePaginationToken(paginationToken);
+ int pageSize = (maxResults > 0) ? maxResults : 100;
+ int end = Math.min(offset + pageSize, keys.size());
+ // Return as ResourceTagMapping with just the key in the ARN field (repurposed for keys)
+ List<ResourceTagMapping> page = keys.subList(offset, end).stream()
+ .map(k -> new ResourceTagMapping(k))
+ .collect(Collectors.toList());
+ String nextToken = (end < keys.size()) ? encodePaginationToken(end) : null;
+ return new PageResult(page, nextToken);
+ }
+
+ // ─── GetTagValues ──────────────────────────────────────────────────────────
+
+ public PageResult getTagValues(String tagKey, String paginationToken, int maxResults, String region) {
+ List<String> values = store.values().stream()
+ .filter(m -> {
+ String[] parts = m.getResourceArn().split(":", 6);
+ if (parts.length >= 4) {
+ String arnRegion = parts[3];
+ if (!arnRegion.isEmpty() && !arnRegion.equals(region)) return false;
+ }
+ return true;
+ })
+ .map(m -> m.getTags().get(tagKey))
+ .filter(Objects::nonNull)
+ .distinct()
+ .sorted()
+ .collect(Collectors.toList());
+
+ int offset = decodePaginationToken(paginationToken);
+ int pageSize = (maxResults > 0) ? maxResults : 100;
+ int end = Math.min(offset + pageSize, values.size());
+ List<ResourceTagMapping> page = values.subList(offset, end).stream()
+ .map(v -> new ResourceTagMapping(v))
+ .collect(Collectors.toList());
+ String nextToken = (end < values.size()) ? encodePaginationToken(end) : null;
+ return new PageResult(page, nextToken);
+ }
+
+ // ─── Pagination helpers ────────────────────────────────────────────────────
+
+ private static String encodePaginationToken(int offset) {
+ return Base64.getEncoder().encodeToString(String.valueOf(offset).getBytes(StandardCharsets.UTF_8));
+ }
+
+ private static int decodePaginationToken(String token) {
+ if (token == null || token.isBlank()) return 0;
+ try {
+ return Integer.parseInt(new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8));
+ } catch (Exception e) {
+ return 0;
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/model/ResourceTagMapping.java b/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/model/ResourceTagMapping.java
new file mode 100644
index 0000000000..0bba41df74
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/model/ResourceTagMapping.java
@@ -0,0 +1,27 @@
+package io.github.hectorvent.floci.services.resourcegroupstagging.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class ResourceTagMapping {
+
+ private String resourceArn;
+ // Preserves insertion order for deterministic responses
+ private final Map<String, String> tags = new LinkedHashMap<>();
+
+ public ResourceTagMapping() {}
+
+ public ResourceTagMapping(String resourceArn) {
+ this.resourceArn = resourceArn;
+ }
+
+ public String getResourceArn() { return resourceArn; }
+ public void setResourceArn(String resourceArn) { this.resourceArn = resourceArn; }
+
+ public Map<String, String> getTags() { return tags; }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java
index 6d994b7e28..020c57e6f9 100644
--- a/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/HealthControllerIntegrationTest.java
@@ -47,7 +47,8 @@ class HealthControllerIntegrationTest {
"ecs": "running",
"appconfig": "running",
"appconfigdata": "running",
- "ecr": "running"
+ "ecr": "running",
+ "tagging": "running"
},
"edition": "floci-always-free",
"version": "dev"
diff --git a/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingIntegrationTest.java
new file mode 100644
index 0000000000..962932870b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingIntegrationTest.java
@@ -0,0 +1,307 @@
+package io.github.hectorvent.floci.services.resourcegroupstagging;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+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.*;
+
+/**
+ * Integration tests for the Resource Groups Tagging API.
+ * Uses JSON 1.1 protocol (X-Amz-Target: ResourceGroupsTaggingAPI_20170126.*).
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class ResourceGroupsTaggingIntegrationTest {
+
+ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
+ private static final String TARGET_PREFIX = "ResourceGroupsTaggingAPI_20170126.";
+
+ private static final String ARN_INSTANCE = "arn:aws:ec2:us-east-1:000000000000:instance/i-abc123";
+ private static final String ARN_BUCKET = "arn:aws:s3:::my-test-bucket";
+ private static final String ARN_FUNCTION = "arn:aws:lambda:us-east-1:000000000000:function/my-func";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ // ─── TagResources ──────────────────────────────────────────────────────────
+
+ @Test
+ @Order(1)
+ void tagResources() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "TagResources")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ResourceARNList": ["%s", "%s"],
+ "Tags": {"Environment": "prod", "Team": "platform"}
+ }
+ """.formatted(ARN_INSTANCE, ARN_BUCKET))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", anEmptyMap());
+ }
+
+ @Test
+ @Order(2)
+ void tagResourcesSecond() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "TagResources")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ResourceARNList": ["%s"],
+ "Tags": {"Environment": "staging", "Team": "data"}
+ }
+ """.formatted(ARN_FUNCTION))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", anEmptyMap());
+ }
+
+ // ─── GetResources ──────────────────────────────────────────────────────────
+
+ @Test
+ @Order(3)
+ void getResourcesAll() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "GetResources")
+ .contentType(CONTENT_TYPE)
+ .body("{}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("ResourceTagMappingList.size()", equalTo(3))
+ .body("ResourceTagMappingList.ResourceARN", hasItems(ARN_INSTANCE, ARN_BUCKET, ARN_FUNCTION));
+ }
+
+ @Test
+ @Order(4)
+ void getResourcesByArnList() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "GetResources")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {"ResourceARNList": ["%s"]}
+ """.formatted(ARN_INSTANCE))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("ResourceTagMappingList.size()", equalTo(1))
+ .body("ResourceTagMappingList[0].ResourceARN", equalTo(ARN_INSTANCE))
+ .body("ResourceTagMappingList[0].Tags.size()", equalTo(2));
+ }
+
+ @Test
+ @Order(5)
+ void getResourcesByTagFilter() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "GetResources")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "TagFilters": [
+ {"Key": "Environment", "Values": ["prod"]}
+ ]
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("ResourceTagMappingList.size()", equalTo(2))
+ .body("ResourceTagMappingList.ResourceARN", hasItems(ARN_INSTANCE, ARN_BUCKET));
+ }
+
+ @Test
+ @Order(6)
+ void getResourcesByTagFilterKeyOnly() {
+ // Values empty → match any resource that has the key
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "GetResources")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "TagFilters": [
+ {"Key": "Team", "Values": []}
+ ]
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("ResourceTagMappingList.size()", equalTo(3));
+ }
+
+ @Test
+ @Order(7)
+ void getResourcesByResourceTypeFilter() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "GetResources")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {"ResourceTypeFilters": ["ec2:instance"]}
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("ResourceTagMappingList.size()", equalTo(1))
+ .body("ResourceTagMappingList[0].ResourceARN", equalTo(ARN_INSTANCE));
+ }
+
+ @Test
+ @Order(8)
+ void getResourcesByServiceTypeFilter() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "GetResources")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {"ResourceTypeFilters": ["lambda"]}
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("ResourceTagMappingList.size()", equalTo(1))
+ .body("ResourceTagMappingList[0].ResourceARN", equalTo(ARN_FUNCTION));
+ }
+
+ @Test
+ @Order(9)
+ void getResourcesPagination() {
+ // ResourcesPerPage=1 → first page has 1 item and a pagination token
+ String paginationToken = given()
+ .header("X-Amz-Target", TARGET_PREFIX + "GetResources")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {"ResourcesPerPage": 1}
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("ResourceTagMappingList.size()", equalTo(1))
+ .body("PaginationToken", not(emptyString()))
+ .extract().path("PaginationToken");
+
+ // Second page using the token
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "GetResources")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {"ResourcesPerPage": 1, "PaginationToken": "%s"}
+ """.formatted(paginationToken))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("ResourceTagMappingList.size()", equalTo(1));
+ }
+
+ // ─── GetTagKeys ────────────────────────────────────────────────────────────
+
+ @Test
+ @Order(10)
+ void getTagKeys() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "GetTagKeys")
+ .contentType(CONTENT_TYPE)
+ .body("{}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("TagKeys", hasItems("Environment", "Team"))
+ .body("PaginationToken", notNullValue());
+ }
+
+ // ─── GetTagValues ──────────────────────────────────────────────────────────
+
+ @Test
+ @Order(11)
+ void getTagValues() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "GetTagValues")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {"Key": "Environment"}
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("TagValues", hasItems("prod", "staging"));
+ }
+
+ // ─── UntagResources ────────────────────────────────────────────────────────
+
+ @Test
+ @Order(12)
+ void untagResources() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "UntagResources")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {
+ "ResourceARNList": ["%s"],
+ "TagKeys": ["Team"]
+ }
+ """.formatted(ARN_INSTANCE))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", anEmptyMap());
+ }
+
+ @Test
+ @Order(13)
+ void getResourcesAfterUntag() {
+ // ARN_INSTANCE should now only have "Environment" tag
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "GetResources")
+ .contentType(CONTENT_TYPE)
+ .body("""
+ {"ResourceARNList": ["%s"]}
+ """.formatted(ARN_INSTANCE))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("ResourceTagMappingList[0].Tags.size()", equalTo(1))
+ .body("ResourceTagMappingList[0].Tags[0].Key", equalTo("Environment"))
+ .body("ResourceTagMappingList[0].Tags[0].Value", equalTo("prod"));
+ }
+
+ // ─── Unsupported action ────────────────────────────────────────────────────
+
+ @Test
+ @Order(20)
+ void unsupportedAction() {
+ given()
+ .header("X-Amz-Target", TARGET_PREFIX + "UnknownAction")
+ .contentType(CONTENT_TYPE)
+ .body("{}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("UnsupportedOperation"));
+ }
+}