From dfcd4921986998b249cf272d65e905ae6bc3dd7d Mon Sep 17 00:00:00 2001 From: Michal Schreiber <73832189+ck-michals@users.noreply.github.com> Date: Sat, 15 Aug 2026 19:11:53 +0200 Subject: [PATCH] feat(ec2): allow a security group rule to take a prefix list as its source (#2271) * feat(ec2): allow a security group rule to take a prefix list as its source AuthorizeSecurityGroupIngress and AuthorizeSecurityGroupEgress now read IpPermissions.N.PrefixListIds.M, so a rule can name a managed prefix list instead of a CIDR. The rule carries prefixListId in place of cidrIpv4 and DescribeSecurityGroups nests the reference under the permission, matching the shapes AWS returns. AWS emits one rule per source, so createRules expands a permission across its CIDRs and its prefix lists rather than treating the two as alternatives; a permission naming neither still yields the single bare rule it did before. An unknown list is rejected with InvalidPrefixListID.NotFound before the rule is stored, so a typo cannot leave a rule pointing at nothing. Closes #2269 * fix(ec2): resolve every prefix list before writing any security group rule createRules stored the CIDR rules of a permission before validating its prefix lists, so a permission naming a valid CIDR alongside an unknown list returned InvalidPrefixListID.NotFound while leaving the CIDR rule behind. AWS persists neither, checked against a live account, and rejects the call as a whole rather than per permission. Resolve every reference a request names before the first write, across all of its permissions, so a later bad permission cannot leave an earlier good one applied. Also brace the new parsing conditional, as AGENTS.md requires. * style(ec2): brace the conditionals in parseIpPermissions AGENTS.md is unconditional about braces, and the method held five unbraced conditionals around the line this branch added. Bracing the whole method rather than only the new line keeps it internally consistent. * fix(ec2): scope security group revocation to the sources it names Revocation compared only protocol and ports, so revoking one source removed every permission sharing that tuple: revoking a prefix list also dropped a CIDR rule on the same port. AWS scopes it to the source, verified against a live account, and leaves the others in place. Subtract the named sources instead, dropping a permission only once it had sources and has lost them all. A request naming no source at all still removes the whole matching permission, which is how a bare protocol and port revoke behaves. The permission a revoke names can be the very object authorize stored on the group, so the source values are snapshotted before either list is mutated. * fix(ec2): validate prefix lists once per request rather than per permission Resolving the prefix lists again inside createRules reopened the window the request-wide check had closed: a list can be deleted between the two, since the group lock and the prefix list lock are different monitors, so a later permission could fail after earlier ones had already stored their rules. Authorize resolves every reference before the first write, so the repeat is removed. createRules keeps no validation of its own; its other callers pass the CIDR-only default egress permission. * fix(ec2): resolve group references when revoking too Scoped revocation compares the sources a request names against the ones stored on the permission. Authorize resolves a reference made by group name to its group id before storing it, so a revoke naming the same source by name alone carried no id and matched nothing: the rule survived the revoke that named it. Resolve on the revoke path as well, mirroring authorize. This only surfaces once both source-scoped revocation and group references as a source exist, so the gap is between this branch and #2266 rather than in either alone. --------- Co-authored-by: Michal Schreiber --- .../sdk-test-awscli/test/ec2.bats | 40 ++++ docs/services/ec2.md | 7 + .../floci/services/ec2/Ec2QueryHandler.java | 40 +++- .../floci/services/ec2/Ec2Service.java | 103 ++++++++-- .../services/ec2/model/IpPermission.java | 4 + .../services/ec2/model/PrefixListId.java | 26 +++ .../services/ec2/model/SecurityGroupRule.java | 5 + ...ecurityGroupPrefixListIntegrationTest.java | 149 +++++++++++++++ .../floci/services/ec2/Ec2ServiceTest.java | 178 ++++++++++++++++++ 9 files changed, 534 insertions(+), 18 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/ec2/model/PrefixListId.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ec2/Ec2SecurityGroupPrefixListIntegrationTest.java diff --git a/compatibility-tests/sdk-test-awscli/test/ec2.bats b/compatibility-tests/sdk-test-awscli/test/ec2.bats index 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.md index 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-add Creation is synchronous: a new list is returned as `create-complete` rather than passing through `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.java index 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 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 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.java index 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 rules = new ArrayList<>(); synchronized (lockFor(key(region, groupId))) { SecurityGroup sg = getRequiredSecurityGroup(region, groupId); + requireKnownPrefixLists(region, permissions); List next = new ArrayList<>(sg.getIpPermissions()); for (IpPermission perm : permissions) { resolveGroupReferences(region, sg.getVpcId(), perm); @@ -1700,6 +1702,7 @@ public class Ec2Service implements ContainerTeardown { List rules = new ArrayList<>(); synchronized (lockFor(key(region, groupId))) { SecurityGroup sg = getRequiredSecurityGroup(region, groupId); + requireKnownPrefixLists(region, permissions); List 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. + * + *

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 createRules(String region, String groupId, IpPermission perm, boolean egress) { List 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 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 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 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 next = new ArrayList<>(sg.getIpPermissionsEgress()); - next.removeIf(p -> matchesAnyPermission(p, permissions)); + for (IpPermission perm : permissions) { + resolveGroupReferences(region, sg.getVpcId(), perm); + } + List 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 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. + * + *

Returns the permissions that remain. + */ + private List revokeSources(List existing, List toRemove) { + List 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 cidrs = removal.getIpRanges().stream().map(IpRange::getCidrIp).toList(); + List cidrsV6 = removal.getIpv6Ranges().stream().map(Ipv6Range::getCidrIpv6).toList(); + List lists = removal.getPrefixListIds().stream() + .map(PrefixListId::getPrefixListId).toList(); + List 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 describeSecurityGroupRules(String region, List groupIds, List 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.java index 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 ipRanges = new ArrayList<>(); private List ipv6Ranges = new ArrayList<>(); private List userIdGroupPairs = new ArrayList<>(); + private List prefixListIds = new ArrayList<>(); public IpPermission() {} @@ -35,5 +36,8 @@ public class IpPermission { public void setIpv6Ranges(List ipv6Ranges) { this.ipv6Ranges = ipv6Ranges; } public List getUserIdGroupPairs() { return userIdGroupPairs; } + + public List getPrefixListIds() { return prefixListIds; } + public void setPrefixListIds(List prefixListIds) { this.prefixListIds = prefixListIds; } public void setUserIdGroupPairs(List 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.java new file mode 100644 index 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.java index 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 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.java new file mode 100644 index 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.java index 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 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 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 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 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 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.