diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 6a04ce7979..3d88b0c9c1 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -1337,6 +1337,13 @@ so they go when it is deleted. `DeleteNetworkInterfacePermission` is not served. #### Interface and VPC endpoint IAM resources +Resource-tag conditions use each concrete ID-bearing resource ARN's stored tags. The lookup follows the +ARN's account and Region; an omitted account, as on an image ARN, uses the caller's account. +An untagged resource does not inherit another resource's tags. Wildcard resources retain their +existing request context. Name-based resources retain their existing lookup path. Generated tag +prefixes and per-target checks remain in effect. + + With IAM enforcement enabled, the generated request-resource catalog checks interface and VPC endpoint operations on their resource ARNs. Creating an interface also names its subnet and security groups; creating an endpoint also names its VPC, subnets, security groups and route tables. diff --git a/docs/services/iam.md b/docs/services/iam.md index 150029055e..bf486ad35c 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3494,6 +3494,10 @@ current stored tags under `aws:ResourceTag/` and `ec2:ResourceTag/`. Tags are re resolved ARN independently; request tags do not replace ownership tags on an existing VPC. The prefixes come from the generated `resourceTagKeys` table in `iam-request-resources.json`, derived from the Service Reference; new keys belong in the generator rather than Java branches. +For an EC2 ARN naming a concrete resource ID, stored tags are read in the account and Region the ARN names, with +caller values for omitted fields. This includes account-less image ARNs. The tag lookup does +not grant cross-account access or change the operation's resource-ownership requirements. + EC2 tagging targets come from `regen_iam_request_resources.py`, with EC2 among its namespaces. The Service Reference supplies the resource types and ARN formats, botocore supplies the diff --git a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java index c61e5d1b44..0c8304db26 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -1057,8 +1057,8 @@ public class IamConditionContextResolver { } /** - * The stored tags and the generated resource keys of one generated EC2 ARN (see {@link #putResourceKeys}), never - * borrowed from another target in the same request. + * The generated record keys of one EC2 ARN (see {@link #putResourceKeys}), retaining their caller-scoped + * lookup. Clear earlier generated tag keys before the shared {@link #resourceTags} path reads this ARN. */ public Map> withEc2ResourceContext(String scope, String action, String resource, String region, String accountId, @@ -1068,25 +1068,24 @@ public class IamConditionContextResolver { return context; } AwsArnUtils.Arn arn = AwsArnUtils.parse(resource); - // A snapshot's and an image's ARN carries no account (arn:aws:ec2:::snapshot/), which is not a - // foreign one: EC2 reads the id in the caller's account, as it reads every other one. - if (!"ec2".equals(arn.service()) || !region.equals(arn.region()) - || AwsArnUtils.isForeignAccount(arn, accountId)) { + if (!"ec2".equals(arn.service())) { return context; } + String resourceRegion = arn.region().isEmpty() ? region : arn.region(); + String resourceAccount = arn.accountId().isEmpty() ? accountId : arn.accountId(); String[] parts = arn.resource().split("/", 2); if (parts.length != 2 || parts[1].contains("*") || parts[1].contains("?")) { return context; } List prefixes = RequestResourceMembers.table().resourceTagKeys() .getOrDefault("ec2", Map.of()).getOrDefault(parts[0], List.of()); - Map keys = ec2ResourceKeys(parts[0]); + boolean callerResource = region.equals(resourceRegion) && accountId.equals(resourceAccount); + Map keys = callerResource ? ec2ResourceKeys(parts[0]) : Map.of(); if (prefixes.isEmpty() && keys.isEmpty()) { return context; } Map> result = context == null ? new LinkedHashMap<>() : new LinkedHashMap<>(context); result.keySet().removeIf(key -> prefixes.stream().anyMatch(key::startsWith) || keys.containsKey(key)); - putStoredTags(result, region, parts[1], prefixes); if (!keys.isEmpty()) { putResourceKeys(result, region, parts[0], ec2Service.get().heldResources(region, parts[0], List.of(parts[1])).get(parts[1])); diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index 19f20bf623..9ab8fc8b5d 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -12007,6 +12007,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return List.copyOf(tagsOf(region, resourceId).orElse(List.of())); } + /** The tags currently on one resource in the account and Region its ARN names. */ + public List resourceTags(String accountId, String region, String resourceId) { + return List.copyOf(tagsOf(accountId, region, resourceId).orElse(List.of())); + } + /** Every tag in {@code region} that matches {@code filters}, unpaged. */ public List> describeTags(String region, Map> filters) { List>> filterList = filters != null diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2StoredResourceArns.java b/src/main/java/io/floci/aws/services/ec2/Ec2StoredResourceArns.java index 35e41e8980..e7f879ceaf 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2StoredResourceArns.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2StoredResourceArns.java @@ -1,22 +1,28 @@ package io.floci.aws.services.ec2; import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.StoredResourceArns; +import io.floci.aws.services.ec2.model.Tag; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Optional; -/** Resolves the caller's launch-template names and network-interface attachments to resource ARNs. */ +/** Resolves EC2 names and attachments and reads the tags of the resource an ARN names. */ @ApplicationScoped public class Ec2StoredResourceArns implements StoredResourceArns { private final Ec2Service ec2; + private final RegionResolver regionResolver; @Inject - public Ec2StoredResourceArns(Ec2Service ec2) { + public Ec2StoredResourceArns(Ec2Service ec2, RegionResolver regionResolver) { this.ec2 = ec2; + this.regionResolver = regionResolver; } @Override @@ -24,6 +30,25 @@ public class Ec2StoredResourceArns implements StoredResourceArns { return "ec2"; } + @Override + public Map storedTags(String resource) { + if (!AwsArnUtils.isArn(resource)) { + return Map.of(); + } + AwsArnUtils.Arn arn = AwsArnUtils.parse(resource); + String[] parts = arn.resource().split("/", 2); + if (!"ec2".equals(arn.service()) || parts.length != 2 || parts[1].isEmpty() + || resource.contains("*") || resource.contains("?")) { + return Map.of(); + } + String account = arn.accountId().isEmpty() ? regionResolver.getAccountId() : arn.accountId(); + Map tags = new LinkedHashMap<>(); + for (Tag tag : ec2.resourceTags(account, arn.region(), parts[1])) { + tags.put(tag.getKey(), tag.getValue() == null ? "" : tag.getValue()); + } + return tags; + } + @Override public Optional findByMembers(String type, List names, String region) { if (("instance".equals(type) || "network-interface".equals(type)) && names.size() == 1) { diff --git a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java index f027eeb7dc..a7feb23573 100644 --- a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java @@ -3,14 +3,22 @@ package io.floci.aws.core.common; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.dynamodb.DynamoDbFacade; import io.floci.aws.services.dynamodb.DynamoDbService; import io.floci.aws.services.dynamodb.backend.NativeDynamoDbBackend; import io.floci.aws.services.dynamodb.model.KeySchemaElement; import io.floci.aws.services.dynamodb.model.TableDefinition; +import io.floci.aws.services.ec2.AmiImageResolver; +import io.floci.aws.services.ec2.Ec2ContainerManager; +import io.floci.aws.services.ec2.Ec2ImageCatalog; +import io.floci.aws.services.ec2.Ec2InstanceTypeCatalog; import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.ec2.Ec2StoredResourceArns; import io.floci.aws.services.ec2.model.NetworkInterface; import io.floci.aws.services.ec2.model.Tag; +import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager; import io.floci.aws.services.iam.IamPolicyEvaluator; import io.floci.aws.services.iam.IamPolicyEvaluator.Decision; import io.floci.aws.services.iam.IamService; @@ -855,6 +863,157 @@ class IamConditionContextResolverTest { null, serviceCatalog, Clock.systemUTC()); } + @Test + void ec2MainPortAccountlessImageReadsCallerTags() { + when(ec2Service.resourceTags("123456789012", "us-east-1", "ami-0123456789")) + .thenReturn(List.of(new Tag("Team", "payments"))); + Map> context = ec2ResourceContext(resolver, "ec2", "ec2:ModifyImageAttribute", + "arn:aws:ec2:us-east-1::image/ami-0123456789", "us-east-1", "123456789012", Map.of()); + assertEquals(List.of("payments"), context.get("aws:ResourceTag/Team")); + } + + @Test + void ec2MainPortAccountlessImageRetainsGeneratedResourceKeys() { + String image = "ami-0123456789"; + when(ec2Service.resourceTags("123456789012", "us-east-1", image)) + .thenReturn(List.of(new Tag("Team", "payments"))); + when(ec2Service.heldResources("us-east-1", "image", List.of(image))).thenReturn(Map.of(image, + Map.of("ImageId", image, "OwnerId", "123456789012", "Public", false))); + Map> context = ec2ResourceContext(resolver, "ec2", "ec2:ModifyImageAttribute", + "arn:aws:ec2:us-east-1::image/" + image, "us-east-1", "123456789012", + Map.of("ec2:Owner", List.of("stale"), "ec2:Public", List.of("true"), + "aws:ResourceTag/Team", List.of("stale"))); + assertEquals(List.of(image), context.get("ec2:ImageID")); + assertEquals(List.of("123456789012"), context.get("ec2:Owner")); + assertEquals(List.of("false"), context.get("ec2:Public")); + assertEquals(List.of("payments"), context.get("aws:ResourceTag/Team")); + } + + @Test + void ec2MainPortForeignArnCannotRetainCallerResourceTags() { + Map> context = ec2ResourceContext(resolver, "ec2", "ec2:ModifyVpcEndpoint", + "arn:aws:ec2:eu-west-1:111111111111:vpc-endpoint/vpce-0123456789", "us-east-1", + "123456789012", Map.of("aws:ResourceTag/OpenSearchManaged", List.of("true"))); + assertFalse(context.containsKey("aws:ResourceTag/OpenSearchManaged")); + } + + @Test + void ec2MainPortForeignArnReadsItsAccountAndRegion() { + when(ec2Service.resourceTags("111111111111", "eu-west-1", "vpce-0123456789")) + .thenReturn(List.of(new Tag("OpenSearchManaged", "true"))); + Map> context = ec2ResourceContext(resolver, "ec2", "ec2:ModifyVpcEndpoint", + "arn:aws:ec2:eu-west-1:111111111111:vpc-endpoint/vpce-0123456789", "us-east-1", + "123456789012", Map.of("aws:ResourceTag/OpenSearchManaged", List.of("false"))); + assertEquals(List.of("true"), context.get("aws:ResourceTag/OpenSearchManaged")); + verify(ec2Service).resourceTags("111111111111", "eu-west-1", "vpce-0123456789"); + verify(ec2Service, never()).resourceTags(anyString(), anyString()); + } + + @ParameterizedTest + @ValueSource(strings = {"111111111111", "123456789012"}) + void ec2ArnReadsRealStoredTagsAcrossAccountsAndRegions(String targetAccount) { + AccountAwareStorageBackend> tags = AccountAwareStorageBackend.inMemory("123456789012"); + tags.putForAccount("123456789012", "us-east-1::vpce-0123456789", List.of(new Tag("Team", "caller-east"))); + tags.putForAccount("123456789012", "eu-west-1::vpce-0123456789", List.of(new Tag("Team", "caller-west"))); + tags.putForAccount("111111111111", "us-east-1::vpce-0123456789", List.of(new Tag("Team", "foreign-east"))); + tags.putForAccount("111111111111", "eu-west-1::vpce-0123456789", List.of(new Tag("Team", "foreign-west"))); + IamConditionContextResolver stored = resolverWithStoredEc2Tags(tags); + String prefix = targetAccount.equals("123456789012") ? "caller" : "foreign"; + for (String region : List.of("us-east-1", "eu-west-1")) { + Map> context = ec2ResourceContext(stored, "ec2", "ec2:ModifyVpcEndpoint", + "arn:aws:ec2:" + region + ":" + targetAccount + ":vpc-endpoint/vpce-0123456789", + "us-east-1", "123456789012", Map.of("aws:ResourceTag/Team", List.of("stale"))); + assertEquals(List.of(prefix + (region.equals("us-east-1") ? "-east" : "-west")), + context.get("aws:ResourceTag/Team")); + } + } + + @Test + void ec2UntaggedForeignArnDoesNotBorrowRealCallerTags() { + AccountAwareStorageBackend> tags = AccountAwareStorageBackend.inMemory("123456789012"); + tags.putForAccount("123456789012", "eu-west-1::vpce-0123456789", List.of(new Tag("Team", "caller-west"))); + tags.putForAccount("111111111111", "us-east-1::vpce-0123456789", List.of(new Tag("Team", "foreign-east"))); + Map> context = ec2ResourceContext(resolverWithStoredEc2Tags(tags), + "ec2", "ec2:ModifyVpcEndpoint", "arn:aws:ec2:eu-west-1:111111111111:vpc-endpoint/vpce-0123456789", + "us-east-1", "123456789012", Map.of("aws:ResourceTag/Team", List.of("stale"))); + assertFalse(context.containsKey("aws:ResourceTag/Team")); + assertEquals("caller-west", tags.getForAccount("123456789012", + "eu-west-1::vpce-0123456789").orElseThrow().getFirst().getValue()); + } + + @SuppressWarnings("unchecked") + private IamConditionContextResolver resolverWithStoredEc2Tags(AccountAwareStorageBackend> tags) { + StorageFactory storage = mock(StorageFactory.class); + when(storage.create(anyString(), anyString(), any())).thenAnswer(call -> + call.getArgument(1).equals("ec2-tags.json") ? tags + : AccountAwareStorageBackend.inMemory("123456789012")); + when(config.defaultAccountId()).thenReturn("123456789012"); + EmulatorConfig.ServicesConfig serviceConfig = mock(EmulatorConfig.ServicesConfig.class); + EmulatorConfig.Ec2ServiceConfig ec2Config = mock(EmulatorConfig.Ec2ServiceConfig.class); + when(config.services()).thenReturn(serviceConfig); + when(serviceConfig.ec2()).thenReturn(ec2Config); + when(ec2Config.mock()).thenReturn(true); + when(ec2Config.mockPublicAddresses()).thenReturn(EmulatorConfig.Ec2ServiceConfig.MockPublicAddresses.DOCUMENTATION); + when(ec2Config.mockPublicAddress()).thenReturn(Optional.empty()); + Ec2Service service = new Ec2Service(config, mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), storage); + Instance services = mock(Instance.class); + when(services.isResolvable()).thenReturn(true); + when(services.get()).thenReturn(service); + Instance readers = mock(Instance.class); + when(readers.iterator()).thenAnswer(call -> List.of(new Ec2StoredResourceArns(service, + new RegionResolver("us-east-1", "123456789012"))).iterator()); + return new IamConditionContextResolver(dynamoDbFacadeInstance, services, mock(Instance.class), + mock(Instance.class), mock(Instance.class), spellings(new ShapeNamingSpelling()), + readers, requestContext, new RegionResolver("us-east-1", "123456789012"), + config, null, serviceCatalog); + } + + @Test + void ec2MainPortOwnUntaggedArnClearsEarlierResourceTags() { + Map> context = ec2ResourceContext(resolver, "ec2", "ec2:ModifyVpcEndpoint", + "arn:aws:ec2:us-east-1:123456789012:vpc-endpoint/vpce-0123456789", "us-east-1", + "123456789012", Map.of("aws:ResourceTag/OpenSearchManaged", List.of("true"))); + assertFalse(context.containsKey("aws:ResourceTag/OpenSearchManaged")); + } + + @Test + void ec2NameBasedForeignArnUsesSharedStoredTags() { + when(ec2Service.resourceTags("111111111111", "eu-west-1", "web")) + .thenReturn(List.of(new Tag("Team", "foreign"))); + Map> context = ec2ResourceContext(resolver, "ec2", "ec2:ModifyInstancePlacement", + "arn:aws:ec2:eu-west-1:111111111111:placement-group/web", "us-east-1", "123456789012", Map.of()); + assertEquals(List.of("foreign"), context.get("aws:ResourceTag/Team")); + } + + @Test + void ec2MainPortWildcardRetainsTheExistingContext() { + Map> original = Map.of("aws:ResourceTag/Team", List.of("payments")); + assertSame(original, ec2ResourceContext(resolver, "ec2", "ec2:ModifyVpcEndpoint", + "arn:aws:ec2:us-east-1:123456789012:vpc-endpoint/*", "us-east-1", "123456789012", original)); + } + + private Map> ec2ResourceContext(IamConditionContextResolver reading, String scope, + String action, String resource, String region, String account, Map> context) { + Map> record = reading.withEc2ResourceContext(scope, action, resource, region, account, context); + IamConditionContextResolver tags = reading == resolver + ? resolverReading(new Ec2StoredResourceArns(ec2Service, new RegionResolver(region, account))) : reading; + return IamConditionContextResolver.withResourceTags(record, tags.resourceTags(resource)); + } + + @Test + void otherServiceReadsEc2TagsThroughGeneratedSharedPath() { + AccountAwareStorageBackend> tags = AccountAwareStorageBackend.inMemory("123456789012"); + tags.putForAccount("111111111111", "eu-west-1::i-0123456789", List.of(new Tag("Team", "foreign"))); + IamConditionContextResolver reading = resolverWithStoredEc2Tags(tags); + String arn = "arn:aws:ec2:eu-west-1:111111111111:instance/i-0123456789"; + Map> context = ec2ResourceContext(reading, "ec2-instance-connect", "ec2-instance-connect:SendSSHPublicKey", + arn, "us-east-1", "123456789012", Map.of("aws:RequestTag/Team", List.of("requested"))); + assertEquals(List.of("foreign"), context.get("aws:ResourceTag/Team")); + assertEquals(List.of("requested"), context.get("aws:RequestTag/Team")); + } + @Test void resourceTagsAreTheGeneratedKeysOfTheArnsTypeValuedFromItsServicesStoredTags() { String secret = "arn:aws:secretsmanager:eu-west-1:123456789012:secret:app-AbCdEf"; diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java index f8a8ffdf7a..2f0a48e16a 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java @@ -690,7 +690,7 @@ class Ec2ServiceTest { attachment.setInstanceId("i-11111111"); eni.setAttachment(attachment); interfaces.putForAccount(owner, region + "::" + eni.getNetworkInterfaceId(), eni); - Ec2StoredResourceArns stored = new Ec2StoredResourceArns(service); + Ec2StoredResourceArns stored = new Ec2StoredResourceArns(service, new RegionResolver("us-east-1", "000000000000")); assertEquals(attachmentArns(region, owner, "i-11111111", "eni-11111111"), service.networkInterfaceAttachmentArns(region, attachment.getAttachmentId())); diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2VpcEndpointResourceTagIamIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2VpcEndpointResourceTagIamIntegrationTest.java new file mode 100644 index 0000000000..c99982bcc3 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2VpcEndpointResourceTagIamIntegrationTest.java @@ -0,0 +1,194 @@ +package io.floci.aws.services.ec2; + +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.floci.aws.testing.SignedIamEnforcementProfile; +import io.floci.aws.testing.SignedIamUsers; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.Ec2Exception; +import software.amazon.awssdk.services.ec2.model.ResourceType; +import software.amazon.awssdk.services.ec2.model.Tag; +import software.amazon.awssdk.services.ec2.model.VpcEndpointType; + +import java.net.URI; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Amazon OpenSearch Service's service-linked role policy lets the service delete and modify only the + * VPC endpoints it manages: AmazonOpenSearchServiceRolePolicy grants {@code ec2:DeleteVpcEndpoints} + * and {@code ec2:ModifyVpcEndpoint} on {@code vpc-endpoint/*} with + * {@code StringEquals aws:ResourceTag/OpenSearchManaged = "true"}. Each endpoint is checked with its + * own stored tags, so the grant reaches a tagged endpoint and no other. + * + *

The principal holds the AWS managed policy itself, attached by ARN, under signed IAM enforcement. + */ +@QuarkusTest +@TestProfile(SignedIamEnforcementProfile.class) +class Ec2VpcEndpointResourceTagIamIntegrationTest { + + private static final String ADMIN = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"*","Resource":"*"}]}"""; + private static final String SLR_POLICY = + "arn:aws:iam::aws:policy/aws-service-role/AmazonOpenSearchServiceRolePolicy"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @TestHTTPResource + URI endpoint; + + @Test + void theServiceLinkedRoleDeletesOnlyTheEndpointsTaggedOpenSearchManaged() throws Exception { + Ec2Client admin = client(SignedIamUsers.createUser(endpoint, "vpce-admin-", "admin", ADMIN)); + Ec2Client service = serviceLinkedRoleClient(); + String vpc = admin.createVpc(request -> request.cidrBlock("10.57.0.0/16")).vpc().vpcId(); + cleanup.register(() -> admin.deleteVpc(request -> request.vpcId(vpc))); + + String managed = gatewayEndpoint(admin, vpc, Map.of("OpenSearchManaged", "true")); + String untagged = gatewayEndpoint(admin, vpc, Map.of()); + String otherValue = gatewayEndpoint(admin, vpc, Map.of("OpenSearchManaged", "false")); + + denied(() -> service.deleteVpcEndpoints(request -> request.vpcEndpointIds(untagged))); + denied(() -> service.deleteVpcEndpoints(request -> request.vpcEndpointIds(otherValue))); + // One endpoint the grant does not reach refuses the whole batch. + denied(() -> service.deleteVpcEndpoints(request -> request.vpcEndpointIds(managed, untagged))); + assertTrue(exists(admin, managed) && exists(admin, untagged) && exists(admin, otherValue)); + + service.deleteVpcEndpoints(request -> request.vpcEndpointIds(managed)); + assertTrue(!exists(admin, managed), "the tagged endpoint was deleted"); + assertTrue(exists(admin, untagged) && exists(admin, otherValue)); + } + + @Test + void theSameTagScopesModifyVpcEndpoint() throws Exception { + Ec2Client admin = client(SignedIamUsers.createUser(endpoint, "vpce-admin-", "admin", ADMIN)); + Ec2Client service = serviceLinkedRoleClient(); + String vpc = admin.createVpc(request -> request.cidrBlock("10.58.0.0/16")).vpc().vpcId(); + cleanup.register(() -> admin.deleteVpc(request -> request.vpcId(vpc))); + String managed = gatewayEndpoint(admin, vpc, Map.of("OpenSearchManaged", "true")); + String untagged = gatewayEndpoint(admin, vpc, Map.of()); + + service.modifyVpcEndpoint(request -> request.vpcEndpointId(managed).resetPolicy(true)); + denied(() -> service.modifyVpcEndpoint(request -> request.vpcEndpointId(untagged).resetPolicy(true))); + } + + @Test + void instanceConnectUsesTheEc2InstancesStoredTags() throws Exception { + RestAssuredJsonUtils.configureAwsContentTypes(); + Ec2Client admin = client(SignedIamUsers.createUser(endpoint, "connect-admin-", "admin", ADMIN)); + String instance = admin.runInstances(request -> request.imageId("ami-0abcdef1234567890") + .instanceType("t3.micro").minCount(1).maxCount(1) + .tagSpecifications(spec -> spec.resourceType(ResourceType.INSTANCE) + .tags(tag -> tag.key("Team").value("operations")))) + .instances().getFirst().instanceId(); + cleanup.register(() -> admin.terminateInstances(request -> request.instanceIds(instance))); + String policy = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"ec2-instance-connect:SendSerialConsoleSSHPublicKey", + "Resource":"arn:aws:ec2:us-east-1:000000000000:instance/*", + "Condition":{"StringEquals":{"aws:ResourceTag/Team":"operations"}}}]} + """; + try (SignedIamUsers.User caller = SignedIamUsers.createUser(endpoint, "connect-tags-", "tags", policy)) { + sendSerialKey(caller, instance, 400, "SerialConsoleSessionUnsupportedException"); + admin.deleteTags(request -> request.resources(instance).tags(tag -> tag.key("Team"))); + sendSerialKey(caller, instance, 400, "AccessDeniedException"); + admin.createTags(request -> request.resources(instance).tags(tag -> tag.key("Team").value("other"))); + sendSerialKey(caller, instance, 400, "AccessDeniedException"); + admin.createTags(request -> request.resources(instance).tags(tag -> tag.key("Team").value("operations"))); + sendSerialKey(caller, instance, 400, "SerialConsoleSessionUnsupportedException"); + } + } + + private void sendSerialKey(SignedIamUsers.User caller, String instance, int status, String code) { + String body = """ + {"InstanceId":"%s","SerialPort":0, + "SSHPublicKey":"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl user@host"} + """.formatted(instance); + given().filter(caller.signer("ec2-instance-connect")) + .header("X-Amz-Target", "AWSEC2InstanceConnectService.SendSerialConsoleSSHPublicKey") + .contentType("application/x-amz-json-1.1").body(body).post(endpoint) + .then().statusCode(status).body("__type", equalTo(code)); + } + + /** + * A client for a principal holding exactly AmazonOpenSearchServiceRolePolicy, the AWS managed + * document attached by ARN. The detach is registered last so it runs before the user is deleted. + */ + private Ec2Client serviceLinkedRoleClient() throws Exception { + SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "vpce-slr-"); + Ec2Client client = client(user); + SignedIamUsers.iam(endpoint, "AttachUserPolicy", Map.of("UserName", user.name(), "PolicyArn", SLR_POLICY)) + .then().statusCode(200); + cleanup.register(() -> { + try { + SignedIamUsers.iam(endpoint, "DetachUserPolicy", + Map.of("UserName", user.name(), "PolicyArn", SLR_POLICY)).then().statusCode(200); + } catch (Exception error) { + throw new IllegalStateException("Cannot detach the test user's policy", error); + } + }); + return client; + } + + private Ec2Client client(SignedIamUsers.User user) { + // Registered first, so it runs after everything this user's client made is cleaned up. + cleanup.register(() -> { + try { + user.close(); + } catch (Exception error) { + throw new IllegalStateException("Cannot retire the owned IAM test user", error); + } + }); + Ec2Client client = Ec2Client.builder().endpointOverride(endpoint).region(Region.US_EAST_1) + .httpClientBuilder(UrlConnectionHttpClient.builder()) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create(user.accessKeyId(), user.secretAccessKey()))).build(); + cleanup.register(client::close); + return client; + } + + private String gatewayEndpoint(Ec2Client admin, String vpc, Map tags) { + String id = admin.createVpcEndpoint(request -> { + request.vpcId(vpc).serviceName("com.amazonaws.us-east-1.s3").vpcEndpointType(VpcEndpointType.GATEWAY); + if (!tags.isEmpty()) { + request.tagSpecifications(spec -> spec.resourceType(ResourceType.VPC_ENDPOINT) + .tags(tags.entrySet().stream() + .map(tag -> Tag.builder() + .key(tag.getKey()).value(tag.getValue()).build()) + .toList())); + } + }).vpcEndpoint().vpcEndpointId(); + cleanup.register(() -> { + if (exists(admin, id)) { + admin.deleteVpcEndpoints(request -> request.vpcEndpointIds(id)); + } + }); + return id; + } + + private static boolean exists(Ec2Client admin, String endpointId) { + return admin.describeVpcEndpoints(request -> request.filters(filter -> filter.name("vpc-endpoint-id") + .values(endpointId))).vpcEndpoints().stream() + .anyMatch(found -> endpointId.equals(found.vpcEndpointId()) + && !"deleted".equalsIgnoreCase(found.stateAsString())); + } + + private void denied(Runnable action) { + assertEquals(403, assertThrows(Ec2Exception.class, action::run).statusCode()); + } +}