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

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