diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2TagRegionTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2TagRegionTest.java new file mode 100644 index 0000000000..0f22009537 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2TagRegionTest.java @@ -0,0 +1,74 @@ +package com.floci.test; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.regions.RegionMetadata; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.CreateTagsRequest; +import software.amazon.awssdk.services.ec2.model.CreateVpcRequest; +import software.amazon.awssdk.services.ec2.model.DeleteVpcRequest; +import software.amazon.awssdk.services.ec2.model.DescribeTagsRequest; +import software.amazon.awssdk.services.ec2.model.Filter; +import software.amazon.awssdk.services.ec2.model.Tag; +import software.amazon.awssdk.services.ec2.model.TagDescription; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@DisplayName("EC2 tags are regional") +class Ec2TagRegionTest { + + @Test + @DisplayName("DescribeTags lists only the tags of resources in the client's region") + void describeTagsListsOnlyTheClientRegionsTags() { + Region other = otherRegionInThePartition(); + try (Ec2Client home = TestFixtures.ec2Client(); Ec2Client away = clientFor(other)) { + String homeVpc = home.createVpc(CreateVpcRequest.builder().cidrBlock("10.92.0.0/16").build()).vpc().vpcId(); + String awayVpc = away.createVpc(CreateVpcRequest.builder().cidrBlock("10.93.0.0/16").build()).vpc().vpcId(); + try { + home.createTags(CreateTagsRequest.builder().resources(homeVpc) + .tags(Tag.builder().key("SdkRegionProbe").value("home").build()).build()); + away.createTags(CreateTagsRequest.builder().resources(awayVpc) + .tags(Tag.builder().key("SdkRegionProbe").value("away").build()).build()); + + assertThat(probedIds(home)).containsExactly(homeVpc); + assertThat(probedIds(away)).containsExactly(awayVpc); + } finally { + home.deleteVpc(DeleteVpcRequest.builder().vpcId(homeVpc).build()); + away.deleteVpc(DeleteVpcRequest.builder().vpcId(awayVpc).build()); + } + } + } + + private static List probedIds(Ec2Client ec2) { + return ec2.describeTags(DescribeTagsRequest.builder() + .filters(Filter.builder().name("key").values("SdkRegionProbe").build()).build()) + .tags().stream().map(TagDescription::resourceId).toList(); + } + + private static Region otherRegionInThePartition() { + Region home = TestFixtures.region(); + String partition = TestFixtures.partition(); + return Region.regions().stream() + .filter(region -> !region.isGlobalRegion() && !region.equals(home)) + .filter(region -> { + RegionMetadata metadata = region.metadata(); + return metadata != null && partition.equals(metadata.partition().id()); + }) + .sorted((a, b) -> a.id().compareTo(b.id())) + .findFirst() + .orElseThrow(() -> new AssertionError("no second region in partition " + partition)); + } + + private static Ec2Client clientFor(Region region) { + return Ec2Client.builder() + .endpointOverride(TestFixtures.endpoint()) + .region(region) + .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) + .build(); + } +} diff --git a/docs/services/ec2.md b/docs/services/ec2.md index d78c76abb7..02ff95f68e 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -302,6 +302,19 @@ that publish those images. | DeleteTags | Removes tags from supported EC2 resources. | | DescribeTags | Lists tags stored for EC2 resources. | +Tags are regional, like the resources they label: `DescribeTags` lists only the tags of resources +in the request's region, and a tag set in one region is not visible from another. Each result +carries the resource's `resourceType` (`image`, `volume`, `snapshot`, `network-acl`, +`vpc-peering-connection` and `spot-instances-request` included). Tags given when a volume or a +VPC peering connection is created are listed like any other tag, and `DescribeVolumes`, +`DescribeSnapshots` and `DescribeSpotInstanceRequests` show later `CreateTags` and `DeleteTags` +changes. Each side of a VPC peering connection sees the tags set in its own account and region. +A resource's tags go with it: deleting a volume, a snapshot or a peering connection, or the +removal of a terminated instance, removes its tags. On upgrade, tags stored by an older Floci +version are moved under their resource's region at startup. Tags on a catalog AMI move to the +default region, and tags on an EKS node instance move to the node's region once the node is +restored; any other tag whose resource no longer exists is dropped. + Public tag mutations reject keys beginning with `aws:` regardless of ASCII case. An empty `DeleteTags` tag list removes user tags and preserves AWS-managed tags. CloudFormation tag updates and rollbacks likewise leave AWS-managed tags intact. diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java index 3a27d315e6..326731c972 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java @@ -648,7 +648,8 @@ public class IamConditionContextResolver { if (resourceId == null || resourceId.isBlank() || !ec2Service.isResolvable()) { return; } - for (Tag tag : ec2Service.get().resourceTags(resourceId)) { + String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion(); + for (Tag tag : ec2Service.get().resourceTags(region, resourceId)) { conditions.put(RESOURCE_TAG_PREFIX + tag.getKey(), List.of(tag.getValue() == null ? "" : tag.getValue())); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 4cab916d11..2cabd17719 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -816,6 +816,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab @PostConstruct void restoreMetadataRegistrations() { + migrateTagsToRegionKeys(); if (portForwardManager != null) { portForwardManager.setPersister(inst -> { if (inst != null && inst.getRegion() != null && inst.getInstanceId() != null) { @@ -1067,6 +1068,147 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return entries; } + /** + * Moves tags stored before tags were regional, keyed by the bare resource id, to + * {@code region::id}, taking the region from where the resource itself is stored (both sides' + * regions for a peering attachment or connection). A catalog AMI, which every region serves + * under one id, takes the default region. An instance no store holds may be an EKS node, which + * its provider restores on its own schedule: it keeps its bare key until + * {@link #getTagsForAccount} first finds that node in a region. Any other tag whose resource + * no store holds is dropped: AWS has no tag without its resource. Runs once at startup; an entry + * already keyed by region is left alone, so a later run finds nothing to do. + */ + void migrateTagsToRegionKeys() { + List>> legacy = entriesOfEveryAccount(tags).stream() + .filter(entry -> !entry.key().contains("::")) + .toList(); + if (legacy.isEmpty()) { + return; + } + Map>> regionsByOwner = resourceRegionsByOwner(); + int moved = 0; + int kept = 0; + int dropped = 0; + for (AccountAwareStorageBackend.AccountEntry> entry : legacy) { + Set regions = regionsByOwner.getOrDefault(ownerKey(entry.accountId()), Map.of()) + .getOrDefault(entry.key(), Set.of()); + if (regions.isEmpty() && entry.key().startsWith("ami-") + && imageCatalog != null && imageCatalog.findByIdOrAlias(entry.key()).isPresent()) { + regions = Set.of(config.defaultRegion()); + } + if (regions.isEmpty() && entry.key().startsWith("i-")) { + kept++; + continue; + } + for (String region : regions) { + AccountAwareStorageBackend.AccountEntry> regional = + new AccountAwareStorageBackend.AccountEntry<>(entry.accountId(), key(region, entry.key()), entry.value()); + if (getForOwner(tags, regional).isEmpty()) { + putForOwner(tags, regional, entry.value()); + } + } + deleteForOwner(tags, entry); + if (regions.isEmpty()) { + dropped++; + } else { + moved++; + } + } + LOG.infov("Moved {0} EC2 tag record(s) under their resource's region; kept {1} for instances not yet" + + " restored; dropped {2} whose resource no region holds", moved, kept, dropped); + } + + /** Resource id to the regions it is stored in, per owning account ("" for a store without accounts). */ + private Map>> resourceRegionsByOwner() { + Map>> index = new HashMap<>(); + for (StorageBackend store : List.of(instances, vpcs, subnets, securityGroups, securityGroupRules, + internetGateways, egressOnlyInternetGateways, routeTables, networkAcls, keyPairs, addresses, volumes, + snapshots, registeredImages, launchTemplates, vpcEndpoints, natGateways, spotInstanceRequests, + managedPrefixLists, transitGateways, transitGatewayRouteTables, transitGatewayVpcAttachments, + networkInterfaces, capacityReservations, hosts)) { + indexRegionalKeys(index, store); + } + for (AccountAwareStorageBackend.AccountEntry entry : entriesOfEveryAccount(instances)) { + String region = entry.value().getRegion(); + if (region != null && entry.value().getNetworkInterfaces() != null) { + entry.value().getNetworkInterfaces().forEach(eni -> + indexRegion(index, entry.accountId(), eni.getNetworkInterfaceId(), region)); + } + } + for (AccountAwareStorageBackend.AccountEntry entry : entriesOfEveryAccount(natGateways)) { + String region = regionOfKey(entry.key()); + if (region != null && entry.value().getNatGatewayAddresses() != null) { + entry.value().getNatGatewayAddresses().forEach(address -> + indexRegion(index, entry.accountId(), address.getNetworkInterfaceId(), region)); + } + } + // Peering records are keyed by bare id: each side's account sees its own tags in its own region. + for (AccountAwareStorageBackend.AccountEntry entry + : entriesOfEveryAccount(transitGatewayPeeringAttachments)) { + String id = entry.value().getTransitGatewayAttachmentId(); + for (TransitGatewayPeeringAttachment.TgwInfo side + : List.of(entry.value().getRequesterTgwInfo(), entry.value().getAccepterTgwInfo())) { + if (side != null) { + indexRegion(index, entry.accountId() == null ? null : side.getOwnerId(), id, side.getRegion()); + } + } + } + for (AccountAwareStorageBackend.AccountEntry entry : entriesOfEveryAccount(vpcPeeringConnections)) { + String id = entry.value().getVpcPeeringConnectionId(); + for (VpcPeeringConnectionVpcInfo side + : List.of(entry.value().getRequesterVpcInfo(), entry.value().getAccepterVpcInfo())) { + if (side != null) { + indexRegion(index, entry.accountId() == null ? null : side.getOwnerId(), id, side.getRegion()); + } + } + } + return index; + } + + private static void indexRegionalKeys(Map>> index, StorageBackend store) { + for (AccountAwareStorageBackend.AccountEntry entry : entriesOfEveryAccount(store)) { + String region = regionOfKey(entry.key()); + if (region != null) { + indexRegion(index, entry.accountId(), entry.key().substring(region.length() + 2), region); + } + } + } + + private static void indexRegion(Map>> index, String accountId, String resourceId, + String region) { + if (resourceId != null && region != null) { + index.computeIfAbsent(ownerKey(accountId), ignored -> new HashMap<>()) + .computeIfAbsent(resourceId, ignored -> new LinkedHashSet<>()) + .add(region); + } + } + + private static String regionOfKey(String storeKey) { + int separator = storeKey.indexOf("::"); + return separator > 0 ? storeKey.substring(0, separator) : null; + } + + private static String ownerKey(String accountId) { + return accountId == null ? "" : accountId; + } + + private static Optional getForOwner(StorageBackend store, AccountAwareStorageBackend.AccountEntry entry) { + if (store instanceof AccountAwareStorageBackend rawAccountAware) { + @SuppressWarnings("unchecked") + AccountAwareStorageBackend accountAware = (AccountAwareStorageBackend) rawAccountAware; + return accountAware.getForAccount(entry.accountId(), entry.key()); + } + return store.get(entry.key()); + } + + private static void deleteForOwner(StorageBackend store, AccountAwareStorageBackend.AccountEntry entry) { + if (store instanceof AccountAwareStorageBackend rawAccountAware) { + rawAccountAware.deleteForAccount(entry.accountId(), entry.key()); + return; + } + store.delete(entry.key()); + } + private static void putForOwner(StorageBackend store, AccountAwareStorageBackend.AccountEntry entry, T value) { if (store instanceof AccountAwareStorageBackend rawAccountAware) { @@ -1531,7 +1673,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab list.getEntriesByVersion().put("1", new ArrayList<>(initial)); if (prefixListTags != null && !prefixListTags.isEmpty()) { list.setTags(new ArrayList<>(prefixListTags)); - tags.put(prefixListId, new ArrayList<>(prefixListTags)); + putTags(region, prefixListId, new ArrayList<>(prefixListTags)); } managedPrefixLists.put(key(region, prefixListId), list); return list; @@ -1633,7 +1775,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab ManagedPrefixList list = getRequiredManagedPrefixList(region, prefixListId); requireCustomerManaged(list, "deleted"); managedPrefixLists.delete(key(region, prefixListId)); - tags.delete(prefixListId); + removeTags(region, prefixListId); reconcileFirewallPolicies(region); // AWS reports delete-complete on the returned object even though it is now gone. list.setState("delete-complete"); @@ -1847,7 +1989,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (gatewayTags != null && !gatewayTags.isEmpty()) { gateway.setTags(new ArrayList<>(gatewayTags)); - tags.put(transitGatewayId, new ArrayList<>(gatewayTags)); + putTags(region, transitGatewayId, new ArrayList<>(gatewayTags)); } transitGateways.put(key(region, transitGatewayId), gateway); return gateway; @@ -2184,10 +2326,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab routesOf(region, routeTableId).forEach(route -> transitGatewayRoutes .delete(routeKey(region, routeTableId, route.getDestinationCidrBlock()))); transitGatewayRouteTables.delete(key(region, routeTableId)); - tags.delete(routeTableId); + removeTags(region, routeTableId); }); transitGateways.delete(key(region, transitGatewayId)); - tags.delete(transitGatewayId); + removeTags(region, transitGatewayId); gateway.setState("deleted"); return gateway; } @@ -2278,7 +2420,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } if (attachmentTags != null && !attachmentTags.isEmpty()) { attachment.setTags(new ArrayList<>(attachmentTags)); - tags.put(attachmentId, new ArrayList<>(attachmentTags)); + putTags(region, attachmentId, new ArrayList<>(attachmentTags)); } transitGatewayVpcAttachments.put(key(region, attachmentId), attachment); return attachment; @@ -2440,7 +2582,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab route.getDestinationCidrBlock()), route); }); transitGatewayVpcAttachments.delete(key(region, attachmentId)); - tags.delete(attachmentId); + removeTags(region, attachmentId); attachment.setState("deleted"); return attachment; } @@ -2490,9 +2632,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab attachment.setCreationTime(ISO_FMT.format(Instant.now())); transitGatewayPeeringAttachments.put(attachmentId, attachment); if (attachmentTags != null && !attachmentTags.isEmpty()) { - tags.put(attachmentId, new ArrayList<>(attachmentTags)); + putTags(region, attachmentId, new ArrayList<>(attachmentTags)); } - return withStoredTags(attachment); + return withStoredTags(attachment, region); } } @@ -2502,7 +2644,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab String account = callerAccountId(); List visible = allPeeringAttachments().stream() .filter(attachment -> isPartyTo(attachment, account, region)) - .map(this::withStoredTags) + .map(attachment -> withStoredTags(attachment, region)) .toList(); for (String attachmentId : attachmentIds) { if (visible.stream().noneMatch(a -> a.getTransitGatewayAttachmentId().equals(attachmentId))) { @@ -2538,7 +2680,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab getRequiredTransitGateway(region, attachment.getAccepterTgwInfo().getTransitGatewayId()); attachment.setState("available"); savePeeringAttachment(owned); - return withStoredTags(attachment); + return withStoredTags(attachment, region); } } } @@ -2568,18 +2710,21 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab public TransitGatewayPeeringAttachment deleteTransitGatewayPeeringAttachment(String region, String attachmentId) { synchronized (lockFor(attachmentId)) { OwnedPeeringAttachment owned = getRequiredPeeringAttachment(region, attachmentId); - TransitGatewayPeeringAttachment attachment = withStoredTags(owned.attachment()); + TransitGatewayPeeringAttachment attachment = withStoredTags(owned.attachment(), region); if (owned.storageAccountId() != null) { peeringAttachmentsByAccount().deleteForAccount(owned.storageAccountId(), attachmentId); } else { transitGatewayPeeringAttachments.delete(attachmentId); } - // Tags are per account, so each side keeps its own; both go with the attachment. + // Tags are per account and per region, so each side keeps its own; both go with the attachment. + TransitGatewayPeeringAttachment.TgwInfo requester = attachment.getRequesterTgwInfo(); + TransitGatewayPeeringAttachment.TgwInfo accepter = attachment.getAccepterTgwInfo(); if (tags instanceof AccountAwareStorageBackend tagsByAccount) { - tagsByAccount.deleteForAccount(attachment.getRequesterTgwInfo().getOwnerId(), attachmentId); - tagsByAccount.deleteForAccount(attachment.getAccepterTgwInfo().getOwnerId(), attachmentId); + tagsByAccount.deleteForAccount(requester.getOwnerId(), key(requester.getRegion(), attachmentId)); + tagsByAccount.deleteForAccount(accepter.getOwnerId(), key(accepter.getRegion(), attachmentId)); } else { - tags.delete(attachmentId); + removeTags(requester.getRegion(), attachmentId); + removeTags(accepter.getRegion(), attachmentId); } attachment.setState("deleted"); return attachment; @@ -2652,8 +2797,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab ? attachment.getAccepterTgwInfo() : attachment.getRequesterTgwInfo(); } - private TransitGatewayPeeringAttachment withStoredTags(TransitGatewayPeeringAttachment attachment) { - attachment.setTags(new ArrayList<>(tags.get(attachment.getTransitGatewayAttachmentId()).orElse(List.of()))); + private TransitGatewayPeeringAttachment withStoredTags(TransitGatewayPeeringAttachment attachment, String region) { + attachment.setTags(new ArrayList<>(tagsOf(region, attachment.getTransitGatewayAttachmentId()).orElse(List.of()))); return attachment; } @@ -2696,7 +2841,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab routeTable.setRegion(region); if (routeTableTags != null && !routeTableTags.isEmpty()) { routeTable.setTags(new ArrayList<>(routeTableTags)); - tags.put(routeTableId, new ArrayList<>(routeTableTags)); + putTags(region, routeTableId, new ArrayList<>(routeTableTags)); } transitGatewayRouteTables.put(key(region, routeTableId), routeTable); return routeTable; @@ -2747,7 +2892,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab routesOf(region, routeTableId).forEach(route -> transitGatewayRoutes .delete(routeKey(region, routeTableId, route.getDestinationCidrBlock()))); transitGatewayRouteTables.delete(key(region, routeTableId)); - tags.delete(routeTableId); + removeTags(region, routeTableId); routeTable.setState("deleted"); return routeTable; } @@ -3530,7 +3675,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab acquiredCpuCredits(effectiveInstanceType, creditSpecificationCpuCredits)); if (instanceTags != null && !instanceTags.isEmpty()) { inst.setTags(new ArrayList<>(instanceTags)); - tags.put(instanceId, new ArrayList<>(instanceTags)); + putTags(region, instanceId, new ArrayList<>(instanceTags)); } // Network interface, either the caller-supplied standalone ENI (override-default-eni, @@ -4062,6 +4207,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab volumeBlockDeviceManager.deleteVolume(inst.getRootVolumeId()); } volumes.delete(key(region, inst.getRootVolumeId())); + removeTags(region, inst.getRootVolumeId()); } } } @@ -4229,6 +4375,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab && inst.getTerminatedAt() > 0 && inst.getTerminatedAt() < cutoff) { instances.delete(storeKey); + if (inst.getRegion() != null) { + removeTags(inst.getRegion(), inst.getInstanceId()); + } } } } @@ -4601,15 +4750,45 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab + "Valid values are: standard, unlimited.", 400); } - private List getTagsForAccount(String accountId, String resourceId, List fallback) { + private List getTagsForAccount(String accountId, String region, String resourceId, List fallback) { String safeAccount = accountId != null ? accountId : callerAccountId(); - Optional> stored = tags instanceof AccountAwareStorageBackend> aware - ? aware.getForAccount(safeAccount, resourceId) - : tags.get(resourceId); - return stored.orElse(fallback); + Optional> regional = tagsOf(safeAccount, region, resourceId); + if (regional.isPresent()) { + return regional.get(); + } + return claimLegacyInstanceTags(safeAccount, region, resourceId).orElse(fallback); } - private Instance copyExternalInstance(String accountId, Instance source) { + /** + * Moves an external instance's tags, stored by bare id before tags were regional and kept by + * {@link #migrateTagsToRegionKeys}, under the region the instance is now found in. With no + * region to file them under, the tags are read in place and left for a regional lookup. + */ + private Optional> claimLegacyInstanceTags(String accountId, String region, String instanceId) { + if (region == null || region.isBlank()) { + return tags instanceof AccountAwareStorageBackend> aware + ? aware.getForAccount(accountId, instanceId) + : tags.get(instanceId); + } + synchronized (lockFor(key(region, instanceId))) { + if (tags instanceof AccountAwareStorageBackend> aware) { + Optional> legacy = aware.getForAccount(accountId, instanceId); + legacy.ifPresent(value -> { + aware.putForAccount(accountId, key(region, instanceId), value); + aware.deleteForAccount(accountId, instanceId); + }); + return legacy; + } + Optional> legacy = tags.get(instanceId); + legacy.ifPresent(value -> { + tags.put(key(region, instanceId), value); + tags.delete(instanceId); + }); + return legacy; + } + } + + private Instance copyExternalInstance(String accountId, String region, Instance source) { if (source == null) { return null; } @@ -4659,7 +4838,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (source.getNetworkInterfaces() != null) { copy.setNetworkInterfaces(new ArrayList<>(source.getNetworkInterfaces())); } - List effectiveTags = getTagsForAccount(accountId, source.getInstanceId(), source.getTags()); + String tagRegion = region != null && !region.isBlank() ? region : source.getRegion(); + List effectiveTags = getTagsForAccount(accountId, tagRegion, source.getInstanceId(), source.getTags()); copy.setTags(effectiveTags != null ? new ArrayList<>(effectiveTags) : new ArrayList<>()); return copy; } @@ -4667,7 +4847,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab private Optional findExternalInstance(String accountId, String region, String instanceId) { if (testClusterNodeInstanceProvider != null) { return testClusterNodeInstanceProvider.findInstance(accountId, region, instanceId) - .map(inst -> copyExternalInstance(accountId, inst)); + .map(inst -> copyExternalInstance(accountId, region, inst)); } if (clusterNodeInstanceProviders == null || clusterNodeInstanceProviders.isUnsatisfied()) { return Optional.empty(); @@ -4675,7 +4855,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab for (ClusterNodeInstanceProvider provider : clusterNodeInstanceProviders) { Optional inst = provider.findInstance(accountId, region, instanceId); if (inst.isPresent()) { - return inst.map(i -> copyExternalInstance(accountId, i)); + return inst.map(i -> copyExternalInstance(accountId, region, i)); } } return Optional.empty(); @@ -4684,7 +4864,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab private List listExternalInstances(String accountId, String region) { if (testClusterNodeInstanceProvider != null) { return testClusterNodeInstanceProvider.listInstances(accountId, region).stream() - .map(inst -> copyExternalInstance(accountId, inst)) + .map(inst -> copyExternalInstance(accountId, region, inst)) .toList(); } if (clusterNodeInstanceProviders == null || clusterNodeInstanceProviders.isUnsatisfied()) { @@ -4695,7 +4875,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab List list = provider.listInstances(accountId, region); if (list != null && !list.isEmpty()) { for (Instance inst : list) { - result.add(copyExternalInstance(accountId, inst)); + result.add(copyExternalInstance(accountId, region, inst)); } } } @@ -4835,7 +5015,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab eigw.setCreationTags(new ArrayList<>(tagList)); eigw.setTags(new ArrayList<>(tagList)); if (!tagList.isEmpty()) { - tags.put(eigw.getEgressOnlyInternetGatewayId(), new ArrayList<>(tagList)); + putTags(region, eigw.getEgressOnlyInternetGatewayId(), new ArrayList<>(tagList)); } egressOnlyInternetGateways.put(key(region, eigw.getEgressOnlyInternetGatewayId()), eigw); return eigw; @@ -4894,7 +5074,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab "The eigw ID '" + eigwId + "' does not exist", 400); } egressOnlyInternetGateways.delete(key(region, eigwId)); - tags.delete(eigwId); + removeTags(region, eigwId); } for (RouteTable table : routeTables.scan(k -> k.startsWith(region + "::"))) { if (table.getRoutes().stream().noneMatch(r -> eigwId.equals(r.getEgressOnlyInternetGatewayId()))) { @@ -4934,7 +5114,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab requireNoVpcDependents(region, vpcId); deleteVpcDefaultResources(region, vpcId); vpcs.delete(key(region, vpcId)); - tags.delete(vpcId); + removeTags(region, vpcId); } if (vpcNetworkManager != null) { vpcNetworkManager.deleteVpcNetwork(region, vpcId); @@ -5025,10 +5205,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab .toList(); ruleIds.forEach(ruleId -> { securityGroupRules.delete(key(region, ruleId)); - tags.delete(ruleId); + removeTags(region, ruleId); }); securityGroups.delete(key(region, group.getGroupId())); - tags.delete(group.getGroupId()); + removeTags(region, group.getGroupId()); } } @@ -5041,7 +5221,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab .toList(); mainRouteTableIds.forEach(routeTableId -> { routeTables.delete(key(region, routeTableId)); - tags.delete(routeTableId); + removeTags(region, routeTableId); }); List defaultNetworkAclIds = networkAcls.scan(k -> k.startsWith(region + "::")).stream() @@ -5052,7 +5232,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab .toList(); defaultNetworkAclIds.forEach(aclId -> { networkAcls.delete(key(region, aclId)); - tags.delete(aclId); + removeTags(region, aclId); }); } @@ -5289,7 +5469,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab endpoint.setPolicyDocument(policyDocument); if (endpointTags != null && !endpointTags.isEmpty()) { endpoint.setTags(new ArrayList<>(endpointTags)); - tags.put(endpoint.getVpcEndpointId(), new ArrayList<>(endpointTags)); + putTags(region, endpoint.getVpcEndpointId(), new ArrayList<>(endpointTags)); } synchronized (attachmentTopologyLock(region)) { getRequiredVpc(region, vpcId); @@ -5498,7 +5678,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab VpcEndpoint endpoint = getRequiredVpcEndpoint(region, endpointId); endpoint.setState("deleted"); vpcEndpoints.delete(key(region, endpointId)); - tags.delete(endpointId); + removeTags(region, endpointId); deleted.add(endpoint); } return deleted; @@ -7345,6 +7525,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab continue; } snapshots.delete(key(region, snapshotId)); + removeTags(region, snapshotId); results.add(new SnapshotDeletion(snapshotId, "success")); } return results; @@ -7491,7 +7672,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab launchTemplate.setData(new LaunchTemplateData(data != null ? data : new LaunchTemplateData())); if (launchTemplateTags != null && !launchTemplateTags.isEmpty()) { launchTemplate.setTags(new ArrayList<>(launchTemplateTags)); - tags.put(launchTemplate.getLaunchTemplateId(), new ArrayList<>(launchTemplateTags)); + putTags(region, launchTemplate.getLaunchTemplateId(), new ArrayList<>(launchTemplateTags)); } launchTemplate.getVersions().put("1", new LaunchTemplateData(launchTemplate.getData())); if (versionDescription != null && !versionDescription.isBlank()) { @@ -7809,7 +7990,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab ensureDefaultResources(region); LaunchTemplate launchTemplate = findLaunchTemplate(region, id, name); launchTemplates.delete(key(region, launchTemplate.getLaunchTemplateId())); - tags.delete(launchTemplate.getLaunchTemplateId()); + removeTags(region, launchTemplate.getLaunchTemplateId()); return launchTemplate; } @@ -8029,7 +8210,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } private Image withCurrentImageTags(Image image) { - List currentTags = tags.get(image.getImageId()) + List currentTags = tagsOf(image.getRegion(), image.getImageId()) .orElseGet(() -> image.getTags() == null ? List.of() : image.getTags()); image.setTags(new ArrayList<>(currentTags)); // Persistent backends may return detached values from scan(), so do not rely on @@ -8152,7 +8333,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab for (String resourceId : resourceIds) { withTopologyLockIfNeeded(region, resourceId, () -> { synchronized (lockFor(key(region, resourceId))) { - List existing = new ArrayList<>(tags.get(resourceId).orElseGet(() -> { + List existing = new ArrayList<>(tagsOf(region, resourceId).orElseGet(() -> { Instance ext = findExternalInstance(callerAccountId(), region, resourceId).orElse(null); return ext != null && ext.getTags() != null ? ext.getTags() : List.of(); })); @@ -8160,7 +8341,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab existing.removeIf(t -> t.getKey().equals(tag.getKey())); existing.add(tag); } - tags.put(resourceId, existing); + putTags(region, resourceId, existing); // Update resource objects updateResourceTags(region, resourceId, existing); } @@ -8190,7 +8371,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab for (String resourceId : resourceIds) { withTopologyLockIfNeeded(region, resourceId, () -> { synchronized (lockFor(key(region, resourceId))) { - List stored = tags.get(resourceId).orElseGet(() -> { + List stored = tagsOf(region, resourceId).orElseGet(() -> { Instance ext = findExternalInstance(callerAccountId(), region, resourceId).orElse(null); return ext != null && ext.getTags() != null ? ext.getTags() : null; }); @@ -8203,7 +8384,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab existing.removeIf(t -> t.getKey().equals(tag.getKey()) && (tag.getValue() == null || tag.getValue().equals(t.getValue()))); } - tags.put(resourceId, existing); + putTags(region, resourceId, existing); updateResourceTags(region, resourceId, existing); } } @@ -8276,6 +8457,24 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab managedPrefixLists.put(storeKey, prefixList); return; } + Volume volume = volumes.get(storeKey).orElse(null); + if (volume != null) { + volume.setTags(new ArrayList<>(tagList)); + volumes.put(storeKey, volume); + return; + } + Snapshot snapshot = snapshots.get(storeKey).orElse(null); + if (snapshot != null) { + snapshot.setTags(new ArrayList<>(tagList)); + snapshots.put(storeKey, snapshot); + return; + } + SpotInstanceRequest spotRequest = spotInstanceRequests.get(storeKey).orElse(null); + if (spotRequest != null) { + spotRequest.setTags(new ArrayList<>(tagList)); + spotInstanceRequests.put(storeKey, spotRequest); + return; + } // Reached with the topology lock already held for tgw- resources, so the read-modify-write // below cannot put back something a concurrent delete has just removed. { @@ -8299,9 +8498,30 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } } - /** The tags currently on one resource, as CreateTags and DeleteTags maintain them. */ - public List resourceTags(String resourceId) { - return List.copyOf(tags.get(resourceId).orElse(List.of())); + // Tags are regional, like the resources they label: one entry per region::id, so a tag set in + // one region is never listed, read or removed from another. + + private Optional> tagsOf(String region, String resourceId) { + return tags.get(key(region, resourceId)); + } + + private Optional> tagsOf(String accountId, String region, String resourceId) { + return tags instanceof AccountAwareStorageBackend> aware + ? aware.getForAccount(accountId, key(region, resourceId)) + : tagsOf(region, resourceId); + } + + private void putTags(String region, String resourceId, List resourceTags) { + tags.put(key(region, resourceId), resourceTags); + } + + private void removeTags(String region, String resourceId) { + tags.delete(key(region, resourceId)); + } + + /** The tags currently on one resource in {@code region}, as CreateTags and DeleteTags maintain them. */ + public List resourceTags(String region, String resourceId) { + return List.copyOf(tagsOf(region, resourceId).orElse(List.of())); } public List> describeTags(String region, Map> filters) { @@ -8313,7 +8533,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab List> result = new ArrayList<>(); Set processedResourceIds = new LinkedHashSet<>(); - for (String resourceId : new ArrayList<>(tags.keys())) { + String regionPrefix = region + "::"; + for (String tagKey : new ArrayList<>(tags.keys())) { + if (!tagKey.startsWith(regionPrefix)) { + continue; + } + String resourceId = tagKey.substring(regionPrefix.length()); processedResourceIds.add(resourceId); String resourceType = inferResourceType(resourceId); @@ -8323,7 +8548,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (filterResourceTypes != null && !filterResourceTypes.contains(resourceType)) { continue; } - for (Tag tag : tags.get(resourceId).orElse(List.of())) { + for (Tag tag : tagsOf(region, resourceId).orElse(List.of())) { if (filterKeys != null && !filterKeys.contains(tag.getKey())) { continue; } @@ -8431,6 +8656,24 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (resourceId.startsWith("tgw-")) { return "transit-gateway"; } + if (resourceId.startsWith("ami-")) { + return "image"; + } + if (resourceId.startsWith("vol-")) { + return "volume"; + } + if (resourceId.startsWith("snap-")) { + return "snapshot"; + } + if (resourceId.startsWith("acl-")) { + return "network-acl"; + } + if (resourceId.startsWith("pcx-")) { + return "vpc-peering-connection"; + } + if (resourceId.startsWith("sir-")) { + return "spot-instances-request"; + } return "unknown"; } @@ -9319,6 +9562,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab "Pending Acceptance by " + accepterOwnerId)); if (peeringTags != null) { pcx.setTags(new ArrayList<>(peeringTags)); + // Tags on create are tags like any other: DescribeTags lists them in this region. + putTags(region, pcxId, new ArrayList<>(peeringTags)); } vpcPeeringConnections.put(pcxId, pcx); @@ -9431,10 +9676,35 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab .filter(pcx -> visibleToAccount(pcx, caller)) .filter(pcx -> visibleFromRegion(pcx, region)) .filter(pcx -> ids.isEmpty() || ids.contains(pcx.getVpcPeeringConnectionId())) + .map(pcx -> withStoredTags(pcx, caller, region)) .filter(pcx -> matchesFilters(pcx, filters, region)) .collect(Collectors.toList()); } + /** + * A peering connection's tags as the caller sees them from {@code region}: each side tags it in + * its own account and region. A connection recorded before its create-time tags reached the tag + * store keeps showing those to its requester. + */ + private VpcPeeringConnection withStoredTags(VpcPeeringConnection pcx, String caller, String region) { + String id = pcx.getVpcPeeringConnectionId(); + VpcPeeringConnectionVpcInfo requester = pcx.getRequesterVpcInfo(); + boolean requesterSide = requester != null && caller.equals(requester.getOwnerId()) + && region.equals(requester.getRegion()); + List fallback = requesterSide && pcx.getTags() != null ? pcx.getTags() : List.of(); + // A copy, so one side's view never reaches the stored connection the other side reads. + VpcPeeringConnection view = new VpcPeeringConnection(); + view.setVpcPeeringConnectionId(id); + view.setRegion(pcx.getRegion()); + view.setRequesterVpcInfo(requester); + view.setAccepterVpcInfo(pcx.getAccepterVpcInfo()); + view.setStatus(pcx.getStatus()); + view.setAccepterAllowRemoteVpcDnsResolution(pcx.isAccepterAllowRemoteVpcDnsResolution()); + view.setRequesterAllowRemoteVpcDnsResolution(pcx.isRequesterAllowRemoteVpcDnsResolution()); + view.setTags(new ArrayList<>(tagsOf(region, id).orElse(fallback))); + return view; + } + public VpcPeeringConnection acceptVpcPeeringConnection(String region, String vpcPeeringConnectionId) { synchronized (lockFor(vpcPeeringConnectionId)) { OwnedVpcPeeringConnection owned = getRequiredOwnedVpcPeeringConnection(vpcPeeringConnectionId); @@ -9556,6 +9826,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } private void deleteVpcPeeringConnection(OwnedVpcPeeringConnection owned) { + removePeeringConnectionTags(owned.pcx()); if (owned.storageAccountId() != null && vpcPeeringConnections instanceof AccountAwareStorageBackend rawAccountAware) { @SuppressWarnings("unchecked") @@ -9567,6 +9838,21 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab vpcPeeringConnections.delete(owned.pcx().getVpcPeeringConnectionId()); } + /** Each side tags a peering connection in its own account and region; both go with it. */ + private void removePeeringConnectionTags(VpcPeeringConnection pcx) { + String id = pcx.getVpcPeeringConnectionId(); + for (VpcPeeringConnectionVpcInfo side : List.of(pcx.getRequesterVpcInfo(), pcx.getAccepterVpcInfo())) { + if (side == null || side.getRegion() == null) { + continue; + } + if (tags instanceof AccountAwareStorageBackend tagsByAccount && side.getOwnerId() != null) { + tagsByAccount.deleteForAccount(side.getOwnerId(), key(side.getRegion(), id)); + } else { + removeTags(side.getRegion(), id); + } + } + } + private static AwsException vpcPeeringConnectionNotFound(String vpcPeeringConnectionId) { return new AwsException("InvalidVpcPeeringConnectionID.NotFound", "The VPC peering connection ID '" + vpcPeeringConnectionId + "' does not exist", 400); @@ -9654,7 +9940,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } if (natGatewayTags != null && !natGatewayTags.isEmpty()) { natGateway.setTags(new ArrayList<>(natGatewayTags)); - tags.put(natGateway.getNatGatewayId(), new ArrayList<>(natGatewayTags)); + putTags(region, natGateway.getNatGatewayId(), new ArrayList<>(natGatewayTags)); } natGateways.put(key(region, natGateway.getNatGatewayId()), natGateway); } @@ -9767,8 +10053,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab }); } natGateways.delete(key(region, natGatewayId)); - tags.delete(natGatewayId); - natGateway.getNatGatewayAddresses().forEach(a -> tags.delete(a.getNetworkInterfaceId())); + removeTags(region, natGatewayId); + natGateway.getNatGatewayAddresses().forEach(a -> removeTags(region, a.getNetworkInterfaceId())); } return natGateway; } @@ -10710,7 +10996,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab vol.setCreateTime(Instant.now()); vol.setState("available"); vol.setRegion(region); - if (volumeTags != null) vol.setTags(new ArrayList<>(volumeTags)); + if (volumeTags != null) { + vol.setTags(new ArrayList<>(volumeTags)); + // Tags on create are tags like any other: DescribeTags lists them in this region. + putTags(region, vol.getVolumeId(), new ArrayList<>(volumeTags)); + } volumes.put(key(region, volumeId), vol); if (volumeBlockDeviceManager != null) { volumeBlockDeviceManager.createVolume(volumeId, vol.getSize()); @@ -10755,6 +11045,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } } volumes.delete(key(region, volumeId)); + removeTags(region, volumeId); }); } @@ -11195,9 +11486,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab // resource. Read the interface's own entry in the tag store instead: // CreateTags on the eni- id writes it, and so does a RunInstances // TagSpecification with ResourceType=network-interface. - Optional> tagList = tags instanceof AccountAwareStorageBackend> aware - ? aware.getForAccount(safeAccount, eni.getNetworkInterfaceId()) - : tags.get(eni.getNetworkInterfaceId()); + Optional> tagList = tagsOf(safeAccount, region, eni.getNetworkInterfaceId()); ni.getTagSet().addAll(tagList.orElse(List.of())); NetworkInterfaceAttachment att = new NetworkInterfaceAttachment(); @@ -11322,8 +11611,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab continue; } foundIds.add(natEniId); - natNi.getTagSet().addAll((tags instanceof AccountAwareStorageBackend> aware - ? aware.getForAccount(safeAccount, natEniId) : tags.get(natEniId)).orElse(List.of())); + natNi.getTagSet().addAll(tagsOf(safeAccount, region, natEniId).orElse(List.of())); if (!matchesFilters(natNi, filters, region)) { continue; } @@ -11636,6 +11924,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab volumeBlockDeviceManager.deleteVolume(vol.getVolumeId()); } volumes.delete(k); + removeTags(region, vol.getVolumeId()); modified = false; break; } else { @@ -11810,7 +12099,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (spotRequestTags != null && !spotRequestTags.isEmpty()) { sir.setTags(new ArrayList<>(spotRequestTags)); - tags.put(spotRequestId, new ArrayList<>(spotRequestTags)); + putTags(region, spotRequestId, new ArrayList<>(spotRequestTags)); } spotInstanceRequests.put(key(region, spotRequestId), sir); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java index 56c45b82b5..eb0f9f8f28 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java @@ -209,7 +209,7 @@ class IamConditionContextResolverTest { query.add("Tag.1.Key", "Team"); query.add("Tag.1.Value", "A+B%2F"); query.add("Tag.1.Value", "ignored"); - when(ec2Service.resourceTags("i-target")).thenReturn(List.of(new Tag("Owner", "alice"))); + when(ec2Service.resourceTags("us-east-1", "i-target")).thenReturn(List.of(new Tag("Owner", "alice"))); Map> conditions = resolver.resolve( "ec2", "ec2:CreateTags", queryRequest("ec2", query)); assertEquals(List.of("A+B%2F"), conditions.get("aws:RequestTag/Team")); @@ -672,7 +672,7 @@ class IamConditionContextResolverTest { @Test void createTagsResolvesBothTheRequestedTagsAndTheResourcesCurrentTags() { - when(ec2Service.resourceTags("i-0123456789")).thenReturn(List.of(new Tag("Owner", "alice"))); + when(ec2Service.resourceTags("us-east-1", "i-0123456789")).thenReturn(List.of(new Tag("Owner", "alice"))); ContainerRequestContext containerRequest = formRequest( "Action=CreateTags&ResourceId.1=i-0123456789&Tag.1.Key=Env&Tag.1.Value=prod"); @@ -685,7 +685,7 @@ class IamConditionContextResolverTest { @Test void instanceActionsResolveResourceTagsFromTheFirstNamedInstance() { - when(ec2Service.resourceTags("i-0123456789")).thenReturn(List.of(new Tag("Team", "payments"))); + when(ec2Service.resourceTags("us-east-1", "i-0123456789")).thenReturn(List.of(new Tag("Team", "payments"))); for (String action : List.of("ec2:TerminateInstances", "ec2:DescribeInstances")) { Map> conditions = resolver.resolve("ec2", action, @@ -698,6 +698,16 @@ class IamConditionContextResolverTest { .get("aws:ResourceTag/Team")); } + @Test + void resourceTagsAreReadInTheRequestRegion() { + requestContext.setRegion("eu-west-1"); + when(ec2Service.resourceTags("eu-west-1", "i-0123456789")).thenReturn(List.of(new Tag("Team", "payments"))); + when(ec2Service.resourceTags("us-east-1", "i-0123456789")).thenReturn(List.of(new Tag("Team", "other"))); + + assertEquals(List.of("payments"), resolver.resolve("ec2", "ec2:TerminateInstances", + formRequest("Action=TerminateInstances&InstanceId.1=i-0123456789")).get("aws:ResourceTag/Team")); + } + @Test void ec2ContextIsAbsentWhenNoResourceIsNamedOrTheActionIsNotCovered() { assertNull(resolver.resolve("ec2", "ec2:DescribeInstances", formRequest("Action=DescribeInstances"))); @@ -709,7 +719,7 @@ class IamConditionContextResolverTest { @Test void formParametersAreBufferedOncePerRequest() { ContainerRequestContext containerRequest = formRequest("Action=TerminateInstances&InstanceId.1=i-1"); - when(ec2Service.resourceTags("i-1")).thenReturn(List.of(new Tag("Team", "payments"))); + when(ec2Service.resourceTags("us-east-1", "i-1")).thenReturn(List.of(new Tag("Team", "payments"))); resolver.resolve("ec2", "ec2:TerminateInstances", containerRequest); @@ -730,12 +740,12 @@ class IamConditionContextResolverTest { ]}"""; String body = "Action=TerminateInstances&InstanceId.1=i-0123456789"; - when(ec2Service.resourceTags("i-0123456789")).thenReturn(List.of(new Tag("Team", "payments"))); + when(ec2Service.resourceTags("us-east-1", "i-0123456789")).thenReturn(List.of(new Tag("Team", "payments"))); assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(List.of(policy), "ec2:TerminateInstances", "*", resolver.resolve("ec2", "ec2:TerminateInstances", formRequest(body)))); - when(ec2Service.resourceTags("i-0123456789")).thenReturn(List.of(new Tag("Team", "engineering"))); + when(ec2Service.resourceTags("us-east-1", "i-0123456789")).thenReturn(List.of(new Tag("Team", "engineering"))); assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), "ec2:TerminateInstances", "*", resolver.resolve("ec2", "ec2:TerminateInstances", formRequest(body)))); @@ -778,9 +788,9 @@ class IamConditionContextResolverTest { @Test void remainingTargetsCarryEachLaterResourcesOwnTags() { - when(ec2Service.resourceTags("i-1")).thenReturn(List.of(new Tag("Team", "payments"))); - when(ec2Service.resourceTags("i-2")).thenReturn(List.of(new Tag("Team", "engineering"))); - when(ec2Service.resourceTags("i-3")).thenReturn(List.of()); + when(ec2Service.resourceTags("us-east-1", "i-1")).thenReturn(List.of(new Tag("Team", "payments"))); + when(ec2Service.resourceTags("us-east-1", "i-2")).thenReturn(List.of(new Tag("Team", "engineering"))); + when(ec2Service.resourceTags("us-east-1", "i-3")).thenReturn(List.of()); ContainerRequestContext containerRequest = formRequest( "Action=TerminateInstances&InstanceId.1=i-1&InstanceId.2=i-2&InstanceId.3=i-3"); @@ -795,7 +805,7 @@ class IamConditionContextResolverTest { @Test void remainingTargetsOfCreateTagsRepeatTheRequestedTagsPerResource() { - when(ec2Service.resourceTags("vpc-2")).thenReturn(List.of(new Tag("Owner", "bob"))); + when(ec2Service.resourceTags("us-east-1", "vpc-2")).thenReturn(List.of(new Tag("Owner", "bob"))); ContainerRequestContext containerRequest = formRequest( "Action=CreateTags&ResourceId.1=vpc-1&ResourceId.2=vpc-2&Tag.1.Key=Env&Tag.1.Value=prod"); @@ -825,19 +835,19 @@ class IamConditionContextResolverTest { "Condition":{"StringEquals":{"aws:ResourceTag/Team":"payments"}}} ]}"""; String body = "Action=TerminateInstances&InstanceId.1=i-1&InstanceId.2=i-2"; - when(ec2Service.resourceTags("i-1")).thenReturn(List.of(new Tag("Team", "payments"))); + when(ec2Service.resourceTags("us-east-1", "i-1")).thenReturn(List.of(new Tag("Team", "payments"))); - when(ec2Service.resourceTags("i-2")).thenReturn(List.of(new Tag("Team", "engineering"))); + when(ec2Service.resourceTags("us-east-1", "i-2")).thenReturn(List.of(new Tag("Team", "engineering"))); assertEquals(Decision.DENY, decisionForEveryTarget(policy, "ec2:TerminateInstances", formRequest(body))); - when(ec2Service.resourceTags("i-2")).thenReturn(List.of(new Tag("Team", "payments"))); + when(ec2Service.resourceTags("us-east-1", "i-2")).thenReturn(List.of(new Tag("Team", "payments"))); assertEquals(Decision.ALLOW, decisionForEveryTarget(policy, "ec2:TerminateInstances", formRequest(body))); } @Test void aRepeatedNumberedParameterKeepsItsFirstValueLikeTheHandlers() { - when(ec2Service.resourceTags("i-first")).thenReturn(List.of(new Tag("Team", "engineering"))); - when(ec2Service.resourceTags("i-second")).thenReturn(List.of(new Tag("Team", "payments"))); + when(ec2Service.resourceTags("us-east-1", "i-first")).thenReturn(List.of(new Tag("Team", "engineering"))); + when(ec2Service.resourceTags("us-east-1", "i-second")).thenReturn(List.of(new Tag("Team", "payments"))); Map> conditions = resolver.resolve("ec2", "ec2:TerminateInstances", formRequest("Action=TerminateInstances&InstanceId.1=i-first&InstanceId.1=i-second")); @@ -847,7 +857,7 @@ class IamConditionContextResolverTest { @Test void remainingTargetsStopAtTheFirstNumberingGapLikeTheHandlers() { - when(ec2Service.resourceTags("i-2")).thenReturn(List.of(new Tag("Team", "payments"))); + when(ec2Service.resourceTags("us-east-1", "i-2")).thenReturn(List.of(new Tag("Team", "payments"))); assertEquals(List.of(), resolver.resolveRemainingTargets("ec2", "ec2:TerminateInstances", formRequest("Action=TerminateInstances&InstanceId.2=i-2"))); @@ -862,8 +872,8 @@ class IamConditionContextResolverTest { {"Effect":"Allow","Action":"ec2:TerminateInstances","Resource":"*", "Condition":{"StringEquals":{"aws:ResourceTag/Team":"payments"}}} ]}"""; - when(ec2Service.resourceTags("i-denied")).thenReturn(List.of(new Tag("Team", "engineering"))); - when(ec2Service.resourceTags("i-allowed")).thenReturn(List.of(new Tag("Team", "payments"))); + when(ec2Service.resourceTags("us-east-1", "i-denied")).thenReturn(List.of(new Tag("Team", "engineering"))); + when(ec2Service.resourceTags("us-east-1", "i-allowed")).thenReturn(List.of(new Tag("Team", "payments"))); // The handler terminates i-denied, the first value, so that is what must be authorized. assertEquals(Decision.DENY, decisionForEveryTarget(policy, "ec2:TerminateInstances", diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DeregisterAndCopyImageIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DeregisterAndCopyImageIntegrationTest.java index 4fb1a3439f..6f7439c687 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DeregisterAndCopyImageIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DeregisterAndCopyImageIntegrationTest.java @@ -223,6 +223,18 @@ class Ec2DeregisterAndCopyImageIntegrationTest { () -> service.describeSnapshots(EAST, List.of(deletedSnapshot), null, null)); } + @Test + void aSnapshotDeletedWithItsImageTakesItsTags() { + Image image = service.registerImage(EAST, uniqueName("floci-tagged-snapshot"), null, + "x86_64", "/dev/xvda", List.of(mapping("/dev/xvda", "snap-" + hex()))); + String snapshotId = snapshotIdOf(image); + service.createTags(EAST, List.of(snapshotId), List.of(new Tag("Team", "snapshots"))); + + service.deregisterImage(EAST, image.getImageId(), true); + + assertTrue(service.describeTags(EAST, Map.of("resource-id", List.of(snapshotId))).isEmpty()); + } + @Test void aSnapshotSharedWithAnotherAmiIsSkippedRatherThanDeleted() { // "if a snapshot is associated with multiple AMIs, it won't be deleted even if specified diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index 8e88e0cc73..766bdec6da 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -666,6 +666,228 @@ class Ec2ServiceTest { } } + @Test + void describeTagsListsOnlyTheRequestRegionsTags() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + String east = service.createVpc("us-east-1", "10.80.0.0/16", false).getVpcId(); + String west = service.createVpc("eu-west-1", "10.81.0.0/16", false).getVpcId(); + service.createTags("us-east-1", List.of(east), List.of(new Tag("Team", "east"))); + service.createTags("eu-west-1", List.of(west), List.of(new Tag("Team", "west"))); + + assertEquals(List.of(east), tagResourceIds(service.describeTags("us-east-1", Map.of("key", List.of("Team"))))); + assertEquals(List.of(west), tagResourceIds(service.describeTags("eu-west-1", Map.of("key", List.of("Team"))))); + assertTrue(service.describeTags("eu-west-1", Map.of("resource-id", List.of(east))).isEmpty()); + assertTrue(service.resourceTags("eu-west-1", east).isEmpty()); + assertEquals("east", service.resourceTags("us-east-1", east).getFirst().getValue()); + } + + @Test + void tagsCarryTheResourceTypeOfImagesVolumesSnapshotsAclsPeeringsAndSpotRequests() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + Map expected = Map.of( + "ami-0abc12345678", "image", "vol-0abc12345678", "volume", "snap-0abc12345678", "snapshot", + "acl-0abc12345678", "network-acl", "pcx-0abc12345678", "vpc-peering-connection", + "sir-0abc12345678", "spot-instances-request"); + service.createSystemTags("us-east-1", List.copyOf(expected.keySet()), List.of(new Tag("Team", "typed"))); + + Map types = new HashMap<>(); + for (Map item : service.describeTags("us-east-1", Map.of("key", List.of("Team")))) { + types.put(item.get("resourceId"), item.get("resourceType")); + } + assertEquals(expected, types); + } + + @Test + void volumeTagsGivenAtCreationAreListedByDescribeTags() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + Volume volume = service.createVolume("us-east-1", "us-east-1a", "gp3", 8, + false, 0, null, null, List.of(new Tag("Team", "storage"))); + + List> listed = service.describeTags("us-east-1", + Map.of("resource-id", List.of(volume.getVolumeId()))); + assertEquals(1, listed.size()); + assertEquals("volume", listed.getFirst().get("resourceType")); + assertTrue(service.describeTags("eu-west-1", Map.of("resource-id", List.of(volume.getVolumeId()))).isEmpty()); + } + + @Test + void tagsStoredByBareIdMoveUnderTheirResourcesRegionAndOrphansAreDropped() { + AccountAwareStorageBackend> tagStore = AccountAwareStorageBackend.inMemory("000000000000"); + Ec2Service service = tagTestService(new InMemoryStorageFactory(Map.of("ec2-tags.json", tagStore))); + String vpcId = service.createVpc("eu-west-1", "10.82.0.0/16", false).getVpcId(); + tagStore.put(vpcId, new ArrayList<>(List.of(new Tag("Team", "legacy")))); + tagStore.put("vpc-0000dead0000", new ArrayList<>(List.of(new Tag("Team", "orphan")))); + + service.migrateTagsToRegionKeys(); + service.migrateTagsToRegionKeys(); + + assertEquals(List.of(vpcId), tagResourceIds(service.describeTags("eu-west-1", Map.of("key", List.of("Team"))))); + assertTrue(service.describeTags("us-east-1", Map.of("key", List.of("Team"))).isEmpty()); + assertTrue(tagStore.keys().stream().allMatch(storeKey -> storeKey.contains("::"))); + } + + @Test + void volumeTagChangesShowInDescribeVolumes() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + String volumeId = service.createVolume("us-east-1", "us-east-1a", "gp3", 8, + false, 0, null, null, List.of(new Tag("Team", "storage"))).getVolumeId(); + + service.createTags("us-east-1", List.of(volumeId), List.of(new Tag("Env", "dev"))); + service.deleteTags("us-east-1", List.of(volumeId), List.of(new Tag("Team", null))); + + List described = service.describeVolumes("us-east-1", List.of(volumeId), Map.of()).getFirst().getTags(); + assertEquals(List.of("Env"), described.stream().map(Tag::getKey).toList()); + } + + @Test + void eachSideOfACrossRegionPeeringConnectionSeesItsOwnTags() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + String eastVpc = service.createVpc("us-east-1", "10.83.0.0/16", false).getVpcId(); + String westVpc = service.createVpc("eu-west-1", "10.84.0.0/16", false).getVpcId(); + String pcxId = service.createVpcPeeringConnection("us-east-1", eastVpc, westVpc, null, "eu-west-1", + List.of(new Tag("Side", "requester"))).getVpcPeeringConnectionId(); + service.createTags("eu-west-1", List.of(pcxId), List.of(new Tag("Side", "accepter"))); + + assertEquals("requester", peeringTag(service, "us-east-1", pcxId)); + assertEquals("accepter", peeringTag(service, "eu-west-1", pcxId)); + assertEquals(List.of(pcxId), tagResourceIds(service.describeTags("us-east-1", Map.of("key", List.of("Side"))))); + assertEquals("requester", peeringTag(service, "us-east-1", pcxId)); + } + + private static String peeringTag(Ec2Service service, String region, String pcxId) { + return service.describeVpcPeeringConnections(region, List.of(pcxId), Map.of()).getFirst().getTags().stream() + .filter(tag -> "Side".equals(tag.getKey())).map(Tag::getValue).findFirst().orElse(null); + } + + @Test + void aDeletedVolumesTagsAreNoLongerListed() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + String volumeId = service.createVolume("us-east-1", "us-east-1a", "gp3", 8, + false, 0, null, null, List.of(new Tag("Team", "storage"))).getVolumeId(); + service.createTags("us-east-1", List.of(volumeId), List.of(new Tag("Env", "dev"))); + + service.deleteVolume("us-east-1", volumeId); + + assertTrue(service.describeTags("us-east-1", Map.of("resource-id", List.of(volumeId))).isEmpty()); + } + + @Test + void aRootVolumeDeletedOnTerminationTakesItsTags() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + Instance inst = service.runInstances("us-east-1", "ami-1234567890abcdef0", "t3.micro", + 1, 1, null, List.of(), null, null, List.of(), null, null).getInstances().getFirst(); + String rootVolumeId = inst.getRootVolumeId(); + service.createTags("us-east-1", List.of(rootVolumeId), List.of(new Tag("Team", "root"))); + + service.terminateInstances("us-east-1", List.of(inst.getInstanceId())); + + assertTrue(service.describeVolumes("us-east-1", List.of(), Map.of()).stream() + .noneMatch(volume -> rootVolumeId.equals(volume.getVolumeId()))); + assertTrue(service.describeTags("us-east-1", Map.of("resource-id", List.of(rootVolumeId))).isEmpty()); + } + + @Test + void deletingAPeeringConnectionRemovesBothSidesTags() { + Ec2Service service = tagTestService(new InMemoryStorageFactory()); + String eastVpc = service.createVpc("us-east-1", "10.89.0.0/16", false).getVpcId(); + String westVpc = service.createVpc("eu-west-1", "10.90.0.0/16", false).getVpcId(); + String pcxId = service.createVpcPeeringConnection("us-east-1", eastVpc, westVpc, null, "eu-west-1", + List.of(new Tag("Side", "requester"))).getVpcPeeringConnectionId(); + service.createTags("eu-west-1", List.of(pcxId), List.of(new Tag("Side", "accepter"))); + + service.deleteVpcPeeringConnection("eu-west-1", pcxId); + + assertTrue(service.describeTags("us-east-1", Map.of("resource-id", List.of(pcxId))).isEmpty()); + assertTrue(service.describeTags("eu-west-1", Map.of("resource-id", List.of(pcxId))).isEmpty()); + } + + @Test + void migrationKeepsCatalogImageAndClusterNodeTags() { + AccountAwareStorageBackend> tagStore = AccountAwareStorageBackend.inMemory("000000000000"); + EmulatorConfig config = mockConfig(true); + when(config.defaultRegion()).thenReturn("us-east-1"); + Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog(); + Ec2Service service = new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class), + new AmiImageResolver(imageCatalog), imageCatalog, new Ec2InstanceTypeCatalog(), + new InMemoryStorageFactory(Map.of("ec2-tags.json", tagStore))); + String catalogImageId = imageCatalog.images().getFirst().imageId; + String nodeId = "i-0de0000000000001a"; + tagStore.put(catalogImageId, new ArrayList<>(List.of(new Tag("Team", "image")))); + tagStore.put(nodeId, new ArrayList<>(List.of(new Tag("Team", "node")))); + tagStore.put("vpc-0000dead0000", new ArrayList<>(List.of(new Tag("Team", "orphan")))); + + service.migrateTagsToRegionKeys(); + + assertEquals(List.of(catalogImageId), + tagResourceIds(service.describeTags("us-east-1", Map.of("key", List.of("Team"))))); + assertTrue(tagStore.keys().contains(nodeId)); + assertFalse(tagStore.keys().contains("vpc-0000dead0000")); + + Instance node = new Instance(); + node.setInstanceId(nodeId); + node.setRegion("eu-west-1"); + node.setPlacement(new Placement("eu-west-1a")); + node.setState(InstanceState.running()); + node.setInstanceType("m5.large"); + service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() { + @Override + public Optional findInstance(String accountId, String region, String instanceId) { + return nodeId.equals(instanceId) && "eu-west-1".equals(region) ? Optional.of(node) : Optional.empty(); + } + + @Override + public List listInstances(String accountId, String region) { + return "eu-west-1".equals(region) ? List.of(node) : List.of(); + } + }); + + assertEquals("node", service.describeInstances("eu-west-1", List.of(nodeId), Map.of()).getFirst() + .getInstances().getFirst().getTags().getFirst().getValue()); + assertEquals(List.of(nodeId), tagResourceIds(service.describeTags("eu-west-1", Map.of("key", List.of("Team"))))); + assertFalse(tagStore.keys().contains(nodeId)); + } + + @Test + void regionlessLookupFilesClusterNodeTagsUnderTheNodesRegion() { + AccountAwareStorageBackend> tagStore = AccountAwareStorageBackend.inMemory("000000000000"); + Ec2Service service = tagTestService(new InMemoryStorageFactory(Map.of("ec2-tags.json", tagStore))); + String nodeId = "i-0de0000000000002b"; + tagStore.put(nodeId, new ArrayList<>(List.of(new Tag("Team", "node")))); + service.migrateTagsToRegionKeys(); + Instance node = new Instance(); + node.setInstanceId(nodeId); + node.setRegion("eu-west-1"); + node.setPlacement(new Placement("eu-west-1a")); + node.setState(InstanceState.running()); + node.setInstanceType("m5.large"); + service.setClusterNodeInstanceProvider(new ClusterNodeInstanceProvider() { + @Override + public Optional findInstance(String accountId, String region, String instanceId) { + return nodeId.equals(instanceId) && (region == null || "eu-west-1".equals(region)) + ? Optional.of(node) : Optional.empty(); + } + + @Override + public List listInstances(String accountId, String region) { + return region == null || "eu-west-1".equals(region) ? List.of(node) : List.of(); + } + }); + + assertEquals("node", service.findInstanceById(nodeId).getTags().getFirst().getValue()); + + assertEquals(List.of(nodeId), tagResourceIds(service.describeTags("eu-west-1", Map.of("key", List.of("Team"))))); + assertFalse(tagStore.keys().contains("null::" + nodeId)); + } + + private static Ec2Service tagTestService(StorageFactory storageFactory) { + return new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class), + mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), storageFactory); + } + + private static List tagResourceIds(List> items) { + return items.stream().map(item -> item.get("resourceId")).distinct().toList(); + } + @Test void deleteVpcRemovesItsOwnTagsAndThoseOnItsDefaultResources() { Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TagRegionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TagRegionIntegrationTest.java new file mode 100644 index 0000000000..e961473e5e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TagRegionIntegrationTest.java @@ -0,0 +1,54 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** EC2 tags are regional: a tag set in one region is listed only there, over the Query API. */ +@QuarkusTest +class Ec2TagRegionIntegrationTest { + + private static final String EAST_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request"; + private static final String WEST_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/eu-west-1/ec2/aws4_request"; + + private XmlPath ec2(String auth, String action, String... formParams) { + RequestSpecification req = given().formParam("Action", action).header("Authorization", auth); + for (int i = 0; i < formParams.length; i += 2) { + req = req.formParam(formParams[i], formParams[i + 1]); + } + return req.when().post("/").then().statusCode(200).extract().xmlPath(); + } + + @Test + void describeTagsListsOnlyTheRequestRegionsTags() { + String east = ec2(EAST_AUTH, "CreateVpc", "CidrBlock", "10.90.0.0/16").getString("CreateVpcResponse.vpc.vpcId"); + String west = ec2(WEST_AUTH, "CreateVpc", "CidrBlock", "10.91.0.0/16").getString("CreateVpcResponse.vpc.vpcId"); + try { + ec2(EAST_AUTH, "CreateTags", "ResourceId.1", east, "Tag.1.Key", "RegionProbe", "Tag.1.Value", "east"); + ec2(WEST_AUTH, "CreateTags", "ResourceId.1", west, "Tag.1.Key", "RegionProbe", "Tag.1.Value", "west"); + + assertEquals(List.of(east), probedIds(EAST_AUTH)); + assertEquals(List.of(west), probedIds(WEST_AUTH)); + XmlPath otherRegion = ec2(WEST_AUTH, "DescribeTags", + "Filter.1.Name", "resource-id", "Filter.1.Value.1", east); + assertTrue(otherRegion.getList("DescribeTagsResponse.tagSet.item.resourceId").isEmpty()); + } finally { + ec2(EAST_AUTH, "DeleteVpc", "VpcId", east); + ec2(WEST_AUTH, "DeleteVpc", "VpcId", west); + } + } + + private List probedIds(String auth) { + return ec2(auth, "DescribeTags", "Filter.1.Name", "key", "Filter.1.Value.1", "RegionProbe") + .getList("DescribeTagsResponse.tagSet.item.resourceId", String.class); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamEnforcementIntegrationTest.java index b6c1a26187..00b8189785 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamEnforcementIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamEnforcementIntegrationTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.iam; import io.github.hectorvent.floci.core.common.IamConditionContextResolver; +import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ec2.model.Tag; import io.github.hectorvent.floci.services.ec2.model.Vpc; @@ -47,6 +48,9 @@ class IamEnforcementIntegrationTest { @Inject S3Service s3Service; + @Inject + RequestContext requestContext; + // ========================================================================= // IamPolicyEvaluator — basic allow / deny / implicit-deny // ========================================================================= @@ -290,6 +294,28 @@ class IamEnforcementIntegrationTest { ec2Request("Action=DeleteTags&ResourceId.1=" + other.getVpcId() + "&Tag.1.Key=Team")))); } + @Test + void resourceTagConditionReadsTheTagsOfTheRequestRegion() { + Vpc west = ec2Service.createVpc("eu-west-1", "10.46.0.0/16", false); + ec2Service.createTags("eu-west-1", List.of(west.getVpcId()), List.of(new Tag("Team", "payments"))); + String deleteTeamTag = "Action=DeleteTags&ResourceId.1=" + west.getVpcId() + "&Tag.1.Key=Team"; + String previousRegion = requestContext.getRegion(); + try { + requestContext.setRegion("eu-west-1"); + assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy( + List.of(TEAM_SCOPED_EC2_POLICY), "ec2:DeleteTags", "*", + conditionContextResolver.resolve("ec2", "ec2:DeleteTags", ec2Request(deleteTeamTag)))); + + requestContext.setRegion("us-east-1"); + assertEquals(Decision.DENY, evaluator.simulateCustomPolicy( + List.of(TEAM_SCOPED_EC2_POLICY), "ec2:DeleteTags", "*", + conditionContextResolver.resolve("ec2", "ec2:DeleteTags", ec2Request(deleteTeamTag)))); + } finally { + requestContext.setRegion(previousRegion); + ec2Service.deleteVpc("eu-west-1", west.getVpcId()); + } + } + @Test void aMultiResourceRequestIsAuthorizedOncePerResource() { Vpc payments = ec2Service.createVpc("us-east-1", "10.44.0.0/16", false);