fix(cloudformation): roll back an AWS::EC2::SecurityGroup updated in place (#7562)

This commit is contained in:
Ronald Li 🛠️ authored and GitHub committed 2026-11-04 22:37:06 -04:00
1 parent 31227106b1
commit d280f451fa
6 files changed
+558 -32

No files matched your search

@@ -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;
* <p>The inline {@code SecurityGroupIngress}/{@code SecurityGroupEgress} properties share their
* rule-object mapping with the standalone rule resources, through
* {@link Ec2SecurityGroupRuleCfnProvisioner#toIpPermission}.
*
* <p>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<String> 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<String> 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<String> 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<IpPermission> authorize, List<IpPermission> revoke, Set<String> 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<IpPermission> existing,
CloudFormationTemplateEngine engine, UnaryOperator<String> peerGroupId,
StackResource r, String attrKey,
Consumer<List<IpPermission>> authorize,
Consumer<List<IpPermission>> revoke) {
private static RulePlan planRules(JsonNode props, String property, List<IpPermission> existing,
CloudFormationTemplateEngine engine, UnaryOperator<String> peerGroupId,
String storedKeys) {
List<IpPermission> 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<String> 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<String> present = sourceKeys(existing, peerGroupId);
List<IpPermission> authorize = new ArrayList<>();
for (IpPermission perm : declared) {
if (present.add(permissionKey(perm, peerGroupId))) {
authorize.accept(List.of(perm));
authorize.add(perm);
}
}
Set<String> priorKeys = parseRuleKeys(r.getAttributes().get(attrKey));
Set<String> priorKeys = parseRuleKeys(storedKeys);
List<IpPermission> 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<String> 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<String> ownedTags, Map<String, String> 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<String> 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<IpPermission> permissions(JsonNode saved) {
List<IpPermission> 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<IpPermission> missing(List<IpPermission> saved, List<IpPermission> current,
UnaryOperator<String> peerGroupId) {
Set<String> 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<String> sourceKeys(List<IpPermission> permissions, UnaryOperator<String> peerGroupId) {
Set<String> keys = new LinkedHashSet<>();
for (IpPermission permission : permissions) {
List<IpPermission> 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<IpPermission> 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);
}
}
@@ -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<String> owned, Map<String, String> desired,
Map<String, String> 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<String> touched = new LinkedHashSet<>();
snapshot.path("touched").forEach(key -> touched.add(key.asText()));
Map<String, String> 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);
}