feat(autoscaling): P0 operations and lifecycle-hook delete-by-name (#2673)

* feat(autoscaling): add SetInstanceProtection and SetInstanceHealth

* test(applicationautoscaling): cover DeleteScalingPolicy over the wire

* chore(autoscaling): cede the DeleteScalingPolicy test to feature/applicationautoscaling-delete-policy

The file was byte-identical on both branches; the ApplicationAutoScaling
test belongs on the applicationautoscaling branch by service, and keeping
both would make whichever merges second conflict on an unrelated file.

* fix(autoscaling): validate LifecycleHookName pattern and LifecycleActionToken length

PutLifecycleHook, DeleteLifecycleHook, and CompleteLifecycleAction accepted any
hook name and lifecycle-action token, so a name with characters outside the
modeled [A-Za-z0-9\-_/]+ pattern or a token that wasn't exactly 36 characters
was stored/consumed instead of rejected the way AWS rejects it
(autoscaling/2011-01-01/service-2.json: LifecycleHookName, LifecycleActionToken).

* fix(autoscaling): address maintainer review on instance ops and lifecycle hooks

- SetInstanceProtection: validate InstanceIds before requireGroup (AWS
  validates required members first), compare requested/found instance
  IDs via set containment instead of size-based matching (duplicate
  stored IDs no longer break the check), and report every missing
  instance ID instead of just the first.
- SetInstanceProtection: ProtectedFromScaleIn is a required boolean
  member; reject missing/malformed values instead of silently
  coercing to false via Boolean.parseBoolean.
- SetInstanceHealth: collapse the redundant second instance lookup
  after the orElseThrow already guarantees group membership. Parse
  and pass through ShouldRespectGracePeriod for wire fidelity (not
  yet enforced -- floci has no instance launch-time tracking against
  HealthCheckGracePeriod).
- deleteLifecycleHookByName (CFN delete path): validate the name for
  parity with deleteLifecycleHook instead of silently no-op'ing on an
  unvalidatable name.
- validateLifecycleHookName: split null/length/pattern checks so the
  thrown message matches the actual failure instead of always citing
  the regex pattern.
- Style: import java.util.regex.Pattern instead of fully qualifying
  it, and fix switch-case column alignment for the two new instance
  ops.

* fix(autoscaling): allow completeLifecycleAction without a token when InstanceId identifies the action

LifecycleActionToken and InstanceId are both optional in CompleteLifecycleActionType
per the service model — only LifecycleHookName, AutoScalingGroupName, and
LifecycleActionResult are required. A caller identifying the action by
InstanceId + LifecycleHookName + AutoScalingGroupName alone was rejected with a
length-36 error even though real AWS accepts it.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-28 17:11:56 -04:00
1 parent 3bd9bcc62b
commit e9a379b37a
4 files changed
+405

No files matched your search

@@ -50,6 +50,8 @@ public class AutoScalingQueryHandler {
case "DeleteTags" -> handleDeleteTags(p, region);
// Instances
case "DescribeAutoScalingInstances" -> handleDescribeAutoScalingInstances(p, region);
case "SetInstanceProtection" -> handleSetInstanceProtection(p, region);
case "SetInstanceHealth" -> handleSetInstanceHealth(p, region);
case "AttachInstances" -> handleAttachInstances(p, region);
case "DetachInstances" -> handleDetachInstances(p, region);
case "TerminateInstanceInAutoScalingGroup" -> handleTerminateInstance(p, region);
@@ -472,6 +474,32 @@ public class AutoScalingQueryHandler {
return ok(xml.build());
}
private Response handleSetInstanceProtection(MultivaluedMap<String, String> p, String region) {
String groupName = p.getFirst("AutoScalingGroupName");
List<String> instanceIds = memberList(p, "InstanceIds");
boolean protectedFromScaleIn = requiredBoolParam(p, "ProtectedFromScaleIn");
service.setInstanceProtection(region, groupName, instanceIds, protectedFromScaleIn);
return ok(new XmlBuilder()
.start("SetInstanceProtectionResponse", NS)
.raw(AwsQueryResponse.responseMetadata())
.end("SetInstanceProtectionResponse")
.build());
}
private Response handleSetInstanceHealth(MultivaluedMap<String, String> p, String region) {
String instanceId = p.getFirst("InstanceId");
String healthStatus = p.getFirst("HealthStatus");
// Defaults to true per the 2011-01-01 model: absent means "respect the grace period".
boolean shouldRespectGracePeriod = Boolean.parseBoolean(
Optional.ofNullable(p.getFirst("ShouldRespectGracePeriod")).orElse("true"));
service.setInstanceHealth(region, instanceId, healthStatus, shouldRespectGracePeriod);
return ok(new XmlBuilder()
.start("SetInstanceHealthResponse", NS)
.raw(AwsQueryResponse.responseMetadata())
.end("SetInstanceHealthResponse")
.build());
}
private static void appendInstanceLaunchTemplateXml(XmlBuilder xml, AsgInstance inst) {
if (inst.getLaunchTemplateId() == null && inst.getLaunchTemplateName() == null) {
return;
@@ -1134,6 +1162,22 @@ public class AutoScalingQueryHandler {
return Boolean.parseBoolean(val);
}
/** A required boolean member must be present and exactly "true"/"false" — never silently coerced to false. */
private boolean requiredBoolParam(MultivaluedMap<String, String> p, String key) {
String val = p.getFirst(key);
if (val == null || val.isBlank()) {
throw new AwsException("ValidationError",
"1 validation error detected: Value null at '" + key
+ "' failed to satisfy constraint: Member must not be null", 400);
}
if (!"true".equalsIgnoreCase(val) && !"false".equalsIgnoreCase(val)) {
throw new AwsException("ValidationError",
"1 validation error detected: Value '" + val + "' at '" + key
+ "' failed to satisfy constraint: Member must be a valid boolean", 400);
}
return Boolean.parseBoolean(val);
}
private String intString(Integer value) {
return value != null ? String.valueOf(value) : null;
}
@@ -17,6 +17,7 @@ import jakarta.inject.Inject;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@ApplicationScoped
@@ -371,6 +372,56 @@ public class AutoScalingService {
return all;
}
public void setInstanceProtection(String region, String groupName, List<String> instanceIds,
boolean protectedFromScaleIn) {
if (instanceIds == null || instanceIds.isEmpty()) {
throw new AwsException("ValidationError", "At least one instance ID is required.", 400);
}
AutoScalingGroup asg = requireGroup(region, groupName);
Set<String> requested = new HashSet<>(instanceIds);
Set<String> found = asg.getInstances().stream()
.map(AsgInstance::getInstanceId)
.filter(requested::contains)
.collect(Collectors.toSet());
if (!found.containsAll(requested)) {
String missing = requested.stream()
.filter(id -> !found.contains(id))
.collect(Collectors.joining(", "));
throw new AwsException("ValidationError",
"Instance(s) '" + missing + "' is/are not part of Auto Scaling group '" + groupName + "'.", 400);
}
asg.getInstances().stream()
.filter(instance -> requested.contains(instance.getInstanceId()))
.forEach(instance -> instance.setProtectedFromScaleIn(protectedFromScaleIn));
groups.put(asgKey(region, groupName), asg);
}
/**
* {@code shouldRespectGracePeriod} is parsed and accepted for wire fidelity (2011-01-01 model)
* but not yet enforced — floci does not currently track instance launch time against
* {@link AutoScalingGroup#getHealthCheckGracePeriod()}, so the health status change below always
* applies immediately regardless of the flag.
*/
public void setInstanceHealth(String region, String instanceId, String healthStatus,
boolean shouldRespectGracePeriod) {
if (!"Healthy".equals(healthStatus) && !"Unhealthy".equals(healthStatus)) {
throw new AwsException("ValidationError",
"HealthStatus must be Healthy or Unhealthy.", 400);
}
AutoScalingGroup asg = groups.values().stream()
.filter(group -> region.equals(group.getRegion()))
.filter(group -> group.getInstances().stream()
.anyMatch(instance -> instanceId != null && instanceId.equals(instance.getInstanceId())))
.findFirst()
.orElseThrow(() -> new AwsException("ValidationError",
"Instance '" + instanceId + "' not found in any Auto Scaling group.", 400));
asg.getInstances().stream()
.filter(instance -> instanceId.equals(instance.getInstanceId()))
.findFirst()
.ifPresent(instance -> instance.setHealthStatus(healthStatus));
groups.put(asgKey(region, asg.getAutoScalingGroupName()), asg);
}
public void attachInstances(String region, String name, List<String> instanceIds) {
AutoScalingGroup asg = requireGroup(region, name);
for (String id : instanceIds) {
@@ -560,6 +611,7 @@ public class AutoScalingService {
String roleArn, String notificationMetadata,
Integer heartbeatTimeout, String defaultResult) {
requireGroup(region, asgName);
validateLifecycleHookName(hookName);
String key = hookKey(region, asgName, hookName);
LifecycleHook hook = hooks.computeIfAbsent(key, k -> new LifecycleHook());
hook.setLifecycleHookName(hookName);
@@ -574,6 +626,7 @@ public class AutoScalingService {
}
public void deleteLifecycleHook(String region, String asgName, String hookName) {
validateLifecycleHookName(hookName);
hooks.remove(hookKey(region, asgName, hookName));
}
@@ -586,6 +639,11 @@ public class AutoScalingService {
if (hookName == null) {
return;
}
// The physical id was only ever assigned from a name that already passed this check
// (see putLifecycleHook), so this call for parity with deleteLifecycleHook should never
// reject a hook created through the normal path — it exists to fail loudly, not silently
// no-op, if a corrupted or hand-authored physical id ever reaches this delete path.
validateLifecycleHookName(hookName);
List<String> keys = new ArrayList<>();
for (Map.Entry<String, LifecycleHook> entry : hooks.entrySet()) {
LifecycleHook hook = entry.getValue();
@@ -616,6 +674,43 @@ public class AutoScalingService {
String instanceId, String actionResult, String token) {
// Stored-only — Phase 2 reconciler observes this via the instance lifecycle state
requireGroup(region, asgName);
validateLifecycleHookName(hookName);
if (token != null) {
validateLifecycleActionToken(token);
}
}
/** LifecycleHookName pattern/length from the Auto Scaling model (autoscaling/2011-01-01/service-2.json). */
private static final Pattern LIFECYCLE_HOOK_NAME_PATTERN =
Pattern.compile("^[A-Za-z0-9\\-_/]+$");
private static void validateLifecycleHookName(String hookName) {
if (hookName == null) {
throw new AwsException("ValidationError",
"1 validation error detected: Value null at 'lifecycleHookName' failed to satisfy constraint: "
+ "Member must not be null", 400);
}
if (hookName.length() > 255) {
throw new AwsException("ValidationError",
"1 validation error detected: Value '" + hookName
+ "' at 'lifecycleHookName' failed to satisfy constraint: Member must have length "
+ "less than or equal to 255", 400);
}
if (!LIFECYCLE_HOOK_NAME_PATTERN.matcher(hookName).matches()) {
throw new AwsException("ValidationError",
"1 validation error detected: Value '" + hookName
+ "' at 'lifecycleHookName' failed to satisfy constraint: Member must satisfy "
+ "regular expression pattern: [A-Za-z0-9\\-_/]+", 400);
}
}
/** LifecycleActionToken is modeled as a fixed 36-character token (autoscaling/2011-01-01/service-2.json). */
private static void validateLifecycleActionToken(String token) {
if (token == null || token.length() != 36) {
throw new AwsException("ValidationError",
"1 validation error detected: Value at 'lifecycleActionToken' failed to satisfy constraint: "
+ "Member must have length equal to 36", 400);
}
}
// ── Scaling policies ───────────────────────────────────────────────────────