fix(iam): read EC2 resource tags in the ARN scope (#9412)

EC2 resource-tag conditions read the tags of the resource an ARN names in the caller's account and Region, and a foreign ARN kept the caller's earlier tags. Ec2StoredResourceArns now answers storedTags for the resource in the ARN's account and Region, with the caller's account for an account-less image or snapshot ARN, so the shared resource-tag reader fills the table's keys for every EC2 type, other services' requests naming an EC2 ARN included. withEc2ResourceContext keeps only the generated record keys.

Ported from Emanuel Aseghehey's original change.
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-24 23:19:17 -04:00
1 parent 74430d7d40
commit b3c8db3022
8 files changed
+404 -11

No files matched your search

@@ -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<String, List<String>> 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<String, List<String>> 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<String, List<String>> 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<String, List<String>> 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<List<Tag>> 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<String, List<String>> 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<List<Tag>> 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<String, List<String>> 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<List<Tag>> 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<Ec2Service> services = mock(Instance.class);
when(services.isResolvable()).thenReturn(true);
when(services.get()).thenReturn(service);
Instance<StoredResourceArns> readers = mock(Instance.class);
when(readers.iterator()).thenAnswer(call -> List.<StoredResourceArns>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<String, List<String>> 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<String, List<String>> 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<String, List<String>> 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<String, List<String>> ec2ResourceContext(IamConditionContextResolver reading, String scope,
String action, String resource, String region, String account, Map<String, List<String>> context) {
Map<String, List<String>> 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<List<Tag>> 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<String, List<String>> 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";
@@ -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()));
@@ -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.
*
* <p>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<String, String> 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());
}
}