fix(cloudformation): keep unchanged VPCs and security groups on stack update (#3033)

* fix(cloudformation): keep unchanged VPCs and security groups on stack update

provision() re-runs for every resource on every UpdateStack, changed or not.
Ec2VpcCfnProvisioner called createVpc() and provisionSecurityGroup() called
createSecurityGroup() unconditionally, so an untouched VPC or security group was
re-created under a fresh id on every update - silently orphaning every subnet,
route table and group that referenced the old one.

The security group case hid behind the VPC one: because the VPC id changed too,
the (name, vpcId) duplicate check never fired, so the stack still reported
UPDATE_COMPLETE while leaking a second group.

Both now reuse the resource the stack already points at. A changed CidrBlock
(VPC) or a changed GroupName (security group) is still treated as a replacement,
and a resource deleted out of band still falls back to create.

Adds CfnUnchangedResourceUpdateIntegrationTest, which asserts physical-id
retention across an update for VPC, security group, S3 bucket, SQS, SNS, log
group, ECR, KMS alias and Kinesis. Asserting UPDATE_COMPLETE alone is not
enough - a re-created resource passes that while breaking every reference to it.

* fix(cloudformation): reconcile a reused security group's inline rules

Reusing an unchanged security group instead of re-creating it exposed a second
bug in the same arm: authorizeSecurityGroupIngress/Egress append without a
duplicate check, and the inline SecurityGroupIngress/SecurityGroupEgress loops
run on every provision pass. A reused group therefore accumulated another copy
of every inline rule on each UpdateStack. Re-creating the group had masked
this, since each update authorized onto a brand new group.

Clear the rule sets the template declares before re-authorizing, which also
drops rules the template no longer lists. A set the template does not declare is
left alone, so a group keeps its default egress.

Also narrows reuse: GroupName, GroupDescription and VpcId are immutable on a
security group, so a template that changes one wants a new group rather than an
edit to this one. Only the GroupName check was exercised before.

Adds securityGroupInlineRulesAreNotDuplicatedByAnUpdate, which asserts the
group still describes each inline rule exactly once after an update. Verified
non-vacuous: without the revoke it fails with the rule present twice.

* test(cloudformation): focused provisioner coverage for AWS::EC2::VPC

Mirrors S3CfnProvisionerTest: mocks only Ec2Service and pins the create path's
Fn::GetAtt keys (VpcId, CidrBlock, DefaultSecurityGroup) alongside the three
update outcomes - reuse when nothing changed, replacement on a changed
CidrBlock, and a fresh create when the VPC is gone from the backend.

The integration test asserts physical-id retention end to end but cannot show
which service call was made; this pins that createVpc is not called at all on
an unchanged update.

* fix(cloudformation): authorize only the inline rules a group is missing

Clearing the declared rule sets before re-authorizing fixed the duplication but
introduced a worse defect: a group can also carry rules from standalone
AWS::EC2::SecurityGroupIngress/Egress resources, and the revoke took those with
it, so an unrelated stack update silently closed ports another resource owns. A
rule rejected mid-authorize also left the prior set already deleted, with
nothing to restore it.

Reconciliation is now additive. Each declared rule is authorized only when the
group does not already carry it, compared on a canonical key since IpPermission
and its range types define no equals. Nothing is revoked, so neither failure
mode is reachable.

The trade-off is explicit: a rule dropped from the template is no longer
revoked. Doing that safely needs the provisioner to record which rules it
authorized, which this arm cannot do while it lives in the legacy monolith.

Also compares the VpcId a template would actually resolve to rather than the
raw property. createSecurityGroup resolves an omitted VpcId to the region's
default VPC, so the stored group always has one - comparing against a null
property let a template that drops VpcId keep a group in the VPC it had named.

Adds anUpdateLeavesRulesOwnedByStandaloneResourcesAlone. Verified non-vacuous:
restoring the revoke fails it with the standalone rule gone.

* fix(cloudformation): branch AWS::EC2::VPC on the context's prior id

provision() serves create and update, and assigns the new physical id onto the
resource as it runs, so deciding create-vs-update by reading that id back flips
mid-method. AGENTS.md step 4 asks for ctx.isUpdate()/ctx.priorPhysicalId()
instead, and the Scheduler provisioner shed the same pattern in #2985.

The two agree on today's call path, since the engine seeds both from the same
existing id, so this is the convention rather than a live defect. The test was
the part that had it wrong: it built a create-path context and set the prior id
only on the resource, so it passed either way.

Pinned by anIdOnTheResourceAloneDoesNotCountAsAnUpdate, which provisions a
resource carrying an id under a create context and fails when the VPC is looked
up for reuse instead of created.

* fix(cloudformation): match a security group rule that names its peer

A rule naming its peer through SourceSecurityGroupName was re-authorized on
every update. Ec2Service.resolveGroupReferences fills in groupId on the pair as
it records the rule, the declaration toIpPermission hands back on the next pass
carries only the name, and the duplicate key preferred the id whenever one was
present, so the two forms never matched and the group accumulated another copy
of the rule each time.

Both sides now resolve a bare name to its group id before keying, the same
lookup the service performs, confined to the group's own VPC because names are
unique per VPC. A name matching nothing there stays a name, which is also what
the service does, so an unresolvable peer still compares equal to itself.

Pinned by aRuleNamingItsPeerByNameIsNotDuplicatedByAnUpdate, which reports the
rule twice when the resolution is dropped. Its DependsOn is load-bearing: the
peer has to exist when the rule is first authorized, or the stored pair keeps
the unresolved name and both sides agree for the wrong reason.

Also moves a doc comment back onto the test it describes.

* test(cloudformation): parse the describe body with XmlParser

The physical-id helper pulled LogicalResourceId/PhysicalResourceId pairs out of
the DescribeStackResources response with a regex, which the repo rules forbid
for XML. extractGroups on "member" gives the same pairs as a map per resource,
so the member is picked by its logical id rather than by matching across tags.
This commit is contained in:
Jerald Lindberg authored and GitHub committed 2026-09-09 18:12:47 -05:00
1 parent cf1aabce39
commit dde11aeb6a
4 files changed
+691 -10

No files matched your search

@@ -41,10 +41,16 @@ import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;
import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
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.PrefixListId;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.kinesis.model.KinesisStream;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
import io.github.hectorvent.floci.services.rds.RdsService;
@@ -702,7 +708,13 @@ public class CloudFormationResourceProvisioner {
description = "Managed by CloudFormation";
}
String vpcId = resolveOptional(props, "VpcId", engine);
var sg = ec2Service.createSecurityGroup(region, groupName, description, vpcId);
// provision() re-runs for every resource on every update. Re-creating an unchanged group
// would mint a new group id (and collide on the name whenever the VPC id is stable), so
// reuse the group this resource already points at.
var reconciled = existingSecurityGroupToReconcile(r.getPhysicalId(), groupName, description, vpcId, region);
final SecurityGroup sg = reconciled != null
? reconciled
: ec2Service.createSecurityGroup(region, groupName, description, vpcId);
// Ref on AWS::EC2::SecurityGroup returns the group id for VPC security groups.
r.setPhysicalId(sg.getGroupId());
r.getAttributes().put("GroupId", sg.getGroupId());
@@ -713,17 +725,24 @@ public class CloudFormationResourceProvisioner {
// 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.
// Authorize appends without a duplicate check, so re-running this on a reused group would
// stack another copy of every inline rule on each update. Only authorize what the group
// does not already carry.
//
// Deliberately additive: a rule dropped from the template is not revoked here. Revoking
// the difference would mean revoking permissions this resource cannot prove it owns - a
// group can also carry rules from standalone AWS::EC2::SecurityGroupIngress/Egress
// resources, and clearing them on an unrelated update would close ports another stack
// resource is responsible for. Removing a rule the template no longer declares needs the
// provisioner to record what it authorized; noted as a follow-up.
var peerGroupId = peerGroupIdResolver(region, sg.getVpcId());
if (props != null && props.has("SecurityGroupIngress")) {
for (JsonNode rule : props.get("SecurityGroupIngress")) {
ec2Service.authorizeSecurityGroupIngress(region, sg.getGroupId(),
List.of(Ec2SecurityGroupRuleCfnProvisioner.toIpPermission(rule, engine)));
}
authorizeMissing(props.get("SecurityGroupIngress"), sg.getIpPermissions(), engine, peerGroupId,
perms -> ec2Service.authorizeSecurityGroupIngress(region, sg.getGroupId(), perms));
}
if (props != null && props.has("SecurityGroupEgress")) {
for (JsonNode rule : props.get("SecurityGroupEgress")) {
ec2Service.authorizeSecurityGroupEgress(region, sg.getGroupId(),
List.of(Ec2SecurityGroupRuleCfnProvisioner.toIpPermission(rule, engine)));
}
authorizeMissing(props.get("SecurityGroupEgress"), sg.getIpPermissionsEgress(), engine, peerGroupId,
perms -> ec2Service.authorizeSecurityGroupEgress(region, sg.getGroupId(), perms));
}
}
@@ -1207,6 +1226,120 @@ public class CloudFormationResourceProvisioner {
r.getAttributes().put("DBClusterParameterGroupName", group.getDbClusterParameterGroupName());
}
/** The VPC a security group would land in for this template value: the default when omitted. */
private String effectiveVpcId(String vpcId, String region) {
return vpcId != null && !vpcId.isEmpty() ? vpcId : String.valueOf(ec2Service.resolveDefaultVpcId(region));
}
/**
* Authorizes each declared rule that the group does not already carry, one call per rule so a
* rejected rule cannot take its siblings down with it.
*/
private void authorizeMissing(JsonNode declared, List<IpPermission> existing,
CloudFormationTemplateEngine engine,
java.util.function.UnaryOperator<String> peerGroupId,
java.util.function.Consumer<List<IpPermission>> authorize) {
Set<String> present = existing.stream()
.map(p -> permissionKey(p, peerGroupId))
.collect(java.util.stream.Collectors.toSet());
for (JsonNode rule : declared) {
IpPermission perm = Ec2SecurityGroupRuleCfnProvisioner.toIpPermission(rule, engine);
if (present.add(permissionKey(perm, peerGroupId))) {
authorize.accept(List.of(perm));
}
}
}
/**
* Resolves a peer group's name to its id, the same lookup {@code Ec2Service} performs when it
* stores an authorized rule. Group names are unique per VPC rather than per region, so the
* search is confined to the group being authorized. A name matching nothing there stays a
* name, which is also what the service does.
*/
private java.util.function.UnaryOperator<String> peerGroupIdResolver(String region, String vpcId) {
return groupName -> ec2Service.describeSecurityGroups(region, List.of(), List.of(groupName), Map.of())
.stream()
.filter(peer -> Objects.equals(vpcId, peer.getVpcId()))
.map(SecurityGroup::getGroupId)
.filter(Objects::nonNull)
.findFirst()
.orElse(groupName);
}
/**
* Identity of a permission for duplicate detection. {@link IpPermission} and the range types
* it holds define no {@code equals}, so compare a canonical rendering instead. Descriptions
* are left out: AWS treats a rule differing only by description as the same rule.
*/
private static String permissionKey(IpPermission p, java.util.function.UnaryOperator<String> peerGroupId) {
return String.join("|",
String.valueOf(p.getIpProtocol()),
String.valueOf(p.getFromPort()),
String.valueOf(p.getToPort()),
p.getIpRanges().stream().map(IpRange::getCidrIp).filter(Objects::nonNull).sorted()
.collect(java.util.stream.Collectors.joining(",")),
p.getIpv6Ranges().stream().map(Ipv6Range::getCidrIpv6).filter(Objects::nonNull).sorted()
.collect(java.util.stream.Collectors.joining(",")),
p.getUserIdGroupPairs().stream()
.map(g -> peerIdentity(g, peerGroupId))
.filter(Objects::nonNull).sorted()
.collect(java.util.stream.Collectors.joining(",")),
p.getPrefixListIds().stream().map(PrefixListId::getPrefixListId)
.filter(Objects::nonNull).sorted()
.collect(java.util.stream.Collectors.joining(",")));
}
/**
* How a peer group is identified when two permissions are compared: its id whenever one can be
* had. A stored pair already carries one, because authorize resolves the name as it records the
* rule, while a pair straight from the template carries only the name it was declared with.
* Keying a resolved id against an unresolved name never matches, which re-authorized a rule
* naming its peer through {@code SourceSecurityGroupName} on every single update.
*/
private static String peerIdentity(UserIdGroupPair pair,
java.util.function.UnaryOperator<String> peerGroupId) {
if (pair.getGroupId() != null) {
return pair.getGroupId();
}
return pair.getGroupName() == null ? null : peerGroupId.apply(pair.getGroupName());
}
/**
* The security group this stack resource already points at, when an UpdateStack re-invocation
* left it unchanged. Unlike most resources the physical id here is the group <em>id</em>, not
* the name, so the rename check compares the stored group's name against the template's.
*
* <p>Returns {@code null} for a fresh create, a group deleted out of band, or any change AWS
* treats as a replacement: GroupName, GroupDescription and VpcId are all immutable on a
* security group, so a template that changes one wants a new group, not an edit to this one.
* The caller then creates.
*/
private SecurityGroup existingSecurityGroupToReconcile(String priorPhysicalId, String groupName,
String description, String vpcId, String region) {
if (priorPhysicalId == null || priorPhysicalId.isBlank()) {
return null;
}
try {
return ec2Service.describeSecurityGroups(region, List.of(priorPhysicalId), List.of(), Map.of())
.stream()
.filter(existing -> groupName == null || groupName.equals(existing.getGroupName()))
.filter(existing -> description == null || description.equals(existing.getDescription()))
// Compare the VpcId the template would actually get, not the raw property.
// createSecurityGroup resolves an omitted VpcId to the region's default VPC,
// so the stored group always has one: comparing against a null property would
// either force a replacement on every update, or - the bug - let a template
// that drops VpcId keep a group sitting in the explicit VPC it named before.
.filter(existing -> effectiveVpcId(vpcId, region).equals(existing.getVpcId()))
.findFirst()
.orElse(null);
} catch (AwsException notFound) {
// Expected when the group was deleted out of band since the prior update.
LOG.debugv(notFound, "No existing security group {0} found on file, falling back to create",
priorPhysicalId);
return null;
}
}
/**
* Looks up {@code name} via {@code lookup} when this is an update re-invocation for the same
* physical resource (i.e. {@code priorPhysicalId} is set and unchanged), returning {@code null}
@@ -1,10 +1,13 @@
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.model.StackResource;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Vpc;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.List;
import java.util.Map;
@@ -17,6 +20,8 @@ import java.util.Set;
@ApplicationScoped
public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(Ec2VpcCfnProvisioner.class);
private final Ec2Service ec2Service;
@Inject
@@ -32,7 +37,8 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
String cidr = ctx.resolveOptional(props, "CidrBlock");
var vpc = ec2Service.createVpc(ctx.region(), cidr, false);
Vpc reconciled = existingVpcToReconcile(ctx.isUpdate() ? ctx.priorPhysicalId() : null, cidr, ctx.region());
final Vpc vpc = reconciled != null ? reconciled : ec2Service.createVpc(ctx.region(), cidr, false);
r.setPhysicalId(vpc.getVpcId());
r.getAttributes().put("VpcId", vpc.getVpcId());
if (vpc.getCidrBlock() != null) {
@@ -46,6 +52,42 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
.ifPresent(sg -> r.getAttributes().put("DefaultSecurityGroup", sg.getGroupId()));
}
/**
* The VPC this stack resource already points at, when an UpdateStack re-invocation left it
* unchanged. {@code provision()} re-runs for every resource on every update, so creating
* unconditionally would mint a fresh VPC id and silently orphan every subnet, route table and
* security group that referenced the old one.
*
* <p>Returns {@code null} for a fresh create, for a CidrBlock change (which AWS treats as a
* replacement), or when the VPC is gone from the backend - the caller then creates.
*
* <p>The prior id is the one the context captured, not the one on the {@link StackResource}:
* {@code provision} assigns the new id onto that resource as it runs, so a resource-derived
* check flips from create to update mid-method.
*/
private Vpc existingVpcToReconcile(String priorPhysicalId, String cidr, String region) {
if (priorPhysicalId == null || priorPhysicalId.isBlank()) {
return null;
}
Vpc existing;
try {
existing = ec2Service.describeVpcs(region, List.of(priorPhysicalId), Map.of())
.stream().findFirst().orElse(null);
} catch (AwsException notFound) {
// Expected when the VPC was deleted out of band since the prior update.
LOG.debugv(notFound, "No existing VPC {0} found on file, falling back to create", priorPhysicalId);
return null;
}
if (existing == null) {
return null;
}
// A changed CidrBlock is a replacement on AWS, so let the caller create a new VPC.
if (cidr != null && !cidr.isBlank() && !cidr.equals(existing.getCidrBlock())) {
return null;
}
return existing;
}
// No delete override: the switch this replaces had no AWS::EC2::VPC delete arm,
// so stack teardown leaves the VPC alone. Adding one here would change teardown
// behavior beyond the scope of this extraction.
@@ -0,0 +1,351 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* UpdateStack must leave an unchanged resource alone, whatever its type.
*
* <p>{@code provision()} re-runs for every resource on every update, changed or not, so a
* provisioner that calls create unconditionally either collides with itself (rolling the stack
* back) or quietly mints a new physical id, orphaning everything that referenced the old one.
* Each case here builds a stack holding one resource plus a throwaway queue, updates only the
* queue, and asserts both that the stack reached UPDATE_COMPLETE and that the untouched resource
* kept its physical id.
*
* <p>Regression cover for "CloudFormation update recreates unchanged named resources"
* (floci-io/floci#2134).
*/
@QuarkusTest
class CfnUnchangedResourceUpdateIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260808/us-west-2/cloudformation/aws4_request";
private static String stackWith(String namedResourceJson, String queueName) {
return """
{
"Resources": {
%s,
"ChurnQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "%s"}
}
}
}
""".formatted(namedResourceJson, queueName);
}
/**
* Pulls the PhysicalResourceId of one logical resource out of a DescribeStackResources body.
* The member ordering is not guaranteed, so pick the member by its LogicalResourceId rather
* than by position.
*/
private static String physicalIdOf(String describeBody, String logicalId) {
return XmlParser.extractGroups(describeBody, "member").stream()
.filter(member -> logicalId.equals(member.get("LogicalResourceId")))
.map(member -> member.get("PhysicalResourceId"))
.findFirst()
.orElse(null);
}
private String namedPhysicalId(String stackName) {
String body = given()
.contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackResources").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.extract().body().asString();
return physicalIdOf(body, "Named");
}
/**
* Creates the stack, updates it with only the churn queue renamed, then asserts both that the
* update completed and that the untouched resource kept its physical id. The second assertion
* is the load-bearing one: a provisioner that re-creates the resource under a fresh id can
* still report UPDATE_COMPLETE while silently orphaning whatever referenced the old id.
*/
private void assertUnchangedResourceSurvivesUpdate(String label, String namedResourceJson) {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-" + label + "-" + suffix;
String body = namedResourceJson.replace("SUFFIX", suffix);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", stackWith(body, "probe-q-a-" + suffix))
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
String before = namedPhysicalId(stackName);
assertNotNull(before, "no PhysicalResourceId for Named after create");
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", stackWith(body, "probe-q-b-" + suffix))
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.body(not(containsString("ROLLBACK")));
assertEquals(before, namedPhysicalId(stackName),
label + ": unchanged resource was re-created under a new physical id");
}
private static final String EC2_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260808/us-west-2/ec2/aws4_request";
/** Runs create-then-update and hands back the Named physical id before and after. */
private String[] createThenUpdate(String label, String createBody, String updateBody) {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-" + label + "-" + suffix;
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", stackWith(createBody.replace("SUFFIX", suffix), "probe-q-a-" + suffix))
.when().post("/").then().statusCode(200);
String before = namedPhysicalId(stackName);
assertNotNull(before, "no PhysicalResourceId for Named after create");
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", stackWith(updateBody.replace("SUFFIX", suffix), "probe-q-b-" + suffix))
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.body(not(containsString("ROLLBACK")));
return new String[] {before, namedPhysicalId(stackName)};
}
private static final String SG_WITH_INGRESS = """
"Named": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupName": "probe-sg-SUFFIX",
"GroupDescription": "probe DESCRIPTION",
"SecurityGroupIngress": [
{"IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "CidrIp": "10.0.0.0/8"}
]
}
}""";
/**
* A group can carry rules from standalone AWS::EC2::SecurityGroupIngress resources as well as
* its own inline ones. Reconciling the inline set by clearing the group first would revoke
* those too, so a stack update unrelated to them would silently close their ports.
*/
@Test
void anUpdateLeavesRulesOwnedByStandaloneResourcesAlone() {
String body = """
"Named": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupName": "probe-sg-mixed-SUFFIX",
"GroupDescription": "probe mixed",
"SecurityGroupIngress": [
{"IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "CidrIp": "10.0.0.0/8"}
]
}
},
"ExtraRule": {
"Type": "AWS::EC2::SecurityGroupIngress",
"Properties": {
"GroupId": {"Ref": "Named"},
"IpProtocol": "tcp",
"FromPort": 8080,
"ToPort": 8080,
"CidrIp": "10.9.0.0/16"
}
}""";
String[] ids = createThenUpdate("sg-mixed", body, body);
assertEquals(ids[0], ids[1], "unchanged security group was re-created under a new physical id");
String described = given()
.contentType("application/x-www-form-urlencoded").header("Authorization", EC2_AUTH)
.formParam("Action", "DescribeSecurityGroups").formParam("GroupId.1", ids[1])
.when().post("/").then().statusCode(200)
.extract().body().asString();
assertEquals(1, described.split("<fromPort>22</fromPort>", -1).length - 1,
"inline rule should appear exactly once after an update");
assertEquals(1, described.split("<fromPort>8080</fromPort>", -1).length - 1,
"the standalone resource's rule was revoked by the inline reconciliation");
}
/**
* AuthorizeSecurityGroupIngress appends without a duplicate check, so re-running provision on a
* reused group stacks another copy of every inline rule on each update. Retaining the group id
* is not enough on its own: the group has to still describe the rules the template declares,
* once each.
*/
@Test
void securityGroupInlineRulesAreNotDuplicatedByAnUpdate() {
String body = SG_WITH_INGRESS.replace("DESCRIPTION", "stable");
String[] ids = createThenUpdate("sg-rules", body, body);
assertEquals(ids[0], ids[1], "unchanged security group was re-created under a new physical id");
String described = given()
.contentType("application/x-www-form-urlencoded").header("Authorization", EC2_AUTH)
.formParam("Action", "DescribeSecurityGroups").formParam("GroupId.1", ids[1])
.when().post("/").then().statusCode(200)
.extract().body().asString();
int occurrences = described.split("<fromPort>22</fromPort>", -1).length - 1;
assertEquals(1, occurrences,
"inline ingress rule appears " + occurrences + " times after one update; "
+ "provision re-authorized it on the reused group");
}
/**
* A rule naming its peer through SourceSecurityGroupName is the case the CidrIp rules above
* cannot reach. Ec2Service resolves the name to a group id as it records the rule, while the
* declaration the template hands back on the next update still carries only the name, so
* comparing the two forms directly finds no match and re-authorizes the rule every time.
*
* <p>DependsOn is load-bearing: the peer has to exist when the rule is first authorized, or
* the stored pair keeps the unresolved name and both sides agree for the wrong reason.
*/
@Test
void aRuleNamingItsPeerByNameIsNotDuplicatedByAnUpdate() {
String body = """
"Peer": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupName": "probe-sg-peer-SUFFIX",
"GroupDescription": "probe peer"
}
},
"Named": {
"Type": "AWS::EC2::SecurityGroup",
"DependsOn": "Peer",
"Properties": {
"GroupName": "probe-sg-byname-SUFFIX",
"GroupDescription": "probe by name",
"SecurityGroupIngress": [
{"IpProtocol": "tcp", "FromPort": 5432, "ToPort": 5432,
"SourceSecurityGroupName": "probe-sg-peer-SUFFIX"}
]
}
}""";
String[] ids = createThenUpdate("sg-byname", body, body);
assertEquals(ids[0], ids[1], "unchanged security group was re-created under a new physical id");
String described = given()
.contentType("application/x-www-form-urlencoded").header("Authorization", EC2_AUTH)
.formParam("Action", "DescribeSecurityGroups").formParam("GroupId.1", ids[1])
.when().post("/").then().statusCode(200)
.extract().body().asString();
int occurrences = described.split("<fromPort>5432</fromPort>", -1).length - 1;
assertEquals(1, occurrences,
"name-based ingress rule appears " + occurrences + " times after one update; "
+ "the stored peer is keyed by id and the declared one by name");
}
@Test
void logGroup() {
assertUnchangedResourceSurvivesUpdate("loggroup", """
"Named": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"LogGroupName": "/probe/log-SUFFIX"}
}""");
}
@Test
void snsTopic() {
assertUnchangedResourceSurvivesUpdate("sns", """
"Named": {
"Type": "AWS::SNS::Topic",
"Properties": {"TopicName": "probe-topic-SUFFIX"}
}""");
}
@Test
void sqsQueue() {
assertUnchangedResourceSurvivesUpdate("sqs", """
"Named": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "probe-queue-SUFFIX"}
}""");
}
@Test
void ecrRepository() {
assertUnchangedResourceSurvivesUpdate("ecr", """
"Named": {
"Type": "AWS::ECR::Repository",
"Properties": {"RepositoryName": "probe-repo-SUFFIX"}
}""");
}
@Test
void kmsAlias() {
assertUnchangedResourceSurvivesUpdate("kms", """
"Key": {"Type": "AWS::KMS::Key", "Properties": {}},
"Named": {
"Type": "AWS::KMS::Alias",
"Properties": {"AliasName": "alias/probe-SUFFIX", "TargetKeyId": {"Ref": "Key"}}
}""");
}
@Test
void kinesisStream() {
assertUnchangedResourceSurvivesUpdate("kinesis", """
"Named": {
"Type": "AWS::Kinesis::Stream",
"Properties": {"Name": "probe-stream-SUFFIX", "ShardCount": 1}
}""");
}
@Test
void securityGroup() {
assertUnchangedResourceSurvivesUpdate("sg", """
"Vpc": {
"Type": "AWS::EC2::VPC",
"Properties": {"CidrBlock": "10.99.0.0/16"}
},
"Named": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupName": "probe-sg-SUFFIX",
"GroupDescription": "probe",
"VpcId": {"Ref": "Vpc"}
}
}""");
}
@Test
void vpc() {
assertUnchangedResourceSurvivesUpdate("vpc", """
"Named": {
"Type": "AWS::EC2::VPC",
"Properties": {"CidrBlock": "10.98.0.0/16"}
}""");
}
@Test
void s3Bucket() {
assertUnchangedResourceSurvivesUpdate("s3", """
"Named": {
"Type": "AWS::S3::Bucket",
"Properties": {"BucketName": "probe-bucket-SUFFIX"}
}""");
}
}
@@ -0,0 +1,155 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.model.Vpc;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** {@code AWS::EC2::VPC}. */
class Ec2VpcCfnProvisionerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String REGION = "us-east-1";
private Ec2Service ec2;
private Ec2VpcCfnProvisioner provisioner;
private CloudFormationTemplateEngine engine;
@BeforeEach
void setUp() {
ec2 = mock(Ec2Service.class);
provisioner = new Ec2VpcCfnProvisioner(ec2);
engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(i -> {
JsonNode node = i.getArgument(0);
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0));
when(ec2.describeSecurityGroups(anyString(), any(), any(), any())).thenReturn(List.of());
}
private static JsonNode props(String json) {
try {
return MAPPER.readTree(json);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
private static Vpc vpc(String id, String cidr) {
Vpc v = new Vpc();
v.setVpcId(id);
v.setCidrBlock(cidr);
return v;
}
/**
* Provisions the way the engine does: an update arrives with the prior id on both the context
* and the resource, so a provisioner reading the wrong one still looks correct here. The
* create-path cases below are what separate them.
*/
private StackResource provision(String priorPhysicalId, String json) {
return provision(priorPhysicalId, priorPhysicalId, json);
}
private StackResource provision(String contextPriorId, String resourcePhysicalId, String json) {
StackResource r = new StackResource();
r.setLogicalId("Vpc");
r.setResourceType("AWS::EC2::VPC");
r.setPhysicalId(resourcePhysicalId);
ProvisionContext ctx =
new ProvisionContext(engine, REGION, "000000000000", "my-stack", contextPriorId);
provisioner.provision(r, props(json), ctx);
return r;
}
@Test
void refIsTheVpcIdAndGetAttExposesTheDocumentedAttributes() {
when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-new", "10.0.0.0/16"));
SecurityGroup def = new SecurityGroup();
def.setGroupId("sg-default");
def.setVpcId("vpc-new");
when(ec2.describeSecurityGroups(REGION, List.of(), List.of("default"), Map.of()))
.thenReturn(List.of(def));
StackResource r = provision(null, """
{"CidrBlock": "10.0.0.0/16"}""");
assertEquals("vpc-new", r.getPhysicalId());
assertEquals("vpc-new", r.getAttributes().get("VpcId"));
assertEquals("10.0.0.0/16", r.getAttributes().get("CidrBlock"));
assertEquals("sg-default", r.getAttributes().get("DefaultSecurityGroup"));
}
@Test
void anUnchangedVpcIsReusedInsteadOfCreatedAgain() {
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))
.thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16")));
StackResource r = provision("vpc-existing", """
{"CidrBlock": "10.0.0.0/16"}""");
verify(ec2, never()).createVpc(anyString(), anyString(), anyBoolean());
assertEquals("vpc-existing", r.getPhysicalId(),
"reusing must keep the id every subnet and route table already references");
}
@Test
void aChangedCidrBlockCreatesAReplacement() {
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))
.thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16")));
when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-replaced", "10.1.0.0/16"));
StackResource r = provision("vpc-existing", """
{"CidrBlock": "10.1.0.0/16"}""");
verify(ec2).createVpc(REGION, "10.1.0.0/16", false);
assertEquals("vpc-replaced", r.getPhysicalId());
}
@Test
void anIdOnTheResourceAloneDoesNotCountAsAnUpdate() {
when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-new", "10.0.0.0/16"));
// A resource carrying a physical id under a create context: what provision() itself
// produces the moment it assigns the new id. Reading create-vs-update off the resource
// makes that state indistinguishable from a real update.
StackResource r = provision(null, "vpc-assigned-mid-method", """
{"CidrBlock": "10.0.0.0/16"}""");
verify(ec2, never()).describeVpcs(anyString(), any(), any());
verify(ec2).createVpc(REGION, "10.0.0.0/16", false);
assertEquals("vpc-new", r.getPhysicalId());
}
@Test
void aVpcDeletedOutOfBandFallsBackToCreate() {
when(ec2.describeVpcs(REGION, List.of("vpc-gone"), Map.of()))
.thenThrow(new AwsException("InvalidVpcID.NotFound", "not found", 400));
when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-fresh", "10.0.0.0/16"));
StackResource r = provision("vpc-gone", """
{"CidrBlock": "10.0.0.0/16"}""");
verify(ec2).createVpc(REGION, "10.0.0.0/16", false);
assertEquals("vpc-fresh", r.getPhysicalId());
}
}