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 6fada14d9a..c2e4f007cc 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 @@ -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); diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 87df060a3e..ba3b59482a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -8163,11 +8163,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab *

Returns the permissions that remain. */ private List revokeSources(List existing, List 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 removals = toRemove.stream().map(Ec2Service::copyPermissionSources).toList(); List 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 cidrs = removal.getIpRanges().stream().map(IpRange::getCidrIp).toList(); List cidrsV6 = removal.getIpv6Ranges().stream().map(Ipv6Range::getCidrIpv6).toList(); List 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()))) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCompositeAlarmIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCompositeAlarmIntegrationTest.java index abba523359..5aed6b8ab2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCompositeAlarmIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCompositeAlarmIntegrationTest.java @@ -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 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 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecurityGroupRulesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecurityGroupRulesIntegrationTest.java index 47bb528e35..a97537b2ed 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecurityGroupRulesIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecurityGroupRulesIntegrationTest.java @@ -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 + "")); + 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("10.1.0.0/16")); + assertTrue(group.contains("10.3.0.0/16")); + assertTrue(group.contains("10.2.0.0/16"), + "frontend update removed another stack's permission"); + + CfnStackWaits.deleteStack(callerStack, CFN_AUTH); + group = describeGroup(groupId); + assertFalse(group.contains("10.2.0.0/16")); + assertTrue(group.contains("10.3.0.0/16")); + } finally { + try { + deleteStackIfPresent(callerStack); + } finally { + deleteStackIfPresent(stackName); + } + } + assertFalse(describeGroup(groupId).contains("")); + 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(""))); + } + + 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("ValidationError") + && body.contains("Stack with id " + name + " does not exist")) { + return; + } + response.then().statusCode(200); + String id = between(body, "", ""); + 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(); } 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 cfd9da3d3e..5d2a7683cb 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 @@ -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 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 { diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index 358f1528bc..53f317b105 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -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 permissions = List.of(retired, current, otherOwner); + List 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 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 ingressRuleIds(Ec2Service service, String groupId) { return service.describeSecurityGroupRules("us-east-1", List.of(groupId), List.of()) diff --git a/src/test/java/io/github/hectorvent/floci/testing/CfnStackWaits.java b/src/test/java/io/github/hectorvent/floci/testing/CfnStackWaits.java index ff2bea8791..02d7862726 100644 --- a/src/test/java/io/github/hectorvent/floci/testing/CfnStackWaits.java +++ b/src/test/java/io/github/hectorvent/floci/testing/CfnStackWaits.java @@ -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.