From d280f451fa86b8a4d95a42e88e5262434ccc441f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ronald=20Li=20=F0=9F=9B=A0=EF=B8=8F?= <137369375+RonCodes88@users.noreply.github.com> Date: Wed, 4 Nov 2026 18:37:06 -0800 Subject: [PATCH] fix(cloudformation): roll back an AWS::EC2::SecurityGroup updated in place (#7562) --- docs/services/cloudformation.md | 2 +- .../Ec2SecurityGroupCfnProvisioner.java | 250 ++++++++++++++++-- .../cloudformation/provisioners/Ec2Tags.java | 7 +- ...ityGroupUpdateRollbackIntegrationTest.java | 133 ++++++++++ .../Ec2SecurityGroupCfnProvisionerTest.java | 196 ++++++++++++++ tools/docs/cfn_resource_types.yaml | 2 +- 6 files changed, 558 insertions(+), 32 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecurityGroupUpdateRollbackIntegrationTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 87dd5c3c09..131527ed31 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -206,7 +206,7 @@ cross-resource references. | ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored), `ServerlessCache` (GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form) | | Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model), `EventSubscription` | | Redshift Serverless | `Namespace` (Managed admin credentials use Secrets Manager; GetAtt uses the dotted Namespace.* form), `Workgroup` (starts a real container; one workgroup per namespace; capacity, VPC and price-performance settings are stored only; snapshot restore properties are ignored; GetAtt uses the dotted Workgroup.* form) | -| EC2 | `VPC` (`Tags` update in place, keeping tags added outside the stack; deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported; `Tags` update in place, keeping tags added outside the stack), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway` (zonal; `AvailabilityMode` regional fails; a change to the `Secondary*` address properties updates the gateway in place), `EIP`, `Instance` (`Tags` update in place, keeping tags added outside the stack), `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` (`Tags` are applied and updated in place, keeping tags added outside the stack; any other change fails, since it needs a replacement), `KeyPair` (a created key's private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key), `PrefixList` (updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails) | +| EC2 | `VPC` (`Tags` update in place, keeping tags added outside the stack; deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported; `Tags` update in place, keeping tags added outside the stack; a failed stack update puts the rules and tags of a group it changed in place back), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway` (zonal; `AvailabilityMode` regional fails; a change to the `Secondary*` address properties updates the gateway in place), `EIP`, `Instance` (`Tags` update in place, keeping tags added outside the stack), `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` (`Tags` are applied and updated in place, keeping tags added outside the stack; any other change fails, since it needs a replacement), `KeyPair` (a created key's private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key), `PrefixList` (updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails) | | Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` | | Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` | | Application Auto Scaling | `ScalableTarget` (`ScheduledActions` are accepted and not run; Floci has no scheduled scaling), `ScalingPolicy` | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java index 2d806afa2e..9205d1ab4a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java @@ -1,6 +1,10 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; @@ -35,6 +39,11 @@ import java.util.stream.Collectors; *

The inline {@code SecurityGroupIngress}/{@code SecurityGroupEgress} properties share their * rule-object mapping with the standalone rule resources, through * {@link Ec2SecurityGroupRuleCfnProvisioner#toIpPermission}. + * + *

An update that keeps the group records what it is about to change (the rules it authorizes + * and revokes, the tag keys it touches, and the ownership records it replaces) in + * {@link #UPDATE_SNAPSHOT_ATTR}, so a stack update that fails on a later resource puts the group + * back. A replacement is not rolled back here, so the stack reports it as not rolled back. */ @ApplicationScoped public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner { @@ -49,6 +58,9 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner { static final String EGRESS_RULES_ATTR = "__FlociSgEgressRules"; /** The tag keys the last deployment wrote, as {@link Ec2Tags#recordKeys} records them. */ static final String TAG_KEYS_ATTR = "__FlociSgTagKeys"; + /** What an update that kept the group changed on it, for {@link #rollbackUpdate} to undo. */ + static final String UPDATE_SNAPSHOT_ATTR = "__FlociSgUpdateSnapshot"; + private static final ObjectMapper MAPPER = new ObjectMapper(); private final Ec2Service ec2Service; @@ -104,21 +116,62 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner { // that the template no longer declares. Ownership is scoped by the keys recorded in the // internal attributes, so a rule owned by a standalone resource is never revoked here. UnaryOperator peerGroupId = peerGroupIdResolver(region, sg.getVpcId()); - reconcileRules(props, "SecurityGroupIngress", sg.getIpPermissions(), engine, peerGroupId, r, - INGRESS_RULES_ATTR, - perms -> ec2Service.authorizeSecurityGroupIngress(region, sg.getGroupId(), perms), - perms -> ec2Service.revokeSecurityGroupIngress(region, sg.getGroupId(), perms)); - reconcileRules(props, "SecurityGroupEgress", sg.getIpPermissionsEgress(), engine, peerGroupId, r, - EGRESS_RULES_ATTR, - perms -> ec2Service.authorizeSecurityGroupEgress(region, sg.getGroupId(), perms), - perms -> ec2Service.revokeSecurityGroupEgress(region, sg.getGroupId(), perms)); + RulePlan ingress = planRules(props, "SecurityGroupIngress", sg.getIpPermissions(), engine, peerGroupId, + r.getAttributes().get(INGRESS_RULES_ATTR)); + RulePlan egress = planRules(props, "SecurityGroupEgress", sg.getIpPermissionsEgress(), engine, peerGroupId, + r.getAttributes().get(EGRESS_RULES_ATTR)); // AWS updates Tags in place and keeps a tag added outside the stack, so a reused group has // only the keys the last deployment wrote removed; a new group carries no tags yet. - Set ownedTags = reconciled != null ? Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx) : Set.of(); - Ec2Tags.reconcileOwned(ec2Service, region, sg.getGroupId(), ownedTags, desiredTags); + boolean reused = reconciled != null; + Set ownedTags = reused ? Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx) : Set.of(); + String groupId = sg.getGroupId(); + CfnRollback.guarded(r, ctx, !reused, () -> delete(SECURITY_GROUP, groupId, region), () -> undoInPlace(r), () -> { + if (reused && ctx.isUpdate()) { + snapshotInPlace(r, region, groupId, ingress, egress, ownedTags, desiredTags); + } + for (IpPermission perm : ingress.authorize()) { + ec2Service.authorizeSecurityGroupIngress(region, groupId, List.of(perm)); + } + for (IpPermission perm : ingress.revoke()) { + ec2Service.revokeSecurityGroupIngress(region, groupId, List.of(perm)); + } + for (IpPermission perm : egress.authorize()) { + ec2Service.authorizeSecurityGroupEgress(region, groupId, List.of(perm)); + } + for (IpPermission perm : egress.revoke()) { + ec2Service.revokeSecurityGroupEgress(region, groupId, List.of(perm)); + } + Ec2Tags.reconcileOwned(ec2Service, region, groupId, ownedTags, desiredTags); + }); + putRuleKeys(r, INGRESS_RULES_ATTR, ingress.declaredKeys()); + putRuleKeys(r, EGRESS_RULES_ATTR, egress.declaredKeys()); Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, desiredTags); } + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + resource.getAttributes().remove(UPDATE_SNAPSHOT_ATTR); + return UpdateCleanupResult.notApplicable(); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(UPDATE_SNAPSHOT_ATTR); + } + + /** + * Undoes an update that kept the group, from the snapshot it recorded. Without one the update + * replaced the group, which is not rolled back here. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (resource.getAttributes().get(UPDATE_SNAPSHOT_ATTR) == null) { + return false; + } + undoInPlace(resource); + return true; + } + @Override public void delete(String resourceType, String physicalId, String region) { // Tolerate a group already deleted out of band, so DeleteStack does not fail on it. @@ -132,18 +185,20 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner { return vpcId != null && !vpcId.isEmpty() ? vpcId : String.valueOf(ec2Service.resolveDefaultVpcId(region)); } + /** What one direction's reconcile authorizes and revokes, and the rule keys it then records. */ + private record RulePlan(List authorize, List revoke, Set declaredKeys) { + } + /** - * Reconciles one direction's inline rules: authorizes each declared rule the group does not - * already carry (one call per rule so a reject cannot take its siblings down), and revokes a - * rule this resource authorized on a prior run that the template no longer declares. The keys - * this resource declared are recorded in {@code attrKey}, so only its own rules are revoked; - * a rule a standalone SecurityGroupIngress/Egress resource added is never in that set. + * Plans one direction's inline rules: authorizes each declared rule whose source the group does + * not already carry (one call per rule so a reject cannot take its siblings down), and revokes a rule this + * resource authorized on a prior run that the template no longer declares. The keys this + * resource declared were recorded in {@code storedKeys}, so only its own rules are revoked; a + * rule a standalone SecurityGroupIngress/Egress resource added is never in that set. */ - private void reconcileRules(JsonNode props, String property, List existing, - CloudFormationTemplateEngine engine, UnaryOperator peerGroupId, - StackResource r, String attrKey, - Consumer> authorize, - Consumer> revoke) { + private static RulePlan planRules(JsonNode props, String property, List existing, + CloudFormationTemplateEngine engine, UnaryOperator peerGroupId, + String storedKeys) { List declared = new ArrayList<>(); if (props != null && props.has(property)) { for (JsonNode rule : props.get(property)) { @@ -154,25 +209,164 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner { for (IpPermission perm : declared) { declaredKeys.add(permissionKey(perm, peerGroupId)); } - Set present = existing.stream() - .map(p -> permissionKey(p, peerGroupId)) - .collect(Collectors.toSet()); + // Compared source by source: a declared rule names one source, while a stored permission can + // hold several, and a revoke removes its source from every permission that carries it. A + // source the group already holds is left alone, so neither a later revoke nor a rollback + // of this update can take it from the permission that held it first. + Set present = sourceKeys(existing, peerGroupId); + List authorize = new ArrayList<>(); for (IpPermission perm : declared) { if (present.add(permissionKey(perm, peerGroupId))) { - authorize.accept(List.of(perm)); + authorize.add(perm); } } - Set priorKeys = parseRuleKeys(r.getAttributes().get(attrKey)); + Set priorKeys = parseRuleKeys(storedKeys); + List revoke = new ArrayList<>(); for (IpPermission existingPermission : existing) { String key = permissionKey(existingPermission, peerGroupId); if (priorKeys.contains(key) && !declaredKeys.contains(key)) { - revoke.accept(List.of(existingPermission)); + revoke.add(existingPermission); } } - if (declaredKeys.isEmpty()) { + return new RulePlan(authorize, revoke, declaredKeys); + } + + private static void putRuleKeys(StackResource r, String attrKey, Set keys) { + if (keys.isEmpty()) { r.getAttributes().remove(attrKey); } else { - r.getAttributes().put(attrKey, String.join("\n", declaredKeys)); + r.getAttributes().put(attrKey, String.join("\n", keys)); + } + } + + /** + * Records what an update is about to change on a reused group before it changes it: each + * direction's rules to authorize and revoke with the rule-key record it replaces, and the tag + * keys it touches with their values and the tag-key record. Written on every update that keeps + * the group, so a rollback can tell an in-place update from a replacement. + */ + private void snapshotInPlace(StackResource r, String region, String groupId, RulePlan ingress, RulePlan egress, + Set ownedTags, Map desiredTags) { + ObjectNode prior = MAPPER.createObjectNode(); + prior.put("region", region); + prior.put("groupId", groupId); + snapshotRules(prior.putObject("ingress"), ingress, r.getAttributes().get(INGRESS_RULES_ATTR)); + snapshotRules(prior.putObject("egress"), egress, r.getAttributes().get(EGRESS_RULES_ATTR)); + Ec2Tags.snapshotOwned(prior, ownedTags, desiredTags, Ec2Tags.current(ec2Service, region, groupId), + r.getAttributes().get(TAG_KEYS_ATTR)); + r.getAttributes().put(UPDATE_SNAPSHOT_ATTR, prior.toString()); + } + + private static void snapshotRules(ObjectNode direction, RulePlan plan, String storedKeys) { + direction.put("ruleKeys", storedKeys); + ArrayNode authorized = direction.putArray("authorized"); + plan.authorize().forEach(perm -> authorized.add(MAPPER.valueToTree(perm))); + ArrayNode revoked = direction.putArray("revoked"); + plan.revoke().forEach(perm -> revoked.add(MAPPER.valueToTree(perm))); + } + + /** + * Puts a reused group back from its snapshot: revokes the rules the update authorized, + * authorizes again the ones it revoked that the group no longer carries (EC2 here does not + * reject a duplicate), and restores the tag keys it touched and every ownership record. The + * snapshot is removed only after the restore succeeds, so a failed one keeps it for a + * ContinueUpdateRollback retry, which repeats it safely. + */ + private void undoInPlace(StackResource r) { + JsonNode prior = CfnRollback.updateSnapshot(r, UPDATE_SNAPSHOT_ATTR); + if (prior == null) { + return; + } + String region = prior.path("region").asText(); + String groupId = prior.path("groupId").asText(); + SecurityGroup current = ec2Service.describeSecurityGroups(region, List.of(groupId), List.of(), Map.of()) + .getFirst(); + UnaryOperator peerGroupId = peerGroupIdResolver(region, current.getVpcId()); + JsonNode ingress = prior.path("ingress"); + for (IpPermission perm : permissions(ingress.path("authorized"))) { + ec2Service.revokeSecurityGroupIngress(region, groupId, List.of(perm)); + } + for (IpPermission perm : missing(permissions(ingress.path("revoked")), current.getIpPermissions(), peerGroupId)) { + ec2Service.authorizeSecurityGroupIngress(region, groupId, List.of(perm)); + } + JsonNode egress = prior.path("egress"); + for (IpPermission perm : permissions(egress.path("authorized"))) { + ec2Service.revokeSecurityGroupEgress(region, groupId, List.of(perm)); + } + for (IpPermission perm : missing(permissions(egress.path("revoked")), current.getIpPermissionsEgress(), + peerGroupId)) { + ec2Service.authorizeSecurityGroupEgress(region, groupId, List.of(perm)); + } + restoreRuleKeys(r, INGRESS_RULES_ATTR, ingress); + restoreRuleKeys(r, EGRESS_RULES_ATTR, egress); + Ec2Tags.restoreOwned(ec2Service, region, groupId, r, TAG_KEYS_ATTR, prior); + r.getAttributes().remove(UPDATE_SNAPSHOT_ATTR); + } + + private static List permissions(JsonNode saved) { + List permissions = new ArrayList<>(); + try { + for (JsonNode perm : saved) { + permissions.add(MAPPER.treeToValue(perm, IpPermission.class)); + } + } catch (JsonProcessingException e) { + throw new IllegalStateException("Unreadable security group rule in the update snapshot", e); + } + return permissions; + } + + /** + * The saved rules with a source the group does not carry now, so restoring them never adds a + * duplicate source. + */ + private static List missing(List saved, List current, + UnaryOperator peerGroupId) { + Set present = sourceKeys(current, peerGroupId); + return saved.stream() + .filter(perm -> !present.containsAll(sourceKeys(List.of(perm), peerGroupId))) + .toList(); + } + + /** + * One {@link #permissionKey} per source the permissions hold, each as if its source stood alone + * in its own permission, the shape an inline rule has. A permission with no source keeps its own + * key. + */ + private static Set sourceKeys(List permissions, UnaryOperator peerGroupId) { + Set keys = new LinkedHashSet<>(); + for (IpPermission permission : permissions) { + List sources = new ArrayList<>(); + permission.getIpRanges().forEach(range -> sources.add(withSource(permission, single -> single + .setIpRanges(List.of(range))))); + permission.getIpv6Ranges().forEach(range -> sources.add(withSource(permission, single -> single + .setIpv6Ranges(List.of(range))))); + permission.getUserIdGroupPairs().forEach(pair -> sources.add(withSource(permission, single -> single + .setUserIdGroupPairs(List.of(pair))))); + permission.getPrefixListIds().forEach(list -> sources.add(withSource(permission, single -> single + .setPrefixListIds(List.of(list))))); + if (sources.isEmpty()) { + sources.add(permission); + } + sources.forEach(single -> keys.add(permissionKey(single, peerGroupId))); + } + return keys; + } + + private static IpPermission withSource(IpPermission permission, Consumer source) { + IpPermission single = new IpPermission(); + single.setIpProtocol(permission.getIpProtocol()); + single.setFromPort(permission.getFromPort()); + single.setToPort(permission.getToPort()); + source.accept(single); + return single; + } + + private static void restoreRuleKeys(StackResource r, String attrKey, JsonNode direction) { + String keys = CfnRollback.snapshotText(direction, "ruleKeys"); + if (keys == null) { + r.getAttributes().remove(attrKey); + } else { + r.getAttributes().put(attrKey, keys); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java index 029c1bfb35..aaf6a2f1c0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java @@ -14,6 +14,7 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; /** @@ -124,7 +125,7 @@ final class Ec2Tags { private static boolean changesOwnedTags(Set owned, Map desired, Map current) { return touched(owned, desired).stream().anyMatch(key -> desired.containsKey(key) - ? !desired.get(key).equals(current.get(key)) + ? !current.containsKey(key) || !Objects.equals(desired.get(key), current.get(key)) : current.containsKey(key)); } @@ -151,7 +152,9 @@ final class Ec2Tags { Set touched = new LinkedHashSet<>(); snapshot.path("touched").forEach(key -> touched.add(key.asText())); Map priorTags = new LinkedHashMap<>(); - snapshot.path("tags").properties().forEach(f -> priorTags.put(f.getKey(), f.getValue().asText())); + // EC2 accepts a tag with no value; asText() would turn the saved null into the text "null". + snapshot.path("tags").properties().forEach(f -> priorTags.put(f.getKey(), + f.getValue().isNull() ? null : f.getValue().asText())); reconcileOwned(ec2Service, region, resourceId, touched, priorTags); restoreRecord(r, recordAttr, snapshot); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecurityGroupUpdateRollbackIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecurityGroupUpdateRollbackIntegrationTest.java new file mode 100644 index 0000000000..14500fb0b7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecurityGroupUpdateRollbackIntegrationTest.java @@ -0,0 +1,133 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.github.hectorvent.floci.testing.CfnStackWaits; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.SecurityGroup; +import software.amazon.awssdk.services.ec2.model.Tag; + +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A stack update that changes an {@code AWS::EC2::SecurityGroup} in place and then fails on a later + * resource rolls the group back through the AWS SDK: its inline rules and the tag keys the stack + * owns are the first deployment's again, a tag added through EC2 is kept, and a following update + * still reconciles from that first deployment. + */ +@QuarkusTest +class CloudFormationSecurityGroupUpdateRollbackIntegrationTest { + + private static final String ORIGINAL = """ + "SecurityGroupIngress": [ + {"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80, "CidrIp": "0.0.0.0/0"}, + {"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443, "CidrIp": "0.0.0.0/0"} + ], + "Tags": [{"Key": "team", "Value": "core"}]"""; + + private static final String CHANGED = """ + "SecurityGroupIngress": [ + {"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80, "CidrIp": "0.0.0.0/0"}, + {"IpProtocol": "tcp", "FromPort": 8080, "ToPort": 8080, "CidrIp": "0.0.0.0/0"} + ], + "Tags": [{"Key": "owner", "Value": "platform"}]"""; + + private final String stackName = "cfn-sg-rollback-" + UUID.randomUUID(); + private CloudFormationClient cfn; + private Ec2Client ec2; + private boolean stackCreated; + + @BeforeEach + void clients() { + cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1); + ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1); + } + + @AfterEach + void deleteStack() { + try { + if (stackCreated) { + cfn.deleteStack(request -> request.stackName(stackName)); + } + } finally { + ec2.close(); + cfn.close(); + } + } + + @Test + void aFailedUpdatePutsTheRulesAndTheOwnedTagsBack() { + cfn.createStack(request -> request.stackName(stackName).templateBody(template(ORIGINAL, ""))); + stackCreated = true; + String groupId = CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE").outputs().getFirst() + .outputValue(); + ec2.createTags(request -> request.resources(groupId) + .tags(Tag.builder().key("external").value("preserve").build())); + + cfn.updateStack(request -> request.stackName(stackName).templateBody(template(CHANGED, failingResource()))); + CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_ROLLBACK_COMPLETE"); + + assertEquals(Set.of(80, 443), ingressPorts(groupId)); + assertEquals(Map.of("team", "core", "external", "preserve"), tags(groupId)); + + // The rollback put the first deployment's records back too, so dropping the rules and tags + // now removes exactly what that deployment wrote. + cfn.updateStack(request -> request.stackName(stackName).templateBody(template("\"Tags\": []", ""))); + CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE"); + assertEquals(Set.of(), ingressPorts(groupId)); + assertEquals(Map.of("external", "preserve"), tags(groupId)); + } + + private String template(String groupProperties, String moreResources) { + return """ + { + "Resources": { + "Group": {"Type": "AWS::EC2::SecurityGroup", "Properties": { + "GroupDescription": "rollback", + %s + }}%s + }, + "Outputs": {"GroupId": {"Value": {"Ref": "Group"}}} + } + """.formatted(groupProperties, moreResources); + } + + /** A resource that fails after the group, so the update rolls back. */ + private String failingResource() { + return """ + , + "BadSecret": { + "Type": "AWS::SecretsManager::Secret", + "DependsOn": "Group", + "Properties": { + "Name": "%s", + "SecretString": "explicit", + "GenerateSecretString": {"PasswordLength": 32} + } + }""".formatted(stackName); + } + + private Set ingressPorts(String groupId) { + SecurityGroup group = ec2.describeSecurityGroups(request -> request.groupIds(groupId)).securityGroups() + .getFirst(); + return group.ipPermissions().stream().map(permission -> permission.fromPort()).collect(Collectors.toSet()); + } + + private Map tags(String groupId) { + Map tags = new TreeMap<>(); + ec2.describeTags(request -> request.filters(filter -> filter.name("resource-id").values(groupId))) + .tags().forEach(tag -> tags.put(tag.key(), tag.value())); + return tags; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisionerTest.java index 059a0747cb..64a40cb01b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisionerTest.java @@ -12,24 +12,29 @@ import io.github.hectorvent.floci.services.ec2.model.SecurityGroup; import io.github.hectorvent.floci.services.ec2.model.Tag; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.mockito.ArgumentMatcher; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -336,6 +341,197 @@ class Ec2SecurityGroupCfnProvisionerTest { assertEquals(443, revoked.getValue().get(0).getFromPort()); } + private static final String WEB_80_443 = """ + {"GroupName": "web", "GroupDescription": "web tier", "VpcId": "vpc-1", + "SecurityGroupIngress": [ + {"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80, "CidrIp": "0.0.0.0/0"}, + {"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443, "CidrIp": "0.0.0.0/0"} + ], + "Tags": [{"Key": "team", "Value": "core"}]} + """; + + private static final String WEB_80_8080 = """ + {"GroupName": "web", "GroupDescription": "web tier", "VpcId": "vpc-1", + "SecurityGroupIngress": [ + {"IpProtocol": "tcp", "FromPort": 80, "ToPort": 80, "CidrIp": "0.0.0.0/0"}, + {"IpProtocol": "tcp", "FromPort": 8080, "ToPort": 8080, "CidrIp": "0.0.0.0/0"} + ], + "Tags": [{"Key": "owner", "Value": "platform"}]} + """; + + /** A group the first deployment created from {@link #WEB_80_443}, its rule and tag records in place. */ + private StackResource createdWeb() throws Exception { + when(ec2.createSecurityGroup("us-east-1", "web", "web tier", "vpc-1")) + .thenReturn(group("sg-1", "web", "web tier", "vpc-1")); + StackResource r = resource("WebSg"); + provisioner.provision(r, props(WEB_80_443), ctx(null)); + r.setPhysicalId("sg-1"); + return r; + } + + /** The group as the first deployment left it, with a port 22 rule a standalone resource added. */ + private static SecurityGroup webBeforeUpdate() { + SecurityGroup group = group("sg-1", "web", "web tier", "vpc-1"); + group.getIpPermissions().add(tcp(80, "0.0.0.0/0")); + group.getIpPermissions().add(tcp(443, "0.0.0.0/0")); + group.getIpPermissions().add(tcp(22, "10.0.0.0/8")); + return group; + } + + @Test + void aRolledBackUpdatePutsTheRulesTheTagsAndTheRecordsBack() throws Exception { + StackResource r = createdWeb(); + Map recordsBefore = new HashMap<>(r.getAttributes()); + SecurityGroup afterUpdate = group("sg-1", "web", "web tier", "vpc-1"); + afterUpdate.getIpPermissions().add(tcp(80, "0.0.0.0/0")); + afterUpdate.getIpPermissions().add(tcp(8080, "0.0.0.0/0")); + afterUpdate.getIpPermissions().add(tcp(22, "10.0.0.0/8")); + when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of())) + .thenReturn(List.of(webBeforeUpdate()), List.of(afterUpdate)); + // external was added through EC2, outside the stack, so neither the update nor its rollback touches it. + when(ec2.describeTags(eq("us-east-1"), any())).thenReturn( + List.of(tagEntry("sg-1", "team", "core"), tagEntry("sg-1", "external", "x")), + List.of(tagEntry("sg-1", "team", "core"), tagEntry("sg-1", "external", "x")), + List.of(tagEntry("sg-1", "owner", "platform"), tagEntry("sg-1", "external", "x"))); + + provisioner.provision(r, props(WEB_80_8080), ctx("sg-1")); + verify(ec2).authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(8080))); + verify(ec2).revokeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(443))); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(ec2).revokeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(8080))); + // 443 the first time, from the create, and again from the rollback. + verify(ec2, times(2)).authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(443))); + verify(ec2).deleteTags(eq("us-east-1"), eq(List.of("sg-1")), argThat(tags("owner"))); + verify(ec2, times(2)).createTags(eq("us-east-1"), eq(List.of("sg-1")), argThat(tags("team"))); + verify(ec2, never()).deleteTags(anyString(), anyList(), argThat(tags("external"))); + assertEquals(recordsBefore, r.getAttributes(), "the rule and tag records are the first deployment's again"); + } + + @Test + void aRollbackDoesNotAuthorizeARuleTheGroupStillCarries() throws Exception { + StackResource r = createdWeb(); + // The update's revoke never took effect, so 443 is still there when the rollback runs. + when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of())) + .thenReturn(List.of(webBeforeUpdate())); + when(ec2.describeTags(eq("us-east-1"), any())).thenReturn(List.of(tagEntry("sg-1", "team", "core"))); + provisioner.provision(r, props(WEB_80_8080), ctx("sg-1")); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(ec2, times(1)).authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(443))); + } + + @Test + void aSourceAPermissionOutsideTheStackAlreadyHoldsIsNeitherAuthorizedNorRolledBack() throws Exception { + StackResource r = resource("WebSg"); + r.setPhysicalId("sg-1"); + // One permission holding two sources, as an AuthorizeSecurityGroupIngress outside the stack + // can leave it; the template declares one of them. + SecurityGroup group = group("sg-1", "web", "web tier", "vpc-1"); + IpPermission external = tcp(80, "0.0.0.0/0"); + external.getIpRanges().add(new IpRange("10.0.0.0/8")); + group.getIpPermissions().add(external); + when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of())).thenReturn(List.of(group)); + + provisioner.provision(r, props(WEB_80_8080), ctx("sg-1")); + assertTrue(provisioner.rollbackUpdate(r)); + + verify(ec2, never()).authorizeSecurityGroupIngress(anyString(), anyString(), argThat(port(80))); + // A revoke of 80 would take 0.0.0.0/0 out of the permission that held it before the update. + verify(ec2, never()).revokeSecurityGroupIngress(anyString(), anyString(), argThat(port(80))); + verify(ec2).revokeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(8080))); + } + + @Test + void aRollbackPutsBackATagThatHadNoValue() throws Exception { + StackResource r = resource("WebSg"); + r.setPhysicalId("sg-1"); + r.getAttributes().put(Ec2SecurityGroupCfnProvisioner.TAG_KEYS_ATTR, "[\"owner\"]"); + when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of())) + .thenReturn(List.of(group("sg-1", "web", "web tier", "vpc-1"))); + when(ec2.describeTags(eq("us-east-1"), any())).thenReturn( + List.of(tagEntry("sg-1", "owner", null)), + List.of(tagEntry("sg-1", "owner", null)), + List.of(tagEntry("sg-1", "owner", "platform"))); + + provisioner.provision(r, props(WEB_80_8080), ctx("sg-1")); + assertTrue(provisioner.rollbackUpdate(r)); + + verify(ec2).createTags(eq("us-east-1"), eq(List.of("sg-1")), argThat(actual -> actual.size() == 1 + && "owner".equals(actual.getFirst().getKey()) && actual.getFirst().getValue() == null)); + } + + @Test + void aFailedStepPutsAReusedGroupBackBeforeTheFailurePropagates() throws Exception { + StackResource r = createdWeb(); + when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of())) + .thenReturn(List.of(webBeforeUpdate())); + when(ec2.describeTags(eq("us-east-1"), any())).thenReturn(List.of(tagEntry("sg-1", "team", "core"))); + doThrow(new AwsException("InternalError", "ec2 is down", 500)) + .when(ec2).createTags(eq("us-east-1"), eq(List.of("sg-1")), argThat(tags("owner"))); + + assertThrows(AwsException.class, () -> provisioner.provision(r, props(WEB_80_8080), ctx("sg-1"))); + + verify(ec2).revokeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), argThat(port(8080))); + assertFalse(r.getAttributes().containsKey(Ec2SecurityGroupCfnProvisioner.UPDATE_SNAPSHOT_ATTR)); + verify(ec2, never()).deleteSecurityGroup(anyString(), anyString()); + } + + @Test + void aFailedTagWriteOnANewGroupDeletesIt() throws Exception { + when(ec2.createSecurityGroup("us-east-1", "web", "web tier", "vpc-1")) + .thenReturn(group("sg-1", "web", "web tier", "vpc-1")); + doThrow(new AwsException("InternalError", "ec2 is down", 500)) + .when(ec2).createTags(anyString(), anyList(), anyList()); + + assertThrows(AwsException.class, () -> provisioner.provision(resource("WebSg"), props(WEB_80_443), ctx(null))); + + verify(ec2).deleteSecurityGroup("us-east-1", "sg-1"); + } + + @Test + void aReplacedGroupIsNotReportedAsRolledBack() throws Exception { + StackResource r = createdWeb(); + when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of())) + .thenReturn(List.of(webBeforeUpdate())); + when(ec2.createSecurityGroup("us-east-1", "web", "new description", "vpc-1")) + .thenReturn(group("sg-2", "web", "new description", "vpc-1")); + + provisioner.provision(r, props(""" + {"GroupName": "web", "GroupDescription": "new description", "VpcId": "vpc-1"} + """), ctx("sg-1")); + + assertEquals("sg-2", r.getPhysicalId()); + assertFalse(provisioner.rollbackUpdate(r), "a replacement is not rolled back here"); + } + + @Test + void aCommittedOrClearedUpdateDropsTheSnapshot() throws Exception { + StackResource r = createdWeb(); + when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of())) + .thenReturn(List.of(webBeforeUpdate())); + provisioner.provision(r, props(WEB_80_8080), ctx("sg-1")); + assertTrue(r.getAttributes().containsKey(Ec2SecurityGroupCfnProvisioner.UPDATE_SNAPSHOT_ATTR)); + + provisioner.completeUpdate(r); + assertFalse(r.getAttributes().containsKey(Ec2SecurityGroupCfnProvisioner.UPDATE_SNAPSHOT_ATTR)); + + provisioner.provision(r, props(WEB_80_443), ctx("sg-1")); + provisioner.clearUpdate(r); + assertFalse(r.getAttributes().containsKey(Ec2SecurityGroupCfnProvisioner.UPDATE_SNAPSHOT_ATTR)); + } + + private static ArgumentMatcher> port(int port) { + return perms -> perms != null && perms.size() == 1 && perms.getFirst().getFromPort() == port; + } + + private static ArgumentMatcher> tags(String... keys) { + return actual -> actual != null + && actual.stream().map(Tag::getKey).collect(Collectors.toSet()).equals(Set.of(keys)); + } + private static Map tagEntry(String resourceId, String key, String value) { Map entry = new HashMap<>(); entry.put("resourceId", resourceId); diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index ec036864f6..f3eb5b14e5 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -194,7 +194,7 @@ notes: AWS::Lambda::WebFunction: control plane only; the endpoint domain does not serve requests yet AWS::Lambda::WebFunctionRevision: every property is createOnly, so a change mints a new revision AWS::EC2::VPC: '`Tags` update in place, keeping tags added outside the stack; deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS' - AWS::EC2::SecurityGroup: 'inline `SecurityGroupIngress`/`SecurityGroupEgress` supported; `Tags` update in place, keeping tags added outside the stack' + AWS::EC2::SecurityGroup: 'inline `SecurityGroupIngress`/`SecurityGroupEgress` supported; `Tags` update in place, keeping tags added outside the stack; a failed stack update puts the rules and tags of a group it changed in place back' AWS::EC2::Instance: '`Tags` update in place, keeping tags added outside the stack' AWS::EC2::FlowLog: '`Tags` are applied and updated in place, keeping tags added outside the stack; any other change fails, since it needs a replacement' AWS::EC2::KeyPair: 'a created key''s private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key'