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

* fix(autoscaling): honor launch configuration metadata options

CreateLaunchConfiguration ignored MetadataOptions, so
DescribeLaunchConfigurations never returned them and every instance
launched from the configuration got EC2's defaults, HttpTokens=optional
included.

- The Query handler and the AWS::AutoScaling::LaunchConfiguration
  provisioner read the structure, validate it as EC2 does
  (ValidationError for a value outside the allowed set or range) and
  store it. CloudFormation resolves Fn::If and AWS::NoValue inside it.
- DescribeLaunchConfigurations returns the structure with defaults for
  the members left out, and omits it when it was never given.
- The reconciler passes it to every launch, instance refresh
  replacements included.
- Auto Scaling launches from a launch template, directly or through a
  mixed instances policy, and CreateFleet forward the template's
  metadata options, which they dropped before.

Split out of #5671 at review.

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

* test(autoscaling): clean up after the launch configuration metadata tests

The metadata tests now delete the groups, launch configurations and
stacks they create, so later reconcileAll calls in the shared test
application stop reconciling leaked groups. They build their
Authorization headers with EnforcementFixtures.auth, and the case that
expects no MetadataOptions first checks that the launch configuration
was found.

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

* fix(autoscaling): word metadata option errors as Auto Scaling does

CreateLaunchConfiguration refused bad MetadataOptions with EC2's
InvalidParameterValue text under a ValidationError code. It now answers
with Auto Scaling's model-validation text, for example "1 validation
error detected: Value '65' at 'metadataOptions.httpPutResponseHopLimit'
failed to satisfy constraint: Member must have value less than or equal
to 64", and reports every invalid member of the structure in one
error, "N validation errors detected: ...; ...". EC2's validator is no
longer shared.

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

* fix(cloudformation): refuse list or object launch configuration metadata members

A MetadataOptions member given as a list or an object, such as
HttpTokens: [required], read as an empty string and so as absent: the
launch configuration was created with that member at its default,
HttpTokens=optional included. Such a member now fails the resource with
ValidationError, as the whole structure already does when it is not an
object.

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

* test(autoscaling): cover every metadata member in the combined error

The test that sends several invalid MetadataOptions members now makes
all three invalid, so the position of HttpEndpoint in the combined
ValidationError is checked, and confirms that no launch configuration
was created.

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

* fix(cloudformation): report metadata type errors as CloudFormation does

A launch configuration MetadataOptions block or member of the wrong
JSON type failed with wording Floci made up, such as "HttpTokens must
be a string.". It now fails with CloudFormation's schema type error, as
the S3 and DynamoDB provisioners already report it, for example "Model
validation failed (#/MetadataOptions/HttpTokens: expected type: String,
found: JSONArray)". A value of the right type that Auto Scaling rejects
keeps Auto Scaling's ValidationError.

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

* fix(cloudformation): report an oversized metadata hop limit as out of range

A whole-number HttpPutResponseHopLimit too large for an int, such as
2147483648, failed with the contradictory "expected type: Integer,
found: Integer". It is an integer outside 1 to 64, so it now fails with
the same Auto Scaling ValidationError text as 65 or 0, with the value
as written.

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

* fix(cloudformation): count an oversized hop limit with the other metadata errors

An oversized CloudFormation HttpPutResponseHopLimit was refused before
the other MetadataOptions members were checked, so an invalid
HttpTokens beside it went unreported, and the value was echoed as
written, "+002147483648" included. Auto Scaling now builds the whole
error from the options and the hop limit as a BigInteger, so the
oversized value is counted with every other violation and printed as
a plain number.

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

* refactor(autoscaling): build metadata option errors through SmithyValidationErrors

The launch configuration MetadataOptions validator assembled its "N
validation errors detected" message by hand. It now uses
SmithyValidationErrors, which main adopted for Auto Scaling's other
checks. The error code and text are unchanged.

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

* fix(cloudformation): read launch configuration metadata through CfnPropertyTypes

The MetadataOptions reader had its own type check and answered every
wrongly typed value with the handler's "Model validation failed"
message. It now reads the block through CfnPropertyTypes, as the Events
and Lambda provisioners do:

- a value of the wrong type fails template validation first, for
  example "Property [HttpTokens] expected type: String, found:
  JSONArray", and a hop limit of 4.5 is "found: Float";
- a hop limit beyond 32 bits fails the handler's model validation,
  before Auto Scaling's own check runs;
- a number or a boolean given for a string member arrives at Auto
  Scaling as its text, as CloudFormation converts it, and fails its
  enum check there.

The hand-written type helpers go away.

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

* refactor(autoscaling): fold the metadata options error back into its validator

The public metadataOptionsError took the hop limit as a BigInteger so
that CloudFormation could report a value beyond 32 bits through it.
CloudFormation now refuses such a value in model validation, before
Auto Scaling, so the helper goes back to a private validator over the
Integer field. The error code and text are unchanged.

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

* test(ec2): delete the launch template the metadata test creates

Ec2LaunchTemplateMetadataOptionsIntegrationTest never deleted its
launch template, and its cleanup began only after the fleet or group
had launched, so an earlier failure left everything behind. Everything
after the template is created now runs in the try block, and the
finally block removes the group or the instance and then the template,
ignoring the status so a test's own failure is kept.

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

* fix(ec2): check template metadata options before a CreateFleet dry run

A launch template stores its metadata options unchecked, as AWS does,
so they fail at launch. CreateFleet forwards them to the launch since
this branch, but a dry run returned DryRunOperation before any launch
ran, saying a fleet would succeed that then fails with
InvalidParameterValue. CreateFleet now checks every launch's metadata
options with the rest of its pre-launch checks, as RunInstances does
before honoring DryRun.

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

* test(autoscaling): pin the Query answer for a hop limit beyond 32 bits

CreateLaunchConfiguration with MetadataOptions.HttpPutResponseHopLimit=
2147483648 answers MalformedInput, as for any value that is not a
32-bit integer: the awsQuery protocol binds the member before model
validation runs. A row now covers it beside the non-numeric case.

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

---------

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-19 09:42:58 -04:00
1 parent 09b14e9d10
commit e75b15809f
14 files changed
+717 -16

No files matched your search

@@ -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);
}
}
@@ -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());
}
@@ -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);
}
}
@@ -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());
}
@@ -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);
}
}