Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(autoscaling): honor launch configuration metadata options (#5964)

Jackson Pricee75b15809fa0
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AutoScalingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AutoScalingTest.java
index cf0a91701f..07eff221d6 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AutoScalingTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AutoScalingTest.java
@@ -19,6 +19,9 @@ import software.amazon.awssdk.services.autoscaling.model.DisableMetricsCollectio
import software.amazon.awssdk.services.autoscaling.model.EnableMetricsCollectionRequest;
import software.amazon.awssdk.services.autoscaling.model.EnabledMetric;
import software.amazon.awssdk.services.autoscaling.model.InstanceMaintenancePolicy;
+import software.amazon.awssdk.services.autoscaling.model.InstanceMetadataEndpointState;
+import software.amazon.awssdk.services.autoscaling.model.InstanceMetadataHttpTokensState;
+import software.amazon.awssdk.services.autoscaling.model.InstanceMetadataOptions;
import software.amazon.awssdk.services.autoscaling.model.LaunchTemplate;
import software.amazon.awssdk.services.autoscaling.model.LaunchTemplateOverrides;
import software.amazon.awssdk.services.autoscaling.model.LaunchTemplateSpecification;
@@ -141,6 +144,52 @@ class AutoScalingTest {
});
}
+ @Test
+ @DisplayName("Launch configuration metadata options round-trip through the SDK")
+ void launchConfigurationMetadataOptionsRoundTripThroughTheSdk() {
+ String partial = TestFixtures.uniqueName("sdk-lc-metadata");
+ String omitted = TestFixtures.uniqueName("sdk-lc-no-metadata");
+ autoScaling.createLaunchConfiguration(CreateLaunchConfigurationRequest.builder()
+ .launchConfigurationName(partial)
+ .imageId("ami-12345678")
+ .instanceType("t3.micro")
+ .metadataOptions(InstanceMetadataOptions.builder()
+ .httpTokens(InstanceMetadataHttpTokensState.REQUIRED)
+ .build())
+ .build());
+ try {
+ autoScaling.createLaunchConfiguration(CreateLaunchConfigurationRequest.builder()
+ .launchConfigurationName(omitted)
+ .imageId("ami-12345678")
+ .instanceType("t3.micro")
+ .build());
+ try {
+ InstanceMetadataOptions described = autoScaling.describeLaunchConfigurations(r -> r
+ .launchConfigurationNames(partial))
+ .launchConfigurations().get(0).metadataOptions();
+ assertThat(described.httpTokens()).isEqualTo(InstanceMetadataHttpTokensState.REQUIRED);
+ assertThat(described.httpEndpoint()).isEqualTo(InstanceMetadataEndpointState.ENABLED);
+ assertThat(described.httpPutResponseHopLimit()).isEqualTo(1);
+ assertThat(autoScaling.describeLaunchConfigurations(r -> r.launchConfigurationNames(omitted))
+ .launchConfigurations().get(0).metadataOptions()).isNull();
+ } finally {
+ autoScaling.deleteLaunchConfiguration(r -> r.launchConfigurationName(omitted));
+ }
+ } finally {
+ autoScaling.deleteLaunchConfiguration(r -> r.launchConfigurationName(partial));
+ }
+ assertThatThrownBy(() -> autoScaling.createLaunchConfiguration(CreateLaunchConfigurationRequest.builder()
+ .launchConfigurationName(TestFixtures.uniqueName("sdk-lc-bad-metadata"))
+ .imageId("ami-12345678")
+ .instanceType("t3.micro")
+ .metadataOptions(InstanceMetadataOptions.builder().httpPutResponseHopLimit(65).build())
+ .build()))
+ .isInstanceOfSatisfying(AutoScalingException.class, error -> {
+ assertThat(error.statusCode()).isEqualTo(400);
+ assertThat(error.awsErrorDetails().errorCode()).isEqualTo("ValidationError");
+ });
+ }
+
@Test
@DisplayName("UpdateAutoScalingGroup rejects desired configuration changes during active instance refresh")
void activeInstanceRefreshDesiredConfigurationConflictMapsToSdkAutoScalingException() {
diff --git a/docs/services/autoscaling.md b/docs/services/autoscaling.md
index f0a576edff..90fd25f456 100644
--- a/docs/services/autoscaling.md
+++ b/docs/services/autoscaling.md
@@ -16,7 +16,7 @@ Floci implements the EC2 Auto Scaling API — stored-state management for launch
| Operation | Notes |
|---|---|
-| `CreateLaunchConfiguration` | Stores template: `ImageId`, `InstanceType`, `KeyName`, `SecurityGroups`, `UserData`, `IamInstanceProfile`, `InstanceMonitoring`, `BlockDeviceMappings` |
+| `CreateLaunchConfiguration` | Stores template: `ImageId`, `InstanceType`, `KeyName`, `SecurityGroups`, `UserData`, `IamInstanceProfile`, `InstanceMonitoring`, `BlockDeviceMappings`, `MetadataOptions` |
| `DescribeLaunchConfigurations` | Filtered by name list; returns all if no filter |
| `DeleteLaunchConfiguration` | Removes the named launch configuration |
@@ -311,3 +311,5 @@ aws autoscaling set-desired-capacity \
```
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.
+
+Launch-configuration metadata options (`HttpTokens`, `HttpEndpoint`, and `HttpPutResponseHopLimit`) round-trip through Query and CloudFormation and reach EC2 launches. CloudFormation resolves intrinsics inside the block, so `Fn::If` and `AWS::NoValue` can select or omit the block or any of its members. When the structure is omitted it stays absent from `DescribeLaunchConfigurations`; a supplied partial structure reports defaults for unspecified fields. Launch templates, mixed-instance templates and EC2 Fleet launches likewise forward their existing metadata options.
diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java
index d2217a8d33..6a93e78089 100644
--- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandler.java
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.autoscaling.model.*;
+import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedMap;
@@ -124,7 +125,7 @@ public class AutoScalingQueryHandler {
p.getFirst("IamInstanceProfile"),
nullableBoolParam(p, "AssociatePublicIpAddress"),
nullableBoolParam(p, "InstanceMonitoring.Enabled"),
- parseLaunchConfigurationBlockDeviceMappings(p));
+ parseLaunchConfigurationBlockDeviceMappings(p), parseMetadataOptions(p));
String xml = new XmlBuilder()
.start("CreateLaunchConfigurationResponse", NS)
.raw(AwsQueryResponse.responseMetadata())
@@ -133,6 +134,24 @@ public class AutoScalingQueryHandler {
return ok(xml);
}
+ private static LaunchTemplateData.MetadataOptions parseMetadataOptions(MultivaluedMap<String, String> p) {
+ if (p.keySet().stream().noneMatch(name -> name.startsWith("MetadataOptions."))) {
+ return null;
+ }
+ LaunchTemplateData.MetadataOptions options = new LaunchTemplateData.MetadataOptions();
+ options.setHttpTokens(p.getFirst("MetadataOptions.HttpTokens"));
+ options.setHttpEndpoint(p.getFirst("MetadataOptions.HttpEndpoint"));
+ String hopLimit = p.getFirst("MetadataOptions.HttpPutResponseHopLimit");
+ if (hopLimit != null) {
+ try {
+ options.setHttpPutResponseHopLimit(Integer.valueOf(hopLimit));
+ } catch (NumberFormatException invalid) {
+ throw new AwsException("MalformedInput", "HttpPutResponseHopLimit must be an integer.", 400);
+ }
+ }
+ return options;
+ }
+
private Response handleDescribeLaunchConfigurations(MultivaluedMap<String, String> p, String region) {
List<LaunchConfiguration> lcs = service.describeLaunchConfigurations(
region, memberList(p, "LaunchConfigurationNames"));
@@ -164,6 +183,15 @@ public class AutoScalingQueryHandler {
.elem("Enabled", String.valueOf(
lc.getInstanceMonitoringEnabled() != null ? lc.getInstanceMonitoringEnabled() : Boolean.TRUE))
.end("InstanceMonitoring");
+ if (lc.getMetadataOptions() != null) {
+ LaunchTemplateData.MetadataOptions metadata = LaunchTemplateData.MetadataOptions.merge(
+ LaunchTemplateData.MetadataOptions.launchDefaults(), lc.getMetadataOptions());
+ xml.start("MetadataOptions")
+ .elem("HttpTokens", metadata.getHttpTokens())
+ .elem("HttpEndpoint", metadata.getHttpEndpoint())
+ .elem("HttpPutResponseHopLimit", String.valueOf(metadata.getHttpPutResponseHopLimit()))
+ .end("MetadataOptions");
+ }
writeLaunchConfigurationBlockDeviceMappings(xml, lc.getBlockDeviceMappings());
xml.end("member");
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java
index d37e43d568..60142aa16c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconciler.java
@@ -552,7 +552,7 @@ public class AutoScalingReconciler {
propagatedInstanceTags(asg, launchSource), launchSource.userData(),
launchSource.launchConfigurationName() == null ? launchSource.iamInstanceProfile()
: asgService.resolveLaunchConfigurationProfile(launchSource.iamInstanceProfile()),
- launchSource.associatePublicIpAddress(), null, 0, null, null, null,
+ launchSource.associatePublicIpAddress(), null, 0, null, launchSource.metadataOptions(), null,
launchSource.encodedUserData() != null ? launchSource.encodedUserData()
: encodeLegacyUserData(launchSource.userData()),
false, null, null, launchSource.blockDeviceMappings());
@@ -851,7 +851,7 @@ public class AutoScalingReconciler {
// subnet's MapPublicIpOnLaunch, and only null means
// "fall back to the subnet default".
lc.getAssociatePublicIpAddress(),
- null);
+ null, lc.getMetadataOptions());
}
LaunchTemplate launchTemplate = resolveLaunchTemplate(asg);
@@ -880,7 +880,7 @@ public class AutoScalingReconciler {
asg.getLaunchTemplateName(),
resolvedVersion,
null,
- version.getData().getBlockDeviceMappings());
+ version.getData().getBlockDeviceMappings(), version.getData().getMetadataOptions());
}
MixedInstancesPolicy.LaunchTemplateSpecification specification =
@@ -915,7 +915,7 @@ public class AutoScalingReconciler {
specification.getLaunchTemplateName(),
resolvedVersion,
null,
- version.getData().getBlockDeviceMappings());
+ version.getData().getBlockDeviceMappings(), version.getData().getMetadataOptions());
}
}
@@ -1027,7 +1027,8 @@ public class AutoScalingReconciler {
String launchTemplateName,
String launchTemplateVersion,
Boolean associatePublicIpAddress,
- List<LaunchTemplateData.BlockDeviceMapping> blockDeviceMappings) {}
+ List<LaunchTemplateData.BlockDeviceMapping> blockDeviceMappings,
+ LaunchTemplateData.MetadataOptions metadataOptions) {}
// Override for describeAutoScalingGroups with null region (all regions)
// The service only filters by region when non-null; null means all.
diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java
index 8532ccda02..bd274cf70d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java
@@ -173,6 +173,19 @@ public class AutoScalingService {
Boolean associatePublicIpAddress,
Boolean instanceMonitoringEnabled,
List<LaunchConfigurationBlockDeviceMapping> blockDeviceMappings) {
+ return createLaunchConfiguration(region, name, instanceId, imageId, instanceType, keyName,
+ securityGroups, userData, iamInstanceProfile, associatePublicIpAddress,
+ instanceMonitoringEnabled, blockDeviceMappings, null);
+ }
+
+ public LaunchConfiguration createLaunchConfiguration(String region, String name, String instanceId,
+ String imageId, String instanceType, String keyName,
+ List<String> securityGroups, String userData,
+ String iamInstanceProfile, Boolean associatePublicIpAddress,
+ Boolean instanceMonitoringEnabled,
+ List<LaunchConfigurationBlockDeviceMapping> blockDeviceMappings,
+ LaunchTemplateData.MetadataOptions metadataOptions) {
+ validateMetadataOptions(metadataOptions);
String key = lcKey(region, name);
if (launchConfigs.containsKey(key)) {
throw new AwsException("AlreadyExists",
@@ -230,6 +243,7 @@ public class AutoScalingService {
lc.setUserData(userData);
lc.setUserDataBase64Encoded(Boolean.TRUE);
lc.setIamInstanceProfile(iamInstanceProfile);
+ lc.setMetadataOptions(metadataOptions);
lc.setAssociatePublicIpAddress(associatePublicIpAddress);
// AWS documents InstanceMonitoring as enabled by default and always returns the
// structure from Describe, unlike AssociatePublicIpAddress whose absence is meaningful.
@@ -241,6 +255,36 @@ public class AutoScalingService {
return lc;
}
+ /**
+ * Refuses metadata options outside the Auto Scaling model, every violation in one
+ * {@code ValidationError} with AWS's texts.
+ */
+ private static void validateMetadataOptions(LaunchTemplateData.MetadataOptions options) {
+ if (options == null) {
+ return;
+ }
+ List<String> violations = new ArrayList<>();
+ requireMetadataEnum(violations, "httpTokens", options.getHttpTokens(), "optional", "required");
+ Integer hopLimit = options.getHttpPutResponseHopLimit();
+ if (hopLimit != null && (hopLimit < 1 || hopLimit > 64)) {
+ violations.add("Value '" + hopLimit + "' at 'metadataOptions.httpPutResponseHopLimit' failed to satisfy"
+ + " constraint: Member must have value "
+ + (hopLimit < 1 ? "greater than or equal to 1" : "less than or equal to 64"));
+ }
+ requireMetadataEnum(violations, "httpEndpoint", options.getHttpEndpoint(), "disabled", "enabled");
+ if (!violations.isEmpty()) {
+ throw SmithyValidationErrors.validationError(violations);
+ }
+ }
+
+ private static void requireMetadataEnum(List<String> violations, String member, String value,
+ String... allowed) {
+ if (value != null && !List.of(allowed).contains(value)) {
+ violations.add("Value '" + value + "' at 'metadataOptions." + member + "' failed to satisfy constraint:"
+ + " Member must satisfy enum value set: [" + String.join(", ", allowed) + "]");
+ }
+ }
+
String resolveLaunchConfigurationProfile(String profile) {
if (isBlank(profile)) {
return null;
diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/LaunchConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/LaunchConfiguration.java
index 63129f1fed..eeb1affb94 100644
--- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/LaunchConfiguration.java
+++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/model/LaunchConfiguration.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.autoscaling.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
@@ -22,6 +23,7 @@ public class LaunchConfiguration {
// retains their existing launch behavior; only newly created records have known encoding.
private Boolean userDataBase64Encoded;
private String iamInstanceProfile;
+ private LaunchTemplateData.MetadataOptions metadataOptions;
// Nullable on purpose: AWS treats an absent flag as "fall back to the
// subnet's MapPublicIpOnLaunch" and an explicit false as an override.
private Boolean associatePublicIpAddress;
@@ -59,6 +61,9 @@ public class LaunchConfiguration {
public Boolean getUserDataBase64Encoded() { return userDataBase64Encoded; }
public void setUserDataBase64Encoded(Boolean v) { this.userDataBase64Encoded = v; }
+ public LaunchTemplateData.MetadataOptions getMetadataOptions() { return metadataOptions; }
+ public void setMetadataOptions(LaunchTemplateData.MetadataOptions value) { this.metadataOptions = value; }
+
public String getIamInstanceProfile() { return iamInstanceProfile; }
public void setIamInstanceProfile(String v) { this.iamInstanceProfile = v; }
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisioner.java
index 9bb42316a7..6ab4161963 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisioner.java
@@ -14,6 +14,8 @@ import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration
import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnPropertyTypes.Type;
+import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -48,6 +50,11 @@ public class AutoScalingGroupCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(AutoScalingGroupCfnProvisioner.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
+ /** The launch configuration's MetadataOptions as its resource schema types them. */
+ private static final Type METADATA_OPTIONS = Type.object(Map.of(
+ "HttpTokens", Type.STRING,
+ "HttpEndpoint", Type.STRING,
+ "HttpPutResponseHopLimit", Type.INTEGER));
private final AutoScalingService autoScalingService;
@@ -202,7 +209,7 @@ public class AutoScalingGroupCfnProvisioner implements CfnResourceProvisioner {
// it stays null rather than collapsing to false.
associatePublicIp == null || associatePublicIp.isBlank()
? null
- : Boolean.parseBoolean(associatePublicIp));
+ : Boolean.parseBoolean(associatePublicIp), null, List.of(), metadataOptions(props, ctx));
deleteRenamedResource(ctx, name, n -> autoScalingService.deleteLaunchConfiguration(region, n),
"launch configuration");
}
@@ -211,6 +218,32 @@ public class AutoScalingGroupCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("Arn", lc.getLaunchConfigurationArn());
}
+ /**
+ * The block read against its schema types, as CloudFormation checks it before the handler sees
+ * it: a value of the wrong type fails template validation, and a hop limit beyond 32 bits the
+ * handler's model validation. Fn::If may select the block or AWS::NoValue, and a member set to
+ * AWS::NoValue is absent.
+ */
+ private LaunchTemplateData.MetadataOptions metadataOptions(JsonNode props, ProvisionContext ctx) {
+ if (props == null || !props.has("MetadataOptions")) {
+ return null;
+ }
+ CfnPropertyTypes.Reader types = new CfnPropertyTypes.Reader(ctx.engine());
+ JsonNode node = types.read("MetadataOptions", props.get("MetadataOptions"), METADATA_OPTIONS);
+ types.finish();
+ if (node == null) {
+ return null;
+ }
+ LaunchTemplateData.MetadataOptions options = new LaunchTemplateData.MetadataOptions();
+ options.setHttpTokens(blankToNull(node.path("HttpTokens").asText(null)));
+ options.setHttpEndpoint(blankToNull(node.path("HttpEndpoint").asText(null)));
+ JsonNode hopLimit = node.path("HttpPutResponseHopLimit");
+ if (hopLimit.isInt()) {
+ options.setHttpPutResponseHopLimit(hopLimit.intValue());
+ }
+ return options;
+ }
+
private LaunchConfiguration requireLaunchConfiguration(String region, String name) {
List<LaunchConfiguration> found = autoScalingService.describeLaunchConfigurations(region, List.of(name));
if (found.isEmpty()) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
index 6c09e94cae..fad3cdea51 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
@@ -937,6 +937,8 @@ public class Ec2QueryHandler {
throw new AwsException("MissingParameter",
"Each fleet launch must specify an InstanceType in the launch template or override.", 400);
}
+ // The template stored them unchecked; the launch would refuse them, so the dry run does.
+ Ec2Service.validateMetadataOptions(launch.metadataOptions());
}
checkDryRun(p);
@@ -961,7 +963,7 @@ public class Ec2QueryHandler {
null,
null,
0,
- launch.availabilityZone(), null, null, launch.encodedUserData(), false,
+ launch.availabilityZone(), launch.metadataOptions(), null, launch.encodedUserData(), false,
null, null, launch.blockDeviceMappings());
Instance instance = reservation.getInstances().get(0);
launchedInstanceIds.add(instance.getInstanceId());
@@ -1119,6 +1121,7 @@ public class Ec2QueryHandler {
template.getUserData(),
template.getEncodedUserData(),
service.iamInstanceProfileArn(template),
+ template.getMetadataOptions(),
template.effectiveSecurityGroupIds(),
new ArrayList<>(tags.values()),
template.getBlockDeviceMappings());
@@ -1166,6 +1169,7 @@ public class Ec2QueryHandler {
private record FleetLaunch(String launchTemplateId, String launchTemplateName, String launchTemplateVersion,
String instanceType, String imageId, String subnetId, String availabilityZone,
String keyName, String userData, String encodedUserData, String iamInstanceProfileArn,
+ LaunchTemplateData.MetadataOptions metadataOptions,
List<String> securityGroupIds, List<Tag> instanceTags,
List<LaunchTemplateData.BlockDeviceMapping> blockDeviceMappings) {}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
index 659a833e4a..4cab916d11 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java
@@ -4566,7 +4566,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return inst;
}
- private static void validateMetadataOptions(LaunchTemplateData.MetadataOptions options) {
+ static void validateMetadataOptions(LaunchTemplateData.MetadataOptions options) {
if (options == null) {
return;
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingLaunchConfigurationMetadataIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingLaunchConfigurationMetadataIntegrationTest.java
new file mode 100644
index 0000000000..f9101e25d9
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingLaunchConfigurationMetadataIntegrationTest.java
@@ -0,0 +1,270 @@
+package io.github.hectorvent.floci.services.autoscaling;
+
+import io.github.hectorvent.floci.testing.EnforcementFixtures;
+import io.quarkus.test.junit.QuarkusTest;
+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.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 AutoScalingLaunchConfigurationMetadataIntegrationTest {
+ private static final String ACCOUNT = "222222222222";
+ private static final String GROUP = "DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult"
+ + ".AutoScalingGroups.member.";
+ private static final String LAUNCH_CONFIGURATION = "DescribeLaunchConfigurationsResponse"
+ + ".DescribeLaunchConfigurationsResult.LaunchConfigurations.member";
+ private static final String INSTANCE = "DescribeInstancesResponse.reservationSet.item.instancesSet.item.";
+
+ @Inject
+ AutoScalingReconciler reconciler;
+
+ @Test
+ void launchPreservesRequiredMetadata() {
+ String name = "launch-metadata-" + UUID.randomUUID();
+ request("autoscaling", "CreateLaunchConfiguration")
+ .formParam("LaunchConfigurationName", name).formParam("ImageId", "ami-amazonlinux2023")
+ .formParam("InstanceType", "t3.micro")
+ .formParam("MetadataOptions.HttpTokens", "required")
+ .formParam("MetadataOptions.HttpEndpoint", "enabled")
+ .formParam("MetadataOptions.HttpPutResponseHopLimit", "2")
+ .post("/").then().statusCode(200);
+ try {
+ createGroup(name);
+ reconciler.reconcileAll();
+ String instance = request("autoscaling", "DescribeAutoScalingGroups")
+ .formParam("AutoScalingGroupNames.member.1", name).post("/").then().statusCode(200)
+ .body(GROUP + "Instances.member.size()", equalTo(1))
+ .extract().path(GROUP + "Instances.member.InstanceId");
+ request("ec2", "DescribeInstances").formParam("InstanceId.1", instance).post("/").then().statusCode(200)
+ .body(INSTANCE + "metadataOptions.httpTokens", equalTo("required"))
+ .body(INSTANCE + "metadataOptions.httpEndpoint", equalTo("enabled"))
+ .body(INSTANCE + "metadataOptions.httpPutResponseHopLimit", equalTo("2"));
+ } finally {
+ deleteGroupAndLaunchConfiguration(name);
+ }
+ }
+
+ @Test
+ void refreshReplacementPreservesRequiredMetadata() {
+ String name = "refresh-metadata-" + UUID.randomUUID();
+ request("autoscaling", "CreateLaunchConfiguration")
+ .formParam("LaunchConfigurationName", name).formParam("ImageId", "ami-amazonlinux2023")
+ .formParam("InstanceType", "t3.micro")
+ .formParam("MetadataOptions.HttpTokens", "required")
+ .formParam("MetadataOptions.HttpPutResponseHopLimit", "2")
+ .post("/").then().statusCode(200);
+ try {
+ createGroup(name);
+ reconciler.reconcileAll();
+ reconciler.reconcileAll();
+ String original = request("autoscaling", "DescribeAutoScalingGroups")
+ .formParam("AutoScalingGroupNames.member.1", name).post("/").then().statusCode(200)
+ .extract().path(GROUP + "Instances.member.InstanceId");
+ String refreshId = request("autoscaling", "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.
+ request("autoscaling", "DescribeInstanceRefreshes")
+ .formParam("AutoScalingGroupName", name).formParam("InstanceRefreshIds.member.1", refreshId)
+ .post("/").then().statusCode(200)
+ .body("DescribeInstanceRefreshesResponse.DescribeInstanceRefreshesResult"
+ + ".InstanceRefreshes.member.Status", equalTo("Successful"));
+ String replacement = request("autoscaling", "DescribeAutoScalingGroups")
+ .formParam("AutoScalingGroupNames.member.1", name).post("/").then().statusCode(200)
+ .extract().path(GROUP + "Instances.member.InstanceId");
+ assertThat(replacement, not(equalTo(original)));
+ request("ec2", "DescribeInstances").formParam("InstanceId.1", replacement).post("/").then()
+ .statusCode(200)
+ .body(INSTANCE + "metadataOptions.httpTokens", equalTo("required"))
+ .body(INSTANCE + "metadataOptions.httpPutResponseHopLimit", equalTo("2"));
+ } finally {
+ deleteGroupAndLaunchConfiguration(name);
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource(delimiter = '|', quoteCharacter = '"', value = {
+ "MetadataOptions.HttpTokens=invalid|ValidationError|1 validation error detected: Value 'invalid' at"
+ + " 'metadataOptions.httpTokens' failed to satisfy constraint: Member must satisfy enum value"
+ + " set: [optional, required]",
+ "MetadataOptions.HttpEndpoint=invalid|ValidationError|1 validation error detected: Value 'invalid' at"
+ + " 'metadataOptions.httpEndpoint' failed to satisfy constraint: Member must satisfy enum value"
+ + " set: [disabled, enabled]",
+ "MetadataOptions.HttpPutResponseHopLimit=0|ValidationError|1 validation error detected: Value '0' at"
+ + " 'metadataOptions.httpPutResponseHopLimit' failed to satisfy constraint: Member must have"
+ + " value greater than or equal to 1",
+ "MetadataOptions.HttpPutResponseHopLimit=65|ValidationError|1 validation error detected: Value '65' at"
+ + " 'metadataOptions.httpPutResponseHopLimit' failed to satisfy constraint: Member must have"
+ + " value less than or equal to 64",
+ "MetadataOptions.HttpPutResponseHopLimit=not-an-integer|MalformedInput"
+ + "|HttpPutResponseHopLimit must be an integer.",
+ // The awsQuery protocol binds the value to a 32-bit integer before model validation runs.
+ "MetadataOptions.HttpPutResponseHopLimit=2147483648|MalformedInput"
+ + "|HttpPutResponseHopLimit must be an integer."})
+ void invalidMetadataRefusesWithoutCreatingLaunchConfiguration(String parameter, String code, String message) {
+ String name = "invalid-metadata-" + UUID.randomUUID();
+ String[] pair = parameter.split("=", 2);
+ request("autoscaling", "CreateLaunchConfiguration")
+ .formParam("LaunchConfigurationName", name).formParam("ImageId", "ami-amazonlinux2023")
+ .formParam("InstanceType", "t3.micro").formParam(pair[0], pair[1])
+ .post("/").then().statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo(code))
+ .body("ErrorResponse.Error.Message", equalTo(message));
+ request("autoscaling", "DescribeLaunchConfigurations")
+ .formParam("LaunchConfigurationNames.member.1", name).post("/").then().statusCode(200)
+ .body(LAUNCH_CONFIGURATION + ".size()", equalTo(0));
+ }
+
+ @Test
+ void everyInvalidMetadataMemberIsReportedInOneValidationError() {
+ String name = "invalid-metadata-" + UUID.randomUUID();
+ request("autoscaling", "CreateLaunchConfiguration")
+ .formParam("LaunchConfigurationName", name).formParam("ImageId", "ami-amazonlinux2023")
+ .formParam("InstanceType", "t3.micro")
+ .formParam("MetadataOptions.HttpTokens", "invalid")
+ .formParam("MetadataOptions.HttpPutResponseHopLimit", "65")
+ .formParam("MetadataOptions.HttpEndpoint", "invalid")
+ .post("/").then().statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))
+ .body("ErrorResponse.Error.Message", equalTo("3 validation errors detected: Value 'invalid' at"
+ + " 'metadataOptions.httpTokens' failed to satisfy constraint: Member must satisfy enum value"
+ + " set: [optional, required]; Value '65' at 'metadataOptions.httpPutResponseHopLimit' failed"
+ + " to satisfy constraint: Member must have value less than or equal to 64; Value 'invalid' at"
+ + " 'metadataOptions.httpEndpoint' failed to satisfy constraint: Member must satisfy enum value"
+ + " set: [disabled, enabled]"));
+ request("autoscaling", "DescribeLaunchConfigurations")
+ .formParam("LaunchConfigurationNames.member.1", name).post("/").then().statusCode(200)
+ .body(LAUNCH_CONFIGURATION + ".size()", equalTo(0));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void describeOmitsMetadataNeverGivenAndReturnsCloudFormationValues(boolean cloudFormation) {
+ String name = "metadata-roundtrip-" + UUID.randomUUID();
+ try {
+ if (cloudFormation) {
+ String template = """
+ {"Resources":{"Launch":{"Type":"AWS::AutoScaling::LaunchConfiguration",
+ "Properties":{"LaunchConfigurationName":"%s","ImageId":"ami-amazonlinux2023",
+ "InstanceType":"t3.micro","MetadataOptions":{"HttpTokens":"required",
+ "HttpEndpoint":"disabled","HttpPutResponseHopLimit":3}}}}}
+ """.formatted(name);
+ request("cloudformation", "CreateStack").formParam("StackName", name)
+ .formParam("TemplateBody", template).post("/").then().statusCode(200);
+ } else {
+ request("autoscaling", "CreateLaunchConfiguration")
+ .formParam("LaunchConfigurationName", name).formParam("ImageId", "ami-amazonlinux2023")
+ .formParam("InstanceType", "t3.micro").post("/").then().statusCode(200);
+ }
+ ValidatableResponse described = describeLaunchConfiguration(name);
+ if (cloudFormation) {
+ described.body(LAUNCH_CONFIGURATION + ".MetadataOptions.HttpTokens", equalTo("required"))
+ .body(LAUNCH_CONFIGURATION + ".MetadataOptions.HttpEndpoint", equalTo("disabled"))
+ .body(LAUNCH_CONFIGURATION + ".MetadataOptions.HttpPutResponseHopLimit", equalTo("3"));
+ } else {
+ described.body(LAUNCH_CONFIGURATION + ".MetadataOptions.size()", equalTo(0));
+ }
+ } finally {
+ if (cloudFormation) {
+ deleteStack(name);
+ } else {
+ deleteLaunchConfiguration(name);
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void cloudFormationResolvesConditionalMetadataOptions(boolean strict) {
+ String name = "conditional-metadata-" + UUID.randomUUID();
+ String template = """
+ {"Parameters":{"Strict":{"Type":"String"}},
+ "Conditions":{"IsStrict":{"Fn::Equals":[{"Ref":"Strict"},"yes"]}},
+ "Resources":{"Launch":{"Type":"AWS::AutoScaling::LaunchConfiguration",
+ "Properties":{"LaunchConfigurationName":"%s","ImageId":"ami-amazonlinux2023",
+ "InstanceType":"t3.micro","MetadataOptions":{"Fn::If":["IsStrict",
+ {"HttpTokens":"required","HttpPutResponseHopLimit":{"Ref":"AWS::NoValue"}},
+ {"Ref":"AWS::NoValue"}]}}}}}
+ """.formatted(name);
+ try {
+ request("cloudformation", "CreateStack").formParam("StackName", name)
+ .formParam("TemplateBody", template)
+ .formParam("Parameters.member.1.ParameterKey", "Strict")
+ .formParam("Parameters.member.1.ParameterValue", strict ? "yes" : "no")
+ .post("/").then().statusCode(200);
+ ValidatableResponse described = describeLaunchConfiguration(name);
+ if (strict) {
+ described.body(LAUNCH_CONFIGURATION + ".MetadataOptions.HttpTokens", equalTo("required"))
+ .body(LAUNCH_CONFIGURATION + ".MetadataOptions.HttpEndpoint", equalTo("enabled"))
+ .body(LAUNCH_CONFIGURATION + ".MetadataOptions.HttpPutResponseHopLimit", equalTo("1"));
+ } else {
+ described.body(LAUNCH_CONFIGURATION + ".MetadataOptions.size()", equalTo(0));
+ }
+ } finally {
+ deleteStack(name);
+ }
+ }
+
+ @Test
+ void partialMetadataFillsOnlyTheOtherMetadataDefaults() {
+ String name = "partial-metadata-" + UUID.randomUUID();
+ request("autoscaling", "CreateLaunchConfiguration")
+ .formParam("LaunchConfigurationName", name).formParam("ImageId", "ami-amazonlinux2023")
+ .formParam("InstanceType", "t3.micro").formParam("MetadataOptions.HttpTokens", "required")
+ .post("/").then().statusCode(200);
+ try {
+ describeLaunchConfiguration(name)
+ .body(LAUNCH_CONFIGURATION + ".MetadataOptions.HttpTokens", equalTo("required"))
+ .body(LAUNCH_CONFIGURATION + ".MetadataOptions.HttpEndpoint", equalTo("enabled"))
+ .body(LAUNCH_CONFIGURATION + ".MetadataOptions.HttpPutResponseHopLimit", equalTo("1"));
+ } finally {
+ deleteLaunchConfiguration(name);
+ }
+ }
+
+ private static void createGroup(String name) {
+ request("autoscaling", "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);
+ }
+
+ /** The named launch configuration's Describe response, after checking it was found. */
+ private static ValidatableResponse describeLaunchConfiguration(String name) {
+ return request("autoscaling", "DescribeLaunchConfigurations")
+ .formParam("LaunchConfigurationNames.member.1", name).post("/").then().statusCode(200)
+ .body(LAUNCH_CONFIGURATION + ".LaunchConfigurationName", equalTo(name));
+ }
+
+ // Cleanup ignores the status, so a test that failed before creating something keeps its own failure.
+ private static void deleteGroupAndLaunchConfiguration(String name) {
+ request("autoscaling", "DeleteAutoScalingGroup").formParam("AutoScalingGroupName", name)
+ .formParam("ForceDelete", "true").post("/");
+ deleteLaunchConfiguration(name);
+ }
+
+ private static void deleteLaunchConfiguration(String name) {
+ request("autoscaling", "DeleteLaunchConfiguration").formParam("LaunchConfigurationName", name).post("/");
+ }
+
+ private static void deleteStack(String name) {
+ request("cloudformation", "DeleteStack").formParam("StackName", name).post("/");
+ }
+
+ private static RequestSpecification request(String service, String action) {
+ return given().header("Authorization", EnforcementFixtures.auth(ACCOUNT, service)).formParam("Action", action);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java
index ba8bfcdf64..23eb41728d 100644
--- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingReconcilerTest.java
@@ -172,6 +172,11 @@ class AutoScalingReconcilerTest {
version.getData().setInstanceType("t3.micro");
version.getData().setUserData(storedText);
version.getData().setEncodedUserData(storedEncoding);
+ LaunchTemplateData.MetadataOptions metadata = new LaunchTemplateData.MetadataOptions();
+ metadata.setHttpTokens("required");
+ metadata.setHttpEndpoint("enabled");
+ metadata.setHttpPutResponseHopLimit(2);
+ version.getData().setMetadataOptions(metadata);
version.getData().setIamInstanceProfile(new LaunchTemplateData.IamInstanceProfile(
"arn:aws:iam::000000000000:instance-profile/app-profile", null));
when(ec2Service.iamInstanceProfileArn(version.getData()))
@@ -192,7 +197,7 @@ class AutoScalingReconcilerTest {
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
anyList(), eq(expectedText),
eq("arn:aws:iam::000000000000:instance-profile/app-profile"), eq(null),
- isNull(), eq(0), isNull(), isNull(), isNull(), eq(expectedEncoding),
+ isNull(), eq(0), isNull(), eq(metadata), isNull(), eq(expectedEncoding),
anyBoolean(), isNull(), isNull(), any())).thenReturn(reservation);
reconciler.reconcile(asg);
@@ -206,7 +211,7 @@ class AutoScalingReconcilerTest {
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
tags.capture(), eq(expectedText),
eq("arn:aws:iam::000000000000:instance-profile/app-profile"), eq(null),
- isNull(), eq(0), isNull(), isNull(), isNull(), eq(expectedEncoding),
+ isNull(), eq(0), isNull(), eq(metadata), isNull(), eq(expectedEncoding),
anyBoolean(), isNull(), isNull(), any());
assertEquals(storedText, version.getData().getUserData());
assertEquals(storedEncoding, version.getData().getEncodedUserData());
@@ -422,6 +427,11 @@ class AutoScalingReconcilerTest {
version.getData().setImageId("ami-version-3");
version.getData().setInstanceType("t3.micro");
version.getData().setEncodedUserData("IyEvYmluL2Jhc2gKZWNobyBoaQo=");
+ LaunchTemplateData.MetadataOptions metadata = new LaunchTemplateData.MetadataOptions();
+ metadata.setHttpTokens("required");
+ metadata.setHttpEndpoint("enabled");
+ metadata.setHttpPutResponseHopLimit(2);
+ version.getData().setMetadataOptions(metadata);
when(ec2Service.describeLaunchTemplates("us-east-1", List.of("lt-123"), List.of(), Map.of()))
.thenReturn(List.of(launchTemplate));
when(ec2Service.describeLaunchTemplateVersions("us-east-1", "lt-123", null, List.of("3")))
@@ -433,7 +443,7 @@ class AutoScalingReconcilerTest {
when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-3"), eq("t3.small"),
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
eq(List.of()), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null),
- isNull(), eq(0), isNull(), isNull(), isNull(), any(),
+ isNull(), eq(0), isNull(), eq(metadata), isNull(), any(),
anyBoolean(), isNull(), isNull(), any())).thenReturn(reservation);
reconciler.reconcile(asg);
@@ -446,7 +456,7 @@ class AutoScalingReconcilerTest {
verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-version-3"), eq("t3.small"),
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
eq(List.of()), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null),
- isNull(), eq(0), isNull(), isNull(), isNull(), any(), anyBoolean(), isNull(), isNull(), any());
+ isNull(), eq(0), isNull(), eq(metadata), isNull(), any(), anyBoolean(), isNull(), isNull(), any());
assertNull(version.getData().getUserData());
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLaunchConfigurationMetadataValidationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLaunchConfigurationMetadataValidationIntegrationTest.java
new file mode 100644
index 0000000000..dbe7cf2b94
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLaunchConfigurationMetadataValidationIntegrationTest.java
@@ -0,0 +1,144 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.github.hectorvent.floci.testing.EnforcementFixtures;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.List;
+import java.util.UUID;
+import java.util.stream.Stream;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Launch-configuration MetadataOptions outside the documented values (HttpTokens optional or
+ * required, HttpEndpoint enabled or disabled, HttpPutResponseHopLimit an integer from 1 to 64), or
+ * of the wrong JSON type, fail the resource and roll the stack back without leaving a launch
+ * configuration behind. A wrong type fails CloudFormation's template validation, a hop limit beyond
+ * 32 bits the handler's model validation, and a wrong value Auto Scaling's own validation, where a
+ * number or a boolean given for a string member arrives as its text.
+ */
+@QuarkusTest
+class CloudFormationLaunchConfigurationMetadataValidationIntegrationTest {
+ private static final String ACCOUNT = "222222222222";
+ private static final String AUTH = EnforcementFixtures.auth(ACCOUNT, "cloudformation");
+ private static final String BEYOND_32_BITS = "Model validation failed (#/MetadataOptions/HttpPutResponseHopLimit:"
+ + " expected type: Integer, found: String. This may occur when a numeric value exceeds 32-bit integer max"
+ + " (2147483647). Consider using 'number' type or ensure value fits in integer range.)";
+
+ static Stream<Arguments> invalidMetadataOptions() {
+ return Stream.of(
+ Arguments.of("{\"HttpTokens\":\"invalid\"}", "1 validation error detected: Value 'invalid' at"
+ + " 'metadataOptions.httpTokens' failed to satisfy constraint: Member must satisfy enum value"
+ + " set: [optional, required]"),
+ Arguments.of("{\"HttpEndpoint\":\"invalid\"}", "1 validation error detected: Value 'invalid' at"
+ + " 'metadataOptions.httpEndpoint' failed to satisfy constraint: Member must satisfy enum value"
+ + " set: [disabled, enabled]"),
+ Arguments.of("{\"HttpPutResponseHopLimit\":0}", "1 validation error detected: Value '0' at"
+ + " 'metadataOptions.httpPutResponseHopLimit' failed to satisfy constraint: Member must have"
+ + " value greater than or equal to 1"),
+ Arguments.of("{\"HttpPutResponseHopLimit\":65}", "1 validation error detected: Value '65' at"
+ + " 'metadataOptions.httpPutResponseHopLimit' failed to satisfy constraint: Member must have"
+ + " value less than or equal to 64"),
+ Arguments.of("{\"HttpTokens\":true}", "1 validation error detected: Value 'true' at"
+ + " 'metadataOptions.httpTokens' failed to satisfy constraint: Member must satisfy enum value"
+ + " set: [optional, required]"),
+ Arguments.of("{\"HttpEndpoint\":1}", "1 validation error detected: Value '1' at"
+ + " 'metadataOptions.httpEndpoint' failed to satisfy constraint: Member must satisfy enum value"
+ + " set: [disabled, enabled]"),
+ Arguments.of("\"required\"", "Property [MetadataOptions] expected type: JSONObject, found: String"),
+ Arguments.of("{\"HttpTokens\":[\"required\"]}",
+ "Property [HttpTokens] expected type: String, found: JSONArray"),
+ Arguments.of("{\"HttpEndpoint\":{\"Value\":\"disabled\"}}",
+ "Property [HttpEndpoint] expected type: String, found: JSONObject"),
+ Arguments.of("{\"HttpPutResponseHopLimit\":[2]}",
+ "Property [HttpPutResponseHopLimit] expected type: Integer, found: JSONArray"),
+ Arguments.of("{\"HttpPutResponseHopLimit\":\"not-an-integer\"}",
+ "Property [HttpPutResponseHopLimit] expected type: Integer, found: String"),
+ Arguments.of("{\"HttpPutResponseHopLimit\":4.5}",
+ "Property [HttpPutResponseHopLimit] expected type: Integer, found: Float"),
+ Arguments.of("{\"HttpPutResponseHopLimit\":\"4.5\"}",
+ "Property [HttpPutResponseHopLimit] expected type: Integer, found: Float"),
+ Arguments.of("{\"HttpPutResponseHopLimit\":true}",
+ "Property [HttpPutResponseHopLimit] expected type: Integer, found: Boolean"),
+ Arguments.of("{\"HttpPutResponseHopLimit\":2147483648}", BEYOND_32_BITS),
+ Arguments.of("{\"HttpPutResponseHopLimit\":-2147483649}", BEYOND_32_BITS),
+ // Model validation fails before Auto Scaling is called, so its own check never runs.
+ Arguments.of("{\"HttpTokens\":\"invalid\",\"HttpPutResponseHopLimit\":2147483648}", BEYOND_32_BITS));
+ }
+
+ @ParameterizedTest
+ @MethodSource("invalidMetadataOptions")
+ void invalidMetadataOptionsFailTheResourceWithoutCreatingIt(String metadataOptions, String message) {
+ String name = "cfn-invalid-metadata-" + UUID.randomUUID();
+ String template = """
+ {"Resources":{"Launch":{"Type":"AWS::AutoScaling::LaunchConfiguration",
+ "Properties":{"LaunchConfigurationName":"%s","ImageId":"ami-amazonlinux2023",
+ "InstanceType":"t3.micro","MetadataOptions":%s}}}}
+ """.formatted(name, metadataOptions);
+ try {
+ request("cloudformation", "CreateStack").formParam("StackName", name).formParam("TemplateBody", template)
+ .post("/").then().statusCode(200);
+
+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(name, AUTH);
+ assertEquals("ROLLBACK_COMPLETE", state.status(), state.reason());
+ String events = request("cloudformation", "DescribeStackEvents").formParam("StackName", name)
+ .post("/").then().statusCode(200).extract().asString();
+ List<String> failures = XmlParser.extractGroups(events, "member").stream()
+ .filter(event -> "Launch".equals(event.get("LogicalResourceId"))
+ && "CREATE_FAILED".equals(event.get("ResourceStatus")))
+ .map(event -> event.get("ResourceStatusReason"))
+ .toList();
+ assertThat(failures, contains(equalTo(message)));
+ request("autoscaling", "DescribeLaunchConfigurations")
+ .formParam("LaunchConfigurationNames.member.1", name).post("/").then().statusCode(200)
+ .body("DescribeLaunchConfigurationsResponse.DescribeLaunchConfigurationsResult"
+ + ".LaunchConfigurations.member.size()", equalTo(0));
+ } finally {
+ deleteStack(name);
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource(delimiter = '|', value = {"1|1", "64|64", "\"2\"|2", "{\"Ref\":\"Hops\"}|5"})
+ void hopLimitsAtTheBoundsAsStringsOrFromParametersAreAccepted(String hopLimit, String stored) {
+ String name = "cfn-valid-metadata-" + UUID.randomUUID();
+ String template = """
+ {"Parameters":{"Hops":{"Type":"Number","Default":"5"}},
+ "Resources":{"Launch":{"Type":"AWS::AutoScaling::LaunchConfiguration",
+ "Properties":{"LaunchConfigurationName":"%s","ImageId":"ami-amazonlinux2023",
+ "InstanceType":"t3.micro","MetadataOptions":{"HttpPutResponseHopLimit":%s}}}}}
+ """.formatted(name, hopLimit);
+ try {
+ request("cloudformation", "CreateStack").formParam("StackName", name).formParam("TemplateBody", template)
+ .post("/").then().statusCode(200);
+
+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(name, AUTH);
+ assertEquals("CREATE_COMPLETE", state.status(), state.reason());
+ request("autoscaling", "DescribeLaunchConfigurations")
+ .formParam("LaunchConfigurationNames.member.1", name).post("/").then().statusCode(200)
+ .body("DescribeLaunchConfigurationsResponse.DescribeLaunchConfigurationsResult"
+ + ".LaunchConfigurations.member.MetadataOptions.HttpPutResponseHopLimit", equalTo(stored));
+ } finally {
+ deleteStack(name);
+ }
+ }
+
+ // Ignores the status, so a test that failed before the stack existed keeps its own failure.
+ private static void deleteStack(String name) {
+ request("cloudformation", "DeleteStack").formParam("StackName", name).post("/");
+ }
+
+ private static RequestSpecification request(String service, String action) {
+ return given().header("Authorization", EnforcementFixtures.auth(ACCOUNT, service)).formParam("Action", action);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisionerTest.java
index fecf00f3c2..05228be1b7 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisionerTest.java
@@ -329,7 +329,7 @@ class AutoScalingGroupCfnProvisionerTest {
lc.setLaunchConfigurationName("my-lc");
lc.setLaunchConfigurationArn("arn:aws:autoscaling:us-east-1:000000000000:launchConfiguration:my-lc");
when(autoScaling.createLaunchConfiguration(eq(REGION), eq("my-lc"), any(), eq("ami-1"),
- eq("t3.micro"), any(), anyList(), any(), any(), any()))
+ eq("t3.micro"), any(), anyList(), any(), any(), any(), any(), anyList(), any()))
.thenReturn(lc);
StackResource r = resource(LAUNCH_CONFIGURATION, "Lc", null);
ObjectNode props = mapper.createObjectNode()
@@ -360,7 +360,7 @@ class AutoScalingGroupCfnProvisionerTest {
provisioner.provision(r, props, ctx("my-lc"));
verify(autoScaling, never()).createLaunchConfiguration(anyString(), anyString(), any(), any(),
- any(), any(), anyList(), any(), any(), any());
+ any(), any(), anyList(), any(), any(), any(), any(), anyList(), any());
assertEquals("my-lc", r.getPhysicalId());
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2LaunchTemplateMetadataOptionsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2LaunchTemplateMetadataOptionsIntegrationTest.java
new file mode 100644
index 0000000000..7536094b8b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2LaunchTemplateMetadataOptionsIntegrationTest.java
@@ -0,0 +1,111 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import io.github.hectorvent.floci.core.common.RequestScopes;
+import io.github.hectorvent.floci.services.autoscaling.AutoScalingReconciler;
+import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
+import io.github.hectorvent.floci.testing.EnforcementFixtures;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.specification.RequestSpecification;
+import jakarta.inject.Inject;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.List;
+import java.util.UUID;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+
+/** A launch template's MetadataOptions reach instances launched by EC2 Fleet and Auto Scaling. */
+@QuarkusTest
+class Ec2LaunchTemplateMetadataOptionsIntegrationTest {
+ private static final String OWNER = "212121212121";
+ private static final String INSTANCE = "DescribeInstancesResponse.reservationSet.item.instancesSet.item.";
+
+ @Inject
+ AutoScalingReconciler reconciler;
+
+ @Inject
+ AutoScalingService groups;
+
+ @ParameterizedTest
+ @ValueSource(strings = {"fleet", "asg"})
+ void templateMetadataOptionsReachTheLaunchedInstance(String source) {
+ String name = "template-metadata-" + UUID.randomUUID().toString().substring(0, 8);
+ String template = request("ec2", "CreateLaunchTemplate").formParam("LaunchTemplateName", name)
+ .formParam("LaunchTemplateData.ImageId", "ami-amazonlinux2023")
+ .formParam("LaunchTemplateData.InstanceType", "t3.micro")
+ .formParam("LaunchTemplateData.MetadataOptions.HttpTokens", "required")
+ .formParam("LaunchTemplateData.MetadataOptions.HttpPutResponseHopLimit", "2")
+ .post("/").then().statusCode(200)
+ .extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
+ String instance = null;
+ try {
+ if ("fleet".equals(source)) {
+ instance = request("ec2", "CreateFleet").formParam("Type", "instant")
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.LaunchTemplateId", template)
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.Version", "1")
+ .formParam("TargetCapacitySpecification.TotalTargetCapacity", 1)
+ .formParam("TargetCapacitySpecification.DefaultTargetCapacityType", "on-demand")
+ .post("/").then().statusCode(200)
+ .extract().path("CreateFleetResponse.fleetInstanceSet.item.instanceIds.item");
+ } else {
+ request("autoscaling", "CreateAutoScalingGroup").formParam("AutoScalingGroupName", name)
+ .formParam("LaunchTemplate.LaunchTemplateId", template).formParam("LaunchTemplate.Version", "1")
+ .formParam("MinSize", 0).formParam("MaxSize", 1).formParam("DesiredCapacity", 1)
+ .formParam("AvailabilityZones.member.1", "us-east-1a").post("/").then().statusCode(200);
+ RequestScopes.runAs(OWNER, () -> reconciler.reconcile(
+ groups.describeAutoScalingGroups("us-east-1", List.of(name)).getFirst()));
+ instance = request("autoscaling", "DescribeAutoScalingGroups")
+ .formParam("AutoScalingGroupNames.member.1", name).post("/").then().statusCode(200)
+ .extract().path("DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult"
+ + ".AutoScalingGroups.member.Instances.member.InstanceId");
+ }
+ request("ec2", "DescribeInstances").formParam("InstanceId.1", instance).post("/").then().statusCode(200)
+ .body(INSTANCE + "metadataOptions.httpTokens", equalTo("required"))
+ .body(INSTANCE + "metadataOptions.httpPutResponseHopLimit", equalTo("2"));
+ } finally {
+ // Cleanup ignores the status, so a test that failed before launching keeps its own failure.
+ if ("asg".equals(source)) {
+ request("autoscaling", "DeleteAutoScalingGroup").formParam("AutoScalingGroupName", name)
+ .formParam("ForceDelete", "true").post("/");
+ } else if (instance != null) {
+ request("ec2", "TerminateInstances").formParam("InstanceId.1", instance).post("/");
+ }
+ request("ec2", "DeleteLaunchTemplate").formParam("LaunchTemplateId", template).post("/");
+ }
+ }
+
+ /**
+ * A template stores its metadata options unchecked, as AWS does, so the launch is where they fail.
+ * A dry run answers that failure too rather than DryRunOperation.
+ */
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void createFleetRefusesInvalidTemplateMetadataWithOrWithoutDryRun(boolean dryRun) {
+ String template = request("ec2", "CreateLaunchTemplate")
+ .formParam("LaunchTemplateName", "bad-metadata-" + UUID.randomUUID().toString().substring(0, 8))
+ .formParam("LaunchTemplateData.ImageId", "ami-amazonlinux2023")
+ .formParam("LaunchTemplateData.InstanceType", "t3.micro")
+ .formParam("LaunchTemplateData.MetadataOptions.HttpTokens", "invalid")
+ .post("/").then().statusCode(200)
+ .extract().path("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");
+ try {
+ request("ec2", "CreateFleet").formParam("Type", "instant").formParam("DryRun", String.valueOf(dryRun))
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.LaunchTemplateId", template)
+ .formParam("LaunchTemplateConfig.1.LaunchTemplateSpecification.Version", "1")
+ .formParam("TargetCapacitySpecification.TotalTargetCapacity", 1)
+ .formParam("TargetCapacitySpecification.DefaultTargetCapacityType", "on-demand")
+ .post("/").then().statusCode(400)
+ .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"))
+ .body("Response.Errors.Error.Message", equalTo(
+ "Value (invalid) for parameter HttpTokens is invalid. Valid values are: optional, required."));
+ } finally {
+ request("ec2", "DeleteLaunchTemplate").formParam("LaunchTemplateId", template).post("/");
+ }
+ }
+
+ private static RequestSpecification request(String service, String action) {
+ return given().header("Authorization", EnforcementFixtures.auth(OWNER, service)).formParam("Action", action);
+ }
+}