fix(ec2): canonicalize VPC and subnet CIDR blocks on create (#5214)

* fix(ec2): canonicalize VPC and subnet CIDR blocks on create

AWS stores the IPv4 CidrBlock of CreateVpc and CreateSubnet in canonical
form ("100.68.0.18/18" becomes "100.68.0.0/18"); Floci stored it
verbatim. Canonicalize once at the top of createVpc and createSubnet so
the stored block, the VPC CIDR association, the subnet conflict check and
the network declaration all use the canonical value. A null subnet CIDR
(IPv6-only subnet) stays null.

The CloudFormation VPC and subnet provisioners compare the template's
CidrBlock against the stored one to decide reuse on update; compare in
canonical form so an unchanged template with host bits set is not
replaced on every update.

* fix(cloudformation): compare saved VPC and subnet CIDRs canonically on update

VPCs and subnets persisted before CIDR canonicalization can still hold host
bits (10.0.1.9/24). Canonicalizing only the template side made an unchanged
range look changed after upgrade: the subnet path called createSubnet and hit
InvalidSubnet.Conflict, the VPC path created a replacement. Canonicalize both
sides of the reuse comparison.

* docs(ec2): generalize canonicalizeIpv4Cidr to its VPC and subnet callers

The helper now canonicalizes CreateVpc and CreateSubnet CIDRs as well as
route destinations, but its Javadoc and parameter name still described
DestinationCidrBlock only. Rename the parameter to ipv4CidrBlock, cover all
three callers in the Javadoc, and drop its em-dashes. No behavior change.

* refactor(cidr): add CidrCanonicalizer.sameBlock for the provisioner comparisons

The subnet and VPC reuse checks each canonicalized both sides inline. Move
that comparison into one helper next to canonicalize, with the same
fallback to the raw string for an unparseable side and the same null
handling. No behavior change.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-10-07 14:09:24 -04:00
1 parent ee2d1a68a6
commit 4eae79d546
8 files changed
+184 -26

No files matched your search

@@ -161,4 +161,39 @@ class CidrCanonicalizerTest {
assertEquals(Optional.empty(), CidrCanonicalizer.canonicalize(" "));
assertFalse(CidrCanonicalizer.isCanonical(" "));
}
// -----------------------------------------------------------------
// sameBlock: the comparison the CloudFormation provisioners run on update.
// -----------------------------------------------------------------
@Test
void sameBlock_hostBitsOnEitherSideAreTheSameNetwork() {
assertTrue(CidrCanonicalizer.sameBlock("10.0.1.9/24", "10.0.1.0/24"));
assertTrue(CidrCanonicalizer.sameBlock("10.0.1.0/24", "10.0.1.9/24"));
assertTrue(CidrCanonicalizer.sameBlock("10.0.1.9/24", "10.0.1.77/24"));
}
@Test
void sameBlock_equalBlocksMatch() {
assertTrue(CidrCanonicalizer.sameBlock("10.0.0.0/16", "10.0.0.0/16"));
}
@Test
void sameBlock_differentNetworksOrPrefixesDoNotMatch() {
assertFalse(CidrCanonicalizer.sameBlock("10.0.1.0/24", "10.0.2.0/24"));
assertFalse(CidrCanonicalizer.sameBlock("10.0.0.0/16", "10.0.0.0/24"));
}
@Test
void sameBlock_nullsMatchOnlyEachOther() {
assertTrue(CidrCanonicalizer.sameBlock(null, null));
assertFalse(CidrCanonicalizer.sameBlock(null, "10.0.0.0/16"));
assertFalse(CidrCanonicalizer.sameBlock("10.0.0.0/16", null));
}
@Test
void sameBlock_malformedSideIsComparedRaw() {
assertTrue(CidrCanonicalizer.sameBlock("not-a-cidr", "not-a-cidr"));
assertFalse(CidrCanonicalizer.sameBlock("not-a-cidr", "10.0.0.0/16"));
}
}
@@ -296,6 +296,38 @@ class Ec2NetworkCfnProvisionerTest {
assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));
}
@Test
void anUnchangedSubnetWhoseTemplateCidrHasHostBitsIsKept() {
Subnet current = subnet();
current.setCidrBlock("10.0.1.0/24");
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(current));
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID));
ObjectNode props = mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.9/24");
provisioner.provision(r, props, ctx(SUBNET_ID));
verify(ec2, never()).createSubnet(any(), any(), any(), any());
assertEquals(SUBNET_ID, r.getPhysicalId());
assertFalse(provisioner.hasReplacementUpdate(r));
}
@Test
void aSubnetSavedWithHostBitsBeforeCanonicalizationIsKept() {
// State persisted by an older build can still hold the template's spelling, host bits and all.
Subnet current = subnet();
current.setCidrBlock("10.0.1.9/24");
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(current));
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID));
ObjectNode props = mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.9/24")
.put("MapPublicIpOnLaunch", true);
provisioner.provision(r, props, ctx(SUBNET_ID));
verify(ec2, never()).createSubnet(any(), any(), any(), any());
assertEquals(SUBNET_ID, r.getPhysicalId());
assertFalse(provisioner.hasReplacementUpdate(r));
}
@Test
void aSubnetWithAChangedCidrIsReplacedAndThePriorOneIsOwedToCleanup() {
Subnet current = subnet();
@@ -111,6 +111,33 @@ class Ec2VpcCfnProvisionerTest {
"reusing must keep the id every subnet and route table already references");
}
@Test
void anUnchangedVpcWhoseTemplateCidrHasHostBitsIsReused() {
// The backend stores the canonical block, so the template's spelling must be compared in
// that form or every update would replace the VPC.
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.5/16"}""");
verify(ec2, never()).createVpc(anyString(), anyString(), anyBoolean());
assertEquals("vpc-existing", r.getPhysicalId());
}
@Test
void aVpcSavedWithHostBitsBeforeCanonicalizationIsReused() {
// State persisted by an older build can still hold the template's spelling, host bits and all.
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))
.thenReturn(List.of(vpc("vpc-existing", "10.0.0.5/16")));
StackResource r = provision("vpc-existing", """
{"CidrBlock": "10.0.0.5/16"}""");
verify(ec2, never()).createVpc(anyString(), anyString(), anyBoolean());
assertEquals("vpc-existing", r.getPhysicalId());
}
@Test
void aChangedCidrBlockCreatesAReplacement() {
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))
@@ -689,6 +689,48 @@ class Ec2ServiceTest {
.filter(s -> vpc.getVpcId().equals(s.getVpcId())).count());
}
@Test
void createVpcAndCreateSubnetStoreTheCidrBlockInCanonicalForm() {
// AWS CreateVpc/CreateSubnet: "We modify the specified CIDR block to its canonical form; for
// example, if you specify 100.68.0.18/18, we modify it to 100.68.0.0/18."
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory());
String vpcId = service.createVpc("us-east-1", "10.20.0.5/16", false).getVpcId();
String subnetId = service.createSubnet("us-east-1", vpcId, "10.20.1.9/24", "us-east-1a").getSubnetId();
String canonicalSubnetId = service.createSubnet("us-east-1", vpcId, "10.20.2.0/24", "us-east-1a").getSubnetId();
Vpc vpc = service.describeVpcs("us-east-1", List.of(vpcId), Map.of()).get(0);
assertEquals("10.20.0.0/16", vpc.getCidrBlock());
assertEquals(List.of("10.20.0.0/16"), vpc.getCidrBlockAssociationSet().stream()
.map(a -> a.getCidrBlock()).toList());
assertEquals("10.20.1.0/24",
service.describeSubnets("us-east-1", List.of(subnetId), Map.of()).get(0).getCidrBlock());
assertEquals("10.20.2.0/24",
service.describeSubnets("us-east-1", List.of(canonicalSubnetId), Map.of()).get(0).getCidrBlock());
// The conflict check runs on the canonical form, and reports it.
AwsException error = assertThrows(AwsException.class, () -> service.createSubnet(
"us-east-1", vpcId, "10.20.1.0/24", "us-east-1a"));
assertEquals("InvalidSubnet.Conflict", error.getErrorCode());
AwsException hostBits = assertThrows(AwsException.class, () -> service.createSubnet(
"us-east-1", vpcId, "10.20.2.77/24", "us-east-1a"));
assertEquals("The CIDR '10.20.2.0/24' conflicts with another subnet", hostBits.getMessage());
}
@Test
void createVpcKeepsAnAlreadyCanonicalCidrBlockUnchanged() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory());
String vpcId = service.createVpc("us-east-1", "10.30.0.0/16", false).getVpcId();
assertEquals("10.30.0.0/16",
service.describeVpcs("us-east-1", List.of(vpcId), Map.of()).get(0).getCidrBlock());
}
@Test
void createSubnetRejectsCidrThatPartiallyOverlapsAnExistingSubnet() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),