Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(ec2): revoke security group rules by SecurityGroupRuleId (#6192)

lex005ed0eca7a936
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 603a40ad7a..a2d17dac8a 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
@@ -3352,14 +3352,26 @@ public class Ec2QueryHandler {
private Response handleRevokeSecurityGroupIngress(MultivaluedMap<String, String> p, String region) {
String groupId = p.getFirst("GroupId");
List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
- service.revokeSecurityGroupIngress(region, groupId, perms);
+ List<String> ruleIds = getList(p, "SecurityGroupRuleId");
+ if (!ruleIds.isEmpty()) {
+ service.revokeSecurityGroupRulesByIds(region, groupId, ruleIds, false);
+ }
+ if (!perms.isEmpty() || ruleIds.isEmpty()) {
+ service.revokeSecurityGroupIngress(region, groupId, perms);
+ }
return booleanResponse("RevokeSecurityGroupIngress");
}
private Response handleRevokeSecurityGroupEgress(MultivaluedMap<String, String> p, String region) {
String groupId = p.getFirst("GroupId");
List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
- service.revokeSecurityGroupEgress(region, groupId, perms);
+ List<String> ruleIds = getList(p, "SecurityGroupRuleId");
+ if (!ruleIds.isEmpty()) {
+ service.revokeSecurityGroupRulesByIds(region, groupId, ruleIds, true);
+ }
+ if (!perms.isEmpty() || ruleIds.isEmpty()) {
+ service.revokeSecurityGroupEgress(region, groupId, perms);
+ }
return booleanResponse("RevokeSecurityGroupEgress");
}
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 79469adab6..acd06080e7 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
@@ -7453,6 +7453,31 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
reconcileFirewallPolicies(region);
}
+ /**
+ * Revokes rules named by their {@code sgr-} ids ({@code SecurityGroupRuleId.N}). Every id must
+ * name a rule of the group in the requested direction before any is removed.
+ */
+ public void revokeSecurityGroupRulesByIds(String region, String groupId, List<String> ruleIds,
+ boolean egress) {
+ ensureDefaultResources(region);
+ getRequiredSecurityGroup(region, groupId);
+ synchronized (lockFor(key(region, groupId))) {
+ List<SecurityGroupRule> rules = new ArrayList<>();
+ for (String ruleId : ruleIds) {
+ SecurityGroupRule rule = securityGroupRules.get(key(region, ruleId)).orElse(null);
+ if (rule == null || !groupId.equals(rule.getGroupId()) || rule.isEgress() != egress) {
+ throw new AwsException("InvalidSecurityGroupRuleId.NotFound",
+ "The security group rule ID '" + ruleId + "' does not exist", 400);
+ }
+ rules.add(rule);
+ }
+ for (SecurityGroupRule rule : rules) {
+ removeRuleFromGroup(region, rule);
+ }
+ }
+ reconcileAfterRuleRemoval(region, groupId, egress);
+ }
+
/**
* 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.
@@ -7464,39 +7489,53 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (rule == null) {
return false;
}
- securityGroupRules.delete(key(region, securityGroupRuleId));
String groupId = rule.getGroupId();
if (groupId == null) {
+ securityGroupRules.delete(key(region, securityGroupRuleId));
return true;
}
synchronized (lockFor(key(region, groupId))) {
- SecurityGroup sg = securityGroups.get(key(region, groupId)).orElse(null);
- if (sg == null) {
- return true;
+ if (securityGroupRules.get(key(region, securityGroupRuleId)).isEmpty()) {
+ return false;
}
- 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);
+ removeRuleFromGroup(region, rule);
+ }
+ reconcileAfterRuleRemoval(region, groupId, rule.isEgress());
+ return true;
+ }
+
+ /** Deletes the rule record and its peer in the group's permissions. Callers hold the group lock. */
+ private void removeRuleFromGroup(String region, SecurityGroupRule rule) {
+ securityGroupRules.delete(key(region, rule.getSecurityGroupRuleId()));
+ String groupId = rule.getGroupId();
+ SecurityGroup sg = securityGroups.get(key(region, groupId)).orElse(null);
+ if (sg == null) {
+ return;
+ }
+ 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()) {
+ }
+
+ private void reconcileAfterRuleRemoval(String region, String groupId, boolean egress) {
+ if (!egress) {
reconcilePublishedPortsForGroup(region, groupId);
} else {
reconcileFirewallPolicies(region);
}
- 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.
+ * Drops exactly the peer a rule record names, its ipv4 cidr, ipv6 cidr, referenced group or
+ * prefix list, 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
@@ -7518,9 +7557,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
dropIfEmpty(perms, perm);
return true;
}
- if (referencedGroupId != null) {
+ if (rule.getReferencedGroupInfo() != null) {
+ // A reference by a name that matched no group was recorded without an id.
UserIdGroupPair matchPair = perm.getUserIdGroupPairs().stream()
- .filter(pair -> referencedGroupId.equals(pair.getGroupId()))
+ .filter(pair -> Objects.equals(referencedGroupId, pair.getGroupId()))
.findFirst().orElse(null);
if (matchPair == null) {
continue;
@@ -7540,9 +7580,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
dropIfEmpty(perms, perm);
return true;
}
+ if (rule.getPrefixListId() != null) {
+ PrefixListId matchList = perm.getPrefixListIds().stream()
+ .filter(l -> rule.getPrefixListId().equals(l.getPrefixListId()))
+ .findFirst().orElse(null);
+ if (matchList == null) {
+ continue;
+ }
+ perm.getPrefixListIds().remove(matchList);
+ 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()) {
+ if (!hasSources(perm)) {
perms.remove(perm);
return true;
}
@@ -7550,9 +7600,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return false;
}
- private static void dropIfEmpty(List<IpPermission> perms, IpPermission perm) {
- if (perm.getIpRanges().isEmpty() && perm.getIpv6Ranges().isEmpty()
- && perm.getUserIdGroupPairs().isEmpty()) {
+ private void dropIfEmpty(List<IpPermission> perms, IpPermission perm) {
+ if (!hasSources(perm)) {
perms.remove(perm);
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2SecurityGroupRuleSourcesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2SecurityGroupRuleSourcesIntegrationTest.java
index cacd1fde2a..27e4046723 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2SecurityGroupRuleSourcesIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2SecurityGroupRuleSourcesIntegrationTest.java
@@ -1,13 +1,18 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
+import java.util.List;
+
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.not;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -25,6 +30,8 @@ class Ec2SecurityGroupRuleSourcesIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private static final String ACCOUNT_ID = "000000000000";
+ private static final String INGRESS = "AuthorizeSecurityGroupIngress";
+ private static final String EGRESS = "AuthorizeSecurityGroupEgress";
@Test
void groupReferenceSurvivesAuthorizeAndBothDescribes() {
@@ -57,7 +64,7 @@ class Ec2SecurityGroupRuleSourcesIntegrationTest {
"AuthorizeSecurityGroupIngress must echo the source group, got: " + authorizeBody);
// Control: the same group with a CIDR rule, which already worked.
- authorizeCidrIngress(targetId, "8443", "10.0.0.0/8", "control");
+ authorize(INGRESS, targetId, "8443", List.of(), "10.0.0.0/8", "control");
given()
.formParam("Action", "DescribeSecurityGroups")
@@ -289,6 +296,182 @@ class Ec2SecurityGroupRuleSourcesIntegrationTest {
+ ".item.description", equalTo("v6-range"));
}
+ @Test
+ void revokeIngressBySecurityGroupRuleIdRemovesTheRule() {
+ String vpcId = createVpc();
+ String groupId = createSecurityGroup(uniqueName("revoke-by-id"), vpcId);
+ Response authorize = authorize(INGRESS, groupId, "5432", List.of(), "10.0.0.0/16", null);
+ String ruleId = ruleIdFor(INGRESS, authorize, "cidrIpv4", "10.0.0.0/16");
+
+ revokeByRuleId("RevokeSecurityGroupIngress", groupId, ruleId)
+ .then()
+ .statusCode(200)
+ .body("RevokeSecurityGroupIngressResponse.return", equalTo("true"));
+
+ 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)
+ .body(not(containsString(ruleId)));
+
+ given()
+ .formParam("Action", "DescribeSecurityGroups")
+ .formParam("GroupId.1", groupId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(not(containsString("<fromPort>5432</fromPort>")));
+ }
+
+ @Test
+ void revokeEgressBySecurityGroupRuleIdRemovesTheRule() {
+ String vpcId = createVpc();
+ String groupId = createSecurityGroup(uniqueName("revoke-egress-by-id"), vpcId);
+ Response authorize = authorize(EGRESS, groupId, "8443", List.of(), "10.5.0.0/16", null);
+ String ruleId = ruleIdFor(EGRESS, authorize, "cidrIpv4", "10.5.0.0/16");
+
+ revokeByRuleId("RevokeSecurityGroupEgress", groupId, ruleId)
+ .then()
+ .statusCode(200);
+
+ given()
+ .formParam("Action", "DescribeSecurityGroups")
+ .formParam("GroupId.1", groupId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(not(containsString("10.5.0.0/16")));
+ }
+
+ @Test
+ void revokeBySecurityGroupRuleIdOfAnotherGroupFailsAndKeepsTheRule() {
+ String vpcId = createVpc();
+ String targetId = createSecurityGroup(uniqueName("revoke-target"), vpcId);
+ String otherId = createSecurityGroup(uniqueName("revoke-other"), vpcId);
+ Response authorize = authorize(INGRESS, otherId, "9999", List.of(), "10.0.0.0/16", null);
+ String otherRuleId = ruleIdFor(INGRESS, authorize, "cidrIpv4", "10.0.0.0/16");
+
+ revokeByRuleId("RevokeSecurityGroupIngress", targetId, otherRuleId)
+ .then()
+ .statusCode(400)
+ .body(containsString("<Code>InvalidSecurityGroupRuleId.NotFound</Code>"));
+
+ given()
+ .formParam("Action", "DescribeSecurityGroupRules")
+ .formParam("SecurityGroupRuleId.1", otherRuleId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString(otherRuleId));
+ }
+
+ @Test
+ void revokingOnePrefixListRuleKeepsAnotherAuthorizedSeparately() {
+ String groupId = createSecurityGroup(uniqueName("revoke-pl-separate"), createVpc());
+ String keptList = createPrefixList();
+ String revokedList = createPrefixList();
+ authorize(INGRESS, groupId, "443", List.of(keptList), null, null);
+ Response authorize = authorize(INGRESS, groupId, "443", List.of(revokedList), null, null);
+ String ruleId = ruleIdFor(INGRESS, authorize, "prefixListId", revokedList);
+
+ revokeByRuleId("RevokeSecurityGroupIngress", groupId, ruleId).then().statusCode(200);
+
+ String group = describeGroup(groupId);
+ assertTrue(group.contains(keptList), group);
+ assertFalse(group.contains(revokedList), group);
+ }
+
+ @Test
+ void revokingOnePrefixListRuleKeepsItsNeighbourInThePermission() {
+ String groupId = createSecurityGroup(uniqueName("revoke-pl-shared"), createVpc());
+ String keptList = createPrefixList();
+ String revokedList = createPrefixList();
+ Response authorize = authorize(INGRESS, groupId, "443", List.of(keptList, revokedList), null, null);
+ String ruleId = ruleIdFor(INGRESS, authorize, "prefixListId", revokedList);
+
+ revokeByRuleId("RevokeSecurityGroupIngress", groupId, ruleId).then().statusCode(200);
+
+ String group = describeGroup(groupId);
+ assertTrue(group.contains(keptList), group);
+ assertFalse(group.contains(revokedList), group);
+ }
+
+ @Test
+ void revokingAPrefixListRuleBesideACidrKeepsTheCidr() {
+ String groupId = createSecurityGroup(uniqueName("revoke-pl-cidr"), createVpc());
+ String prefixList = createPrefixList();
+ Response authorize = authorize(INGRESS, groupId, "443", List.of(prefixList), "10.9.0.0/16", null);
+ String ruleId = ruleIdFor(INGRESS, authorize, "prefixListId", prefixList);
+
+ revokeByRuleId("RevokeSecurityGroupIngress", groupId, ruleId).then().statusCode(200);
+
+ String group = describeGroup(groupId);
+ assertFalse(group.contains(prefixList), group);
+ assertTrue(group.contains("10.9.0.0/16"), group);
+ }
+
+ @Test
+ void revokingACidrRuleBesideAPrefixListKeepsTheList() {
+ String groupId = createSecurityGroup(uniqueName("revoke-cidr-pl"), createVpc());
+ String prefixList = createPrefixList();
+ Response authorize = authorize(INGRESS, groupId, "443", List.of(prefixList), "10.9.0.0/16", null);
+ String cidrRuleId = ruleIdFor(INGRESS, authorize, "cidrIpv4", "10.9.0.0/16");
+ String listRuleId = ruleIdFor(INGRESS, authorize, "prefixListId", prefixList);
+
+ revokeByRuleId("RevokeSecurityGroupIngress", groupId, cidrRuleId).then().statusCode(200);
+
+ String group = describeGroup(groupId);
+ assertTrue(group.contains(prefixList), group);
+ assertFalse(group.contains("10.9.0.0/16"), group);
+ assertTrue(describeRules(groupId).contains(listRuleId));
+ }
+
+ @Test
+ void revokingARuleForAnUnknownGroupNameRemovesThePair() {
+ String groupId = createSecurityGroup(uniqueName("revoke-unknown-name"), createVpc());
+ String missingName = uniqueName("no-such-group");
+ String ruleId = 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.Groups.1.GroupName", missingName)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().path("AuthorizeSecurityGroupIngressResponse.securityGroupRuleSet.item.securityGroupRuleId");
+
+ revokeByRuleId("RevokeSecurityGroupIngress", groupId, ruleId).then().statusCode(200);
+
+ String group = describeGroup(groupId);
+ assertFalse(group.contains(missingName), group);
+ assertFalse(group.contains("<fromPort>9100</fromPort>"), group);
+ }
+
+ private Response revokeByRuleId(String action, String groupId, String ruleId) {
+ return given()
+ .formParam("Action", action)
+ .formParam("GroupId", groupId)
+ .formParam("SecurityGroupRuleId.1", ruleId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/");
+ }
+
private String referencedGroupInfoXml(String groupId) {
return "<referencedGroupInfo><groupId>" + groupId + "</groupId>"
+ "<userId>" + ACCOUNT_ID + "</userId></referencedGroupInfo>";
@@ -325,19 +508,71 @@ class Ec2SecurityGroupRuleSourcesIntegrationTest {
.extract().path("CreateSecurityGroupResponse.groupId");
}
- private void authorizeCidrIngress(String groupId, String port, String cidr, String description) {
- given()
- .formParam("Action", "AuthorizeSecurityGroupIngress")
+ /** Authorizes one tcp permission on {@code port} naming every source given. */
+ private Response authorize(String action, String groupId, String port, List<String> prefixLists,
+ String cidr, String description) {
+ RequestSpecification request = given()
+ .formParam("Action", action)
.formParam("GroupId", groupId)
.formParam("IpPermissions.1.IpProtocol", "tcp")
.formParam("IpPermissions.1.FromPort", port)
- .formParam("IpPermissions.1.ToPort", port)
- .formParam("IpPermissions.1.IpRanges.1.CidrIp", cidr)
- .formParam("IpPermissions.1.IpRanges.1.Description", description)
+ .formParam("IpPermissions.1.ToPort", port);
+ for (int i = 0; i < prefixLists.size(); i++) {
+ request.formParam("IpPermissions.1.PrefixListIds." + (i + 1) + ".PrefixListId", prefixLists.get(i));
+ }
+ if (cidr != null) {
+ request.formParam("IpPermissions.1.IpRanges.1.CidrIp", cidr);
+ }
+ if (description != null) {
+ request.formParam("IpPermissions.1.IpRanges.1.Description", description);
+ }
+ Response response = request.header("Authorization", AUTH_HEADER).when().post("/");
+ response.then().statusCode(200);
+ return response;
+ }
+
+ private String ruleIdFor(String action, Response authorize, String field, String value) {
+ return authorize.path(action + "Response.securityGroupRuleSet.item.find { it."
+ + field + " == '" + value + "' }.securityGroupRuleId");
+ }
+
+ private String createPrefixList() {
+ return given()
+ .formParam("Action", "CreateManagedPrefixList")
+ .formParam("PrefixListName", uniqueName("revoke-pl"))
+ .formParam("AddressFamily", "IPv4")
+ .formParam("MaxEntries", "5")
+ .formParam("Entry.1.Cidr", "10.0.0.0/8")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
- .statusCode(200);
+ .statusCode(200)
+ .extract().path("CreateManagedPrefixListResponse.prefixList.prefixListId");
+ }
+
+ private String describeGroup(String groupId) {
+ return given()
+ .formParam("Action", "DescribeSecurityGroups")
+ .formParam("GroupId.1", groupId)
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().body().asString();
+ }
+
+ private String describeRules(String groupId) {
+ return 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)
+ .extract().body().asString();
}
}