Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ec2): allow a security group rule to take a prefix list as its source (#2271)
Michal Schreiberdfcd49219869
diff --git a/compatibility-tests/sdk-test-awscli/test/ec2.bats b/compatibility-tests/sdk-test-awscli/test/ec2.batsindex 90aec31a82..be536387be 100644--- a/compatibility-tests/sdk-test-awscli/test/ec2.bats+++ b/compatibility-tests/sdk-test-awscli/test/ec2.bats@@ -146,6 +146,46 @@ create_prefix_list() {[ "$id" = "pl-63a5400a" ]}+# ─── security group rules sourced from a prefix list ────────────────────────++@test "EC2: authorize a security group rule from a prefix list" {+ create_prefix_list+ local sg+ sg=$(aws_cmd ec2 create-security-group --group-name "$(unique_name bats-sg)" \+ --description "prefix list source" --query 'GroupId' --output text)++ run aws_cmd ec2 authorize-security-group-ingress --group-id "$sg" \+ --ip-permissions "IpProtocol=tcp,FromPort=5432,ToPort=5432,PrefixListIds=[{PrefixListId=$PREFIX_LIST_ID,Description=from-corp}]"+ assert_success+ pl=$(json_get "$output" '.SecurityGroupRules[0].PrefixListId')+ [ "$pl" = "$PREFIX_LIST_ID" ]++ run aws_cmd ec2 describe-security-groups --group-ids "$sg"+ assert_success+ nested=$(json_get "$output" '.SecurityGroups[0].IpPermissions[0].PrefixListIds[0].PrefixListId')+ [ "$nested" = "$PREFIX_LIST_ID" ]++ run aws_cmd ec2 describe-security-group-rules --filters "Name=group-id,Values=$sg"+ assert_success+ found=$(echo "$output" | jq --arg pl "$PREFIX_LIST_ID" '.SecurityGroupRules | any(.PrefixListId == $pl)')+ [ "$found" = "true" ]++ aws_cmd ec2 delete-security-group --group-id "$sg" >/dev/null 2>&1 || true+}++@test "EC2: authorizing from an unknown prefix list is rejected" {+ local sg+ sg=$(aws_cmd ec2 create-security-group --group-name "$(unique_name bats-sg)" \+ --description "unknown prefix list" --query 'GroupId' --output text)++ run aws_cmd ec2 authorize-security-group-ingress --group-id "$sg" \+ --ip-permissions 'IpProtocol=tcp,FromPort=1,ToPort=1,PrefixListIds=[{PrefixListId=pl-doesnotexist}]'+ assert_failure+ assert_output --partial "InvalidPrefixListID.NotFound"++ aws_cmd ec2 delete-security-group --group-id "$sg" >/dev/null 2>&1 || true+}+# Creates a VPC holding a source and a target security group, and sets SG_VPC_ID,# SG_SOURCE_ID and SG_TARGET_ID.create_sg_pair() {diff --git a/docs/services/ec2.md b/docs/services/ec2.mdindex 122fcd3a27..8ca96f5e42 100644--- a/docs/services/ec2.md+++ b/docs/services/ec2.md@@ -303,6 +303,13 @@ additions, so one call can replace an entry's description by removing and re-addCreation is synchronous: a new list is returned as `create-complete` rather than passingthrough `create-in-progress`, since nothing about it is slow locally.+A security group rule can take a prefix list as its source instead of a CIDR. Pass it as+`IpPermissions.N.PrefixListIds.M.PrefixListId`, optionally with a `Description`; AWS emits one rule+per source, so a permission naming both CIDRs and prefix lists expands to a rule for each. The+resulting rule carries `prefixListId` in place of `cidrIpv4`, and `DescribeSecurityGroups` nests+the reference under the permission as `prefixListIds`. Authorizing against a list that does not+exist returns `InvalidPrefixListID.NotFound`, so a typo cannot leave a rule pointing at nothing.+### NAT Gateways| Action | Description |diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.javaindex 52e1e1f530..44928bae4a 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java@@ -336,17 +336,27 @@ public class Ec2QueryHandler {List<IpPermission> perms = new ArrayList<>();for (int i = 1; ; i++) {String proto = p.getFirst(prefix + "." + i + ".IpProtocol");- if (proto == null) break;+ if (proto == null) {+ break;+ }IpPermission perm = new IpPermission();perm.setIpProtocol(proto);String fromPort = p.getFirst(prefix + "." + i + ".FromPort");String toPort = p.getFirst(prefix + "." + i + ".ToPort");- if (fromPort != null) perm.setFromPort(Integer.parseInt(fromPort));- if (toPort != null) perm.setToPort(Integer.parseInt(toPort));+ if (fromPort != null) {+ perm.setFromPort(Integer.parseInt(fromPort));+ }+ if (toPort != null) {+ perm.setToPort(Integer.parseInt(toPort));+ }for (int j = 1; ; j++) {String cidr = p.getFirst(prefix + "." + i + ".IpRanges." + j + ".CidrIp");- if (cidr == null) cidr = p.getFirst(prefix + "." + i + ".IpRanges." + j);- if (cidr == null) break;+ if (cidr == null) {+ cidr = p.getFirst(prefix + "." + i + ".IpRanges." + j);+ }+ if (cidr == null) {+ break;+ }String desc = p.getFirst(prefix + "." + i + ".IpRanges." + j + ".Description");perm.getIpRanges().add(new IpRange(cidr, desc));}@@ -376,6 +386,14 @@ public class Ec2QueryHandler {pair.setDescription(desc);perm.getUserIdGroupPairs().add(pair);}+ for (int j = 1; ; j++) {+ String prefixListId = p.getFirst(prefix + "." + i + ".PrefixListIds." + j + ".PrefixListId");+ if (prefixListId == null) {+ break;+ }+ String desc = p.getFirst(prefix + "." + i + ".PrefixListIds." + j + ".Description");+ perm.getPrefixListIds().add(new PrefixListId(prefixListId, desc));+ }perms.add(perm);}return perms;@@ -2506,7 +2524,8 @@ public class Ec2QueryHandler {if (rule.getFromPort() != null) xml.elem("fromPort", String.valueOf(rule.getFromPort()));if (rule.getToPort() != null) xml.elem("toPort", String.valueOf(rule.getToPort()));xml.elem("cidrIpv4", rule.getCidrIpv4())- .elem("cidrIpv6", rule.getCidrIpv6());+ .elem("cidrIpv6", rule.getCidrIpv6())+ .elem("prefixListId", rule.getPrefixListId());// Guarded: unlike elem(), start()/end() emit even when every child is null, which would put// an empty <referencedGroupInfo/> on every CIDR rule.ReferencedSecurityGroup ref = rule.getReferencedGroupInfo();@@ -3008,7 +3027,14 @@ public class Ec2QueryHandler {.elem("description", g.getDescription()).end("item");}- xml.end("groups").end("item");+ xml.end("groups").start("prefixListIds");+ for (PrefixListId prefixList : perm.getPrefixListIds()) {+ xml.start("item")+ .elem("prefixListId", prefixList.getPrefixListId())+ .elem("description", prefixList.getDescription())+ .end("item");+ }+ xml.end("prefixListIds").end("item");}xml.end(wrapperTag);return xml.build();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 ebfc0dd4cd..c88e80a9a7 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@@ -58,6 +58,7 @@ import io.github.hectorvent.floci.services.ec2.model.NetworkAcl;import io.github.hectorvent.floci.services.ec2.model.NetworkAclAssociation;import io.github.hectorvent.floci.services.ec2.model.NetworkAclEntry;import io.github.hectorvent.floci.services.ec2.model.PrefixList;+import io.github.hectorvent.floci.services.ec2.model.PrefixListId;import io.github.hectorvent.floci.services.ec2.model.PrefixListEntry;import io.github.hectorvent.floci.services.ec2.model.Placement;import io.github.hectorvent.floci.services.ec2.model.ReferencedSecurityGroup;@@ -1682,6 +1683,7 @@ public class Ec2Service implements ContainerTeardown {List<SecurityGroupRule> rules = new ArrayList<>();synchronized (lockFor(key(region, groupId))) {SecurityGroup sg = getRequiredSecurityGroup(region, groupId);+ requireKnownPrefixLists(region, permissions);List<IpPermission> next = new ArrayList<>(sg.getIpPermissions());for (IpPermission perm : permissions) {resolveGroupReferences(region, sg.getVpcId(), perm);@@ -1700,6 +1702,7 @@ public class Ec2Service implements ContainerTeardown {List<SecurityGroupRule> rules = new ArrayList<>();synchronized (lockFor(key(region, groupId))) {SecurityGroup sg = getRequiredSecurityGroup(region, groupId);+ requireKnownPrefixLists(region, permissions);List<IpPermission> next = new ArrayList<>(sg.getIpPermissionsEgress());for (IpPermission perm : permissions) {resolveGroupReferences(region, sg.getVpcId(), perm);@@ -1716,6 +1719,12 @@ public class Ec2Service implements ContainerTeardown {* Flattens one permission into the {@link SecurityGroupRule} entries DescribeSecurityGroupRules* serves. AWS gives every rule exactly one source, so a permission carrying several sources fans* out into one rule each.+ *+ * <p>Deliberately does not validate the prefix lists it reads: authorize resolves every list a+ * request names before the first write. Re-checking per permission would reopen the+ * partial-write window, since a list can be deleted between the two checks — the group lock and+ * the prefix list lock are different monitors. The other callers pass a CIDR-only default egress+ * permission.*/private List<SecurityGroupRule> createRules(String region, String groupId, IpPermission perm, boolean egress) {List<SecurityGroupRule> rules = new ArrayList<>();@@ -1746,6 +1755,14 @@ public class Ec2Service implements ContainerTeardown {rules.add(rule);}}+ if (perm.getPrefixListIds() != null) {+ for (PrefixListId prefixList : perm.getPrefixListIds()) {+ SecurityGroupRule rule = newRule(groupId, perm, egress);+ rule.setPrefixListId(prefixList.getPrefixListId());+ rule.setDescription(prefixList.getDescription());+ rules.add(rule);+ }+ }// Real AWS rejects a permission with no source at all; Floci keeps accepting it, so it still// needs a rule to describe.if (rules.isEmpty()) {@@ -1757,6 +1774,21 @@ public class Ec2Service implements ContainerTeardown {return rules;}+ /**+ * Resolves every prefix list a request names before anything is written. AWS rejects the whole+ * call, so a permission carrying a valid CIDR alongside an unknown list must persist neither.+ */+ private void requireKnownPrefixLists(String region, List<IpPermission> permissions) {+ for (IpPermission perm : permissions) {+ if (perm.getPrefixListIds() == null) {+ continue;+ }+ for (PrefixListId prefixList : perm.getPrefixListIds()) {+ getRequiredManagedPrefixList(region, prefixList.getPrefixListId());+ }+ }+ }+private SecurityGroupRule newRule(String groupId, IpPermission perm, boolean egress) {SecurityGroupRule rule = new SecurityGroupRule();rule.setSecurityGroupRuleId("sgr-" + randomHex(17));@@ -1801,8 +1833,12 @@ public class Ec2Service implements ContainerTeardown {ensureDefaultResources(region);synchronized (lockFor(key(region, groupId))) {SecurityGroup sg = getRequiredSecurityGroup(region, groupId);- List<IpPermission> next = new ArrayList<>(sg.getIpPermissions());- next.removeIf(p -> matchesAnyPermission(p, permissions));+ // Authorize stores a group reference by id, so a revoke naming it by name alone has to+ // resolve the same way before the sources can be compared.+ for (IpPermission perm : permissions) {+ resolveGroupReferences(region, sg.getVpcId(), perm);+ }+ List<IpPermission> next = revokeSources(new ArrayList<>(sg.getIpPermissions()), permissions);sg.setIpPermissions(next);securityGroups.put(key(region, groupId), sg);}@@ -1813,8 +1849,10 @@ public class Ec2Service implements ContainerTeardown {ensureDefaultResources(region);synchronized (lockFor(key(region, groupId))) {SecurityGroup sg = getRequiredSecurityGroup(region, groupId);- List<IpPermission> next = new ArrayList<>(sg.getIpPermissionsEgress());- next.removeIf(p -> matchesAnyPermission(p, permissions));+ for (IpPermission perm : permissions) {+ resolveGroupReferences(region, sg.getVpcId(), perm);+ }+ List<IpPermission> next = revokeSources(new ArrayList<>(sg.getIpPermissionsEgress()), permissions);sg.setIpPermissionsEgress(next);securityGroups.put(key(region, groupId), sg);}@@ -1828,15 +1866,58 @@ public class Ec2Service implements ContainerTeardown {return sg;}- private boolean matchesAnyPermission(IpPermission existing, List<IpPermission> toRemove) {- for (IpPermission perm : toRemove) {- if (Objects.equals(existing.getIpProtocol(), perm.getIpProtocol())- && Objects.equals(existing.getFromPort(), perm.getFromPort())- && Objects.equals(existing.getToPort(), perm.getToPort())) {- return true;+ /**+ * Revocation is scoped to the sources it names, as on AWS: revoking one source leaves other+ * permissions sharing the same protocol and ports in place, and a permission that names+ * several sources loses only those revoked. A request naming no source at all still removes+ * the whole matching permission, which is how a bare protocol/port revoke behaves.+ *+ * <p>Returns the permissions that remain.+ */+ private List<IpPermission> revokeSources(List<IpPermission> existing, List<IpPermission> toRemove) {+ List<IpPermission> remaining = new ArrayList<>();+ for (IpPermission perm : existing) {+ boolean dropWholePermission = false;+ boolean hadSources = hasSources(perm);+ for (IpPermission removal : toRemove) {+ if (!sameProtocolAndPorts(perm, removal)) {+ continue;+ }+ if (!hasSources(removal)) {+ 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()+ .map(PrefixListId::getPrefixListId).toList();+ List<String> groups = removal.getUserIdGroupPairs().stream()+ .map(UserIdGroupPair::getGroupId).toList();+ perm.getIpRanges().removeIf(e -> cidrs.contains(e.getCidrIp()));+ perm.getIpv6Ranges().removeIf(e -> cidrsV6.contains(e.getCidrIpv6()));+ perm.getPrefixListIds().removeIf(e -> lists.contains(e.getPrefixListId()));+ perm.getUserIdGroupPairs().removeIf(e -> groups.contains(e.getGroupId()));+ }+ // A permission that had sources and has lost them all is gone; one that never had any+ // survives unless a sourceless revoke named it.+ if (!dropWholePermission && (!hadSources || hasSources(perm))) {+ remaining.add(perm);}}- return false;+ return remaining;+ }++ private boolean sameProtocolAndPorts(IpPermission a, IpPermission b) {+ return Objects.equals(a.getIpProtocol(), b.getIpProtocol())+ && Objects.equals(a.getFromPort(), b.getFromPort())+ && Objects.equals(a.getToPort(), b.getToPort());+ }++ private boolean hasSources(IpPermission perm) {+ return !perm.getIpRanges().isEmpty() || !perm.getIpv6Ranges().isEmpty()+ || !perm.getPrefixListIds().isEmpty() || !perm.getUserIdGroupPairs().isEmpty();}public List<SecurityGroupRule> describeSecurityGroupRules(String region, List<String> groupIds, List<String> ruleIds) {diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpPermission.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpPermission.javaindex 054849a98c..3743dbc7e9 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpPermission.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IpPermission.java@@ -16,6 +16,7 @@ public class IpPermission {private List<IpRange> ipRanges = new ArrayList<>();private List<Ipv6Range> ipv6Ranges = new ArrayList<>();private List<UserIdGroupPair> userIdGroupPairs = new ArrayList<>();+ private List<PrefixListId> prefixListIds = new ArrayList<>();public IpPermission() {}@@ -35,5 +36,8 @@ public class IpPermission {public void setIpv6Ranges(List<Ipv6Range> ipv6Ranges) { this.ipv6Ranges = ipv6Ranges; }public List<UserIdGroupPair> getUserIdGroupPairs() { return userIdGroupPairs; }++ public List<PrefixListId> getPrefixListIds() { return prefixListIds; }+ public void setPrefixListIds(List<PrefixListId> prefixListIds) { this.prefixListIds = prefixListIds; }public void setUserIdGroupPairs(List<UserIdGroupPair> userIdGroupPairs) { this.userIdGroupPairs = userIdGroupPairs; }}diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/PrefixListId.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/PrefixListId.javanew file mode 100644index 0000000000..b999764e31--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/PrefixListId.java@@ -0,0 +1,26 @@+package io.github.hectorvent.floci.services.ec2.model;++import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import io.quarkus.runtime.annotations.RegisterForReflection;++/** A prefix list reference inside an {@link IpPermission}, as AWS returns it under prefixListIds. */+@RegisterForReflection+@JsonIgnoreProperties(ignoreUnknown = true)+public class PrefixListId {++ private String prefixListId;+ private String description;++ public PrefixListId() {}++ public PrefixListId(String prefixListId, String description) {+ this.prefixListId = prefixListId;+ this.description = description;+ }++ public String getPrefixListId() { return prefixListId; }+ public void setPrefixListId(String prefixListId) { this.prefixListId = prefixListId; }++ public String getDescription() { return description; }+ public void setDescription(String description) { this.description = description; }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/SecurityGroupRule.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/SecurityGroupRule.javaindex ea11c1ae47..35f56e39db 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/model/SecurityGroupRule.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/SecurityGroupRule.java@@ -19,6 +19,8 @@ public class SecurityGroupRule {private Integer toPort;private String cidrIpv4;private String cidrIpv6;+ /** Set instead of a CIDR when the rule's source is a managed prefix list. */+ private String prefixListId;private ReferencedSecurityGroup referencedGroupInfo;private String description;private List<Tag> tags = new ArrayList<>();@@ -52,6 +54,9 @@ public class SecurityGroupRule {public String getCidrIpv6() { return cidrIpv6; }public void setCidrIpv6(String cidrIpv6) { this.cidrIpv6 = cidrIpv6; }+ public String getPrefixListId() { return prefixListId; }+ public void setPrefixListId(String prefixListId) { this.prefixListId = prefixListId; }+public ReferencedSecurityGroup getReferencedGroupInfo() { return referencedGroupInfo; }public void setReferencedGroupInfo(ReferencedSecurityGroup referencedGroupInfo) {this.referencedGroupInfo = referencedGroupInfo;diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2SecurityGroupPrefixListIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2SecurityGroupPrefixListIntegrationTest.javanew file mode 100644index 0000000000..6ad9199707--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2SecurityGroupPrefixListIntegrationTest.java@@ -0,0 +1,149 @@+package io.github.hectorvent.floci.services.ec2;++import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.emptyOrNullString;+import static org.hamcrest.Matchers.not;++/**+ * Security group rules whose source is a managed prefix list, over the EC2 Query protocol:+ * authorize, both read-back shapes, and the rejection of an unknown list.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class Ec2SecurityGroupPrefixListIntegrationTest {++ private static final String AUTH_HEADER =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";++ private static String prefixListId;+ private static String groupId;++ @Test+ @Order(1)+ void createThePrefixListAndGroup() {+ prefixListId = given()+ .formParam("Action", "CreateManagedPrefixList")+ .formParam("PrefixListName", "sg-source")+ .formParam("AddressFamily", "IPv4")+ .formParam("MaxEntries", "5")+ .formParam("Entry.1.Cidr", "10.0.0.0/8")+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(200)+ .extract().path("CreateManagedPrefixListResponse.prefixList.prefixListId");++ groupId = given()+ .formParam("Action", "CreateSecurityGroup")+ .formParam("GroupName", "prefix-list-consumer")+ .formParam("GroupDescription", "references a prefix list")+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(200)+ .extract().path("CreateSecurityGroupResponse.groupId");+ }++ @Test+ @Order(2)+ void authorizeIngressFromThePrefixList() {+ given()+ .formParam("Action", "AuthorizeSecurityGroupIngress")+ .formParam("GroupId", groupId)+ .formParam("IpPermissions.1.IpProtocol", "tcp")+ .formParam("IpPermissions.1.FromPort", "5432")+ .formParam("IpPermissions.1.ToPort", "5432")+ .formParam("IpPermissions.1.PrefixListIds.1.PrefixListId", prefixListId)+ .formParam("IpPermissions.1.PrefixListIds.1.Description", "from-corp")+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then()+ .statusCode(200)+ .body("AuthorizeSecurityGroupIngressResponse.securityGroupRuleSet.item.prefixListId",+ equalTo(prefixListId))+ .body("AuthorizeSecurityGroupIngressResponse.securityGroupRuleSet.item.description",+ equalTo("from-corp"))+ .body("AuthorizeSecurityGroupIngressResponse.securityGroupRuleSet.item.securityGroupRuleId",+ not(emptyOrNullString()));+ }++ @Test+ @Order(3)+ void describeSecurityGroupsNestsItUnderThePermission() {+ given()+ .formParam("Action", "DescribeSecurityGroups")+ .formParam("GroupId.1", groupId)+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then()+ .statusCode(200)+ .body("DescribeSecurityGroupsResponse.securityGroupInfo.item.ipPermissions.item.prefixListIds.item.prefixListId",+ equalTo(prefixListId))+ .body("DescribeSecurityGroupsResponse.securityGroupInfo.item.ipPermissions.item.prefixListIds.item.description",+ equalTo("from-corp"));+ }++ @Test+ @Order(4)+ void describeSecurityGroupRulesCarriesThePrefixListId() {+ given()+ .formParam("Action", "DescribeSecurityGroupRules")+ .formParam("Filter.1.Name", "group-id")+ .formParam("Filter.1.Value.1", groupId)+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then()+ .statusCode(200)+ // Only the ingress rule carries a prefixListId; the group's default egress rule omits+ // the element entirely, so this resolves to a single value rather than a list.+ .body("DescribeSecurityGroupRulesResponse.securityGroupRuleSet.item.prefixListId",+ equalTo(prefixListId));+ }++ @Test+ @Order(5)+ void authorizeAgainstAnUnknownPrefixListIsRejected() {+ given()+ .formParam("Action", "AuthorizeSecurityGroupIngress")+ .formParam("GroupId", groupId)+ .formParam("IpPermissions.1.IpProtocol", "tcp")+ .formParam("IpPermissions.1.FromPort", "9999")+ .formParam("IpPermissions.1.ToPort", "9999")+ .formParam("IpPermissions.1.PrefixListIds.1.PrefixListId", "pl-doesnotexist")+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then()+ .statusCode(400)+ .body("Response.Errors.Error.Code", equalTo("InvalidPrefixListID.NotFound"));+ }++ @Test+ @Order(6)+ void revokeRemovesThePermission() {+ given()+ .formParam("Action", "RevokeSecurityGroupIngress")+ .formParam("GroupId", groupId)+ .formParam("IpPermissions.1.IpProtocol", "tcp")+ .formParam("IpPermissions.1.FromPort", "5432")+ .formParam("IpPermissions.1.ToPort", "5432")+ .formParam("IpPermissions.1.PrefixListIds.1.PrefixListId", prefixListId)+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then().statusCode(200);++ given()+ .formParam("Action", "DescribeSecurityGroups")+ .formParam("GroupId.1", groupId)+ .header("Authorization", AUTH_HEADER)+ .when().post("/")+ .then()+ .statusCode(200)+ .body("DescribeSecurityGroupsResponse.securityGroupInfo.item.ipPermissions",+ emptyOrNullString());+ }+}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 1234516d5d..ea11ac4600 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@@ -13,6 +13,8 @@ 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.LaunchTemplate;import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;+import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;+import io.github.hectorvent.floci.services.ec2.model.PrefixListId;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.PrefixListEntry;@@ -21,6 +23,7 @@ import io.github.hectorvent.floci.services.ec2.model.Reservation;import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;import io.github.hectorvent.floci.services.ec2.model.Snapshot;import io.github.hectorvent.floci.services.ec2.model.Tag;+import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint;import io.github.hectorvent.floci.services.ec2.model.Volume;import io.github.hectorvent.floci.services.ec2.model.VolumeAttachment;@@ -35,6 +38,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotEquals;import static org.junit.jupiter.api.Assertions.assertNotNull;+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.argThat;@@ -1069,6 +1073,180 @@ class Ec2ServiceTest {.getFirst().getTags().isEmpty());}+ // =========================================================================+ // Security group rules sourced from a prefix list+ // =========================================================================++ private static IpPermission tcpPermission(int port) {+ IpPermission perm = new IpPermission();+ perm.setIpProtocol("tcp");+ perm.setFromPort(port);+ perm.setToPort(port);+ return perm;+ }++ @Test+ void authorizeIngressFromAPrefixListCreatesARuleCarryingIt() {+ Ec2Service service = prefixListService();+ ManagedPrefixList list = service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5,+ List.of(new PrefixListEntry("10.0.0.0/8", null)), List.of());+ String groupId = service.createSecurityGroup("us-east-1", "db", "db", null).getGroupId();++ IpPermission perm = tcpPermission(5432);+ perm.getPrefixListIds().add(new PrefixListId(list.getPrefixListId(), "from-corp"));+ List<SecurityGroupRule> rules = service.authorizeSecurityGroupIngress("us-east-1", groupId, List.of(perm));++ assertEquals(1, rules.size());+ SecurityGroupRule rule = rules.getFirst();+ assertEquals(list.getPrefixListId(), rule.getPrefixListId());+ assertEquals("from-corp", rule.getDescription());+ assertNull(rule.getCidrIpv4(), "a prefix list rule carries no CIDR");+ assertFalse(rule.isEgress());+ assertEquals(5432, rule.getFromPort());+ }++ @Test+ void authorizeAgainstAnUnknownPrefixListIsRejected() {+ Ec2Service service = prefixListService();+ String groupId = service.createSecurityGroup("us-east-1", "db", "db", null).getGroupId();++ IpPermission perm = tcpPermission(5432);+ perm.getPrefixListIds().add(new PrefixListId("pl-doesnotexist", null));++ AwsException error = assertThrows(AwsException.class,+ () -> service.authorizeSecurityGroupIngress("us-east-1", groupId, List.of(perm)));+ assertEquals("InvalidPrefixListID.NotFound", error.getErrorCode());+ // The rejected rule must not have been stored. The group still holds its default+ // allow-all egress rule, so the check is for an ingress rule rather than for none.+ assertTrue(service.describeSecurityGroupRules("us-east-1", List.of(groupId), List.of()).stream()+ .noneMatch(r -> !r.isEgress() || r.getPrefixListId() != null));+ }++ /** AWS emits one rule per source, so a permission naming both expands to two. */+ @Test+ void aPermissionNamingBothACidrAndAPrefixListYieldsARuleForEach() {+ Ec2Service service = prefixListService();+ ManagedPrefixList list = service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5,+ List.of(), List.of());+ String groupId = service.createSecurityGroup("us-east-1", "db", "db", null).getGroupId();++ IpPermission perm = tcpPermission(443);+ perm.getIpRanges().add(new IpRange("10.1.0.0/16", "direct"));+ perm.getPrefixListIds().add(new PrefixListId(list.getPrefixListId(), "via-list"));+ List<SecurityGroupRule> rules = service.authorizeSecurityGroupIngress("us-east-1", groupId, List.of(perm));++ assertEquals(2, rules.size());+ assertEquals(1, rules.stream().filter(r -> "10.1.0.0/16".equals(r.getCidrIpv4())).count());+ assertEquals(1, rules.stream().filter(r -> list.getPrefixListId().equals(r.getPrefixListId())).count());+ }++ /**+ * Verified against a live AWS account: a permission naming a valid CIDR alongside an unknown+ * prefix list persists neither, so the whole call has to resolve before anything is written.+ */+ @Test+ void anUnknownPrefixListLeavesNoPartialRuleFromTheSamePermission() {+ Ec2Service service = prefixListService();+ String groupId = service.createSecurityGroup("us-east-1", "db", "db", null).getGroupId();++ IpPermission perm = tcpPermission(5432);+ perm.getIpRanges().add(new IpRange("10.9.0.0/16", "direct"));+ perm.getPrefixListIds().add(new PrefixListId("pl-doesnotexist", null));++ AwsException error = assertThrows(AwsException.class,+ () -> service.authorizeSecurityGroupIngress("us-east-1", groupId, List.of(perm)));+ assertEquals("InvalidPrefixListID.NotFound", error.getErrorCode());+ assertTrue(service.describeSecurityGroupRules("us-east-1", List.of(groupId), List.of()).stream()+ .noneMatch(r -> !r.isEgress()), "the CIDR rule must not survive the rejection");+ }++ /** A later bad permission must not leave an earlier good one applied either. */+ @Test+ void anUnknownPrefixListInASecondPermissionLeavesTheFirstUnapplied() {+ Ec2Service service = prefixListService();+ String groupId = service.createSecurityGroup("us-east-1", "db", "db", null).getGroupId();++ IpPermission good = tcpPermission(443);+ good.getIpRanges().add(new IpRange("10.1.0.0/16", null));+ IpPermission bad = tcpPermission(5432);+ bad.getPrefixListIds().add(new PrefixListId("pl-doesnotexist", null));++ assertThrows(AwsException.class,+ () -> service.authorizeSecurityGroupIngress("us-east-1", groupId, List.of(good, bad)));+ assertTrue(service.describeSecurityGroupRules("us-east-1", List.of(groupId), List.of()).stream()+ .noneMatch(r -> !r.isEgress()), "no ingress rule from either permission");+ }++ /**+ * Verified against a live AWS account: revoking the prefix list source leaves a CIDR+ * permission on the same protocol and ports untouched.+ */+ @Test+ void revokingAPrefixListSourceLeavesACidrOnTheSameTupleAlone() {+ Ec2Service service = prefixListService();+ ManagedPrefixList list = service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5,+ List.of(), List.of());+ String groupId = service.createSecurityGroup("us-east-1", "db", "db", null).getGroupId();++ IpPermission viaCidr = tcpPermission(5432);+ viaCidr.getIpRanges().add(new IpRange("192.168.0.0/16", null));+ IpPermission viaList = tcpPermission(5432);+ viaList.getPrefixListIds().add(new PrefixListId(list.getPrefixListId(), null));+ service.authorizeSecurityGroupIngress("us-east-1", groupId, List.of(viaCidr, viaList));++ service.revokeSecurityGroupIngress("us-east-1", groupId, List.of(viaList));++ List<IpPermission> left = service.describeSecurityGroups("us-east-1", List.of(groupId), List.of(), Map.of())+ .getFirst().getIpPermissions();+ assertEquals(1, left.size(), "only the prefix list permission should have been revoked");+ assertEquals("192.168.0.0/16", left.getFirst().getIpRanges().getFirst().getCidrIp());+ }++ @Test+ void anEgressRuleCanAlsoComeFromAPrefixList() {+ Ec2Service service = prefixListService();+ ManagedPrefixList list = service.createManagedPrefixList("us-east-1", "corp", "IPv4", 5,+ List.of(), List.of());+ String groupId = service.createSecurityGroup("us-east-1", "db", "db", null).getGroupId();++ IpPermission perm = tcpPermission(443);+ perm.getPrefixListIds().add(new PrefixListId(list.getPrefixListId(), null));+ List<SecurityGroupRule> rules = service.authorizeSecurityGroupEgress("us-east-1", groupId, List.of(perm));++ assertEquals(1, rules.size());+ assertTrue(rules.getFirst().isEgress());+ assertEquals(list.getPrefixListId(), rules.getFirst().getPrefixListId());+ }++ /**+ * A caller may name the source group by name alone, which authorize resolves to a group id+ * before storing it. Scoped revocation has to resolve the same way, or a rule survives the+ * revoke that names it.+ */+ @Test+ void revokingAGroupSourceNamedByNameOnlyStillMatchesTheStoredReference() {+ Ec2Service service = prefixListService();+ String sourceId = service.createSecurityGroup("us-east-1", "app", "app", null).getGroupId();+ String targetId = service.createSecurityGroup("us-east-1", "db", "db", null).getGroupId();++ IpPermission authorized = tcpPermission(5432);+ UserIdGroupPair byName = new UserIdGroupPair();+ byName.setGroupName("app");+ authorized.getUserIdGroupPairs().add(byName);+ List<SecurityGroupRule> rules =+ service.authorizeSecurityGroupIngress("us-east-1", targetId, List.of(authorized));+ assertEquals(sourceId, rules.getFirst().getReferencedGroupInfo().getGroupId());++ IpPermission revocation = tcpPermission(5432);+ UserIdGroupPair alsoByName = new UserIdGroupPair();+ alsoByName.setGroupName("app");+ revocation.getUserIdGroupPairs().add(alsoByName);+ service.revokeSecurityGroupIngress("us-east-1", targetId, List.of(revocation));++ assertTrue(service.describeSecurityGroups("us-east-1", List.of(targetId), List.of(), Map.of())+ .getFirst().getIpPermissions().isEmpty(), "the revoked group reference must be gone");+ }+/*** A rule's tags already reach the store and the rule itself; only DescribeTags mistyped them,* so a resource-type filter never matched.