fix(ec2): honour DryRun on the security group rule calls (#9225)

AuthorizeSecurityGroupIngress and Egress, RevokeSecurityGroupIngress and
Egress and ModifySecurityGroupRules ignored DryRun=true and made the
change: a dry-run AuthorizeSecurityGroupIngress added the rule. Each now
answers DryRunOperation once the request has passed the checks the real
call makes, and changes nothing. UpdateSecurityGroupRuleDescriptionsIngress
and Egress change nothing in Floci and refuse nothing, so they answer it
through the handler's checkDryRun.

Part of #8220
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-22 16:56:22 -04:00
1 parent 749daf638f
commit d4af2a836e
4 files changed
+165 -15

No files matched your search

@@ -3736,7 +3736,7 @@ public class Ec2QueryHandler {
List<Tag> ruleTags = parseTagsForResource(p, "security-group-rule");
String groupId = p.getFirst("GroupId");
List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
List<SecurityGroupRule> rules = service.authorizeSecurityGroupIngress(region, groupId, perms);
List<SecurityGroupRule> rules = service.authorizeSecurityGroupIngress(region, groupId, perms, dryRun(p));
applySecurityGroupRuleTags(ruleTags, region, rules);
XmlBuilder xml = new XmlBuilder()
.start("AuthorizeSecurityGroupIngressResponse", AwsNamespaces.EC2)
@@ -3754,7 +3754,7 @@ public class Ec2QueryHandler {
List<Tag> ruleTags = parseTagsForResource(p, "security-group-rule");
String groupId = p.getFirst("GroupId");
List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
List<SecurityGroupRule> rules = service.authorizeSecurityGroupEgress(region, groupId, perms);
List<SecurityGroupRule> rules = service.authorizeSecurityGroupEgress(region, groupId, perms, dryRun(p));
applySecurityGroupRuleTags(ruleTags, region, rules);
XmlBuilder xml = new XmlBuilder()
.start("AuthorizeSecurityGroupEgressResponse", AwsNamespaces.EC2)
@@ -3772,11 +3772,14 @@ public class Ec2QueryHandler {
String groupId = p.getFirst("GroupId");
List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
List<String> ruleIds = getList(p, "SecurityGroupRuleId");
boolean dryRun = dryRun(p);
// A dry run naming rule ids is answered once they are checked: the permissions' revoke refuses only a
// group that doesn't exist, which the ids' check refuses first.
if (!ruleIds.isEmpty()) {
service.revokeSecurityGroupRulesByIds(region, groupId, ruleIds, false);
service.revokeSecurityGroupRulesByIds(region, groupId, ruleIds, false, dryRun);
}
if (!perms.isEmpty() || ruleIds.isEmpty()) {
service.revokeSecurityGroupIngress(region, groupId, perms);
service.revokeSecurityGroupIngress(region, groupId, perms, dryRun);
}
return booleanResponse("RevokeSecurityGroupIngress");
}
@@ -3785,11 +3788,13 @@ public class Ec2QueryHandler {
String groupId = p.getFirst("GroupId");
List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
List<String> ruleIds = getList(p, "SecurityGroupRuleId");
boolean dryRun = dryRun(p);
// As for RevokeSecurityGroupIngress, a dry run naming rule ids is answered once they are checked.
if (!ruleIds.isEmpty()) {
service.revokeSecurityGroupRulesByIds(region, groupId, ruleIds, true);
service.revokeSecurityGroupRulesByIds(region, groupId, ruleIds, true, dryRun);
}
if (!perms.isEmpty() || ruleIds.isEmpty()) {
service.revokeSecurityGroupEgress(region, groupId, perms);
service.revokeSecurityGroupEgress(region, groupId, perms, dryRun);
}
return booleanResponse("RevokeSecurityGroupEgress");
}
@@ -3831,17 +3836,19 @@ public class Ec2QueryHandler {
if (desc != null) update.put("Description", desc);
updates.add(update);
}
service.modifySecurityGroupRules(region, groupId, updates);
service.modifySecurityGroupRules(region, groupId, updates, dryRun(p));
return booleanResponse("ModifySecurityGroupRules");
}
private Response handleUpdateSgRuleDescriptionsIngress(MultivaluedMap<String, String> p, String region) {
checkDryRun(p);
String groupId = p.getFirst("GroupId");
service.updateSecurityGroupRuleDescriptionsIngress(region, groupId, Collections.emptyList());
return booleanResponse("UpdateSecurityGroupRuleDescriptionsIngress");
}
private Response handleUpdateSgRuleDescriptionsEgress(MultivaluedMap<String, String> p, String region) {
checkDryRun(p);
String groupId = p.getFirst("GroupId");
service.updateSecurityGroupRuleDescriptionsEgress(region, groupId, Collections.emptyList());
return booleanResponse("UpdateSecurityGroupRuleDescriptionsEgress");
@@ -8608,12 +8608,24 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public List<SecurityGroupRule> authorizeSecurityGroupIngress(String region, String groupId, List<IpPermission> permissions) {
return authorizeSecurityGroupIngress(region, groupId, permissions, false);
}
/**
* As above; with {@code dryRun} the group and every prefix list the permissions name must exist, and the
* request is then answered with DryRunOperation, no rule added.
*/
public List<SecurityGroupRule> authorizeSecurityGroupIngress(String region, String groupId,
List<IpPermission> permissions, boolean dryRun) {
ensureDefaultResources(region);
List<SecurityGroupRule> rules = new ArrayList<>();
synchronized (attachmentTopologyLock(region)) {
synchronized (lockFor(key(region, groupId))) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
requireKnownPrefixLists(region, permissions);
if (dryRun) {
throw dryRunOperation();
}
List<IpPermission> next = new ArrayList<>(sg.getIpPermissions());
for (IpPermission perm : permissions) {
resolveGroupReferences(region, sg.getVpcId(), perm);
@@ -8629,12 +8641,24 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public List<SecurityGroupRule> authorizeSecurityGroupEgress(String region, String groupId, List<IpPermission> permissions) {
return authorizeSecurityGroupEgress(region, groupId, permissions, false);
}
/**
* As above; with {@code dryRun} the group and every prefix list the permissions name must exist, and the
* request is then answered with DryRunOperation, no rule added.
*/
public List<SecurityGroupRule> authorizeSecurityGroupEgress(String region, String groupId,
List<IpPermission> permissions, boolean dryRun) {
ensureDefaultResources(region);
List<SecurityGroupRule> rules = new ArrayList<>();
synchronized (attachmentTopologyLock(region)) {
synchronized (lockFor(key(region, groupId))) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
requireKnownPrefixLists(region, permissions);
if (dryRun) {
throw dryRunOperation();
}
List<IpPermission> next = new ArrayList<>(sg.getIpPermissionsEgress());
for (IpPermission perm : permissions) {
resolveGroupReferences(region, sg.getVpcId(), perm);
@@ -8764,9 +8788,21 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public void revokeSecurityGroupIngress(String region, String groupId, List<IpPermission> permissions) {
revokeSecurityGroupIngress(region, groupId, permissions, false);
}
/**
* As above; with {@code dryRun} the group must exist, and the request is then answered with DryRunOperation,
* no rule removed.
*/
public void revokeSecurityGroupIngress(String region, String groupId, List<IpPermission> permissions,
boolean dryRun) {
ensureDefaultResources(region);
synchronized (lockFor(key(region, groupId))) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
if (dryRun) {
throw dryRunOperation();
}
// 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) {
@@ -8780,9 +8816,21 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public void revokeSecurityGroupEgress(String region, String groupId, List<IpPermission> permissions) {
revokeSecurityGroupEgress(region, groupId, permissions, false);
}
/**
* As above; with {@code dryRun} the group must exist, and the request is then answered with DryRunOperation,
* no rule removed.
*/
public void revokeSecurityGroupEgress(String region, String groupId, List<IpPermission> permissions,
boolean dryRun) {
ensureDefaultResources(region);
synchronized (lockFor(key(region, groupId))) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
if (dryRun) {
throw dryRunOperation();
}
for (IpPermission perm : permissions) {
resolveGroupReferences(region, sg.getVpcId(), perm);
}
@@ -8799,6 +8847,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
*/
public void revokeSecurityGroupRulesByIds(String region, String groupId, List<String> ruleIds,
boolean egress) {
revokeSecurityGroupRulesByIds(region, groupId, ruleIds, egress, false);
}
/**
* As above; with {@code dryRun} every id must name a rule of the group in the requested direction, and the
* request is then answered with DryRunOperation, no rule removed.
*/
public void revokeSecurityGroupRulesByIds(String region, String groupId, List<String> ruleIds,
boolean egress, boolean dryRun) {
ensureDefaultResources(region);
getRequiredSecurityGroup(region, groupId);
synchronized (lockFor(key(region, groupId))) {
@@ -8811,6 +8868,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
rules.add(rule);
}
if (dryRun) {
throw dryRunOperation();
}
for (SecurityGroupRule rule : rules) {
removeRuleFromGroup(region, rule);
}
@@ -9049,11 +9109,23 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public void modifySecurityGroupRules(String region, String groupId, List<Map<String, String>> ruleUpdates) {
modifySecurityGroupRules(region, groupId, ruleUpdates, false);
}
/**
* As above; with {@code dryRun} the group must exist and every update name a rule of it, and the request is
* then answered with DryRunOperation, no description changed.
*/
public void modifySecurityGroupRules(String region, String groupId, List<Map<String, String>> ruleUpdates,
boolean dryRun) {
ensureDefaultResources(region);
synchronized (attachmentTopologyLock(region)) {
synchronized (lockFor(key(region, groupId))) {
SecurityGroup group = getRequiredSecurityGroup(region, groupId);
List<RuleDescriptionUpdate> updates = requireRuleDescriptionUpdates(region, groupId, ruleUpdates);
if (dryRun) {
throw dryRunOperation();
}
for (RuleDescriptionUpdate update : updates) {
SecurityGroupRule rule = update.rule();
rule.setDescription(update.description());
@@ -19,6 +19,7 @@ import java.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
@@ -30,7 +31,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* A dry run checks the caller's permission and changes nothing else: under IAM enforcement a caller the
* policy does not allow gets UnauthorizedOperation for a dry run, as for the real call, and one it allows
* gets DryRunOperation, with nothing created, deleted or terminated either way.
* gets DryRunOperation, with nothing created, deleted, terminated or authorized either way.
*/
@QuarkusTest
@TestProfile(SignedIamEnforcementProfile.class)
@@ -124,6 +125,24 @@ class Ec2DryRunIamIntegrationTest {
}
}
@Test
void anAuthorizeSecurityGroupIngressDryRunNeedsTheCallersCurrentPermission() throws Exception {
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint)) {
String groupId = admin.createSecurityGroup(r -> r.groupName("dryrun-" + UUID.randomUUID())
.description("dry run")).groupId();
try {
assertADryRunNeedsTheCallersCurrentPermission("AuthorizeSecurityGroupIngress",
() -> admin.describeSecurityGroupRules(r -> r.filters(f -> f.name("group-id")
.values(groupId))).securityGroupRules(),
caller -> caller.authorizeSecurityGroupIngress(r -> r.groupId(groupId).dryRun(true)
.ipPermissions(p -> p.ipProtocol("tcp").fromPort(22).toPort(22)
.ipRanges(range -> range.cidrIp("10.0.0.0/8")))));
} finally {
admin.deleteSecurityGroup(r -> r.groupId(groupId));
}
}
}
/**
* A caller the policy allows {@code action} gets DryRunOperation for {@code dryRun} on a running instance,
* and UnauthorizedOperation once the policy is removed; the instance is unchanged either way.
@@ -19,9 +19,9 @@ import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* DryRun on the VPC, subnet, internet gateway and route table calls is answered with DryRunOperation and
* HTTP 412 once the request has passed the checks the real call makes, and changes nothing. A dry run the
* real call would refuse keeps that call's error.
* DryRun on the VPC, subnet, internet gateway, route table and security group rule calls is answered with
* DryRunOperation and HTTP 412 once the request has passed the checks the real call makes, and changes nothing.
* A dry run the real call would refuse keeps that call's error.
*/
@QuarkusTest
class Ec2VpcDryRunIntegrationTest {
@@ -31,6 +31,11 @@ class Ec2VpcDryRunIntegrationTest {
private static final String MISSING_VPC = "vpc-0123456789abcdef0";
private static final String MISSING_GATEWAY = "igw-0123456789abcdef0";
private static final String MISSING_TABLE = "rtb-0123456789abcdef0";
private static final String MISSING_GROUP = "sg-0123456789abcdef0";
private static final String MISSING_RULE = "sgr-0123456789abcdef0";
/** One TCP port from 10.0.0.0/8, in an IpPermissions member; each request below gives the port it adds. */
private static final String PERMISSION = "IpPermissions.1.IpProtocol=tcp IpPermissions.1.FromPort=%1$d"
+ " IpPermissions.1.ToPort=%1$d IpPermissions.1.IpRanges.1.CidrIp=10.0.0.0/8";
private String account;
/** The fixture's ids by the names the requests below give them in braces, such as {vpc}. */
@@ -39,7 +44,8 @@ class Ec2VpcDryRunIntegrationTest {
/**
* A VPC with two subnets, one holding a network interface; an internet gateway attached to it; a route
* table routing 0.0.0.0/0 to the gateway and associated with the occupied subnet, and a second one with
* neither. Beside them, an empty VPC and a gateway attached to nothing.
* neither. Beside them, an empty VPC and a gateway attached to nothing. In the first VPC, a security group
* allowing port 22 in and port 443 out, from and to 10.0.0.0/8.
*/
@BeforeEach
void buildTheNetwork() {
@@ -61,6 +67,10 @@ class Ec2VpcDryRunIntegrationTest {
"GatewayId", ids.get("gateway"));
ids.put("association", create("AssociateRouteTable", "associationId", "RouteTableId", ids.get("table"),
"SubnetId", ids.get("subnet")));
ids.put("group", create("CreateSecurityGroup", "groupId", "GroupName", "dry-run",
"GroupDescription", "dry run", "VpcId", ids.get("vpc")));
ids.put("ingressRule", authorize("AuthorizeSecurityGroupIngress", 22));
ids.put("egressRule", authorize("AuthorizeSecurityGroupEgress", 443));
}
/** A request each call's real call accepts in the fixture. */
@@ -77,7 +87,20 @@ class Ec2VpcDryRunIntegrationTest {
new String[] {"DeleteRouteTable", "RouteTableId={spareTable}"},
new String[] {"AssociateRouteTable", "RouteTableId={spareTable} SubnetId={freeSubnet}"},
new String[] {"DisassociateRouteTable", "AssociationId={association}"},
new String[] {"DeleteRoute", "RouteTableId={table} DestinationCidrBlock=0.0.0.0/0"});
new String[] {"DeleteRoute", "RouteTableId={table} DestinationCidrBlock=0.0.0.0/0"},
new String[] {"AuthorizeSecurityGroupIngress", "GroupId={group} " + PERMISSION.formatted(8080)},
new String[] {"AuthorizeSecurityGroupEgress", "GroupId={group} " + PERMISSION.formatted(8443)},
new String[] {"RevokeSecurityGroupIngress", "GroupId={group} " + PERMISSION.formatted(22)},
new String[] {"RevokeSecurityGroupIngress", "GroupId={group} SecurityGroupRuleId.1={ingressRule}"},
new String[] {"RevokeSecurityGroupEgress", "GroupId={group} " + PERMISSION.formatted(443)},
new String[] {"RevokeSecurityGroupEgress", "GroupId={group} SecurityGroupRuleId.1={egressRule}"},
new String[] {"ModifySecurityGroupRules", "GroupId={group}"
+ " SecurityGroupRule.1.SecurityGroupRuleId={ingressRule}"
+ " SecurityGroupRule.1.SecurityGroupRule.Description=changed"},
new String[] {"UpdateSecurityGroupRuleDescriptionsIngress", "GroupId={group} "
+ PERMISSION.formatted(22) + " IpPermissions.1.IpRanges.1.Description=changed"},
new String[] {"UpdateSecurityGroupRuleDescriptionsEgress", "GroupId={group} "
+ PERMISSION.formatted(443) + " IpPermissions.1.IpRanges.1.Description=changed"});
}
@ParameterizedTest
@@ -126,7 +149,28 @@ class Ec2VpcDryRunIntegrationTest {
+ " | InvalidRouteTableID.NotFound",
"DeleteRoute | RouteTableId={table} DestinationCidrBlock=10.0.0.0/16 | InvalidParameterValue",
"DeleteRoute | RouteTableId={table} DestinationCidrBlock=10.9.0.0/16 | InvalidRoute.NotFound",
"DeleteRoute | RouteTableId={table} | MissingParameter"
"DeleteRoute | RouteTableId={table} | MissingParameter",
"AuthorizeSecurityGroupIngress | GroupId=" + MISSING_GROUP + " IpPermissions.1.IpProtocol=-1"
+ " | InvalidGroup.NotFound",
"AuthorizeSecurityGroupIngress | GroupId={group} IpPermissions.1.IpProtocol=-1"
+ " IpPermissions.1.PrefixListIds.1.PrefixListId=pl-0123456789abcdef0"
+ " | InvalidPrefixListID.NotFound",
"AuthorizeSecurityGroupIngress | GroupId={group} IpPermissions.1.IpProtocol=-1"
+ " TagSpecification.1.ResourceType=security-group-rule TagSpecification.1.Tag.1.Key=aws:dry-run"
+ " | InvalidParameter",
"AuthorizeSecurityGroupEgress | GroupId=" + MISSING_GROUP + " IpPermissions.1.IpProtocol=-1"
+ " | InvalidGroup.NotFound",
"RevokeSecurityGroupIngress | GroupId=" + MISSING_GROUP + " IpPermissions.1.IpProtocol=-1"
+ " | InvalidGroup.NotFound",
"RevokeSecurityGroupIngress | GroupId={group} SecurityGroupRuleId.1={egressRule}"
+ " | InvalidSecurityGroupRuleId.NotFound",
"RevokeSecurityGroupEgress | GroupId={group} SecurityGroupRuleId.1=" + MISSING_RULE
+ " | InvalidSecurityGroupRuleId.NotFound",
"ModifySecurityGroupRules | GroupId=" + MISSING_GROUP + " SecurityGroupRule.1.SecurityGroupRuleId="
+ MISSING_RULE + " | InvalidGroup.NotFound",
"ModifySecurityGroupRules | GroupId={group} SecurityGroupRule.1.SecurityGroupRuleId=" + MISSING_RULE
+ " SecurityGroupRule.1.SecurityGroupRule.Description=changed"
+ " | InvalidSecurityGroupRuleId.NotFound"
})
void aDryRunTheRealCallWouldRefuseKeepsItsError(String action, String params, String code) {
String before = snapshot();
@@ -143,7 +187,8 @@ class Ec2VpcDryRunIntegrationTest {
/**
* Everything these calls can change in the test's account, as the describe calls report it: the VPCs
* and what DeleteVpc removes with one (its default security group and network ACL), the subnets, the
* network interface, the internet gateways and the route tables with their routes and associations.
* network interface, the internet gateways, the route tables with their routes and associations, and the
* security groups with their rules.
*/
private String snapshot() {
return String.join("\n",
@@ -151,6 +196,7 @@ class Ec2VpcDryRunIntegrationTest {
body("DescribeSubnets"),
body("DescribeNetworkInterfaces"),
body("DescribeSecurityGroups"),
body("DescribeSecurityGroupRules"),
body("DescribeNetworkAcls"),
body("DescribeInternetGateways"),
body("DescribeRouteTables"));
@@ -181,6 +227,12 @@ class Ec2VpcDryRunIntegrationTest {
return result;
}
/** Adds {@code port} to the fixture's group in the direction {@code action} names, and returns the rule's id. */
private String authorize(String action, int port) {
return create(action, "securityGroupRuleSet.item.securityGroupRuleId",
params("GroupId={group} " + PERMISSION.formatted(port)));
}
/** Runs {@code action} and returns what its answer holds at {@code path}. */
private String create(String action, String path, String... params) {
return ec2(action, params).getString(action + "Response." + path);