Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudformation): apply security-group rules — inline properties and standalone resources (#1993)
lex001461a10de7b2
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex 0986e41d5b..8e57290641 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -67,7 +67,7 @@ cross-resource references.| ECS | `Cluster`, `TaskDefinition`, `Service` || EKS | `Cluster`, `Nodegroup` || RDS | `DBInstance`, `DBCluster`, `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup` (DBInstance/DBCluster start real containers) |-| EC2 | `VPC`, `Subnet`, `SecurityGroup`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` |+| EC2 | `VPC`, `Subnet`, `SecurityGroup` (including inline `SecurityGroupIngress`/`SecurityGroupEgress`), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` || Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` || Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook` || Route 53 | `HostedZone`, `RecordSet` |diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.javaindex a0ba05512e..422f99a38e 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollbaimport io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext;import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceProvisioner;+import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2SecurityGroupRuleCfnProvisioner;import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters;@@ -762,6 +763,22 @@ public class CloudFormationResourceProvisioner {if (sg.getVpcId() != null) {r.getAttributes().put("VpcId", sg.getVpcId());}++ // Inline rule properties — previously dropped, leaving the group empty. The mapping is+ // shared with the standalone SecurityGroupIngress/Egress resource types, which live in+ // Ec2SecurityGroupRuleCfnProvisioner; this arm joins them when it is extracted.+ if (props != null && props.has("SecurityGroupIngress")) {+ for (JsonNode rule : props.get("SecurityGroupIngress")) {+ ec2Service.authorizeSecurityGroupIngress(region, sg.getGroupId(),+ List.of(Ec2SecurityGroupRuleCfnProvisioner.toIpPermission(rule, engine)));+ }+ }+ if (props != null && props.has("SecurityGroupEgress")) {+ for (JsonNode rule : props.get("SecurityGroupEgress")) {+ ec2Service.authorizeSecurityGroupEgress(region, sg.getGroupId(),+ List.of(Ec2SecurityGroupRuleCfnProvisioner.toIpPermission(rule, engine)));+ }+ }}private void provisionInternetGateway(StackResource r, String region) {diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupRuleCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupRuleCfnProvisioner.javanew file mode 100644index 0000000000..5fe804f66f--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupRuleCfnProvisioner.java@@ -0,0 +1,211 @@+package io.github.hectorvent.floci.services.cloudformation.provisioners;++import com.fasterxml.jackson.databind.JsonNode;+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;+import io.github.hectorvent.floci.services.ec2.Ec2Service;+import io.github.hectorvent.floci.services.ec2.model.IpPermission;+import io.github.hectorvent.floci.services.ec2.model.IpRange;+import io.github.hectorvent.floci.services.ec2.model.Ipv6Range;+import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;+import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;+import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.stream.Stream;++/**+ * CloudFormation provisioning for the standalone security-group rule resources:+ * {@code AWS::EC2::SecurityGroupIngress} and {@code AWS::EC2::SecurityGroupEgress} (issue #1992).+ *+ * <p>The rule-object to {@link IpPermission} mapping lives here as+ * {@link #toIpPermission(JsonNode, CloudFormationTemplateEngine)} because the inline+ * {@code SecurityGroupIngress}/{@code SecurityGroupEgress} properties of+ * {@code AWS::EC2::SecurityGroup} take the same shape. That arm is still in+ * {@code CloudFormationResourceProvisioner} and calls this method, so there is one mapping rather+ * than two; it moves here when the security-group arm itself is extracted.+ */+@ApplicationScoped+public class Ec2SecurityGroupRuleCfnProvisioner implements CfnResourceProvisioner {++ private static final String INGRESS = "AWS::EC2::SecurityGroupIngress";+ private static final String EGRESS = "AWS::EC2::SecurityGroupEgress";++ private final Ec2Service ec2Service;++ @Inject+ public Ec2SecurityGroupRuleCfnProvisioner(Ec2Service ec2Service) {+ this.ec2Service = ec2Service;+ }++ @Override+ public Set<String> resourceTypes() {+ return Set.of(INGRESS, EGRESS);+ }++ @Override+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {+ boolean ingress = switch (r.getResourceType()) {+ case INGRESS -> true;+ case EGRESS -> false;+ default -> throw new IllegalStateException(+ "Ec2SecurityGroupRuleCfnProvisioner cannot handle " + r.getResourceType());+ };++ String groupId = resolveGroupId(props, ctx);+ IpPermission perm = toIpPermission(props, ctx.engine());++ // UpdateStack re-executes every resource with the physical id it got at create time, and the+ // authorize APIs are append-only, so the rule the previous execution created has to go:+ // otherwise an unchanged rule doubles up on the group, and a changed one leaves its old+ // permission behind. These resources are immutable in CloudFormation — every property change+ // is a replacement — so the update semantics are authorize-then-revoke.+ //+ // Authorize first, revoke second. The other order leaves the group with neither rule when+ // the new authorization fails, and rollback keeps the old physical id without recreating+ // its permission, so the stack settles as UPDATE_ROLLBACK_COMPLETE minus a valid rule.+ String previousRuleId = r.getPhysicalId();++ List<SecurityGroupRule> rules = ingress+ ? ec2Service.authorizeSecurityGroupIngress(ctx.region(), groupId, List.of(perm))+ : ec2Service.authorizeSecurityGroupEgress(ctx.region(), groupId, List.of(perm));++ if (previousRuleId != null && previousRuleId.startsWith("sgr-")) {+ ec2Service.deleteSecurityGroupRule(ctx.region(), previousRuleId);+ }+ // Ref and Fn::GetAtt Id both return the rule id, as they do in CloudFormation. The logical+ // id is only a fallback for the (unreachable in practice) case of no rule being recorded —+ // a null physical id would make the stack skip this resource on delete.+ String ruleId = !rules.isEmpty() && rules.get(0).getSecurityGroupRuleId() != null+ ? rules.get(0).getSecurityGroupRuleId()+ : r.getLogicalId();+ r.setPhysicalId(ruleId);+ r.getAttributes().put("Id", ruleId);+ }++ @Override+ public void delete(String resourceType, String physicalId, String region) {+ if (physicalId == null || !physicalId.startsWith("sgr-")) {+ return;+ }+ // A standalone rule can target a group that outlives the stack, so the permission has to be+ // revoked explicitly. deleteSecurityGroupRule already absorbs the two cases a stack delete+ // runs into, returning false for a rule that is no longer recorded and succeeding when the+ // group itself is gone, so a throw from here is a real failure and belongs to the caller.+ ec2Service.deleteSecurityGroupRule(region, physicalId);+ }++ /**+ * Maps a CloudFormation rule object — the properties of a standalone+ * SecurityGroupIngress/Egress resource, or one entry of a security group's inline+ * {@code SecurityGroupIngress}/{@code SecurityGroupEgress} list — onto the EC2 model.+ */+ public static IpPermission toIpPermission(JsonNode rule, CloudFormationTemplateEngine engine) {+ IpPermission perm = new IpPermission();+ String protocol = resolve(rule, "IpProtocol", engine);+ perm.setIpProtocol(protocol != null ? protocol : "-1");+ if (rule != null && rule.hasNonNull("FromPort")) {+ perm.setFromPort(rule.get("FromPort").asInt());+ }+ if (rule != null && rule.hasNonNull("ToPort")) {+ perm.setToPort(rule.get("ToPort").asInt());+ }+ // One Description property covers whichever peer the rule names, matching CloudFormation.+ String description = resolve(rule, "Description", engine);+ String cidr = resolve(rule, "CidrIp", engine);+ String cidr6 = resolve(rule, "CidrIpv6", engine);+ String peerGroup = firstNonBlank(+ resolve(rule, "SourceSecurityGroupId", engine),+ resolve(rule, "DestinationSecurityGroupId", engine));+ // Ingress also names a peer by group name, with an owner id for a group in another+ // account. Egress has no name variant. Counting only the id form rejected a template+ // that did name exactly one source.+ String peerGroupName = resolve(rule, "SourceSecurityGroupName", engine);+ String peerGroupOwner = resolve(rule, "SourceSecurityGroupOwnerId", engine);+ String prefixList = firstNonBlank(+ resolve(rule, "SourcePrefixListId", engine),+ resolve(rule, "DestinationPrefixListId", engine));++ // "You must specify exactly one of the following sources: an IPv4 address range, an IPv6+ // address range, a prefix list, or a security group." Naming several used to authorize a+ // rule record per peer while only the first id was kept, so delete revoked one of them and+ // an update left the others on the group.+ String peer = firstNonBlank(peerGroup, peerGroupName);+ long sources = Stream.of(cidr, cidr6, peer, prefixList)+ .filter(s -> s != null && !s.isBlank())+ .count();+ // Exactly one, so zero is rejected too. Letting none through sent an IpPermission naming+ // no peer at all, which the stack then reported as successfully provisioned.+ if (sources != 1) {+ throw new AwsException("ValidationError",+ "A security group rule must specify exactly one of CidrIp, CidrIpv6, "+ + "a prefix list, or a security group.", 400);+ }++ if (cidr != null && !cidr.isBlank()) {+ IpRange range = new IpRange();+ range.setCidrIp(cidr);+ range.setDescription(description);+ perm.getIpRanges().add(range);+ }+ if (cidr6 != null && !cidr6.isBlank()) {+ Ipv6Range range6 = new Ipv6Range();+ range6.setCidrIpv6(cidr6);+ range6.setDescription(description);+ perm.getIpv6Ranges().add(range6);+ }+ if (peer != null && !peer.isBlank()) {+ UserIdGroupPair pair = new UserIdGroupPair();+ // Ec2Service resolves a name to an id on authorize, before it records the rule, so the+ // name form is handed over as-is rather than resolved twice.+ if (peerGroup != null && !peerGroup.isBlank()) {+ pair.setGroupId(peerGroup);+ } else {+ pair.setGroupName(peerGroupName);+ }+ if (peerGroupOwner != null && !peerGroupOwner.isBlank()) {+ pair.setUserId(peerGroupOwner);+ }+ pair.setDescription(description);+ perm.getUserIdGroupPairs().add(pair);+ }+ return perm;+ }++ /**+ * GroupId is the VPC form. GroupName is the EC2-Classic/default-VPC form: look the group up by+ * name so the rule lands on it, falling back to the raw name so a miss reports what was asked+ * for rather than {@code null}.+ */+ private String resolveGroupId(JsonNode props, ProvisionContext ctx) {+ String groupId = ctx.resolveOptional(props, "GroupId");+ if (groupId != null && !groupId.isBlank()) {+ return groupId;+ }+ String groupName = ctx.resolveOptional(props, "GroupName");+ if (groupName == null || groupName.isBlank()) {+ return null;+ }+ return ec2Service.describeSecurityGroups(ctx.region(), List.of(), List.of(groupName), Map.of())+ .stream()+ .map(SecurityGroup::getGroupId)+ .findFirst()+ .orElse(groupName);+ }++ private static String firstNonBlank(String preferred, String fallback) {+ return preferred != null && !preferred.isBlank() ? preferred : fallback;+ }++ private static String resolve(JsonNode props, String name, CloudFormationTemplateEngine engine) {+ if (props == null || !props.has(name) || props.get(name).isNull()) {+ return null;+ }+ return engine.resolve(props.get(name));+ }+}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.javaindex 5825b34522..9dcab763f9 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@@ -2528,6 +2528,108 @@ public class Ec2Service implements ContainerTeardown {}}+ /**+ * Deletes a rule by its {@code sgr-} id, which is what a standalone+ * {@code AWS::EC2::SecurityGroupIngress} or {@code Egress} resource holds as its physical id.+ * Returns false when the rule is already gone, so a stack delete stays idempotent.+ */+ public boolean deleteSecurityGroupRule(String region, String securityGroupRuleId) {+ ensureDefaultResources(region);+ SecurityGroupRule rule = securityGroupRules.get(key(region, securityGroupRuleId)).orElse(null);+ if (rule == null) {+ return false;+ }+ securityGroupRules.delete(key(region, securityGroupRuleId));+ String groupId = rule.getGroupId();+ if (groupId == null) {+ return true;+ }+ synchronized (lockFor(key(region, groupId))) {+ SecurityGroup sg = securityGroups.get(key(region, groupId)).orElse(null);+ if (sg == null) {+ return true;+ }+ List<IpPermission> next = new ArrayList<>(rule.isEgress()+ ? sg.getIpPermissionsEgress() : sg.getIpPermissions());+ if (removeRecordedPermission(next, rule)) {+ if (rule.isEgress()) {+ sg.setIpPermissionsEgress(next);+ } else {+ sg.setIpPermissions(next);+ }+ securityGroups.put(key(region, groupId), sg);+ }+ }+ if (!rule.isEgress()) {+ reconcilePublishedPortsForGroup(region, groupId);+ }+ return true;+ }++ /**+ * Drops exactly the peer a rule record names, its ipv4 cidr, ipv6 cidr or referenced group, and+ * the whole permission only once nothing is left in it. Matching on protocol and ports alone+ * would take out an unrelated rule that happens to share them.+ */+ private boolean removeRecordedPermission(List<IpPermission> perms, SecurityGroupRule rule) {+ String referencedGroupId = rule.getReferencedGroupInfo() == null+ ? null : rule.getReferencedGroupInfo().getGroupId();+ for (IpPermission perm : perms) {+ if (!Objects.equals(perm.getIpProtocol(), rule.getIpProtocol())+ || !Objects.equals(perm.getFromPort(), rule.getFromPort())+ || !Objects.equals(perm.getToPort(), rule.getToPort())) {+ continue;+ }+ if (rule.getCidrIpv6() != null) {+ Ipv6Range match6 = perm.getIpv6Ranges().stream()+ .filter(r -> rule.getCidrIpv6().equals(r.getCidrIpv6()))+ .findFirst().orElse(null);+ if (match6 == null) {+ continue;+ }+ perm.getIpv6Ranges().remove(match6);+ dropIfEmpty(perms, perm);+ return true;+ }+ if (referencedGroupId != null) {+ UserIdGroupPair matchPair = perm.getUserIdGroupPairs().stream()+ .filter(pair -> referencedGroupId.equals(pair.getGroupId()))+ .findFirst().orElse(null);+ if (matchPair == null) {+ continue;+ }+ perm.getUserIdGroupPairs().remove(matchPair);+ dropIfEmpty(perms, perm);+ return true;+ }+ if (rule.getCidrIpv4() != null) {+ IpRange match = perm.getIpRanges().stream()+ .filter(r -> rule.getCidrIpv4().equals(r.getCidrIp()))+ .findFirst().orElse(null);+ if (match == null) {+ continue;+ }+ perm.getIpRanges().remove(match);+ dropIfEmpty(perms, perm);+ return true;+ }+ // A record naming no peer matches only a permission that names none either.+ if (perm.getIpRanges().isEmpty() && perm.getIpv6Ranges().isEmpty()+ && perm.getUserIdGroupPairs().isEmpty()) {+ perms.remove(perm);+ return true;+ }+ }+ return false;+ }++ private static void dropIfEmpty(List<IpPermission> perms, IpPermission perm) {+ if (perm.getIpRanges().isEmpty() && perm.getIpv6Ranges().isEmpty()+ && perm.getUserIdGroupPairs().isEmpty()) {+ perms.remove(perm);+ }+ }+private SecurityGroup getRequiredSecurityGroup(String region, String groupId) {SecurityGroup sg = securityGroups.get(key(region, groupId)).orElse(null);if (sg == null)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.javanew file mode 100644index 0000000000..2fe78aec9f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecurityGroupRulesIntegrationTest.java@@ -0,0 +1,370 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * End-to-end check that CloudFormation security-group rules exist for real+ * (issue #1992): inline SecurityGroupIngress/Egress properties on+ * AWS::EC2::SecurityGroup, and the standalone SecurityGroupIngress/Egress+ * resource types, all land in Ec2Service. Metadata-only — Docker-free.+ */+@QuarkusTest+class CloudFormationSecurityGroupRulesIntegrationTest {++ private static final String CFN_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";+ private static final String EC2_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";++ @Test+ void inlineAndStandaloneRulesAreApplied() throws InterruptedException {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "cfn-sgrules-stack-" + suffix;++ String template = """+ {+ "Resources": {+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.50.0.0/16"}},+ "WebSg": {+ "Type": "AWS::EC2::SecurityGroup",+ "Properties": {+ "GroupDescription": "web",+ "VpcId": {"Ref": "Vpc"},+ "SecurityGroupIngress": [+ {"IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "CidrIp": "0.0.0.0/0", "Description": "ssh"}+ ]+ }+ },+ "AppSg": {+ "Type": "AWS::EC2::SecurityGroup",+ "Properties": {"GroupDescription": "app", "VpcId": {"Ref": "Vpc"}}+ },+ "AppFromWeb": {+ "Type": "AWS::EC2::SecurityGroupIngress",+ "Properties": {+ "GroupId": {"Fn::GetAtt": ["AppSg", "GroupId"]},+ "IpProtocol": "tcp",+ "FromPort": 8080,+ "ToPort": 8080,+ "SourceSecurityGroupId": {"Fn::GetAtt": ["WebSg", "GroupId"]}+ }+ },+ "WebEgress": {+ "Type": "AWS::EC2::SecurityGroupEgress",+ "Properties": {+ "GroupId": {"Fn::GetAtt": ["WebSg", "GroupId"]},+ "IpProtocol": "tcp",+ "FromPort": 443,+ "ToPort": 443,+ "CidrIp": "10.50.0.0/16"+ }+ }+ },+ "Outputs": {+ "WebSgId": {"Value": {"Fn::GetAtt": ["WebSg", "GroupId"]}},+ "AppSgId": {"Value": {"Fn::GetAtt": ["AppSg", "GroupId"]}}+ }+ }+ """;++ String created = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();+ String stackId = between(created, "<StackId>", "</StackId>");++ String describe = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))+ .extract().asString();++ String webSg = between(describe, "<OutputKey>WebSgId</OutputKey>", "</member>");+ webSg = between(webSg, "<OutputValue>", "</OutputValue>");+ String appSg = between(describe, "<OutputKey>AppSgId</OutputKey>", "</member>");+ appSg = between(appSg, "<OutputValue>", "</OutputValue>");++ // Inline SSH ingress exists on WebSg.+ given()+ .formParam("Action", "DescribeSecurityGroups")+ .formParam("GroupId.1", webSg)+ .header("Authorization", EC2_AUTH)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<fromPort>22</fromPort>"))+ .body(containsString("0.0.0.0/0"))+ .body(containsString("<fromPort>443</fromPort>"));++ // Standalone ingress referencing WebSg exists on AppSg.+ given()+ .formParam("Action", "DescribeSecurityGroups")+ .formParam("GroupId.1", appSg)+ .header("Authorization", EC2_AUTH)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<fromPort>8080</fromPort>"))+ .body(containsString(webSg));++ // Revoking rules whose group is deleted along with them must not fail the stack.+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DeleteStack")+ .formParam("StackName", stackName)+ .when().post("/").then().statusCode(200);+ assertTrue(awaitStackStatus(stackId, "DELETE_COMPLETE"),+ "stack did not reach DELETE_COMPLETE");+ }++ @Test+ void inlineIpv6RuleKeepsItsDescription() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "cfn-sgrules-v6-" + suffix;+ String template = """+ {+ "Resources": {+ "V6Sg": {+ "Type": "AWS::EC2::SecurityGroup",+ "Properties": {+ "GroupDescription": "v6",+ "SecurityGroupIngress": [+ {"IpProtocol": "tcp", "FromPort": 22, "ToPort": 22,+ "CidrIpv6": "2001:db8:1992::/48", "Description": "ssh over v6"}+ ]+ }+ }+ },+ "Outputs": {"SgId": {"Value": {"Fn::GetAtt": ["V6Sg", "GroupId"]}}}+ }+ """;+ createStack(stackName, template);+ String sgId = output(stackName, "SgId");++ // The description travels with the ipv6 range, not just the ipv4 one.+ given()+ .formParam("Action", "DescribeSecurityGroups")+ .formParam("GroupId.1", sgId)+ .header("Authorization", EC2_AUTH)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<cidrIpv6>2001:db8:1992::/48</cidrIpv6>"))+ .body(containsString("<description>ssh over v6</description>"));+ }++ /**+ * A standalone rule can target a group that is not part of the stack. Deleting the stack has to+ * revoke that rule — and only that rule, not the group's own rule that shares its ports.+ */+ @Test+ void standaloneRuleOnAForeignGroupIsRevokedWithTheStack() throws InterruptedException {+ String suffix = Long.toString(System.nanoTime(), 36);+ String groupId = createSecurityGroup("foreign-sg-" + suffix);+ authorizeIngress(groupId, "10.1.0.0/16");++ String stackName = "cfn-sgrules-delete-" + suffix;+ createStack(stackName, standaloneIngressTemplate(groupId, "10.2.0.0/16"));+ assertTrue(describeGroup(groupId).contains("<cidrIp>10.2.0.0/16</cidrIp>"),+ "stack should have authorized its rule on the foreign group");++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DeleteStack")+ .formParam("StackName", stackName)+ .when().post("/").then().statusCode(200);++ // DeleteStack is asynchronous.+ String group = null;+ for (int i = 0; i < 100; i++) {+ group = describeGroup(groupId);+ if (!group.contains("<cidrIp>10.2.0.0/16</cidrIp>")) {+ break;+ }+ Thread.sleep(50);+ }+ assertFalse(group.contains("<cidrIp>10.2.0.0/16</cidrIp>"),+ "stack deletion left the standalone rule on the group");+ assertTrue(group.contains("<cidrIp>10.1.0.0/16</cidrIp>"),+ "stack deletion revoked the group's own rule, which shares protocol and ports");++ // The rule record goes too, so DescribeSecurityGroupRules does not report a revoked rule.+ String rules = given()+ .formParam("Action", "DescribeSecurityGroupRules")+ .formParam("Filter.1.Name", "group-id")+ .formParam("Filter.1.Value.1", groupId)+ .header("Authorization", EC2_AUTH)+ .when().post("/").then().statusCode(200).extract().asString();+ assertEquals(0, occurrences(rules, "<cidrIpv4>10.2.0.0/16</cidrIpv4>"));+ assertEquals(1, occurrences(rules, "<cidrIpv4>10.1.0.0/16</cidrIpv4>"));+ }++ /** Re-running a template must not stack up duplicate permissions, or orphan replaced ones. */+ @Test+ void updateNeitherDuplicatesNorOrphansTheRule() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String groupId = createSecurityGroup("update-sg-" + suffix);+ String stackName = "cfn-sgrules-update-" + suffix;++ createStack(stackName, standaloneIngressTemplate(groupId, "10.3.0.0/16"));+ assertEquals(1, occurrences(describeGroup(groupId), "<cidrIp>10.3.0.0/16</cidrIp>"));++ // Unchanged template: the append-only authorize API would double the permission.+ updateStack(stackName, standaloneIngressTemplate(groupId, "10.3.0.0/16"));+ assertEquals(1, occurrences(describeGroup(groupId), "<cidrIp>10.3.0.0/16</cidrIp>"),+ "update duplicated an unchanged standalone rule");++ // Changed template: the old permission must go with it.+ updateStack(stackName, standaloneIngressTemplate(groupId, "10.4.0.0/16"));+ String group = describeGroup(groupId);+ assertEquals(1, occurrences(group, "<cidrIp>10.4.0.0/16</cidrIp>"));+ assertEquals(0, occurrences(group, "<cidrIp>10.3.0.0/16</cidrIp>"),+ "update left the replaced permission behind");+ }++ /** 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++) {+ String xml = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackId)+ .when().post("/").then().extract().asString();+ if (xml.contains("<StackStatus>" + status + "</StackStatus>")) {+ return true;+ }+ Thread.sleep(50);+ }+ return false;+ }++ private static String standaloneIngressTemplate(String groupId, String cidr) {+ return """+ {+ "Resources": {+ "Rule": {+ "Type": "AWS::EC2::SecurityGroupIngress",+ "Properties": {+ "GroupId": "%s",+ "IpProtocol": "tcp",+ "FromPort": 9100,+ "ToPort": 9100,+ "CidrIp": "%s"+ }+ }+ }+ }+ """.formatted(groupId, cidr);+ }++ /** Creates the stack and returns its id, which is how a deleted stack is described. */+ private static String createStack(String stackName, String template) {+ String created = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when().post("/").then().statusCode(200).extract().asString();+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when().post("/").then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));+ return between(created, "<StackId>", "</StackId>");+ }++ private static void updateStack(String stackName, String template) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "UpdateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when().post("/").then().statusCode(200);+ }++ private static String output(String stackName, String key) {+ String describe = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when().post("/").then().statusCode(200).extract().asString();+ String member = between(describe, "<OutputKey>" + key + "</OutputKey>", "</member>");+ return between(member, "<OutputValue>", "</OutputValue>");+ }++ private static String createSecurityGroup(String groupName) {+ String response = given()+ .formParam("Action", "CreateSecurityGroup")+ .formParam("GroupName", groupName)+ .formParam("GroupDescription", "not managed by the stack")+ .header("Authorization", EC2_AUTH)+ .when().post("/").then().statusCode(200).extract().asString();+ return between(response, "<groupId>", "</groupId>");+ }++ private static void authorizeIngress(String groupId, String cidr) {+ given()+ .formParam("Action", "AuthorizeSecurityGroupIngress")+ .formParam("GroupId", groupId)+ .formParam("IpPermissions.1.IpProtocol", "tcp")+ .formParam("IpPermissions.1.FromPort", "9100")+ .formParam("IpPermissions.1.ToPort", "9100")+ .formParam("IpPermissions.1.IpRanges.1.CidrIp", cidr)+ .header("Authorization", EC2_AUTH)+ .when().post("/").then().statusCode(200);+ }++ private static String describeGroup(String groupId) {+ return given()+ .formParam("Action", "DescribeSecurityGroups")+ .formParam("GroupId.1", groupId)+ .header("Authorization", EC2_AUTH)+ .when().post("/").then().statusCode(200).extract().asString();+ }++ private static int occurrences(String haystack, String needle) {+ int count = 0;+ for (int i = haystack.indexOf(needle); i >= 0; i = haystack.indexOf(needle, i + needle.length())) {+ count++;+ }+ return count;+ }++ private static String between(String haystack, String open, String close) {+ int i = haystack.indexOf(open);+ int j = haystack.indexOf(close, i + open.length());+ return haystack.substring(i + open.length(), j);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupRuleCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupRuleCfnProvisionerTest.javanew file mode 100644index 0000000000..dfa0e5be74--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupRuleCfnProvisionerTest.java@@ -0,0 +1,411 @@+package io.github.hectorvent.floci.services.cloudformation.provisioners;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+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;+import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;+import io.github.hectorvent.floci.services.ec2.Ec2Service;+import io.github.hectorvent.floci.services.ec2.model.IpPermission;+import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;+import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;+import org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;++import java.util.HashMap;+import java.util.List;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+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.eq;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.inOrder;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++/**+ * The standalone security-group rule provisioner in isolation: property mapping, the+ * revoke-before-authorize that keeps UpdateStack from duplicating rules, and the delete that keeps a+ * rule from outliving its stack on a group that survives it (issue #1992).+ */+class Ec2SecurityGroupRuleCfnProvisionerTest {++ private static final String INGRESS = "AWS::EC2::SecurityGroupIngress";+ private static final String EGRESS = "AWS::EC2::SecurityGroupEgress";++ private final Ec2Service ec2 = mock(Ec2Service.class);+ private final Ec2SecurityGroupRuleCfnProvisioner provisioner = new Ec2SecurityGroupRuleCfnProvisioner(ec2);+ private final ObjectMapper mapper = new ObjectMapper();++ private ProvisionContext ctx() {+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);+ when(engine.resolve(any())).thenAnswer(inv -> {+ JsonNode node = inv.getArgument(0);+ return node == null ? null : node.asText();+ });+ return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");+ }++ private StackResource resource(String type, String logicalId) {+ StackResource r = new StackResource();+ r.setLogicalId(logicalId);+ r.setResourceType(type);+ r.setAttributes(new HashMap<>());+ return r;+ }++ private SecurityGroupRule rule(String id) {+ SecurityGroupRule rule = new SecurityGroupRule();+ rule.setSecurityGroupRuleId(id);+ return rule;+ }++ @SuppressWarnings("unchecked")+ private IpPermission authorizedIngress() {+ ArgumentCaptor<List<IpPermission>> perms = ArgumentCaptor.forClass(List.class);+ verify(ec2).authorizeSecurityGroupIngress(eq("us-east-1"), anyString(), perms.capture());+ return perms.getValue().get(0);+ }++ @Test+ void ingressAuthorizesCidrRuleAndExposesRuleId() {+ when(ec2.authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-123"), anyList()))+ .thenReturn(List.of(rule("sgr-abc")));+ StackResource r = resource(INGRESS, "WebIngress");+ ObjectNode props = mapper.createObjectNode()+ .put("GroupId", "sg-123")+ .put("IpProtocol", "tcp")+ .put("FromPort", 443)+ .put("ToPort", 443)+ .put("CidrIp", "10.0.0.0/16")+ .put("Description", "https from vpc");++ provisioner.provision(r, props, ctx());++ assertEquals("sgr-abc", r.getPhysicalId());+ assertEquals("sgr-abc", r.getAttributes().get("Id"));+ IpPermission perm = authorizedIngress();+ assertEquals("tcp", perm.getIpProtocol());+ assertEquals(443, perm.getFromPort().intValue());+ assertEquals(443, perm.getToPort().intValue());+ assertEquals("10.0.0.0/16", perm.getIpRanges().get(0).getCidrIp());+ assertEquals("https from vpc", perm.getIpRanges().get(0).getDescription());+ verify(ec2, never()).authorizeSecurityGroupEgress(anyString(), anyString(), anyList());+ }++ @Test+ void egressGoesToTheEgressApi() {+ when(ec2.authorizeSecurityGroupEgress(eq("us-east-1"), eq("sg-123"), anyList()))+ .thenReturn(List.of(rule("sgr-egr")));+ StackResource r = resource(EGRESS, "WebEgress");+ ObjectNode props = mapper.createObjectNode()+ .put("GroupId", "sg-123")+ .put("IpProtocol", "tcp")+ .put("FromPort", 80)+ .put("ToPort", 80)+ .put("CidrIp", "0.0.0.0/0");++ provisioner.provision(r, props, ctx());++ assertEquals("sgr-egr", r.getPhysicalId());+ verify(ec2).authorizeSecurityGroupEgress(eq("us-east-1"), eq("sg-123"), anyList());+ verify(ec2, never()).authorizeSecurityGroupIngress(anyString(), anyString(), anyList());+ }++ @Test+ void ipv6RuleKeepsItsDescription() {+ when(ec2.authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-123"), anyList()))+ .thenReturn(List.of(rule("sgr-v6")));+ StackResource r = resource(INGRESS, "V6Ingress");+ ObjectNode props = mapper.createObjectNode()+ .put("GroupId", "sg-123")+ .put("IpProtocol", "tcp")+ .put("FromPort", 22)+ .put("ToPort", 22)+ .put("CidrIpv6", "::/0")+ .put("Description", "ssh over v6");++ provisioner.provision(r, props, ctx());++ IpPermission perm = authorizedIngress();+ assertEquals("::/0", perm.getIpv6Ranges().get(0).getCidrIpv6());+ assertEquals("ssh over v6", perm.getIpv6Ranges().get(0).getDescription());+ assertTrue(perm.getIpRanges().isEmpty());+ }++ @Test+ void sourceSecurityGroupBecomesAPeerPair() {+ when(ec2.authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-app"), anyList()))+ .thenReturn(List.of(rule("sgr-peer")));+ StackResource r = resource(INGRESS, "AppFromWeb");+ ObjectNode props = mapper.createObjectNode()+ .put("GroupId", "sg-app")+ .put("IpProtocol", "tcp")+ .put("FromPort", 8080)+ .put("ToPort", 8080)+ .put("SourceSecurityGroupId", "sg-web")+ .put("Description", "app from web");++ provisioner.provision(r, props, ctx());++ IpPermission perm = authorizedIngress();+ assertEquals("sg-web", perm.getUserIdGroupPairs().get(0).getGroupId());+ // Ec2Service reads the description off the pair, so dropping it here loses the+ // template's text from DescribeSecurityGroupRules, as it would for a cidr peer.+ assertEquals("app from web", perm.getUserIdGroupPairs().get(0).getDescription());+ }++ @Test+ @SuppressWarnings("unchecked")+ void destinationSecurityGroupBecomesAPeerPair() {+ when(ec2.authorizeSecurityGroupEgress(eq("us-east-1"), eq("sg-web"), anyList()))+ .thenReturn(List.of(rule("sgr-peer")));+ StackResource r = resource(EGRESS, "WebToApp");+ ObjectNode props = mapper.createObjectNode()+ .put("GroupId", "sg-web")+ .put("IpProtocol", "tcp")+ .put("FromPort", 8080)+ .put("ToPort", 8080)+ .put("DestinationSecurityGroupId", "sg-app");++ provisioner.provision(r, props, ctx());++ ArgumentCaptor<List<IpPermission>> perms = ArgumentCaptor.forClass(List.class);+ verify(ec2).authorizeSecurityGroupEgress(eq("us-east-1"), eq("sg-web"), perms.capture());+ assertEquals("sg-app", perms.getValue().get(0).getUserIdGroupPairs().get(0).getGroupId());+ }++ @Test+ void missingProtocolDefaultsToAll() {+ when(ec2.authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-123"), anyList()))+ .thenReturn(List.of(rule("sgr-all")));+ StackResource r = resource(INGRESS, "AllIngress");+ ObjectNode props = mapper.createObjectNode().put("GroupId", "sg-123").put("CidrIp", "10.0.0.0/8");++ provisioner.provision(r, props, ctx());++ IpPermission perm = authorizedIngress();+ assertEquals("-1", perm.getIpProtocol());+ assertNull(perm.getFromPort());+ assertNull(perm.getToPort());+ }++ @Test+ void groupNameResolvesToTheGroupId() {+ SecurityGroup sg = new SecurityGroup();+ sg.setGroupId("sg-by-name");+ sg.setGroupName("legacy-group");+ when(ec2.describeSecurityGroups(eq("us-east-1"), eq(List.of()), eq(List.of("legacy-group")), any()))+ .thenReturn(List.of(sg));+ when(ec2.authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-by-name"), anyList()))+ .thenReturn(List.of(rule("sgr-named")));+ StackResource r = resource(INGRESS, "NamedIngress");+ ObjectNode props = mapper.createObjectNode()+ .put("GroupName", "legacy-group")+ .put("IpProtocol", "tcp")+ .put("FromPort", 25)+ .put("ToPort", 25)+ .put("CidrIp", "10.0.0.0/8");++ provisioner.provision(r, props, ctx());++ assertEquals("sgr-named", r.getPhysicalId());+ verify(ec2).authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-by-name"), anyList());+ }++ @Test+ void updateAuthorizesTheNewRuleBeforeRevokingThePrevious() {+ when(ec2.authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-123"), anyList()))+ .thenReturn(List.of(rule("sgr-new")));+ StackResource r = resource(INGRESS, "WebIngress");+ r.setPhysicalId("sgr-old"); // what the previous stack execution created+ ObjectNode props = mapper.createObjectNode()+ .put("GroupId", "sg-123")+ .put("IpProtocol", "tcp")+ .put("FromPort", 443)+ .put("ToPort", 443)+ .put("CidrIp", "10.0.0.0/16");++ provisioner.provision(r, props, ctx());++ var order = inOrder(ec2);+ order.verify(ec2).authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-123"), anyList());+ order.verify(ec2).deleteSecurityGroupRule("us-east-1", "sgr-old");+ assertEquals("sgr-new", r.getPhysicalId());+ }++ @Test+ void aFailedUpdateLeavesThePreviousRuleInPlace() {+ // Revoking first would leave the group with neither rule, and rollback keeps the old+ // physical id without recreating its permission.+ when(ec2.authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-123"), anyList()))+ .thenThrow(new AwsException("InvalidPermission.Malformed", "bad rule", 400));+ StackResource r = resource(INGRESS, "WebIngress");+ r.setPhysicalId("sgr-old");+ ObjectNode props = mapper.createObjectNode().put("GroupId", "sg-123").put("CidrIp", "10.0.0.0/16");++ assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));++ verify(ec2, never()).deleteSecurityGroupRule(anyString(), anyString());+ assertEquals("sgr-old", r.getPhysicalId());+ }++ @Test+ void createDoesNotRevokeAnything() {+ when(ec2.authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-123"), anyList()))+ .thenReturn(List.of(rule("sgr-new")));+ StackResource r = resource(INGRESS, "WebIngress");+ ObjectNode props = mapper.createObjectNode().put("GroupId", "sg-123").put("CidrIp", "10.0.0.0/8");++ provisioner.provision(r, props, ctx());++ verify(ec2, never()).deleteSecurityGroupRule(anyString(), anyString());+ }++ @Test+ void deleteRevokesTheRule() {+ provisioner.delete(INGRESS, "sgr-abc", "us-east-1");+ verify(ec2).deleteSecurityGroupRule("us-east-1", "sgr-abc");+ }++ @Test+ void deleteOfANonRuleIdIsANoOp() {+ // The logical-id fallback, or a null id on a resource that never got provisioned.+ provisioner.delete(EGRESS, "WebEgress", "us-east-1");+ provisioner.delete(EGRESS, null, "us-east-1");+ verifyNoInteractions(ec2);+ }++ @Test+ void deletePropagatesServiceFailures() {+ // deleteSecurityGroupRule already absorbs an unrecorded rule and an absent group, so a+ // throw is a real failure. Swallowing it reported the resource deleted while its permission+ // was still on the group.+ doThrow(new AwsException("InternalFailure", "storage down", 500))+ .when(ec2).deleteSecurityGroupRule("us-east-1", "sgr-abc");++ AwsException failure = assertThrows(AwsException.class,+ () -> provisioner.delete(INGRESS, "sgr-abc", "us-east-1"));++ assertEquals("InternalFailure", failure.getErrorCode());+ }++ @Test+ void severalPeerPropertiesAreRejected() {+ // "You must specify exactly one of the following sources." Naming several authorized a rule+ // record per peer while only the first id was kept as the physical id, so delete revoked one+ // of them and the rest stayed on the group.+ StackResource r = resource(INGRESS, "WebIngress");+ ObjectNode props = mapper.createObjectNode()+ .put("GroupId", "sg-123")+ .put("IpProtocol", "tcp")+ .put("CidrIp", "10.0.0.0/16")+ .put("CidrIpv6", "::/0");++ AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));++ assertEquals("ValidationError", failure.getErrorCode());+ verify(ec2, never()).authorizeSecurityGroupIngress(anyString(), anyString(), anyList());+ }++ @Test+ void aPeerNamedByGroupNameCountsAsASource() {+ // The schema lists SourceSecurityGroupName beside the id form. Counting only the id meant+ // a template naming its peer by name was rejected for naming no source.+ when(ec2.authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-app"), anyList()))+ .thenReturn(List.of(rule("sgr-byname")));+ StackResource r = resource(INGRESS, "AppFromWeb");+ ObjectNode props = mapper.createObjectNode()+ .put("GroupId", "sg-app")+ .put("IpProtocol", "tcp")+ .put("FromPort", 8080)+ .put("ToPort", 8080)+ .put("SourceSecurityGroupName", "web-sg")+ .put("SourceSecurityGroupOwnerId", "111111111111");++ provisioner.provision(r, props, ctx());++ // Handed over as a name. Ec2Service resolves it to an id on authorize, before it records+ // the rule, so delete still matches on the resolved id.+ UserIdGroupPair pair = authorizedIngress().getUserIdGroupPairs().get(0);+ assertEquals("web-sg", pair.getGroupName());+ assertNull(pair.getGroupId());+ assertEquals("111111111111", pair.getUserId());+ }++ @Test+ void aPeerNamedByBothIdAndNameStillCountsAsOneSource() {+ when(ec2.authorizeSecurityGroupIngress(eq("us-east-1"), eq("sg-app"), anyList()))+ .thenReturn(List.of(rule("sgr-both")));+ StackResource r = resource(INGRESS, "AppFromWeb");+ ObjectNode props = mapper.createObjectNode()+ .put("GroupId", "sg-app")+ .put("IpProtocol", "tcp")+ .put("SourceSecurityGroupId", "sg-web")+ .put("SourceSecurityGroupName", "web-sg");++ provisioner.provision(r, props, ctx());++ // One peer named two ways is still one source, and the id wins.+ UserIdGroupPair pair = authorizedIngress().getUserIdGroupPairs().get(0);+ assertEquals("sg-web", pair.getGroupId());+ assertNull(pair.getGroupName());+ }++ @Test+ void aRuleNamingNoSourceAtAllIsRejected() {+ // Exactly one, so none is as invalid as several. Accepting zero sent an IpPermission+ // naming no peer, which the stack then reported as successfully provisioned.+ StackResource r = resource(INGRESS, "WebIngress");+ ObjectNode props = mapper.createObjectNode()+ .put("GroupId", "sg-123")+ .put("IpProtocol", "tcp")+ .put("FromPort", 443)+ .put("ToPort", 443);++ AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));++ assertEquals("ValidationError", failure.getErrorCode());+ verify(ec2, never()).authorizeSecurityGroupIngress(anyString(), anyString(), anyList());+ }++ @Test+ void aCidrAndAPeerGroupTogetherAreRejected() {+ StackResource r = resource(EGRESS, "WebEgress");+ ObjectNode props = mapper.createObjectNode()+ .put("GroupId", "sg-123")+ .put("IpProtocol", "tcp")+ .put("CidrIp", "10.0.0.0/16")+ .put("DestinationSecurityGroupId", "sg-peer");++ AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));++ assertEquals("ValidationError", failure.getErrorCode());+ verify(ec2, never()).authorizeSecurityGroupEgress(anyString(), anyString(), anyList());+ }++ @Test+ void unknownResourceTypeIsRejected() {+ StackResource r = resource("AWS::EC2::SecurityGroup", "Sg");+ assertThrows(IllegalStateException.class,+ () -> provisioner.provision(r, mapper.createObjectNode(), ctx()));+ }++ @Test+ void registryRoutesBothStandaloneTypes() {+ CloudFormationResourceRegistry registry = new CloudFormationResourceRegistry(List.of(provisioner));+ assertEquals(provisioner, registry.forType(INGRESS).orElseThrow());+ assertEquals(provisioner, registry.forType(EGRESS).orElseThrow());+ assertTrue(registry.forType("AWS::EC2::SecurityGroup").isEmpty());+ }+}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.javaindex 2eeae3b1e2..28cafc32b3 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@@ -11,6 +11,10 @@ import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;import io.github.hectorvent.floci.services.ec2.model.Image;import io.github.hectorvent.floci.services.ec2.model.Instance;+import io.github.hectorvent.floci.services.ec2.model.IpPermission;+import io.github.hectorvent.floci.services.ec2.model.Ipv6Range;+import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;+import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;@@ -774,6 +778,103 @@ class Ec2ServiceTest {assertEquals("available", detached.getState());}+ @Test+ void deletingAnIpv6RuleRevokesThatRangeAndNotAnotherOnTheSamePort() {+ Ec2Service service = sgService();+ String groupId = service.createSecurityGroup("us-east-1", "web", "web", null).getGroupId();+ String first = onlyRuleId(service.authorizeSecurityGroupIngress("us-east-1", groupId,+ List.of(ipv6Permission("2001:db8:1::/64"))));+ String second = onlyRuleId(service.authorizeSecurityGroupIngress("us-east-1", groupId,+ List.of(ipv6Permission("2001:db8:2::/64"))));++ service.deleteSecurityGroupRule("us-east-1", second);++ // The one that was asked for is gone and the other survives — protocol and ports are+ // identical, so a match on those alone would have taken the wrong one.+ assertEquals(List.of(first), ingressRuleIds(service, groupId));+ List<String> cidrs = service.describeSecurityGroups("us-east-1", List.of(groupId), List.of(), Map.of())+ .getFirst().getIpPermissions().stream()+ .flatMap(p -> p.getIpv6Ranges().stream())+ .map(Ipv6Range::getCidrIpv6).toList();+ assertEquals(List.of("2001:db8:1::/64"), cidrs);+ }++ @Test+ void deletingAPeerGroupRuleRevokesThatPeerAndNotAnotherOnTheSamePort() {+ Ec2Service service = sgService();+ String groupId = service.createSecurityGroup("us-east-1", "web", "web", null).getGroupId();+ String first = onlyRuleId(service.authorizeSecurityGroupIngress("us-east-1", groupId,+ List.of(peerPermission("sg-peer-a"))));+ String second = onlyRuleId(service.authorizeSecurityGroupIngress("us-east-1", groupId,+ List.of(peerPermission("sg-peer-b"))));++ service.deleteSecurityGroupRule("us-east-1", second);++ assertEquals(List.of(first), ingressRuleIds(service, groupId));+ List<String> peers = service.describeSecurityGroups("us-east-1", List.of(groupId), List.of(), Map.of())+ .getFirst().getIpPermissions().stream()+ .flatMap(p -> p.getUserIdGroupPairs().stream())+ .map(UserIdGroupPair::getGroupId).toList();+ assertEquals(List.of("sg-peer-a"), peers);+ }++ @Test+ void ruleRecordsCarryTheirPeerIdentity() {+ Ec2Service service = sgService();+ String groupId = service.createSecurityGroup("us-east-1", "web", "web", null).getGroupId();+ service.authorizeSecurityGroupIngress("us-east-1", groupId, List.of(peerPermission("sg-peer-a")));+ service.authorizeSecurityGroupIngress("us-east-1", groupId, List.of(ipv6Permission("2001:db8:1::/64")));++ List<SecurityGroupRule> rules =+ service.describeSecurityGroupRules("us-east-1", List.of(groupId), List.of());++ assertEquals(1, rules.stream().filter(r -> r.getReferencedGroupInfo() != null+ && "sg-peer-a".equals(r.getReferencedGroupInfo().getGroupId())).count());+ assertEquals(1, rules.stream().filter(r -> "2001:db8:1::/64".equals(r.getCidrIpv6())).count());+ }++ /** 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())+ .stream().filter(r -> !r.isEgress())+ .map(SecurityGroupRule::getSecurityGroupRuleId).toList();+ }++ private static String onlyRuleId(List<SecurityGroupRule> rules) {+ assertEquals(1, rules.size());+ return rules.getFirst().getSecurityGroupRuleId();+ }++ private static IpPermission ipv6Permission(String cidr6) {+ IpPermission perm = basePermission();+ Ipv6Range range = new Ipv6Range();+ range.setCidrIpv6(cidr6);+ perm.getIpv6Ranges().add(range);+ return perm;+ }++ private static IpPermission peerPermission(String peerGroupId) {+ IpPermission perm = basePermission();+ UserIdGroupPair pair = new UserIdGroupPair();+ pair.setGroupId(peerGroupId);+ perm.getUserIdGroupPairs().add(pair);+ return perm;+ }++ private static IpPermission basePermission() {+ IpPermission perm = new IpPermission();+ perm.setIpProtocol("tcp");+ perm.setFromPort(443);+ perm.setToPort(443);+ return perm;+ }++ private static Ec2Service sgService() {+ return new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class),+ mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());+ }+// =========================================================================// Managed prefix lists// =========================================================================