mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 23:59:27 -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
+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());
|
||||
|
||||
Reference in new issue
Block a user