fix(ec2): resolve instance profile names through IAM (#3856)

This commit is contained in:
luiseterc authored and GitHub committed 2026-09-18 08:46:22 -04:00
1 parent 6e034837ad
commit 5ec3fb67a8
8 files changed
+293 -12

No files matched your search

@@ -0,0 +1,78 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.InstanceType;
import software.amazon.awssdk.services.ec2.model.RequestLaunchTemplateData;
import software.amazon.awssdk.services.ec2.model.RunInstancesRequest;
import software.amazon.awssdk.services.iam.IamClient;
import java.util.UUID;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
class Ec2InstanceProfilePathTest {
static Stream<Arguments> launches() {
return Stream.of("direct", "template", "fleet", "override").flatMap(mode ->
Stream.of("/", "/workers/nested/").map(path -> Arguments.of(mode, path)));
}
@ParameterizedTest
@MethodSource("launches")
@DisplayName("EC2 launches resolve profile names to the full IAM ARN, including its path")
void preservesInstanceProfilePath(String mode, String path) {
String name = "profile-path-" + UUID.randomUUID();
try (Ec2Client ec2 = TestFixtures.ec2Client(); IamClient iam = TestFixtures.iamClient()) {
String profileArn = iam.createInstanceProfile(r -> r.instanceProfileName(name).path(path))
.instanceProfile().arn();
String instanceId = null;
String templateId = null;
try {
RunInstancesRequest.Builder launch = RunInstancesRequest.builder().minCount(1).maxCount(1);
if (mode.equals("direct")) {
launch.imageId("ami-0abcdef1234567890").instanceType(InstanceType.T3_MICRO)
.iamInstanceProfile(p -> p.name(name));
} else {
templateId = ec2.createLaunchTemplate(r -> r.launchTemplateName(name)
.launchTemplateData(RequestLaunchTemplateData.builder()
.imageId("ami-0abcdef1234567890").instanceType(InstanceType.T3_MICRO)
.iamInstanceProfile(p -> p.name(mode.equals("override") ? "missing-" + name : name))
.build())).launchTemplate().launchTemplateId();
String selectedTemplate = templateId;
launch.launchTemplate(t -> t.launchTemplateId(selectedTemplate).version("$Latest"));
if (mode.equals("override")) {
launch.iamInstanceProfile(p -> p.name(name));
}
}
if (mode.equals("fleet")) {
String selectedTemplate = templateId;
instanceId = ec2.createFleet(r -> r.type("instant")
.launchTemplateConfigs(c -> c.launchTemplateSpecification(t ->
t.launchTemplateId(selectedTemplate).version("$Latest")))
.targetCapacitySpecification(t -> t.totalTargetCapacity(1)
.defaultTargetCapacityType("on-demand")))
.instances().get(0).instanceIds().get(0);
} else {
instanceId = ec2.runInstances(launch.build()).instances().get(0).instanceId();
}
String selectedInstance = instanceId;
assertThat(ec2.describeInstances(r -> r.instanceIds(selectedInstance))
.reservations().get(0).instances().get(0).iamInstanceProfile().arn()).isEqualTo(profileArn);
} finally {
if (instanceId != null) {
String cleanupId = instanceId;
ec2.terminateInstances(r -> r.instanceIds(cleanupId));
}
if (templateId != null) {
String cleanupId = templateId;
ec2.deleteLaunchTemplate(r -> r.launchTemplateId(cleanupId));
}
iam.deleteInstanceProfile(r -> r.instanceProfileName(name));
}
}
}
}
+4 -2
View File
@@ -604,8 +604,10 @@ starts from empty data and is how a template moves between the two selection mod
Two behaviours worth calling out, because they are what Terraform reads back:
- **`IamInstanceProfile` keeps the form it was given.** A profile submitted as `Name` reads back as
`Name`, not rewritten to `Arn`. The instance-profile ARN is derived at launch time instead, so
`aws_launch_template.iam_instance_profile.name` converges.
`Name`, not rewritten to `Arn`. At launch time, Floci resolves that name against IAM in the
caller's account and preserves the profile's full path in its ARN. A name missing from that
account is rejected with `InvalidParameterValue`. This also applies to direct `RunInstances`
requests and `CreateFleet` launches, so `aws_launch_template.iam_instance_profile.name` converges.
- **`NetworkInterfaces` stays a `NetworkInterfaces` block.** Its `Groups` are not hoisted into
top-level `SecurityGroupIds`; on AWS the two are mutually exclusive. A launch from the template
resolves its security groups from whichever of the two is populated.
@@ -754,8 +754,9 @@ public class Ec2QueryHandler {
userData = launchTemplateData.getUserData();
userDataEncoded = launchTemplateData.getEncodedUserData();
}
iamInstanceProfileArn = firstNonBlank(iamInstanceProfileArn,
service.iamInstanceProfileArn(launchTemplateData));
if (iamInstanceProfileArn == null) {
iamInstanceProfileArn = service.iamInstanceProfileArn(launchTemplateData);
}
if (sgIds.isEmpty()) {
sgIds = new ArrayList<>(launchTemplateData.effectiveSecurityGroupIds());
}
@@ -4478,7 +4479,7 @@ public class Ec2QueryHandler {
if (name == null || name.isBlank()) {
return null;
}
return AwsArnUtils.Arn.of("iam", "", service.callerAccountId(), "instance-profile/" + name).toString();
return service.resolveIamInstanceProfileName(name);
}
private String vpcXml(Vpc vpc) {
@@ -107,6 +107,8 @@ import io.github.hectorvent.floci.services.ec2.model.VpcEndpointSubnetConfigurat
import io.github.hectorvent.floci.services.ec2.model.VpcPeeringConnection;
import io.github.hectorvent.floci.services.ec2.model.VpcPeeringConnectionStateReason;
import io.github.hectorvent.floci.services.ec2.model.VpcPeeringConnectionVpcInfo;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import jakarta.annotation.PostConstruct;
import io.github.hectorvent.floci.services.ec2.model.LaunchSpecification;
import io.github.hectorvent.floci.services.ec2.model.SpotInstanceRequest;
@@ -147,6 +149,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
private final String defaultAccountId;
private final jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance;
private final EmulatorConfig config;
private final IamService iamService;
private final Ec2ContainerManager containerManager;
private final Ec2PortForwardManager portForwardManager;
private final AmiImageResolver amiImageResolver;
@@ -227,9 +230,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
Ec2InstanceTypeCatalog instanceTypeCatalog, StorageFactory storageFactory,
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,
VpcNetworkManager vpcNetworkManager) {
VpcNetworkManager vpcNetworkManager, IamService iamService) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog,
instanceTypeCatalog, storageFactory, requestContextInstance);
instanceTypeCatalog, storageFactory, requestContextInstance, iamService);
this.vpcNetworkManager = vpcNetworkManager;
}
@@ -238,6 +241,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
Ec2InstanceTypeCatalog instanceTypeCatalog, StorageFactory storageFactory,
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog,
instanceTypeCatalog, storageFactory, requestContextInstance, null);
}
public Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
Ec2PortForwardManager portForwardManager,
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
Ec2InstanceTypeCatalog instanceTypeCatalog, StorageFactory storageFactory,
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,
IamService iamService) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog, instanceTypeCatalog,
storageFactory.create("ec2", "ec2-vpcs.json", new TypeReference<Map<String, Vpc>>() {}),
storageFactory.create("ec2", "ec2-subnets.json", new TypeReference<Map<String, Subnet>>() {}),
@@ -273,7 +286,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
new TypeReference<Map<String, NetworkInterface>>() {}),
storageFactory.create("ec2", "ec2-capacity-reservations.json",
new TypeReference<Map<String, CapacityReservation>>() {}),
requestContextInstance);
requestContextInstance, iamService);
}
// Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly).
@@ -383,6 +396,49 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
StorageBackend<String, NetworkInterface> networkInterfaces,
StorageBackend<String, CapacityReservation> capacityReservations,
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog,
instanceTypeCatalog, vpcs, subnets, securityGroups, securityGroupRules,
internetGateways, routeTables, keyPairs, addresses, instances,
volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,
transitGateways, transitGatewayRouteTables, transitGatewayVpcAttachments,
transitGatewayPropagations, transitGatewayRoutes, vpcPeeringConnections, networkInterfaces, capacityReservations, requestContextInstance, null);
}
Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
Ec2PortForwardManager portForwardManager,
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
Ec2InstanceTypeCatalog instanceTypeCatalog,
StorageBackend<String, Vpc> vpcs,
StorageBackend<String, Subnet> subnets,
StorageBackend<String, SecurityGroup> securityGroups,
StorageBackend<String, SecurityGroupRule> securityGroupRules,
StorageBackend<String, InternetGateway> internetGateways,
StorageBackend<String, RouteTable> routeTables,
StorageBackend<String, KeyPair> keyPairs,
StorageBackend<String, Address> addresses,
StorageBackend<String, Instance> instances,
StorageBackend<String, Volume> volumes,
StorageBackend<String, Image> registeredImages,
StorageBackend<String, Snapshot> snapshots,
StorageBackend<String, LaunchTemplate> launchTemplates,
StorageBackend<String, VpcEndpoint> vpcEndpoints,
StorageBackend<String, NatGateway> natGateways,
StorageBackend<String, SpotInstanceRequest> spotInstanceRequests,
StorageBackend<String, NetworkAcl> networkAcls,
StorageBackend<String, ManagedPrefixList> managedPrefixLists,
StorageBackend<String, List<Tag>> tags,
StorageBackend<String, TransitGateway> transitGateways,
StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables,
StorageBackend<String, TransitGatewayVpcAttachment> transitGatewayVpcAttachments,
StorageBackend<String, TransitGatewayRouteTablePropagation> transitGatewayPropagations,
StorageBackend<String, TransitGatewayRoute> transitGatewayRoutes,
StorageBackend<String, VpcPeeringConnection> vpcPeeringConnections,
StorageBackend<String, NetworkInterface> networkInterfaces,
StorageBackend<String, CapacityReservation> capacityReservations,
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance,
IamService iamService) {
this.iamService = iamService;
this.defaultAccountId = config.defaultAccountId();
this.requestContextInstance = requestContextInstance;
this.config = config;
@@ -5559,7 +5615,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
/**
* The instance-profile ARN a launch from {@code data} should use. A template given only a
* {@code Name} keeps that form as stored; the ARN is derived here, at launch time, instead of
* {@code Name} keeps that form as stored; the ARN is resolved from IAM here, at launch time, instead of
* being written back into the template.
*/
public String iamInstanceProfileArn(LaunchTemplateData data) {
@@ -5573,7 +5629,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
if (profile.getName() == null || profile.getName().isBlank()) {
return null;
}
return AwsArnUtils.Arn.of("iam", "", callerAccountId(), "instance-profile/" + profile.getName()).toString();
return resolveIamInstanceProfileName(profile.getName());
}
public String resolveIamInstanceProfileName(String name) {
if (iamService == null) {
throw new IllegalStateException("IAM service is required to resolve instance profile names");
}
return iamService.findInstanceProfile(callerAccountId(), name)
.map(InstanceProfile::getArn)
.orElseThrow(() -> new AwsException("InvalidParameterValue",
"Invalid IAM Instance Profile name: " + name, 400));
}
public LaunchTemplateData resolveLaunchTemplateData(String region, String id, String name, String version) {
@@ -0,0 +1,129 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.iam.IamService;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Instant;
import java.util.UUID;
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.assertTrue;
@QuarkusTest
class Ec2InstanceProfilePathIntegrationTest {
@Inject IamService iam;
@Inject Ec2Service ec2;
@ParameterizedTest
@ValueSource(strings = {"direct", "template", "fleet"})
void resolvesProfileInCallerAccountAndPreservesItsPath(String launch) {
String name = "profile-path-" + UUID.randomUUID().toString().substring(0, 8);
String account = "246813579012";
String other = "135792468013";
String arn = "arn:aws:iam::" + account + ":instance-profile/workers/nested/" + name;
String roleArn = "arn:aws:iam::" + account + ":role/" + name;
String template = null;
String instanceId = null;
request(account, "iam", "CreateRole").formParam("RoleName", name)
.formParam("AssumeRolePolicyDocument", "{}").post("/").then().statusCode(200);
request(account, "iam", "CreateInstanceProfile").formParam("InstanceProfileName", name)
.formParam("Path", "/workers/nested/").post("/").then().statusCode(200);
request(other, "iam", "CreateInstanceProfile").formParam("InstanceProfileName", name)
.formParam("Path", "/other/").post("/").then().statusCode(200);
request(account, "iam", "AddRoleToInstanceProfile").formParam("InstanceProfileName", name)
.formParam("RoleName", name).post("/").then().statusCode(200);
Ec2InstanceCredentials credentials = new Ec2InstanceCredentials(iam);
try {
RequestSpecification run = request(account, "ec2", "RunInstances")
.formParam("MinCount", "1").formParam("MaxCount", "1");
if (launch.equals("direct")) {
run.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
.formParam("IamInstanceProfile.Name", name);
} else {
template = request(account, "ec2", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", name)
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.formParam("LaunchTemplateData.IamInstanceProfile.Name", name)
.post("/").then().statusCode(200)
.extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
run.formParam("LaunchTemplate.LaunchTemplateId", template)
.formParam("LaunchTemplate.Version", "1");
}
if (launch.equals("fleet")) {
instanceId = request(account, "ec2", "CreateFleet").formParam("Type", "instant")
.formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.LaunchTemplateId", template)
.formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.Version", "1")
.formParam("TargetCapacitySpecification.TotalTargetCapacity", "1")
.formParam("TargetCapacitySpecification.DefaultTargetCapacityType", "on-demand")
.post("/").then().statusCode(200)
.extract().path("CreateFleetResponse.fleetInstanceSet.item.instanceIds.item");
} else {
instanceId = run.post("/").then().statusCode(200)
.body("RunInstancesResponse.instancesSet.item.iamInstanceProfile.arn", equalTo(arn))
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
}
request(account, "ec2", "DescribeInstances").formParam("InstanceId.1", instanceId)
.post("/").then().statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.iamInstanceProfile.arn",
equalTo(arn));
Instance instance = ec2.findInstanceForAccount(account, "us-east-1", instanceId).orElseThrow();
credentials.register(instance);
assertEquals(roleArn, credentials.role(instance).orElseThrow().getArn());
assertTrue(credentials.get(instance, name, Instant.now()).isPresent());
} finally {
credentials.clear();
if (instanceId != null) {
request(account, "ec2", "TerminateInstances").formParam("InstanceId.1", instanceId)
.post("/").then().statusCode(200);
}
if (template != null) {
request(account, "ec2", "DeleteLaunchTemplate").formParam("LaunchTemplateId", template)
.post("/").then().statusCode(200);
}
request(account, "iam", "RemoveRoleFromInstanceProfile").formParam("InstanceProfileName", name)
.formParam("RoleName", name).post("/").then().statusCode(200);
for (String owner : new String[]{account, other}) {
request(owner, "iam", "DeleteInstanceProfile").formParam("InstanceProfileName", name)
.post("/").then().statusCode(200);
}
request(account, "iam", "DeleteRole").formParam("RoleName", name).post("/").then().statusCode(200);
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void rejectsNamesMissingFromCallerAccount(boolean existsInOtherAccount) {
String name = "missing-profile-" + UUID.randomUUID().toString().substring(0, 8);
String other = "135792468013";
if (existsInOtherAccount) {
request(other, "iam", "CreateInstanceProfile").formParam("InstanceProfileName", name)
.post("/").then().statusCode(200);
}
try {
request("246813579012", "ec2", "RunInstances")
.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
.formParam("MinCount", "1").formParam("MaxCount", "1")
.formParam("IamInstanceProfile.Name", name).post("/").then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
} finally {
if (existsInOtherAccount) {
request(other, "iam", "DeleteInstanceProfile").formParam("InstanceProfileName", name)
.post("/").then().statusCode(200);
}
}
}
private static RequestSpecification request(String account, String service, String action) {
return given().header("Authorization", "AWS4-HMAC-SHA256 Credential=" + account
+ "/20260918/us-east-1/" + service + "/aws4_request, SignedHeaders=host, Signature=abc")
.formParam("Action", action);
}
}
@@ -2254,6 +2254,9 @@ class Ec2IntegrationTest {
@Test
@Order(49)
void runInstancesResolvesLaunchTemplateDefaultsWithRequestOverrides() {
given().header("Authorization", AUTH_HEADER.replace("/ec2/", "/iam/"))
.formParam("Action", "CreateInstanceProfile").formParam("InstanceProfileName", "sample-profile-v2")
.post("/").then().statusCode(200);
String launchedInstanceId = given()
.formParam("Action", "RunInstances")
.formParam("LaunchTemplate.LaunchTemplateId", launchTemplateId)
@@ -76,8 +76,8 @@ class Ec2OwnerIdIntegrationTest {
@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().header("Authorization", AUTH.replace("/ec2/", "/iam/")).formParam("Action", "CreateInstanceProfile")
.formParam("InstanceProfileName", "owner-profile").post("/").then().statusCode(200);
given()
.formParam("Action", "RunInstances")
.formParam("ImageId", "ami-0abcdef1234567890")
@@ -124,6 +124,8 @@ class Ec2Phase2IntegrationTest {
@Order(12)
void runInstancesWithIamInstanceProfileName() {
String profileName = "my-app-profile";
given().header("Authorization", AUTH_HEADER.replace("/ec2/", "/iam/")).formParam("Action", "CreateInstanceProfile")
.formParam("InstanceProfileName", profileName).post("/").then().statusCode(200);
instanceWithProfileName = given()
.formParam("Action", "RunInstances")