fix(ec2): preserve IAM instance profile identity (#5671)

* fix(ec2): preserve IAM instance profile identity

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): probe metadata readiness with IMDSv2

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(autoscaling): preserve launch profiles and metadata options

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): preserve automatic public addresses across launch paths

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): honor metadata token requirements and profile identity

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): keep synthesized node identity and mock addresses consistent

- IMDS iam/info serves the instance profile identity EKS synthesizes for
  its cluster nodes while IAM holds no such profile. The node carries a
  stable IAM-shaped profile id, which DescribeInstances now copies too.
- Mock instances get their automatic public address however the launch
  completes, DescribeInstanceStatus included. An associated Elastic IP
  replaces it, disassociating gives a running instance a new one, and
  termination leaves none.
- CreateFleet forwards the launch template's metadata options and its
  primary interface AssociatePublicIpAddress.
- Launch templates store a profile name and ARN pair as given and the
  launch from them rejects it, since AWS does not fully validate
  template parameters at creation.
- CloudFormation launch-configuration MetadataOptions resolve Fn::If and
  AWS::NoValue.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): refuse profile pairs for groups and keep Elastic IPs exclusive

- Auto Scaling refuses a group whose launch template, directly or
  through its mixed instances policy, names both an instance profile
  name and an ARN, with ValidationError, instead of accepting a group
  that can never launch.
- AssociateAddress disassociates the Elastic IP an instance already
  has, as AWS documents. In mock mode a terminated instance takes no
  address, and an unchanged address is not written again.
- IMDS iam/info falls back to a cluster node's synthesized identity
  only while IAM holds no profile at that ARN; a held profile without a
  role answers 404.
- CreateFleet takes the subnet of the device-index-0 interface first,
  as RunInstances does.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): assert profile ids and launch configuration metadata via the SDK

Ec2InstanceProfilePathTest now checks that direct, template, override
and fleet launches report IAM's InstanceProfileId, and AutoScalingTest
round-trips launch configuration MetadataOptions through the AWS SDK for
Java v2, including the absent structure and a rejected hop limit.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): displace an Elastic IP a retained interface carries

- AssociateAddress also disassociates an Elastic IP held by the
  instance's primary interface, which a retained network interface
  carries from an earlier instance, so one instance never holds two.
- Mock stop and terminate change the instance's state and public
  address under its lock, like the launch and Elastic IP writes.
- Docs and comments say where the profile pair fails and when
  CreateFleet falls back to another interface's subnet.
- Tests cover the retained-interface address, the group update path,
  the full refusal message and the fleet's availability zone, and the
  SDK launch configuration test cleans up on failure.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): refuse reserved RunInstances tags before resolving the profile

Resolving the instance profile called the EC2 service before tag parsing,
so a reserved aws: tag was refused only after that lookup. Parse tags first,
as the reserved-tag check requires.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(autoscaling): assert the refresh launched the replacement

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(autoscaling): describe what the refresh assertion checks

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): cover invalid launch-configuration metadata options

Invalid HttpTokens, invalid HttpEndpoint, hop limits of 0 and 65 and a
non-integer hop limit each fail the AWS::AutoScaling::LaunchConfiguration
resource with the validation message, roll the stack back and leave no
launch configuration behind.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): pin metadata failure reasons and accepted hop limits

Assert the exact resource failure reason, and cover hop limits of 1 and 64,
a string hop limit and one from a Number parameter.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* refactor(ec2): leave IMDS token enforcement to a separate change

HttpTokens=required enforcement, the IMDSv2 readiness probe and the helper
shell environment reset move to their own pull request, so this change
keeps only the instance profile identity.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* refactor(ec2): leave mock public addresses to a separate change

Mock public IPv4 assignment, primary-interface public IP and subnet handling
and Elastic IP displacement move to their own pull request.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* refactor(autoscaling): leave launch metadata options to a separate change

Launch-configuration MetadataOptions over Query and CloudFormation, and
metadata options forwarded from launch templates and EC2 Fleet, move to
their own pull request. Launch-configuration profile resolution stays.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): use the shared metadata and authorization fixtures

Ec2MetadataProfileIntegrationTest starts its metadata server and requests
tokens through Ec2MetadataTestFixture, and it and
Ec2InstanceProfileIdentityIntegrationTest build their Authorization header
with EnforcementFixtures.auth.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* docs(ec2): close the Auto Scaling profile paragraph's code fence

Removes a stray fence that rendered the launch-configuration profile
paragraph as code, and a doubled blank line before the iam/info paragraph.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): find profile identity launches by a run tag

Each launch carries a tag unique to the test run, and the tests look their
instances up by that tag rather than by client token.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* refactor(ec2): leave the client-token filter to a separate change

The instance filter is not part of the profile identity, and this copy let
a wildcard match instances launched without a token.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

---------

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-17 08:03:38 -04:00
1 parent fa2a49e771
commit 0be4581d4e
19 files changed
+840 -68

No files matched your search

@@ -0,0 +1,179 @@
package io.github.hectorvent.floci.services.autoscaling;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
@QuarkusTest
class AutoScalingLaunchConfigurationIdentityIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=222222222222/20261012/us-east-1/autoscaling/aws4_request";
@Inject
AutoScalingReconciler reconciler;
@ParameterizedTest
@ValueSource(booleans = {false, true})
void launchResolvesProfile(boolean useArn) {
String name = "launch-identity-" + UUID.randomUUID();
XmlPath profile = given().header("Authorization", AUTH.replace("/autoscaling/", "/iam/"))
.formParam("Action", "CreateInstanceProfile").formParam("InstanceProfileName", name)
.post("/").then().statusCode(200).extract().xmlPath();
String arn = profile.getString("CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.Arn");
String profileId = profile.getString(
"CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.InstanceProfileId");
given().header("Authorization", AUTH).formParam("Action", "CreateLaunchConfiguration")
.formParam("LaunchConfigurationName", name).formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t3.micro").formParam("IamInstanceProfile", useArn ? arn : name)
.post("/").then().statusCode(200);
given().header("Authorization", AUTH).formParam("Action", "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", name).formParam("LaunchConfigurationName", name)
.formParam("MinSize", "1").formParam("MaxSize", "1").formParam("DesiredCapacity", "1")
.formParam("AvailabilityZones.member.1", "us-east-1a").post("/").then().statusCode(200);
reconciler.reconcileAll();
String instance = given().header("Authorization", AUTH)
.formParam("Action", "DescribeAutoScalingGroups").formParam("AutoScalingGroupNames.member.1", name)
.post("/").then().statusCode(200)
.body("DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult"
+ ".AutoScalingGroups.member.Instances.member.size()", equalTo(1))
.extract().path("DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult"
+ ".AutoScalingGroups.member.Instances.member.InstanceId");
given().header("Authorization", AUTH.replace("/autoscaling/", "/ec2/")).formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", instance).post("/").then().statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.iamInstanceProfile.arn", equalTo(arn))
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.iamInstanceProfile.id", equalTo(profileId));
}
@Test
void refreshReplacementResolvesProfile() {
String name = "refresh-identity-" + UUID.randomUUID();
String arn = given().header("Authorization", AUTH.replace("/autoscaling/", "/iam/"))
.formParam("Action", "CreateInstanceProfile").formParam("InstanceProfileName", name)
.post("/").then().statusCode(200).extract().path(
"CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.Arn");
given().header("Authorization", AUTH).formParam("Action", "CreateLaunchConfiguration")
.formParam("LaunchConfigurationName", name).formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t3.micro").formParam("IamInstanceProfile", name)
.post("/").then().statusCode(200);
given().header("Authorization", AUTH).formParam("Action", "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", name).formParam("LaunchConfigurationName", name)
.formParam("MinSize", "1").formParam("MaxSize", "1").formParam("DesiredCapacity", "1")
.formParam("AvailabilityZones.member.1", "us-east-1a").post("/").then().statusCode(200);
String instancePath = "DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult"
+ ".AutoScalingGroups.member.Instances.member.InstanceId";
reconciler.reconcileAll();
reconciler.reconcileAll();
String original = given().header("Authorization", AUTH).formParam("Action", "DescribeAutoScalingGroups")
.formParam("AutoScalingGroupNames.member.1", name).post("/").then().statusCode(200)
.extract().path(instancePath);
String refreshId = given().header("Authorization", AUTH).formParam("Action", "StartInstanceRefresh")
.formParam("AutoScalingGroupName", name).post("/").then().statusCode(200).extract().path(
"StartInstanceRefreshResponse.StartInstanceRefreshResult.InstanceRefreshId");
reconciler.reconcileAll();
reconciler.reconcileAll();
// The refresh completes once its replacement is in service.
given().header("Authorization", AUTH).formParam("Action", "DescribeInstanceRefreshes")
.formParam("AutoScalingGroupName", name).formParam("InstanceRefreshIds.member.1", refreshId)
.post("/").then().statusCode(200)
.body("DescribeInstanceRefreshesResponse.DescribeInstanceRefreshesResult"
+ ".InstanceRefreshes.member.Status", equalTo("Successful"));
String replacement = given().header("Authorization", AUTH).formParam("Action", "DescribeAutoScalingGroups")
.formParam("AutoScalingGroupNames.member.1", name).post("/").then().statusCode(200)
.extract().path(instancePath);
assertThat(replacement, not(equalTo(original)));
String item = "DescribeInstancesResponse.reservationSet.item.instancesSet.item";
given().header("Authorization", AUTH.replace("/autoscaling/", "/ec2/")).formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", replacement).post("/").then().statusCode(200)
.body(item + ".iamInstanceProfile.arn", equalTo(arn));
given().header("Authorization", AUTH).formParam("Action", "DeleteAutoScalingGroup")
.formParam("AutoScalingGroupName", name).formParam("ForceDelete", "true")
.post("/").then().statusCode(200);
}
@ParameterizedTest
@ValueSource(strings = {"create", "mixed", "update"})
void groupRefusesALaunchTemplateNamingBothProfileSelectors(String request) {
String name = "pair-template-" + UUID.randomUUID();
String ec2 = AUTH.replace("/autoscaling/", "/ec2/");
String arn = given().header("Authorization", AUTH.replace("/autoscaling/", "/iam/"))
.formParam("Action", "CreateInstanceProfile").formParam("InstanceProfileName", name)
.post("/").then().statusCode(200).extract().path(
"CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.Arn");
String template = given().header("Authorization", ec2)
.formParam("Action", "CreateLaunchTemplate").formParam("LaunchTemplateName", name)
.formParam("LaunchTemplateData.ImageId", "ami-amazonlinux2023")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.formParam("LaunchTemplateData.IamInstanceProfile.Name", name)
.post("/").then().statusCode(200)
.extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
// Version 2 adds the ARN beside the name; version 1 names the profile once.
given().header("Authorization", ec2).formParam("Action", "CreateLaunchTemplateVersion")
.formParam("LaunchTemplateId", template)
.formParam("LaunchTemplateData.ImageId", "ami-amazonlinux2023")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.formParam("LaunchTemplateData.IamInstanceProfile.Name", name)
.formParam("LaunchTemplateData.IamInstanceProfile.Arn", arn)
.post("/").then().statusCode(200);
String prefix = "mixed".equals(request)
? "MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification." : "LaunchTemplate.";
if ("update".equals(request)) {
given().header("Authorization", AUTH).formParam("Action", "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", name).formParam(prefix + "LaunchTemplateId", template)
.formParam(prefix + "Version", "1")
.formParam("MinSize", "0").formParam("MaxSize", "1").formParam("DesiredCapacity", "0")
.formParam("AvailabilityZones.member.1", "us-east-1a").post("/").then().statusCode(200);
}
given().header("Authorization", AUTH)
.formParam("Action", "update".equals(request) ? "UpdateAutoScalingGroup" : "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", name).formParam(prefix + "LaunchTemplateId", template)
.formParam(prefix + "Version", "2")
.formParam("MinSize", "0").formParam("MaxSize", "1").formParam("DesiredCapacity", "1")
.formParam("AvailabilityZones.member.1", "us-east-1a").post("/").then().statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo("You must use a valid fully-formed launch template. "
+ "The parameter iamInstanceProfile.name may not be used with iamInstanceProfile.arn."));
String group = "DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult.AutoScalingGroups.member";
ValidatableResponse described = given().header("Authorization", AUTH)
.formParam("Action", "DescribeAutoScalingGroups")
.formParam("AutoScalingGroupNames.member.1", name).post("/").then().statusCode(200);
if ("update".equals(request)) {
described.body(group + ".LaunchTemplate.Version", equalTo("1"));
given().header("Authorization", AUTH).formParam("Action", "DeleteAutoScalingGroup")
.formParam("AutoScalingGroupName", name).formParam("ForceDelete", "true")
.post("/").then().statusCode(200);
} else {
described.body(group + ".size()", equalTo(0));
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void missingOrForeignProfileRefusesLaunchConfiguration(boolean foreignArn) {
String name = "refused-profile-" + UUID.randomUUID();
if (foreignArn) {
given().header("Authorization", AUTH.replace("/autoscaling/", "/iam/"))
.formParam("Action", "CreateInstanceProfile").formParam("InstanceProfileName", name)
.post("/").then().statusCode(200);
}
given().header("Authorization", AUTH).formParam("Action", "CreateLaunchConfiguration")
.formParam("LaunchConfigurationName", name).formParam("ImageId", "ami-amazonlinux2023")
.formParam("InstanceType", "t3.micro").formParam("IamInstanceProfile",
foreignArn ? "arn:aws:iam::333333333333:instance-profile/" + name : name)
.post("/").then().statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
given().header("Authorization", AUTH).formParam("Action", "DescribeLaunchConfigurations")
.formParam("LaunchConfigurationNames.member.1", name).post("/").then().statusCode(200)
.body("DescribeLaunchConfigurationsResponse.DescribeLaunchConfigurationsResult"
+ ".LaunchConfigurations.member.size()", equalTo(0));
}
}
@@ -259,6 +259,8 @@ class AutoScalingServiceTest {
source.setSecurityGroups(List.of(new GroupIdentifier("sg-source", "default")));
source.setUserData("source-user-data");
source.setIamInstanceProfileArn("arn:aws:iam::000000000000:instance-profile/source");
when(ec2Service.resolveIamInstanceProfileName("source"))
.thenReturn(source.getIamInstanceProfileArn());
Reservation reservation = new Reservation();
reservation.getInstances().add(source);
when(ec2Service.describeInstances(REGION, List.of("i-1234567890abcdef0"), java.util.Map.of()))
@@ -0,0 +1,271 @@
package io.github.hectorvent.floci.services.ec2;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import java.util.List;
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.assertNull;
@QuarkusTest
class Ec2InstanceProfileIdentityIntegrationTest {
private static final String ACCOUNT = "246813579012";
private static final String OTHER = "135792468013";
private static final String LAUNCH_TAG = "floci-test-launch";
@Inject Ec2Service ec2;
@Inject ObjectMapper mapper;
@ParameterizedTest
@CsvSource({"Name,false", "Arn,false", "Name,true", "Arn,true"})
void launchUsesTheSameIamIdentityForEveryInstance(String field, boolean template) {
String name = "profile-identity-" + UUID.randomUUID().toString().substring(0, 8);
Profile profile = createProfile(ACCOUNT, name);
List<String> instances = new ArrayList<>();
String templateId = null;
try {
RequestSpecification run = tagged(request(ACCOUNT, "ec2", "RunInstances")
.formParam("MinCount", "2").formParam("MaxCount", "2"), name);
String value = field.equals("Name") ? name : profile.arn();
if (template) {
templateId = request(ACCOUNT, "ec2", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", name)
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.formParam("LaunchTemplateData.IamInstanceProfile." + field, value)
.post("/").then().statusCode(200)
.extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
run.formParam("LaunchTemplate.LaunchTemplateId", templateId);
} else {
run.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
.formParam("IamInstanceProfile." + field, value);
}
XmlPath response = run.post("/").then().statusCode(200).extract().xmlPath();
instances.addAll(response.getList("RunInstancesResponse.instancesSet.item.instanceId"));
assertEquals(List.of(profile.id(), profile.id()),
response.getList("RunInstancesResponse.instancesSet.item.iamInstanceProfile.id"));
assertEquals(instances.stream().sorted().toList(), launchedWith(name).stream().sorted().toList());
for (String id : instances) {
assertProfile(id, profile);
}
} finally {
for (String id : instances) {
terminate(id);
}
if (templateId != null) {
request(ACCOUNT, "ec2", "DeleteLaunchTemplate").formParam("LaunchTemplateId", templateId)
.post("/").then().statusCode(200);
}
deleteProfile(ACCOUNT, name);
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void invalidArnsCannotCreateInstances(boolean template) {
String name = "profile-invalid-" + UUID.randomUUID().toString().substring(0, 8);
Profile own = createProfile(ACCOUNT, name);
Profile other = createProfile(OTHER, name);
try {
for (String arn : List.of(own.arn() + "-absent", other.arn(),
own.arn().replace("/workers/", "/other/"),
own.arn().replace(":instance-profile/", ":role/"),
own.arn().replace("arn:aws:", "arn:aws-cn:"))) {
String launchTag = UUID.randomUUID().toString();
String templateId = null;
try {
RequestSpecification run = tagged(request(ACCOUNT, "ec2", "RunInstances")
.formParam("MinCount", "1").formParam("MaxCount", "1"), launchTag);
if (template) {
ValidatableResponse created = request(ACCOUNT, "ec2", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", "invalid-" + launchTag)
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.formParam("LaunchTemplateData.IamInstanceProfile.Arn", arn)
.post("/").then();
if (arn.contains(":role/") || arn.startsWith("arn:aws-cn:")) {
created.statusCode(400).body("Response.Errors.Error.Code",
equalTo("InvalidIamInstanceProfileArn.Malformed"));
continue;
}
templateId = created.statusCode(200)
.extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
run.formParam("LaunchTemplate.LaunchTemplateId", templateId);
} else {
run.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
.formParam("IamInstanceProfile.Arn", arn);
}
run.post("/").then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
assertEquals(List.of(), launchedWith(launchTag));
} finally {
if (templateId != null) {
request(ACCOUNT, "ec2", "DeleteLaunchTemplate").formParam("LaunchTemplateId", templateId)
.post("/").then().statusCode(200);
}
}
}
} finally {
deleteProfile(ACCOUNT, name);
deleteProfile(OTHER, name);
}
}
@Test
void attachmentIdentityIsPersistedAndUnknownLegacyIdsAreOmitted() throws Exception {
String name = "profile-stored-" + UUID.randomUUID().toString().substring(0, 8);
Profile profile = createProfile(ACCOUNT, name);
String id = request(ACCOUNT, "ec2", "RunInstances")
.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
.formParam("IamInstanceProfile.Name", name).post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
try {
Instance stored = ec2.findInstanceForAccount(ACCOUNT, "us-east-1", id).orElseThrow();
Instance roundTrip = mapper.readValue(mapper.writeValueAsBytes(stored), Instance.class);
assertEquals(profile.id(), roundTrip.getIamInstanceProfileId());
roundTrip.setIamInstanceProfileId(null);
assertNull(mapper.readValue(mapper.writeValueAsBytes(roundTrip), Instance.class)
.getIamInstanceProfileId());
stored.setIamInstanceProfileId(null);
request(ACCOUNT, "ec2", "DescribeInstances").formParam("InstanceId.1", id)
.post("/").then().statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.iamInstanceProfile.id.size()",
equalTo(0));
} finally {
terminate(id);
deleteProfile(ACCOUNT, name);
}
}
@Test
void replacementUsesArnWhenBothSelectorsAreProvided() {
String name = "profile-replace-" + UUID.randomUUID().toString().substring(0, 8);
Profile first = createProfile(ACCOUNT, name);
Profile second = createProfile(ACCOUNT, name + "-second");
String id = request(ACCOUNT, "ec2", "RunInstances")
.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
.formParam("IamInstanceProfile.Name", name).post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
try {
String association = Ec2Service.iamInstanceProfileAssociationId(id);
request(ACCOUNT, "ec2", "ReplaceIamInstanceProfileAssociation")
.formParam("AssociationId", association).formParam("IamInstanceProfile.Name", name)
.formParam("IamInstanceProfile.Arn", second.arn()).post("/").then().statusCode(200)
.body("ReplaceIamInstanceProfileAssociationResponse.iamInstanceProfileAssociation"
+ ".iamInstanceProfile.id", equalTo(second.id()));
assertProfile(id, second);
request(ACCOUNT, "ec2", "DisassociateIamInstanceProfile").formParam("AssociationId", association)
.post("/").then().statusCode(200)
.body("DisassociateIamInstanceProfileResponse.iamInstanceProfileAssociation"
+ ".iamInstanceProfile.id", equalTo(second.id()));
} finally {
terminate(id);
deleteProfile(ACCOUNT, name);
deleteProfile(ACCOUNT, name + "-second");
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void launchRejectsBothProfileSelectors(boolean template) {
String name = "profile-selectors-" + UUID.randomUUID().toString().substring(0, 8);
Profile profile = createProfile(ACCOUNT, name);
String launchTag = UUID.randomUUID().toString();
String templateId = null;
try {
RequestSpecification run = tagged(request(ACCOUNT, "ec2", "RunInstances"), launchTag);
if (template) {
// As on AWS, a template is not fully validated when it is created: the pair is
// stored, and the launch from it is what fails.
templateId = request(ACCOUNT, "ec2", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", name)
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.formParam("LaunchTemplateData.IamInstanceProfile.Name", name)
.formParam("LaunchTemplateData.IamInstanceProfile.Arn", profile.arn())
.post("/").then().statusCode(200)
.extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
run.formParam("LaunchTemplate.LaunchTemplateId", templateId);
} else {
run.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
.formParam("IamInstanceProfile.Name", name)
.formParam("IamInstanceProfile.Arn", profile.arn());
}
run.post("/").then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination"));
assertEquals(List.of(), launchedWith(launchTag));
} finally {
if (templateId != null) {
request(ACCOUNT, "ec2", "DeleteLaunchTemplate").formParam("LaunchTemplateId", templateId)
.post("/").then().statusCode(200);
}
deleteProfile(ACCOUNT, name);
}
}
private static void assertProfile(String instanceId, Profile profile) {
request(ACCOUNT, "ec2", "DescribeInstances").formParam("InstanceId.1", instanceId)
.post("/").then().statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.iamInstanceProfile.arn",
equalTo(profile.arn()))
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.iamInstanceProfile.id",
equalTo(profile.id()));
request(ACCOUNT, "ec2", "DescribeIamInstanceProfileAssociations")
.formParam("Filter.1.Name", "instance-id").formParam("Filter.1.Value.1", instanceId)
.post("/").then().statusCode(200)
.body("DescribeIamInstanceProfileAssociationsResponse.iamInstanceProfileAssociationSet"
+ ".item.iamInstanceProfile.id", equalTo(profile.id()));
}
private static Profile createProfile(String account, String name) {
String prefix = "CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.";
XmlPath value = request(account, "iam", "CreateInstanceProfile")
.formParam("InstanceProfileName", name).formParam("Path", "/workers/").post("/")
.then().statusCode(200).extract().xmlPath();
return new Profile(value.getString(prefix + "Arn"), value.getString(prefix + "InstanceProfileId"));
}
private static void deleteProfile(String account, String name) {
request(account, "iam", "DeleteInstanceProfile").formParam("InstanceProfileName", name)
.post("/").then().statusCode(200);
}
/** Tags the launch's instances with a value unique to this test run, so a lookup finds only them. */
private static RequestSpecification tagged(RequestSpecification run, String value) {
return run.formParam("TagSpecification.1.ResourceType", "instance")
.formParam("TagSpecification.1.Tag.1.Key", LAUNCH_TAG)
.formParam("TagSpecification.1.Tag.1.Value", value);
}
private static List<String> launchedWith(String value) {
return request(ACCOUNT, "ec2", "DescribeInstances").formParam("Filter.1.Name", "tag:" + LAUNCH_TAG)
.formParam("Filter.1.Value.1", value).post("/").then().statusCode(200).extract().xmlPath()
.getList("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceId");
}
private static void terminate(String instanceId) {
request(ACCOUNT, "ec2", "TerminateInstances").formParam("InstanceId.1", instanceId)
.post("/").then().statusCode(200);
}
private static RequestSpecification request(String account, String service, String action) {
return given().header("Authorization", EnforcementFixtures.auth(account, service))
.formParam("Action", action);
}
private record Profile(String arn, String id) {}
}
@@ -0,0 +1,165 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import io.vertx.core.json.JsonObject;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.net.http.HttpResponse;
import java.util.Set;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
@QuarkusTest
class Ec2MetadataProfileIntegrationTest {
private static final String ACCOUNT = "246813579012";
private static final String TRUST_POLICY = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}
""";
@Inject
IamService iam;
@Test
void iamInfoMatchesCreatedProfileAndRejectsMissingOrMismatchedAttachments() throws Exception {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String roleName = "metadata-role-" + suffix;
String profileName = "metadata-profile-" + suffix;
iamRequest("CreateRole").formParam("RoleName", roleName)
.formParam("AssumeRolePolicyDocument", TRUST_POLICY)
.post("/").then().statusCode(200);
Response created = iamRequest("CreateInstanceProfile")
.formParam("InstanceProfileName", profileName).formParam("Path", "/nodes/")
.post("/").then().statusCode(200).extract().response();
String profileArn = created.xmlPath().getString(
"CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.Arn");
String profileId = created.xmlPath().getString(
"CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.InstanceProfileId");
Instance instance = Ec2MetadataTestFixture.instance("i-0123456789abcdef0");
instance.setIamInstanceProfileArn(profileArn);
boolean roleAdded = false;
boolean profileDeleted = false;
try (Ec2MetadataTestFixture fixture = new Ec2MetadataTestFixture()) {
fixture.start(iam, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), instance);
String token = token(fixture);
assertEquals(404, info(fixture, token).statusCode());
iamRequest("AddRoleToInstanceProfile")
.formParam("InstanceProfileName", profileName).formParam("RoleName", roleName)
.post("/").then().statusCode(200);
roleAdded = true;
HttpResponse<String> response = info(fixture, token);
assertEquals(200, response.statusCode());
JsonObject body = new JsonObject(response.body());
assertEquals("Success", body.getString("Code"));
assertEquals(profileArn, body.getString("InstanceProfileArn"));
assertEquals(profileId, body.getString("InstanceProfileId"));
instance.setIamInstanceProfileArn(profileArn.replace("/nodes/", "/other/"));
assertEquals(404, info(fixture, token).statusCode());
instance.setIamInstanceProfileArn(profileArn);
iamRequest("RemoveRoleFromInstanceProfile")
.formParam("InstanceProfileName", profileName).formParam("RoleName", roleName)
.post("/").then().statusCode(200);
roleAdded = false;
assertEquals(404, info(fixture, token).statusCode());
iamRequest("DeleteInstanceProfile").formParam("InstanceProfileName", profileName)
.post("/").then().statusCode(200);
profileDeleted = true;
assertEquals(404, info(fixture, token).statusCode());
} finally {
if (roleAdded) {
iamRequest("RemoveRoleFromInstanceProfile")
.formParam("InstanceProfileName", profileName).formParam("RoleName", roleName)
.post("/").then().statusCode(200);
}
if (!profileDeleted) {
iamRequest("DeleteInstanceProfile")
.formParam("InstanceProfileName", profileName).post("/").then().statusCode(200);
}
iamRequest("DeleteRole").formParam("RoleName", roleName).post("/").then().statusCode(200);
}
}
@Test
void clusterNodeReportsItsSynthesizedProfileUntilIamHoldsOne() throws Exception {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String roleName = "node-role-" + suffix;
String profileName = "cluster-" + suffix + "-node-profile";
String profileArn = "arn:aws:iam::" + ACCOUNT + ":instance-profile/" + profileName;
Instance node = Ec2MetadataTestFixture.instance("i-0fedcba9876543210");
node.setIamInstanceProfileArn(profileArn);
node.setIamInstanceProfileId("AIPA0FEDCBA9876543210");
boolean roleCreated = false;
boolean profileCreated = false;
boolean roleAttached = false;
try (Ec2MetadataTestFixture fixture = new Ec2MetadataTestFixture()) {
fixture.start(iam, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), node);
assertEquals(404, info(fixture, token(fixture)).statusCode());
fixture.server().unregisterInstance(node);
fixture.server().reconcileClusterNodeAddresses(Set.of(Ec2MetadataTestFixture.CALLER_IP), node);
HttpResponse<String> synthesized = info(fixture, token(fixture));
assertEquals(200, synthesized.statusCode());
JsonObject body = new JsonObject(synthesized.body());
assertEquals(profileArn, body.getString("InstanceProfileArn"));
assertEquals("AIPA0FEDCBA9876543210", body.getString("InstanceProfileId"));
iamRequest("CreateRole").formParam("RoleName", roleName)
.formParam("AssumeRolePolicyDocument", TRUST_POLICY)
.post("/").then().statusCode(200);
roleCreated = true;
String iamProfileId = iamRequest("CreateInstanceProfile")
.formParam("InstanceProfileName", profileName).post("/").then().statusCode(200)
.extract().path("CreateInstanceProfileResponse.CreateInstanceProfileResult"
+ ".InstanceProfile.InstanceProfileId");
profileCreated = true;
// Once IAM holds the profile its answer wins: no role yet is the empty-profile 404.
assertEquals(404, info(fixture, token(fixture)).statusCode());
iamRequest("AddRoleToInstanceProfile")
.formParam("InstanceProfileName", profileName).formParam("RoleName", roleName)
.post("/").then().statusCode(200);
roleAttached = true;
HttpResponse<String> backed = info(fixture, token(fixture));
assertEquals(200, backed.statusCode());
assertEquals(iamProfileId, new JsonObject(backed.body()).getString("InstanceProfileId"));
} finally {
if (roleAttached) {
iamRequest("RemoveRoleFromInstanceProfile")
.formParam("InstanceProfileName", profileName).formParam("RoleName", roleName)
.post("/").then().statusCode(200);
}
if (profileCreated) {
iamRequest("DeleteInstanceProfile")
.formParam("InstanceProfileName", profileName).post("/").then().statusCode(200);
}
if (roleCreated) {
iamRequest("DeleteRole").formParam("RoleName", roleName).post("/").then().statusCode(200);
}
}
}
private static String token(Ec2MetadataTestFixture fixture) throws Exception {
HttpResponse<String> token = fixture.putToken("60");
assertEquals(200, token.statusCode());
return token.body();
}
private static HttpResponse<String> info(Ec2MetadataTestFixture fixture, String token) throws Exception {
return fixture.get("/latest/meta-data/iam/info", token);
}
private static RequestSpecification iamRequest(String action) {
return given().header("Authorization", EnforcementFixtures.auth(ACCOUNT, "iam"))
.contentType("application/x-www-form-urlencoded").formParam("Action", action);
}
}
@@ -85,6 +85,9 @@ class Ec2Phase2IntegrationTest {
@Order(10)
void runInstancesWithIamInstanceProfile() {
String profileArn = "arn:aws:iam::000000000000:instance-profile/my-app-role";
given().header("Authorization", AUTH_HEADER.replace("/ec2/", "/iam/"))
.formParam("Action", "CreateInstanceProfile").formParam("InstanceProfileName", "my-app-role")
.post("/").then().statusCode(200);
instanceWithProfile = given()
.formParam("Action", "RunInstances")
@@ -342,7 +342,7 @@ class Ec2ServicePersistenceTest {
.getFirst()
.getData();
assertEquals("arn:aws:iam::000000000000:instance-profile/legacy-profile",
restarted.iamInstanceProfileArn(versioned),
versioned.getIamInstanceProfile().getArn(),
"IAM instance profile on a legacy versions-map entry must survive restart");
assertEquals(List.of("legacy-versioned"),
versioned.getInstanceTags().stream().map(Tag::getValue).toList(),
@@ -353,7 +353,7 @@ class Ec2ServicePersistenceTest {
.getFirst()
.getData();
assertEquals("arn:aws:iam::000000000000:instance-profile/legacy-profile",
restarted.iamInstanceProfileArn(noVersions),
noVersions.getIamInstanceProfile().getArn(),
"IAM instance profile on a legacy template with no versions map must survive restart");
assertEquals(List.of("legacy-no-versions"),
noVersions.getInstanceTags().stream().map(Tag::getValue).toList(),
@@ -126,6 +126,10 @@ class Ec2VolumeThroughputAndIamProfileIntegrationTest {
@Test
@Order(20)
void instanceWithIamProfileExposesItInDescribeAndAssociations() {
String profileId = given().header("Authorization", AUTH_HEADER.replace("/ec2/", "/iam/"))
.formParam("Action", "CreateInstanceProfile").formParam("InstanceProfileName", "my-profile")
.post("/").then().statusCode(200)
.extract().path("CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.InstanceProfileId");
String instanceId = given()
.header("Authorization", AUTH_HEADER)
.formParam("Action", "RunInstances")
@@ -153,7 +157,7 @@ class Ec2VolumeThroughputAndIamProfileIntegrationTest {
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.iamInstanceProfile.arn",
equalTo("arn:aws:iam::000000000000:instance-profile/my-profile"))
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.iamInstanceProfile.id",
startsWith("AIPA"));
equalTo(profileId));
// DescribeIamInstanceProfileAssociations must resolve the association.
given()
@@ -1469,6 +1469,7 @@ class EksClusterManagerTest {
assertEquals("172.17.0.2", instance.getPrivateIpAddress());
assertEquals("i-0e413a1bfb5c3cd79.us-west-2.compute.internal", instance.getPrivateDnsName());
assertEquals("arn:aws:iam::123456789012:instance-profile/prod-cluster-node-profile", instance.getIamInstanceProfileArn());
assertEquals("AIPA0E413A1BFB5C3CD79", instance.getIamInstanceProfileId());
assertNotEquals(cluster.getRoleArn(), instance.getIamInstanceProfileArn());
assertEquals("running", instance.getState().getName());
}
@@ -1594,7 +1595,7 @@ class EksClusterManagerTest {
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
verify(metadataServer).reconcileContainerAddresses(any(), any());
verify(metadataServer).reconcileClusterNodeAddresses(any(), any());
// imds=true, imdsPodNetwork=false (default): 2 commands (install probe, start proxy)
assertEquals(2, capturedCmds.size());
// First command: install probe
@@ -1615,7 +1616,7 @@ class EksClusterManagerTest {
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
verify(metadataServer).reconcileContainerAddresses(any(), any());
verify(metadataServer).reconcileClusterNodeAddresses(any(), any());
assertEquals(3, capturedCmds.size());
// First command: install probe
assertTrue(capturedCmds.get(0)[2].contains("command -v socat"));