feat(cloudformation): apply security-group rules — inline properties and standalone resources (#1993)

* feat(cloudformation): apply security-group rules — inline properties and standalone resources

Inline SecurityGroupIngress/Egress on AWS::EC2::SecurityGroup were
silently dropped (groups deployed with no rules), and the standalone
AWS::EC2::SecurityGroupIngress/Egress resource types were unsupported.
Both now map onto the existing Ec2Service authorize APIs, including
CidrIp/CidrIpv6 ranges and Source/DestinationSecurityGroupId peer pairs.
Rules are removed with their group, so stack delete needs no revoke.

Fixes #1992

* refactor(cloudformation): move standalone security-group rules into a per-service provisioner

The standalone AWS::EC2::SecurityGroupIngress and AWS::EC2::SecurityGroupEgress
types move out of the CloudFormationResourceProvisioner switch and into
Ec2SecurityGroupRuleCfnProvisioner, discovered through the CDI registry. The
inline SecurityGroupIngress/SecurityGroupEgress properties stay with
AWS::EC2::SecurityGroup, which has not been extracted yet, and call the shared
rule-to-IpPermission mapping so there is one copy of it.

Along with the move:

- delete() revokes the rule. A standalone rule can target a group that outlives
  the stack, so DeleteStack and create rollback used to mark the resource gone
  while its permission stayed active on the group.
- Update revokes the rule the previous execution created before authorizing.
  The authorize APIs append, so re-running a template used to duplicate an
  unchanged rule and orphan the permission of a changed one.
- A rule's Description now reaches its ipv6 range, and DescribeSecurityGroups
  reports ipv6 range descriptions.
- GroupName resolves to a group id instead of being passed through as one.

Ec2Service.deleteSecurityGroupRule removes a rule by SecurityGroupRuleId: the
rule record plus the one permission (or the one range within it) that the record
describes. The existing by-permission revoke matches on protocol and ports
alone, which would strip a group's unrelated rules that share them.

* fix(ec2): security-group rule records carry their peer, so deletion hits the right rule

Three review findings with one root cause.

createRules only turned ipv4 ranges into rule records. An ipv6 range or a
referenced group collapsed into a single record holding nothing but protocol
and ports, so DescribeSecurityGroupRules could not report the peer, and
deleting one of several rules sharing a port revoked whichever permission
happened to carry no ipv4 ranges — the requested rule stayed active while an
unrelated one disappeared. Records are now created per peer, as AWS does: one
per ipv4 range, one per ipv6 range, one per referenced group, with the peer
recorded on each. removeRecordedPermission matches on that peer and drops the
enclosing permission only once nothing is left in it. A record naming no peer
matches only a permission that names none either, instead of falling back to
the first port match. DescribeSecurityGroupRules gained referencedGroupInfo.

The CFN provisioner updated a standalone rule by revoking then authorizing,
so a rejected replacement left the group with neither rule: rollback keeps the
old physical id but never recreates its permission, and the stack settled as
UPDATE_ROLLBACK_COMPLETE minus a valid rule. It now authorizes first and
revokes the previous rule only after that succeeds.

* fix(cloudformation): a security-group rule names exactly one peer

CloudFormation documents exactly one source per rule, an IPv4 range, an IPv6
range, a prefix list or a security group. Floci read each peer property
independently, and authorize creates a rule record per peer, so a rule naming
several kept only the first record as its physical id. Delete revoked that one
and the rest stayed on the group, and a replacement leaked them. Naming more
than one is now a ValidationError, which covers the standalone resources and the
inline SecurityGroupIngress/Egress entries through the shared mapping.

Delete no longer swallows failures from deleteSecurityGroupRule. That call
already returns false for a rule it has no record of and succeeds when the group
is gone, so the cases the catch existed for never reached it, and what it did
absorb was a real failure reported to CloudFormation as a successful delete.

* fix(cloudformation): a security-group rule carries its Description to a peer group

The ipv4 and ipv6 branches both put Description on the range they build, while
the peer-group branch left it off the UserIdGroupPair. Ec2Service reads the
description straight off the pair, so a rule declaring SourceSecurityGroupId or
DestinationSecurityGroupId with a Description came back from
DescribeSecurityGroupRules without it.

* fix(cloudformation): a security-group rule naming no source is rejected

The peer check counted sources and rejected more than one, so a rule naming
none passed and sent an IpPermission with no cidr, prefix list or group on it.
CloudFormation then reported the source-less rule as successfully provisioned.
AWS requires exactly one, so zero is as invalid as several.

* fix(cloudformation): a security-group rule can name its peer group by name

The source count read SourceSecurityGroupId but not SourceSecurityGroupName, so
tightening the count to exactly one rejected a template that named its peer by
name. The ingress schema lists both, along with SourceSecurityGroupOwnerId for a
group in another account, and neither was read. Egress has no name variant.

The name is handed to Ec2Service as a name rather than resolved here.
resolveGroupReferences maps it to an id on authorize before createRules records
the rule, so the delete path still matches on the resolved id.

Also drops a stale comment three lines above the code it contradicted, claiming
UserIdGroupPair has no description field.
This commit is contained in:
lex00 authored and GitHub committed 2026-08-18 07:07:37 -04:00
1 parent 74e43a4632
commit 1461a10de7
7 files changed
+1213 -1

No files matched your search

@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollba
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2SecurityGroupRuleCfnProvisioner;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters;
@@ -762,6 +763,22 @@ public class CloudFormationResourceProvisioner {
if (sg.getVpcId() != null) {
r.getAttributes().put("VpcId", sg.getVpcId());
}
// Inline rule properties — previously dropped, leaving the group empty. The mapping is
// shared with the standalone SecurityGroupIngress/Egress resource types, which live in
// Ec2SecurityGroupRuleCfnProvisioner; this arm joins them when it is extracted.
if (props != null && props.has("SecurityGroupIngress")) {
for (JsonNode rule : props.get("SecurityGroupIngress")) {
ec2Service.authorizeSecurityGroupIngress(region, sg.getGroupId(),
List.of(Ec2SecurityGroupRuleCfnProvisioner.toIpPermission(rule, engine)));
}
}
if (props != null && props.has("SecurityGroupEgress")) {
for (JsonNode rule : props.get("SecurityGroupEgress")) {
ec2Service.authorizeSecurityGroupEgress(region, sg.getGroupId(),
List.of(Ec2SecurityGroupRuleCfnProvisioner.toIpPermission(rule, engine)));
}
}
}
private void provisionInternetGateway(StackResource r, String region) {
@@ -0,0 +1,211 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.IpPermission;
import io.github.hectorvent.floci.services.ec2.model.IpRange;
import io.github.hectorvent.floci.services.ec2.model.Ipv6Range;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;
import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
/**
* CloudFormation provisioning for the standalone security-group rule resources:
* {@code AWS::EC2::SecurityGroupIngress} and {@code AWS::EC2::SecurityGroupEgress} (issue #1992).
*
* <p>The rule-object to {@link IpPermission} mapping lives here as
* {@link #toIpPermission(JsonNode, CloudFormationTemplateEngine)} because the inline
* {@code SecurityGroupIngress}/{@code SecurityGroupEgress} properties of
* {@code AWS::EC2::SecurityGroup} take the same shape. That arm is still in
* {@code CloudFormationResourceProvisioner} and calls this method, so there is one mapping rather
* than two; it moves here when the security-group arm itself is extracted.
*/
@ApplicationScoped
public class Ec2SecurityGroupRuleCfnProvisioner implements CfnResourceProvisioner {
private static final String INGRESS = "AWS::EC2::SecurityGroupIngress";
private static final String EGRESS = "AWS::EC2::SecurityGroupEgress";
private final Ec2Service ec2Service;
@Inject
public Ec2SecurityGroupRuleCfnProvisioner(Ec2Service ec2Service) {
this.ec2Service = ec2Service;
}
@Override
public Set<String> resourceTypes() {
return Set.of(INGRESS, EGRESS);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
boolean ingress = switch (r.getResourceType()) {
case INGRESS -> true;
case EGRESS -> false;
default -> throw new IllegalStateException(
"Ec2SecurityGroupRuleCfnProvisioner cannot handle " + r.getResourceType());
};
String groupId = resolveGroupId(props, ctx);
IpPermission perm = toIpPermission(props, ctx.engine());
// UpdateStack re-executes every resource with the physical id it got at create time, and the
// authorize APIs are append-only, so the rule the previous execution created has to go:
// otherwise an unchanged rule doubles up on the group, and a changed one leaves its old
// permission behind. These resources are immutable in CloudFormation — every property change
// is a replacement — so the update semantics are authorize-then-revoke.
//
// Authorize first, revoke second. The other order leaves the group with neither rule when
// the new authorization fails, and rollback keeps the old physical id without recreating
// its permission, so the stack settles as UPDATE_ROLLBACK_COMPLETE minus a valid rule.
String previousRuleId = r.getPhysicalId();
List<SecurityGroupRule> rules = ingress
? ec2Service.authorizeSecurityGroupIngress(ctx.region(), groupId, List.of(perm))
: ec2Service.authorizeSecurityGroupEgress(ctx.region(), groupId, List.of(perm));
if (previousRuleId != null && previousRuleId.startsWith("sgr-")) {
ec2Service.deleteSecurityGroupRule(ctx.region(), previousRuleId);
}
// Ref and Fn::GetAtt Id both return the rule id, as they do in CloudFormation. The logical
// id is only a fallback for the (unreachable in practice) case of no rule being recorded —
// a null physical id would make the stack skip this resource on delete.
String ruleId = !rules.isEmpty() && rules.get(0).getSecurityGroupRuleId() != null
? rules.get(0).getSecurityGroupRuleId()
: r.getLogicalId();
r.setPhysicalId(ruleId);
r.getAttributes().put("Id", ruleId);
}
@Override
public void delete(String resourceType, String physicalId, String region) {
if (physicalId == null || !physicalId.startsWith("sgr-")) {
return;
}
// A standalone rule can target a group that outlives the stack, so the permission has to be
// revoked explicitly. deleteSecurityGroupRule already absorbs the two cases a stack delete
// runs into, returning false for a rule that is no longer recorded and succeeding when the
// group itself is gone, so a throw from here is a real failure and belongs to the caller.
ec2Service.deleteSecurityGroupRule(region, physicalId);
}
/**
* Maps a CloudFormation rule object — the properties of a standalone
* SecurityGroupIngress/Egress resource, or one entry of a security group's inline
* {@code SecurityGroupIngress}/{@code SecurityGroupEgress} list — onto the EC2 model.
*/
public static IpPermission toIpPermission(JsonNode rule, CloudFormationTemplateEngine engine) {
IpPermission perm = new IpPermission();
String protocol = resolve(rule, "IpProtocol", engine);
perm.setIpProtocol(protocol != null ? protocol : "-1");
if (rule != null && rule.hasNonNull("FromPort")) {
perm.setFromPort(rule.get("FromPort").asInt());
}
if (rule != null && rule.hasNonNull("ToPort")) {
perm.setToPort(rule.get("ToPort").asInt());
}
// One Description property covers whichever peer the rule names, matching CloudFormation.
String description = resolve(rule, "Description", engine);
String cidr = resolve(rule, "CidrIp", engine);
String cidr6 = resolve(rule, "CidrIpv6", engine);
String peerGroup = firstNonBlank(
resolve(rule, "SourceSecurityGroupId", engine),
resolve(rule, "DestinationSecurityGroupId", engine));
// Ingress also names a peer by group name, with an owner id for a group in another
// account. Egress has no name variant. Counting only the id form rejected a template
// that did name exactly one source.
String peerGroupName = resolve(rule, "SourceSecurityGroupName", engine);
String peerGroupOwner = resolve(rule, "SourceSecurityGroupOwnerId", engine);
String prefixList = firstNonBlank(
resolve(rule, "SourcePrefixListId", engine),
resolve(rule, "DestinationPrefixListId", engine));
// "You must specify exactly one of the following sources: an IPv4 address range, an IPv6
// address range, a prefix list, or a security group." Naming several used to authorize a
// rule record per peer while only the first id was kept, so delete revoked one of them and
// an update left the others on the group.
String peer = firstNonBlank(peerGroup, peerGroupName);
long sources = Stream.of(cidr, cidr6, peer, prefixList)
.filter(s -> s != null && !s.isBlank())
.count();
// Exactly one, so zero is rejected too. Letting none through sent an IpPermission naming
// no peer at all, which the stack then reported as successfully provisioned.
if (sources != 1) {
throw new AwsException("ValidationError",
"A security group rule must specify exactly one of CidrIp, CidrIpv6, "
+ "a prefix list, or a security group.", 400);
}
if (cidr != null && !cidr.isBlank()) {
IpRange range = new IpRange();
range.setCidrIp(cidr);
range.setDescription(description);
perm.getIpRanges().add(range);
}
if (cidr6 != null && !cidr6.isBlank()) {
Ipv6Range range6 = new Ipv6Range();
range6.setCidrIpv6(cidr6);
range6.setDescription(description);
perm.getIpv6Ranges().add(range6);
}
if (peer != null && !peer.isBlank()) {
UserIdGroupPair pair = new UserIdGroupPair();
// Ec2Service resolves a name to an id on authorize, before it records the rule, so the
// name form is handed over as-is rather than resolved twice.
if (peerGroup != null && !peerGroup.isBlank()) {
pair.setGroupId(peerGroup);
} else {
pair.setGroupName(peerGroupName);
}
if (peerGroupOwner != null && !peerGroupOwner.isBlank()) {
pair.setUserId(peerGroupOwner);
}
pair.setDescription(description);
perm.getUserIdGroupPairs().add(pair);
}
return perm;
}
/**
* GroupId is the VPC form. GroupName is the EC2-Classic/default-VPC form: look the group up by
* name so the rule lands on it, falling back to the raw name so a miss reports what was asked
* for rather than {@code null}.
*/
private String resolveGroupId(JsonNode props, ProvisionContext ctx) {
String groupId = ctx.resolveOptional(props, "GroupId");
if (groupId != null && !groupId.isBlank()) {
return groupId;
}
String groupName = ctx.resolveOptional(props, "GroupName");
if (groupName == null || groupName.isBlank()) {
return null;
}
return ec2Service.describeSecurityGroups(ctx.region(), List.of(), List.of(groupName), Map.of())
.stream()
.map(SecurityGroup::getGroupId)
.findFirst()
.orElse(groupName);
}
private static String firstNonBlank(String preferred, String fallback) {
return preferred != null && !preferred.isBlank() ? preferred : fallback;
}
private static String resolve(JsonNode props, String name, CloudFormationTemplateEngine engine) {
if (props == null || !props.has(name) || props.get(name).isNull()) {
return null;
}
return engine.resolve(props.get(name));
}
}
@@ -2528,6 +2528,108 @@ public class Ec2Service implements ContainerTeardown {
}
}
/**
* Deletes a rule by its {@code sgr-} id, which is what a standalone
* {@code AWS::EC2::SecurityGroupIngress} or {@code Egress} resource holds as its physical id.
* Returns false when the rule is already gone, so a stack delete stays idempotent.
*/
public boolean deleteSecurityGroupRule(String region, String securityGroupRuleId) {
ensureDefaultResources(region);
SecurityGroupRule rule = securityGroupRules.get(key(region, securityGroupRuleId)).orElse(null);
if (rule == null) {
return false;
}
securityGroupRules.delete(key(region, securityGroupRuleId));
String groupId = rule.getGroupId();
if (groupId == null) {
return true;
}
synchronized (lockFor(key(region, groupId))) {
SecurityGroup sg = securityGroups.get(key(region, groupId)).orElse(null);
if (sg == null) {
return true;
}
List<IpPermission> next = new ArrayList<>(rule.isEgress()
? sg.getIpPermissionsEgress() : sg.getIpPermissions());
if (removeRecordedPermission(next, rule)) {
if (rule.isEgress()) {
sg.setIpPermissionsEgress(next);
} else {
sg.setIpPermissions(next);
}
securityGroups.put(key(region, groupId), sg);
}
}
if (!rule.isEgress()) {
reconcilePublishedPortsForGroup(region, groupId);
}
return true;
}
/**
* Drops exactly the peer a rule record names, its ipv4 cidr, ipv6 cidr or referenced group, and
* the whole permission only once nothing is left in it. Matching on protocol and ports alone
* would take out an unrelated rule that happens to share them.
*/
private boolean removeRecordedPermission(List<IpPermission> perms, SecurityGroupRule rule) {
String referencedGroupId = rule.getReferencedGroupInfo() == null
? null : rule.getReferencedGroupInfo().getGroupId();
for (IpPermission perm : perms) {
if (!Objects.equals(perm.getIpProtocol(), rule.getIpProtocol())
|| !Objects.equals(perm.getFromPort(), rule.getFromPort())
|| !Objects.equals(perm.getToPort(), rule.getToPort())) {
continue;
}
if (rule.getCidrIpv6() != null) {
Ipv6Range match6 = perm.getIpv6Ranges().stream()
.filter(r -> rule.getCidrIpv6().equals(r.getCidrIpv6()))
.findFirst().orElse(null);
if (match6 == null) {
continue;
}
perm.getIpv6Ranges().remove(match6);
dropIfEmpty(perms, perm);
return true;
}
if (referencedGroupId != null) {
UserIdGroupPair matchPair = perm.getUserIdGroupPairs().stream()
.filter(pair -> referencedGroupId.equals(pair.getGroupId()))
.findFirst().orElse(null);
if (matchPair == null) {
continue;
}
perm.getUserIdGroupPairs().remove(matchPair);
dropIfEmpty(perms, perm);
return true;
}
if (rule.getCidrIpv4() != null) {
IpRange match = perm.getIpRanges().stream()
.filter(r -> rule.getCidrIpv4().equals(r.getCidrIp()))
.findFirst().orElse(null);
if (match == null) {
continue;
}
perm.getIpRanges().remove(match);
dropIfEmpty(perms, perm);
return true;
}
// A record naming no peer matches only a permission that names none either.
if (perm.getIpRanges().isEmpty() && perm.getIpv6Ranges().isEmpty()
&& perm.getUserIdGroupPairs().isEmpty()) {
perms.remove(perm);
return true;
}
}
return false;
}
private static void dropIfEmpty(List<IpPermission> perms, IpPermission perm) {
if (perm.getIpRanges().isEmpty() && perm.getIpv6Ranges().isEmpty()
&& perm.getUserIdGroupPairs().isEmpty()) {
perms.remove(perm);
}
}
private SecurityGroup getRequiredSecurityGroup(String region, String groupId) {
SecurityGroup sg = securityGroups.get(key(region, groupId)).orElse(null);
if (sg == null)