fix(ec2): report the calling account as resource owner (#3814)

EC2 froze every resource's owner to the configured default account at
construction time, so OwnerId came back as 000000000000 no matter which
account the request resolved to. Per-account isolation itself worked, but
the reported owner contradicted what STS returns for the same credentials
and what SQS embeds in its ARNs.

The visible consequence was DescribeImages --owners: the filter was honored
but matched against the frozen value, so filtering on the account actually
in use returned nothing, and the common Terraform pattern of pinning an AMI
to a known owner account failed with "Your query returned no results".

Resolve the owner per request through callerAccountId() instead, for the
ownerId fields, the generated ARNs and the self owner alias. Callers outside
a request scope (startup seeding, internal provisioning) still fall back to
the configured default account.

Closes #3775
This commit is contained in:
Mohamed Amine ALOUINI authored and GitHub committed 2026-09-17 13:36:30 -04:00
1 parent 5cb1453f4e
commit 7e539155e1
7 files changed
+424 -51

No files matched your search

@@ -0,0 +1,209 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
import io.github.hectorvent.floci.services.ec2.model.CapacityReservation;
import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;
import io.github.hectorvent.floci.services.ec2.model.Image;
import io.github.hectorvent.floci.services.ec2.model.InternetGateway;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
import io.github.hectorvent.floci.services.ec2.model.PrefixListEntry;
import io.github.hectorvent.floci.services.ec2.model.RouteTable;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.model.Snapshot;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.ec2.model.TransitGateway;
import io.github.hectorvent.floci.services.ec2.model.Vpc;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Regression test for issue #3775. EC2 attributed every resource to the configured default
* account, no matter which account the caller resolved to, so {@code OwnerId} disagreed with
* what STS reported for the same credentials and {@code DescribeImages --owners <caller>}
* matched nothing. Each resource must carry the calling account as its owner (and in its ARN),
* and the {@code self} owner alias must resolve to that same account.
*
* <p>Hermetic: a real {@link Ec2Service} over in-memory storage with a stubbed request context
* whose account the test switches between calls.
*/
class Ec2OwnerAttributionTest {
private static final String REGION = "us-east-1";
private static final String DEFAULT_ACCOUNT = "000000000000";
private static final String CALLER = "444444444444";
private static final String OTHER_CALLER = "111111111111";
private final AtomicReference<String> caller = new AtomicReference<>(CALLER);
@Test
void registeredImageIsOwnedByTheCallingAccount() {
Ec2Service service = newService();
Image image = service.registerImage(REGION, "owner-test", null, "x86_64", "/dev/xvda", List.of());
assertEquals(CALLER, image.getOwnerId());
assertTrue(describesImage(service, image, List.of(CALLER)),
"filtering on the account the caller actually uses must match its own image");
assertTrue(describesImage(service, image, List.of("self")),
"the self alias must resolve to the calling account");
assertFalse(describesImage(service, image, List.of(DEFAULT_ACCOUNT)),
"the default account must not be reported as owner of another account's image");
}
@Test
void ownerFollowsTheCallerWhenTheAccountChanges() {
Ec2Service service = newService();
Image first = service.registerImage(REGION, "first", null, "x86_64", "/dev/xvda", List.of());
caller.set(OTHER_CALLER);
Image second = service.registerImage(REGION, "second", null, "x86_64", "/dev/xvda", List.of());
assertEquals(CALLER, first.getOwnerId());
assertEquals(OTHER_CALLER, second.getOwnerId());
// The owner is resolved per request, not frozen at construction time.
assertTrue(describesImage(service, second, List.of("self")));
assertFalse(describesImage(service, first, List.of("self")),
"self must not match an image the current caller does not own");
}
@Test
void snapshotsAreOwnedByTheCallingAccountAndDescribeDefaultsToThem() {
Ec2Service service = newService();
service.registerImage(REGION, "with-snapshot", null, "x86_64", "/dev/xvda",
List.of(blockDeviceMapping("snap-3775", 8)));
List<Snapshot> own = service.describeSnapshots(REGION, List.of(), List.of(), Map.of());
assertEquals(1, own.size(), "with no owner filter DescribeSnapshots reports the caller's own snapshots");
assertEquals(CALLER, own.getFirst().getOwnerId());
assertEquals(1, service.describeSnapshots(REGION, List.of(), List.of("self"), Map.of()).size());
assertTrue(service.describeSnapshots(REGION, List.of(), List.of(DEFAULT_ACCOUNT), Map.of()).isEmpty(),
"the default account owns none of the caller's snapshots");
}
@Test
void networkingResourcesAreOwnedByTheCallingAccount() {
Ec2Service service = newService();
Vpc vpc = service.createVpc(REGION, "10.0.0.0/16", false);
Subnet subnet = service.createSubnet(REGION, vpc.getVpcId(), "10.0.1.0/24", REGION + "a");
SecurityGroup sg = service.createSecurityGroup(REGION, "owner-sg", "t", vpc.getVpcId());
InternetGateway igw = service.createInternetGateway(REGION);
RouteTable routeTable = service.createRouteTable(REGION, vpc.getVpcId());
ManagedPrefixList prefixList = service.createManagedPrefixList(REGION, "owner-pl", "IPv4", 5,
List.of(new PrefixListEntry("10.0.0.0/8", "corporate")), List.of());
assertEquals(CALLER, vpc.getOwnerId());
assertEquals(CALLER, subnet.getOwnerId());
assertTrue(subnet.getSubnetArn().contains(":" + CALLER + ":"), subnet.getSubnetArn());
assertEquals(CALLER, sg.getOwnerId());
assertEquals(CALLER, igw.getOwnerId());
assertEquals(CALLER, routeTable.getOwnerId());
assertEquals(CALLER, prefixList.getOwnerId());
assertTrue(prefixList.getPrefixListArn().contains(":" + CALLER + ":"), prefixList.getPrefixListArn());
}
@Test
void transitGatewayCapacityReservationAndEniAreOwnedByTheCallingAccount() {
Ec2Service service = newService();
TransitGateway gateway = service.createTransitGateway(REGION, "owner-tgw", null, List.of());
CapacityReservation reservation = service.createCapacityReservation(REGION, "t3.micro",
"Linux/UNIX", REGION + "a", null, 1, null, null, null, null, null, null, null, null);
Vpc vpc = service.createVpc(REGION, "10.1.0.0/16", false);
Subnet subnet = service.createSubnet(REGION, vpc.getVpcId(), "10.1.1.0/24", REGION + "a");
NetworkInterface eni = service.createNetworkInterface(REGION, subnet.getSubnetId(), "owner-eni",
null, List.of(), List.of(), List.of());
assertEquals(CALLER, gateway.getOwnerId());
assertTrue(gateway.getTransitGatewayArn().contains(":" + CALLER + ":"),
gateway.getTransitGatewayArn());
assertEquals(CALLER, reservation.getOwnerId());
assertTrue(reservation.getCapacityReservationArn().contains(":" + CALLER + ":"),
reservation.getCapacityReservationArn());
assertEquals(CALLER, eni.getOwnerId());
}
@Test
void launchTemplateCreatedByNamesTheCallingAccount() {
Ec2Service service = newService();
LaunchTemplate template = service.createLaunchTemplate(REGION, "owner-lt",
new LaunchTemplateData(), List.of());
// createdBy is an IAM ARN, so a frozen owner would hand back the default account's root.
assertEquals("arn:aws:iam::" + CALLER + ":root", template.getCreatedBy());
}
@Test
void withoutARequestAccountResourcesFallBackToTheDefaultAccount() {
Ec2Service service = newService();
caller.set(null);
Image image = service.registerImage(REGION, "startup-seeded", null, "x86_64", "/dev/xvda", List.of());
assertEquals(DEFAULT_ACCOUNT, image.getOwnerId());
}
private static boolean describesImage(Ec2Service service, Image image, List<String> owners) {
return service.describeImages(REGION, List.of(), owners, Map.of()).stream()
.anyMatch(img -> image.getImageId().equals(img.getImageId()));
}
private static BlockDeviceMapping blockDeviceMapping(String snapshotId, int volumeSize) {
EbsBlockDevice ebs = new EbsBlockDevice();
ebs.setSnapshotId(snapshotId);
ebs.setVolumeSize(volumeSize);
BlockDeviceMapping mapping = new BlockDeviceMapping();
mapping.setDeviceName("/dev/sda1");
mapping.setEbs(ebs);
return mapping;
}
@SuppressWarnings("unchecked")
private Ec2Service newService() {
RequestContext requestContext = mock(RequestContext.class);
when(requestContext.getAccountId()).thenAnswer(invocation -> caller.get());
Instance<RequestContext> contextInstance = mock(Instance.class);
when(contextInstance.get()).thenReturn(requestContext);
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.Ec2ServiceConfig ec2 = mock(EmulatorConfig.Ec2ServiceConfig.class);
when(config.defaultAccountId()).thenReturn(DEFAULT_ACCOUNT);
when(config.services()).thenReturn(services);
when(services.ec2()).thenReturn(ec2);
when(ec2.mock()).thenReturn(true);
Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog();
return new Ec2Service(config, null, mock(Ec2PortForwardManager.class),
new AmiImageResolver(imageCatalog), imageCatalog, new Ec2InstanceTypeCatalog(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
contextInstance);
}
}
@@ -0,0 +1,138 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.xml.HasXPath.hasXPath;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Issue #3775: EC2 reported {@code OwnerId: 000000000000} on every resource regardless of the
* account the caller resolved to, so {@code aws ec2 describe-images --owners <account>} for the
* account actually in use returned nothing and Terraform's {@code data "aws_ami"} with a pinned
* {@code owners} list failed with "Your query returned no results". The owner reported on the wire
* must be the same account STS would report for the credentials, and the {@code self} alias must
* resolve to it.
*/
@QuarkusTest
class Ec2OwnerIdIntegrationTest {
private static final String ACCOUNT = "444444444444";
private static final String DEFAULT_ACCOUNT = "000000000000";
/** SigV4 access key ids that are 12 digits resolve to that account. */
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20260917/us-east-1/ec2/aws4_request";
@Test
void registeredImageReportsTheCallersAccountAsOwner() {
String imageId = registerImage(uniqueName("owner-test"));
given()
.formParam("Action", "DescribeImages")
.formParam("ImageId.1", imageId)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(hasXPath("//*[local-name()='imageOwnerId']", equalTo(ACCOUNT)));
}
@Test
void describeImagesOwnersFilterMatchesTheCallersAccount() {
String imageId = registerImage(uniqueName("owner-filter"));
assertTrue(ec2("DescribeImages", "Owner.1", ACCOUNT).contains(imageId),
"--owners <caller account> must match the image the caller registered");
assertTrue(ec2("DescribeImages", "Owner.1", "self").contains(imageId),
"--owners self must resolve to the caller account");
assertFalse(ec2("DescribeImages", "Owner.1", DEFAULT_ACCOUNT).contains(imageId),
"the default account must not own an image registered by another account");
}
@Test
void synthesizedLookupImageForSelfIsOwnedByTheCaller() {
// CDK/Terraform AMI lookups by name wildcard synthesize an image when nothing matches;
// with Owner.1=self that image must belong to the caller, not the default account.
given()
.formParam("Action", "DescribeImages")
.formParam("Owner.1", "self")
.formParam("Filter.1.Name", "name")
.formParam("Filter.1.Value.1", "floci-3775-lookup-" + UUID.randomUUID() + "-*")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(hasXPath("//*[local-name()='imageOwnerId']", equalTo(ACCOUNT)));
}
@Test
void instanceProfileArnBuiltFromANameCarriesTheCallersAccount() {
// RunInstances accepts IamInstanceProfile.Name and builds the ARN itself. Built from the
// default account, the instance would claim a profile in an account the caller does not use.
given()
.formParam("Action", "RunInstances")
.formParam("ImageId", "ami-0abcdef1234567890")
.formParam("InstanceType", "t3.micro")
.formParam("MinCount", "1")
.formParam("MaxCount", "1")
.formParam("IamInstanceProfile.Name", "owner-profile")
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(hasXPath("//*[local-name()='iamInstanceProfile']/*[local-name()='arn']",
equalTo("arn:aws:iam::" + ACCOUNT + ":instance-profile/owner-profile")));
}
@Test
void securityGroupReportsTheCallersAccountAsOwner() {
String groupId = xmlValue(ec2("CreateSecurityGroup",
"GroupName", uniqueName("owner-sg"), "GroupDescription", "t"), "groupId");
given()
.formParam("Action", "DescribeSecurityGroups")
.formParam("GroupId.1", groupId)
.header("Authorization", AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body(hasXPath("//*[local-name()='securityGroupInfo']/*[local-name()='item']"
+ "/*[local-name()='ownerId']", equalTo(ACCOUNT)));
}
private String registerImage(String name) {
return xmlValue(ec2("RegisterImage", "Name", name, "Architecture", "x86_64",
"RootDeviceName", "/dev/xvda", "VirtualizationType", "hvm"), "imageId");
}
private String ec2(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().asString();
}
private static String xmlValue(String xml, String element) {
String open = "<" + element + ">";
String close = "</" + element + ">";
int start = xml.indexOf(open);
return start < 0 ? null : xml.substring(start + open.length(), xml.indexOf(close, start));
}
/** A name unique per test run, so reruns never collide on InvalidAMIName.Duplicate. */
private static String uniqueName(String prefix) {
return prefix + "-" + UUID.randomUUID();
}
}
@@ -1,6 +1,5 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.ec2.model.FlowLog;
import io.github.hectorvent.floci.services.s3.S3Service;
@@ -21,13 +20,27 @@ class FlowLogServiceTest {
@BeforeEach
void setUp() {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.defaultAccountId()).thenReturn("000000000000");
flowLogService = serviceCallingAs("000000000000");
}
/** A service whose EC2 dependency resolves the caller to {@code accountId}. */
private FlowLogService serviceCallingAs(String accountId) {
Ec2Service ec2Service = mock(Ec2Service.class);
when(ec2Service.callerAccountId()).thenReturn(accountId);
when(ec2Service.describeInstances(any(), any(), any())).thenReturn(List.of());
when(ec2Service.endpointNetworkInterfaces(any())).thenReturn(List.of());
flowLogService = new FlowLogService(config, ec2Service, mock(S3Service.class),
new InMemoryStorage<>());
return new FlowLogService(ec2Service, mock(S3Service.class), new InMemoryStorage<>());
}
@Test
void createFlowLogRecordsTheCallingAccountNotTheDefault() {
// The account lands in the delivered record's account-id field and in the S3 key prefix
// (AWSLogs/{account}/vpcflowlogs/...), so a flow log created by a non-default caller must
// carry that caller. Before issue #3775 this was pinned to the configured default account.
FlowLog fl = serviceCallingAs("444444444444").createFlowLog("us-east-1", "vpc-123", "VPC",
"ALL", "s3", "arn:aws:s3:::flow-bucket", null, null, 600);
assertEquals("444444444444", fl.getAccountId());
}
@Test