diff --git a/docs/services/iam.md b/docs/services/iam.md index 7379f87f39..dfa678da20 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3119,10 +3119,11 @@ floci populates: reads from the Service Reference for every namespace it reads, valued from the tags the type's service holds on that resource (`StoredResourceArns.storedTags`); a service that holds none leaves them absent. Secrets Manager answers for its secrets, S3 Tables for its table buckets and tables, EventBridge Scheduler for - its schedule groups, CloudFormation for its stacks, stack sets and change sets, and Lambda for its functions, + its schedule groups, CloudFormation for its stacks, stack sets and change sets, Lambda for its functions, their versions and aliases (the function's tags), event source mappings, web functions, their revisions and - endpoints (the web function's tags), MicroVM images and network connectors. Tag keys differing only in case are - one condition key holding every value. + endpoints (the web function's tags), MicroVM images and network connectors, and Glue for its schema registries + and schemas and for the jobs, crawlers, triggers, workflows, connections, databases, tables and other resources + it tags. Tag keys differing only in case are one condition key holding every value. - EC2 resource keys such as a network interface's `ec2:Vpc`, `ec2:Subnet`, `ec2:AvailabilityZone` and `ec2:NetworkInterfaceID`: for every action on a resource EC2 holds, the members of the resource the key names, an ARN for a key the Service Reference types as one. `resourceKeys` in diff --git a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java index 6021bbeef6..1867ebc4c6 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -30,9 +30,9 @@ import java.util.Optional; * or a change set; S3 Tables, for the table a request names by its table bucket, namespace and name, and the tags of a * table bucket or a table; Lambda, for the layer version a layer version ARN selects, the image of a MicroVM and the * execution of a callback, and the tags of a function, an event source mapping, a web function, a MicroVM image or a - * network connector); looked up lazily by {@code ResourceArnBuilder} and {@code IamConditionContextResolver} - * through {@code Instance} for the namespace a request or an ARN is of, so IAM never depends on - * that service directly.

+ * network connector; Glue, for the tags of a resource it tags); looked up lazily by {@code ResourceArnBuilder} and + * {@code IamConditionContextResolver} through {@code Instance} for the namespace a request or an + * ARN is of, so IAM never depends on that service directly.

* *

Each answer is a lookup of what the service holds, asked for by an entry of the generated table ({@code find}, * {@code through}, a default, {@code forwarded}, a type's {@code resourceTagKeys}): never a fact about what an operation acts on, which the table alone diff --git a/src/main/java/io/floci/aws/services/glue/GlueService.java b/src/main/java/io/floci/aws/services/glue/GlueService.java index b93e38da43..2e25aabfe2 100644 --- a/src/main/java/io/floci/aws/services/glue/GlueService.java +++ b/src/main/java/io/floci/aws/services/glue/GlueService.java @@ -453,8 +453,13 @@ public class GlueService { .map(Table::getName) .toList(); tableNames.forEach(tableName -> deleteTable(name, tableName)); + List functionArns = functionStore.scan(k -> true).stream() + .filter(function -> databaseName.equals(function.getDatabaseName())) + .map(function -> userDefinedFunctionArn(region, databaseName, function.getFunctionName())) + .toList(); StorageOperations.deleteMatchingAtomically(functionStore, function -> databaseName.equals(function.getDatabaseName())); + resourceGroupsTaggingService.deleteResources(functionArns, region); databaseStore.delete(databaseName); resourceGroupsTaggingService.deleteResources(List.of(databaseArn(region, databaseName)), region); LOG.infov("Deleted Glue Database: {0}", name); @@ -806,9 +811,12 @@ public class GlueService { } public synchronized void deleteTable(String databaseName, String tableName) { - getTable(databaseName, tableName); + Table table = getTable(databaseName, tableName); String key = tableKey(databaseName, tableName); tableStore.delete(key); + String region = regionResolver.getRegion(); + resourceGroupsTaggingService.deleteResources( + List.of(tableArn(region, table.getDatabaseName(), table.getName())), region); tableVersionStore.keys().stream() .filter(versionKey -> versionKey.startsWith(key + ":")) .forEach(tableVersionStore::delete); @@ -1370,8 +1378,11 @@ public class GlueService { } public synchronized void deleteUserDefinedFunction(String databaseName, String functionName) { - getUserDefinedFunction(databaseName, functionName); + UserDefinedFunction function = getUserDefinedFunction(databaseName, functionName); functionStore.delete(functionKey(databaseName, functionName)); + String region = regionResolver.getRegion(); + resourceGroupsTaggingService.deleteResources(List.of( + userDefinedFunctionArn(region, function.getDatabaseName(), function.getFunctionName())), region); } private void validateSchemaReference(Table table) { @@ -1709,6 +1720,14 @@ public class GlueService { return regionResolver.buildArn("glue", region, "database/" + databaseName); } + private String tableArn(String region, String databaseName, String tableName) { + return regionResolver.buildArn("glue", region, "table/" + databaseName + "/" + tableName); + } + + private String userDefinedFunctionArn(String region, String databaseName, String functionName) { + return regionResolver.buildArn("glue", region, "userDefinedFunction/" + databaseName + "/" + functionName); + } + private String jobArn(String region, String jobName) { return regionResolver.buildArn("glue", region, "job/" + jobName); } @@ -3238,6 +3257,30 @@ public class GlueService { } } + /** + * The tags of the resource stored under {@code arn}, in the account and Region it names: a registry's or a schema's + * from the schema registry, any other resource's from the tags applied to its ARN, which Glue drops when it deletes + * the resource; read in place and empty for an ARN naming nothing tagged. Only string values are tags: TagResource + * keeps the request's map as given. + */ + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "glue")) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String resource = parsed.resource(); + Map applied = resource.startsWith("registry/") || resource.startsWith("schema/") + ? schemaRegistryService.storedTags(arn) + : resourceGroupsTaggingService.storedTags(parsed.accountId(), parsed.region(), arn); + Map tags = new LinkedHashMap<>(); + applied.forEach((key, value) -> { + if (value instanceof String text) { + tags.put(key, text); + } + }); + return tags; + } + private void validateArn(String arn) { if (!AwsArnUtils.looksLikeArn(arn)) { throw new AwsException("InvalidInputException", "Invalid ARN", 400); diff --git a/src/main/java/io/floci/aws/services/glue/GlueStoredResourceArns.java b/src/main/java/io/floci/aws/services/glue/GlueStoredResourceArns.java new file mode 100644 index 0000000000..195fe75e49 --- /dev/null +++ b/src/main/java/io/floci/aws/services/glue/GlueStoredResourceArns.java @@ -0,0 +1,37 @@ +package io.floci.aws.services.glue; + +import io.floci.aws.core.common.StoredResourceArns; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** What IAM asks Glue of the resources a request names: the tags of the resource an ARN names. */ +@ApplicationScoped +public class GlueStoredResourceArns implements StoredResourceArns { + + private final GlueService glue; + + @Inject + public GlueStoredResourceArns(GlueService glue) { + this.glue = glue; + } + + @Override + public String namespace() { + return "glue"; + } + + /** Glue mints no id into an ARN a request names by its name, so there is nothing to find. */ + @Override + public Optional find(String type, List names, String region) { + return Optional.empty(); + } + + @Override + public Map storedTags(String arn) { + return glue.storedTags(arn); + } +} diff --git a/src/main/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryService.java b/src/main/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryService.java index 76a9fa1ad0..448c3752a1 100644 --- a/src/main/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryService.java +++ b/src/main/java/io/floci/aws/services/glue/schemaregistry/GlueSchemaRegistryService.java @@ -1,9 +1,11 @@ package io.floci.aws.services.glue.schemaregistry; import com.fasterxml.jackson.core.type.TypeReference; +import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.Digests; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; @@ -628,6 +630,33 @@ public class GlueSchemaRegistryService { resource.persist(); } + /** + * A copy of the tags of the registry or the schema stored under {@code arn} in the account it names, matched on the + * whole ARN and read in place; empty for an ARN naming nothing stored, or any other resource. + */ + public Map storedTags(String arn) { + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String resource = parsed.resource(); + Map tags = null; + if (resource.startsWith("registry/")) { + tags = AccountAwareStorageBackend.readInAccount(registryStore, parsed.accountId(), + resource.substring("registry/".length())) + .filter(registry -> arn.equals(registry.getRegistryArn())) + .map(Registry::getTags) + .orElse(null); + } else if (resource.startsWith("schema/")) { + String[] names = resource.substring("schema/".length()).split("/", 2); + if (names.length == 2) { + tags = AccountAwareStorageBackend.readInAccount(schemaStore, parsed.accountId(), + schemaKey(names[0], names[1])) + .filter(schema -> arn.equals(schema.getSchemaArn())) + .map(Schema::getTags) + .orElse(null); + } + } + return tags == null ? Map.of() : new LinkedHashMap<>(tags); + } + public Map getTags(String resourceArn) { TaggedResource resource = resolveTaggedResource(resourceArn); Map tags = resource.getTags(); diff --git a/src/main/java/io/floci/aws/services/glue/schemaregistry/model/Registry.java b/src/main/java/io/floci/aws/services/glue/schemaregistry/model/Registry.java index 57ab65b812..f3742b65d8 100644 --- a/src/main/java/io/floci/aws/services/glue/schemaregistry/model/Registry.java +++ b/src/main/java/io/floci/aws/services/glue/schemaregistry/model/Registry.java @@ -33,7 +33,7 @@ public class Registry { private Instant updatedTime; @JsonProperty("Tags") - private Map tags; + private volatile Map tags; public Registry() {} diff --git a/src/main/java/io/floci/aws/services/glue/schemaregistry/model/Schema.java b/src/main/java/io/floci/aws/services/glue/schemaregistry/model/Schema.java index 9d15b87985..261ffaed74 100644 --- a/src/main/java/io/floci/aws/services/glue/schemaregistry/model/Schema.java +++ b/src/main/java/io/floci/aws/services/glue/schemaregistry/model/Schema.java @@ -54,7 +54,7 @@ public class Schema { private Instant updatedTime; @JsonProperty("Tags") - private Map tags; + private volatile Map tags; public Schema() {} diff --git a/src/main/java/io/floci/aws/services/resourcegroupstagging/ResourceGroupsTaggingService.java b/src/main/java/io/floci/aws/services/resourcegroupstagging/ResourceGroupsTaggingService.java index 7d6a7a072e..bfee9844a2 100644 --- a/src/main/java/io/floci/aws/services/resourcegroupstagging/ResourceGroupsTaggingService.java +++ b/src/main/java/io/floci/aws/services/resourcegroupstagging/ResourceGroupsTaggingService.java @@ -9,7 +9,9 @@ import io.floci.aws.core.common.TagHandler; import io.floci.aws.core.resource.ExplorerResource; import io.floci.aws.core.resource.ResourceProvider; import io.floci.aws.core.resource.SupportedResourceType; +import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackedMap; +import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.resourcegroupstagging.model.ResourceTagMapping; import jakarta.annotation.PostConstruct; @@ -29,6 +31,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; @@ -50,6 +53,8 @@ public class ResourceGroupsTaggingService implements Resettable { // region::arn → ResourceTagMapping private Map store = new ConcurrentHashMap<>(); + /** The backend of {@link #store}, read in another account than the caller's. */ + private StorageBackend storage; @Inject public ResourceGroupsTaggingService(StorageFactory storageFactory, @@ -80,8 +85,9 @@ public class ResourceGroupsTaggingService implements Resettable { if (storageFactory == null) { return; // keeps non-CDI unit tests working } - this.store = new StorageBackedMap<>(storageFactory.create("tagging", - "tagging-resource-mappings.json", new TypeReference>() {})); + this.storage = storageFactory.create("tagging", + "tagging-resource-mappings.json", new TypeReference>() {}); + this.store = new StorageBackedMap<>(storage); } private String key(String region, String arn) { @@ -96,6 +102,17 @@ public class ResourceGroupsTaggingService implements Resettable { return mapping != null ? Collections.unmodifiableMap(mapping.getTags()) : Map.of(); } + /** + * A copy of the tags applied to the resource {@code arn} names, stored in {@code accountId} and {@code region}, + * read in place, a pre-multi-account mapping of the default account included; empty when none were applied. + */ + public Map storedTags(String accountId, String region, String arn) { + String storeKey = key(region, arn); + Optional mapping = storage == null ? Optional.ofNullable(store.get(storeKey)) + : AccountAwareStorageBackend.readInAccount(storage, accountId, storeKey); + return mapping.>map(stored -> new LinkedHashMap<>(stored.getTags())).orElse(Map.of()); + } + // ─── TagResources ────────────────────────────────────────────────────────── // Mutators are synchronized: StorageBackedMap has no atomic computeIfAbsent, so @@ -107,7 +124,9 @@ public class ResourceGroupsTaggingService implements Resettable { if (mapping == null) { mapping = new ResourceTagMapping(arn); } - mapping.getTags().putAll(tags); + Map next = new LinkedHashMap<>(mapping.getTags()); + next.putAll(tags); + mapping.setTags(next); // Re-put so StorageBackedMap routes the mutation through the backend store.put(storeKey, mapping); } @@ -120,7 +139,9 @@ public class ResourceGroupsTaggingService implements Resettable { String storeKey = key(region, arn); ResourceTagMapping mapping = store.get(storeKey); if (mapping != null) { - tagKeys.forEach(mapping.getTags()::remove); + Map next = new LinkedHashMap<>(mapping.getTags()); + tagKeys.forEach(next::remove); + mapping.setTags(next); store.put(storeKey, mapping); } } diff --git a/src/main/java/io/floci/aws/services/resourcegroupstagging/model/ResourceTagMapping.java b/src/main/java/io/floci/aws/services/resourcegroupstagging/model/ResourceTagMapping.java index 45b8534fa0..3d5f68e777 100644 --- a/src/main/java/io/floci/aws/services/resourcegroupstagging/model/ResourceTagMapping.java +++ b/src/main/java/io/floci/aws/services/resourcegroupstagging/model/ResourceTagMapping.java @@ -11,8 +11,9 @@ import java.util.Map; public class ResourceTagMapping { private String resourceArn; - // Preserves insertion order for deterministic responses - private final Map tags = new LinkedHashMap<>(); + // Preserves insertion order for deterministic responses. A stored mapping's tags are replaced, never changed in + // place, so a reader copying them sees one whole set. + private volatile Map tags = new LinkedHashMap<>(); public ResourceTagMapping() {} @@ -24,4 +25,5 @@ public class ResourceTagMapping { public void setResourceArn(String resourceArn) { this.resourceArn = resourceArn; } public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags == null ? new LinkedHashMap<>() : tags; } } diff --git a/src/test/java/io/floci/aws/services/glue/GlueServiceTest.java b/src/test/java/io/floci/aws/services/glue/GlueServiceTest.java index 53d124a746..5fbed1ce0a 100644 --- a/src/test/java/io/floci/aws/services/glue/GlueServiceTest.java +++ b/src/test/java/io/floci/aws/services/glue/GlueServiceTest.java @@ -1660,6 +1660,68 @@ class GlueServiceTest { assertEquals("prod", crawlerTags.get("env")); } + @Test + @SuppressWarnings("unchecked") + void storedTagsAreTheStringTagsOfTheJobOrTheRegistryTheArnNames() { + glueService.createJob(createValidJob("stored-tags-job"), Map.of("team", "data"), REGION); + String jobArn = "arn:aws:glue:" + REGION + ":" + ACCOUNT_ID + ":job/stored-tags-job"; + String registryArn = schemaRegistryService.createRegistry("stored-tags-registry", null, + Map.of("team", "stream"), REGION).getRegistryArn(); + Map mixed = (Map) (Map) Map.of("owner", "ingest", "count", 5); + glueService.tagResource(jobArn, mixed, REGION); + + assertEquals(Map.of("team", "data", "owner", "ingest"), glueService.storedTags(jobArn)); + assertEquals(Map.of("team", "stream"), glueService.storedTags(registryArn)); + assertEquals(Map.of(), glueService.storedTags(jobArn.replace(ACCOUNT_ID, "111111111111"))); + assertEquals(Map.of(), glueService.storedTags(jobArn.replace(REGION, "us-west-2"))); + assertEquals(Map.of(), glueService.storedTags(registryArn.replace(REGION, "us-west-2"))); + assertEquals(Map.of(), glueService.storedTags(registryArn + "-missing")); + + glueService.deleteJob("stored-tags-job", REGION); + + assertEquals(Map.of(), glueService.storedTags(jobArn)); + } + + @Test + void aTablesAndAFunctionsTagsGoWhenTheyOrTheirDatabaseAreDeleted() { + String tableArn = "arn:aws:glue:" + REGION + ":" + ACCOUNT_ID + ":table/db1/tagged"; + String functionArn = "arn:aws:glue:" + REGION + ":" + ACCOUNT_ID + ":userDefinedFunction/db1/tagged_fn"; + createTaggedTableAndFunction(tableArn, functionArn); + assertEquals(Map.of("team", "data"), glueService.storedTags(tableArn)); + assertEquals(Map.of("team", "data"), glueService.storedTags(functionArn)); + + glueService.deleteTable("db1", "tagged"); + glueService.deleteUserDefinedFunction("db1", "tagged_fn"); + Table recreated = new Table(); + recreated.setName("tagged"); + glueService.createTable("db1", recreated); + UserDefinedFunction function = new UserDefinedFunction(); + function.setFunctionName("tagged_fn"); + glueService.createUserDefinedFunction("db1", function); + + assertEquals(Map.of(), glueService.storedTags(tableArn)); + assertEquals(Map.of(), glueService.storedTags(functionArn)); + + glueService.deleteTable("db1", "tagged"); + glueService.deleteUserDefinedFunction("db1", "tagged_fn"); + createTaggedTableAndFunction(tableArn, functionArn); + glueService.deleteDatabase("db1", REGION); + + assertEquals(Map.of(), glueService.storedTags(tableArn)); + assertEquals(Map.of(), glueService.storedTags(functionArn)); + } + + private void createTaggedTableAndFunction(String tableArn, String functionArn) { + Table table = new Table(); + table.setName("tagged"); + glueService.createTable("db1", table); + UserDefinedFunction function = new UserDefinedFunction(); + function.setFunctionName("tagged_fn"); + glueService.createUserDefinedFunction("db1", function); + glueService.tagResource(tableArn, Map.of("team", "data"), REGION); + glueService.tagResource(functionArn, Map.of("team", "data"), REGION); + } + @Test void jobAndCrawlerRejectsDuplicateCreation() { Job job = createValidJob("dup-job"); diff --git a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java index 2b58859c47..a7fb86d54d 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java @@ -1912,6 +1912,42 @@ class IamRequestResourceEnforcementIntegrationTest { refusedJson(send(user, "glue", "AWSGlue.GetJob", "1.1", "{\"JobName\":\"" + job + "-other\"}"), "glue:GetJob"); } + /** + * An {@code aws:ResourceTag} condition reads the tags Glue holds on the resource a request names, a job's and a + * schema registry's, so an allow on one team's tag lets the caller read that team's job and registry and not + * another's. + */ + @Test + void aGlueResourceTagConditionReadsTheTagsOfTheJobAndTheRegistry() { + String tagged = "res-tag-job-" + suffix(); + String other = "res-tag-job-" + suffix(); + String jobRest = "\",\"Role\":\"arn:aws:iam::" + ACCOUNT + ":role/glue\"," + + "\"Command\":{\"Name\":\"glueetl\",\"ScriptLocation\":\"s3://scripts/job.py\"}"; + glue("CreateJob", "{\"Name\":\"" + tagged + jobRest + ",\"Tags\":{\"team\":\"data\"}}").statusCode(200); + cleanup.register(() -> glue("DeleteJob", "{\"JobName\":\"" + tagged + "\"}")); + glue("CreateJob", "{\"Name\":\"" + other + jobRest + ",\"Tags\":{\"team\":\"web\"}}").statusCode(200); + cleanup.register(() -> glue("DeleteJob", "{\"JobName\":\"" + other + "\"}")); + String taggedRegistry = "res-tag-reg-" + suffix(); + String otherRegistry = "res-tag-reg-" + suffix(); + glue("CreateRegistry", "{\"RegistryName\":\"" + taggedRegistry + "\",\"Tags\":{\"team\":\"data\"}}") + .statusCode(200); + cleanup.register(() -> glue("DeleteRegistry", "{\"RegistryId\":{\"RegistryName\":\"" + taggedRegistry + + "\"}}")); + glue("CreateRegistry", "{\"RegistryName\":\"" + otherRegistry + "\"}").statusCode(200); + cleanup.register(() -> glue("DeleteRegistry", "{\"RegistryId\":{\"RegistryName\":\"" + otherRegistry + + "\"}}")); + + User user = user("res-glue-tags"); + user.policy("{\"Effect\":\"Allow\",\"Action\":[\"glue:GetJob\",\"glue:GetRegistry\"],\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}"); + send(user, "glue", "AWSGlue.GetJob", "1.1", "{\"JobName\":\"" + tagged + "\"}").statusCode(200); + refusedJson(send(user, "glue", "AWSGlue.GetJob", "1.1", "{\"JobName\":\"" + other + "\"}"), "glue:GetJob"); + send(user, "glue", "AWSGlue.GetRegistry", "1.1", "{\"RegistryId\":{\"RegistryName\":\"" + taggedRegistry + + "\"}}").statusCode(200); + refusedJson(send(user, "glue", "AWSGlue.GetRegistry", "1.1", "{\"RegistryId\":{\"RegistryName\":\"" + + otherRegistry + "\"}}"), "glue:GetRegistry"); + } + /** * What Glue's batch deletes name, the tables of {@code TablesToDelete} and the connections of * {@code ConnectionNameList}, is checked one by one, so a deny scoped to one of them holds under an allow on diff --git a/src/test/java/io/floci/aws/services/resourcegroupstagging/ResourceGroupsTaggingServiceTest.java b/src/test/java/io/floci/aws/services/resourcegroupstagging/ResourceGroupsTaggingServiceTest.java index b7b88f483e..55b170fa9f 100644 --- a/src/test/java/io/floci/aws/services/resourcegroupstagging/ResourceGroupsTaggingServiceTest.java +++ b/src/test/java/io/floci/aws/services/resourcegroupstagging/ResourceGroupsTaggingServiceTest.java @@ -6,6 +6,8 @@ import io.floci.aws.core.common.TagHandler; import io.floci.aws.core.resource.ExplorerResource; import io.floci.aws.core.resource.ResourceProvider; import io.floci.aws.core.resource.SupportedResourceType; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.resourcegroupstagging.model.ResourceTagMapping; import org.junit.jupiter.api.Test; @@ -25,6 +27,10 @@ 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; +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 ResourceGroupsTaggingServiceTest { @@ -47,6 +53,26 @@ class ResourceGroupsTaggingServiceTest { assertEquals("my-bucket", ResourceGroupsTaggingService.parsedType("my-bucket")); } + @Test + void storedTagsReadTheMappingOfTheAccountAndRegionAskedForAndTaggingReplacesIt() { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenAnswer(inv -> AccountAwareStorageBackend.inMemory(ACCOUNT)); + ResourceGroupsTaggingService service = new ResourceGroupsTaggingService(storageFactory, List.of(), List.of(), + new RegionResolver(REGION, ACCOUNT)); + service.initializeStorage(); + service.tagResources(List.of(QUEUE_ARN), Map.of("team", "a"), REGION); + Map held = service.getTagsForResource(REGION, QUEUE_ARN); + + service.tagResources(List.of(QUEUE_ARN), Map.of("stage", "prod"), REGION); + service.untagResources(List.of(QUEUE_ARN), List.of("team"), REGION); + + assertEquals(Map.of("stage", "prod"), service.storedTags(ACCOUNT, REGION, QUEUE_ARN)); + assertEquals(Map.of("team", "a"), held); + assertEquals(Map.of(), service.storedTags("111111111111", REGION, QUEUE_ARN)); + assertEquals(Map.of(), service.storedTags(ACCOUNT, "us-west-2", QUEUE_ARN)); + } + @Test void resourceTypeFilterMatchesProviderDeclaredType() { ResourceGroupsTaggingService service = service(List.of(