Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(tagging): find resources by the tags their own service holds (#4563)

Mario Toffia560de5c13f53
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ResourceGroupsTaggingDiscoveryTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ResourceGroupsTaggingDiscoveryTest.java
new file mode 100644
index 0000000000..3550c7292c
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ResourceGroupsTaggingDiscoveryTest.java
@@ -0,0 +1,295 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.core.exception.SdkException;
+import software.amazon.awssdk.services.apigateway.ApiGatewayClient;
+import software.amazon.awssdk.services.apigateway.model.CreateApiKeyResponse;
+import software.amazon.awssdk.services.apigateway.model.GetApiKeyResponse;
+import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
+import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogGroupsResponse;
+import software.amazon.awssdk.services.cloudwatchlogs.model.LogGroup;
+import software.amazon.awssdk.services.lambda.LambdaClient;
+import software.amazon.awssdk.services.lambda.model.CreateFunctionResponse;
+import software.amazon.awssdk.services.lambda.model.FunctionCode;
+import software.amazon.awssdk.services.lambda.model.GetFunctionResponse;
+import software.amazon.awssdk.services.lambda.model.Runtime;
+import software.amazon.awssdk.services.resourcegroupstaggingapi.ResourceGroupsTaggingApiClient;
+import software.amazon.awssdk.services.resourcegroupstaggingapi.model.GetResourcesRequest;
+import software.amazon.awssdk.services.resourcegroupstaggingapi.model.GetResourcesResponse;
+import software.amazon.awssdk.services.resourcegroupstaggingapi.model.ResourceTagMapping;
+import software.amazon.awssdk.services.resourcegroupstaggingapi.model.Tag;
+import software.amazon.awssdk.services.resourcegroupstaggingapi.model.TagFilter;
+import software.amazon.awssdk.services.resourcegroupstaggingapi.model.TagResourcesResponse;
+import software.amazon.awssdk.services.resourcegroupstaggingapi.model.UntagResourcesResponse;
+import software.amazon.awssdk.services.sqs.SqsClient;
+import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
+import software.amazon.awssdk.services.sqs.model.SendMessageResponse;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@DisplayName("Resource Groups Tagging discovery of resources tagged by their own service")
+class ResourceGroupsTaggingDiscoveryTest {
+
+ private static final String ROLE = "arn:aws:iam::000000000000:role/lambda-role";
+
+ private static ResourceGroupsTaggingApiClient tagging;
+ private static SqsClient sqs;
+ private static LambdaClient lambda;
+ private static CloudWatchLogsClient logs;
+ private static ApiGatewayClient apiGateway;
+
+ @BeforeAll
+ static void setup() {
+ tagging = TestFixtures.resourceGroupsTaggingApiClient();
+ sqs = TestFixtures.sqsClient();
+ lambda = TestFixtures.lambdaClient();
+ logs = TestFixtures.cloudWatchLogsClient();
+ apiGateway = TestFixtures.apiGatewayClient();
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (tagging != null) {
+ tagging.close();
+ sqs.close();
+ lambda.close();
+ logs.close();
+ apiGateway.close();
+ }
+ }
+
+ @Test
+ @DisplayName("SQS queues tagged on CreateQueue are found by type and tag filters, page by page, and stay usable")
+ void sqsQueueIsDiscoveredAndUsable() {
+ String run = TestFixtures.uniqueName("run");
+ String primaryName = TestFixtures.uniqueName("tag-discovery-primary");
+ String secondaryName = TestFixtures.uniqueName("tag-discovery-secondary");
+ String primaryUrl = sqs.createQueue(request -> request
+ .queueName(primaryName)
+ .tags(Map.of("Run", run, "Team", "platform", "Env", "dev"))).queueUrl();
+ String secondaryUrl = sqs.createQueue(request -> request
+ .queueName(secondaryName)
+ .tags(Map.of("Run", run))).queueUrl();
+
+ try {
+ GetResourcesResponse matched = tagging.getResources(request -> request
+ .resourceTypeFilters("sqs:queue")
+ .tagFilters(tagFilter("Run", run), tagFilter("Team", "platform"), tagFilter("Env", "dev")));
+
+ assertThat(matched.resourceTagMappingList()).singleElement().satisfies(mapping -> {
+ assertThat(mapping.resourceARN()).endsWith(":" + primaryName);
+ assertThat(tags(mapping)).containsOnly(
+ Map.entry("Run", run), Map.entry("Team", "platform"), Map.entry("Env", "dev"));
+ });
+
+ List<GetResourcesResponse> pages = tagging.getResourcesPaginator(GetResourcesRequest.builder()
+ .resourceTypeFilters("sqs:queue")
+ .tagFilters(tagFilter("Run", run))
+ .resourcesPerPage(1)
+ .build()).stream().collect(Collectors.toList());
+ List<String> pagedArns = new ArrayList<>();
+ for (GetResourcesResponse page : pages) {
+ assertThat(page.resourceTagMappingList()).hasSizeLessThanOrEqualTo(1);
+ page.resourceTagMappingList().forEach(mapping -> pagedArns.add(mapping.resourceARN()));
+ }
+ assertThat(pagedArns).hasSize(2)
+ .anySatisfy(arn -> assertThat(arn).endsWith(":" + primaryName))
+ .anySatisfy(arn -> assertThat(arn).endsWith(":" + secondaryName));
+
+ String discoveredArn = matched.resourceTagMappingList().get(0).resourceARN();
+ String discoveredName = discoveredArn.substring(discoveredArn.lastIndexOf(':') + 1);
+ String discoveredUrl = sqs.getQueueUrl(request -> request.queueName(discoveredName)).queueUrl();
+ SendMessageResponse sent = sqs.sendMessage(request -> request
+ .queueUrl(discoveredUrl)
+ .messageBody("found by tag"));
+
+ assertThat(discoveredUrl).isEqualTo(primaryUrl);
+ assertThat(sent.messageId()).isNotBlank();
+ } finally {
+ sqs.deleteQueue(request -> request.queueUrl(primaryUrl));
+ sqs.deleteQueue(request -> request.queueUrl(secondaryUrl));
+ }
+ }
+
+ @Test
+ @DisplayName("Tags written on an SQS queue through the tagging API are the queue's own tags")
+ void taggingApiWritesReachSqsQueueTags() {
+ String queueName = TestFixtures.uniqueName("tag-discovery-write");
+ String queueUrl = sqs.createQueue(request -> request
+ .queueName(queueName)
+ .tags(Map.of("Env", "dev"))).queueUrl();
+
+ try {
+ String arn = sqs.getQueueAttributes(request -> request
+ .queueUrl(queueUrl)
+ .attributeNames(QueueAttributeName.QUEUE_ARN))
+ .attributes().get(QueueAttributeName.QUEUE_ARN);
+
+ TagResourcesResponse tagged = tagging.tagResources(request -> request
+ .resourceARNList(arn)
+ .tags(Map.of("Owner", "compat")));
+
+ assertThat(tagged.failedResourcesMap()).isEmpty();
+ assertThat(sqs.listQueueTags(request -> request.queueUrl(queueUrl)).tags())
+ .containsOnly(Map.entry("Env", "dev"), Map.entry("Owner", "compat"));
+
+ UntagResourcesResponse untagged = tagging.untagResources(request -> request
+ .resourceARNList(arn)
+ .tagKeys("Owner"));
+
+ assertThat(untagged.failedResourcesMap()).isEmpty();
+ assertThat(sqs.listQueueTags(request -> request.queueUrl(queueUrl)).tags())
+ .containsOnly(Map.entry("Env", "dev"));
+ } finally {
+ sqs.deleteQueue(request -> request.queueUrl(queueUrl));
+ }
+ }
+
+ @Test
+ @DisplayName("Lambda functions tagged on CreateFunction are found by type and tag, and the ARN resolves")
+ void lambdaFunctionIsDiscoveredByTag() {
+ String run = TestFixtures.uniqueName("run");
+ String functionName = TestFixtures.uniqueName("tag-discovery-fn");
+ CreateFunctionResponse created = lambda.createFunction(request -> request
+ .functionName(functionName)
+ .runtime(Runtime.NODEJS20_X)
+ .role(ROLE)
+ .handler("index.handler")
+ .code(FunctionCode.builder()
+ .zipFile(SdkBytes.fromByteArray(LambdaUtils.minimalZip()))
+ .build())
+ .tags(Map.of("Run", run)));
+
+ try {
+ GetResourcesResponse matched = tagging.getResources(request -> request
+ .resourceTypeFilters("lambda:function")
+ .tagFilters(tagFilter("Run", run)));
+
+ assertThat(matched.resourceTagMappingList()).singleElement().satisfies(mapping -> {
+ assertThat(mapping.resourceARN()).isEqualTo(created.functionArn());
+ assertThat(tags(mapping)).containsEntry("Run", run);
+ });
+
+ String discoveredArn = matched.resourceTagMappingList().get(0).resourceARN();
+ GetFunctionResponse function = lambda.getFunction(request -> request.functionName(discoveredArn));
+
+ assertThat(function.configuration().functionName()).isEqualTo(functionName);
+ assertThat(function.tags()).containsEntry("Run", run);
+ } finally {
+ lambda.deleteFunction(request -> request.functionName(functionName));
+ }
+ }
+
+ @Test
+ @DisplayName("Log groups tagged on CreateLogGroup are found by type and tag, without the trailing :* ARN suffix")
+ void logGroupIsDiscoveredByTag() {
+ String run = TestFixtures.uniqueName("run");
+ String logGroupName = "/compat/" + TestFixtures.uniqueName("tag-discovery");
+ logs.createLogGroup(request -> request
+ .logGroupName(logGroupName)
+ .tags(Map.of("Run", run)));
+
+ try {
+ GetResourcesResponse matched = tagging.getResources(request -> request
+ .resourceTypeFilters("logs:log-group")
+ .tagFilters(tagFilter("Run", run)));
+
+ assertThat(matched.resourceTagMappingList()).singleElement().satisfies(mapping -> {
+ assertThat(mapping.resourceARN())
+ .endsWith(":log-group:" + logGroupName)
+ .doesNotEndWith(":*");
+ assertThat(tags(mapping)).containsEntry("Run", run);
+ });
+
+ String discoveredArn = matched.resourceTagMappingList().get(0).resourceARN();
+ String discoveredName = discoveredArn.substring(discoveredArn.indexOf("log-group:") + "log-group:".length());
+ DescribeLogGroupsResponse described = logs.describeLogGroups(request -> request
+ .logGroupNamePrefix(discoveredName));
+
+ assertThat(described.logGroups()).extracting(LogGroup::logGroupName).containsExactly(logGroupName);
+ } finally {
+ logs.deleteLogGroup(request -> request.logGroupName(logGroupName));
+ }
+ }
+
+ @Test
+ @DisplayName("API keys are found by type, tagged and untagged through the tagging API, and gone once deleted")
+ void apiKeyIsDiscoveredAndTaggedThroughTaggingApi() {
+ String run = TestFixtures.uniqueName("run");
+ CreateApiKeyResponse created = apiGateway.createApiKey(request -> request
+ .name(TestFixtures.uniqueName("tag-discovery-key"))
+ .enabled(true)
+ .tags(Map.of("Run", run, "Stage", "initial")));
+ boolean deleted = false;
+
+ try {
+ GetResourcesResponse matched = tagging.getResources(request -> request
+ .resourceTypeFilters("apigateway:apikeys")
+ .tagFilters(tagFilter("Run", run)));
+
+ assertThat(matched.resourceTagMappingList()).singleElement().satisfies(mapping -> {
+ assertThat(mapping.resourceARN()).endsWith("::/apikeys/" + created.id());
+ assertThat(tags(mapping)).containsOnly(Map.entry("Run", run), Map.entry("Stage", "initial"));
+ });
+ String arn = matched.resourceTagMappingList().get(0).resourceARN();
+
+ TagResourcesResponse tagged = tagging.tagResources(request -> request
+ .resourceARNList(arn)
+ .tags(Map.of("Owner", "compat")));
+ UntagResourcesResponse untagged = tagging.untagResources(request -> request
+ .resourceARNList(arn)
+ .tagKeys("Stage"));
+
+ assertThat(tagged.failedResourcesMap()).isEmpty();
+ assertThat(untagged.failedResourcesMap()).isEmpty();
+
+ GetApiKeyResponse read = apiGateway.getApiKey(request -> request.apiKey(created.id()));
+ assertThat(read.tags()).containsOnly(Map.entry("Run", run), Map.entry("Owner", "compat"));
+
+ GetResourcesResponse retagged = tagging.getResources(request -> request
+ .resourceTypeFilters("apigateway:apikeys")
+ .tagFilters(tagFilter("Run", run), tagFilter("Owner", "compat")));
+ assertThat(retagged.resourceTagMappingList()).singleElement().satisfies(mapping -> {
+ assertThat(mapping.resourceARN()).isEqualTo(arn);
+ assertThat(tags(mapping)).doesNotContainKey("Stage");
+ });
+
+ apiGateway.deleteApiKey(request -> request.apiKey(created.id()));
+ deleted = true;
+
+ GetResourcesResponse afterDelete = tagging.getResources(request -> request
+ .resourceTypeFilters("apigateway:apikeys")
+ .tagFilters(tagFilter("Run", run)));
+ assertThat(afterDelete.resourceTagMappingList()).isEmpty();
+ } finally {
+ if (!deleted) {
+ deleteApiKeyAfterFailure(created.id());
+ }
+ }
+ }
+
+ private static TagFilter tagFilter(String key, String value) {
+ return TagFilter.builder().key(key).values(value).build();
+ }
+
+ private static Map<String, String> tags(ResourceTagMapping mapping) {
+ return mapping.tags().stream().collect(Collectors.toMap(Tag::key, Tag::value));
+ }
+
+ private static void deleteApiKeyAfterFailure(String id) {
+ try {
+ apiGateway.deleteApiKey(request -> request.apiKey(id));
+ } catch (SdkException ignored) {
+ // Runs only after an assertion already failed; a cleanup error must not hide that failure.
+ }
+ }
+}
diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md
index 3e661c84d0..8cf851f2d1 100644
--- a/docs/services/api-gateway.md
+++ b/docs/services/api-gateway.md
@@ -99,6 +99,14 @@ includes mapping templates and applies to both `ImportRestApi` and `PutRestApi`.
| **Account** | GetAccount, UpdateAccount |
| **Tags** | TagResource, UntagResource, GetTags (ListTagsForResource) |
+`TagResource`, `UntagResource` and `GetTags` also accept API key and usage plan ARNs,
+`arn:aws:apigateway:<region>::/apikeys/<id>` and `arn:aws:apigateway:<region>::/usageplans/<id>`.
+An ARN nested under `/restapis/<id>/` other than a stage, such as a deployment or resource, is rejected with `BadRequestException`.
+An ARN with an account segment is rejected with `BadRequestException` and an ARN from another region with `NotFoundException`, as on AWS.
+Tagged REST APIs, stages, API keys, usage plans and custom domain names are discoverable through the
+[Resource Groups Tagging API](resource-groups-tagging.md), whose `TagResources` and `UntagResources`
+write REST API, stage, API key, usage plan and custom domain name tags through to API Gateway.
+
### API Key Behaviour Notes
#### `CreateApiKey` and `ImportApiKeys` share one route
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 82bc6360d3..5d90d6408e 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -269,6 +269,7 @@ accepts, not only by name:
- Replacement-only changes such as `FunctionName` or `PackageType` changes create a replacement function and remove the old one.
- S3-backed code stays linked through `S3Bucket` / `S3Key`, so Lambda's reactive S3 sync continues to work for functions created by CloudFormation or CDK.
- Hot-reload code (`S3Bucket: hot-reload`) is compared by host path: the same path is a no-op, a different path updates the bind mount in place.
+- `Tags` are applied when the function is created, including a replacement function. On `UpdateStack` the template's tags are applied and only the keys the previous template set and the new one drops are removed, so a tag added outside the template is kept, as in AWS.
## RDS Credential Dynamic References
@@ -309,6 +310,9 @@ before provisioning:
The `AWS::SSM::Parameter` **resource** type exposes `Value`, `Type`, `Name`, and `Arn` attributes through
`Ref` / `Fn::GetAtt` so downstream resources can consume a parameter the same stack creates.
+`Tags` are applied when the parameter is created. On `UpdateStack` the template's tags are applied and
+only the keys the previous template set and the new one drops are removed, so a tag added outside the
+template is kept, as in AWS.
## AWS::Include (`Fn::Transform`)
diff --git a/docs/services/resource-explorer.md b/docs/services/resource-explorer.md
index 2e091fc0b1..5c40b43dd6 100644
--- a/docs/services/resource-explorer.md
+++ b/docs/services/resource-explorer.md
@@ -84,6 +84,7 @@ map as empty.
|---|---|
| ACM | `acm:certificate` |
| Amazon MQ | `mq:broker` |
+| API Gateway | `apigateway:restapis`, `apigateway:restapis/stages`, `apigateway:apikeys`, `apigateway:usageplans`, `apigateway:domainnames` |
| CloudFormation | `cloudformation:stack` |
| CloudWatch Logs | `logs:log-group` |
| Cognito | `cognito-idp:userpool` |
@@ -113,9 +114,9 @@ map as empty.
| SSM | `ssm:parameter` |
| Step Functions | `states:statemachine` |
-API Gateway and Route 53 are not discoverable yet, each for its own reason: `RestApi` carries no
-Region, and `Route53Service` resolves no account id — a hosted zone's ARN has neither. Both are
-waiting on a field, not on new query support.
+API Gateway ARNs carry no account; its resources report the calling account as their owner.
+Route 53 is not discoverable yet: `Route53Service` resolves no account id, and a hosted zone's ARN
+has neither a Region nor an account. It is waiting on a field, not on new query support.
## Query syntax
diff --git a/docs/services/resource-groups-tagging.md b/docs/services/resource-groups-tagging.md
index c674bab579..65982bc605 100644
--- a/docs/services/resource-groups-tagging.md
+++ b/docs/services/resource-groups-tagging.md
@@ -5,9 +5,11 @@
**Endpoint prefix:** `tagging`
Floci emulates the AWS Resource Groups Tagging API for local tests that need
-centralized tag discovery across AWS-shaped ARNs. The service accepts arbitrary
-resource ARNs, stores their tags in-process, and supports filtering by ARN, tag
-filters, and resource type filters.
+centralized tag discovery across AWS-shaped ARNs. `GetResources`, `GetTagKeys`
+and `GetTagValues` list both the tags written through this API and the tags
+each resource's own service holds, so a queue created with `CreateQueue` tags
+is found without a separate `TagResources` call. Any other ARN is accepted as
+well, and its tags are kept in the tagging store.
## Supported Operations
@@ -20,8 +22,59 @@ filters, and resource type filters.
| `GetTagValues` | Lists distinct values for a requested tag key in the current region |
`TagResources` and `UntagResources` return an empty `FailedResourcesMap` on
-success. `GetResources`, `GetTagKeys`, and `GetTagValues` support pagination
-tokens for multi-page responses.
+success. An ARN the owning service rejected is listed there with that
+service's own `StatusCode`, `ErrorCode` and `ErrorMessage`, such as
+`400 BadRequestException` for a reserved `floci:` key on an API key, and the
+call still returns HTTP 200. An ARN that names a region other than the
+request's fails the whole call with HTTP 400 `InvalidParameterException`,
+`Region in the ARN <arn> does not match with the region in which TagResources
+API is invoked` (or `UntagResources`), and nothing is tagged or untagged.
+`GetResources`, `GetTagKeys`, and `GetTagValues` support pagination tokens for
+multi-page responses; a token past the last result returns an empty page.
+
+## Resource discovery
+
+Reads merge two sources for the request's region and account:
+
+- The owning service's tags, for every service that
+ [Resource Explorer 2 indexes](resource-explorer.md#discoverable-services),
+ including SQS, Lambda, CloudWatch Logs, S3 and API Gateway (REST APIs,
+ stages, API keys, usage plans and custom domain names). Only resources that
+ carry at least one tag are listed.
+- The tagging store, which holds tags written through `TagResources` that were
+ not forwarded to an owning service, and the copies EventBridge and Glue keep
+ there.
+
+When both hold the same ARN, the result is one mapping, and for the same key
+the owning service's value wins. CloudWatch Logs log group ARNs are returned
+without the trailing `:*`.
+
+`TagResources` forwards the tags to the owning service only when that service
+registers a tag handler, such as API Gateway, MSK, SQS, Lambda or CloudWatch
+Logs, and currently lists the exact ARN as one of its resources visible to the
+request's region and account, by the same rule reads use. The tags then live
+only in the owning service, so `GetApiKey`, `ListQueueTags`, Lambda `ListTags`
+and CloudWatch Logs `ListTagsForResource` show a tag set through
+`TagResources`, and nothing is written to the tagging store. When the owning
+service rejects the tags, for example a reserved `floci:` key on an API key or
+a log group ARN with the trailing `:*`, the ARN appears in `FailedResourcesMap`
+with that service's error and no tags are stored for it. A log group ARN with
+the trailing `:*` is rejected this way whether or not the group exists, as in
+AWS, and so is any other ARN ending in `:*` whose service registers a tag
+handler, such as an SQS queue ARN. Every other ARN, including
+one the owning service does not list such as an API Gateway deployment ARN,
+goes to the tagging store and the owning service is not called.
+`UntagResources` routes the same way, and also removes the keys from the
+tagging store for every ARN, including one the owning service rejects but not
+one reported as unresolved or from another account, so a copy stored earlier
+can always be cleared. When the service owning an ARN cannot be read while
+routing and no service lists the ARN, it is reported in `FailedResourcesMap`
+with `InternalServiceException` (status 500) and left unchanged, while ARNs a
+service lists, and ARNs of services that were read, still go through. An ARN
+from another account is reported in `FailedResourcesMap` with
+`AccessDeniedException` (status 403) and nothing is tagged; AWS also reports
+it per ARN, but with the owning service's own error, such as `InvalidAddress`
+for SQS or `ValidationException` for CloudWatch Logs.
## Filtering
@@ -31,18 +84,39 @@ tokens for multi-page responses.
|--------|----------|
| `ResourceARNList` | Restricts results to the requested ARNs |
| `TagFilters` | Matches resources that have each requested key; values are optional |
-| `ResourceTypeFilters` | Matches `service` or `service:resourceType`, such as `lambda` or `ec2:instance` |
+| `ResourceTypeFilters` | Matches `service` or `service:resourceType`, such as `lambda`, `lambda:function` or `ec2:instance` |
| `ResourcesPerPage` + `PaginationToken` | Pages through matching resource mappings |
-Region filtering follows the ARN region when present. Global ARNs, such as S3
-bucket ARNs, are visible across regions because their ARN region segment is
-empty.
+The resource type in `service:resourceType` matches the ARN's type, which is
+the ARN resource part with one leading `/` dropped, cut at the first `/` or
+`:`, or the type the owning service declares for the resource. So
+`lambda:function`, `logs:log-group`, `ec2:instance`, `apigateway:apikeys` and
+`apigateway:restapis/stages` all match. SQS queue ARNs have no type segment, so
+`sqs:queue` matches through the type SQS declares for its queues. As in AWS,
+`apigateway:restapis` lists REST APIs together with their stages, and a filter
+type with a leading `/`, such as `apigateway:/apikeys`, matches nothing.
+
+A resource is visible in the region its ARN names. When the ARN has no region,
+such as an S3 bucket ARN, the owning service's region for the resource
+decides, also for tags the tagging store holds for that ARN, so an
+`eu-west-1` bucket tagged through `TagResources` is not listed from
+`us-east-1`. A region-less ARN known only to the tagging store is visible in
+every region. As in AWS, a resource the owning service reports without a
+region, or in the region `global` as IAM does for users and roles, is never
+listed, and `TagResources` does not forward to its owning service; an IAM ARN
+is never listed at all, even one only the tagging store holds, for example
+after the role is deleted. Every store is per account, so results are scoped
+to the calling account. An ARN with an empty account segment, such as an API
+Gateway ARN, only leaves the account out of the ARN; the resource is still
+listed for the account that owns it.
## Configuration
| Variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_TAGGING_ENABLED` | `true` | Enable or disable the Resource Groups Tagging API service |
+| `FLOCI_STORAGE_SERVICES_TAGGING_MODE` | _(global storage mode)_ | Override the storage mode for the tagging store |
+| `FLOCI_STORAGE_SERVICES_TAGGING_FLUSH_INTERVAL_MS` | `5000` | Flush interval for the tagging store in `hybrid` mode |
## Examples
@@ -77,7 +151,7 @@ tagging = boto3.client(
region_name="us-east-1",
)
-arn = "arn:aws:lambda:us-east-1:000000000000:function/my-func"
+arn = "arn:aws:lambda:us-east-1:000000000000:function:my-func"
tagging.tag_resources(
ResourceARNList=[arn],
@@ -92,6 +166,6 @@ print(resources["ResourceTagMappingList"])
## Out of Scope
-- Validation that an ARN already exists in another emulated service.
+- Validation that a `TagResources` ARN names an existing resource: an ARN that
+ no emulated service lists is accepted and kept in the tagging store.
- AWS Organizations tag policy enforcement.
-- Persistent tag storage across process restarts.
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/TaggingApiOnly.java b/src/main/java/io/github/hectorvent/floci/core/common/TaggingApiOnly.java
new file mode 100644
index 0000000000..bad2310536
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/TaggingApiOnly.java
@@ -0,0 +1,21 @@
+package io.github.hectorvent.floci.core.common;
+
+import jakarta.inject.Qualifier;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Marks a {@link TagHandler} for a service whose tag operations live in its own protocol, so
+ * neither the {@code /tags/{arn}} nor the {@code /v1/tags/{arn}} path serves it.
+ *
+ * <p>A qualified bean is not a {@code @Default} bean, and it does not carry {@link V1Tags}, so
+ * only the Resource Groups Tagging API's {@code @Any Instance<TagHandler>} reaches it.
+ */
+@Qualifier
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
+public @interface TaggingApiOnly {
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
index 4c04fd155a..6fa2031045 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
@@ -6,12 +6,16 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsCertificateManager;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsPartition;
import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.AwsRegionFacts;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
+import io.github.hectorvent.floci.core.resource.ExplorerResource;
+import io.github.hectorvent.floci.core.resource.ResourceProvider;
+import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.apigateway.model.Account;
@@ -50,6 +54,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import java.time.Instant;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
@@ -68,7 +73,7 @@ import java.util.function.Predicate;
import java.util.regex.Pattern;
@ApplicationScoped
-public class ApiGatewayService {
+public class ApiGatewayService implements ResourceProvider {
/** The only partition where API Gateway offers edge-optimized APIs and custom domain names. */
private static final Set<String> EDGE_OPTIMIZED_PARTITIONS = Set.of("aws");
@@ -1254,6 +1259,18 @@ public class ApiGatewayService {
return key;
}
+ public void tagApiKey(String region, String apiKeyId, Map<String, String> tags) {
+ Map<String, String> merged = new HashMap<>(getApiKey(region, apiKeyId).getTags());
+ merged.putAll(tags);
+ replaceApiKeyTags(region, apiKeyId, merged);
+ }
+
+ public void untagApiKey(String region, String apiKeyId, List<String> tagKeys) {
+ Map<String, String> remaining = new HashMap<>(getApiKey(region, apiKeyId).getTags());
+ tagKeys.forEach(remaining::remove);
+ replaceApiKeyTags(region, apiKeyId, remaining);
+ }
+
// ──────────────────────────── Usage Plans ────────────────────────────
public UsagePlan createUsagePlan(String region, Map<String, Object> request) {
@@ -1372,6 +1389,19 @@ public class ApiGatewayService {
return plan;
}
+ public void tagUsagePlan(String region, String usagePlanId, Map<String, String> tags) {
+ ReservedTags.rejectApiGatewayReservedTagsOnUpdate(tags);
+ Map<String, String> merged = new HashMap<>(getUsagePlan(region, usagePlanId).getTags());
+ merged.putAll(tags);
+ replaceUsagePlanTags(region, usagePlanId, merged);
+ }
+
+ public void untagUsagePlan(String region, String usagePlanId, List<String> tagKeys) {
+ Map<String, String> remaining = new HashMap<>(getUsagePlan(region, usagePlanId).getTags());
+ tagKeys.forEach(remaining::remove);
+ replaceUsagePlanTags(region, usagePlanId, remaining);
+ }
+
// ──────────────────────────── Usage Plan Keys ────────────────────────────
public UsagePlanKey createUsagePlanKey(String region, String usagePlanId, Map<String, Object> request) {
@@ -2695,6 +2725,61 @@ public class ApiGatewayService {
}
}
+ // ──────────────────────────── Resource Explorer 2 ────────────────────────────
+
+ @Override
+ public List<ExplorerResource> getResources() {
+ String account = regionResolver.getAccountId();
+ List<ExplorerResource> resources = new ArrayList<>();
+ for (String key : apiStore.keys()) {
+ apiStore.get(key).ifPresent(api -> resources.add(explorerResource(key, account,
+ "/restapis/" + api.getId(), "apigateway:restapis", api.getCreatedDate(), api.getTags())));
+ }
+ for (String key : stageStore.keys()) {
+ String[] parts = key.split("::", 3);
+ if (parts.length == 3) {
+ stageStore.get(key).ifPresent(stage -> resources.add(explorerResource(key, account,
+ "/restapis/" + parts[1] + "/stages/" + stage.getStageName(), "apigateway:restapis/stages",
+ stage.getCreatedDate(), stage.getTags())));
+ }
+ }
+ for (String key : apiKeyStore.keys()) {
+ apiKeyStore.get(key).ifPresent(apiKey -> resources.add(explorerResource(key, account,
+ "/apikeys/" + apiKey.getId(), "apigateway:apikeys", apiKey.getCreatedDate(), apiKey.getTags())));
+ }
+ for (String key : usagePlanStore.keys()) {
+ usagePlanStore.get(key).ifPresent(plan -> resources.add(explorerResource(key, account,
+ "/usageplans/" + plan.getId(), "apigateway:usageplans", 0, plan.getTags())));
+ }
+ for (String key : domainStore.keys()) {
+ domainStore.get(key).ifPresent(domain -> resources.add(explorerResource(key, account,
+ "/domainnames/" + domain.getDomainName(), "apigateway:domainnames", 0, domain.getTags())));
+ }
+ return resources;
+ }
+
+ @Override
+ public Set<SupportedResourceType> getSupportedResourceTypes() {
+ return Set.of(
+ new SupportedResourceType("apigateway:restapis", "apigateway", true),
+ new SupportedResourceType("apigateway:restapis/stages", "apigateway", true),
+ new SupportedResourceType("apigateway:apikeys", "apigateway", true),
+ new SupportedResourceType("apigateway:usageplans", "apigateway", true),
+ new SupportedResourceType("apigateway:domainnames", "apigateway", true));
+ }
+
+ /** API Gateway ARNs carry no account: {@code arn:<partition>:apigateway:<region>::<path>}. */
+ private static ExplorerResource explorerResource(String storeKey, String account, String path,
+ String resourceType, long createdEpochSeconds,
+ Map<String, String> tags) {
+ String region = storeKey.substring(0, storeKey.indexOf("::"));
+ return new ExplorerResource(
+ AwsArnUtils.Arn.of("apigateway", region, "", path).toString(),
+ resourceType, "apigateway", region, account,
+ createdEpochSeconds > 0 ? Instant.ofEpochSecond(createdEpochSeconds) : Instant.now(),
+ tags != null ? tags : Map.of());
+ }
+
// ──────────────────────────── OpenAPI Import ────────────────────────────
public RestApi importRestApi(String region, String specBody) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagHandler.java
index 2c2a0e0b1c..07aa4b3185 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagHandler.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.apigateway;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.TagHandler;
import jakarta.enterprise.context.ApplicationScoped;
@@ -7,20 +8,27 @@ import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
/**
* {@link TagHandler} implementation for API Gateway.
*
- * <p>ARN formats: {@code arn:aws:apigateway:<region>::/restapis/<apiId>} for a REST API and
- * {@code arn:aws:apigateway:<region>::/domainnames/<domainName>} for a custom domain. The
- * {@code apiId} or domain name is the canonical identifier the underlying {@link ApiGatewayService}
- * uses for its tag store.
+ * <p>ARN formats: {@code arn:aws:apigateway:<region>::/restapis/<apiId>} for a REST API,
+ * {@code arn:aws:apigateway:<region>::/domainnames/<domainName>} for a custom domain,
+ * {@code arn:aws:apigateway:<region>::/apikeys/<apiKeyId>} for an API key and
+ * {@code arn:aws:apigateway:<region>::/usageplans/<usagePlanId>} for a usage plan. The
+ * {@code apiId}, domain name, key id or plan id is the canonical identifier the underlying
+ * {@link ApiGatewayService} uses for its tag store.
*/
@ApplicationScoped
public class ApiGatewayTagHandler implements TagHandler {
+ private static final String API_KEYS = "/apikeys/";
private static final String DOMAIN_NAMES = "/domainnames/";
- private static final String STAGES = "/stages/";
+ private static final String REST_APIS = "/restapis/";
+ private static final String USAGE_PLANS = "/usageplans/";
+ private static final Pattern STAGE_RESOURCE = Pattern.compile("/restapis/[^/]+/stages/([^/]+)");
private final ApiGatewayService service;
@@ -41,39 +49,84 @@ public class ApiGatewayTagHandler implements TagHandler {
@Override
public Map<String, String> listTags(String region, String arn) {
- String domainName = domainNameFromArn(arn);
+ rejectAccountOrOtherRegion(region, arn);
+ String domainName = topLevelIdFromArn(arn, DOMAIN_NAMES);
if (domainName != null) {
return service.getDomainNameTags(region, domainName);
}
+ String apiKeyId = topLevelIdFromArn(arn, API_KEYS);
+ if (apiKeyId != null) {
+ return service.getApiKey(region, apiKeyId).getTags();
+ }
+ String usagePlanId = topLevelIdFromArn(arn, USAGE_PLANS);
+ if (usagePlanId != null) {
+ return service.getUsagePlan(region, usagePlanId).getTags();
+ }
String stageName = stageNameFromArn(arn);
return stageName != null
? service.getStageTags(region, apiIdFromArn(arn), stageName)
- : service.getTags(region, apiIdFromArn(arn));
+ : service.getTags(region, restApiIdFromArn(arn));
}
@Override
public void tagResource(String region, String arn, Map<String, String> tags) {
- String domainName = domainNameFromArn(arn);
+ rejectAccountOrOtherRegion(region, arn);
+ String domainName = topLevelIdFromArn(arn, DOMAIN_NAMES);
+ String apiKeyId = topLevelIdFromArn(arn, API_KEYS);
+ String usagePlanId = topLevelIdFromArn(arn, USAGE_PLANS);
String stageName = stageNameFromArn(arn);
if (domainName != null) {
service.tagDomainName(region, domainName, tags);
+ } else if (apiKeyId != null) {
+ service.tagApiKey(region, apiKeyId, tags);
+ } else if (usagePlanId != null) {
+ service.tagUsagePlan(region, usagePlanId, tags);
} else if (stageName != null) {
service.tagStage(region, apiIdFromArn(arn), stageName, tags);
} else {
- service.tagResource(region, apiIdFromArn(arn), tags);
+ service.tagResource(region, restApiIdFromArn(arn), tags);
}
}
@Override
public void untagResource(String region, String arn, List<String> tagKeys) {
- String domainName = domainNameFromArn(arn);
+ rejectAccountOrOtherRegion(region, arn);
+ String domainName = topLevelIdFromArn(arn, DOMAIN_NAMES);
+ String apiKeyId = topLevelIdFromArn(arn, API_KEYS);
+ String usagePlanId = topLevelIdFromArn(arn, USAGE_PLANS);
String stageName = stageNameFromArn(arn);
if (domainName != null) {
service.untagDomainName(region, domainName, tagKeys);
+ } else if (apiKeyId != null) {
+ service.untagApiKey(region, apiKeyId, tagKeys);
+ } else if (usagePlanId != null) {
+ service.untagUsagePlan(region, usagePlanId, tagKeys);
} else if (stageName != null) {
service.untagStage(region, apiIdFromArn(arn), stageName, tagKeys);
} else {
- service.untagResource(region, apiIdFromArn(arn), tagKeys);
+ service.untagResource(region, restApiIdFromArn(arn), tagKeys);
+ }
+ }
+
+ /**
+ * API Gateway ARNs carry no account: AWS rejects one that does, even the caller's own, before
+ * resolving anything, and answers an ARN naming another region as a missing resource. A string
+ * that is not an ARN is left to the parse and its errors.
+ */
+ private static void rejectAccountOrOtherRegion(String region, String arn) {
+ if (!AwsArnUtils.isArn(arn)) {
+ return;
+ }
+ AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
+ // ponytail: AWS names the resource type in both messages ("on RestApi <id>", "Invalid API
+ // identifier specified <account>:<id>"); Floci uses one generic message per error.
+ if (!parsed.accountId().isEmpty()) {
+ AwsArnUtils.Arn canonical = new AwsArnUtils.Arn(
+ parsed.partition(), parsed.service(), parsed.region(), "", parsed.resource());
+ throw new AwsException("BadRequestException", "Expected ARN " + canonical + ", not " + arn, 400);
+ }
+ if (!parsed.region().isEmpty() && !parsed.region().equals(region)) {
+ throw new AwsException("NotFoundException", "Invalid resource identifier specified", 404);
}
}
@@ -86,29 +139,45 @@ public class ApiGatewayTagHandler implements TagHandler {
}
/**
- * The stage a {@code /restapis/<apiId>/stages/<stageName>} ARN names, or null for any other ARN.
- * Stages carry their own tags; without this they would land on the REST API.
+ * The id a {@code /restapis/<apiId>} ARN names. Any other ARN, such as a deployment or resource
+ * nested under a REST API, is rejected as AWS rejects it rather than tagging the REST API.
+ */
+ private static String restApiIdFromArn(String arn) {
+ String apiId = topLevelIdFromArn(arn, REST_APIS);
+ if (apiId == null) {
+ throw new AwsException("BadRequestException", "Invalid ARN specified in the request", 400);
+ }
+ return apiId;
+ }
+
+ /**
+ * The stage an ARN whose resource part is exactly {@code /restapis/<apiId>/stages/<stageName>}
+ * names, or null for any other ARN. Stages carry their own tags; without this they would land on
+ * the REST API.
*/
private static String stageNameFromArn(String arn) {
- int at = arn.indexOf(STAGES);
- if (at < 0 || !arn.contains("/restapis/")) {
+ if (!AwsArnUtils.isArn(arn)) {
return null;
}
- String stageName = arn.substring(at + STAGES.length());
- return stageName.isEmpty() || stageName.contains("/") ? null : stageName;
+ Matcher matcher = STAGE_RESOURCE.matcher(AwsArnUtils.parse(arn).resource());
+ return matcher.matches() ? matcher.group(1) : null;
}
/**
- * The domain a {@code /domainnames/<name>} ARN names, or null for any other ARN. A base path
- * mapping ARN continues past the domain and is not taggable, so it falls through to the REST API
- * parse and its "invalid ARN" answer.
+ * The id an ARN whose resource part is exactly {@code <prefix><id>} names, such as
+ * {@code /apikeys/<apiKeyId>} or {@code /domainnames/<domainName>}, or null for any other ARN,
+ * including one that nests the prefix under another resource. A base path mapping ARN continues
+ * past the domain, so it falls through to the REST API parse and its "invalid ARN" answer.
*/
- private static String domainNameFromArn(String arn) {
- int at = arn.indexOf(DOMAIN_NAMES);
- if (at < 0) {
+ private static String topLevelIdFromArn(String arn, String prefix) {
+ if (!AwsArnUtils.isArn(arn)) {
+ return null;
+ }
+ String resource = AwsArnUtils.parse(arn).resource();
+ if (!resource.startsWith(prefix)) {
return null;
}
- String domainName = arn.substring(at + DOMAIN_NAMES.length());
- return domainName.isEmpty() || domainName.contains("/") ? null : domainName;
+ String id = resource.substring(prefix.length());
+ return id.isEmpty() || id.contains("/") ? null : id;
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java
index d57995f41d..7670cac313 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java
@@ -24,6 +24,7 @@ import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashMap;
@@ -32,6 +33,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
+import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -53,6 +55,7 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
private static final String HOT_RELOAD_BUCKET = "hot-reload";
private static final String LAMBDA_NAME_MODE_ATTR = "FlociLambdaFunctionNameMode";
private static final String LAMBDA_PACKAGE_TYPE_ATTR = "FlociLambdaPackageType";
+ private static final String LAMBDA_TEMPLATE_TAG_KEYS_ATTR = "FlociLambdaTemplateTagKeys";
private static final String NAME_MODE_EXPLICIT = "explicit";
private static final String NAME_MODE_GENERATED = "generated";
@@ -108,18 +111,31 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
boolean replacement = lambdaRequiresReplacement(r, desired, existing);
LambdaFunction func;
+ boolean adopted = false;
if (existing == null || replacement) {
if (replacement && desired.functionName().equals(r.getPhysicalId())) {
throw new AwsException("ValidationError",
"Cannot replace Lambda function " + r.getPhysicalId()
+ " without a new FunctionName", 400);
}
- func = createLambdaFunction(region, desired, !replacement);
+ try {
+ func = lambdaService.createFunction(region, desired.createRequest());
+ } catch (AwsException e) {
+ if (!replacement && ("ResourceConflictException".equals(e.getErrorCode())
+ || (e.getMessage() != null && e.getMessage().contains("Function already exist")))) {
+ func = lambdaService.getFunction(region, desired.functionName());
+ adopted = true;
+ } else {
+ throw e;
+ }
+ }
if (replacement && r.getPhysicalId() != null) {
deleteReplacedLambda(region, r.getPhysicalId());
}
} else {
func = updateLambdaFunction(region, existing, desired, r);
+ reconcileTags(func.getFunctionArn(), r.getAttributes().get(LAMBDA_TEMPLATE_TAG_KEYS_ATTR),
+ desired.tags());
}
applyLambdaReservedConcurrency(region, func, desired);
@@ -130,6 +146,13 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put(LAMBDA_NAME_MODE_ATTR,
desired.explicitFunctionName() ? NAME_MODE_EXPLICIT : NAME_MODE_GENERATED);
r.getAttributes().put(LAMBDA_PACKAGE_TYPE_ATTR, desired.packageType());
+ if (adopted) {
+ r.getAttributes().remove(LAMBDA_TEMPLATE_TAG_KEYS_ATTR);
+ } else {
+ // Tag keys cannot contain a comma, so the sorted keys join losslessly.
+ r.getAttributes().put(LAMBDA_TEMPLATE_TAG_KEYS_ATTR,
+ String.join(",", new TreeSet<>(desired.tags().keySet())));
+ }
}
private LambdaDesiredState buildLambdaDesiredState(StackResource r, JsonNode props, ProvisionContext ctx) {
@@ -236,6 +259,11 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
putResolvedMapIfPresent(configRequest, props, "ImageConfig", "ImageConfig", engine);
createRequest.putAll(configRequest);
+ Map<String, String> tags = ctx.resolveTags(props, "Tags");
+ LambdaService.validateTagKeys(tags);
+ if (!tags.isEmpty()) {
+ createRequest.put("Tags", tags);
+ }
Integer reservedConcurrentExecutions = null;
String reserved = ctx.resolveOptional(props, "ReservedConcurrentExecutions");
if (reserved != null) {
@@ -248,7 +276,7 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
}
return new LambdaDesiredState(functionName, hasExplicitName, packageType,
- createRequest, code, configRequest, props != null && props.has("ReservedConcurrentExecutions"),
+ createRequest, code, configRequest, tags, props != null && props.has("ReservedConcurrentExecutions"),
reservedConcurrentExecutions);
}
@@ -354,18 +382,6 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
return !Objects.equals(existingPackageType, desired.packageType());
}
- private LambdaFunction createLambdaFunction(String region, LambdaDesiredState desired, boolean allowAdopt) {
- try {
- return lambdaService.createFunction(region, desired.createRequest());
- } catch (AwsException e) {
- if (allowAdopt && ("ResourceConflictException".equals(e.getErrorCode())
- || (e.getMessage() != null && e.getMessage().contains("Function already exist")))) {
- return lambdaService.getFunction(region, desired.functionName());
- }
- throw e;
- }
- }
-
private LambdaFunction updateLambdaFunction(String region,
LambdaFunction existing,
LambdaDesiredState desired,
@@ -381,6 +397,26 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
return current;
}
+ /**
+ * Applies the template's tags to an in-place updated function and untags only the keys the
+ * previous template set and this one drops, so a tag added outside the template stays, as in
+ * AWS. A function provisioned before the keys were recorded has none to drop. A created
+ * function already carries its tags in the create request.
+ */
+ private void reconcileTags(String functionArn, String previousTemplateKeys, Map<String, String> desired) {
+ List<String> dropped = previousTemplateKeys == null || previousTemplateKeys.isEmpty()
+ ? List.of()
+ : Arrays.stream(previousTemplateKeys.split(","))
+ .filter(key -> !desired.containsKey(key))
+ .toList();
+ if (!dropped.isEmpty()) {
+ lambdaService.untagResource(functionArn, dropped);
+ }
+ if (!desired.isEmpty()) {
+ lambdaService.tagResource(functionArn, desired);
+ }
+ }
+
private void deleteReplacedLambda(String region, String functionName) {
try {
lambdaService.deleteFunction(region, functionName);
@@ -886,6 +922,7 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
Map<String, Object> createRequest,
LambdaCodeSpec code,
Map<String, Object> configRequest,
+ Map<String, String> tags,
boolean reservedConcurrentExecutionsPresent,
Integer reservedConcurrentExecutions) {}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SsmCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SsmCfnProvisioner.java
index f0910cbb71..f0afd60c1e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SsmCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SsmCfnProvisioner.java
@@ -6,13 +6,18 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.ssm.SsmService;
import jakarta.enterprise.context.ApplicationScoped;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
import java.util.Set;
+import java.util.TreeSet;
/** Provisions {@code AWS::SSM::Parameter}. */
@ApplicationScoped
public class SsmCfnProvisioner implements CfnResourceProvisioner {
private static final int PARAMETER_NAME_MAX_LENGTH = 2048;
+ private static final String SSM_TEMPLATE_TAG_KEYS_ATTR = "FlociSsmTemplateTagKeys";
private final SsmService ssmService;
@@ -37,12 +42,42 @@ public class SsmCfnProvisioner implements CfnResourceProvisioner {
if (type == null) {
type = "String";
}
+ Map<String, String> tags = ctx.resolveTags(props, "Tags");
+ SsmService.validateTagKeys(tags);
ssmService.putParameter(name, value, type, null, true, ctx.region());
+ reconcileTags(name, r.getAttributes().get(SSM_TEMPLATE_TAG_KEYS_ATTR), tags, ctx.region());
r.setPhysicalId(name);
r.getAttributes().put("Name", name);
r.getAttributes().put("Type", type);
r.getAttributes().put("Value", value);
r.getAttributes().put("Arn", parameterArn(name, ctx));
+ // Tag keys cannot contain a comma, so the sorted keys join losslessly.
+ if (tags.isEmpty()) {
+ r.getAttributes().remove(SSM_TEMPLATE_TAG_KEYS_ATTR);
+ } else {
+ r.getAttributes().put(SSM_TEMPLATE_TAG_KEYS_ATTR, String.join(",", new TreeSet<>(tags.keySet())));
+ }
+ }
+
+ /**
+ * Applies the template's tags and removes only the keys the previous template set and this one
+ * drops, so a tag added outside the template stays, as in AWS. The overwriting put keeps the
+ * parameter's existing tags, and a parameter provisioned before the keys were recorded has none
+ * to drop.
+ */
+ private void reconcileTags(String name, String previousTemplateKeys, Map<String, String> desired,
+ String region) {
+ List<String> dropped = previousTemplateKeys == null || previousTemplateKeys.isEmpty()
+ ? List.of()
+ : Arrays.stream(previousTemplateKeys.split(","))
+ .filter(key -> !desired.containsKey(key))
+ .toList();
+ if (!dropped.isEmpty()) {
+ ssmService.removeTagsFromResource(name, dropped, region);
+ }
+ if (!desired.isEmpty()) {
+ ssmService.addTagsToResource(name, desired, region);
+ }
}
/** AWS's form is {@code parameter/<name>} whether or not the name starts with a slash. */
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java
index 45d2c6f1b5..efe6d58bfc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsHandler.java
@@ -642,7 +642,7 @@ public class CloudWatchLogsHandler {
return name;
}
- private String extractLogGroupNameFromArn(String arn) {
+ static String extractLogGroupNameFromArn(String arn) {
if (arn != null && arn.contains(":log-group:")) {
String name = arn.substring(arn.indexOf(":log-group:") + ":log-group:".length());
if (name.endsWith(":*")) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/LogsTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/LogsTagHandler.java
new file mode 100644
index 0000000000..b87461b1c0
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/LogsTagHandler.java
@@ -0,0 +1,57 @@
+package io.github.hectorvent.floci.services.cloudwatch.logs;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.TagHandler;
+import io.github.hectorvent.floci.core.common.TaggingApiOnly;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Lets Resource Groups Tagging API writes reach a log group's own tags.
+ *
+ * <p>A separate {@link TaggingApiOnly} bean because CloudWatch Logs tags through its own JSON
+ * {@code TagResource} action: a default-qualified handler would also serve the log group on
+ * {@code /tags/{arn}}, which AWS does not define.
+ */
+@ApplicationScoped
+@TaggingApiOnly
+public class LogsTagHandler implements TagHandler {
+
+ private final CloudWatchLogsService logsService;
+
+ @Inject
+ public LogsTagHandler(CloudWatchLogsService logsService) {
+ this.logsService = logsService;
+ }
+
+ @Override
+ public String serviceKey() {
+ return "logs";
+ }
+
+ @Override
+ public Map<String, String> listTags(String region, String arn) {
+ return logsService.listTagsLogGroup(logGroupName(arn), region);
+ }
+
+ @Override
+ public void tagResource(String region, String arn, Map<String, String> tags) {
+ logsService.tagLogGroup(logGroupName(arn), tags, region);
+ }
+
+ @Override
+ public void untagResource(String region, String arn, List<String> tagKeys) {
+ logsService.untagLogGroup(logGroupName(arn), tagKeys, region);
+ }
+
+ // AWS rejects the :* form of a log group ARN here, as Logs' own ListTagsForResource does.
+ private static String logGroupName(String arn) {
+ if (arn.endsWith(":*")) {
+ throw new AwsException("ValidationException", "Invalid resourceArn", 400);
+ }
+ return CloudWatchLogsHandler.extractLogGroupNameFromArn(arn);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
index 46c991b930..eb37f995be 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
@@ -85,6 +85,8 @@ public class LambdaService implements ResourceProvider {
"^arn:(aws[a-zA-Z-]*)?:iam::\\d{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+$");
private static final Pattern HANDLER_PATTERN = Pattern.compile("^[^\\s]+$");
private static final int MAX_HANDLER_LENGTH = 128;
+ private static final Pattern TAG_KEY_PATTERN = Pattern.compile("([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)");
+ private static final int MAX_TAG_KEY_LENGTH = 128;
private static final Pattern KMS_KEY_ARN_PATTERN = Pattern.compile(
"^(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)?$");
private static final Pattern LAYER_VERSION_ARN_PATTERN = Pattern.compile(
@@ -436,6 +438,9 @@ public class LambdaService implements ResourceProvider {
validateEnum(runtime, "runtime", RUNTIME_VALUES);
validateMaxLength(description, "description", 256);
+ @SuppressWarnings("unchecked")
+ Map<String, String> tags = (Map<String, String>) request.get("Tags");
+ validateTagKeys(tags);
if (functionStore.get(region, functionName).isPresent()) {
throw new AwsException("ResourceConflictException",
"Function already exist: " + functionName, 409);
@@ -463,8 +468,6 @@ public class LambdaService implements ResourceProvider {
}
// Handle tags
- @SuppressWarnings("unchecked")
- Map<String, String> tags = (Map<String, String>) request.get("Tags");
if (tags != null) fn.setTags(tags);
if (architectures != null && !architectures.isEmpty()) {
@@ -3356,6 +3359,7 @@ public class LambdaService implements ResourceProvider {
}
public void tagResource(String functionArn, Map<String, String> tags) {
+ validateTagKeys(tags);
EventSourceMapping esm = taggedEventSourceMapping(functionArn);
if (esm != null) {
esm.getTags().putAll(tags);
@@ -3369,6 +3373,26 @@ public class LambdaService implements ResourceProvider {
functionStore.save(target.region, fn);
}
+ /**
+ * The key constraint AWS checks before any lookup. AWS renders the whole map in the message, so
+ * {@code toString()} gives its {@code {key=value}} form.
+ */
+ public static void validateTagKeys(Map<String, String> tags) {
+ if (tags == null) {
+ return;
+ }
+ for (String key : tags.keySet()) {
+ if (key.isEmpty() || key.codePointCount(0, key.length()) > MAX_TAG_KEY_LENGTH
+ || !TAG_KEY_PATTERN.matcher(key).matches()) {
+ throw new AwsException("ValidationException", "1 validation error detected: Value '" + tags
+ + "' at 'tags' failed to satisfy constraint: Map keys must satisfy constraint: [Member"
+ + " must have length less than or equal to " + MAX_TAG_KEY_LENGTH + ", Member must have"
+ + " length greater than or equal to 1, Member must satisfy regular expression pattern: "
+ + TAG_KEY_PATTERN.pattern() + "]", 400);
+ }
+ }
+ }
+
public void untagResource(String functionArn, List<String> tagKeys) {
EventSourceMapping esm = taggedEventSourceMapping(functionArn);
if (esm != null) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagHandler.java
new file mode 100644
index 0000000000..54876d46d1
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaTagHandler.java
@@ -0,0 +1,48 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import io.github.hectorvent.floci.core.common.TagHandler;
+import io.github.hectorvent.floci.core.common.TaggingApiOnly;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Lets Resource Groups Tagging API writes reach a function's own tags.
+ *
+ * <p>A separate {@link TaggingApiOnly} bean because Lambda tags on its own
+ * {@code /2017-03-31/tags/{arn}} path: a default-qualified handler would also serve the
+ * function on {@code /tags/{arn}}, which AWS does not define.
+ */
+@ApplicationScoped
+@TaggingApiOnly
+public class LambdaTagHandler implements TagHandler {
+
+ private final LambdaService lambdaService;
+
+ @Inject
+ public LambdaTagHandler(LambdaService lambdaService) {
+ this.lambdaService = lambdaService;
+ }
+
+ @Override
+ public String serviceKey() {
+ return "lambda";
+ }
+
+ @Override
+ public Map<String, String> listTags(String region, String arn) {
+ return lambdaService.listTags(arn);
+ }
+
+ @Override
+ public void tagResource(String region, String arn, Map<String, String> tags) {
+ lambdaService.tagResource(arn, tags);
+ }
+
+ @Override
+ public void untagResource(String region, String arn, List<String> tagKeys) {
+ lambdaService.untagResource(arn, tagKeys);
+ }
+}
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
index eef9e96d43..0e6ae44186 100644
--- a/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingJsonHandler.java
@@ -5,6 +5,7 @@ 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.core.common.AwsException;
import io.github.hectorvent.floci.services.resourcegroupstagging.model.ResourceTagMapping;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -70,11 +71,10 @@ public class ResourceGroupsTaggingJsonHandler {
Map<String, String> tags = new LinkedHashMap<>();
request.path("Tags").fields().forEachRemaining(e -> tags.put(e.getKey(), e.getValue().asText()));
- service.tagResources(arns, tags, region);
+ Map<String, AwsException> failures = service.applyTags(arns, tags, region);
ObjectNode response = objectMapper.createObjectNode();
- // FailedResourcesMap is empty on success
- response.set("FailedResourcesMap", objectMapper.createObjectNode());
+ response.set("FailedResourcesMap", failedResourcesMap(failures));
return Response.ok(response).build();
}
@@ -84,10 +84,10 @@ public class ResourceGroupsTaggingJsonHandler {
List<String> arns = toStringList(request.path("ResourceARNList"));
List<String> tagKeys = toStringList(request.path("TagKeys"));
- service.untagResources(arns, tagKeys, region);
+ Map<String, AwsException> failures = service.removeTags(arns, tagKeys, region);
ObjectNode response = objectMapper.createObjectNode();
- response.set("FailedResourcesMap", objectMapper.createObjectNode());
+ response.set("FailedResourcesMap", failedResourcesMap(failures));
return Response.ok(response).build();
}
@@ -126,6 +126,18 @@ public class ResourceGroupsTaggingJsonHandler {
// ─── Helpers ───────────────────────────────────────────────────────────────
+ // AWS reports the owning service's own error, although the model's ErrorCode enum names only two codes.
+ private ObjectNode failedResourcesMap(Map<String, AwsException> failures) {
+ ObjectNode map = objectMapper.createObjectNode();
+ failures.forEach((arn, e) -> {
+ ObjectNode info = map.putObject(arn);
+ info.put("StatusCode", e.getHttpStatus());
+ info.put("ErrorCode", e.getErrorCode());
+ info.put("ErrorMessage", e.getMessage());
+ });
+ return map;
+ }
+
private List<String> toStringList(JsonNode node) {
List<String> result = new ArrayList<>();
if (node != null && node.isArray()) {
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
index ff6d4fa181..5c0c2e06cb 100644
--- a/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingService.java
@@ -2,30 +2,77 @@ package io.github.hectorvent.floci.services.resourcegroupstagging;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.Resettable;
+import io.github.hectorvent.floci.core.common.TagHandler;
+import io.github.hectorvent.floci.core.resource.ExplorerResource;
+import io.github.hectorvent.floci.core.resource.ResourceProvider;
+import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.StorageBackedMap;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.resourcegroupstagging.model.ResourceTagMapping;
-import io.github.hectorvent.floci.core.common.Resettable;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Any;
+import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.Pattern;
import java.util.stream.Collectors;
@ApplicationScoped
public class ResourceGroupsTaggingService implements Resettable {
+ private static final Logger LOG = Logger.getLogger(ResourceGroupsTaggingService.class);
+ private static final Pattern TYPE_DELIMITER = Pattern.compile("[/:]");
+ private static final String WILDCARD_SUFFIX = ":*";
+ private static final String GLOBAL_REGION = "global";
+
private final StorageFactory storageFactory;
+ private final Iterable<ResourceProvider> providers;
+ private final Iterable<TagHandler> tagHandlers;
+ private final RegionResolver regionResolver;
// region::arn → ResourceTagMapping
private Map<String, ResourceTagMapping> store = new ConcurrentHashMap<>();
@Inject
+ public ResourceGroupsTaggingService(StorageFactory storageFactory,
+ Instance<ResourceProvider> providers,
+ @Any Instance<TagHandler> tagHandlers,
+ RegionResolver regionResolver) {
+ // The upcasts select the Iterable constructor instead of recursing into this one.
+ this(storageFactory, (Iterable<ResourceProvider>) providers, (Iterable<TagHandler>) tagHandlers,
+ regionResolver);
+ }
+
public ResourceGroupsTaggingService(StorageFactory storageFactory) {
+ this(storageFactory, List.of(), List.of(), null);
+ }
+
+ ResourceGroupsTaggingService(StorageFactory storageFactory,
+ Iterable<ResourceProvider> providers,
+ Iterable<TagHandler> tagHandlers,
+ RegionResolver regionResolver) {
this.storageFactory = storageFactory;
+ this.providers = providers;
+ this.tagHandlers = tagHandlers;
+ this.regionResolver = regionResolver;
}
@PostConstruct
@@ -89,6 +136,144 @@ public class ResourceGroupsTaggingService implements Resettable {
store.clear();
}
+ // ─── Write-through for the tagging API ────────────────────────────────────
+
+ /**
+ * TagResources from the tagging API. An ARN that a {@link ResourceProvider} currently lists,
+ * visible to the request's region and account as on the read path, goes to its owning
+ * service's {@link TagHandler} only, so the owner holds the one copy; any other ARN goes to
+ * the tagging store. {@link #tagResources} stays store-only for services that dual-write, so
+ * they can never recurse through their own handler.
+ *
+ * @return the owning service's rejection per ARN, empty when every ARN was tagged; an ARN whose
+ * owner could not be read is reported as {@code InternalServiceException}, and one from
+ * another account as {@code AccessDeniedException}
+ * @throws AwsException {@code InvalidParameterException} when an ARN names another region;
+ * nothing is tagged then
+ */
+ public Map<String, AwsException> applyTags(List<String> resourceArns, Map<String, String> tags, String region) {
+ rejectOtherRegion(resourceArns, region, "TagResources");
+ Map<String, AwsException> failures = new LinkedHashMap<>();
+ Map<String, TagHandler> owners = listedOwners(resourceArns, region, failures);
+ for (String arn : resourceArns) {
+ if (failures.containsKey(arn)) {
+ continue;
+ }
+ TagHandler owner = owners.get(arn);
+ if (owner == null) {
+ tagResources(List.of(arn), tags, region);
+ continue;
+ }
+ try {
+ owner.tagResource(region, arn, tags);
+ } catch (AwsException e) {
+ failures.put(arn, e);
+ }
+ }
+ return failures;
+ }
+
+ /**
+ * UntagResources from the tagging API, routed as {@link #applyTags} routes. The keys also
+ * leave the tagging store for every ARN except one reported as unresolved or from another
+ * account, still including one its owning service rejected, so a copy stored earlier can
+ * always be cleared.
+ *
+ * @return the owning service's rejection per ARN, empty when every ARN was untagged; an ARN whose
+ * owner could not be read is reported as {@code InternalServiceException}, and one from
+ * another account as {@code AccessDeniedException}
+ * @throws AwsException {@code InvalidParameterException} when an ARN names another region;
+ * nothing is untagged then
+ */
+ public Map<String, AwsException> removeTags(List<String> resourceArns, List<String> tagKeys, String region) {
+ rejectOtherRegion(resourceArns, region, "UntagResources");
+ Map<String, AwsException> failures = new LinkedHashMap<>();
+ Map<String, TagHandler> owners = listedOwners(resourceArns, region, failures);
+ List<String> resolved = resourceArns.stream().filter(arn -> !failures.containsKey(arn)).toList();
+ for (String arn : resourceArns) {
+ TagHandler owner = owners.get(arn);
+ if (owner != null) {
+ try {
+ owner.untagResource(region, arn, tagKeys);
+ } catch (AwsException e) {
+ failures.put(arn, e);
+ }
+ }
+ }
+ untagResources(resolved, tagKeys, region);
+ return failures;
+ }
+
+ private static void rejectOtherRegion(List<String> resourceArns, String region, String operation) {
+ for (String arn : resourceArns) {
+ String arnRegion = AwsArnUtils.regionOrDefault(arn, "");
+ if (!arnRegion.isEmpty() && !arnRegion.equals(region)) {
+ throw new AwsException("InvalidParameterException", "Region in the ARN " + arn
+ + " does not match with the region in which " + operation + " API is invoked", 400);
+ }
+ }
+ }
+
+ // Providers are only read when some ARN has a handler, so a store-only request stays cheap. When the
+ // provider of an ARN's service failed, an unlisted ARN with a handler may be one it lists, so it fails.
+ private Map<String, TagHandler> listedOwners(List<String> resourceArns, String region,
+ Map<String, AwsException> failures) {
+ Map<String, TagHandler> owners = new HashMap<>();
+ String accountId = regionResolver != null ? regionResolver.getAccountId() : null;
+ Set<String> listed = null;
+ Set<String> unreadServices = Set.of();
+ for (String arn : resourceArns) {
+ // ponytail: AWS returns the owner's own error code per ARN; Floci uses AccessDeniedException 403 for all.
+ if (accountId != null && !AwsArnUtils.accountOrDefault(arn, accountId).equals(accountId)) {
+ failures.put(arn, new AwsException("AccessDeniedException",
+ "The resource belongs to another account.", 403));
+ continue;
+ }
+ TagHandler handler = ownerHandler(arn);
+ if (handler == null) {
+ continue;
+ }
+ if (listed == null) {
+ listed = new HashSet<>();
+ ProviderScan scan = providerResources();
+ unreadServices = scan.unreadServices();
+ for (ExplorerResource resource : scan.resources()) {
+ String listedArn = withoutWildcard(resource.arn());
+ String resourceRegion = providerRegion(listedArn, resource.region());
+ if (resourceRegion != null && resourceRegion.equals(region)
+ && isVisible(listedArn, region, accountId)) {
+ listed.add(listedArn);
+ }
+ }
+ }
+ // A wildcard ARN always reaches its handler, which rejects it as AWS does, listed or not.
+ if (arn.endsWith(WILDCARD_SUFFIX) || listed.contains(arn)) {
+ owners.put(arn, handler);
+ } else if (unreadServices.contains(handler.serviceKey())) {
+ failures.put(arn, new AwsException("InternalServiceException",
+ "An owning service could not be read. Retry the request.", 500));
+ }
+ }
+ return owners;
+ }
+
+ private TagHandler ownerHandler(String arn) {
+ if (!AwsArnUtils.isArn(arn)) {
+ return null;
+ }
+ String service = AwsArnUtils.parse(arn).service();
+ for (TagHandler handler : tagHandlers) {
+ if (handler.serviceKey().equals(service)) {
+ return handler;
+ }
+ }
+ return null;
+ }
+
+ private static String withoutWildcard(String arn) {
+ return arn.endsWith(WILDCARD_SUFFIX) ? arn.substring(0, arn.length() - WILDCARD_SUFFIX.length()) : arn;
+ }
+
// ─── GetResources ──────────────────────────────────────────────────────────
public record TagFilter(String key, List<String> values) {}
@@ -101,24 +286,15 @@ public class ResourceGroupsTaggingService implements Resettable {
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))
+ List<ResourceTagMapping> all = visibleEntries(region).stream()
+ .filter(e -> resourceArnList == null || resourceArnList.isEmpty()
+ || resourceArnList.contains(e.mapping().getResourceArn()))
+ .filter(e -> matchesTagFilters(e.mapping(), tagFilters))
+ .filter(e -> matchesResourceTypeFilters(e, resourceTypeFilters))
+ .map(ViewEntry::mapping)
.collect(Collectors.toList());
- int offset = decodePaginationToken(paginationToken);
+ int offset = Math.min(decodePaginationToken(paginationToken), all.size());
int pageSize = (resourcesPerPage > 0) ? resourcesPerPage : 100;
int end = Math.min(offset + pageSize, all.size());
List<ResourceTagMapping> page = all.subList(offset, end);
@@ -137,53 +313,156 @@ public class ResourceGroupsTaggingService implements Resettable {
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>:::...
- AwsArnUtils.Arn arn;
- try {
- arn = AwsArnUtils.parse(m.getResourceArn());
- } catch (IllegalArgumentException e) {
+ private boolean matchesResourceTypeFilters(ViewEntry entry, List<String> resourceTypeFilters) {
+ if (resourceTypeFilters == null || resourceTypeFilters.isEmpty()) {
+ return true;
+ }
+ String resourceArn = entry.mapping().getResourceArn();
+ if (!AwsArnUtils.isArn(resourceArn)) {
return false;
}
- String service = arn.service();
- String resourcePart = arn.resource(); // "type/id" or just "type"
- String resourceType = resourcePart.contains("/")
- ? resourcePart.substring(0, resourcePart.indexOf('/'))
- : resourcePart;
- // filter format is "service:resourceType" (e.g. "ec2:instance")
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
+ String resourceType = parsedType(arn.resource());
+ // filter format is "service[:resourceType]" (e.g. "ec2:instance", "apigateway:restapis/stages")
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;
+ if (!filterParts[0].equalsIgnoreCase(arn.service())) {
+ continue;
+ }
+ if (filterParts.length == 1) {
+ return true;
+ }
+ String filterType = filterParts[1];
+ if (filterType.equalsIgnoreCase(resourceType)
+ || entry.declaredTypes().stream().anyMatch(filterType::equalsIgnoreCase)) {
+ return true;
}
}
return false;
}
+ /**
+ * The type segment of an ARN resource part: one leading {@code /} dropped, then cut at the
+ * first {@code /} or {@code :}, so {@code function:f}, {@code instance/i-1} and
+ * {@code /apikeys/k} yield {@code function}, {@code instance} and {@code apikeys}.
+ */
+ static String parsedType(String resource) {
+ return TYPE_DELIMITER.split(stripLeadingSlash(resource), 2)[0];
+ }
+
+ private static String stripLeadingSlash(String value) {
+ return value.startsWith("/") ? value.substring(1) : value;
+ }
+
+ private static String typeSuffix(String resourceType) {
+ return resourceType.substring(resourceType.indexOf(':') + 1);
+ }
+
+ // ─── Merged view ───────────────────────────────────────────────────────────
+
+ private record ViewEntry(ResourceTagMapping mapping, Set<String> declaredTypes) {
+
+ static ViewEntry of(String arn) {
+ return new ViewEntry(new ResourceTagMapping(arn), new HashSet<>());
+ }
+ }
+
+ /**
+ * Store mappings plus every provider resource that has tags or is already in the store,
+ * visible to the request's region and account. The owning service's tags win on the same
+ * key. Entries are copies, so the stored mappings are never mutated.
+ */
+ private List<ViewEntry> visibleEntries(String region) {
+ String accountId = regionResolver != null ? regionResolver.getAccountId() : null;
+ // TreeMap keeps the ARN order offset pagination depends on
+ Map<String, ViewEntry> byArn = new TreeMap<>();
+ synchronized (this) {
+ for (ResourceTagMapping stored : store.values()) {
+ String arn = stored.getResourceArn();
+ // ponytail: IAM is the only global service with store-only ARNs handled here; another would need adding.
+ if (isVisible(arn, region, accountId) && !AwsArnUtils.isArnFor(arn, "iam")) {
+ byArn.computeIfAbsent(arn, ViewEntry::of).mapping().getTags().putAll(stored.getTags());
+ }
+ }
+ }
+ for (ExplorerResource resource : providerResources().resources()) {
+ String arn = withoutWildcard(resource.arn());
+ String resourceRegion = providerRegion(arn, resource.region());
+ // A global resource, or one owned in another region, hides any store copy of its ARN too.
+ if (resourceRegion == null || !resourceRegion.equals(region) || !isVisible(arn, region, accountId)) {
+ byArn.remove(arn);
+ continue;
+ }
+ ViewEntry entry = byArn.get(arn);
+ if (entry == null) {
+ if (resource.tags().isEmpty()) {
+ continue;
+ }
+ entry = ViewEntry.of(arn);
+ byArn.put(arn, entry);
+ }
+ entry.mapping().getTags().putAll(resource.tags());
+ entry.declaredTypes().add(typeSuffix(resource.resourceType()));
+ }
+ return new ArrayList<>(byArn.values());
+ }
+
+ private record ProviderScan(List<ExplorerResource> resources, Set<String> unreadServices) {}
+
+ // Tags are copied inside the try so a live tag map that changes mid-copy skips only its provider,
+ // and the services it declares are then unread.
+ private ProviderScan providerResources() {
+ List<ExplorerResource> resources = new ArrayList<>();
+ Set<String> unreadServices = new HashSet<>();
+ for (ResourceProvider provider : providers) {
+ try {
+ List<ExplorerResource> copies = new ArrayList<>();
+ for (ExplorerResource resource : provider.getResources()) {
+ copies.add(new ExplorerResource(resource.arn(), resource.resourceType(), resource.service(),
+ resource.region(), resource.owningAccountId(), resource.lastReportedAt(),
+ new HashMap<>(resource.tags())));
+ }
+ resources.addAll(copies);
+ } catch (RuntimeException e) {
+ LOG.warnv(e, "ResourceProvider {0} failed to supply resources; excluding it from tag discovery",
+ provider.getClass().getSimpleName());
+ for (SupportedResourceType type : provider.getSupportedResourceTypes()) {
+ unreadServices.add(type.service());
+ }
+ }
+ }
+ return new ProviderScan(resources, unreadServices);
+ }
+
+ // Region and account come from the ARN (arn:<partition>:svc:region:acct:resource), and a string
+ // that is not an ARN, or an ARN without a region, stays visible as it always has.
+ private static boolean isVisible(String arn, String region, String accountId) {
+ String[] parts = arn.split(":", 6);
+ if (parts.length >= 4 && !parts[3].isEmpty() && !parts[3].equals(region)) {
+ return false;
+ }
+ return accountId == null || parts.length < 5 || parts[4].isEmpty() || parts[4].equals(accountId);
+ }
+
+ // A provider resource's region is its ARN's, else the owner's region for it. Null means it has none,
+ // like the IAM resources reported as "global": the tagging API never lists or routes those.
+ private static String providerRegion(String arn, String ownerRegion) {
+ String resourceRegion = AwsArnUtils.regionOrDefault(arn, ownerRegion);
+ return resourceRegion == null || resourceRegion.isEmpty() || resourceRegion.equals(GLOBAL_REGION)
+ ? null
+ : resourceRegion;
+ }
+
// ─── 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())
+ List<String> keys = visibleEntries(region).stream()
+ .flatMap(e -> e.mapping().getTags().keySet().stream())
.distinct()
.sorted()
.collect(Collectors.toList());
- int offset = decodePaginationToken(paginationToken);
+ int offset = Math.min(decodePaginationToken(paginationToken), keys.size());
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)
@@ -197,22 +476,14 @@ public class ResourceGroupsTaggingService implements Resettable {
// ─── 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))
+ List<String> values = visibleEntries(region).stream()
+ .map(e -> e.mapping().getTags().get(tagKey))
.filter(Objects::nonNull)
.distinct()
.sorted()
.collect(Collectors.toList());
- int offset = decodePaginationToken(paginationToken);
+ int offset = Math.min(decodePaginationToken(paginationToken), values.size());
int pageSize = (maxResults > 0) ? maxResults : 100;
int end = Math.min(offset + pageSize, values.size());
List<ResourceTagMapping> page = values.subList(offset, end).stream()
@@ -231,7 +502,7 @@ public class ResourceGroupsTaggingService implements Resettable {
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));
+ return Math.max(0, 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/sqs/SqsTagHandler.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsTagHandler.java
new file mode 100644
index 0000000000..5d8d50fd33
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsTagHandler.java
@@ -0,0 +1,53 @@
+package io.github.hectorvent.floci.services.sqs;
+
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.TagHandler;
+import io.github.hectorvent.floci.core.common.TaggingApiOnly;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Lets Resource Groups Tagging API writes reach a queue's own tags.
+ *
+ * <p>A separate {@link TaggingApiOnly} bean because SQS tags through its own {@code TagQueue}
+ * action: a default-qualified handler would also serve the queue on {@code /tags/{arn}}, which
+ * AWS does not define.
+ */
+@ApplicationScoped
+@TaggingApiOnly
+public class SqsTagHandler implements TagHandler {
+
+ private final SqsService sqsService;
+
+ @Inject
+ public SqsTagHandler(SqsService sqsService) {
+ this.sqsService = sqsService;
+ }
+
+ @Override
+ public String serviceKey() {
+ return "sqs";
+ }
+
+ @Override
+ public Map<String, String> listTags(String region, String arn) {
+ return sqsService.listQueueTags(queueUrl(region, arn), region);
+ }
+
+ @Override
+ public void tagResource(String region, String arn, Map<String, String> tags) {
+ sqsService.tagQueue(queueUrl(region, arn), tags, region);
+ }
+
+ @Override
+ public void untagResource(String region, String arn, List<String> tagKeys) {
+ sqsService.untagQueue(queueUrl(region, arn), tagKeys, region);
+ }
+
+ private String queueUrl(String region, String arn) {
+ return sqsService.getQueueUrl(AwsArnUtils.parse(arn).resource(), region);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmJsonHandler.java
index f7a98c2bab..626bd74de5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmJsonHandler.java
@@ -1039,7 +1039,7 @@ public class SsmJsonHandler {
private Response handleAddTagsToResource(JsonNode request, String region) {
String resourceId = request.path("ResourceId").asText();
- Map<String, String> tags = new HashMap<>();
+ Map<String, String> tags = new LinkedHashMap<>();
request.path("Tags").forEach(t ->
tags.put(t.path("Key").asText(), t.path("Value").asText()));
diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java
index db9ba91f35..6d8d06a5b5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java
@@ -35,6 +35,7 @@ import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.ArrayList;
import java.util.Set;
+import java.util.regex.Pattern;
@ApplicationScoped
public class SsmService implements ResourceProvider {
@@ -49,6 +50,9 @@ public class SsmService implements ResourceProvider {
private static final Set<String> DESCRIBE_PARAMETERS_FILTER_KEYS =
Set.of("Name", "Type", "KeyId", "Path", "Tier", "DataType");
private static final String DEFAULT_SSM_KEY_ID = "alias/aws/ssm";
+ private static final String TAG_KEY_REGEX = "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$";
+ private static final Pattern TAG_KEY_PATTERN = Pattern.compile(TAG_KEY_REGEX);
+ private static final int MAX_TAG_KEY_LENGTH = 128;
/**
* Account-default values for the service settings floci models. AWS rejects
@@ -179,6 +183,7 @@ public class SsmService implements ResourceProvider {
public long putParameter(String name, String value, String type, String description, boolean overwrite,
Map<String, String> tags, String region) {
+ validateTagKeys(tags);
rejectReservedName(name);
String storageKey = regionKey(region, name);
Parameter existing = parameterStore.get(storageKey).orElse(null);
@@ -713,6 +718,7 @@ public class SsmService implements ResourceProvider {
}
public void addTagsToResource(String resourceId, Map<String, String> tags, String region) {
+ validateTagKeys(tags);
String normalizedId = normalizeResourceId(resourceId);
String storageKey = regionKey(region, normalizedId);
Parameter param = parameterStore.get(storageKey)
@@ -727,6 +733,32 @@ public class SsmService implements ResourceProvider {
LOG.debugv("Added tags to parameter: {0}", resourceId);
}
+ /**
+ * The key constraint AWS checks before any lookup, naming the offending key by its 1-based
+ * position in the request's {@code Tags} list.
+ */
+ public static void validateTagKeys(Map<String, String> tags) {
+ if (tags == null) {
+ return;
+ }
+ int position = 0;
+ for (String key : tags.keySet()) {
+ position++;
+ String constraint;
+ if (key.isEmpty()) {
+ constraint = "Member must have length greater than or equal to 1";
+ } else if (key.codePointCount(0, key.length()) > MAX_TAG_KEY_LENGTH) {
+ constraint = "Member must have length less than or equal to " + MAX_TAG_KEY_LENGTH;
+ } else if (!TAG_KEY_PATTERN.matcher(key).matches()) {
+ constraint = "Member must satisfy regular expression pattern: " + TAG_KEY_REGEX;
+ } else {
+ continue;
+ }
+ throw new AwsException("ValidationException", "1 validation error detected: Value at 'tags."
+ + position + ".member.key' failed to satisfy constraint: " + constraint, 400);
+ }
+ }
+
public Map<String, String> listTagsForResource(String resourceId, String region) {
String normalizedId = normalizeResourceId(resourceId);
String storageKey = regionKey(region, normalizedId);
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDomainTlsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDomainTlsServiceTest.java
index 0d61bcd12f..1a5e91f4be 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDomainTlsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayDomainTlsServiceTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import org.junit.jupiter.api.BeforeEach;
@@ -46,7 +47,8 @@ class ApiGatewayDomainTlsServiceTest {
certificateManager = mock(TlsCertificateManager.class);
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().cloudfront().domainSuffix()).thenReturn("cloudfront.net");
- service = new ApiGatewayService(storageFactory, config, certificateManager);
+ service = new ApiGatewayService(storageFactory, config, certificateManager,
+ new RegionResolver(REGION, "000000000000"));
}
private static Map<String, Object> regional(String domain) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayEdgeDomainPartitionTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayEdgeDomainPartitionTest.java
index 3ee22ac022..0f15ed6c3a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayEdgeDomainPartitionTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayEdgeDomainPartitionTest.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
@@ -41,7 +42,8 @@ class ApiGatewayEdgeDomainPartitionTest {
ignored -> AccountAwareStorageBackend.inMemory("000000000000")));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().cloudfront().domainSuffix()).thenReturn("cloudfront.net");
- service = new ApiGatewayService(storageFactory, config, mock(TlsCertificateManager.class));
+ service = new ApiGatewayService(storageFactory, config, mock(TlsCertificateManager.class),
+ new RegionResolver(GOV_REGION, "000000000000"));
}
@SuppressWarnings("unchecked")
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayResourceProviderTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayResourceProviderTest.java
new file mode 100644
index 0000000000..27296d1b4c
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayResourceProviderTest.java
@@ -0,0 +1,42 @@
+package io.github.hectorvent.floci.services.apigateway;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.config.TlsCertificateManager;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.resource.ExplorerResource;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class ApiGatewayResourceProviderTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String DEFAULT_ACCOUNT = "000000000000";
+ private static final String CALLING_ACCOUNT = "111111111111";
+
+ @Test
+ void resourcesReportTheCallingAccountAsOwner() {
+ StorageFactory storageFactory = mock(StorageFactory.class);
+ when(storageFactory.create(anyString(), anyString(), any()))
+ .thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(DEFAULT_ACCOUNT));
+ EmulatorConfig config = mock(EmulatorConfig.class);
+ when(config.defaultAccountId()).thenReturn(DEFAULT_ACCOUNT);
+ ApiGatewayService service = new ApiGatewayService(storageFactory, config,
+ mock(TlsCertificateManager.class), new RegionResolver(REGION, CALLING_ACCOUNT));
+ service.createRestApi(REGION, Map.of("name", "owned", "tags", Map.of("k", "v")));
+
+ List<ExplorerResource> resources = service.getResources();
+
+ assertEquals(1, resources.size());
+ assertEquals(CALLING_ACCOUNT, resources.getFirst().owningAccountId());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRootResourceLookupTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRootResourceLookupTest.java
index fe83078437..02f6051e7f 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRootResourceLookupTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRootResourceLookupTest.java
@@ -53,7 +53,7 @@ class ApiGatewayRootResourceLookupTest {
};
});
service = new ApiGatewayService(storageFactory, mock(EmulatorConfig.class),
- mock(TlsCertificateManager.class));
+ mock(TlsCertificateManager.class), new RegionResolver(REGION, "000000000000"));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagResourceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagResourceIntegrationTest.java
index 4493dff039..c19f654a21 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagResourceIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayTagResourceIntegrationTest.java
@@ -1,13 +1,18 @@
package io.github.hectorvent.floci.services.apigateway;
import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.nullValue;
@QuarkusTest
class ApiGatewayTagResourceIntegrationTest {
+ private static final String CERTIFICATE_ARN =
+ "arn:aws:acm:us-east-1:000000000000:certificate/11111111-2222-3333-4444-555555555555";
+
@Test
void testTagResource() {
String apiId = given()
@@ -38,4 +43,85 @@ class ApiGatewayTagResourceIntegrationTest {
.statusCode(200)
.body("tags.environment", equalTo("test"));
}
+
+ @Test
+ void arnWithAnAccountSegmentIsRejectedForEveryTagOperation() {
+ String apiId = given()
+ .contentType("application/json")
+ .body("{\"name\":\"account-arn-api\"}")
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+ String canonicalArn = "arn:aws:apigateway:us-east-1::/restapis/" + apiId;
+ String accountArn = "arn:aws:apigateway:us-east-1:111111111111:/restapis/" + apiId;
+ String expectedMessage = "Expected ARN " + canonicalArn + ", not " + accountArn;
+
+ given().pathParam("arn", canonicalArn).contentType(ContentType.JSON)
+ .body("{\"tags\":{\"keep\":\"yes\"}}")
+ .when().put("/tags/{arn}").then().statusCode(204);
+
+ given().pathParam("arn", accountArn).contentType(ContentType.JSON)
+ .body("{\"tags\":{\"environment\":\"test\"}}")
+ .when().put("/tags/{arn}").then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo(expectedMessage));
+
+ given().pathParam("arn", accountArn)
+ .when().get("/tags/{arn}").then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo(expectedMessage));
+
+ given().pathParam("arn", accountArn).queryParam("tagKeys", "keep")
+ .when().delete("/tags/{arn}").then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo(expectedMessage));
+
+ given().pathParam("arn", canonicalArn)
+ .when().get("/tags/{arn}").then()
+ .statusCode(200)
+ .body("tags.environment", nullValue())
+ .body("tags.keep", equalTo("yes"));
+ }
+
+ @Test
+ void arnNamingAnotherRegionIsNotFoundAndLeavesTheCallersDomainAlone() {
+ String domain = "other-region-arn.apigw-tags-it.example.com";
+ given().contentType(ContentType.JSON)
+ .body("""
+ {"domainName":"%s","regionalCertificateArn":"%s","tags":{"env":"prod"}}
+ """.formatted(domain, CERTIFICATE_ARN))
+ .when().post("/domainnames").then().statusCode(201);
+ String otherRegionArn = "arn:aws:apigateway:eu-west-1::/domainnames/" + domain;
+
+ given().pathParam("arn", otherRegionArn).contentType(ContentType.JSON)
+ .body("{\"tags\":{\"team\":\"api\"}}")
+ .when().put("/tags/{arn}").then()
+ .statusCode(404)
+ .body("__type", equalTo("NotFoundException"))
+ .body("message", equalTo("Invalid resource identifier specified"));
+
+ given().pathParam("arn", otherRegionArn)
+ .when().get("/tags/{arn}").then()
+ .statusCode(404)
+ .body("__type", equalTo("NotFoundException"))
+ .body("message", equalTo("Invalid resource identifier specified"));
+
+ given().pathParam("arn", otherRegionArn).queryParam("tagKeys", "env")
+ .when().delete("/tags/{arn}").then()
+ .statusCode(404)
+ .body("__type", equalTo("NotFoundException"))
+ .body("message", equalTo("Invalid resource identifier specified"));
+
+ given().when().get("/domainnames/" + domain).then()
+ .statusCode(200)
+ .body("tags.env", equalTo("prod"))
+ .body("tags.team", nullValue());
+
+ given().when().delete("/domainnames/" + domain).then().statusCode(202);
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
index 235d0daa4f..5464aae8d1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.testing.MutableClock;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
@@ -49,6 +50,7 @@ class CloudFormationIntegrationTest {
private static final String SSM_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String SM_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String COGNITO_CONTENT_TYPE = "application/x-amz-json-1.1";
+ private static final String TAGGING_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Inject
@@ -1094,6 +1096,292 @@ class CloudFormationIntegrationTest {
.body("Configuration.Environment.Variables.STAGE", equalTo("green"));
}
+ @Test
+ void updateStack_lambdaFunctionTagsFollowTheTemplate() {
+ String stackName = "cfn-lambda-tags-stack";
+ String functionName = "cfn-lambda-tags-func";
+ String functionArn = "arn:aws:lambda:us-east-1:000000000000:function:" + functionName;
+ String template = """
+ {
+ "Resources": {
+ "MyFunction": {
+ "Type": "AWS::Lambda::Function",
+ "Properties": {
+ "FunctionName": "%s",
+ "Runtime": "nodejs20.x",
+ "Handler": "index.handler",
+ "Role": "arn:aws:iam::000000000000:role/cfn-test-lambda-role"%s
+ }
+ }
+ }
+ }
+ """;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template.formatted(functionName, """
+ ,
+ "Tags": [{"Key": "a", "Value": "1"}, {"Key": "b", "Value": "2"}]"""))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/2017-03-31/tags/" + functionArn)
+ .then()
+ .statusCode(200)
+ .body("Tags.size()", equalTo(2))
+ .body("Tags.a", equalTo("1"))
+ .body("Tags.b", equalTo("2"));
+
+ given()
+ .header("X-Amz-Target", "ResourceGroupsTaggingAPI_20170126.GetResources")
+ .contentType(TAGGING_CONTENT_TYPE)
+ .body("""
+ {"ResourceTypeFilters": ["lambda:function"], "TagFilters": [{"Key": "a", "Values": ["1"]}]}
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("ResourceTagMappingList.ResourceARN", hasItem(functionArn));
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {"Tags": {"oob": "x"}}
+ """)
+ .when()
+ .post("/2017-03-31/tags/" + functionArn)
+ .then()
+ .statusCode(204);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template.formatted(functionName, """
+ ,
+ "Tags": [{"Key": "a", "Value": "1"}, {"Key": "c", "Value": "3"}]"""))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/2017-03-31/tags/" + functionArn)
+ .then()
+ .statusCode(200)
+ .body("Tags.size()", equalTo(3))
+ .body("Tags.a", equalTo("1"))
+ .body("Tags.c", equalTo("3"))
+ .body("Tags.oob", equalTo("x"));
+ }
+
+ @Test
+ void updateStack_ssmParameterTagsFollowTheTemplate() {
+ String stackName = "cfn-ssm-tags-stack";
+ String parameterName = "/cfn/ssm-tags-param";
+
+ createSsmParameterStackWithOutOfTemplateTag(stackName, parameterName);
+ updateSsmParameterStack(stackName, parameterName, """
+ ,
+ "Tags": {"a": "changed"}""");
+
+ ssmParameterTags(parameterName)
+ .body("TagList.size()", equalTo(2))
+ .body("TagList.find { it.Key == 'a' }.Value", equalTo("changed"))
+ .body("TagList.find { it.Key == 'ext' }.Value", equalTo("x"));
+ }
+
+ @Test
+ void updateStack_ssmParameterTagsPropertyRemovedKeepsOutOfTemplateTags() {
+ String stackName = "cfn-ssm-tags-removed-stack";
+ String parameterName = "/cfn/ssm-tags-removed-param";
+
+ createSsmParameterStackWithOutOfTemplateTag(stackName, parameterName);
+ updateSsmParameterStack(stackName, parameterName, "");
+
+ ssmParameterTags(parameterName)
+ .body("TagList.size()", equalTo(1))
+ .body("TagList.find { it.Key == 'ext' }.Value", equalTo("x"));
+ }
+
+ @Test
+ void updateStack_ssmParameterInvalidTagKeyFailsBeforeWritingANewVersion() {
+ String stackName = "cfn-ssm-invalid-tag-stack";
+ String parameterName = "/cfn/ssm-invalid-tag-param";
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", ssmParameterTemplate(parameterName, ""))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", ssmParameterTemplate(parameterName, "v2", """
+ ,
+ "Tags": {"a,b": "x"}"""))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ awaitStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.GetParameter")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ {"Name": "%s"}
+ """.formatted(parameterName))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("Parameter.Value", equalTo("v"))
+ .body("Parameter.Version", equalTo(1));
+ }
+
+ @Test
+ void updateStack_lambdaInvalidTagKeyFailsBeforeChangingTheFunction() {
+ String stackName = "cfn-lambda-invalid-tag-stack";
+ String functionName = "cfn-lambda-invalid-tag-func";
+ String template = """
+ {
+ "Resources": {
+ "MyFunction": {
+ "Type": "AWS::Lambda::Function",
+ "Properties": {
+ "FunctionName": "%s",
+ "Runtime": "nodejs20.x",
+ "Handler": "index.handler",
+ "Role": "arn:aws:iam::000000000000:role/cfn-test-lambda-role",
+ "Description": "%s"%s
+ }
+ }
+ }
+ }
+ """;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template.formatted(functionName, "before", ""))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template.formatted(functionName, "after", """
+ ,
+ "Tags": [{"Key": "a,b", "Value": "x"}]"""))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ awaitStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
+
+ given()
+ .when()
+ .get("/2015-03-31/functions/" + functionName)
+ .then()
+ .statusCode(200)
+ .body("Configuration.Description", equalTo("before"));
+ }
+
+ private static String ssmParameterTemplate(String parameterName, String tagsProperty) {
+ return ssmParameterTemplate(parameterName, "v", tagsProperty);
+ }
+
+ private static String ssmParameterTemplate(String parameterName, String value, String tagsProperty) {
+ return """
+ {
+ "Resources": {
+ "MyParameter": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {
+ "Name": "%s",
+ "Type": "String",
+ "Value": "%s"%s
+ }
+ }
+ }
+ }
+ """.formatted(parameterName, value, tagsProperty);
+ }
+
+ private static void createSsmParameterStackWithOutOfTemplateTag(String stackName, String parameterName) {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", ssmParameterTemplate(parameterName, """
+ ,
+ "Tags": {"a": "1", "b": "2"}"""))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ ssmParameterTags(parameterName)
+ .body("TagList.size()", equalTo(2))
+ .body("TagList.find { it.Key == 'a' }.Value", equalTo("1"))
+ .body("TagList.find { it.Key == 'b' }.Value", equalTo("2"));
+
+ given()
+ .header("X-Amz-Target", "AmazonSSM.AddTagsToResource")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ {"ResourceType": "Parameter", "ResourceId": "%s", "Tags": [{"Key": "ext", "Value": "x"}]}
+ """.formatted(parameterName))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ private static void updateSsmParameterStack(String stackName, String parameterName, String tagsProperty) {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", ssmParameterTemplate(parameterName, tagsProperty))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ private static ValidatableResponse ssmParameterTags(String parameterName) {
+ return given()
+ .header("X-Amz-Target", "AmazonSSM.ListTagsForResource")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ {"ResourceType": "Parameter", "ResourceId": "%s"}
+ """.formatted(parameterName))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
@Test
void updateStack_lambdaFunctionNameChangeReplacesPhysicalResource() {
String stackName = "cfn-lambda-replace-stack";
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisionerTest.java
new file mode 100644
index 0000000000..d0a5a0e221
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisionerTest.java
@@ -0,0 +1,192 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+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.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.lambda.LambdaLayerService;
+import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
+import io.github.hectorvent.floci.services.s3.S3Service;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * The Lambda function CFN provisioner in isolation, for the {@code Tags} property: the create
+ * request carries the template's tags, and an in-place update applies the template's set and removes
+ * only the keys the previous template had, keeping tags added outside the template.
+ */
+class LambdaCfnProvisionerTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:";
+ private static final String TEMPLATE_TAG_KEYS_ATTR = "FlociLambdaTemplateTagKeys";
+
+ private final LambdaService lambda = mock(LambdaService.class);
+ private final LambdaCfnProvisioner provisioner = new LambdaCfnProvisioner(
+ lambda, mock(LambdaLayerService.class), mock(S3Service.class), null);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private ProvisionContext ctx() {
+ // Scalar properties and flat tag lists only, so a passthrough engine keeps this isolated.
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null || node.isMissingNode() ? null : node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ return new ProvisionContext(engine, REGION, "000000000000", "my-stack");
+ }
+
+ private ProvisionContext updateCtx(String priorPhysicalId) {
+ ProvisionContext create = ctx();
+ return new ProvisionContext(create.engine(), create.region(), create.accountId(),
+ create.stackName(), priorPhysicalId);
+ }
+
+ private StackResource function(String physicalId, String templateTagKeys) {
+ StackResource r = function(physicalId);
+ r.getAttributes().put(TEMPLATE_TAG_KEYS_ATTR, templateTagKeys);
+ return r;
+ }
+
+ private StackResource function(String physicalId) {
+ StackResource r = new StackResource();
+ r.setLogicalId("MyFunction");
+ r.setResourceType("AWS::Lambda::Function");
+ r.setAttributes(new HashMap<>());
+ if (physicalId != null) {
+ r.setPhysicalId(physicalId);
+ r.getAttributes().put("FlociLambdaFunctionNameMode", "explicit");
+ r.getAttributes().put("FlociLambdaPackageType", "Zip");
+ }
+ return r;
+ }
+
+ private ObjectNode props(String functionName, String... keyValues) {
+ ObjectNode props = mapper.createObjectNode().put("FunctionName", functionName);
+ if (keyValues.length > 0) {
+ ArrayNode tags = props.putArray("Tags");
+ for (int i = 0; i < keyValues.length; i += 2) {
+ tags.add(mapper.createObjectNode().put("Key", keyValues[i]).put("Value", keyValues[i + 1]));
+ }
+ }
+ return props;
+ }
+
+ private static LambdaFunction lambdaFunction(String name) {
+ LambdaFunction fn = new LambdaFunction();
+ fn.setFunctionName(name);
+ fn.setFunctionArn(FUNCTION_ARN + name);
+ fn.setPackageType("Zip");
+ return fn;
+ }
+
+ private void stubInPlaceUpdate(String name, Map<String, String> currentTags) {
+ LambdaFunction existing = lambdaFunction(name);
+ when(lambda.getFunction(REGION, name)).thenReturn(existing);
+ when(lambda.updateFunctionConfiguration(anyString(), anyString(), anyMap())).thenReturn(existing);
+ when(lambda.updateFunctionCode(anyString(), anyString(), anyMap())).thenReturn(existing);
+ when(lambda.listTags(FUNCTION_ARN + name)).thenReturn(new HashMap<>(currentTags));
+ }
+
+ @Test
+ void functionTagsFromTheTemplateReachCreateFunction() {
+ when(lambda.createFunction(eq(REGION), anyMap())).thenReturn(lambdaFunction("my-fn"));
+ StackResource r = function(null);
+
+ provisioner.provision(r, props("my-fn", "team", "a", "env", "dev"), ctx());
+
+ assertEquals(Map.of("team", "a", "env", "dev"), capturedCreateRequest().get("Tags"));
+ assertEquals("env,team", r.getAttributes().get(TEMPLATE_TAG_KEYS_ATTR));
+ verify(lambda, never()).tagResource(anyString(), anyMap());
+ verify(lambda, never()).untagResource(anyString(), any());
+ }
+
+ @Test
+ void adoptedFunctionKeepsItsOwnTags() {
+ when(lambda.createFunction(eq(REGION), anyMap())).thenThrow(
+ new AwsException("ResourceConflictException", "Function already exist: my-fn", 409));
+ when(lambda.getFunction(REGION, "my-fn")).thenReturn(lambdaFunction("my-fn"));
+ StackResource r = function(null);
+
+ provisioner.provision(r, props("my-fn", "team", "a", "env", "dev"), ctx());
+
+ verify(lambda, never()).tagResource(any(), any());
+ assertFalse(r.getAttributes().containsKey(TEMPLATE_TAG_KEYS_ATTR));
+ }
+
+ @Test
+ void replacementCarriesTheTemplateTagsOnTheNewFunction() {
+ when(lambda.getFunction(REGION, "old-fn")).thenReturn(lambdaFunction("old-fn"));
+ when(lambda.createFunction(eq(REGION), anyMap())).thenReturn(lambdaFunction("new-fn"));
+
+ provisioner.provision(function("old-fn"), props("new-fn", "team", "b"), updateCtx("old-fn"));
+
+ assertEquals(Map.of("team", "b"), capturedCreateRequest().get("Tags"));
+ verify(lambda).deleteFunction(REGION, "old-fn");
+ verify(lambda, never()).tagResource(anyString(), anyMap());
+ }
+
+ @Test
+ void inPlaceUpdateUntagsOnlyTheKeyTheTemplateDropped() {
+ stubInPlaceUpdate("my-fn", Map.of("team", "a", "env", "dev", "oob", "x"));
+ StackResource r = function("my-fn", "env,team");
+
+ provisioner.provision(r, props("my-fn", "team", "b"), updateCtx("my-fn"));
+
+ verify(lambda).untagResource(FUNCTION_ARN + "my-fn", List.of("env"));
+ verify(lambda).tagResource(FUNCTION_ARN + "my-fn", Map.of("team", "b"));
+ verify(lambda, never()).createFunction(anyString(), anyMap());
+ assertEquals("team", r.getAttributes().get(TEMPLATE_TAG_KEYS_ATTR));
+ }
+
+ @Test
+ void inPlaceUpdateWithTheTagsPropertyGoneUntagsOnlyTheTemplateKeys() {
+ stubInPlaceUpdate("my-fn", Map.of("team", "a", "env", "dev", "oob", "x"));
+ StackResource r = function("my-fn", "env,team");
+
+ provisioner.provision(r, props("my-fn"), updateCtx("my-fn"));
+
+ verify(lambda).untagResource(eq(FUNCTION_ARN + "my-fn"),
+ argThat(keys -> keys.size() == 2 && keys.containsAll(List.of("team", "env"))));
+ verify(lambda, never()).tagResource(anyString(), anyMap());
+ assertEquals("", r.getAttributes().get(TEMPLATE_TAG_KEYS_ATTR));
+ }
+
+ @Test
+ void inPlaceUpdateWithoutRecordedTemplateKeysUntagsNothing() {
+ stubInPlaceUpdate("my-fn", Map.of("legacy", "x"));
+
+ provisioner.provision(function("my-fn"), props("my-fn", "team", "b"), updateCtx("my-fn"));
+
+ verify(lambda, never()).untagResource(anyString(), any());
+ verify(lambda).tagResource(FUNCTION_ARN + "my-fn", Map.of("team", "b"));
+ }
+
+ @SuppressWarnings("unchecked")
+ private Map<String, Object> capturedCreateRequest() {
+ ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);
+ verify(lambda).createFunction(eq(REGION), request.capture());
+ return request.getValue();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SsmCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SsmCfnProvisionerTest.java
new file mode 100644
index 0000000000..96e7ebd238
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SsmCfnProvisionerTest.java
@@ -0,0 +1,141 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.ssm.SsmService;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * The SSM parameter CFN provisioner in isolation, for the {@code Tags} property: the parameter is
+ * written without tags, then the template's tags are added, and an update removes only the keys the
+ * previous template had, keeping tags added outside the template.
+ */
+class SsmCfnProvisionerTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String NAME = "/app/param";
+ private static final String TEMPLATE_TAG_KEYS_ATTR = "FlociSsmTemplateTagKeys";
+
+ private final SsmService ssm = mock(SsmService.class);
+ private final SsmCfnProvisioner provisioner = new SsmCfnProvisioner(ssm);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private ProvisionContext ctx() {
+ // Scalar properties and a flat tag map only, so a passthrough engine keeps this isolated.
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null || node.isMissingNode() ? null : node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ return new ProvisionContext(engine, REGION, "000000000000", "my-stack");
+ }
+
+ private ProvisionContext updateCtx() {
+ ProvisionContext create = ctx();
+ return new ProvisionContext(create.engine(), create.region(), create.accountId(),
+ create.stackName(), NAME);
+ }
+
+ private static StackResource parameter(String physicalId, String templateTagKeys) {
+ StackResource r = new StackResource();
+ r.setLogicalId("MyParameter");
+ r.setResourceType("AWS::SSM::Parameter");
+ r.setAttributes(new HashMap<>());
+ if (physicalId != null) {
+ r.setPhysicalId(physicalId);
+ }
+ if (templateTagKeys != null) {
+ r.getAttributes().put(TEMPLATE_TAG_KEYS_ATTR, templateTagKeys);
+ }
+ return r;
+ }
+
+ private ObjectNode props(String... keyValues) {
+ ObjectNode props = mapper.createObjectNode()
+ .put("Name", NAME)
+ .put("Type", "String")
+ .put("Value", "v");
+ if (keyValues.length > 0) {
+ ObjectNode tags = props.putObject("Tags");
+ for (int i = 0; i < keyValues.length; i += 2) {
+ tags.put(keyValues[i], keyValues[i + 1]);
+ }
+ }
+ return props;
+ }
+
+ @Test
+ void parameterTagsFromTheTemplateAreAddedAfterThePut() {
+ StackResource r = parameter(null, null);
+
+ provisioner.provision(r, props("team", "a", "env", "dev"), ctx());
+
+ verify(ssm).putParameter(NAME, "v", "String", null, true, REGION);
+ verify(ssm).addTagsToResource(NAME, Map.of("team", "a", "env", "dev"), REGION);
+ verify(ssm, never()).removeTagsFromResource(anyString(), any(), anyString());
+ assertEquals("env,team", r.getAttributes().get(TEMPLATE_TAG_KEYS_ATTR));
+ }
+
+ @Test
+ void parameterWithoutTagsIsNotTagged() {
+ StackResource r = parameter(null, null);
+
+ provisioner.provision(r, props(), ctx());
+
+ verify(ssm).putParameter(NAME, "v", "String", null, true, REGION);
+ verify(ssm, never()).addTagsToResource(anyString(), anyMap(), anyString());
+ verify(ssm, never()).removeTagsFromResource(anyString(), any(), anyString());
+ assertFalse(r.getAttributes().containsKey(TEMPLATE_TAG_KEYS_ATTR));
+ }
+
+ @Test
+ void updateRemovesOnlyTheKeyTheTemplateDropped() {
+ StackResource r = parameter(NAME, "env,team");
+
+ provisioner.provision(r, props("team", "b"), updateCtx());
+
+ verify(ssm).removeTagsFromResource(NAME, List.of("env"), REGION);
+ verify(ssm).addTagsToResource(NAME, Map.of("team", "b"), REGION);
+ assertEquals("team", r.getAttributes().get(TEMPLATE_TAG_KEYS_ATTR));
+ }
+
+ @Test
+ void updateWithTheTagsPropertyGoneRemovesOnlyTheTemplateKeys() {
+ StackResource r = parameter(NAME, "env,team");
+
+ provisioner.provision(r, props(), updateCtx());
+
+ verify(ssm).removeTagsFromResource(eq(NAME),
+ argThat(keys -> keys.size() == 2 && keys.containsAll(List.of("team", "env"))), eq(REGION));
+ verify(ssm, never()).addTagsToResource(anyString(), anyMap(), anyString());
+ assertFalse(r.getAttributes().containsKey(TEMPLATE_TAG_KEYS_ATTR));
+ }
+
+ @Test
+ void updateWithoutRecordedTemplateKeysRemovesNothing() {
+ provisioner.provision(parameter(NAME, null), props("team", "b"), updateCtx());
+
+ verify(ssm, never()).removeTagsFromResource(anyString(), any(), anyString());
+ verify(ssm).addTagsToResource(NAME, Map.of("team", "b"), REGION);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPermissionTagLayerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPermissionTagLayerIntegrationTest.java
index 18af31a9f8..214f6eefad 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPermissionTagLayerIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPermissionTagLayerIntegrationTest.java
@@ -273,6 +273,25 @@ class LambdaPermissionTagLayerIntegrationTest {
.body("Tags.team", equalTo("platform"));
}
+ @Test
+ @Order(16)
+ void tagResource_keyOutsideTheAwsPattern_returns400() {
+ given()
+ .contentType("application/json")
+ .body("""
+ {"Tags": {"a,b": "x"}}
+ """)
+ .when()
+ .post("/2017-03-31/tags/" + FN_ARN)
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"))
+ .body("message", equalTo("1 validation error detected: Value '{a,b=x}' at 'tags' failed to satisfy"
+ + " constraint: Map keys must satisfy constraint: [Member must have length less than or"
+ + " equal to 128, Member must have length greater than or equal to 1, Member must satisfy"
+ + " regular expression pattern: ([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)]"));
+ }
+
// ── ListLayers / ListLayerVersions ────────────────────────────────────────
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
index 5e65956135..be6f7e5bc2 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
@@ -43,6 +43,11 @@ class LambdaServiceTest {
private static final String REGION = "us-east-1";
+ private static final String TAG_KEYS_CONSTRAINT = " at 'tags' failed to satisfy constraint: Map keys must"
+ + " satisfy constraint: [Member must have length less than or equal to 128, Member must have length"
+ + " greater than or equal to 1, Member must satisfy regular expression pattern:"
+ + " ([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)]";
+
private LambdaService service;
@BeforeEach
@@ -337,6 +342,70 @@ class LambdaServiceTest {
assertEquals(404, ex.getHttpStatus());
}
+ @Test
+ void tagResource_keyOutsideTheAwsPattern_isRejectedBeforeTheLookup() {
+ AwsException ex = assertThrows(AwsException.class, () -> service.tagResource(
+ "arn:aws:lambda:us-east-1:000000000000:function:no-such-fn", Map.of("a,b", "x")));
+ assertEquals("ValidationException", ex.getErrorCode());
+ assertEquals(400, ex.getHttpStatus());
+ assertEquals("1 validation error detected: Value '{a,b=x}'" + TAG_KEYS_CONSTRAINT, ex.getMessage());
+ }
+
+ @Test
+ void tagResource_emptyOrTooLongKeyIsRejected() {
+ LambdaFunction fn = service.createFunction(REGION, baseRequest("tag-length-fn"));
+ String longKey = "k".repeat(129);
+
+ AwsException empty = assertThrows(AwsException.class,
+ () -> service.tagResource(fn.getFunctionArn(), Map.of("", "x")));
+ AwsException tooLong = assertThrows(AwsException.class,
+ () -> service.tagResource(fn.getFunctionArn(), Map.of(longKey, "x")));
+
+ assertEquals("ValidationException", empty.getErrorCode());
+ assertEquals("1 validation error detected: Value '{=x}'" + TAG_KEYS_CONSTRAINT, empty.getMessage());
+ assertEquals("ValidationException", tooLong.getErrorCode());
+ assertEquals("1 validation error detected: Value '{" + longKey + "=x}'" + TAG_KEYS_CONSTRAINT,
+ tooLong.getMessage());
+ assertTrue(service.listTags(fn.getFunctionArn()).isEmpty());
+ }
+
+ @Test
+ void tagResource_keyLengthCountsCodePoints() {
+ LambdaFunction fn = service.createFunction(REGION, baseRequest("tag-code-points-fn"));
+ String letter = new String(Character.toChars(0x20000));
+
+ service.tagResource(fn.getFunctionArn(), Map.of(letter.repeat(128), "x"));
+ AwsException ex = assertThrows(AwsException.class,
+ () -> service.tagResource(fn.getFunctionArn(), Map.of(letter.repeat(129), "x")));
+
+ assertEquals(Map.of(letter.repeat(128), "x"), service.listTags(fn.getFunctionArn()));
+ assertEquals("ValidationException", ex.getErrorCode());
+ }
+
+ @Test
+ void tagResource_validKeyIsApplied() {
+ LambdaFunction fn = service.createFunction(REGION, baseRequest("tag-valid-fn"));
+
+ service.tagResource(fn.getFunctionArn(), Map.of("team:name/x=y+z-@_. 1", "v"));
+
+ assertEquals(Map.of("team:name/x=y+z-@_. 1", "v"), service.listTags(fn.getFunctionArn()));
+ }
+
+ @Test
+ void createFunction_invalidTagKeyIsRejectedAndTheFunctionIsNotCreated() {
+ Map<String, Object> request = baseRequest("tag-rejected-fn");
+ request.put("Tags", Map.of("a,b", "x"));
+
+ AwsException ex = assertThrows(AwsException.class, () -> service.createFunction(REGION, request));
+
+ assertEquals("ValidationException", ex.getErrorCode());
+ assertEquals(400, ex.getHttpStatus());
+ assertEquals("1 validation error detected: Value '{a,b=x}'" + TAG_KEYS_CONSTRAINT, ex.getMessage());
+ AwsException missing = assertThrows(AwsException.class,
+ () -> service.getFunction(REGION, "tag-rejected-fn"));
+ assertEquals("ResourceNotFoundException", missing.getErrorCode());
+ }
+
@Test
void getFunctionAcceptsPartialArn() {
service.createFunction(REGION, baseRequest("arn-fn"));
diff --git a/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingDiscoveryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingDiscoveryIntegrationTest.java
new file mode 100644
index 0000000000..097985197b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingDiscoveryIntegrationTest.java
@@ -0,0 +1,1129 @@
+package io.github.hectorvent.floci.services.resourcegroupstagging;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+import io.restassured.response.ValidatableResponse;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
+
+/**
+ * GetResources, GetTagKeys and GetTagValues see the tags a resource's own service holds, so a
+ * queue, function, log group or API Gateway resource tagged through its own service is
+ * discoverable without ever being tagged through the Resource Groups Tagging API.
+ */
+@QuarkusTest
+class ResourceGroupsTaggingDiscoveryIntegrationTest {
+
+ private static final String TAGGING_TARGET = "ResourceGroupsTaggingAPI_20170126.";
+ private static final String JSON_1_0 = "application/x-amz-json-1.0";
+ private static final String JSON_1_1 = "application/x-amz-json-1.1";
+ private static final String ARN_PREFIX = "arn:aws:%s:us-east-1:000000000000:";
+ private static final String APIGATEWAY_ARN_PREFIX = "arn:aws:apigateway:us-east-1::";
+ private static final String IAM_AUTH = "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void sqsQueueIsDiscoveredByTypeAndItsOwnTags() {
+ String name = "discovery-" + unique();
+ String marker = unique();
+ String arn = ARN_PREFIX.formatted("sqs") + name;
+ String queueUrl = sqs("CreateQueue", """
+ {"QueueName": "%s", "tags": {"fd": "%s", "pn": "p1", "pt": "t1"}}
+ """.formatted(name, marker))
+ .then()
+ .statusCode(200)
+ .extract().path("QueueUrl");
+
+ getResources("""
+ {"ResourceTypeFilters": ["sqs:queue"], "TagFilters": [%s, %s, %s]}
+ """.formatted(tagFilter("fd", marker), tagFilter("pn", "p1"), tagFilter("pt", "t1")))
+ .body("ResourceTagMappingList.ResourceARN", contains(arn))
+ .body("ResourceTagMappingList[0].Tags.size()", equalTo(3))
+ .body("ResourceTagMappingList[0].Tags.find { it.Key == 'fd' }.Value", equalTo(marker))
+ .body("ResourceTagMappingList[0].Tags.find { it.Key == 'pn' }.Value", equalTo("p1"))
+ .body("ResourceTagMappingList[0].Tags.find { it.Key == 'pt' }.Value", equalTo("t1"));
+
+ sqs("TagQueue", """
+ {"QueueUrl": "%s", "Tags": {"added": "yes"}}
+ """.formatted(queueUrl)).then().statusCode(200);
+ getResources(markerAndAddedFilter("sqs:queue", marker))
+ .body("ResourceTagMappingList.ResourceARN", contains(arn));
+
+ sqs("UntagQueue", """
+ {"QueueUrl": "%s", "TagKeys": ["added"]}
+ """.formatted(queueUrl)).then().statusCode(200);
+ getResources(markerAndAddedFilter("sqs:queue", marker))
+ .body("ResourceTagMappingList", empty());
+
+ sqs("DeleteQueue", """
+ {"QueueUrl": "%s"}
+ """.formatted(queueUrl)).then().statusCode(200);
+ getResources(markerFilter("sqs:queue", marker))
+ .body("ResourceTagMappingList", empty());
+ }
+
+ @Test
+ void lambdaFunctionIsDiscoveredByTypeAndItsOwnTags() {
+ String name = "discovery-" + unique();
+ String marker = unique();
+ String arn = given()
+ .contentType("application/json")
+ .body("""
+ {
+ "FunctionName": "%s",
+ "Runtime": "nodejs20.x",
+ "Role": "arn:aws:iam::000000000000:role/lambda-role",
+ "Handler": "index.handler",
+ "Tags": {"fd": "%s"}
+ }
+ """.formatted(name, marker))
+ .when()
+ .post("/2015-03-31/functions")
+ .then()
+ .statusCode(201)
+ .extract().path("FunctionArn");
+ assertThat(arn, equalTo(ARN_PREFIX.formatted("lambda") + "function:" + name));
+
+ getResources(markerFilter("lambda:function", marker))
+ .body("ResourceTagMappingList.ResourceARN", contains(arn))
+ .body("ResourceTagMappingList[0].Tags.find { it.Key == 'fd' }.Value", equalTo(marker));
+
+ given()
+ .contentType("application/json")
+ .body("""
+ {"Tags": {"added": "yes"}}
+ """)
+ .when()
+ .post("/2017-03-31/tags/" + arn)
+ .then()
+ .statusCode(204);
+ getResources(markerAndAddedFilter("lambda:function", marker))
+ .body("ResourceTagMappingList.ResourceARN", contains(arn));
+
+ given()
+ .queryParam("tagKeys", "added")
+ .when()
+ .delete("/2017-03-31/tags/" + arn)
+ .then()
+ .statusCode(204);
+ getResources(markerAndAddedFilter("lambda:function", marker))
+ .body("ResourceTagMappingList", empty());
+
+ given()
+ .when()
+ .delete("/2015-03-31/functions/" + name)
+ .then()
+ .statusCode(204);
+ getResources(markerFilter("lambda:function", marker))
+ .body("ResourceTagMappingList", empty());
+ }
+
+ @Test
+ void logGroupIsDiscoveredWithoutWildcardSuffix() {
+ String name = "/probe/" + unique();
+ String marker = unique();
+ logs("CreateLogGroup", """
+ {"logGroupName": "%s", "tags": {"fd": "%s"}}
+ """.formatted(name, marker)).then().statusCode(200);
+
+ getResources(markerFilter("logs:log-group", marker))
+ .body("ResourceTagMappingList.ResourceARN", contains(ARN_PREFIX.formatted("logs") + "log-group:" + name));
+
+ logs("TagLogGroup", """
+ {"logGroupName": "%s", "tags": {"added": "yes"}}
+ """.formatted(name)).then().statusCode(200);
+ getResources(markerAndAddedFilter("logs:log-group", marker))
+ .body("ResourceTagMappingList.ResourceARN", contains(ARN_PREFIX.formatted("logs") + "log-group:" + name));
+
+ logs("UntagLogGroup", """
+ {"logGroupName": "%s", "tags": ["added"]}
+ """.formatted(name)).then().statusCode(200);
+ getResources(markerAndAddedFilter("logs:log-group", marker))
+ .body("ResourceTagMappingList", empty());
+
+ logs("DeleteLogGroup", """
+ {"logGroupName": "%s"}
+ """.formatted(name)).then().statusCode(200);
+ getResources(markerFilter("logs:log-group", marker))
+ .body("ResourceTagMappingList", empty());
+ }
+
+ @Test
+ void tagKeysAndValuesIncludeKeySetOnlyThroughSqs() {
+ String key = "sqs-only-" + unique();
+ String value = unique();
+ String queueUrl = sqs("CreateQueue", """
+ {"QueueName": "discovery-%s", "tags": {"%s": "%s"}}
+ """.formatted(unique(), key, value))
+ .then()
+ .statusCode(200)
+ .extract().path("QueueUrl");
+
+ assertThat(allTagKeys(), hasItem(key));
+ tagging("GetTagValues", """
+ {"Key": "%s"}
+ """.formatted(key))
+ .then()
+ .statusCode(200)
+ .body("TagValues", contains(value));
+
+ sqs("DeleteQueue", """
+ {"QueueUrl": "%s"}
+ """.formatted(queueUrl)).then().statusCode(200);
+ }
+
+ @Test
+ void apiKeyIsDiscoveredByTypeAndItsOwnTags() {
+ String marker = unique();
+ String id = createApiKey(marker);
+ String arn = APIGATEWAY_ARN_PREFIX + "/apikeys/" + id;
+
+ getResources(rsidFilter("apigateway:apikeys", marker))
+ .body("ResourceTagMappingList.ResourceARN", contains(arn))
+ .body("ResourceTagMappingList[0].Tags.size()", equalTo(3))
+ .body("ResourceTagMappingList[0].Tags.find { it.Key == 'cid' }.Value", equalTo("c1"));
+ getResources(rsidFilter("apigateway:/apikeys", marker))
+ .body("ResourceTagMappingList", empty());
+
+ deleteApiKey(id);
+ getResources(rsidFilter("apigateway:apikeys", marker))
+ .body("ResourceTagMappingList", empty());
+ }
+
+ @Test
+ void taggingApiWritesReachTheApiKey() {
+ String marker = unique();
+ String cid = "c2-" + marker;
+ String id = createApiKey(marker);
+ String arn = APIGATEWAY_ARN_PREFIX + "/apikeys/" + id;
+
+ tagging("TagResources", """
+ {"ResourceARNList": ["%s"], "Tags": {"cid": "%s"}}
+ """.formatted(arn, cid))
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", anEmptyMap());
+ tagging("UntagResources", """
+ {"ResourceARNList": ["%s"], "TagKeys": ["baah"]}
+ """.formatted(arn))
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", anEmptyMap());
+
+ given()
+ .when()
+ .get("/apikeys/" + id)
+ .then()
+ .statusCode(200)
+ .body("tags.rsid", equalTo(marker))
+ .body("tags.cid", equalTo(cid))
+ .body("tags", not(hasKey("baah")));
+ getResources("""
+ {"ResourceTypeFilters": ["apigateway:apikeys"], "TagFilters": [%s]}
+ """.formatted(tagFilter("cid", cid)))
+ .body("ResourceTagMappingList.ResourceARN", contains(arn))
+ .body("ResourceTagMappingList[0].Tags.size()", equalTo(2));
+
+ deleteApiKey(id);
+ getResources("""
+ {"TagFilters": [%s]}
+ """.formatted(tagFilter("cid", cid)))
+ .body("ResourceTagMappingList", empty());
+ }
+
+ @Test
+ void apiKeyRejectionOfReservedTagIsReportedInFailedResourcesMap() {
+ String marker = unique();
+ String id = createApiKey(marker);
+ String arn = APIGATEWAY_ARN_PREFIX + "/apikeys/" + id;
+
+ tagging("TagResources", """
+ {"ResourceARNList": ["%s"], "Tags": {"floci:override-id": "x%s"}}
+ """.formatted(arn, marker))
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", hasKey(arn))
+ .body("FailedResourcesMap['%s'].StatusCode".formatted(arn), equalTo(400))
+ .body("FailedResourcesMap['%s'].ErrorCode".formatted(arn), equalTo("BadRequestException"))
+ .body("FailedResourcesMap['%s'].ErrorMessage".formatted(arn), containsString("floci:override-id"));
+
+ getResources(rsidFilter("apigateway:apikeys", marker))
+ .body("ResourceTagMappingList.ResourceARN", contains(arn))
+ .body("ResourceTagMappingList[0].Tags.Key", not(hasItem("floci:override-id")));
+ given()
+ .when()
+ .get("/apikeys/" + id)
+ .then()
+ .statusCode(200)
+ .body("tags", not(hasKey("floci:override-id")));
+
+ deleteApiKey(id);
+ }
+
+ @Test
+ void usagePlanRejectionOfReservedTagIsReportedInFailedResourcesMap() {
+ String marker = unique();
+ String planId = given()
+ .contentType("application/json")
+ .body("""
+ {"name": "discovery-%s", "tags": {"rsid": "%s"}}
+ """.formatted(marker, marker))
+ .when()
+ .post("/usageplans")
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+ String arn = APIGATEWAY_ARN_PREFIX + "/usageplans/" + planId;
+
+ tagging("TagResources", """
+ {"ResourceARNList": ["%s"], "Tags": {"floci:override-id": "x%s"}}
+ """.formatted(arn, marker))
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", hasKey(arn))
+ .body("FailedResourcesMap['%s'].StatusCode".formatted(arn), equalTo(400))
+ .body("FailedResourcesMap['%s'].ErrorCode".formatted(arn), equalTo("BadRequestException"))
+ .body("FailedResourcesMap['%s'].ErrorMessage".formatted(arn), containsString("floci:override-id"));
+
+ getResources(rsidFilter("apigateway:usageplans", marker))
+ .body("ResourceTagMappingList.ResourceARN", contains(arn))
+ .body("ResourceTagMappingList[0].Tags.Key", not(hasItem("floci:override-id")));
+ given()
+ .when()
+ .get("/usageplans/" + planId)
+ .then()
+ .statusCode(200)
+ .body("tags.rsid", equalTo(marker))
+ .body("tags.size()", equalTo(1));
+
+ given().when().delete("/usageplans/" + planId).then().statusCode(202);
+ }
+
+ @Test
+ void deploymentArnDoesNotRetagTheRestApi() {
+ String marker = unique();
+ String apiId = createRestApi(marker);
+ String restApiArn = APIGATEWAY_ARN_PREFIX + "/restapis/" + apiId;
+ String deploymentArn = restApiArn + "/deployments/d1";
+
+ tagging("TagResources", """
+ {"ResourceARNList": ["%s"], "Tags": {"leak": "yes"}}
+ """.formatted(deploymentArn))
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", anEmptyMap());
+
+ given()
+ .pathParam("arn", restApiArn)
+ .when()
+ .get("/tags/{arn}")
+ .then()
+ .statusCode(200)
+ .body("tags.fd", equalTo(marker))
+ .body("tags", not(hasKey("leak")));
+
+ tagging("UntagResources", """
+ {"ResourceARNList": ["%s"], "TagKeys": ["leak"]}
+ """.formatted(deploymentArn)).then().statusCode(200);
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+
+ @Test
+ void restTagsPathReadsAndWritesApiKeyTags() {
+ String marker = unique();
+ String id = createApiKey(marker);
+ String arn = APIGATEWAY_ARN_PREFIX + "/apikeys/" + id;
+
+ given()
+ .pathParam("arn", arn)
+ .contentType("application/json")
+ .body("""
+ {"tags": {"added": "yes"}}
+ """)
+ .when()
+ .put("/tags/{arn}")
+ .then()
+ .statusCode(204);
+ given()
+ .pathParam("arn", arn)
+ .when()
+ .get("/tags/{arn}")
+ .then()
+ .statusCode(200)
+ .body("tags.rsid", equalTo(marker))
+ .body("tags.added", equalTo("yes"));
+ given()
+ .pathParam("arn", arn)
+ .queryParam("tagKeys", "added")
+ .when()
+ .delete("/tags/{arn}")
+ .then()
+ .statusCode(204);
+ given()
+ .when()
+ .get("/apikeys/" + id)
+ .then()
+ .statusCode(200)
+ .body("tags", not(hasKey("added")));
+
+ deleteApiKey(id);
+ }
+
+ @Test
+ void apiKeySegmentNestedUnderRestApiArnIsRejected() {
+ String marker = unique();
+ String apiId = createRestApi(marker);
+ String keyId = createApiKey(marker);
+ String arn = APIGATEWAY_ARN_PREFIX + "/restapis/" + apiId + "/apikeys/" + keyId;
+
+ putNestedTagIsRejected(arn);
+ given()
+ .when()
+ .get("/apikeys/" + keyId)
+ .then()
+ .statusCode(200)
+ .body("tags.rsid", equalTo(marker))
+ .body("tags", not(hasKey("nested")));
+ restApiTagsAreUnchanged(apiId, marker);
+
+ deleteApiKey(keyId);
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+
+ @Test
+ void domainSegmentNestedUnderRestApiArnIsRejected() {
+ String marker = unique();
+ String apiId = createRestApi(marker);
+ String domainName = "discovery-" + marker + ".example.com";
+ given()
+ .contentType("application/json")
+ .body("""
+ {"domainName": "%s", "regionalCertificateArn": "%s",
+ "endpointConfiguration": {"types": ["REGIONAL"]}, "tags": {"fd": "%s"}}
+ """.formatted(domainName, ARN_PREFIX.formatted("acm") + "certificate/" + UUID.randomUUID(), marker))
+ .when()
+ .post("/domainnames")
+ .then()
+ .statusCode(201);
+
+ putNestedTagIsRejected(APIGATEWAY_ARN_PREFIX + "/restapis/" + apiId + "/domainnames/" + domainName);
+ given()
+ .when()
+ .get("/domainnames/" + domainName)
+ .then()
+ .statusCode(200)
+ .body("tags.fd", equalTo(marker))
+ .body("tags", not(hasKey("nested")));
+ restApiTagsAreUnchanged(apiId, marker);
+
+ given().when().delete("/domainnames/" + domainName).then().statusCode(202);
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+
+ @Test
+ void deploymentArnIsRejectedByTheTagsPath() {
+ String marker = unique();
+ String apiId = createRestApi(marker);
+
+ putNestedTagIsRejected(APIGATEWAY_ARN_PREFIX + "/restapis/" + apiId + "/deployments/d1");
+ restApiTagsAreUnchanged(apiId, marker);
+
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+
+ @Test
+ void restApiIsDiscoveredByType() {
+ String marker = unique();
+ String apiId = createRestApi(marker);
+
+ getResources(markerFilter("apigateway:restapis", marker))
+ .body("ResourceTagMappingList.ResourceARN", contains(APIGATEWAY_ARN_PREFIX + "/restapis/" + apiId));
+
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ getResources(markerFilter("apigateway:restapis", marker))
+ .body("ResourceTagMappingList", empty());
+ }
+
+ @Test
+ void stageIsDiscoveredByType() {
+ String marker = unique();
+ String apiId = createRestApi(marker);
+ String deploymentId = given()
+ .contentType("application/json")
+ .body("{}")
+ .when()
+ .post("/restapis/" + apiId + "/deployments")
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+ given()
+ .contentType("application/json")
+ .body("""
+ {"stageName": "dev", "deploymentId": "%s", "tags": {"fd": "%s"}}
+ """.formatted(deploymentId, marker))
+ .when()
+ .post("/restapis/" + apiId + "/stages")
+ .then()
+ .statusCode(201);
+
+ String restApiArn = APIGATEWAY_ARN_PREFIX + "/restapis/" + apiId;
+ getResources(markerFilter("apigateway:restapis/stages", marker))
+ .body("ResourceTagMappingList.ResourceARN", contains(restApiArn + "/stages/dev"));
+ getResources(markerFilter("apigateway:restapis", marker))
+ .body("ResourceTagMappingList.ResourceARN", contains(restApiArn, restApiArn + "/stages/dev"));
+
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+
+ @Test
+ void taggedIamRoleIsNotListed() {
+ String role = "discovery-" + unique();
+ String marker = unique();
+ given()
+ .header("Authorization", IAM_AUTH)
+ .formParam("Action", "CreateRole")
+ .formParam("RoleName", role)
+ .formParam("AssumeRolePolicyDocument", """
+ {"Version": "2012-10-17", "Statement": [{"Effect": "Allow",
+ "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}""")
+ .formParam("Tags.member.1.Key", "fd")
+ .formParam("Tags.member.1.Value", marker)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ getResources("""
+ {"TagFilters": [%s]}
+ """.formatted(tagFilter("fd", marker)))
+ .body("ResourceTagMappingList", empty());
+
+ given()
+ .header("Authorization", IAM_AUTH)
+ .formParam("Action", "DeleteRole")
+ .formParam("RoleName", role)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ @Test
+ void iamRoleTaggedThroughTheTaggingApiIsNotListed() {
+ String role = "discovery-" + unique();
+ String marker = unique();
+ String roleArn = given()
+ .header("Authorization", IAM_AUTH)
+ .formParam("Action", "CreateRole")
+ .formParam("RoleName", role)
+ .formParam("AssumeRolePolicyDocument", """
+ {"Version": "2012-10-17", "Statement": [{"Effect": "Allow",
+ "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}""")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().path("CreateRoleResponse.CreateRoleResult.Role.Arn");
+
+ tagging("TagResources", """
+ {"ResourceARNList": ["%s"], "Tags": {"fd": "%s"}}
+ """.formatted(roleArn, marker))
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", anEmptyMap());
+
+ getResources("""
+ {"TagFilters": [%s]}
+ """.formatted(tagFilter("fd", marker)))
+ .body("ResourceTagMappingList", empty());
+
+ given()
+ .header("Authorization", IAM_AUTH)
+ .formParam("Action", "DeleteRole")
+ .formParam("RoleName", role)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ getResources("""
+ {"TagFilters": [%s]}
+ """.formatted(tagFilter("fd", marker)))
+ .body("ResourceTagMappingList", empty());
+ }
+
+ @Test
+ void tagResourcesRejectsArnFromAnotherRegion() {
+ String marker = unique();
+ String westArn = "arn:aws:sqs:eu-west-1:000000000000:discovery-" + marker;
+
+ tagging("TagResources", """
+ {"ResourceARNList": ["%s"], "Tags": {"fd": "%s"}}
+ """.formatted(westArn, marker))
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("InvalidParameterException"))
+ .body("message", equalTo("Region in the ARN " + westArn
+ + " does not match with the region in which TagResources API is invoked"));
+ }
+
+ @Test
+ void taggingApiWritesReachTheMskCluster() {
+ String marker = unique();
+ String clusterArn = given()
+ .contentType("application/json")
+ .body("""
+ {"clusterName": "discovery-%s", "kafkaVersion": "3.6.0", "tags": {"fd": "%s"}}
+ """.formatted(marker, marker))
+ .when()
+ .post("/v1/clusters")
+ .then()
+ .statusCode(200)
+ .extract().path("clusterArn");
+
+ tagging("TagResources", """
+ {"ResourceARNList": ["%s"], "Tags": {"added": "yes"}}
+ """.formatted(clusterArn))
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", anEmptyMap());
+ mskTags(clusterArn)
+ .body("tags.fd", equalTo(marker))
+ .body("tags.added", equalTo("yes"));
+
+ tagging("UntagResources", """
+ {"ResourceARNList": ["%s"], "TagKeys": ["added"]}
+ """.formatted(clusterArn))
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", anEmptyMap());
+ mskTags(clusterArn)
+ .body("tags.fd", equalTo(marker))
+ .body("tags", not(hasKey("added")));
+
+ given().when().delete("/v1/clusters/{arn}", clusterArn).then().statusCode(200);
+ }
+
+ @Test
+ void taggingApiWritesReachTheSqsQueue() {
+ String name = "discovery-" + unique();
+ String marker = unique();
+ String value = unique();
+ String arn = ARN_PREFIX.formatted("sqs") + name;
+ String queueUrl = sqs("CreateQueue", """
+ {"QueueName": "%s", "tags": {"fd": "%s"}}
+ """.formatted(name, marker))
+ .then()
+ .statusCode(200)
+ .extract().path("QueueUrl");
+
+ tagAddedThroughTaggingApi(arn, value);
+ sqsQueueTags(queueUrl)
+ .body("Tags.fd", equalTo(marker))
+ .body("Tags.added", equalTo(value));
+ addedTagIsListedOnce(arn, value);
+
+ untagAddedThroughTaggingApi(arn);
+ sqsQueueTags(queueUrl)
+ .body("Tags.fd", equalTo(marker))
+ .body("Tags", not(hasKey("added")));
+ addedTagIsNotListed(arn);
+
+ sqs("DeleteQueue", """
+ {"QueueUrl": "%s"}
+ """.formatted(queueUrl)).then().statusCode(200);
+ }
+
+ @Test
+ void taggingApiReportsAnotherAccountsArn() {
+ String name = "discovery-" + unique();
+ String foreignArn = "arn:aws:sqs:us-east-1:111111111111:" + name;
+ String queueUrl = sqs("CreateQueue", """
+ {"QueueName": "%s"}
+ """.formatted(name))
+ .then()
+ .statusCode(200)
+ .extract().path("QueueUrl");
+
+ tagging("TagResources", """
+ {"ResourceARNList": ["%s"], "Tags": {"added": "%s"}}
+ """.formatted(foreignArn, unique()))
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap.size()", equalTo(1))
+ .body("FailedResourcesMap['%s'].ErrorCode".formatted(foreignArn), equalTo("AccessDeniedException"))
+ .body("FailedResourcesMap['%s'].StatusCode".formatted(foreignArn), equalTo(403));
+ sqsQueueTags(queueUrl)
+ .body("Tags", anEmptyMap());
+
+ sqs("DeleteQueue", """
+ {"QueueUrl": "%s"}
+ """.formatted(queueUrl)).then().statusCode(200);
+ }
+
+ @Test
+ void taggingApiWritesReachTheLambdaFunction() {
+ String name = "discovery-" + unique();
+ String marker = unique();
+ String value = unique();
+ String arn = given()
+ .contentType("application/json")
+ .body("""
+ {
+ "FunctionName": "%s",
+ "Runtime": "nodejs20.x",
+ "Role": "arn:aws:iam::000000000000:role/lambda-role",
+ "Handler": "index.handler",
+ "Tags": {"fd": "%s"}
+ }
+ """.formatted(name, marker))
+ .when()
+ .post("/2015-03-31/functions")
+ .then()
+ .statusCode(201)
+ .extract().path("FunctionArn");
+
+ tagAddedThroughTaggingApi(arn, value);
+ lambdaTags(arn)
+ .body("Tags.fd", equalTo(marker))
+ .body("Tags.added", equalTo(value));
+ addedTagIsListedOnce(arn, value);
+
+ untagAddedThroughTaggingApi(arn);
+ lambdaTags(arn)
+ .body("Tags.fd", equalTo(marker))
+ .body("Tags", not(hasKey("added")));
+ addedTagIsNotListed(arn);
+
+ given().when().delete("/2015-03-31/functions/" + name).then().statusCode(204);
+ }
+
+ @Test
+ void taggingApiWritesReachTheLogGroup() {
+ String name = "/probe/" + unique();
+ String marker = unique();
+ String value = unique();
+ String arn = ARN_PREFIX.formatted("logs") + "log-group:" + name;
+ logs("CreateLogGroup", """
+ {"logGroupName": "%s", "tags": {"fd": "%s"}}
+ """.formatted(name, marker)).then().statusCode(200);
+
+ tagAddedThroughTaggingApi(arn, value);
+ logs("ListTagsLogGroup", """
+ {"logGroupName": "%s"}
+ """.formatted(name))
+ .then()
+ .statusCode(200)
+ .body("tags.fd", equalTo(marker))
+ .body("tags.added", equalTo(value));
+ logGroupTagsByArn(arn)
+ .body("tags.fd", equalTo(marker))
+ .body("tags.added", equalTo(value));
+ addedTagIsListedOnce(arn, value);
+
+ untagAddedThroughTaggingApi(arn);
+ logGroupTagsByArn(arn)
+ .body("tags.fd", equalTo(marker))
+ .body("tags", not(hasKey("added")));
+ addedTagIsNotListed(arn);
+
+ logs("DeleteLogGroup", """
+ {"logGroupName": "%s"}
+ """.formatted(name)).then().statusCode(200);
+ }
+
+ @Test
+ void taggingApiRejectsWildcardLogGroupArn() {
+ String name = "/probe/" + unique();
+ String marker = unique();
+ String wildcardArn = ARN_PREFIX.formatted("logs") + "log-group:" + name + ":*";
+ logs("CreateLogGroup", """
+ {"logGroupName": "%s", "tags": {"fd": "%s"}}
+ """.formatted(name, marker)).then().statusCode(200);
+
+ wildcardArnIsRejected(tagging("TagResources", """
+ {"ResourceARNList": ["%s"], "Tags": {"added": "yes"}}
+ """.formatted(wildcardArn)), wildcardArn);
+ logGroupTagsAreOnlyTheMarker(name, marker);
+
+ wildcardArnIsRejected(tagging("UntagResources", """
+ {"ResourceARNList": ["%s"], "TagKeys": ["fd"]}
+ """.formatted(wildcardArn)), wildcardArn);
+ logGroupTagsAreOnlyTheMarker(name, marker);
+
+ String missingArn = ARN_PREFIX.formatted("logs") + "log-group:/probe/missing-" + marker + ":*";
+ wildcardArnIsRejected(tagging("TagResources", """
+ {"ResourceARNList": ["%s"], "Tags": {"missing": "%s"}}
+ """.formatted(missingArn, marker)), missingArn);
+ getResources("""
+ {"TagFilters": [%s]}
+ """.formatted(tagFilter("missing", marker)))
+ .body("ResourceTagMappingList", empty());
+
+ logs("DeleteLogGroup", """
+ {"logGroupName": "%s"}
+ """.formatted(name)).then().statusCode(200);
+ }
+
+ @Test
+ void sqsQueueIsNotServedOnTheSharedTagsPaths() {
+ String name = "discovery-" + unique();
+ String arn = ARN_PREFIX.formatted("sqs") + name;
+ String unhandledArn = ARN_PREFIX.formatted("sns") + name;
+ String queueUrl = sqs("CreateQueue", """
+ {"QueueName": "%s", "tags": {"fd": "%s"}}
+ """.formatted(name, unique()))
+ .then()
+ .statusCode(200)
+ .extract().path("QueueUrl");
+
+ for (String path : List.of("/tags/{arn}", "/v1/tags/{arn}")) {
+ tagsPathRejectsArn(path, unhandledArn);
+ tagsPathRejectsArn(path, arn);
+ }
+
+ sqs("DeleteQueue", """
+ {"QueueUrl": "%s"}
+ """.formatted(queueUrl)).then().statusCode(200);
+ }
+
+ @Test
+ void usagePlanIsDiscoveredByType() {
+ String marker = unique();
+ String planId = given()
+ .contentType("application/json")
+ .body("""
+ {"name": "discovery-%s", "tags": {"fd": "%s"}}
+ """.formatted(marker, marker))
+ .when()
+ .post("/usageplans")
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+
+ getResources(markerFilter("apigateway:usageplans", marker))
+ .body("ResourceTagMappingList.ResourceARN", contains(APIGATEWAY_ARN_PREFIX + "/usageplans/" + planId));
+
+ given().when().delete("/usageplans/" + planId).then().statusCode(202);
+ getResources(markerFilter("apigateway:usageplans", marker))
+ .body("ResourceTagMappingList", empty());
+ }
+
+ @Test
+ void taggingApiWritesReachTheUsagePlan() {
+ String marker = unique();
+ String planId = given()
+ .contentType("application/json")
+ .body("""
+ {"name": "discovery-%s", "tags": {"fd": "%s"}}
+ """.formatted(marker, marker))
+ .when()
+ .post("/usageplans")
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+ String arn = APIGATEWAY_ARN_PREFIX + "/usageplans/" + planId;
+
+ tagging("TagResources", """
+ {"ResourceARNList": ["%s"], "Tags": {"added": "yes"}}
+ """.formatted(arn))
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", anEmptyMap());
+
+ given()
+ .when()
+ .get("/usageplans/" + planId)
+ .then()
+ .statusCode(200)
+ .body("tags.fd", equalTo(marker))
+ .body("tags.added", equalTo("yes"));
+ given()
+ .pathParam("arn", arn)
+ .when()
+ .get("/tags/{arn}")
+ .then()
+ .statusCode(200)
+ .body("tags.fd", equalTo(marker))
+ .body("tags.added", equalTo("yes"));
+
+ tagging("UntagResources", """
+ {"ResourceARNList": ["%s"], "TagKeys": ["added"]}
+ """.formatted(arn))
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", anEmptyMap());
+ given()
+ .when()
+ .get("/usageplans/" + planId)
+ .then()
+ .statusCode(200)
+ .body("tags.fd", equalTo(marker))
+ .body("tags", not(hasKey("added")));
+
+ given().when().delete("/usageplans/" + planId).then().statusCode(202);
+ }
+
+ @Test
+ void domainNameIsDiscoveredByType() {
+ String marker = unique();
+ String domainName = "discovery-" + marker + ".example.com";
+ given()
+ .contentType("application/json")
+ .body("""
+ {"domainName": "%s", "regionalCertificateArn": "%s",
+ "endpointConfiguration": {"types": ["REGIONAL"]}, "tags": {"fd": "%s"}}
+ """.formatted(domainName, ARN_PREFIX.formatted("acm") + "certificate/" + UUID.randomUUID(), marker))
+ .when()
+ .post("/domainnames")
+ .then()
+ .statusCode(201);
+
+ getResources(markerFilter("apigateway:domainnames", marker))
+ .body("ResourceTagMappingList.ResourceARN", contains(APIGATEWAY_ARN_PREFIX + "/domainnames/" + domainName));
+
+ given().when().delete("/domainnames/" + domainName).then().statusCode(202);
+ getResources(markerFilter("apigateway:domainnames", marker))
+ .body("ResourceTagMappingList", empty());
+ }
+
+ private static String createApiKey(String marker) {
+ return given()
+ .contentType("application/json")
+ .body("""
+ {"name": "discovery-%s", "tags": {"rsid": "%s", "cid": "c1", "baah": "x"}}
+ """.formatted(marker, marker))
+ .when()
+ .post("/apikeys")
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+ }
+
+ private static void putNestedTagIsRejected(String arn) {
+ given()
+ .pathParam("arn", arn)
+ .contentType("application/json")
+ .body("""
+ {"tags": {"nested": "yes"}}
+ """)
+ .when()
+ .put("/tags/{arn}")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Invalid ARN specified in the request"));
+ }
+
+ private static void restApiTagsAreUnchanged(String apiId, String marker) {
+ given()
+ .pathParam("arn", APIGATEWAY_ARN_PREFIX + "/restapis/" + apiId)
+ .when()
+ .get("/tags/{arn}")
+ .then()
+ .statusCode(200)
+ .body("tags.fd", equalTo(marker))
+ .body("tags", not(hasKey("nested")));
+ }
+
+ private static ValidatableResponse mskTags(String arn) {
+ return given()
+ .pathParam("arn", arn)
+ .when()
+ .get("/v1/tags/{arn}")
+ .then()
+ .statusCode(200);
+ }
+
+ private static void deleteApiKey(String id) {
+ given().when().delete("/apikeys/" + id).then().statusCode(202);
+ }
+
+ private static void tagAddedThroughTaggingApi(String arn, String value) {
+ tagging("TagResources", """
+ {"ResourceARNList": ["%s"], "Tags": {"added": "%s"}}
+ """.formatted(arn, value))
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", anEmptyMap());
+ }
+
+ private static void untagAddedThroughTaggingApi(String arn) {
+ tagging("UntagResources", """
+ {"ResourceARNList": ["%s"], "TagKeys": ["added"]}
+ """.formatted(arn))
+ .then()
+ .statusCode(200)
+ .body("FailedResourcesMap", anEmptyMap());
+ }
+
+ private static void addedTagIsListedOnce(String arn, String value) {
+ getResources(arnFilter(arn))
+ .body("ResourceTagMappingList.ResourceARN", contains(arn))
+ .body("ResourceTagMappingList[0].Tags.findAll { it.Key == 'added' }.Value", contains(value));
+ }
+
+ private static void addedTagIsNotListed(String arn) {
+ getResources(arnFilter(arn))
+ .body("ResourceTagMappingList.ResourceARN", contains(arn))
+ .body("ResourceTagMappingList[0].Tags.Key", not(hasItem("added")));
+ }
+
+ private static String arnFilter(String arn) {
+ return """
+ {"ResourceARNList": ["%s"]}
+ """.formatted(arn);
+ }
+
+ private static ValidatableResponse sqsQueueTags(String queueUrl) {
+ return sqs("ListQueueTags", """
+ {"QueueUrl": "%s"}
+ """.formatted(queueUrl))
+ .then()
+ .statusCode(200);
+ }
+
+ private static ValidatableResponse lambdaTags(String arn) {
+ return given()
+ .when()
+ .get("/2017-03-31/tags/" + arn)
+ .then()
+ .statusCode(200);
+ }
+
+ private static ValidatableResponse logGroupTagsByArn(String arn) {
+ return logs("ListTagsForResource", """
+ {"resourceArn": "%s"}
+ """.formatted(arn))
+ .then()
+ .statusCode(200);
+ }
+
+ private static void wildcardArnIsRejected(Response response, String wildcardArn) {
+ response.then()
+ .statusCode(200)
+ .body("FailedResourcesMap.size()", equalTo(1))
+ .body("FailedResourcesMap['%s'].StatusCode".formatted(wildcardArn), equalTo(400))
+ .body("FailedResourcesMap['%s'].ErrorCode".formatted(wildcardArn), equalTo("ValidationException"))
+ .body("FailedResourcesMap['%s'].ErrorMessage".formatted(wildcardArn), equalTo("Invalid resourceArn"));
+ }
+
+ private static void logGroupTagsAreOnlyTheMarker(String name, String marker) {
+ logs("ListTagsLogGroup", """
+ {"logGroupName": "%s"}
+ """.formatted(name))
+ .then()
+ .statusCode(200)
+ .body("tags.size()", equalTo(1))
+ .body("tags.fd", equalTo(marker));
+ }
+
+ private static void tagsPathRejectsArn(String path, String arn) {
+ given()
+ .pathParam("arn", arn)
+ .when()
+ .get(path)
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Invalid resource ARN: " + arn));
+ }
+
+ private static String createRestApi(String marker) {
+ return given()
+ .contentType("application/json")
+ .body("""
+ {"name": "discovery-%s", "tags": {"fd": "%s"}}
+ """.formatted(marker, marker))
+ .when()
+ .post("/restapis")
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+ }
+
+ private static String rsidFilter(String resourceType, String marker) {
+ return """
+ {"ResourceTypeFilters": ["%s"], "TagFilters": [%s]}
+ """.formatted(resourceType, tagFilter("rsid", marker));
+ }
+
+ private static List<String> allTagKeys() {
+ List<String> keys = new ArrayList<>();
+ String token = "";
+ do {
+ Response response = tagging("GetTagKeys", """
+ {"PaginationToken": "%s"}
+ """.formatted(token));
+ response.then().statusCode(200);
+ keys.addAll(response.jsonPath().getList("TagKeys", String.class));
+ token = response.jsonPath().getString("PaginationToken");
+ } while (token != null && !token.isEmpty());
+ return keys;
+ }
+
+ private static String markerFilter(String resourceType, String marker) {
+ return """
+ {"ResourceTypeFilters": ["%s"], "TagFilters": [%s]}
+ """.formatted(resourceType, tagFilter("fd", marker));
+ }
+
+ private static String markerAndAddedFilter(String resourceType, String marker) {
+ return """
+ {"ResourceTypeFilters": ["%s"], "TagFilters": [%s, {"Key": "added"}]}
+ """.formatted(resourceType, tagFilter("fd", marker));
+ }
+
+ private static String tagFilter(String key, String value) {
+ return """
+ {"Key": "%s", "Values": ["%s"]}""".formatted(key, value);
+ }
+
+ private static ValidatableResponse getResources(String body) {
+ return tagging("GetResources", body).then().statusCode(200);
+ }
+
+ private static Response tagging(String action, String body) {
+ return given()
+ .header("X-Amz-Target", TAGGING_TARGET + action)
+ .contentType(JSON_1_1)
+ .body(body)
+ .when()
+ .post("/");
+ }
+
+ private static Response sqs(String action, String body) {
+ return given()
+ .header("X-Amz-Target", "AmazonSQS." + action)
+ .contentType(JSON_1_0)
+ .body(body)
+ .when()
+ .post("/");
+ }
+
+ private static Response logs(String action, String body) {
+ return given()
+ .header("X-Amz-Target", "Logs_20140328." + action)
+ .contentType(JSON_1_1)
+ .body(body)
+ .when()
+ .post("/");
+ }
+
+ private static String unique() {
+ return UUID.randomUUID().toString().substring(0, 8);
+ }
+}
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
index f28b5d8d15..85619806a1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingIntegrationTest.java
@@ -14,6 +14,8 @@ import static org.hamcrest.Matchers.*;
/**
* Integration tests for the Resource Groups Tagging API.
* Uses JSON 1.1 protocol (X-Amz-Target: ResourceGroupsTaggingAPI_20170126.*).
+ * Unscoped queries also return tagged resources other test classes left in the shared
+ * application, so they assert on this class's ARNs rather than on result counts.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@@ -123,8 +125,8 @@ class ResourceGroupsTaggingIntegrationTest {
.post("/")
.then()
.statusCode(200)
- .body("ResourceTagMappingList.size()", equalTo(2))
- .body("ResourceTagMappingList.ResourceARN", hasItems(ARN_INSTANCE, ARN_BUCKET));
+ .body("ResourceTagMappingList.ResourceARN", hasItems(ARN_INSTANCE, ARN_BUCKET))
+ .body("ResourceTagMappingList.ResourceARN", not(hasItem(ARN_FUNCTION)));
}
@Test
@@ -145,7 +147,7 @@ class ResourceGroupsTaggingIntegrationTest {
.post("/")
.then()
.statusCode(200)
- .body("ResourceTagMappingList.size()", equalTo(3));
+ .body("ResourceTagMappingList.ResourceARN", hasItems(ARN_INSTANCE, ARN_BUCKET, ARN_FUNCTION));
}
@Test
@@ -161,8 +163,9 @@ class ResourceGroupsTaggingIntegrationTest {
.post("/")
.then()
.statusCode(200)
- .body("ResourceTagMappingList.size()", equalTo(1))
- .body("ResourceTagMappingList[0].ResourceARN", equalTo(ARN_INSTANCE));
+ .body("ResourceTagMappingList.ResourceARN", hasItem(ARN_INSTANCE))
+ .body("ResourceTagMappingList.ResourceARN",
+ everyItem(startsWith("arn:aws:ec2:us-east-1:000000000000:instance/")));
}
@Test
@@ -178,8 +181,8 @@ class ResourceGroupsTaggingIntegrationTest {
.post("/")
.then()
.statusCode(200)
- .body("ResourceTagMappingList.size()", equalTo(1))
- .body("ResourceTagMappingList[0].ResourceARN", equalTo(ARN_FUNCTION));
+ .body("ResourceTagMappingList.ResourceARN", hasItem(ARN_FUNCTION))
+ .body("ResourceTagMappingList.ResourceARN", everyItem(startsWith("arn:aws:lambda:")));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingServiceTest.java
new file mode 100644
index 0000000000..d855c01d75
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingServiceTest.java
@@ -0,0 +1,695 @@
+package io.github.hectorvent.floci.services.resourcegroupstagging;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.TagHandler;
+import io.github.hectorvent.floci.core.resource.ExplorerResource;
+import io.github.hectorvent.floci.core.resource.ResourceProvider;
+import io.github.hectorvent.floci.core.resource.SupportedResourceType;
+import io.github.hectorvent.floci.services.resourcegroupstagging.model.ResourceTagMapping;
+import org.junit.jupiter.api.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.AbstractMap;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.ConcurrentModificationException;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ResourceGroupsTaggingServiceTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String ACCOUNT = "000000000000";
+
+ private static final String QUEUE_ARN = "arn:aws:sqs:us-east-1:000000000000:q1";
+ private static final String INSTANCE_ARN = "arn:aws:ec2:us-east-1:000000000000:instance/i-1";
+ private static final String API_KEY_ARN = "arn:aws:apigateway:us-east-1::/apikeys/k1";
+ private static final String IOT_ARN = "arn:aws:iot:us-east-1:000000000000:thing/t1";
+ private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/r";
+
+ @Test
+ void parsedTypeCutsAtSlashOrColonAfterLeadingSlash() {
+ assertEquals("instance", ResourceGroupsTaggingService.parsedType("instance/i-1"));
+ assertEquals("function", ResourceGroupsTaggingService.parsedType("function:f"));
+ assertEquals("log-group", ResourceGroupsTaggingService.parsedType("log-group:/a/b"));
+ assertEquals("apikeys", ResourceGroupsTaggingService.parsedType("/apikeys/k"));
+ assertEquals("restapis", ResourceGroupsTaggingService.parsedType("/restapis/a/stages/s"));
+ assertEquals("my-bucket", ResourceGroupsTaggingService.parsedType("my-bucket"));
+ }
+
+ @Test
+ void resourceTypeFilterMatchesProviderDeclaredType() {
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(QUEUE_ARN, "sqs:queue", Map.of("team", "a")))), List.of());
+
+ List<ResourceTagMapping> items = service.getResources(
+ List.of(), List.of(), List.of("sqs:queue"), null, 0, REGION).items();
+
+ assertEquals(List.of(QUEUE_ARN), arns(items));
+ }
+
+ @Test
+ void resourceTypeFilterMatchesColonAndLeadingSlashArns() {
+ String functionArn = "arn:aws:lambda:us-east-1:000000000000:function:f1";
+ String logGroupArn = "arn:aws:logs:us-east-1:000000000000:log-group:/a/b";
+ ResourceGroupsTaggingService service = service(List.of(), List.of());
+ service.tagResources(List.of(functionArn, logGroupArn, API_KEY_ARN), Map.of("k", "v"), REGION);
+
+ assertEquals(List.of(functionArn), arns(filterByType(service, "lambda:function")));
+ assertEquals(List.of(logGroupArn), arns(filterByType(service, "logs:log-group")));
+ assertEquals(List.of(API_KEY_ARN), arns(filterByType(service, "apigateway:apikeys")));
+ assertTrue(filterByType(service, "apigateway:/apikeys").isEmpty());
+ }
+
+ @Test
+ void restApisFilterMatchesRestApisAndTheirStages() {
+ String apiArn = "arn:aws:apigateway:us-east-1::/restapis/a";
+ String stageArn = apiArn + "/stages/s";
+ ResourceGroupsTaggingService service = service(List.of(provider(
+ resource(apiArn, "apigateway:restapis", Map.of("k", "v")),
+ resource(stageArn, "apigateway:restapis/stages", Map.of("k", "v")))), List.of());
+
+ assertEquals(List.of(apiArn, stageArn), arns(filterByType(service, "apigateway:restapis")));
+ assertEquals(List.of(stageArn), arns(filterByType(service, "apigateway:restapis/stages")));
+ }
+
+ @Test
+ void providerResourceWithTagsIsListed() {
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(QUEUE_ARN, "sqs:queue", Map.of("team", "a")))), List.of());
+
+ List<ResourceTagMapping> items = allResources(service);
+
+ assertEquals(List.of(QUEUE_ARN), arns(items));
+ assertEquals(Map.of("team", "a"), items.getFirst().getTags());
+ }
+
+ @Test
+ void untaggedProviderResourceIsNotListed() {
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(QUEUE_ARN, "sqs:queue", Map.of()))), List.of());
+
+ assertTrue(allResources(service).isEmpty());
+ }
+
+ @Test
+ void providerTagsOverlayStoreTagsForSameArn() {
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(QUEUE_ARN, "sqs:queue", Map.of("b", "provider", "c", "provider")))), List.of());
+ service.tagResources(List.of(QUEUE_ARN), Map.of("a", "store", "b", "store"), REGION);
+
+ List<ResourceTagMapping> items = allResources(service);
+
+ assertEquals(1, items.size());
+ assertEquals(Map.of("a", "store", "b", "provider", "c", "provider"), items.getFirst().getTags());
+ assertEquals(Map.of("a", "store", "b", "store"), service.getTagsForResource(REGION, QUEUE_ARN));
+ }
+
+ @Test
+ void logGroupWildcardSuffixIsStripped() {
+ ResourceGroupsTaggingService service = service(List.of(provider(resource(
+ "arn:aws:logs:us-east-1:000000000000:log-group:/app/x:*", "logs:log-group",
+ Map.of("team", "a")))), List.of());
+
+ List<ResourceTagMapping> items = service.getResources(
+ List.of(), List.of(), List.of("logs:log-group"), null, 0, REGION).items();
+
+ assertEquals(List.of("arn:aws:logs:us-east-1:000000000000:log-group:/app/x"), arns(items));
+ }
+
+ @Test
+ void otherRegionAndOtherAccountAreHidden() {
+ String otherRegion = "arn:aws:sqs:us-west-2:000000000000:q-west";
+ String otherAccount = "arn:aws:sqs:us-east-1:111111111111:q-foreign";
+ ResourceGroupsTaggingService service = service(List.of(provider(
+ resource(otherRegion, "sqs:queue", Map.of("k", "v")),
+ resource(otherAccount, "sqs:queue", Map.of("k", "v")),
+ resource(QUEUE_ARN, "sqs:queue", Map.of("k", "v")))), List.of());
+
+ assertEquals(List.of(QUEUE_ARN), arns(allResources(service)));
+ }
+
+ @Test
+ void otherAccountArnIsReportedAndNotStored() {
+ String foreignArn = "arn:aws:sqs:us-east-1:111111111111:q-foreign";
+ ResourceGroupsTaggingService service = service(List.of(), List.of());
+
+ Map<String, AwsException> tagFailures = service.applyTags(List.of(foreignArn, QUEUE_ARN),
+ Map.of("k", "v"), REGION);
+
+ assertEquals(Set.of(foreignArn), tagFailures.keySet());
+ assertEquals("AccessDeniedException", tagFailures.get(foreignArn).getErrorCode());
+ assertEquals(403, tagFailures.get(foreignArn).getHttpStatus());
+ assertTrue(service.getTagsForResource(REGION, foreignArn).isEmpty());
+ assertEquals(Map.of("k", "v"), service.getTagsForResource(REGION, QUEUE_ARN));
+
+ service.tagResources(List.of(foreignArn), Map.of("k", "v"), REGION);
+ Map<String, AwsException> untagFailures = service.removeTags(List.of(foreignArn), List.of("k"), REGION);
+
+ assertEquals(Set.of(foreignArn), untagFailures.keySet());
+ assertEquals("AccessDeniedException", untagFailures.get(foreignArn).getErrorCode());
+ assertEquals(403, untagFailures.get(foreignArn).getHttpStatus());
+ assertEquals(Map.of("k", "v"), service.getTagsForResource(REGION, foreignArn));
+ }
+
+ @Test
+ void providerResourceWithoutArnRegionUsesItsOwnRegion() {
+ String bucketArn = "arn:aws:s3:::b";
+ ResourceGroupsTaggingService service = service(List.of(provider(new ExplorerResource(
+ bucketArn, "s3:bucket", "s3", "eu-west-1", ACCOUNT, Instant.EPOCH, Map.of("k", "v")))), List.of());
+
+ assertTrue(resourcesIn(service, REGION).isEmpty());
+ assertEquals(List.of(bucketArn), arns(resourcesIn(service, "eu-west-1")));
+ }
+
+ @Test
+ void storeCopyOfProviderResourceInAnotherRegionIsHidden() {
+ String bucketArn = "arn:aws:s3:::b";
+ ResourceGroupsTaggingService service = service(List.of(provider(new ExplorerResource(
+ bucketArn, "s3:bucket", "s3", "eu-west-1", ACCOUNT, Instant.EPOCH, Map.of("k", "v")))), List.of());
+ service.tagResources(List.of(bucketArn), Map.of("team", "a"), REGION);
+
+ List<ResourceTagMapping> west = resourcesIn(service, "eu-west-1");
+
+ assertTrue(resourcesIn(service, REGION).isEmpty());
+ assertEquals(List.of(bucketArn), arns(west));
+ assertEquals(Map.of("team", "a", "k", "v"), west.getFirst().getTags());
+ }
+
+ @Test
+ void globalProviderResourceIsNotListedInAnyRegion() {
+ ResourceGroupsTaggingService service = service(List.of(provider(globalRole(Map.of("k", "v")),
+ resource("arn:aws:iam::000000000000:user/u1", "iam:user", Map.of("k", "v")))), List.of());
+
+ assertTrue(resourcesIn(service, REGION).isEmpty());
+ assertTrue(resourcesIn(service, "eu-west-1").isEmpty());
+ assertTrue(service.getTagKeys(null, 0, REGION).items().isEmpty());
+ }
+
+ @Test
+ void storeEntryForGlobalProviderResourceIsNotListed() {
+ ResourceGroupsTaggingService service = service(List.of(provider(globalRole(Map.of("k", "v")))), List.of());
+ service.tagResources(List.of(ROLE_ARN), Map.of("team", "a"), REGION);
+
+ assertTrue(allResources(service).isEmpty());
+ }
+
+ @Test
+ void storeOnlyIamArnIsNotListed() {
+ ResourceGroupsTaggingService service = service(List.of(), List.of());
+ service.tagResources(List.of(ROLE_ARN), Map.of("team", "a"), REGION);
+
+ assertTrue(allResources(service).isEmpty());
+ }
+
+ @Test
+ void failingProviderIsSkipped() {
+ ResourceGroupsTaggingService service = service(List.of(failingProvider("ssm"),
+ provider(resource(QUEUE_ARN, "sqs:queue", Map.of("k", "v")))), List.of());
+
+ assertEquals(List.of(QUEUE_ARN), arns(allResources(service)));
+ }
+
+ @Test
+ void tagResourcesFailsWhenAnOwnerCannotBeRead() {
+ RecordingTagHandler handler = new RecordingTagHandler("sqs", false);
+ ResourceGroupsTaggingService service = service(List.of(failingProvider("sqs")), List.of(handler));
+
+ Map<String, AwsException> failures = service.applyTags(List.of(QUEUE_ARN), Map.of("k", "v"), REGION);
+
+ assertEquals(Set.of(QUEUE_ARN), failures.keySet());
+ assertEquals("InternalServiceException", failures.get(QUEUE_ARN).getErrorCode());
+ assertEquals(500, failures.get(QUEUE_ARN).getHttpStatus());
+ assertTrue(handler.tagged.isEmpty());
+ assertTrue(service.getTagsForResource(REGION, QUEUE_ARN).isEmpty());
+ assertTrue(allResources(service).isEmpty());
+ }
+
+ @Test
+ void untagResourcesFailsWhenAnOwnerCannotBeRead() {
+ RecordingTagHandler handler = new RecordingTagHandler("sqs", false);
+ ResourceGroupsTaggingService service = service(List.of(failingProvider("sqs")), List.of(handler));
+ service.tagResources(List.of(QUEUE_ARN), Map.of("k", "v"), REGION);
+
+ Map<String, AwsException> failures = service.removeTags(List.of(QUEUE_ARN), List.of("k"), REGION);
+
+ assertEquals(Set.of(QUEUE_ARN), failures.keySet());
+ assertEquals("InternalServiceException", failures.get(QUEUE_ARN).getErrorCode());
+ assertEquals(500, failures.get(QUEUE_ARN).getHttpStatus());
+ assertTrue(handler.untagged.isEmpty());
+ assertEquals(Map.of("k", "v"), service.getTagsForResource(REGION, QUEUE_ARN));
+ }
+
+ @Test
+ void listedOwnerIsTaggedWhenAnotherProviderFails() {
+ RecordingTagHandler handler = new RecordingTagHandler("sqs", false);
+ ResourceGroupsTaggingService service = service(List.of(failingProvider("sqs"),
+ provider(resource(QUEUE_ARN, "sqs:queue", Map.of()))), List.of(handler));
+
+ assertTrue(service.applyTags(List.of(QUEUE_ARN), Map.of("k", "v"), REGION).isEmpty());
+ assertTrue(service.removeTags(List.of(QUEUE_ARN), List.of("k"), REGION).isEmpty());
+
+ assertEquals(Map.of("k", "v"), handler.tagged.get(QUEUE_ARN));
+ assertEquals(List.of("k"), handler.untagged.get(QUEUE_ARN));
+ assertTrue(service.getTagsForResource(REGION, QUEUE_ARN).isEmpty());
+ }
+
+ @Test
+ void storeOnlyWriteSucceedsWhenAProviderCannotBeRead() {
+ RecordingTagHandler handler = new RecordingTagHandler("sqs", false);
+ ResourceGroupsTaggingService service = service(List.of(failingProvider("sqs")), List.of(handler));
+
+ service.applyTags(List.of(INSTANCE_ARN), Map.of("a", "1", "b", "2"), REGION);
+ service.removeTags(List.of(INSTANCE_ARN), List.of("a"), REGION);
+
+ assertEquals(Map.of("b", "2"), service.getTagsForResource(REGION, INSTANCE_ARN));
+ assertTrue(handler.tagged.isEmpty());
+ }
+
+ @Test
+ void unlistedArnIsStoredWhenAnotherServicesProviderFails() {
+ String deploymentArn = "arn:aws:apigateway:us-east-1::/restapis/abc/deployments/d1";
+ RecordingTagHandler handler = new RecordingTagHandler("apigateway", false);
+ ResourceGroupsTaggingService service = service(List.of(failingProvider("ssm"), provider(resource(
+ "arn:aws:apigateway:us-east-1::/restapis/abc", "apigateway:restapis", Map.of()))),
+ List.of(handler));
+
+ Map<String, AwsException> failures = service.applyTags(List.of(deploymentArn), Map.of("k", "v"), REGION);
+
+ assertTrue(failures.isEmpty());
+ assertTrue(handler.tagged.isEmpty());
+ assertEquals(Map.of("k", "v"), service.getTagsForResource(REGION, deploymentArn));
+ }
+
+ @Test
+ void providerWhoseTagsFailToCopyIsSkipped() {
+ Map<String, String> liveTags = new AbstractMap<>() {
+ @Override
+ public Set<Entry<String, String>> entrySet() {
+ throw new ConcurrentModificationException();
+ }
+ };
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(INSTANCE_ARN, "ec2:instance", liveTags)),
+ provider(resource(QUEUE_ARN, "sqs:queue", Map.of("k", "v")))), List.of());
+
+ assertEquals(List.of(QUEUE_ARN), arns(allResources(service)));
+ }
+
+ @Test
+ void getTagKeysAndValuesIncludeProviderTags() {
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(QUEUE_ARN, "sqs:queue", Map.of("pk", "pv")))), List.of());
+ service.tagResources(List.of(INSTANCE_ARN), Map.of("sk", "sv"), REGION);
+
+ List<String> keys = arns(service.getTagKeys(null, 0, REGION).items());
+ List<String> values = arns(service.getTagValues("pk", null, 0, REGION).items());
+
+ assertEquals(List.of("pk", "sk"), keys);
+ assertEquals(List.of("pv"), values);
+ }
+
+ @Test
+ void paginationSpansStoreAndProviderEntries() {
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(QUEUE_ARN, "sqs:queue", Map.of("k", "v")))), List.of());
+ service.tagResources(List.of(INSTANCE_ARN), Map.of("k", "v"), REGION);
+
+ ResourceGroupsTaggingService.PageResult first = service.getResources(
+ List.of(), List.of(), List.of(), null, 1, REGION);
+ ResourceGroupsTaggingService.PageResult second = service.getResources(
+ List.of(), List.of(), List.of(), first.nextPaginationToken(), 1, REGION);
+
+ assertEquals(List.of(INSTANCE_ARN), arns(first.items()));
+ assertEquals(List.of(QUEUE_ARN), arns(second.items()));
+ assertNull(second.nextPaginationToken());
+ }
+
+ @Test
+ void staleTokenPastTheEndReturnsAnEmptyPage() {
+ ResourceGroupsTaggingService service = service(List.of(), List.of());
+ service.tagResources(List.of(INSTANCE_ARN), Map.of("a", "v1"), REGION);
+ service.tagResources(List.of(QUEUE_ARN), Map.of("a", "v2", "b", "x"), REGION);
+ String resourcesToken = service.getResources(
+ List.of(), List.of(), List.of(), null, 1, REGION).nextPaginationToken();
+ String keysToken = service.getTagKeys(null, 1, REGION).nextPaginationToken();
+ String valuesToken = service.getTagValues("a", null, 1, REGION).nextPaginationToken();
+
+ service.deleteResources(List.of(INSTANCE_ARN, QUEUE_ARN), REGION);
+ ResourceGroupsTaggingService.PageResult resources = service.getResources(
+ List.of(), List.of(), List.of(), resourcesToken, 1, REGION);
+ ResourceGroupsTaggingService.PageResult keys = service.getTagKeys(keysToken, 1, REGION);
+ ResourceGroupsTaggingService.PageResult values = service.getTagValues("a", valuesToken, 1, REGION);
+
+ assertTrue(resources.items().isEmpty());
+ assertNull(resources.nextPaginationToken());
+ assertTrue(keys.items().isEmpty());
+ assertNull(keys.nextPaginationToken());
+ assertTrue(values.items().isEmpty());
+ assertNull(values.nextPaginationToken());
+ }
+
+ @Test
+ void negativeTokenReadsFromTheFirstPage() {
+ ResourceGroupsTaggingService service = service(List.of(), List.of());
+ service.tagResources(List.of(QUEUE_ARN), Map.of("a", "v"), REGION);
+ String negative = Base64.getEncoder().encodeToString("-1".getBytes(StandardCharsets.UTF_8));
+
+ assertEquals(1, service.getResources(List.of(), List.of(), List.of(), negative, 1, REGION).items().size());
+ assertEquals(1, service.getTagKeys(negative, 1, REGION).items().size());
+ assertEquals(1, service.getTagValues("a", negative, 1, REGION).items().size());
+ }
+
+ @Test
+ void malformedStoreArnStillListedWithoutFilters() {
+ ResourceGroupsTaggingService service = service(List.of(), List.of());
+ service.tagResources(List.of("not-an-arn"), Map.of("k", "v"), REGION);
+
+ assertEquals(List.of("not-an-arn"), arns(allResources(service)));
+ }
+
+ @Test
+ void listedArnWithHandlerIsForwardedAndNotStored() {
+ RecordingTagHandler handler = new RecordingTagHandler("apigateway", false);
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(API_KEY_ARN, "apigateway:apikeys", Map.of()))), List.of(handler));
+
+ Map<String, AwsException> failures = service.applyTags(List.of(API_KEY_ARN), Map.of("cid", "c2"), REGION);
+
+ assertTrue(failures.isEmpty());
+ assertEquals(Map.of("cid", "c2"), handler.tagged.get(API_KEY_ARN));
+ assertEquals(List.of(REGION), handler.regions);
+ assertTrue(service.getTagsForResource(REGION, API_KEY_ARN).isEmpty());
+ }
+
+ @Test
+ void listedArnMatchesWithoutWildcardSuffix() {
+ String logGroupArn = "arn:aws:logs:us-east-1:000000000000:log-group:/a";
+ RecordingTagHandler handler = new RecordingTagHandler("logs", false);
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(logGroupArn + ":*", "logs:log-group", Map.of()))), List.of(handler));
+
+ service.applyTags(List.of(logGroupArn), Map.of("k", "v"), REGION);
+
+ assertEquals(Map.of("k", "v"), handler.tagged.get(logGroupArn));
+ assertTrue(service.getTagsForResource(REGION, logGroupArn).isEmpty());
+ }
+
+ @Test
+ void unlistedArnWithHandlerGoesToStoreWithoutCallingHandler() {
+ String deploymentArn = "arn:aws:apigateway:us-east-1::/restapis/abc/deployments/d1";
+ RecordingTagHandler handler = new RecordingTagHandler("apigateway", false);
+ ResourceGroupsTaggingService service = service(List.of(provider(resource(
+ "arn:aws:apigateway:us-east-1::/restapis/abc", "apigateway:restapis", Map.of()))),
+ List.of(handler));
+
+ Map<String, AwsException> failures = service.applyTags(List.of(deploymentArn), Map.of("k", "v"), REGION);
+
+ assertTrue(failures.isEmpty());
+ assertTrue(handler.tagged.isEmpty());
+ assertEquals(Map.of("k", "v"), service.getTagsForResource(REGION, deploymentArn));
+ }
+
+ @Test
+ void ownerInAnotherRegionIsNotForwarded() {
+ String bucketArn = "arn:aws:s3:::b";
+ RecordingTagHandler handler = new RecordingTagHandler("s3", false);
+ ResourceGroupsTaggingService service = service(List.of(provider(new ExplorerResource(
+ bucketArn, "s3:bucket", "s3", "us-west-2", ACCOUNT, Instant.EPOCH, Map.of()))), List.of(handler));
+
+ service.applyTags(List.of(bucketArn), Map.of("a", "1", "b", "2"), REGION);
+ service.removeTags(List.of(bucketArn), List.of("a"), REGION);
+
+ assertTrue(handler.tagged.isEmpty());
+ assertTrue(handler.untagged.isEmpty());
+ assertEquals(Map.of("b", "2"), service.getTagsForResource(REGION, bucketArn));
+ }
+
+ @Test
+ void applyTagsPassesRequestRegionWhenArnHasNone() {
+ String bucketArn = "arn:aws:s3:::b";
+ RecordingTagHandler handler = new RecordingTagHandler("s3", false);
+ ResourceGroupsTaggingService service = service(List.of(provider(new ExplorerResource(
+ bucketArn, "s3:bucket", "s3", "eu-west-1", ACCOUNT, Instant.EPOCH, Map.of()))), List.of(handler));
+
+ service.applyTags(List.of(bucketArn), Map.of("k", "v"), "eu-west-1");
+
+ assertEquals(List.of("eu-west-1"), handler.regions);
+ }
+
+ @Test
+ void globalProviderResourceIsNotRoutedToItsOwner() {
+ RecordingTagHandler handler = new RecordingTagHandler("iam", false);
+ ResourceGroupsTaggingService service = service(List.of(provider(globalRole(Map.of()))), List.of(handler));
+
+ service.applyTags(List.of(ROLE_ARN), Map.of("k", "v"), REGION);
+
+ assertTrue(handler.tagged.isEmpty());
+ assertEquals(Map.of("k", "v"), service.getTagsForResource(REGION, ROLE_ARN));
+ }
+
+ @Test
+ void applyTagsRejectsArnFromAnotherRegionAndWritesNothing() {
+ String westQueueArn = "arn:aws:sqs:us-west-2:000000000000:q-west";
+ RecordingTagHandler handler = new RecordingTagHandler("apigateway", false);
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(API_KEY_ARN, "apigateway:apikeys", Map.of()))), List.of(handler));
+
+ AwsException e = assertThrows(AwsException.class, () -> service.applyTags(
+ List.of(API_KEY_ARN, QUEUE_ARN, westQueueArn), Map.of("k", "v"), REGION));
+
+ assertEquals("InvalidParameterException", e.getErrorCode());
+ assertEquals(400, e.getHttpStatus());
+ assertEquals("Region in the ARN " + westQueueArn
+ + " does not match with the region in which TagResources API is invoked", e.getMessage());
+ assertTrue(handler.tagged.isEmpty());
+ assertTrue(service.getTagsForResource(REGION, QUEUE_ARN).isEmpty());
+ assertTrue(service.getTagsForResource(REGION, westQueueArn).isEmpty());
+ }
+
+ @Test
+ void removeTagsRejectsArnFromAnotherRegionAndRemovesNothing() {
+ String westQueueArn = "arn:aws:sqs:us-west-2:000000000000:q-west";
+ RecordingTagHandler handler = new RecordingTagHandler("apigateway", false);
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(API_KEY_ARN, "apigateway:apikeys", Map.of()))), List.of(handler));
+ service.tagResources(List.of(QUEUE_ARN), Map.of("k", "v"), REGION);
+
+ AwsException e = assertThrows(AwsException.class, () -> service.removeTags(
+ List.of(API_KEY_ARN, QUEUE_ARN, westQueueArn), List.of("k"), REGION));
+
+ assertEquals("InvalidParameterException", e.getErrorCode());
+ assertEquals(400, e.getHttpStatus());
+ assertEquals("Region in the ARN " + westQueueArn
+ + " does not match with the region in which UntagResources API is invoked", e.getMessage());
+ assertTrue(handler.untagged.isEmpty());
+ assertEquals(Map.of("k", "v"), service.getTagsForResource(REGION, QUEUE_ARN));
+ }
+
+ @Test
+ void handlerRejectionIsReturnedAndNotStored() {
+ RecordingTagHandler handler = new RecordingTagHandler("apigateway", true);
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(API_KEY_ARN, "apigateway:apikeys", Map.of()))), List.of(handler));
+
+ Map<String, AwsException> failures = service.applyTags(
+ List.of(API_KEY_ARN, QUEUE_ARN), Map.of("cid", "c2"), REGION);
+
+ assertEquals(List.of(API_KEY_ARN), List.copyOf(failures.keySet()));
+ assertEquals("NotFoundException", failures.get(API_KEY_ARN).getErrorCode());
+ assertTrue(service.getTagsForResource(REGION, API_KEY_ARN).isEmpty());
+ assertEquals(Map.of("cid", "c2"), service.getTagsForResource(REGION, QUEUE_ARN));
+ }
+
+ @Test
+ void applyTagsWithoutHandlerWritesStore() {
+ ResourceGroupsTaggingService service = service(List.of(), List.of(new RecordingTagHandler("iot", false)));
+
+ Map<String, AwsException> failures = service.applyTags(List.of(QUEUE_ARN), Map.of("k", "v"), REGION);
+
+ assertTrue(failures.isEmpty());
+ assertEquals(Map.of("k", "v"), service.getTagsForResource(REGION, QUEUE_ARN));
+ }
+
+ @Test
+ void removeTagsCallsHandlerAndUntagsStore() {
+ RecordingTagHandler handler = new RecordingTagHandler("iot", false);
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(IOT_ARN, "iot:thing", Map.of()))), List.of(handler));
+ service.tagResources(List.of(IOT_ARN), Map.of("a", "1", "b", "2"), REGION);
+
+ Map<String, AwsException> failures = service.removeTags(List.of(IOT_ARN), List.of("a"), REGION);
+
+ assertTrue(failures.isEmpty());
+ assertEquals(List.of("a"), handler.untagged.get(IOT_ARN));
+ assertEquals(Map.of("b", "2"), service.getTagsForResource(REGION, IOT_ARN));
+ }
+
+ @Test
+ void removeTagsForUnlistedArnSkipsHandlerAndUntagsStore() {
+ RecordingTagHandler handler = new RecordingTagHandler("iot", false);
+ ResourceGroupsTaggingService service = service(List.of(), List.of(handler));
+ service.tagResources(List.of(IOT_ARN), Map.of("a", "1", "b", "2"), REGION);
+
+ service.removeTags(List.of(IOT_ARN), List.of("a"), REGION);
+
+ assertTrue(handler.untagged.isEmpty());
+ assertEquals(Map.of("b", "2"), service.getTagsForResource(REGION, IOT_ARN));
+ }
+
+ @Test
+ void removeTagsFailureIsReportedAndStoreStillUntagged() {
+ RecordingTagHandler handler = new RecordingTagHandler("apigateway", true);
+ ResourceGroupsTaggingService service = service(List.of(
+ provider(resource(API_KEY_ARN, "apigateway:apikeys", Map.of()))), List.of(handler));
+ service.tagResources(List.of(API_KEY_ARN, QUEUE_ARN), Map.of("a", "1", "b", "2"), REGION);
+
+ Map<String, AwsException> failures = service.removeTags(List.of(API_KEY_ARN, QUEUE_ARN), List.of("a"), REGION);
+
+ assertEquals(List.of(API_KEY_ARN), List.copyOf(failures.keySet()));
+ assertEquals(Map.of("b", "2"), service.getTagsForResource(REGION, API_KEY_ARN));
+ assertEquals(Map.of("b", "2"), service.getTagsForResource(REGION, QUEUE_ARN));
+ }
+
+ @Test
+ void removeTagsClearsStoredWildcardLogGroupArnTheHandlerRejects() {
+ String wildcardArn = "arn:aws:logs:us-east-1:000000000000:log-group:/a:*";
+ RecordingTagHandler handler = new RecordingTagHandler("logs", true);
+ ResourceGroupsTaggingService service = service(List.of(), List.of(handler));
+ service.tagResources(List.of(wildcardArn), Map.of("a", "1", "b", "2"), REGION);
+
+ Map<String, AwsException> failures = service.removeTags(List.of(wildcardArn), List.of("a"), REGION);
+
+ assertEquals(List.of(wildcardArn), List.copyOf(failures.keySet()));
+ assertEquals(Map.of("b", "2"), service.getTagsForResource(REGION, wildcardArn));
+ }
+
+ @Test
+ void tagResourcesStaysStoreOnly() {
+ RecordingTagHandler handler = new RecordingTagHandler("iot", false);
+ ResourceGroupsTaggingService service = service(List.of(), List.of(handler));
+
+ service.tagResources(List.of(IOT_ARN), Map.of("k", "v"), REGION);
+
+ assertTrue(handler.tagged.isEmpty());
+ assertEquals(Map.of("k", "v"), service.getTagsForResource(REGION, IOT_ARN));
+ }
+
+ private static ResourceGroupsTaggingService service(List<ResourceProvider> providers, List<TagHandler> handlers) {
+ return new ResourceGroupsTaggingService(null, providers, handlers, new RegionResolver(REGION, ACCOUNT));
+ }
+
+ private static List<ResourceTagMapping> allResources(ResourceGroupsTaggingService service) {
+ return resourcesIn(service, REGION);
+ }
+
+ private static List<ResourceTagMapping> resourcesIn(ResourceGroupsTaggingService service, String region) {
+ return service.getResources(List.of(), List.of(), List.of(), null, 0, region).items();
+ }
+
+ private static List<ResourceTagMapping> filterByType(ResourceGroupsTaggingService service, String typeFilter) {
+ return service.getResources(List.of(), List.of(), List.of(typeFilter), null, 0, REGION).items();
+ }
+
+ private static List<String> arns(List<ResourceTagMapping> items) {
+ return items.stream().map(ResourceTagMapping::getResourceArn).toList();
+ }
+
+ private static ExplorerResource resource(String arn, String resourceType, Map<String, String> tags) {
+ String[] parts = arn.split(":", 6);
+ return new ExplorerResource(arn, resourceType, parts[2], parts[3], parts[4], Instant.EPOCH, tags);
+ }
+
+ // IamService reports its region-less ARNs with the region "global".
+ private static ExplorerResource globalRole(Map<String, String> tags) {
+ return new ExplorerResource(ROLE_ARN, "iam:role", "iam", "global", ACCOUNT, Instant.EPOCH, tags);
+ }
+
+ private static ResourceProvider provider(ExplorerResource... resources) {
+ Set<SupportedResourceType> types = new HashSet<>();
+ for (ExplorerResource resource : resources) {
+ types.add(new SupportedResourceType(resource.resourceType(), resource.service(), true));
+ }
+ return new FakeProvider(List.of(resources), types);
+ }
+
+ private static ResourceProvider failingProvider(String service) {
+ return new ResourceProvider() {
+ @Override
+ public List<ExplorerResource> getResources() {
+ throw new IllegalStateException("storage unavailable");
+ }
+
+ @Override
+ public Set<SupportedResourceType> getSupportedResourceTypes() {
+ return Set.of(new SupportedResourceType(service + ":thing", service, true));
+ }
+ };
+ }
+
+ private record FakeProvider(List<ExplorerResource> resources, Set<SupportedResourceType> types)
+ implements ResourceProvider {
+
+ @Override
+ public List<ExplorerResource> getResources() {
+ return resources;
+ }
+
+ @Override
+ public Set<SupportedResourceType> getSupportedResourceTypes() {
+ return types;
+ }
+ }
+
+ private static final class RecordingTagHandler implements TagHandler {
+
+ private final String serviceKey;
+ private final boolean reject;
+ private final Map<String, Map<String, String>> tagged = new LinkedHashMap<>();
+ private final Map<String, List<String>> untagged = new LinkedHashMap<>();
+ private final List<String> regions = new ArrayList<>();
+
+ private RecordingTagHandler(String serviceKey, boolean reject) {
+ this.serviceKey = serviceKey;
+ this.reject = reject;
+ }
+
+ @Override
+ public String serviceKey() {
+ return serviceKey;
+ }
+
+ @Override
+ public Map<String, String> listTags(String region, String arn) {
+ return tagged.getOrDefault(arn, Map.of());
+ }
+
+ @Override
+ public void tagResource(String region, String arn, Map<String, String> tags) {
+ if (reject) {
+ throw new AwsException("NotFoundException", "Invalid resource ARN: " + arn, 404);
+ }
+ regions.add(region);
+ tagged.computeIfAbsent(arn, ignored -> new LinkedHashMap<>()).putAll(tags);
+ }
+
+ @Override
+ public void untagResource(String region, String arn, List<String> tagKeys) {
+ if (reject) {
+ throw new AwsException("NotFoundException", "Invalid resource ARN: " + arn, 404);
+ }
+ regions.add(region);
+ untagged.put(arn, List.copyOf(tagKeys));
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmIntegrationTest.java
index 8660d04ea6..6e8cd7eb09 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmIntegrationTest.java
@@ -1547,6 +1547,30 @@ class SsmIntegrationTest {
.body("__type", equalTo("ValidationException"));
}
+ @Test
+ void addTagsToResourceWithAKeyOutsideTheAwsPatternReturns400BeforeTheLookup() {
+ given()
+ .header("X-Amz-Target", "AmazonSSM.AddTagsToResource")
+ .contentType(SSM_CONTENT_TYPE)
+ .body("""
+ {
+ "ResourceType": "Parameter",
+ "ResourceId": "/demo/no-such-param-for-tag-validation",
+ "Tags": [
+ {"Key": "a,b", "Value": "x"}
+ ]
+ }
+ """)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("__type", equalTo("ValidationException"))
+ .body("message", equalTo("1 validation error detected: Value at 'tags.1.member.key' failed to"
+ + " satisfy constraint: Member must satisfy regular expression pattern:"
+ + " ^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$"));
+ }
+
@Test
@Order(20)
void describeParametersAppliesParameterFilters() {
diff --git a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmServiceTest.java
index 91973f09df..1ce6541a0f 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ssm/SsmServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ssm/SsmServiceTest.java
@@ -17,6 +17,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -136,6 +137,89 @@ class SsmServiceTest {
assertEquals("ParameterNotFound", ex.getErrorCode());
}
+ @Test
+ void addTagsToResource_keyOutsideTheAwsPattern_isRejectedBeforeTheLookup() {
+ AwsException ex = assertThrows(AwsException.class, () ->
+ ssmService.addTagsToResource("/no/such/param", Map.of("a,b", "x"), "eu-west-1"));
+ assertEquals("ValidationException", ex.getErrorCode());
+ assertEquals(400, ex.getHttpStatus());
+ assertEquals("1 validation error detected: Value at 'tags.1.member.key' failed to satisfy constraint: "
+ + "Member must satisfy regular expression pattern: ^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$",
+ ex.getMessage());
+ }
+
+ @Test
+ void addTagsToResource_namesTheOffendingKeyByItsPosition() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/tags/position", "v", "String", null, false, region);
+ Map<String, String> tags = new LinkedHashMap<>();
+ tags.put("ok", "1");
+ tags.put("a,b", "x");
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ ssmService.addTagsToResource("/tags/position", tags, region));
+ assertTrue(ex.getMessage().contains("'tags.2.member.key'"), ex.getMessage());
+ assertTrue(ssmService.listTagsForResource("/tags/position", region).isEmpty());
+ }
+
+ @Test
+ void addTagsToResource_validKeyIsApplied() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/tags/valid", "v", "String", null, false, region);
+
+ ssmService.addTagsToResource("/tags/valid", Map.of("team:name/x=y+z-@_. 1", "v"), region);
+
+ assertEquals(Map.of("team:name/x=y+z-@_. 1", "v"), ssmService.listTagsForResource("/tags/valid", region));
+ }
+
+ @Test
+ void addTagsToResource_emptyKeyIsRejected() {
+ AwsException ex = assertThrows(AwsException.class, () ->
+ ssmService.addTagsToResource("/no/such/param", Map.of("", "x"), "eu-west-1"));
+ assertEquals("ValidationException", ex.getErrorCode());
+ assertEquals("1 validation error detected: Value at 'tags.1.member.key' failed to satisfy constraint: "
+ + "Member must have length greater than or equal to 1", ex.getMessage());
+ }
+
+ @Test
+ void addTagsToResource_keyLongerThan128IsRejected() {
+ AwsException ex = assertThrows(AwsException.class, () ->
+ ssmService.addTagsToResource("/no/such/param", Map.of("k".repeat(129), "x"), "eu-west-1"));
+ assertEquals("ValidationException", ex.getErrorCode());
+ assertEquals("1 validation error detected: Value at 'tags.1.member.key' failed to satisfy constraint: "
+ + "Member must have length less than or equal to 128", ex.getMessage());
+ }
+
+ @Test
+ void addTagsToResource_keyLengthCountsCodePoints() {
+ String region = "eu-west-1";
+ ssmService.putParameter("/tags/code-points", "v", "String", null, false, region);
+ String letter = new String(Character.toChars(0x20000));
+
+ ssmService.addTagsToResource("/tags/code-points", Map.of(letter.repeat(128), "x"), region);
+ AwsException ex = assertThrows(AwsException.class, () ->
+ ssmService.addTagsToResource("/tags/code-points", Map.of(letter.repeat(129), "x"), region));
+
+ assertEquals(Map.of(letter.repeat(128), "x"), ssmService.listTagsForResource("/tags/code-points", region));
+ assertEquals("1 validation error detected: Value at 'tags.1.member.key' failed to satisfy constraint: "
+ + "Member must have length less than or equal to 128", ex.getMessage());
+ }
+
+ @Test
+ void putParameter_invalidTagKeyIsRejectedAndTheParameterIsNotCreated() {
+ String region = "eu-west-1";
+ AwsException ex = assertThrows(AwsException.class, () ->
+ ssmService.putParameter("/tags/rejected", "v", "String", null, false,
+ Map.of("a,b", "x"), region));
+ assertEquals("ValidationException", ex.getErrorCode());
+ assertEquals("1 validation error detected: Value at 'tags.1.member.key' failed to satisfy constraint: "
+ + "Member must satisfy regular expression pattern: ^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$",
+ ex.getMessage());
+ AwsException missing = assertThrows(AwsException.class, () ->
+ ssmService.getParameter("/tags/rejected", region));
+ assertEquals("ParameterNotFound", missing.getErrorCode());
+ }
+
@Test
void getParameters() {
String region = "eu-west-1";