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");
+ }
+}