mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
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:
1 parent
fa2a49e771
commit
0be4581d4e
19 files changed
+840
-68
No files matched your search
+10
-5
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
@@ -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 |
|
||||
|
||||
+3
-1
@@ -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());
|
||||
|
||||
+36
-2
@@ -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<LaunchConfiguration> describeLaunchConfigurations(String region, List<String> 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(
|
||||
|
||||
@@ -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<IamRole> role(Instance instance) {
|
||||
return attachedProfile(instance).map(AttachedProfile::role);
|
||||
}
|
||||
|
||||
synchronized Optional<InstanceProfile> 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> 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<InstanceProfile> 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<SessionCredential> 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) {}
|
||||
}
|
||||
@@ -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<String, SessionToken> tokens = new ConcurrentHashMap<>();
|
||||
/** IMDSv1 fallback: container bridge IP → Instance */
|
||||
private final Map<String, Instance> containerIpToInstance = new ConcurrentHashMap<>();
|
||||
/** Cluster nodes whose instance-profile identity their registrar synthesizes rather than IAM holding it. */
|
||||
private final Set<Instance> 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<String> 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<InstanceProfile> 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) {
|
||||
|
||||
@@ -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<Tag> instanceTags = parseTagsForResource(p, "instance");
|
||||
List<Tag> 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<String, String> 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) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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; }
|
||||
|
||||
|
||||
@@ -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());
|
||||
|
||||
+179
@@ -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));
|
||||
}
|
||||
|
||||
}
|
||||
+2
@@ -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()))
|
||||
|
||||
+271
@@ -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) {}
|
||||
}
|
||||
+165
@@ -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")
|
||||
|
||||
+2
-2
@@ -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(),
|
||||
|
||||
+5
-1
@@ -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"));
|
||||
|
||||
Reference in new issue
Block a user