diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2InstanceProfilePathTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2InstanceProfilePathTest.java index 35ec256966..2faa9ec5f4 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2InstanceProfilePathTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2InstanceProfilePathTest.java @@ -5,10 +5,12 @@ 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.IamInstanceProfile; 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 software.amazon.awssdk.services.iam.model.InstanceProfile; import java.util.UUID; import java.util.stream.Stream; @@ -23,12 +25,13 @@ class Ec2InstanceProfilePathTest { @ParameterizedTest @MethodSource("launches") - @DisplayName("EC2 launches resolve profile names to the full IAM ARN, including its path") + @DisplayName("EC2 launches resolve profile names to the full IAM ARN and IAM's profile id") 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(); + InstanceProfile created = iam.createInstanceProfile(r -> r.instanceProfileName(name).path(path)) + .instanceProfile(); + String profileArn = created.arn(); String instanceId = null; String templateId = null; try { @@ -60,8 +63,10 @@ class Ec2InstanceProfilePathTest { 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); + IamInstanceProfile attached = ec2.describeInstances(r -> r.instanceIds(selectedInstance)) + .reservations().get(0).instances().get(0).iamInstanceProfile(); + assertThat(attached.arn()).isEqualTo(profileArn); + assertThat(attached.id()).isEqualTo(created.instanceProfileId()); } finally { if (instanceId != null) { String cleanupId = instanceId; diff --git a/docs/services/autoscaling.md b/docs/services/autoscaling.md index 1711ecd916..c84aa07082 100644 --- a/docs/services/autoscaling.md +++ b/docs/services/autoscaling.md @@ -296,3 +296,5 @@ aws autoscaling set-desired-capacity \ --auto-scaling-group-name my-asg \ --desired-capacity 3 ``` + +Launch configurations accept an IAM instance profile name or ARN. Unknown and foreign profiles fail creation with `ValidationError`. At launch, the reconciler resolves a stored name to its ARN in the owning account. `CreateAutoScalingGroup` and `UpdateAutoScalingGroup` refuse, with `ValidationError`, a launch template that names both an instance profile name and an ARN, directly or through the mixed instances policy. diff --git a/docs/services/ec2.md b/docs/services/ec2.md index f7e9046c1b..79ff2500bc 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -118,6 +118,11 @@ CloudFormation `AWS::EC2::VPCEndpoint` resolves `IpAddressType` on create and up Floci runs an IMDS-compatible HTTP server on port `9169` of the host. Each launched container receives the environment variable `AWS_EC2_METADATA_SERVICE_ENDPOINT` pointing to this server. +`iam/info` returns the ARN and ID that IAM holds for the attached profile, and 404 when that +profile is missing, has no role or does not match the attached ARN. An EKS cluster node, whose +profile Floci synthesizes, reports the synthesized ARN and a stable ID instead while IAM holds no +such profile. + Both IMDSv1 (no token) and IMDSv2 (token-based) flows are supported: ```bash @@ -755,6 +760,20 @@ prefix lists, `EnaSrdSpecification`, `PrimaryIpv6` and `EnaQueueCount` are likew | ReplaceIamInstanceProfileAssociation | Swaps the profile behind an existing association id; an unknown id answers `InvalidAssociationID.NotFound`. | | DisassociateIamInstanceProfile | Detaches the profile behind an association id. | +Launches and association changes resolve both names and ARNs against IAM in the +caller's account. Unknown profiles and foreign-account ARNs fail with +`InvalidParameterValue` before allocation or association changes. A RunInstances launch +that names both a profile name and an ARN, directly or through its launch template, and a +CreateFleet launch through such a template, fail with `InvalidParameterCombination`; +association replacement uses the ARN when both are provided. Launch templates reject +malformed profile ARNs at creation with `InvalidIamInstanceProfileArn.Malformed` but, as +on AWS, store a name and ARN pair as given; the pair fails when something uses the +template, and Auto Scaling refuses a group over it. +EC2 stores and returns IAM's profile ID, including for launch-template, EC2 Fleet and +Auto Scaling instances. Persisted instances from older versions omit the unknown ID until the +profile is reassociated; looking up the ARN could misidentify a deleted and recreated +profile. + ### Network Interfaces | Action | Description | diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java index c5323150fe..d37e43d568 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java @@ -550,7 +550,9 @@ public class AutoScalingReconciler { asg.getRegion(), launchSource.imageId(), launchSource.instanceType(), 1, 1, launchSource.keyName(), launchSource.securityGroupIds(), placement.subnetId(), clientToken, propagatedInstanceTags(asg, launchSource), launchSource.userData(), - launchSource.iamInstanceProfile(), launchSource.associatePublicIpAddress(), null, 0, null, null, null, + launchSource.launchConfigurationName() == null ? launchSource.iamInstanceProfile() + : asgService.resolveLaunchConfigurationProfile(launchSource.iamInstanceProfile()), + launchSource.associatePublicIpAddress(), null, 0, null, null, null, launchSource.encodedUserData() != null ? launchSource.encodedUserData() : encodeLegacyUserData(launchSource.userData()), false, null, null, launchSource.blockDeviceMappings()); diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java index 72d8c8cccb..2b93e77272 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java @@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ec2.Ec2UserDataDecoder; import io.github.hectorvent.floci.services.ec2.model.Instance; import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate; +import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -30,8 +31,9 @@ import java.util.stream.Collectors; @ApplicationScoped public class AutoScalingService { + private static final String FULLY_FORMED_LAUNCH_TEMPLATE = "You must use a valid fully-formed launch template. "; static final String MISSING_LAUNCH_TEMPLATE_IMAGE_ID_MESSAGE = - "You must use a valid fully-formed launch template. The request must contain the parameter ImageId"; + FULLY_FORMED_LAUNCH_TEMPLATE + "The request must contain the parameter ImageId"; static final String INVALID_LAUNCH_TEMPLATE_MESSAGE = "The specified launch template does not exist."; static final String INVALID_LAUNCH_CONFIGURATION_PARAMETERS_MESSAGE = @@ -213,6 +215,7 @@ public class AutoScalingService { } } Ec2UserDataDecoder.decode(userData); + resolveLaunchConfigurationProfile(iamInstanceProfile); LaunchConfiguration lc = new LaunchConfiguration(); lc.setLaunchConfigurationName(name); lc.setLaunchConfigurationArn( @@ -236,6 +239,26 @@ public class AutoScalingService { return lc; } + String resolveLaunchConfigurationProfile(String profile) { + if (isBlank(profile)) { + return null; + } + boolean arn = AwsArnUtils.isArn(profile); + String name = arn ? profile.substring(profile.lastIndexOf('/') + 1) : profile; + try { + String resolved = ec2Service.resolveIamInstanceProfileName(name); + if (arn && !profile.equals(resolved)) { + throw new AwsException("ValidationError", "Invalid IamInstanceProfile: " + profile, 400); + } + return resolved; + } catch (AwsException error) { + if (!"InvalidParameterValue".equals(error.getErrorCode())) { + throw error; + } + throw new AwsException("ValidationError", "Invalid IamInstanceProfile: " + profile, 400); + } + } + public List describeLaunchConfigurations(String region, List names) { if (names != null && !names.isEmpty()) { return names.stream() @@ -1617,9 +1640,20 @@ public class AutoScalingService { if (launchTemplateVersions.isEmpty()) { throw invalidLaunchTemplate(); } - if (isBlank(launchTemplateVersions.getFirst().getData().getImageId())) { + LaunchTemplateData data = launchTemplateVersions.getFirst().getData(); + if (isBlank(data.getImageId())) { throw missingLaunchTemplateImageId(); } + // EC2 stores a template naming both profile selectors; the group's launch would fail, so + // the group is refused up front, as AWS does. + if (data.getIamInstanceProfile() != null) { + try { + Ec2Service.validateLaunchProfileSelectors(data.getIamInstanceProfile().getName(), + data.getIamInstanceProfile().getArn()); + } catch (AwsException invalid) { + throw new AwsException("ValidationError", FULLY_FORMED_LAUNCH_TEMPLATE + invalid.getMessage(), 400); + } + } } private static MixedInstancesPolicy.LaunchTemplateSpecification mixedInstancesLaunchTemplateSpecification( diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.java index 7dada48c44..96e71cde4f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceCredentials.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.services.ec2.model.Instance; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.iam.model.IamRole; +import io.github.hectorvent.floci.services.iam.model.InstanceProfile; import io.github.hectorvent.floci.services.iam.model.SessionCredential; import java.security.SecureRandom; @@ -88,8 +89,36 @@ final class Ec2InstanceCredentials { } synchronized Optional role(Instance instance) { + return attachedProfile(instance).map(AttachedProfile::role); + } + + synchronized Optional profile(Instance instance) { + return attachedProfile(instance).map(AttachedProfile::profile); + } + + /** Whether IAM holds a profile at the instance's attached ARN, whether or not it carries a role. */ + synchronized boolean holdsProfile(Instance instance) { + return heldProfile(instance.getIamInstanceProfileArn()).isPresent(); + } + + private Optional attachedProfile(Instance instance) { String arn = instance.getIamInstanceProfileArn(); - if (!sessions.containsKey(instance) || arn == null) { + if (!sessions.containsKey(instance)) { + return Optional.empty(); + } + return heldProfile(arn) + .filter(profile -> profile.getRoleNames() != null && profile.getRoleNames().size() == 1) + .flatMap(profile -> { + String[] parts = arn.split(":", 6); + return iam.findRole(parts[4], profile.getRoleNames().getFirst()) + .filter(role -> role.getArn() != null && role.getArn().startsWith( + "arn:" + parts[1] + ":iam::" + parts[4] + ":role/")) + .map(role -> new AttachedProfile(profile, role)); + }); + } + + private Optional heldProfile(String arn) { + if (arn == null) { return Optional.empty(); } String[] parts = arn.split(":", 6); @@ -99,12 +128,7 @@ final class Ec2InstanceCredentials { return Optional.empty(); } String name = arn.substring(arn.lastIndexOf('/') + 1); - return iam.findInstanceProfile(parts[4], name) - .filter(profile -> arn.equals(profile.getArn())) - .filter(profile -> profile.getRoleNames() != null && profile.getRoleNames().size() == 1) - .flatMap(profile -> iam.findRole(parts[4], profile.getRoleNames().getFirst())) - .filter(role -> role.getArn() != null && role.getArn().startsWith( - "arn:" + parts[1] + ":iam::" + parts[4] + ":role/")); + return iam.findInstanceProfile(parts[4], name).filter(profile -> arn.equals(profile.getArn())); } synchronized Optional get(Instance instance, String roleName, Instant now) { @@ -165,4 +189,6 @@ final class Ec2InstanceCredentials { } private record Issued(SessionCredential session, String roleId, String profileArn) {} + + private record AttachedProfile(InstanceProfile profile, IamRole role) {} } diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java index 600a1e42f9..72271ac8c9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.ec2.model.Instance; import io.github.hectorvent.floci.services.ec2.model.Tag; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.iam.model.IamRole; +import io.github.hectorvent.floci.services.iam.model.InstanceProfile; import io.github.hectorvent.floci.services.iam.model.SessionCredential; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; @@ -61,6 +62,8 @@ public class Ec2MetadataServer { private final Map tokens = new ConcurrentHashMap<>(); /** IMDSv1 fallback: container bridge IP → Instance */ private final Map containerIpToInstance = new ConcurrentHashMap<>(); + /** Cluster nodes whose instance-profile identity their registrar synthesizes rather than IAM holding it. */ + private final Set synthesizedProfiles = ConcurrentHashMap.newKeySet(); private volatile HttpServer httpServer; @@ -101,8 +104,19 @@ public class Ec2MetadataServer { entry.getValue() == instance && !addresses.contains(entry.getKey())); } + /** + * Registers a cluster node that another service synthesizes instead of EC2 launching it. Its + * instance-profile ARN and ID are the registrar's own, so {@code iam/info} reports them while IAM + * holds no such profile. + */ + public void reconcileClusterNodeAddresses(Set addresses, Instance instance) { + synthesizedProfiles.add(instance); + reconcileContainerAddresses(addresses, instance); + } + public void unregisterInstance(Instance instance) { if (instance != null) { + synthesizedProfiles.remove(instance); credentials.unregister(instance); tokens.values().removeIf(token -> token.instance() == instance); containerIpToInstance.entrySet().removeIf(entry -> entry.getValue() == instance); @@ -179,6 +193,7 @@ public class Ec2MetadataServer { credentials.clear(); tokens.clear(); containerIpToInstance.clear(); + synthesizedProfiles.clear(); if (httpServer != null) { httpServer.close(); httpServer = null; @@ -290,18 +305,25 @@ public class Ec2MetadataServer { if (inst == null) { return; } - String profileArn = inst.getIamInstanceProfileArn(); - if (profileArn == null) { + Optional resolved = credentials.profile(inst); + String profileArn; + String profileId; + if (resolved.isPresent()) { + profileArn = resolved.get().getArn(); + profileId = resolved.get().getInstanceProfileId(); + } else if (synthesizedProfiles.contains(inst) && inst.getIamInstanceProfileArn() != null + && !credentials.holdsProfile(inst)) { + profileArn = inst.getIamInstanceProfileArn(); + profileId = inst.getIamInstanceProfileId(); + } else { ctx.response().setStatusCode(404).end("{}"); return; } - String profileId = "AIPA" + inst.getInstanceId().toUpperCase().substring(2, 16); - String body = "{\"Code\":\"Success\",\"LastUpdated\":\"" + now() + "\"," - + "\"InstanceProfileArn\":\"" + profileArn + "\"," - + "\"InstanceProfileId\":\"" + profileId + "\"}"; ctx.response().setStatusCode(200) .putHeader("content-type", "application/json") - .end(body); + .end(new JsonObject().put("Code", "Success").put("LastUpdated", now()) + .put("InstanceProfileArn", profileArn) + .put("InstanceProfileId", profileId).encode()); } private void handleCredentialsList(RoutingContext ctx) { 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 8c5d2666b6..81c19c9a72 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 @@ -783,13 +783,14 @@ public class Ec2QueryHandler { userData = Ec2UserDataDecoder.decode(userDataEncoded); } - String iamInstanceProfileArn = resolveIamInstanceProfileArn(p); - // Parse TagSpecifications. AWS applies each specification to exactly the resource // type it names, so the interfaces RunInstances creates are tagged only by a // ResourceType=network-interface specification - never by the instance's own tags. List instanceTags = parseTagsForResource(p, "instance"); List networkInterfaceTags = parseTagsForResource(p, "network-interface"); + // Resolved after tag parsing so reserved tags are refused before any service call. + String iamInstanceProfileArn = service.resolveLaunchIamInstanceProfileArn( + p.getFirst("IamInstanceProfile.Name"), p.getFirst("IamInstanceProfile.Arn")); // Absent fields stay null so the launch default, or the launch template's value, applies. LaunchTemplateData.MetadataOptions metadataOptions = parseMetadataOptions(p, "MetadataOptions."); @@ -1210,7 +1211,7 @@ public class Ec2QueryHandler { .elem("instanceId", inst.getInstanceId()) .start("iamInstanceProfile") .elem("arn", inst.getIamInstanceProfileArn()) - .elem("id", Ec2Service.iamInstanceProfileId(inst.getInstanceId())) + .elem("id", inst.getIamInstanceProfileId()) .end("iamInstanceProfile") .elem("state", "associated"); if (inst.getIamInstanceProfileAssociationTime() != null) { @@ -4922,7 +4923,7 @@ public class Ec2QueryHandler { if (inst.getIamInstanceProfileArn() != null) { xml.start("iamInstanceProfile") .elem("arn", inst.getIamInstanceProfileArn()) - .elem("id", Ec2Service.iamInstanceProfileId(inst.getInstanceId())) + .elem("id", inst.getIamInstanceProfileId()) .end("iamInstanceProfile"); } xml.raw(tagSetXml(inst.getTags())); @@ -4934,15 +4935,7 @@ public class Ec2QueryHandler { } private String resolveIamInstanceProfileArn(MultivaluedMap p, String prefix) { - String arn = p.getFirst(prefix + ".Arn"); - if (arn != null && !arn.isBlank()) { - return arn; - } - String name = p.getFirst(prefix + ".Name"); - if (name == null || name.isBlank()) { - return null; - } - return service.resolveIamInstanceProfileName(name); + return service.resolveIamInstanceProfileArn(p.getFirst(prefix + ".Name"), p.getFirst(prefix + ".Arn")); } 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 6c0539df73..07a68ca90e 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 @@ -3362,6 +3362,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab requireNotDeregistered(region, imageId); validateMetadataOptions(metadataOptions); validateCreditSpecification(creditSpecificationCpuCredits); + InstanceProfile launchProfile = resolveIamInstanceProfile(null, iamInstanceProfileArn); LaunchTemplateData.MetadataOptions launchMetadataOptions = LaunchTemplateData.MetadataOptions.merge( LaunchTemplateData.MetadataOptions.launchDefaults(), metadataOptions); ensureDefaultResources(region); @@ -3520,7 +3521,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab inst.setUserData(userData); inst.setEncodedUserData(encodedUserData); inst.setIamInstanceProfileArn(iamInstanceProfileArn); - if (iamInstanceProfileArn != null) { + if (launchProfile != null) { + inst.setIamInstanceProfileId(launchProfile.getInstanceProfileId()); inst.setIamInstanceProfileAssociationTime(inst.getLaunchTime()); } inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(launchMetadataOptions, null)); @@ -4402,13 +4404,6 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab instances.put(key(region, instanceId), inst); } - /** - * Deterministic instance-profile id derived from the instance id so repeated describes are stable. - */ - public static String iamInstanceProfileId(String instanceId) { - return "AIPA" + stableSuffix(instanceId, 17).toUpperCase(); - } - /** * Deterministic association id derived from the instance id so repeated describes are stable. */ @@ -4442,7 +4437,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab throw new AwsException("IncorrectState", "There is an existing association for instance " + instanceId, 400); } + InstanceProfile profile = resolveIamInstanceProfile(null, profileArn); inst.setIamInstanceProfileArn(profileArn); + inst.setIamInstanceProfileId(profile.getInstanceProfileId()); inst.setIamInstanceProfileAssociationTime(Instant.now()); instances.put(key(region, instanceId), inst); return association(inst, profileArn, "associating"); @@ -4453,7 +4450,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab String profileArn) { ensureDefaultResources(region); Instance inst = getRequiredAssociatedInstance(region, associationId); + InstanceProfile profile = resolveIamInstanceProfile(null, profileArn); inst.setIamInstanceProfileArn(profileArn); + inst.setIamInstanceProfileId(profile.getInstanceProfileId()); inst.setIamInstanceProfileAssociationTime(Instant.now()); instances.put(key(region, inst.getInstanceId()), inst); return association(inst, profileArn, "associating"); @@ -4464,12 +4463,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab ensureDefaultResources(region); Instance inst = getRequiredAssociatedInstance(region, associationId); String detached = inst.getIamInstanceProfileArn(); + String detachedId = inst.getIamInstanceProfileId(); Instant associatedAt = inst.getIamInstanceProfileAssociationTime(); inst.setIamInstanceProfileArn(null); + inst.setIamInstanceProfileId(null); inst.setIamInstanceProfileAssociationTime(null); instances.put(key(region, inst.getInstanceId()), inst); return new IamInstanceProfileAssociation(associationId, inst.getInstanceId(), detached, - iamInstanceProfileId(inst.getInstanceId()), "disassociating", associatedAt); + detachedId, "disassociating", associatedAt); } private Instance getRequiredAssociatedInstance(String region, String associationId) { @@ -4483,9 +4484,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab "An invalid association-id of '" + associationId + "' was given", 400); } - private static IamInstanceProfileAssociation association(Instance inst, String profileArn, String state) { + private IamInstanceProfileAssociation association(Instance inst, String profileArn, String state) { return new IamInstanceProfileAssociation(iamInstanceProfileAssociationId(inst.getInstanceId()), - inst.getInstanceId(), profileArn, iamInstanceProfileId(inst.getInstanceId()), state, + inst.getInstanceId(), profileArn, inst.getIamInstanceProfileId(), state, inst.getIamInstanceProfileAssociationTime()); } @@ -4641,6 +4642,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab copy.setEbsOptimized(source.isEbsOptimized()); copy.setEnaSupport(source.isEnaSupport()); copy.setIamInstanceProfileArn(source.getIamInstanceProfileArn()); + copy.setIamInstanceProfileId(source.getIamInstanceProfileId()); copy.setIamInstanceProfileAssociationTime(source.getIamInstanceProfileAssociationTime()); copy.setStateReasonCode(source.getStateReasonCode()); copy.setStateReasonMessage(source.getStateReasonMessage()); @@ -7471,7 +7473,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab if (name == null || name.isBlank()) { throw new AwsException("MissingParameter", "The request must contain the parameter LaunchTemplateName", 400); } - validateLaunchTemplateData(data); + validateLaunchTemplateData(region, data); boolean exists = launchTemplates.scan(k -> true).stream() .anyMatch(lt -> lt.getRegion().equals(region) && name.equals(lt.getLaunchTemplateName())); if (exists) { @@ -7511,10 +7513,23 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab * ExcludedInstanceTypes", and "Only one of SpotMaxPricePercentageOverLowestPrice or * MaxSpotPriceAsPercentageOfOptimalOnDemandPrice can be specified". */ - private static void validateLaunchTemplateData(LaunchTemplateData data) { + private static void validateLaunchTemplateData(String region, LaunchTemplateData data) { if (data == null) { return; } + // A malformed profile ARN fails here, but a template naming both selectors is stored as + // given: AWS does not fully validate template parameters, so the pair fails at launch. + LaunchTemplateData.IamInstanceProfile profile = data.getIamInstanceProfile(); + if (profile != null && isSet(profile.getArn())) { + AwsArnUtils.Arn arn = AwsArnUtils.isArn(profile.getArn()) ? AwsArnUtils.parse(profile.getArn()) : null; + if (arn == null || !AwsRegions.partitionFor(region).equals(arn.partition()) + || !"iam".equals(arn.service()) || !arn.region().isEmpty() + || !arn.accountId().matches("\\d{12}") + || !arn.resource().startsWith("instance-profile/") || arn.resource().endsWith("/")) { + throw new AwsException("InvalidIamInstanceProfileArn.Malformed", + "Invalid IAM instance profile ARN: " + profile.getArn(), 400); + } + } requireInstanceTypeOrInstanceRequirements(data); validateInstanceRequirements(data.getInstanceRequirements()); for (LaunchTemplateData.NetworkInterface networkInterface : data.getNetworkInterfaces()) { @@ -7608,7 +7623,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab String sourceVersion, LaunchTemplateData data, String versionDescription) { ensureDefaultResources(region); - validateLaunchTemplateData(data); + validateLaunchTemplateData(region, data); LaunchTemplate launchTemplate = findLaunchTemplate(region, id, name); ensureLaunchTemplateVersions(launchTemplate); int latestVersion = parseLaunchTemplateVersion(launchTemplate.getLatestVersionNumber()) + 1; @@ -7620,7 +7635,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab resolveLaunchTemplateVersion(launchTemplate, sourceVersion, launchTemplate.getLatestVersionNumber())); } LaunchTemplateData merged = source.mergedWith(data != null ? data : new LaunchTemplateData()); - validateLaunchTemplateData(merged); + validateLaunchTemplateData(region, merged); launchTemplate.setLatestVersionNumber(String.valueOf(latestVersion)); launchTemplate.getVersions().put(String.valueOf(latestVersion), merged); launchTemplate.setData(new LaunchTemplateData(merged)); @@ -7728,23 +7743,47 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return null; } LaunchTemplateData.IamInstanceProfile profile = data.getIamInstanceProfile(); - if (profile.getArn() != null && !profile.getArn().isBlank()) { - return profile.getArn(); - } - if (profile.getName() == null || profile.getName().isBlank()) { - return null; - } - return resolveIamInstanceProfileName(profile.getName()); + return resolveLaunchIamInstanceProfileArn(profile.getName(), profile.getArn()); } public String resolveIamInstanceProfileName(String name) { - if (iamService == null) { - throw new IllegalStateException("IAM service is required to resolve instance profile names"); + return resolveIamInstanceProfileArn(name, null); + } + + public String resolveLaunchIamInstanceProfileArn(String name, String arn) { + validateLaunchProfileSelectors(name, arn); + return resolveIamInstanceProfileArn(name, arn); + } + + public static void validateLaunchProfileSelectors(String name, String arn) { + if (isSet(name) && isSet(arn)) { + throw new AwsException("InvalidParameterCombination", + "The parameter iamInstanceProfile.name may not be used with iamInstanceProfile.arn.", 400); } - return iamService.findInstanceProfile(callerAccountId(), name) - .map(InstanceProfile::getArn) + } + + public String resolveIamInstanceProfileArn(String name, String arn) { + InstanceProfile profile = resolveIamInstanceProfile(name, arn); + return profile == null ? null : profile.getArn(); + } + + private InstanceProfile resolveIamInstanceProfile(String name, String arn) { + boolean hasName = name != null && !name.isBlank(); + boolean hasArn = arn != null && !arn.isBlank(); + if (!hasName && !hasArn) { + return null; + } + if (iamService == null) { + throw new IllegalStateException("IAM service is required to resolve instance profiles"); + } + String lookupName = name; + if (hasArn) { + lookupName = arn.substring(arn.lastIndexOf('/') + 1); + } + return iamService.findInstanceProfile(callerAccountId(), lookupName) + .filter(profile -> !hasArn || arn.equals(profile.getArn())) .orElseThrow(() -> new AwsException("InvalidParameterValue", - "Invalid IAM Instance Profile name: " + name, 400)); + "Invalid IAM Instance Profile: " + (hasArn ? arn : name), 400)); } public LaunchTemplateData resolveLaunchTemplateData(String region, String id, String name, String version) { diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java index 61d9b26985..59f4d129ea 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java @@ -45,6 +45,7 @@ public class Instance { private boolean ebsOptimized = false; private boolean enaSupport = true; private String iamInstanceProfileArn; + private String iamInstanceProfileId; private Instant iamInstanceProfileAssociationTime; private String stateReasonCode; private String stateReasonMessage; @@ -184,6 +185,8 @@ public class Instance { public String getIamInstanceProfileArn() { return iamInstanceProfileArn; } public void setIamInstanceProfileArn(String iamInstanceProfileArn) { this.iamInstanceProfileArn = iamInstanceProfileArn; } + public String getIamInstanceProfileId() { return iamInstanceProfileId; } + public void setIamInstanceProfileId(String iamInstanceProfileId) { this.iamInstanceProfileId = iamInstanceProfileId; } public Instant getIamInstanceProfileAssociationTime() { return iamInstanceProfileAssociationTime; } public void setIamInstanceProfileAssociationTime(Instant iamInstanceProfileAssociationTime) { this.iamInstanceProfileAssociationTime = iamInstanceProfileAssociationTime; } diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java index 00a34801f3..4b25652e0d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java @@ -2306,7 +2306,7 @@ public class EksClusterManager } if (metadataServer != null) { - metadataServer.reconcileContainerAddresses(containerIps.allIps(), nodeInstance); + metadataServer.reconcileClusterNodeAddresses(containerIps.allIps(), nodeInstance); } ContainerExec.Result install = execInContainerForResult(containerId, @@ -2832,6 +2832,8 @@ public class EksClusterManager // node instance profile identity so /latest/meta-data/iam/info returns a valid profile ARN. String nodeProfileName = safeClusterName + "-node-profile"; inst.setIamInstanceProfileArn(regionResolver.buildGlobalArn("iam", safeAccountId, "instance-profile/" + nodeProfileName)); + // IAM holds no such profile, so the node carries its own stable id, shaped like IAM's. + inst.setIamInstanceProfileId("AIPA" + instanceId.substring(2).toUpperCase(Locale.ROOT)); if (cluster.getResourcesVpcConfig() != null) { inst.setVpcId(cluster.getResourcesVpcConfig().getVpcId()); diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingLaunchConfigurationIdentityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingLaunchConfigurationIdentityIntegrationTest.java new file mode 100644 index 0000000000..99d47e8260 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingLaunchConfigurationIdentityIntegrationTest.java @@ -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)); + } + +} diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java index 32626b90cb..54fe56bc0d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java @@ -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())) diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceProfileIdentityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceProfileIdentityIntegrationTest.java new file mode 100644 index 0000000000..305624da8e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2InstanceProfileIdentityIntegrationTest.java @@ -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 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 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) {} +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataProfileIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataProfileIntegrationTest.java new file mode 100644 index 0000000000..d1776514d9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataProfileIntegrationTest.java @@ -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 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 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 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 token = fixture.putToken("60"); + assertEquals(200, token.statusCode()); + return token.body(); + } + + private static HttpResponse 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); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2Phase2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2Phase2IntegrationTest.java index 0adff9cb14..9dc666b41a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2Phase2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2Phase2IntegrationTest.java @@ -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") diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java index 3a1944bd49..9e950e4ffd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServicePersistenceTest.java @@ -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(), diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeThroughputAndIamProfileIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeThroughputAndIamProfileIntegrationTest.java index d9f6c06cb9..c0ac2c6309 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeThroughputAndIamProfileIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VolumeThroughputAndIamProfileIntegrationTest.java @@ -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() diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java index 561e2af9be..cb6e3e796f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java @@ -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"));