fix(cloudformation): preserve security group identity and rule ownership (#7430)

Retain an unnamed security group across inline-rule updates and snapshot every EC2 revoke criterion before mutating stored permissions. Preserve immutable-property replacement and rules owned by other stacks. Share DeleteStack followed by awaitStackDeleted in CfnStackWaits for the security group and composite alarm fixtures.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-03 14:55:32 -04:00
1 parent e27aa382e1
commit 7a7fef93d9
7 files changed
+230 -19

No files matched your search

@@ -68,7 +68,7 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner {
String region = ctx.region();
String groupName = ctx.resolveOptional(props, "GroupName");
if (groupName == null || groupName.isBlank()) {
groupName = ctx.generatePhysicalName(r.getLogicalId(), 255, false);
groupName = null;
}
String description = ctx.resolveOptional(props, "GroupDescription");
if (description == null || description.isBlank()) {
@@ -78,8 +78,12 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner {
// provision() re-runs for every resource on every update. Re-creating an unchanged group
// would mint a new group id (and collide on the name whenever the VPC id is stable), so
// reuse the group this resource already points at.
SecurityGroup reconciled = existingSecurityGroupToReconcile(ctx.priorPhysicalId(), groupName, description,
vpcId, region);
// An omitted name keeps the generated name, unless this update removed an explicit one.
SecurityGroup reconciled = groupName == null && ctx.previouslyDeclared("GroupName") ? null
: existingSecurityGroupToReconcile(ctx.priorPhysicalId(), groupName, description, vpcId, region);
if (reconciled == null && groupName == null) {
groupName = ctx.generatePhysicalName(r.getLogicalId(), 255, false);
}
final SecurityGroup sg = reconciled != null
? reconciled
: ec2Service.createSecurityGroup(region, groupName, description, vpcId);
@@ -8163,11 +8163,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
* <p>Returns the permissions that remain.
*/
private List<IpPermission> revokeSources(List<IpPermission> existing, List<IpPermission> toRemove) {
// A caller can pass permissions stored on the group. Freeze all removal criteria before
// mutating any of them; an emptied source list otherwise becomes a wildcard for later rules.
List<IpPermission> removals = toRemove.stream().map(Ec2Service::copyPermissionSources).toList();
List<IpPermission> remaining = new ArrayList<>();
for (IpPermission perm : existing) {
boolean dropWholePermission = false;
boolean hadSources = hasSources(perm);
for (IpPermission removal : toRemove) {
for (IpPermission removal : removals) {
if (!sameProtocolAndPorts(perm, removal)) {
continue;
}
@@ -8175,8 +8178,6 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
dropWholePermission = true;
break;
}
// authorize stores the caller's IpPermission object, so a revoke can name the very
// instance held on the group. Snapshot the values before mutating either list.
List<String> cidrs = removal.getIpRanges().stream().map(IpRange::getCidrIp).toList();
List<String> cidrsV6 = removal.getIpv6Ranges().stream().map(Ipv6Range::getCidrIpv6).toList();
List<String> lists = removal.getPrefixListIds().stream()
@@ -8197,6 +8198,18 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return remaining;
}
private static IpPermission copyPermissionSources(IpPermission permission) {
IpPermission copy = new IpPermission();
copy.setIpProtocol(permission.getIpProtocol());
copy.setFromPort(permission.getFromPort());
copy.setToPort(permission.getToPort());
copy.setIpRanges(new ArrayList<>(permission.getIpRanges()));
copy.setIpv6Ranges(new ArrayList<>(permission.getIpv6Ranges()));
copy.setPrefixListIds(new ArrayList<>(permission.getPrefixListIds()));
copy.setUserIdGroupPairs(new ArrayList<>(permission.getUserIdGroupPairs()));
return copy;
}
private boolean sameProtocolAndPorts(IpPermission a, IpPermission b) {
String protocol = SecurityGroupPolicy.normalizeProtocol(a.getIpProtocol());
if (!Objects.equals(protocol, SecurityGroupPolicy.normalizeProtocol(b.getIpProtocol()))) {
@@ -65,7 +65,7 @@ class CloudFormationCompositeAlarmIntegrationTest {
if (rename) {
assertMissing(next);
}
deleteStack(stack);
CfnStackWaits.deleteStack(stack);
assertMissing(name);
}
@@ -85,7 +85,7 @@ class CloudFormationCompositeAlarmIntegrationTest {
} else {
assertMissing(original);
}
deleteStack(stack);
CfnStackWaits.deleteStack(stack);
assertMissing(next);
if (retain) {
assertEquals("TRUE", alarm(original).get("AlarmRule"));
@@ -109,7 +109,7 @@ class CloudFormationCompositeAlarmIntegrationTest {
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
assertMissing(name);
assertEquals("FALSE", alarm(replacement).get("AlarmRule"));
deleteStack(stack);
CfnStackWaits.deleteStack(stack);
assertMissing(replacement);
}
@@ -121,7 +121,7 @@ class CloudFormationCompositeAlarmIntegrationTest {
deploy("CreateStack", stack, template(name, "FALSE", Map.of(), false, false));
assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
assertEquals("TRUE", alarm(name).get("AlarmRule"));
deleteStack(stack);
CfnStackWaits.deleteStack(stack);
assertEquals("TRUE", alarm(name).get("AlarmRule"));
cw("DeleteAlarms", Map.of("AlarmNames", List.of(name))).then().statusCode(200);
}
@@ -145,7 +145,7 @@ class CloudFormationCompositeAlarmIntegrationTest {
Map<String, Object> created = alarm(parent);
assertEquals(created.get("AlarmArn") + " was created and its alarm rule evaluates to OK",
created.get("StateReason"));
deleteStack(stack);
CfnStackWaits.deleteStack(stack);
assertMissing(parent);
assertEquals(List.of(), cw("DescribeAlarms", Map.of("AlarmNames", List.of(child))).then().statusCode(200)
.extract().jsonPath().getList("MetricAlarms"));
@@ -164,7 +164,7 @@ class CloudFormationCompositeAlarmIntegrationTest {
assertTrue(reason.contains("Could not save the composite alarm as alarms [arn:aws:cloudwatch:us-east-1:"
+ "000000000000:alarm:" + stack + "-missing] in the alarm rule do not exist"), reason);
assertMissing(parent);
deleteStack(stack);
CfnStackWaits.deleteStack(stack);
}
private String template(String name, String rule, Map<String, String> tags, boolean fail, boolean retain)
@@ -219,11 +219,6 @@ class CloudFormationCompositeAlarmIntegrationTest {
.extract().jsonPath().getList("CompositeAlarms"));
}
private void deleteStack(String stack) {
given().contentType("application/x-www-form-urlencoded").formParam("Action", "DeleteStack")
.formParam("StackName", stack).post("/").then().statusCode(200);
CfnStackWaits.awaitStackDeleted(stack);
}
private static String unique(String prefix) {
return prefix + "-" + Long.toString(System.nanoTime(), 36);
@@ -1,10 +1,13 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -247,6 +250,94 @@ class CloudFormationSecurityGroupRulesIntegrationTest {
"update left the replaced permission behind");
}
@Test
void unnamedGroupUpdateKeepsItsIdentityAndAnotherStacksRules() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-unnamed-sg-" + suffix;
String callerStack = "cfn-unnamed-caller-" + suffix;
String template = """
{
"Resources": {
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.51.0.0/16"}},
"Group": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupDescription": "unnamed frontend",
"VpcId": {"Ref": "Vpc"},
"SecurityGroupIngress": [
{"IpProtocol": "tcp", "FromPort": 9100, "ToPort": 9100, "CidrIp": "10.1.0.0/16"}
]
}
}
},
"Outputs": {
"RefId": {"Value": {"Ref": "Group"}},
"GroupId": {"Value": {"Fn::GetAtt": ["Group", "GroupId"]}},
"VpcId": {"Value": {"Ref": "Vpc"}}
}
}
""";
String groupId = null;
String vpcId = null;
try {
String stackId = createStack(stackName, template);
groupId = output(stackName, "RefId");
vpcId = output(stackName, "VpcId");
given()
.header("Authorization", EC2_AUTH)
.formParam("Action", "DescribeVpcs")
.formParam("Filter.1.Name", "vpc-id")
.formParam("Filter.1.Value.1", vpcId)
.when().post("/").then().statusCode(200).body(containsString("<vpcId>" + vpcId + "</vpcId>"));
createStack(callerStack, standaloneIngressTemplate(groupId, "10.2.0.0/16"));
updateStack(stackName, template.replace("10.1.0.0/16", "10.3.0.0/16"));
assertTrue(awaitStackStatus(stackId, "UPDATE_COMPLETE"));
assertEquals(groupId, output(stackName, "RefId"));
assertEquals(groupId, output(stackName, "GroupId"));
String group = describeGroup(groupId);
assertFalse(group.contains("<cidrIp>10.1.0.0/16</cidrIp>"));
assertTrue(group.contains("<cidrIp>10.3.0.0/16</cidrIp>"));
assertTrue(group.contains("<cidrIp>10.2.0.0/16</cidrIp>"),
"frontend update removed another stack's permission");
CfnStackWaits.deleteStack(callerStack, CFN_AUTH);
group = describeGroup(groupId);
assertFalse(group.contains("<cidrIp>10.2.0.0/16</cidrIp>"));
assertTrue(group.contains("<cidrIp>10.3.0.0/16</cidrIp>"));
} finally {
try {
deleteStackIfPresent(callerStack);
} finally {
deleteStackIfPresent(stackName);
}
}
assertFalse(describeGroup(groupId).contains("<groupId>"));
given()
.header("Authorization", EC2_AUTH)
.formParam("Action", "DescribeVpcs")
.formParam("Filter.1.Name", "vpc-id")
.formParam("Filter.1.Value.1", vpcId)
.when().post("/").then().statusCode(200).body(not(containsString("<vpcId>")));
}
private static void deleteStackIfPresent(String name) throws InterruptedException {
Response response = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", name)
.when().post("/");
String body = response.asString();
if (response.statusCode() == 400 && body.contains("<Code>ValidationError</Code>")
&& body.contains("Stack with id " + name + " does not exist")) {
return;
}
response.then().statusCode(200);
String id = between(body, "<StackId>", "</StackId>");
assertFalse(id.isBlank(), "owned stack has no id");
CfnStackWaits.deleteStack(name, CFN_AUTH);
}
/** A deleted stack is only describable by id, as in AWS; it is retained for a grace period. */
private static boolean awaitStackStatus(String stackId, String status) throws InterruptedException {
for (int i = 0; i < 100; i++) {
@@ -349,7 +440,8 @@ class CloudFormationSecurityGroupRulesIntegrationTest {
private static String describeGroup(String groupId) {
return given()
.formParam("Action", "DescribeSecurityGroups")
.formParam("GroupId.1", groupId)
.formParam("Filter.1.Name", "group-id")
.formParam("Filter.1.Value.1", groupId)
.header("Authorization", EC2_AUTH)
.when().post("/").then().statusCode(200).extract().asString();
}
@@ -92,6 +92,63 @@ class Ec2SecurityGroupCfnProvisionerTest {
verify(ec2, never()).createSecurityGroup(anyString(), anyString(), anyString(), any());
}
@Test
void updateWithoutGroupNameKeepsTheGeneratedGroupAndAddsItsRule() throws Exception {
when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of()))
.thenReturn(List.of(group("sg-1", "my-stack-WebSg-0123456789ab", "web tier", "vpc-1")));
StackResource r = resource("WebSg");
r.setPhysicalId("sg-1");
provisioner.provision(r, props("""
{"GroupDescription": "web tier", "VpcId": "vpc-1",
"SecurityGroupIngress": [
{"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443, "CidrIp": "192.0.2.1/32"}
]}
"""), ctx("sg-1", props("""
{"GroupDescription": "web tier", "VpcId": "vpc-1"}
""")));
assertEquals("sg-1", r.getPhysicalId());
assertEquals("sg-1", r.getAttributes().get("GroupId"));
verify(ec2).authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-1"), anyList());
verify(ec2, never()).createSecurityGroup(anyString(), anyString(), anyString(), any());
}
@Test
void removingAnExplicitGroupNameStillCreatesAReplacement() throws Exception {
when(ec2.createSecurityGroup(eq("us-east-1"), anyString(), eq("web tier"), eq("vpc-1")))
.thenReturn(group("sg-new", "generated", "web tier", "vpc-1"));
StackResource r = resource("WebSg");
r.setPhysicalId("sg-old");
provisioner.provision(r, props("""
{"GroupDescription": "web tier", "VpcId": "vpc-1"}
"""), ctx("sg-old", props("""
{"GroupName": "web", "GroupDescription": "web tier", "VpcId": "vpc-1"}
""")));
assertEquals("sg-new", r.getPhysicalId());
ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);
verify(ec2).createSecurityGroup(eq("us-east-1"), name.capture(), eq("web tier"), eq("vpc-1"));
assertTrue(name.getValue().matches("my-stack-WebSg-[0-9a-f]{12}"), name.getValue());
}
@Test
void changingAnUnnamedGroupsDescriptionStillCreatesAReplacement() throws Exception {
when(ec2.describeSecurityGroups("us-east-1", List.of("sg-old"), List.of(), Map.of()))
.thenReturn(List.of(group("sg-old", "my-stack-WebSg-0123456789ab", "old tier", "vpc-1")));
when(ec2.createSecurityGroup(eq("us-east-1"), anyString(), eq("new tier"), eq("vpc-1")))
.thenReturn(group("sg-new", "generated", "new tier", "vpc-1"));
StackResource r = resource("WebSg");
r.setPhysicalId("sg-old");
provisioner.provision(r, props("""
{"GroupDescription": "new tier", "VpcId": "vpc-1"}
"""), ctx("sg-old"));
assertEquals("sg-new", r.getPhysicalId());
}
@Test
void reservedUpdateTagsFailBeforeChangingRulesOrDeletingExistingTags() throws Exception {
StackResource r = resource("WebSg");
@@ -261,13 +318,18 @@ class Ec2SecurityGroupCfnProvisionerTest {
}
private ProvisionContext ctx(String priorPhysicalId) {
return ctx(priorPhysicalId, null);
}
private ProvisionContext ctx(String priorPhysicalId, JsonNode priorProperties) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId,
event -> {}, priorProperties);
}
private JsonNode props(String json) throws Exception {
@@ -6828,6 +6828,35 @@ class Ec2ServiceTest {
.getFirst().getIpPermissions().isEmpty(), "protocol 6 is tcp");
}
@ParameterizedTest
@CsvSource({"false, false", "false, true", "true, false", "true, true"})
void revokingAStoredPermissionKeepsLaterSources(boolean egress, boolean repeatedRemoval) {
Ec2Service service = sgService();
String groupId = service.createSecurityGroup("us-east-1", "web", "web", null).getGroupId();
IpPermission retired = basePermission();
retired.getIpRanges().add(new IpRange("192.0.2.1/32", null));
IpPermission current = basePermission();
current.getIpRanges().add(new IpRange("192.0.2.2/32", null));
IpPermission otherOwner = basePermission();
otherOwner.getIpRanges().add(new IpRange("192.0.2.3/32", null));
List<IpPermission> permissions = List.of(retired, current, otherOwner);
List<IpPermission> removals = repeatedRemoval ? List.of(retired, retired) : List.of(retired);
if (egress) {
service.revokeSecurityGroupEgress("us-east-1", groupId, List.of(cidrPermission("-1", 0, 0)));
service.authorizeSecurityGroupEgress("us-east-1", groupId, permissions);
service.revokeSecurityGroupEgress("us-east-1", groupId, removals);
} else {
service.authorizeSecurityGroupIngress("us-east-1", groupId, permissions);
service.revokeSecurityGroupIngress("us-east-1", groupId, removals);
}
SecurityGroup group = service.describeSecurityGroups("us-east-1", List.of(groupId), List.of(), Map.of())
.getFirst();
List<IpPermission> remaining = egress ? group.getIpPermissionsEgress() : group.getIpPermissions();
assertEquals(List.of("192.0.2.2/32", "192.0.2.3/32"),
remaining.stream().flatMap(permission -> permission.getIpRanges().stream())
.map(IpRange::getCidrIp).toList());
}
/** Ingress only: createSecurityGroup seeds a default allow-all egress rule. */
private static List<String> ingressRuleIds(Ec2Service service, String groupId) {
return service.describeSecurityGroupRules("us-east-1", List.of(groupId), List.of())
@@ -162,6 +162,22 @@ public final class CfnStackWaits {
return child == null ? "" : child.value();
}
public static void deleteStack(String stackName) {
deleteStack(stackName, null);
}
public static void deleteStack(String stackName, String authorization) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName);
if (authorization != null) {
request.header("Authorization", authorization);
}
request.when().post("/").then().statusCode(200);
awaitStackDeleted(stackName, authorization);
}
/**
* Waits until DescribeStacks answers 400, which is how a missing stack is reported. Fails on
* DELETE_FAILED or after ten seconds.