Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Mohamed Amine ALOUINI7e539155e181
diff --git a/docs/services/ec2.md b/docs/services/ec2.md
index 58205c0f9f..6878a64b01 100644
--- a/docs/services/ec2.md
+++ b/docs/services/ec2.md
@@ -249,6 +249,14 @@ Floci seeds the following resources on first use in each region so Terraform, th
| CreateImage | Captures an instance as a new AMI. Reboots the source unless `NoReboot=true`. |
| RegisterImage | Registers an AMI from supplied metadata and block device mappings. |
+Every resource EC2 creates is owned by the account the request resolves to, the same account
+[STS](sts.md) reports for those credentials, and that account is what `ownerId` and the resource ARN
+carry. So `DescribeImages` with `--owners <your account id>` matches the AMIs that account
+registered, and `--owners self` resolves to the same account. This is what lets a Terraform
+`aws_ami` data source pin `owners` to the account under test instead of the emulator's default
+`000000000000`. The `amazon` and `aws-marketplace` aliases still resolve to the AWS-owned accounts
+that publish those images.
+
### Tags
| Action | Description |
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
index a6221553d6..b00f6afabf 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
@@ -3203,7 +3203,7 @@ public class Ec2QueryHandler {
.stream().findFirst()
.orElseGet(() -> firstFilterValue(filters, "owner-alias", AMAZON_OWNER_ID));
return switch (requested) {
- case "self" -> config.defaultAccountId();
+ case "self" -> service.callerAccountId();
case "amazon" -> AMAZON_OWNER_ID;
case "aws-marketplace" -> AWS_MARKETPLACE_OWNER_ID;
default -> requested;
@@ -4477,7 +4477,7 @@ public class Ec2QueryHandler {
if (name == null || name.isBlank()) {
return null;
}
- return AwsArnUtils.Arn.of("iam", "", config.defaultAccountId(), "instance-profile/" + name).toString();
+ return AwsArnUtils.Arn.of("iam", "", service.callerAccountId(), "instance-profile/" + name).toString();
}
private String vpcXml(Vpc vpc) {
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 d7ab8f0ed6..54e0905433 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
@@ -143,7 +143,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
private static final Duration CONTAINER_LAUNCH_TIMEOUT = Duration.ofMinutes(5);
private static final long CONTAINER_LAUNCH_POLL_MILLIS = 50;
- private final String accountId;
+ private final String defaultAccountId;
private final jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance;
private final EmulatorConfig config;
private final Ec2ContainerManager containerManager;
@@ -382,7 +382,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
StorageBackend<String, NetworkInterface> networkInterfaces,
StorageBackend<String, CapacityReservation> capacityReservations,
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance) {
- this.accountId = config.defaultAccountId();
+ this.defaultAccountId = config.defaultAccountId();
this.requestContextInstance = requestContextInstance;
this.config = config;
this.containerManager = containerManager;
@@ -959,10 +959,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
String prefixListId = "pl-" + randomHex(17);
list.setPrefixListId(prefixListId);
list.setPrefixListName(prefixListName);
- list.setPrefixListArn(AwsArnUtils.Arn.of("ec2", region, accountId, "prefix-list/" + prefixListId).toString());
+ String ownerAccountId = callerAccountId();
+ list.setPrefixListArn(AwsArnUtils.Arn.of("ec2", region, ownerAccountId, "prefix-list/" + prefixListId).toString());
list.setAddressFamily(addressFamily);
list.setMaxEntries(maxEntries);
- list.setOwnerId(accountId);
+ list.setOwnerId(ownerAccountId);
list.setRegion(region);
// AWS creates asynchronously (create-in-progress then create-complete). Nothing here is
// slow, so the list is complete by the time the caller sees it.
@@ -1263,10 +1264,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
String transitGatewayId = "tgw-" + randomHex(17);
TransitGateway gateway = new TransitGateway();
gateway.setTransitGatewayId(transitGatewayId);
+ String ownerAccountId = callerAccountId();
gateway.setTransitGatewayArn(AwsArnUtils.Arn
- .of("ec2", region, accountId, "transit-gateway/" + transitGatewayId).toString());
+ .of("ec2", region, ownerAccountId, "transit-gateway/" + transitGatewayId).toString());
gateway.setState("available");
- gateway.setOwnerId(accountId);
+ gateway.setOwnerId(ownerAccountId);
gateway.setDescription(description);
gateway.setCreationTime(ISO_FMT.format(Instant.now()));
gateway.setRegion(region);
@@ -1680,7 +1682,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
attachment.setTransitGatewayAttachmentId(attachmentId);
attachment.setTransitGatewayId(gateway.getTransitGatewayId());
attachment.setVpcId(vpcId);
- attachment.setVpcOwnerId(accountId);
+ attachment.setVpcOwnerId(callerAccountId());
attachment.setTransitGatewayOwnerId(gateway.getOwnerId());
// AWS reports pending and settles on available; nothing is slow locally, the same
// compression createTransitGateway applies.
@@ -2588,7 +2590,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
String reservationId = "r-" + randomHex(17);
Reservation reservation = new Reservation();
reservation.setReservationId(reservationId);
- reservation.setOwnerId(accountId);
+ reservation.setOwnerId(callerAccountId());
String effectiveInstanceType = instanceType != null ? instanceType : "t2.micro";
validateArchitectureCompatibility(region, imageId, effectiveInstanceType);
@@ -2673,7 +2675,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
eni.setNetworkInterfaceId(suppliedEni != null ? suppliedEni.getNetworkInterfaceId() : "eni-" + randomHex(17));
eni.setSubnetId(finalSubnetId);
eni.setVpcId(vpcId);
- eni.setOwnerId(accountId);
+ eni.setOwnerId(callerAccountId());
eni.setDescription(suppliedEni != null ? suppliedEni.getDescription() : null);
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : null);
eni.setPrivateIpAddress(privateIp);
@@ -2697,7 +2699,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
launchAttachment.setDeviceIndex(eni.getDeviceIndex());
launchAttachment.setStatus("attached");
launchAttachment.setInstanceId(instanceId);
- launchAttachment.setInstanceOwnerId(accountId);
+ launchAttachment.setInstanceOwnerId(callerAccountId());
launchAttachment.setAttachTime(eni.getAttachTime());
launchAttachment.setDeleteOnTermination(false);
suppliedEni.setAttachment(launchAttachment);
@@ -2999,10 +3001,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
// Group into reservations (one instance per reservation for simplicity)
Map<String, Reservation> reservationMap = new LinkedHashMap<>();
+ String ownerAccountId = callerAccountId();
for (Instance inst : matched) {
Reservation res = new Reservation();
res.setReservationId("r-" + randomHex(17));
- res.setOwnerId(accountId);
+ res.setOwnerId(ownerAccountId);
res.getInstances().add(inst);
reservationMap.put(inst.getInstanceId(), res);
}
@@ -3991,9 +3994,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
subnet.setAvailabilityZone(zoneName);
subnet.setAvailabilityZoneId(zoneIdForZoneName(region, zoneName));
subnet.setAvailableIpAddressCount(251);
- subnet.setOwnerId(accountId);
+ String ownerAccountId = callerAccountId();
+ subnet.setOwnerId(ownerAccountId);
subnet.setRegion(region);
- subnet.setSubnetArn(AwsArnUtils.Arn.of("ec2", region, accountId, "subnet/" + subnetId).toString());
+ subnet.setSubnetArn(AwsArnUtils.Arn.of("ec2", region, ownerAccountId, "subnet/" + subnetId).toString());
if (ipv6CidrBlock != null && !ipv6CidrBlock.isBlank()) {
subnet.getIpv6CidrBlockAssociationSet().add(new VpcIpv6CidrBlockAssociation(
"subnet-cidr-assoc-" + randomHex(17), ipv6CidrBlock, null));
@@ -4115,7 +4119,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
sg.setGroupName(groupName);
sg.setDescription(description);
sg.setVpcId(vpcId);
- sg.setOwnerId(accountId);
+ sg.setOwnerId(callerAccountId());
sg.setRegion(region);
// Default egress all
IpPermission egressAll = new IpPermission();
@@ -4275,7 +4279,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
SecurityGroupRule rule = new SecurityGroupRule();
rule.setSecurityGroupRuleId("sgr-" + randomHex(17));
rule.setGroupId(groupId);
- rule.setGroupOwnerId(accountId);
+ rule.setGroupOwnerId(callerAccountId());
rule.setEgress(egress);
rule.setIpProtocol(perm.getIpProtocol());
rule.setFromPort(perm.getFromPort());
@@ -4298,7 +4302,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
}
for (UserIdGroupPair pair : perm.getUserIdGroupPairs()) {
if (pair.getUserId() == null) {
- pair.setUserId(accountId);
+ pair.setUserId(callerAccountId());
}
if (pair.getGroupId() == null && pair.getGroupName() != null) {
securityGroups.scan(k -> true).stream()
@@ -5010,7 +5014,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
image.setImageId("ami-" + randomHex(17));
image.setName(name);
image.setDescription(description != null ? description : name);
- image.setOwnerId(accountId);
+ image.setOwnerId(callerAccountId());
image.setImageOwnerAlias(null);
image.setPublic(false);
image.setArchitecture(architecture != null ? architecture : "x86_64");
@@ -5317,7 +5321,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
launchTemplate.setLaunchTemplateId("lt-" + randomHex(17));
launchTemplate.setLaunchTemplateName(name);
launchTemplate.setCreateTime(Instant.now());
- launchTemplate.setCreatedBy(AwsArnUtils.Arn.of("iam", "", accountId, "root").toString());
+ launchTemplate.setCreatedBy(AwsArnUtils.Arn.of("iam", "", callerAccountId(), "root").toString());
launchTemplate.setRegion(region);
launchTemplate.setData(new LaunchTemplateData(data != null ? data : new LaunchTemplateData()));
if (launchTemplateTags != null && !launchTemplateTags.isEmpty()) {
@@ -5567,7 +5571,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
if (profile.getName() == null || profile.getName().isBlank()) {
return null;
}
- return AwsArnUtils.Arn.of("iam", "", accountId, "instance-profile/" + profile.getName()).toString();
+ return AwsArnUtils.Arn.of("iam", "", callerAccountId(), "instance-profile/" + profile.getName()).toString();
}
public LaunchTemplateData resolveLaunchTemplateData(String region, String id, String name, String version) {
@@ -5713,7 +5717,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
}
String ownerId = image.getOwnerId();
return owners.contains(ownerId)
- || (owners.contains("self") && accountId.equals(ownerId))
+ || (owners.contains("self") && callerAccountId().equals(ownerId))
|| (owners.contains("amazon") && AMAZON_OWNER_ID.equals(ownerId))
|| (owners.contains("aws-marketplace") && AWS_MARKETPLACE_OWNER_ID.equals(ownerId));
}
@@ -5775,7 +5779,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
EbsBlockDevice ebs = mapping.getEbs();
Snapshot snapshot = new Snapshot();
snapshot.setSnapshotId(snapshotId);
- snapshot.setOwnerId(accountId);
+ snapshot.setOwnerId(callerAccountId());
snapshot.setState("completed");
snapshot.setDescription("Created by RegisterImage for " + image.getName());
snapshot.setStartTime(Instant.now());
@@ -5798,11 +5802,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
}
private boolean matchesSnapshotOwners(Snapshot snapshot, List<String> ownerIds) {
+ String caller = callerAccountId();
if (ownerIds == null || ownerIds.isEmpty()) {
- return accountId.equals(snapshot.getOwnerId());
+ return caller.equals(snapshot.getOwnerId());
}
return ownerIds.contains(snapshot.getOwnerId())
- || ownerIds.contains("self") && accountId.equals(snapshot.getOwnerId());
+ || ownerIds.contains("self") && caller.equals(snapshot.getOwnerId());
}
private boolean matchesSnapshotFilter(Snapshot snapshot, String name, List<String> values) {
@@ -6073,7 +6078,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
String igwId = "igw-" + randomHex(8);
InternetGateway igw = new InternetGateway();
igw.setInternetGatewayId(igwId);
- igw.setOwnerId(accountId);
+ igw.setOwnerId(callerAccountId());
igw.setRegion(region);
internetGateways.put(key(region, igwId), igw);
return igw;
@@ -6153,10 +6158,11 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
int count = requirePositiveInstanceCount(instanceCount);
CapacityReservation reservation = new CapacityReservation();
reservation.setCapacityReservationId("cr-" + randomHex(17));
- reservation.setOwnerId(accountId);
+ String ownerAccountId = callerAccountId();
+ reservation.setOwnerId(ownerAccountId);
reservation.setRegion(region);
reservation.setCapacityReservationArn(
- AwsArnUtils.Arn.of("ec2", region, accountId, "capacity-reservation/" + reservation.getCapacityReservationId()).toString());
+ AwsArnUtils.Arn.of("ec2", region, ownerAccountId, "capacity-reservation/" + reservation.getCapacityReservationId()).toString());
reservation.setAvailabilityZone(availabilityZone);
reservation.setAvailabilityZoneId(availabilityZoneId);
reservation.setInstanceType(instanceType);
@@ -6264,7 +6270,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
RouteTable rt = new RouteTable();
rt.setRouteTableId(rtId);
rt.setVpcId(vpcId);
- rt.setOwnerId(accountId);
+ rt.setOwnerId(callerAccountId());
rt.setRegion(region);
rt.getRoutes().add(new Route(vpc.getCidrBlock(), "local", "CreateRouteTable"));
routeTables.put(key(region, rtId), rt);
@@ -6867,10 +6873,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
/**
* The account making the current request, resolved the same way {@code AccountAwareStorageBackend}
- * derives its key prefix, so an identity comparison against a resolved peering connection's
- * requester/accepter owner id is meaningful both in and out of a request scope.
+ * derives its key prefix. Every resource EC2 creates is attributed to this account (its
+ * {@code ownerId} and ARN), and the {@code self} owner alias resolves to it, so what a caller
+ * sees as owner matches the account STS reports for the same credentials. Falls back to the
+ * configured default account outside a request scope (startup, internal provisioning).
*/
- private String callerAccountId() {
+ String callerAccountId() {
if (requestContextInstance != null) {
try {
String caller = requestContextInstance.get().getAccountId();
@@ -6880,10 +6888,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
} catch (ContextNotActiveException e) {
// Tolerated: callers outside a request scope (startup, internal provisioning)
// legitimately fall through to the default account.
- LOG.debugv("No active request context — resolving caller as default account {0}", accountId);
+ LOG.debugv("No active request context — resolving caller as default account {0}", defaultAccountId);
}
}
- return accountId;
+ return defaultAccountId;
}
// ─── NAT Gateways ─────────────────────────────────────────────────────────
@@ -7912,7 +7920,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
ni.setVpcId(subnet.getVpcId());
ni.setAvailabilityZone(subnet.getAvailabilityZone());
ni.setDescription(description);
- ni.setOwnerId(accountId);
+ ni.setOwnerId(callerAccountId());
ni.setStatus("available");
ni.setMacAddress(randomMac());
ni.setPrivateIpAddress(primaryIp);
@@ -7985,7 +7993,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
attachment.setDeviceIndex(deviceIndex);
attachment.setStatus("attached");
attachment.setInstanceId(instanceId);
- attachment.setInstanceOwnerId(accountId);
+ attachment.setInstanceOwnerId(callerAccountId());
attachment.setAttachTime(ISO_FMT.format(Instant.now()));
attachment.setDeleteOnTermination(false);
@@ -8305,6 +8313,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
private <T> void collectExplorerResources(List<ExplorerResource> out, List<T> stored, String resourceType,
Function<T, String> id, Function<T, String> region,
Function<T, Instant> createdAt, Function<T, List<Tag>> tags) {
+ String ownerAccountId = callerAccountId();
for (T resource : stored) {
String resourceId = id.apply(resource);
String resourceRegion = region.apply(resource);
@@ -8313,8 +8322,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
}
Instant created = createdAt.apply(resource);
out.add(new ExplorerResource(
- "arn:aws:ec2:" + resourceRegion + ":" + accountId + ":" + resourceType + "/" + resourceId,
- "ec2:" + resourceType, "ec2", resourceRegion, accountId,
+ "arn:aws:ec2:" + resourceRegion + ":" + ownerAccountId + ":" + resourceType + "/" + resourceId,
+ "ec2:" + resourceType, "ec2", resourceRegion, ownerAccountId,
created != null ? created : Instant.now(),
explorerTags(tags.apply(resource))));
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/FlowLogService.java b/src/main/java/io/github/hectorvent/floci/services/ec2/FlowLogService.java
index 247fc184fd..6df73a455f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/FlowLogService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/FlowLogService.java
@@ -1,7 +1,6 @@
package io.github.hectorvent.floci.services.ec2;
import com.fasterxml.jackson.core.type.TypeReference;
-import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -73,22 +72,19 @@ public class FlowLogService {
// restart in persistent/hybrid/wal modes and generation resumes)
private final StorageBackend<String, FlowLog> flowLogs;
- private final EmulatorConfig config;
private final Ec2Service ec2Service;
private final S3Service s3Service;
private ScheduledExecutorService scheduler;
@Inject
- public FlowLogService(EmulatorConfig config, Ec2Service ec2Service, S3Service s3Service,
- StorageFactory storageFactory) {
- this(config, ec2Service, s3Service,
+ public FlowLogService(Ec2Service ec2Service, S3Service s3Service, StorageFactory storageFactory) {
+ this(ec2Service, s3Service,
storageFactory.create("ec2", "ec2-flow-logs.json", new TypeReference<Map<String, FlowLog>>() {}));
}
// Package-private for hermetic tests (pass an in-memory StorageBackend directly).
- FlowLogService(EmulatorConfig config, Ec2Service ec2Service, S3Service s3Service,
+ FlowLogService(Ec2Service ec2Service, S3Service s3Service,
StorageBackend<String, FlowLog> flowLogs) {
- this.config = config;
this.ec2Service = ec2Service;
this.s3Service = s3Service;
this.flowLogs = flowLogs;
@@ -131,7 +127,7 @@ public class FlowLogService {
fl.setLogFormat(logFormat);
fl.setMaxAggregationInterval(maxAggregationInterval);
fl.setRegion(region);
- fl.setAccountId(config.defaultAccountId());
+ fl.setAccountId(ec2Service.callerAccountId());
flowLogs.put(fl.getFlowLogId(), fl);
LOG.infov("Created flow log {0} for {1} {2} -> {3}",
fl.getFlowLogId(), fl.getResourceType(), resourceId, fl.getBucketName());
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2OwnerAttributionTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2OwnerAttributionTest.java
new file mode 100644
index 0000000000..70af5c87e3
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2OwnerAttributionTest.java
@@ -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);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2OwnerIdIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2OwnerIdIntegrationTest.java
new file mode 100644
index 0000000000..e555920d71
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2OwnerIdIntegrationTest.java
@@ -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();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/FlowLogServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/FlowLogServiceTest.java
index ed2cfc9935..fd9543dc10 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/FlowLogServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/FlowLogServiceTest.java
@@ -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