diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml index 993ed75d33..c2b7d5f14e 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -494,6 +494,11 @@ software.amazon.awssdk elasticloadbalancingv2 + + + software.amazon.awssdk + route53resolver + software.amazon.awssdk diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index 3edbd7f0af..d105073b2c 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -121,6 +121,7 @@ import software.amazon.awssdk.services.route53.model.CreateHostedZoneResponse; import software.amazon.awssdk.services.route53.model.RRType; import software.amazon.awssdk.services.route53.model.ResourceRecord; import software.amazon.awssdk.services.route53.model.ResourceRecordSet; +import software.amazon.awssdk.services.route53resolver.Route53ResolverClient; import software.amazon.awssdk.services.rum.RumClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; @@ -1647,6 +1648,14 @@ public final class TestFixtures { .build(); } + public static Route53ResolverClient route53ResolverClient() { + return Route53ResolverClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + .build(); + } + public static GlobalAcceleratorClient globalAcceleratorClient() { return GlobalAcceleratorClient.builder() .endpointOverride(ENDPOINT) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Route53ResolverTaggingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Route53ResolverTaggingTest.java new file mode 100644 index 0000000000..026577cdc5 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Route53ResolverTaggingTest.java @@ -0,0 +1,103 @@ +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.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import software.amazon.awssdk.services.route53resolver.Route53ResolverClient; +import software.amazon.awssdk.services.route53resolver.model.IpAddressRequest; +import software.amazon.awssdk.services.route53resolver.model.ResolverEndpoint; +import software.amazon.awssdk.services.route53resolver.model.ResolverEndpointDirection; +import software.amazon.awssdk.services.route53resolver.model.ResourceNotFoundException; +import software.amazon.awssdk.services.route53resolver.model.Tag; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("Route 53 Resolver tagging") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class Route53ResolverTaggingTest { + + private static Route53ResolverClient resolver; + private static String endpointId; + private static String endpointArn; + + @BeforeAll + static void setup() { + resolver = TestFixtures.route53ResolverClient(); + } + + @AfterAll + static void cleanup() { + if (resolver == null) { + return; + } + if (endpointId != null) { + try { + resolver.deleteResolverEndpoint(r -> r.resolverEndpointId(endpointId)); + } catch (RuntimeException e) { + System.out.println("Route 53 Resolver cleanup skipped: " + e.getMessage()); + } + } + resolver.close(); + } + + private static Map tags() { + return resolver.listTagsForResource(r -> r.resourceArn(endpointArn)).tags().stream() + .collect(Collectors.toMap(Tag::key, Tag::value)); + } + + @Test + @Order(1) + void createWithTags() { + ResolverEndpoint endpoint = + resolver.createResolverEndpoint(r -> r + .name("sdk-tagging-" + System.currentTimeMillis()) + .creatorRequestId("sdk-tagging-" + System.nanoTime()) + .direction(ResolverEndpointDirection.OUTBOUND) + .securityGroupIds("sg-12345678") + .ipAddresses(IpAddressRequest.builder().subnetId("subnet-aaaa1111").build(), + IpAddressRequest.builder().subnetId("subnet-bbbb2222").build()) + .tags(Tag.builder().key("env").value("dev").build())) + .resolverEndpoint(); + endpointId = endpoint.id(); + endpointArn = endpoint.arn(); + + assertThat(tags()).containsExactly(Map.entry("env", "dev")); + } + + @Test + @Order(2) + void tagResource() { + resolver.tagResource(r -> r.resourceArn(endpointArn).tags( + Tag.builder().key("env").value("prod").build(), + Tag.builder().key("team").value("net").build())); + + assertThat(tags()).containsOnly(Map.entry("env", "prod"), Map.entry("team", "net")); + } + + @Test + @Order(3) + void untagResource() { + resolver.untagResource(r -> r.resourceArn(endpointArn).tagKeys(List.of("env"))); + + assertThat(tags()).containsOnly(Map.entry("team", "net")); + } + + @Test + @Order(4) + void deletedResourceHasNoTags() { + resolver.deleteResolverEndpoint(r -> r.resolverEndpointId(endpointId)); + endpointId = null; + + assertThatThrownBy(() -> resolver.listTagsForResource(r -> r.resourceArn(endpointArn))) + .isInstanceOf(ResourceNotFoundException.class); + } +} diff --git a/docs/services/index.md b/docs/services/index.md index da090da878..f43a5576b6 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -125,7 +125,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package`, `/v1/package/version*`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 32 | | [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*` | REST XML | 50 | | [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*` | REST XML | 27 | -| [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 19 | +| [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 22 | | [Amazon SageMaker](sagemaker.md) | `POST /` + `X-Amz-Target: SageMaker.*` | JSON 1.1 | 20 | | [SageMaker Runtime](sagemaker.md#endpoint-hosting) | `/endpoints/{EndpointName}/invocations` | REST (binary payload) | 1 | | [Cloud Map](cloudmap.md) | `POST /` + `X-Amz-Target: Route53AutoNaming_v20170314.*` | JSON 1.1 | 22 | diff --git a/docs/services/route53resolver.md b/docs/services/route53resolver.md index 642146c206..352e0720ce 100644 --- a/docs/services/route53resolver.md +++ b/docs/services/route53resolver.md @@ -24,6 +24,9 @@ | `DisassociateResolverRule` | Removes the association between a resolver rule and a VPC. | | `GetResolverRuleAssociation` | Returns a resolver rule association by id. | | `ListResolverRuleAssociations` | Lists all resolver rule associations. | +| `TagResource` | Adds or overwrites tags on a resolver endpoint, resolver rule or custom firewall domain list, by ARN. | +| `UntagResource` | Removes tag keys from a resolver endpoint, resolver rule or custom firewall domain list; absent keys are ignored. | +| `ListTagsForResource` | Lists a resource's tags, paginated by `MaxResults` (default and maximum 100) and `NextToken`. | ## Design notes @@ -161,3 +164,14 @@ cluster DNS does, governed by `floci.services.eks.embedded-dns`. it through RAM; Floci reports every rule as `NOT_SHARED` and models no rule policy, so a rule and its associations always live in one account and resolution only ever consults that account's own. - **DNS Firewall rule groups, query logging and DNSSEC validation do not affect resolution.** + +Tags passed to `CreateResolverEndpoint`, `CreateResolverRule` and `CreateFirewallDomainList` +are stored and read back through `ListTagsForResource`; they never appear on the resource +shapes, which model no `Tags` member. Tagging is keyed by the full ARN: an ARN naming another +account, region or partition is `ResourceNotFoundException` even when its id matches a local +resource. Rule associations carry no ARN and the AWS-managed firewall domain lists are not +stored, so neither is taggable here. A tag outside the modelled `Tag` shape (key 1-128 +characters, value 0-256) is `InvalidTagException` on `TagResource`, and the create +operation's own parameter error on create. A request carrying more than the modelled 200 +tags or tag keys is `InvalidParameterException` (`ValidationException` on +`CreateFirewallDomainList`). A per-resource total is not modelled, so none is enforced. diff --git a/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverJsonHandler.java index ed386e291c..22cd3b17c7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverJsonHandler.java @@ -73,6 +73,18 @@ public class Route53ResolverJsonHandler { service.getResolverRuleAssociation(text(request, "ResolverRuleAssociationId"))); case "ListResolverRuleAssociations" -> handleListResolverRuleAssociations(); + case "TagResource" -> { + service.tagResource(text(request, "ResourceArn"), request.get("Tags"), region, accountId); + yield Response.ok(objectMapper.createObjectNode()).build(); + } + case "UntagResource" -> { + service.untagResource(text(request, "ResourceArn"), request.get("TagKeys"), region, accountId); + yield Response.ok(objectMapper.createObjectNode()).build(); + } + case "ListTagsForResource" -> Response.ok(service.listTagsForResource( + text(request, "ResourceArn"), request.get("MaxResults"), + text(request, "NextToken"), region, accountId)).build(); + default -> Response.status(400) .entity(new AwsErrorResponse("UnknownOperationException", "Unknown operation: Route53Resolver." + action)) diff --git a/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java index 29213c2a7d..6ea8aca96d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java +++ b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java @@ -9,6 +9,8 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.Digests; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; @@ -23,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.function.Predicate; /** * Route 53 Resolver: DNS Firewall (managed + custom domain lists), resolver @@ -86,6 +89,12 @@ public class Route53ResolverService { * wire. Read by the CreatorRequestId conflict check and ListResolverEndpointIpAddresses. */ private final StorageBackend endpointIpRequestStore; + /** + * Tags keyed by resource ARN, each an object of key to value. Kept apart from the resources + * for the same reason as {@link #endpointIpRequestStore}: none of the modeled resource + * shapes carries {@code Tags}, and the handlers return stored nodes verbatim. + */ + private final StorageBackend tagStore; private final ObjectMapper objectMapper; @Inject @@ -101,6 +110,8 @@ public class Route53ResolverService { this.endpointIpRequestStore = storageFactory.create("route53resolver", "route53resolver-endpoint-ip-requests.json", new TypeReference>() {}); + this.tagStore = storageFactory.create("route53resolver", "route53resolver-tags.json", + new TypeReference>() {}); this.objectMapper = objectMapper; } @@ -112,12 +123,14 @@ public class Route53ResolverService { StorageBackend ruleStore, StorageBackend ruleAssociationStore, StorageBackend endpointIpRequestStore, + StorageBackend tagStore, ObjectMapper objectMapper) { this.domainListStore = domainListStore; this.endpointStore = endpointStore; this.ruleStore = ruleStore; this.ruleAssociationStore = ruleAssociationStore; this.endpointIpRequestStore = endpointIpRequestStore; + this.tagStore = tagStore; this.objectMapper = objectMapper; } @@ -140,6 +153,7 @@ public class Route53ResolverService { public synchronized ObjectNode createFirewallDomainList(JsonNode request, String region, String accountId) { String name = requireText(request, "Name", VALIDATION); + JsonNode tags = validatedTags(request.get("Tags"), VALIDATION); Optional replay = replayOf(domainListStore, request, region); if (replay.isPresent()) { return replay.get(); @@ -156,12 +170,14 @@ public class Route53ResolverService { list.put("CreationTime", Instant.now().toString()); list.put("ModificationTime", Instant.now().toString()); domainListStore.put(id, list); + putTags(list, tags); return list.deepCopy(); } public ObjectNode deleteFirewallDomainList(String id) { ObjectNode list = require(domainListStore, id, "firewall domain list"); domainListStore.delete(id); + tagStore.delete(text(list, "Arn")); ObjectNode result = list.deepCopy(); result.put("Status", "DELETING"); return result; @@ -182,6 +198,7 @@ public class Route53ResolverService { String direction = requireText(request, "Direction", INVALID_PARAMETER); String idPrefix = endpointIdPrefix(direction); JsonNode ipAddresses = ipAddressesOf(request); + JsonNode tags = validatedTags(request.get("Tags"), INVALID_PARAMETER); if (!ipAddresses.isArray() || ipAddresses.isEmpty()) { throw new AwsException(INVALID_PARAMETER, "IpAddresses is required", 400); } @@ -219,6 +236,7 @@ public class Route53ResolverService { endpointStore.put(id, endpoint); endpointIpRequestStore.put(id, objectMapper.createObjectNode().set("IpAddressRequests", normalizedIpRequests(ipAddresses))); + putTags(endpoint, tags); return endpoint.deepCopy(); } @@ -226,6 +244,7 @@ public class Route53ResolverService { ObjectNode endpoint = require(endpointStore, id, "resolver endpoint"); endpointStore.delete(id); endpointIpRequestStore.delete(id); + tagStore.delete(text(endpoint, "Arn")); ObjectNode result = endpoint.deepCopy(); result.put("Status", "DELETING"); return result; @@ -297,6 +316,7 @@ public class Route53ResolverService { "TargetIps must contain at least one target address.", 400); } String domainName = text(request, "DomainName"); + JsonNode tags = validatedTags(request.get("Tags"), INVALID_PARAMETER); Optional replay = replayOf(ruleStore, request, region); if (replay.isPresent()) { requireReplayMatches(replay.get(), request, @@ -319,12 +339,14 @@ public class Route53ResolverService { rule.put("CreationTime", Instant.now().toString()); rule.put("ModificationTime", Instant.now().toString()); ruleStore.put(id, rule); + putTags(rule, tags); return rule.deepCopy(); } public ObjectNode deleteResolverRule(String id) { ObjectNode rule = require(ruleStore, id, "resolver rule"); ruleStore.delete(id); + tagStore.delete(text(rule, "Arn")); ObjectNode result = rule.deepCopy(); result.put("Status", "DELETING"); return result; @@ -454,6 +476,174 @@ public class Route53ResolverService { return ruleStore.get(ruleId); } + // ---------- Tagging ---------- + + public synchronized void tagResource(String arn, JsonNode tags, String region, String accountId) { + if (tags == null || tags.isNull()) { + throw new AwsException(INVALID_PARAMETER, "Tags is required", 400); + } + requireAtMostPerRequest(tags, "Tags", INVALID_PARAMETER); + JsonNode validated = validatedTags(tags, "InvalidTagException"); + putTags(requireTaggable(arn, region, accountId), validated); + } + + public synchronized void untagResource(String arn, JsonNode tagKeys, String region, String accountId) { + if (tagKeys == null || !tagKeys.isArray()) { + throw new AwsException(INVALID_PARAMETER, "TagKeys is required", 400); + } + requireAtMostPerRequest(tagKeys, "TagKeys", INVALID_PARAMETER); + for (JsonNode key : tagKeys) { + if (!key.isTextual()) { + throw new AwsException(INVALID_PARAMETER, "TagKeys must be a list of strings", 400); + } + } + requireTaggable(arn, region, accountId); + ObjectNode stored = tagStore.get(arn).orElse(null); + if (stored == null) { + return; + } + tagKeys.forEach(key -> stored.remove(key.asText())); + tagStore.put(arn, stored); + } + + /** + * One page of a resource's tags as modeled {@code Tag} entries, paged by + * {@link Pagination#paginate} on the tag key; {@code MaxResults} defaults to the modeled 100. + * {@code MaxResults} arrives as a JSON value, so it is type-checked here rather than parsed + * from a string: {@code 1.5}, {@code true} and {@code "1"} are not the modeled integer. + * + *

The stored tag node is copied under the monitor {@link #tagResource} and + * {@link #untagResource} mutate it under, so a concurrent tag change can neither break the + * iteration nor show a half-applied page.

+ */ + public ObjectNode listTagsForResource(String arn, JsonNode maxResults, String nextToken, + String region, String accountId) { + boolean absent = maxResults == null || maxResults.isNull(); + if (!absent && (!maxResults.isIntegralNumber() || !maxResults.canConvertToInt() + || maxResults.intValue() < 1 || maxResults.intValue() > 100)) { + throw new AwsException(INVALID_PARAMETER, "MaxResults must be an integer between 1 and 100", 400); + } + ObjectNode snapshot; + synchronized (this) { + requireTaggable(arn, region, accountId); + snapshot = tagStore.get(arn).map(ObjectNode::deepCopy).orElse(null); + } + List> all = new ArrayList<>(); + if (snapshot != null) { + snapshot.fields().forEachRemaining(all::add); + } + PaginatedResult> paged = Pagination.paginate(all, Map.Entry::getKey, + absent ? 100 : maxResults.intValue(), nextToken, "tags", + token -> new AwsException("InvalidNextTokenException", "Invalid NextToken: " + token, 400)); + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode page = result.putArray("Tags"); + for (Map.Entry tag : paged.items()) { + page.addObject().put("Key", tag.getKey()).set("Value", tag.getValue()); + } + if (paged.nextToken() != null) { + result.put("NextToken", paged.nextToken()); + } + return result; + } + + /** + * The stored resource an ARN names. The ARN must name the caller's own partition, region and + * account before anything is read, the id is looked up in the caller's account partition, + * and the stored resource's ARN must match the request exactly; anything else is not found + * rather than resolved to a resource that happens to share its id. A pre-multi-account + * (unprefixed) entry is migrated into the caller's partition only once its own ARN proves + * the caller owns it, so another account cannot claim it by naming its ARN. AWS-managed + * firewall domain lists are not stored and so are not taggable here. + */ + private ObjectNode requireTaggable(String arn, String region, String accountId) { + if (arn == null || arn.isBlank()) { + throw new AwsException(INVALID_PARAMETER, "ResourceArn is required", 400); + } + String callerPrefix = "arn:" + AwsRegions.partitionFor(region) + ":route53resolver:" + region + ":" + + accountId + ":"; + String resource = arn.startsWith(callerPrefix) + ? AwsArnUtils.resourceIfArnFor(arn, "route53resolver").orElse("") : ""; + int slash = resource.indexOf('/'); + StorageBackend store = slash < 0 ? null : switch (resource.substring(0, slash)) { + case "resolver-endpoint" -> endpointStore; + case "resolver-rule" -> ruleStore; + case "firewall-domain-list" -> domainListStore; + default -> null; + }; + return Optional.ofNullable(store) + .flatMap(s -> ownedBy(s, accountId, resource.substring(slash + 1), + stored -> arn.equals(text(stored, "Arn")))) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Resource not found: " + arn, 400)); + } + + /** + * The caller's resource by id. Unlike {@link StorageBackend#get}, which migrates an unprefixed + * legacy entry into whichever account reads it first, a legacy entry moves only when + * {@code owner} accepts it. + */ + private static Optional ownedBy(StorageBackend store, String accountId, + String id, Predicate owner) { + if (store instanceof AccountAwareStorageBackend rawAccountAware) { + @SuppressWarnings("unchecked") + AccountAwareStorageBackend accountAware = + (AccountAwareStorageBackend) rawAccountAware; + return accountAware.getForAccountMigratingLegacy(accountId, id, owner); + } + return store.get(id).filter(owner); + } + + /** + * Checks a modeled {@code TagList}: each {@code Tag} requires {@code Key} (1-128 chars) and + * {@code Value} (0-256 chars). Returns {@code null} for an absent list. Called before a + * create allocates anything, so an invalid tag never leaves a resource behind. + * + *

{@code InvalidTagException} is modeled only on {@code TagResource}; the create + * operations reject with their own parameter error (see {@link #INVALID_PARAMETER}).

+ */ + private JsonNode validatedTags(JsonNode tags, String errorCode) { + if (tags == null || tags.isNull()) { + return null; + } + if (!tags.isArray()) { + throw new AwsException(errorCode, "Tags must be a list", 400); + } + requireAtMostPerRequest(tags, "Tags", errorCode); + for (JsonNode tag : tags) { + if (!tag.path("Key").isTextual() || !tag.path("Value").isTextual()) { + throw new AwsException(errorCode, "Each tag needs a string Key and a string Value.", 400); + } + String key = text(tag, "Key"); + String value = text(tag, "Value"); + if (key == null || key.isEmpty() || key.length() > 128 || value == null || value.length() > 256) { + throw new AwsException(errorCode, + "Each tag needs a Key of 1-128 characters and a Value of at most 256 characters.", 400); + } + } + return tags; + } + + /** + * The model caps {@code TagList} and {@code TagKeyList} at 200 entries per request. That is + * the only tag-count limit the model states; a per-resource total is not modeled, so none + * is enforced. + */ + private static void requireAtMostPerRequest(JsonNode list, String name, String errorCode) { + if (list.isArray() && list.size() > 200) { + throw new AwsException(errorCode, name + " must contain at most 200 entries", 400); + } + } + + private void putTags(ObjectNode resource, JsonNode tags) { + if (tags == null || tags.isEmpty()) { + return; + } + String arn = text(resource, "Arn"); + ObjectNode stored = tagStore.get(arn).orElseGet(objectMapper::createObjectNode); + tags.forEach(tag -> stored.put(text(tag, "Key"), text(tag, "Value"))); + tagStore.put(arn, stored); + } + /** * AWS gives a resolver endpoint a direction-specific id prefix: {@code rslvr-in-} for * inbound endpoints, {@code rslvr-out-} for outbound. {@code INBOUND_DELEGATION} is an diff --git a/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverReplayFallbackTest.java b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverReplayFallbackTest.java index 047bd7e819..097875f521 100644 --- a/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverReplayFallbackTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverReplayFallbackTest.java @@ -37,7 +37,8 @@ class Route53ResolverReplayFallbackTest { void setUp() { endpointIpRequests = new InMemoryStorage<>(); service = new Route53ResolverService(new InMemoryStorage<>(), new InMemoryStorage<>(), - new InMemoryStorage<>(), new InMemoryStorage<>(), endpointIpRequests, objectMapper); + new InMemoryStorage<>(), new InMemoryStorage<>(), endpointIpRequests, new InMemoryStorage<>(), + objectMapper); } private JsonNode createRequest(String token, String ip) { diff --git a/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverTaggingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverTaggingIntegrationTest.java new file mode 100644 index 0000000000..84242490ae --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverTaggingIntegrationTest.java @@ -0,0 +1,276 @@ +package io.github.hectorvent.floci.services.route53resolver; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +/** + * TagResource / UntagResource / ListTagsForResource for the Route 53 Resolver resources Floci + * stores: resolver endpoints, resolver rules and custom firewall domain lists. Tags given to + * a Create call must be readable back through ListTagsForResource, which is how the Terraform + * provider reads them after every create. + */ +@QuarkusTest +class Route53ResolverTaggingIntegrationTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/route53resolver/aws4_request"; + private static final String OTHER_ACCOUNT_AUTH = + "AWS4-HMAC-SHA256 Credential=000000000077/20260101/us-east-1/route53resolver/aws4_request"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static ValidatableResponse call(String action, String body) { + return call(AUTH_HEADER, action, body); + } + + private static ValidatableResponse call(String auth, String action, String body) { + return given() + .contentType(CONTENT_TYPE) + .header("X-Amz-Target", "Route53Resolver." + action) + .header("Authorization", auth) + .body(body) + .when() + .post("/") + .then(); + } + + private static String createEndpoint(String tagsJson) { + return call("CreateResolverEndpoint", """ + {"Name":"tagged","Direction":"OUTBOUND","SecurityGroupIds":["sg-1"], + "IpAddresses":[{"SubnetId":"subnet-a"},{"SubnetId":"subnet-b"}], + "Tags":%s}""".formatted(tagsJson)) + .statusCode(200) + .extract().path("ResolverEndpoint.Arn"); + } + + private static ValidatableResponse listTags(String arn) { + return call("ListTagsForResource", "{\"ResourceArn\":\"" + arn + "\"}"); + } + + @Test + void createResolverEndpoint_tagsAreListed_andNotOnTheEndpointShape() { + String arn = createEndpoint("[{\"Key\":\"env\",\"Value\":\"dev\"},{\"Key\":\"team\",\"Value\":\"net\"}]"); + + listTags(arn) + .statusCode(200) + .body("Tags.Key", containsInAnyOrder("env", "team")) + .body("Tags.find { it.Key == 'env' }.Value", equalTo("dev")); + + String id = arn.substring(arn.lastIndexOf('/') + 1); + call("GetResolverEndpoint", "{\"ResolverEndpointId\":\"" + id + "\"}") + .statusCode(200) + .body("ResolverEndpoint.Tags", nullValue()); + } + + @Test + void tagUntagLifecycle_onResolverEndpoint() { + String arn = createEndpoint("[]"); + listTags(arn).statusCode(200).body("Tags", empty()); + + call("TagResource", """ + {"ResourceArn":"%s","Tags":[{"Key":"a","Value":"1"},{"Key":"b","Value":"2"}]}""".formatted(arn)) + .statusCode(200); + call("TagResource", """ + {"ResourceArn":"%s","Tags":[{"Key":"a","Value":"changed"}]}""".formatted(arn)) + .statusCode(200); + listTags(arn) + .statusCode(200) + .body("Tags", hasSize(2)) + .body("Tags.find { it.Key == 'a' }.Value", equalTo("changed")); + + call("UntagResource", "{\"ResourceArn\":\"" + arn + "\",\"TagKeys\":[\"a\",\"absent\"]}") + .statusCode(200); + listTags(arn) + .statusCode(200) + .body("Tags.Key", containsInAnyOrder("b")); + } + + @Test + void resolverRule_isTaggable() { + String arn = call("CreateResolverRule", """ + {"Name":"r","RuleType":"FORWARD","DomainName":"example.com", + "TargetIps":[{"Ip":"10.0.0.2","Port":53}], + "Tags":[{"Key":"k","Value":"v"}]}""") + .statusCode(200) + .extract().path("ResolverRule.Arn"); + + listTags(arn).statusCode(200).body("Tags.Key", containsInAnyOrder("k")); + call("TagResource", "{\"ResourceArn\":\"" + arn + "\",\"Tags\":[{\"Key\":\"k2\",\"Value\":\"\"}]}") + .statusCode(200); + listTags(arn).statusCode(200).body("Tags.Key", containsInAnyOrder("k", "k2")); + } + + @Test + void firewallDomainList_isTaggable() { + String arn = call("CreateFirewallDomainList", """ + {"Name":"fdl","Tags":[{"Key":"k","Value":"v"}]}""") + .statusCode(200) + .extract().path("FirewallDomainList.Arn"); + + listTags(arn).statusCode(200).body("Tags.Key", containsInAnyOrder("k")); + } + + @Test + void listTags_pagesWithMaxResults() { + String arn = createEndpoint("[{\"Key\":\"a\",\"Value\":\"1\"},{\"Key\":\"b\",\"Value\":\"2\"}]"); + + String token = call("ListTagsForResource", "{\"ResourceArn\":\"" + arn + "\",\"MaxResults\":1}") + .statusCode(200) + .body("Tags", hasSize(1)) + .body("NextToken", notNullValue()) + .extract().path("NextToken"); + call("ListTagsForResource", + "{\"ResourceArn\":\"" + arn + "\",\"MaxResults\":1,\"NextToken\":\"" + token + "\"}") + .statusCode(200) + .body("Tags", hasSize(1)) + .body("NextToken", nullValue()); + + for (String malformed : new String[] {"1.5", "true", "\"1\"", "0", "101"}) { + call("ListTagsForResource", "{\"ResourceArn\":\"" + arn + "\",\"MaxResults\":" + malformed + "}") + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + } + + // The token is an opaque cursor, not an offset a caller can forge. + for (String forged : new String[] {"bogus", "1", "0"}) { + call("ListTagsForResource", "{\"ResourceArn\":\"" + arn + "\",\"NextToken\":\"" + forged + "\"}") + .statusCode(400) + .body("__type", equalTo("InvalidNextTokenException")); + } + } + + @Test + void tagListsAreCappedAt200EntriesPerRequest() { + String arn = createEndpoint("[]"); + call("TagResource", "{\"ResourceArn\":\"" + arn + "\",\"Tags\":" + tags(200) + "}").statusCode(200); + call("TagResource", "{\"ResourceArn\":\"" + arn + "\",\"Tags\":" + tags(201) + "}") + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + call("UntagResource", "{\"ResourceArn\":\"" + arn + "\",\"TagKeys\":" + keys(201) + "}") + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + listTags(arn).statusCode(200).body("Tags", hasSize(100)); + call("UntagResource", "{\"ResourceArn\":\"" + arn + "\",\"TagKeys\":" + keys(200) + "}").statusCode(200); + listTags(arn).statusCode(200).body("Tags", empty()); + + createEndpoint(tags(200)); + call("CreateResolverEndpoint", """ + {"Name":"over","Direction":"OUTBOUND","SecurityGroupIds":["sg-1"], + "IpAddresses":[{"SubnetId":"subnet-a"},{"SubnetId":"subnet-b"}],"Tags":%s}""".formatted(tags(201))) + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + call("CreateResolverRule", """ + {"Name":"ok","RuleType":"SYSTEM","DomainName":"ok.example","Tags":%s}""".formatted(tags(200))) + .statusCode(200); + call("CreateResolverRule", """ + {"Name":"over","RuleType":"SYSTEM","DomainName":"over.example","Tags":%s}""".formatted(tags(201))) + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + call("CreateFirewallDomainList", "{\"Name\":\"ok\",\"Tags\":" + tags(200) + "}").statusCode(200); + call("CreateFirewallDomainList", "{\"Name\":\"over\",\"Tags\":" + tags(201) + "}") + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + private static String tags(int n) { + return IntStream.range(0, n).mapToObj(i -> "{\"Key\":\"k" + i + "\",\"Value\":\"v\"}") + .collect(Collectors.joining(",", "[", "]")); + } + + private static String keys(int n) { + return IntStream.range(0, n).mapToObj(i -> "\"k" + i + "\"").collect(Collectors.joining(",", "[", "]")); + } + + @Test + void unknownOrDeletedResource_isResourceNotFound() { + listTags("arn:aws:route53resolver:us-east-1:000000000000:resolver-endpoint/rslvr-out-doesnotexist1") + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + + String arn = createEndpoint("[{\"Key\":\"a\",\"Value\":\"1\"}]"); + String id = arn.substring(arn.lastIndexOf('/') + 1); + call("DeleteResolverEndpoint", "{\"ResolverEndpointId\":\"" + id + "\"}").statusCode(200); + listTags(arn) + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + call("TagResource", "{\"ResourceArn\":\"" + arn + "\",\"Tags\":[{\"Key\":\"a\",\"Value\":\"1\"}]}") + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + } + + @Test + void arnNamingAnotherRegionOrAccount_isResourceNotFound() { + String arn = createEndpoint("[{\"Key\":\"a\",\"Value\":\"1\"}]"); + + listTags(arn.replace(":us-east-1:", ":us-west-2:")) + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + listTags(arn.replace(":000000000000:", ":000000000077:")) + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + listTags(arn.replace("arn:aws:", "arn:aws-cn:")) + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + // Another account cannot read or write this account's resource by its exact ARN. + call(OTHER_ACCOUNT_AUTH, "ListTagsForResource", "{\"ResourceArn\":\"" + arn + "\"}") + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + call(OTHER_ACCOUNT_AUTH, "UntagResource", "{\"ResourceArn\":\"" + arn + "\",\"TagKeys\":[\"a\"]}") + .statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + listTags(arn).statusCode(200).body("Tags.Key", containsInAnyOrder("a")); + } + + @Test + void invalidTags_areRejected_andCreateWithInvalidTagStoresNothing() { + String arn = createEndpoint("[]"); + call("TagResource", "{\"ResourceArn\":\"" + arn + "\",\"Tags\":[{\"Key\":\"\",\"Value\":\"v\"}]}") + .statusCode(400) + .body("__type", equalTo("InvalidTagException")); + call("TagResource", "{\"ResourceArn\":\"" + arn + "\",\"Tags\":[{\"Key\":\"k\"}]}") + .statusCode(400) + .body("__type", equalTo("InvalidTagException")); + for (String malformed : new String[] { + "{\"Key\":123,\"Value\":\"v\"}", "{\"Key\":\"k\",\"Value\":true}", + "{\"Key\":\"k\",\"Value\":{\"x\":1}}", "{\"Key\":[\"k\"],\"Value\":\"v\"}"}) { + call("TagResource", "{\"ResourceArn\":\"" + arn + "\",\"Tags\":[" + malformed + "]}") + .statusCode(400) + .body("__type", equalTo("InvalidTagException")); + } + call("UntagResource", "{\"ResourceArn\":\"" + arn + "\",\"TagKeys\":[123]}") + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + call("TagResource", "{\"ResourceArn\":\"" + arn + "\"}") + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + call("UntagResource", "{\"ResourceArn\":\"" + arn + "\"}") + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + listTags(arn).statusCode(200).body("Tags", empty()); + + int before = call("ListResolverRules", "{}").statusCode(200).extract().path("ResolverRules.size()"); + call("CreateResolverRule", """ + {"Name":"bad","RuleType":"SYSTEM","DomainName":"bad.example","Tags":[{"Key":"","Value":"v"}]}""") + .statusCode(400) + .body("__type", equalTo("InvalidParameterException")); + call("ListResolverRules", "{}").statusCode(200).body("ResolverRules", hasSize(before)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverTaggingStorageTest.java b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverTaggingStorageTest.java new file mode 100644 index 0000000000..27f4e5fb45 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverTaggingStorageTest.java @@ -0,0 +1,105 @@ +package io.github.hectorvent.floci.services.route53resolver; + +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.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import org.junit.jupiter.api.Test; + +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tagging behaviour that depends on storage state the public API cannot produce: a + * pre-multi-account (unprefixed) resource entry, and reads of the shared tag store. + */ +class Route53ResolverTaggingStorageTest { + + private static final String REGION = "us-east-1"; + private static final String DEFAULT_ACCOUNT = "000000000000"; + private static final String OWNER = "111111111111"; + private static final String OTHER = "222222222222"; + private static final String ID = "rslvr-out-legacy0000001"; + private static final String ARN = + "arn:aws:route53resolver:us-east-1:" + OWNER + ":resolver-endpoint/" + ID; + + private final ObjectMapper objectMapper = new ObjectMapper(); + + private Route53ResolverService service(InMemoryStorage endpointDelegate, + InMemoryStorage tagStore) { + return new Route53ResolverService(new InMemoryStorage<>(), + new AccountAwareStorageBackend<>(endpointDelegate, null, DEFAULT_ACCOUNT), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), tagStore, + objectMapper); + } + + private InMemoryStorage legacyEndpointStore() { + InMemoryStorage delegate = new InMemoryStorage<>(); + delegate.put(ID, objectMapper.createObjectNode().put("Id", ID).put("Arn", ARN)); + return delegate; + } + + private ArrayNode tags(String key, String value) { + ArrayNode tags = objectMapper.createArrayNode(); + tags.addObject().put("Key", key).put("Value", value); + return tags; + } + + @Test + void legacyResource_isNotClaimedByAnotherAccountNamingItsArn() { + InMemoryStorage delegate = legacyEndpointStore(); + Route53ResolverService service = service(delegate, new InMemoryStorage<>()); + + AwsException tag = assertThrows(AwsException.class, + () -> service.tagResource(ARN, tags("k", "v"), REGION, OTHER)); + assertEquals("ResourceNotFoundException", tag.getErrorCode()); + AwsException list = assertThrows(AwsException.class, + () -> service.listTagsForResource(ARN, null, null, REGION, OTHER)); + assertEquals("ResourceNotFoundException", list.getErrorCode()); + // Naming the same id under its own account must not drag the legacy entry over either. + AwsException ownArn = assertThrows(AwsException.class, + () -> service.listTagsForResource(ARN.replace(OWNER, OTHER), null, null, REGION, OTHER)); + assertEquals("ResourceNotFoundException", ownArn.getErrorCode()); + + // The legacy entry stays where it was; no other account's partition gained it. + assertTrue(delegate.get(ID).isPresent()); + assertEquals(1, delegate.keys().size(), delegate.keys().toString()); + + // Its real owner can still tag it, which migrates it into the owner's partition. + service.tagResource(ARN, tags("k", "v"), REGION, OWNER); + assertEquals("v", service.listTagsForResource(ARN, null, null, REGION, OWNER) + .path("Tags").path(0).path("Value").asText()); + assertTrue(delegate.get(OWNER + "/" + ID).isPresent()); + assertFalse(delegate.get(ID).isPresent()); + } + + @Test + void listTags_readsTheTagStoreUnderTheMutatorsMonitor() { + AtomicReference self = new AtomicReference<>(); + AtomicBoolean unlockedRead = new AtomicBoolean(); + InMemoryStorage tagStore = new InMemoryStorage<>() { + @Override + public Optional get(String key) { + if (!Thread.holdsLock(self.get())) { + unlockedRead.set(true); + } + return super.get(key); + } + }; + Route53ResolverService service = service(legacyEndpointStore(), tagStore); + self.set(service); + + service.tagResource(ARN, tags("k", "v"), REGION, OWNER); + service.listTagsForResource(ARN, null, null, REGION, OWNER); + + assertFalse(unlockedRead.get(), "ListTagsForResource read the live tag node outside the monitor"); + } +}