diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisioner.java index 620a1b9657..b5ac44a1b5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisioner.java @@ -21,6 +21,7 @@ import org.jboss.logging.Logger; import java.time.Instant; import java.time.format.DateTimeParseException; +import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -131,9 +132,13 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { // Ref is the name, but deletion needs both name and group. The cleanup helper's private // identity includes the group so a group move with an unchanged Ref is still tracked. + String priorIdentity = null; + if (ctx.isUpdate()) { + priorIdentity = CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore) + ? ctx.priorPhysicalId() : address(priorGroup, ctx.priorPhysicalId()); + } ProvisionContext cleanupContext = new ProvisionContext(ctx.engine(), ctx.region(), ctx.accountId(), - ctx.stackName(), ctx.isUpdate() ? address(priorGroup, ctx.priorPhysicalId()) : null, ctx.progress(), - ctx.priorProperties()); + ctx.stackName(), priorIdentity, ctx.progress(), ctx.priorProperties()); ReplacementCleanup.record(cleanupResource(resource), cleanupContext, attributesBefore); if (moveSnapshot != null) { moveSnapshot.put("destinationCreated", true); @@ -248,8 +253,11 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { @Override public void delete(StackResource resource, String region) { - deleteAddress(address(resource.getAttributes().getOrDefault(GROUP_ATTR, "default"), - resource.getPhysicalId()), region); + readCleanup(resource); + if (!CfnResourceDispatcher.isStub(resource.getPhysicalId(), resource.getAttributes())) { + deleteAddress(address(resource.getAttributes().getOrDefault(GROUP_ATTR, "default"), + resource.getPhysicalId()), region); + } UpdateCleanupResult result = ReplacementCleanup.complete(cleanupResource(resource), (type, id, cleanupRegion) -> deleteAddress(id, cleanupRegion)); if (result.applicable() && !result.complete()) { @@ -259,6 +267,7 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { } private void deleteAddress(String physicalId, String region) { + validateAddress(physicalId); int separator = physicalId.indexOf('/'); String group = physicalId.substring(0, separator); String name = physicalId.substring(separator + 1); @@ -287,16 +296,19 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { @Override public boolean hasReplacementUpdate(StackResource resource) { + readCleanup(resource); return ReplacementCleanup.hasReplacement(resource); } @Override public String updateCleanupPhysicalId(StackResource resource) { + readCleanup(resource); return ReplacementCleanup.cleanupPhysicalId(cleanupResource(resource)); } @Override public UpdateCleanupResult completeUpdate(StackResource resource) { + readCleanup(resource); if ("UPDATE_FAILED".equals(resource.getStatus()) && retainsFailedUpdateState(resource)) { throw new IllegalStateException("Schedule rollback is still pending; its original configuration " + "cannot be discarded by another resource's update cleanup"); @@ -312,6 +324,7 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { @Override public UpdateCleanupResult completeDeleteCleanup(StackResource resource) { + readCleanup(resource); UpdateCleanupResult result = ReplacementCleanup.complete(cleanupResource(resource), (type, id, region) -> deleteAddress(id, region)); return result; @@ -319,6 +332,7 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { @Override public void clearDeleteCleanup(StackResource resource) { + readCleanup(resource); ReplacementCleanup.clear(resource); if (!ReplacementCleanup.hasReplacement(resource)) { resource.getAttributes().remove(NAME_REPLACEMENT_ATTR); @@ -327,6 +341,7 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { @Override public void clearUpdate(StackResource resource) { + readCleanup(resource); resource.getAttributes().remove(SNAPSHOT_ATTR); ReplacementCleanup.clear(resource); resource.getAttributes().remove(NAME_REPLACEMENT_ATTR); @@ -334,6 +349,7 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { @Override public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { + readCleanup(previous); ObjectNode source = readCleanup(attempted); if (source != null) { String currentAddress = cleanupResource(previous).getPhysicalId(); @@ -360,10 +376,77 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { if (!node.isObject() || (node.has("displaced") && !node.path("displaced").isArray())) { throw new IllegalStateException("Invalid schedule replacement cleanup"); } - for (JsonNode entry : node.path("displaced")) { - if (!entry.isObject()) { + String legacyStubAddress = null; + String legacyStubId = null; + if (node.has("priorPhysicalId") != node.has("priorAttributes")) { + throw new IllegalStateException("Invalid schedule replacement cleanup"); + } + if (node.has("priorPhysicalId")) { + JsonNode priorId = node.path("priorPhysicalId"); + JsonNode priorAttributes = node.path("priorAttributes"); + if (!priorId.isTextual() || !priorAttributes.isObject()) { throw new IllegalStateException("Invalid schedule replacement cleanup"); } + Map priorValues = new HashMap<>(); + priorAttributes.fields().forEachRemaining(entry -> { + if (entry.getKey().startsWith("__Floci") || !entry.getValue().isTextual()) { + throw new IllegalStateException("Invalid schedule replacement cleanup"); + } + priorValues.put(entry.getKey(), entry.getValue().textValue()); + }); + String expectedStubArn = CfnResourceDispatcher.STUB_ARN_PREFIX + resource.getLogicalId(); + boolean priorStub = CfnResourceDispatcher.isStub(priorId.textValue(), priorValues) + && expectedStubArn.equals(priorValues.get("Arn")); + if (!priorStub && priorId.textValue().startsWith("default/")) { + String candidate = priorId.textValue().substring("default/".length()); + if (CfnResourceDispatcher.isStub(candidate, priorValues) + && expectedStubArn.equals(priorValues.get("Arn"))) { + legacyStubAddress = priorId.textValue(); + legacyStubId = candidate; + priorStub = true; + } + } + if (!priorStub) { + if (!isValidAddress(priorId.textValue())) { + throw new IllegalStateException("Invalid schedule replacement cleanup"); + } + String priorGroup = priorId.textValue().substring(0, priorId.textValue().indexOf('/')); + JsonNode recordedGroup = priorAttributes.path(GROUP_ATTR); + if (recordedGroup.isMissingNode() ? !"default".equals(priorGroup) + : !recordedGroup.isTextual() || !priorGroup.equals(recordedGroup.textValue())) { + throw new IllegalStateException("Invalid schedule replacement cleanup"); + } + } + } + for (JsonNode entry : node.path("displaced")) { + JsonNode id = entry.path("physicalId"); + JsonNode type = entry.path("resourceType"); + JsonNode region = entry.path("region"); + JsonNode retainable = entry.path("retainable"); + JsonNode attempts = entry.path("cleanupAttempts"); + JsonNode failure = entry.path("cleanupFailureReason"); + boolean legacyStubEntry = id.isTextual() && id.textValue().equals(legacyStubAddress); + if (!entry.isObject() || !id.isTextual() + || (!legacyStubEntry && !isValidAddress(id.textValue())) + || (!type.isMissingNode() && (!type.isTextual() || !TYPE.equals(type.textValue()))) + || (!region.isMissingNode() && !region.isNull() && !region.isTextual()) + || (!retainable.isMissingNode() && !retainable.isBoolean()) + || (!attempts.isMissingNode() && (!attempts.isIntegralNumber() + || !attempts.canConvertToInt() || attempts.intValue() < 0)) + || (!failure.isMissingNode() && !failure.isNull() && !failure.isTextual())) { + throw new IllegalStateException("Invalid schedule replacement cleanup"); + } + } + if (legacyStubAddress != null) { + ((ObjectNode) node).put("priorPhysicalId", legacyStubId); + ArrayNode remaining = MAPPER.createArrayNode(); + for (JsonNode entry : node.path("displaced")) { + if (!legacyStubAddress.equals(entry.path("physicalId").asText())) { + remaining.add(entry); + } + } + ((ObjectNode) node).set("displaced", remaining); + resource.getAttributes().put(CfnRollback.REPLACEMENT_CLEANUP_ATTR, node.toString()); } return (ObjectNode) node; } catch (JsonProcessingException e) { @@ -371,6 +454,22 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { } } + private static void validateAddress(String physicalId) { + if (!isValidAddress(physicalId)) { + throw new IllegalStateException("Invalid schedule address"); + } + } + + private static boolean isValidAddress(String physicalId) { + if (physicalId == null) { + return false; + } + int separator = physicalId.indexOf('/'); + return separator > 0 + && SchedulerService.isValidName(physicalId.substring(0, separator)) + && SchedulerService.isValidName(physicalId.substring(separator + 1)); + } + private static void retireDisplaced(StackResource resource, String physicalId) { ObjectNode cleanup = readCleanup(resource); if (cleanup == null) { @@ -392,6 +491,7 @@ public class SchedulerScheduleCfnProvisioner implements CfnResourceProvisioner { @Override public boolean rollbackUpdate(StackResource resource) { + readCleanup(resource); JsonNode snapshot = readSnapshot(resource); if (snapshot != null && snapshot.path("destinationCreated").asBoolean(false)) { // Disable the move's destination before restoring an enabled original, even if deleting diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java index 055dfd2272..cdcc0a9c9b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/SchedulerService.java @@ -325,11 +325,15 @@ public class SchedulerService { // ──────────────────────────── Helpers ──────────────────────────── + public static boolean isValidName(String name) { + return name != null && NAME_PATTERN.matcher(name).matches(); + } + private void validateName(String name) { if (name == null || name.isBlank()) { throw new AwsException("ValidationException", "Name is required.", 400); } - if (!NAME_PATTERN.matcher(name).matches()) { + if (!isValidName(name)) { throw new AwsException("ValidationException", "Name must match pattern [0-9a-zA-Z-_.]{1,64}: " + name, 400); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisionerTest.java index 4e89e3da62..d94f7b296d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SchedulerScheduleCfnProvisionerTest.java @@ -342,7 +342,10 @@ class SchedulerScheduleCfnProvisionerTest { } @ParameterizedTest - @ValueSource(strings = {"1", "true", "null", "\"invalid\"", "[]"}) + @ValueSource(strings = {"1", "true", "null", "\"invalid\"", "[]", + "{\"physicalId\":\"/victim\"}", "{\"physicalId\":\"default/\"}", + "{\"physicalId\":\"default/victim/extra\"}", "{\"physicalId\":123}", + "{\"physicalId\":\"default/victim\",\"cleanupAttempts\":\"zero\"}"}) void malformedCleanupEntryRejectsCreateBeforeAnyServiceCall(String entry) throws Exception { StackResource resource = resource(); appendMalformedCleanupEntry(resource, entry); @@ -351,7 +354,10 @@ class SchedulerScheduleCfnProvisionerTest { } @ParameterizedTest - @ValueSource(strings = {"1", "true", "null", "\"invalid\"", "[]"}) + @ValueSource(strings = {"1", "true", "null", "\"invalid\"", "[]", + "{\"physicalId\":\"/victim\"}", "{\"physicalId\":\"default/\"}", + "{\"physicalId\":\"default/victim/extra\"}", "{\"physicalId\":123}", + "{\"physicalId\":\"default/victim\",\"cleanupAttempts\":\"zero\"}"}) void malformedCleanupEntryRejectsReplacementBeforeAnyServiceCall(String entry) throws Exception { StackResource resource = resource(); provisioner.provision(resource, properties("current", "default"), context(null)); @@ -361,7 +367,10 @@ class SchedulerScheduleCfnProvisionerTest { } @ParameterizedTest - @ValueSource(strings = {"1", "true", "null", "\"invalid\"", "[]"}) + @ValueSource(strings = {"1", "true", "null", "\"invalid\"", "[]", + "{\"physicalId\":\"/victim\"}", "{\"physicalId\":\"default/\"}", + "{\"physicalId\":\"default/victim/extra\"}", "{\"physicalId\":123}", + "{\"physicalId\":\"default/victim\",\"cleanupAttempts\":\"zero\"}"}) void malformedCleanupEntryRejectsInPlaceUpdateBeforeAnyServiceCall(String entry) throws Exception { StackResource resource = resource(); provisioner.provision(resource, properties("current", "default"), context(null)); @@ -372,7 +381,10 @@ class SchedulerScheduleCfnProvisionerTest { } @ParameterizedTest - @ValueSource(strings = {"1", "true", "null", "\"invalid\"", "[]"}) + @ValueSource(strings = {"1", "true", "null", "\"invalid\"", "[]", + "{\"physicalId\":\"/victim\"}", "{\"physicalId\":\"default/\"}", + "{\"physicalId\":\"default/victim/extra\"}", "{\"physicalId\":123}", + "{\"physicalId\":\"default/victim\",\"cleanupAttempts\":\"zero\"}"}) void malformedCleanupEntryPreservesPendingRollbackBeforeAnotherUpdate(String entry) throws Exception { StackResource resource = resource(); provisioner.provision(resource, properties("current", "default"), context(null)); @@ -387,7 +399,10 @@ class SchedulerScheduleCfnProvisionerTest { } @ParameterizedTest - @ValueSource(strings = {"1", "true", "null", "\"invalid\"", "[]"}) + @ValueSource(strings = {"1", "true", "null", "\"invalid\"", "[]", + "{\"physicalId\":\"/victim\"}", "{\"physicalId\":\"default/\"}", + "{\"physicalId\":\"default/victim/extra\"}", "{\"physicalId\":123}", + "{\"physicalId\":\"default/victim\",\"cleanupAttempts\":\"zero\"}"}) void malformedCleanupEntryRejectsMergeWithoutChangingExistingDebt(String entry) throws Exception { StackResource previous = resource(); provisioner.provision(previous, properties("current", "default"), context(null)); @@ -431,6 +446,166 @@ class SchedulerScheduleCfnProvisionerTest { () -> verifyNoInteractions(scheduler)); } + @Test + void malformedCleanupAddressCannotDeleteAnotherSchedule() throws Exception { + StackResource resource = resource(); + provisioner.provision(resource, properties("current", "default"), context(null)); + appendMalformedCleanupEntry(resource, "{\"physicalId\":\"/victim\"}"); + Map before = Map.copyOf(resource.getAttributes()); + clearInvocations(scheduler); + + assertAll( + () -> assertThrows(IllegalStateException.class, + () -> provisioner.completeDeleteCleanup(resource)), + () -> assertThrows(IllegalStateException.class, + () -> provisioner.delete(resource, REGION)), + () -> assertThrows(IllegalStateException.class, + () -> provisioner.completeUpdate(resource)), + () -> assertEquals(before, resource.getAttributes()), + () -> verifyNoInteractions(scheduler)); + } + + @ParameterizedTest + @ValueSource(strings = { + "{\"priorPhysicalId\":\"/victim\",\"priorAttributes\":{}}", + "{\"priorPhysicalId\":\"a/victim\",\"priorAttributes\":{\"FlociSchedulerGroupName\":\"default\"}}", + "{\"priorPhysicalId\":\"a/victim\",\"priorAttributes\":{}}", + "{\"priorPhysicalId\":\"default/victim\",\"priorAttributes\":{\"FlociSchedulerGroupName\":\"a\"}}", + "{\"priorPhysicalId\":\"default/victim\",\"priorAttributes\":{\"FlociSchedulerGroupName\":42}}", + "{\"priorPhysicalId\":\"default/victim\",\"priorAttributes\":[]}", + "{\"priorPhysicalId\":\"default/victim\",\"priorAttributes\":{\"Arn\":42}}", + "{\"priorPhysicalId\":\"default/victim\",\"priorAttributes\":{\"__FlociReplacementCleanup\":\"x\"}}", + "{\"priorPhysicalId\":\"default/victim\"}", + "{\"priorAttributes\":{}}", + "{\"priorPhysicalId\":42,\"priorAttributes\":{}}"}) + void malformedPriorCleanupRejectsEveryMutationEntryPoint(String cleanup) throws Exception { + StackResource resource = resource(); + provisioner.provision(resource, properties("current", "default"), context(null)); + resource.getAttributes().put("__FlociReplacementCleanup", cleanup); + Map before = Map.copyOf(resource.getAttributes()); + String physicalIdBefore = resource.getPhysicalId(); + clearInvocations(scheduler); + + assertAll( + () -> assertThrows(IllegalStateException.class, () -> provisioner.provision(resource, + properties("new", "default"), context("current"))), + () -> assertThrows(IllegalStateException.class, () -> provisioner.rollbackUpdate(resource)), + () -> assertThrows(IllegalStateException.class, () -> provisioner.delete(resource, REGION)), + () -> assertThrows(IllegalStateException.class, () -> provisioner.completeUpdate(resource)), + () -> assertThrows(IllegalStateException.class, () -> provisioner.completeDeleteCleanup(resource)), + () -> assertEquals(physicalIdBefore, resource.getPhysicalId()), + () -> assertEquals(before, resource.getAttributes()), + () -> verifyNoInteractions(scheduler)); + } + + @Test + void priorDefaultGroupCanBeOmittedFromStoredCleanup() throws Exception { + StackResource resource = resource(); + provisioner.provision(resource, properties("old", "default"), context(null)); + provisioner.provision(resource, properties("new", "default"), context("old")); + ObjectNode cleanup = (ObjectNode) mapper.readTree(resource.getAttributes().get("__FlociReplacementCleanup")); + ((ObjectNode) cleanup.path("priorAttributes")).remove("FlociSchedulerGroupName"); + resource.getAttributes().put("__FlociReplacementCleanup", cleanup.toString()); + + assertTrue(provisioner.rollbackUpdate(resource)); + + assertEquals("old", resource.getPhysicalId()); + verify(scheduler).deleteSchedule("new", "default", REGION); + } + + @ParameterizedTest + @ValueSource(ints = {5, 56}) + void stubMigrationDoesNotScheduleTheStubForDeletion(int logicalIdLength) throws Exception { + StackResource resource = stubResource(logicalIdLength); + String stubId = resource.getPhysicalId(); + + provisioner.provision(resource, properties("new", "default"), context(stubId)); + + assertFalse(provisioner.hasReplacementUpdate(resource)); + assertNull(provisioner.updateCleanupPhysicalId(resource)); + assertTrue(provisioner.completeUpdate(resource).complete()); + verify(scheduler, never()).deleteSchedule(any(), any(), eq(REGION)); + } + + @ParameterizedTest + @ValueSource(ints = {5, 56}) + void stubMigrationRollbackRestoresTheStubWithoutDeletingIt(int logicalIdLength) throws Exception { + StackResource resource = stubResource(logicalIdLength); + String stubId = resource.getPhysicalId(); + String stubArn = resource.getAttributes().get("Arn"); + provisioner.provision(resource, properties("new", "default"), context(stubId)); + + assertTrue(provisioner.rollbackUpdate(resource)); + assertEquals(stubId, resource.getPhysicalId()); + assertEquals(stubArn, resource.getAttributes().get("Arn")); + verify(scheduler).deleteSchedule("new", "default", REGION); + + clearInvocations(scheduler); + provisioner.delete(resource, REGION); + verifyNoInteractions(scheduler); + } + + @ParameterizedTest + @ValueSource(ints = {5, 56}) + void persistedStubMigrationDoesNotDeleteAnUnownedSchedule(int logicalIdLength) throws Exception { + StackResource resource = stubResource(logicalIdLength); + String stubId = resource.getPhysicalId(); + provisioner.provision(resource, properties("new", "default"), context(stubId)); + restoreLegacyStubCleanup(resource, stubId); + clearInvocations(scheduler); + + assertFalse(provisioner.hasReplacementUpdate(resource)); + assertTrue(provisioner.completeUpdate(resource).complete()); + verifyNoInteractions(scheduler); + } + + @ParameterizedTest + @ValueSource(ints = {5, 56}) + void persistedStubMigrationCanRollbackWithoutDeletingTheStub(int logicalIdLength) throws Exception { + StackResource resource = stubResource(logicalIdLength); + String stubId = resource.getPhysicalId(); + provisioner.provision(resource, properties("new", "default"), context(stubId)); + restoreLegacyStubCleanup(resource, stubId); + clearInvocations(scheduler); + + assertTrue(provisioner.rollbackUpdate(resource)); + assertEquals(stubId, resource.getPhysicalId()); + verify(scheduler).deleteSchedule("new", "default", REGION); + clearInvocations(scheduler); + provisioner.delete(resource, REGION); + verifyNoInteractions(scheduler); + } + + @Test + void malformedPersistedStubCleanupIsNotPartiallyRewritten() throws Exception { + StackResource resource = stubResource(5); + String stubId = resource.getPhysicalId(); + provisioner.provision(resource, properties("new", "default"), context(stubId)); + restoreLegacyStubCleanup(resource, stubId); + ObjectNode cleanup = (ObjectNode) mapper.readTree(resource.getAttributes().get("__FlociReplacementCleanup")); + cleanup.withArray("displaced").addObject().put("physicalId", "/victim"); + resource.getAttributes().put("__FlociReplacementCleanup", cleanup.toString()); + Map before = Map.copyOf(resource.getAttributes()); + clearInvocations(scheduler); + + assertThrows(IllegalStateException.class, () -> provisioner.completeUpdate(resource)); + assertEquals(before, resource.getAttributes()); + verifyNoInteractions(scheduler); + } + + private void restoreLegacyStubCleanup(StackResource resource, String stubId) throws Exception { + ObjectNode cleanup = (ObjectNode) mapper.readTree(resource.getAttributes().get("__FlociReplacementCleanup")); + String oldAddress = "default/" + stubId; + cleanup.put("priorPhysicalId", oldAddress); + cleanup.withArray("displaced").addObject() + .put("physicalId", oldAddress) + .put("resourceType", "AWS::Scheduler::Schedule") + .put("region", REGION) + .put("retainable", true) + .put("cleanupAttempts", 0); + resource.getAttributes().put("__FlociReplacementCleanup", cleanup.toString()); + } + @Test void groupMoveKeepsRefAndDoesNotHonorReplacementRetain() throws Exception { StackResource resource = resource(); @@ -1028,6 +1203,15 @@ class SchedulerScheduleCfnProvisionerTest { return resource; } + private static StackResource stubResource(int logicalIdLength) { + StackResource resource = resource(); + String logicalId = "S".repeat(logicalIdLength); + resource.setLogicalId(logicalId); + resource.setPhysicalId(logicalId + "-01234567"); + resource.getAttributes().put("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + logicalId); + return resource; + } + private static ScheduleRequest request(String name, String group, String expression) { ScheduleRequest request = new ScheduleRequest(); request.setName(name);