From e9a379b37a3627cb8e0a3dc752687562e6b00a73 Mon Sep 17 00:00:00 2001 From: Sam Fakhreddine Date: Fri, 28 Aug 2026 15:11:56 -0600 Subject: [PATCH] feat(autoscaling): P0 operations and lifecycle-hook delete-by-name (#2673) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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. --- .../autoscaling/AutoScalingQueryHandler.java | 44 ++++++ .../autoscaling/AutoScalingService.java | 95 ++++++++++++ .../AutoScalingQueryHandlerTest.java | 135 ++++++++++++++++++ .../autoscaling/AutoScalingServiceTest.java | 131 +++++++++++++++++ 4 files changed, 405 insertions(+) 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 ff8f9eb52c..53c8a44e0b 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 @@ -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 p, String region) { + String groupName = p.getFirst("AutoScalingGroupName"); + List 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 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 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; } 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 aaf0495caf..638a4a8ad2 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 @@ -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 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 requested = new HashSet<>(instanceIds); + Set 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 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 keys = new ArrayList<>(); for (Map.Entry 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 ─────────────────────────────────────────────────────── diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandlerTest.java index ab3347f8e1..f03321ecf6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingQueryHandlerTest.java @@ -185,6 +185,141 @@ class AutoScalingQueryHandlerTest { assertTrue(xml.contains("7")); } + @Test + void setInstanceProtectionMutatesInstanceAndReturnsAwsQueryShape() { + AutoScalingService service = new AutoScalingService(); + service.regionResolver = new RegionResolver(REGION, "000000000000"); + service.createAutoScalingGroup(REGION, "protected-asg", null, "lt", null, "1", null, + 0, 2, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), + "EC2", 0, List.of("Default"), java.util.Map.of(), java.util.Map.of()); + AsgInstance instance = new AsgInstance(); + instance.setInstanceId("i-protected"); + instance.setLifecycleState("InService"); + instance.setHealthStatus("Healthy"); + service.describeAutoScalingGroups(REGION, List.of("protected-asg")).getFirst().getInstances().add(instance); + + AutoScalingQueryHandler handler = new AutoScalingQueryHandler(service); + MultivaluedHashMap params = new MultivaluedHashMap<>(); + params.add("AutoScalingGroupName", "protected-asg"); + params.add("InstanceIds.member.1", "i-protected"); + params.add("ProtectedFromScaleIn", "true"); + + Response response = handler.handle("SetInstanceProtection", params, REGION); + + assertEquals(200, response.getStatus()); + assertTrue(((String) response.getEntity()).contains(" params = new MultivaluedHashMap<>(); + params.add("InstanceId", "i-unhealthy"); + params.add("HealthStatus", "Unhealthy"); + + Response response = handler.handle("SetInstanceHealth", params, REGION); + + assertEquals(200, response.getStatus()); + assertTrue(((String) response.getEntity()).contains(" params = new MultivaluedHashMap<>(); + params.add("AutoScalingGroupName", "no-protection-flag-asg"); + params.add("InstanceIds.member.1", "i-flagless"); + // ProtectedFromScaleIn deliberately omitted — it is a required member. + + Response response = handler.handle("SetInstanceProtection", params, REGION); + + assertEquals(400, response.getStatus()); + assertTrue(((String) response.getEntity()).contains("ValidationError")); + assertEquals(false, service.describeAutoScalingInstances(REGION, List.of("i-flagless")) + .getFirst().isProtectedFromScaleIn(), + "a rejected request must not silently strip/apply protection"); + } + + @Test + void setInstanceProtectionRejectsMalformedProtectedFromScaleIn() { + AutoScalingService service = new AutoScalingService(); + service.regionResolver = new RegionResolver(REGION, "000000000000"); + service.createAutoScalingGroup(REGION, "malformed-flag-asg", null, "lt", null, "1", null, + 0, 2, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), + "EC2", 0, List.of("Default"), java.util.Map.of(), java.util.Map.of()); + AsgInstance instance = new AsgInstance(); + instance.setInstanceId("i-malformed"); + instance.setLifecycleState("InService"); + instance.setHealthStatus("Healthy"); + service.describeAutoScalingGroups(REGION, List.of("malformed-flag-asg")).getFirst() + .getInstances().add(instance); + + AutoScalingQueryHandler handler = new AutoScalingQueryHandler(service); + MultivaluedHashMap params = new MultivaluedHashMap<>(); + params.add("AutoScalingGroupName", "malformed-flag-asg"); + params.add("InstanceIds.member.1", "i-malformed"); + params.add("ProtectedFromScaleIn", "yes"); + + Response response = handler.handle("SetInstanceProtection", params, REGION); + + assertEquals(400, response.getStatus()); + assertEquals(false, service.describeAutoScalingInstances(REGION, List.of("i-malformed")) + .getFirst().isProtectedFromScaleIn(), + "a malformed boolean must not silently coerce to false and succeed"); + } + + @Test + void setInstanceHealthParsesShouldRespectGracePeriodWithoutError() { + AutoScalingService service = new AutoScalingService(); + service.regionResolver = new RegionResolver(REGION, "000000000000"); + service.createAutoScalingGroup(REGION, "grace-asg", null, "lt", null, "1", null, + 0, 2, 1, 300, List.of("us-east-1a"), List.of(), List.of(), List.of(), + "EC2", 0, List.of("Default"), java.util.Map.of(), java.util.Map.of()); + AsgInstance instance = new AsgInstance(); + instance.setInstanceId("i-grace"); + instance.setLifecycleState("InService"); + instance.setHealthStatus("Healthy"); + service.describeAutoScalingGroups(REGION, List.of("grace-asg")).getFirst().getInstances().add(instance); + + AutoScalingQueryHandler handler = new AutoScalingQueryHandler(service); + MultivaluedHashMap params = new MultivaluedHashMap<>(); + params.add("InstanceId", "i-grace"); + params.add("HealthStatus", "Unhealthy"); + params.add("ShouldRespectGracePeriod", "true"); + + Response response = handler.handle("SetInstanceHealth", params, REGION); + + assertEquals(200, response.getStatus()); + assertTrue(((String) response.getEntity()).contains(" service.putLifecycleHook(REGION, "test-asg", + "bad name!", "autoscaling:EC2_INSTANCE_LAUNCHING", null, null, null, null, null)); + assertEquals("ValidationError", ex.getErrorCode()); + } + + @Test + void deleteLifecycleHookRejectsNameOutsideModeledPattern() { + assertThrows(AwsException.class, + () -> service.deleteLifecycleHook(REGION, "test-asg", "bad name!")); + } + + @Test + void completeLifecycleActionRejectsNameOutsideModeledPattern() { + assertThrows(AwsException.class, + () -> service.completeLifecycleAction(REGION, "test-asg", "bad name!", + "i-0123456789abcdef0", "CONTINUE", "12345678-1234-1234-1234-123456789012")); + } + + @Test + void completeLifecycleActionRejectsTokenOfWrongLength() { + service.putLifecycleHook(REGION, "test-asg", "hook-1", "autoscaling:EC2_INSTANCE_LAUNCHING", + null, null, null, null, null); + + AwsException ex = assertThrows(AwsException.class, + () -> service.completeLifecycleAction(REGION, "test-asg", "hook-1", + "i-0123456789abcdef0", "CONTINUE", "not-a-uuid")); + assertEquals("ValidationError", ex.getErrorCode()); + } + + @Test + void completeLifecycleActionAllowsNullTokenWhenInstanceIdIdentifiesTheAction() { + service.putLifecycleHook(REGION, "test-asg", "hook-1", "autoscaling:EC2_INSTANCE_LAUNCHING", + null, null, null, null, null); + + assertDoesNotThrow(() -> service.completeLifecycleAction(REGION, "test-asg", "hook-1", + "i-0123456789abcdef0", "CONTINUE", null)); + } + + @Test + void deleteLifecycleHookByNameRejectsNameOutsideModeledPattern() { + AwsException ex = assertThrows(AwsException.class, + () -> service.deleteLifecycleHookByName(REGION, "bad name!")); + assertEquals("ValidationError", ex.getErrorCode()); + } + + @Test + void deleteLifecycleHookByNameIsIdempotentOnNullPhysicalId() { + assertDoesNotThrow(() -> service.deleteLifecycleHookByName(REGION, null)); + } + + @Test + void putLifecycleHookRejectsNullNameWithNotNullMessage() { + AwsException ex = assertThrows(AwsException.class, () -> service.putLifecycleHook(REGION, "test-asg", + null, "autoscaling:EC2_INSTANCE_LAUNCHING", null, null, null, null, null)); + assertTrue(ex.getMessage().contains("must not be null")); + } + + @Test + void putLifecycleHookRejectsOverlongNameWithLengthMessage() { + String tooLong = "h".repeat(256); + AwsException ex = assertThrows(AwsException.class, () -> service.putLifecycleHook(REGION, "test-asg", + tooLong, "autoscaling:EC2_INSTANCE_LAUNCHING", null, null, null, null, null)); + assertTrue(ex.getMessage().contains("length less than or equal to 255"), + "expected a length-specific message, got: " + ex.getMessage()); + } + + @Test + void putLifecycleHookRejectsBadCharsWithPatternMessage() { + AwsException ex = assertThrows(AwsException.class, () -> service.putLifecycleHook(REGION, "test-asg", + "bad name!", "autoscaling:EC2_INSTANCE_LAUNCHING", null, null, null, null, null)); + assertTrue(ex.getMessage().contains("regular expression pattern")); + } + + @Test + void setInstanceProtectionValidatesEmptyInstanceIdsBeforeGroupLookup() { + AwsException ex = assertThrows(AwsException.class, + () -> service.setInstanceProtection(REGION, "no-such-group", List.of(), true)); + assertEquals("ValidationError", ex.getErrorCode()); + assertTrue(ex.getMessage().contains("At least one instance ID is required"), + "a doubly-bad request (unknown group + empty list) must surface the missing-parameter " + + "error, not 'Group not found'; got: " + ex.getMessage()); + } + + @Test + void setInstanceProtectionReportsAllMissingInstanceIds() { + AsgInstance instance = new AsgInstance(); + instance.setInstanceId("i-real"); + instance.setLifecycleState("InService"); + instance.setHealthStatus("Healthy"); + service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst().getInstances().add(instance); + + AwsException ex = assertThrows(AwsException.class, + () -> service.setInstanceProtection(REGION, "test-asg", + List.of("i-missing-1", "i-missing-2"), true)); + assertTrue(ex.getMessage().contains("i-missing-1") && ex.getMessage().contains("i-missing-2"), + "expected both missing IDs in the message, got: " + ex.getMessage()); + } + + @Test + void setInstanceProtectionUsesSetContainmentAgainstDuplicateStoredInstanceIds() { + AsgInstance dup1 = new AsgInstance(); + dup1.setInstanceId("i-dup"); + dup1.setLifecycleState("InService"); + dup1.setHealthStatus("Healthy"); + AsgInstance dup2 = new AsgInstance(); + dup2.setInstanceId("i-dup"); + dup2.setLifecycleState("InService"); + dup2.setHealthStatus("Healthy"); + var instances = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst().getInstances(); + instances.add(dup1); + instances.add(dup2); + + assertDoesNotThrow(() -> service.setInstanceProtection(REGION, "test-asg", List.of("i-dup"), true)); + assertTrue(instances.stream().allMatch(AsgInstance::isProtectedFromScaleIn)); + } + + @Test + void setInstanceHealthAcceptsShouldRespectGracePeriodFlag() { + AsgInstance instance = new AsgInstance(); + instance.setInstanceId("i-health"); + instance.setLifecycleState("InService"); + instance.setHealthStatus("Healthy"); + service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst().getInstances().add(instance); + + assertDoesNotThrow(() -> service.setInstanceHealth(REGION, "i-health", "Unhealthy", true)); + assertEquals("Unhealthy", service.describeAutoScalingInstances(REGION, List.of("i-health")) + .getFirst().getHealthStatus()); + } + private static final class AutoScalingGroupFixture { private static void addInstance(AutoScalingService service, String region, String name, String instanceId, String lifecycleState, String launchTemplateId, String launchTemplateVersion) {