fix(ec2): canonicalize IPv4 route destinations at the API boundary (#2620)

* feat(core): add IPv4/IPv6 CIDR canonicalisation utility

AWS canonicalises CIDR blocks on write (zeroing host bits, e.g.
100.68.0.18/18 -> 100.68.0.0/18) but Floci currently stores them
verbatim. Add CidrCanonicalizer as a shared, pure-function utility in
core.common so EC2 routes and other CIDR-bearing resources can adopt
it without duplicating parsing logic.

Handles both IPv4 and IPv6 (commons-net's SubnetUtils is IPv4-only
and was deliberately not used), parses the address half as a literal
via InetAddress.ofLiteral to avoid ever falling through to a DNS
lookup on malformed input, and renders IPv6 in RFC 5952 compressed
form to match what AWS itself returns. canonicalize() and
isCanonical() give callers a real, distinguishable signal between
"malformed" and "valid but non-canonical" rather than overloading one
outcome for both.

No caller is wired up yet; this is foundation-only for floci-1dn.

* fix(ec2): canonicalize IPv4 route destinations at the API boundary

AWS documents that a DestinationCidrBlock is reduced to its canonical
form on input (e.g. 100.68.0.18/18 becomes 100.68.0.0/18). Without
that step, CreateRoute, ReplaceRoute and DeleteRoute could each be
handed a differently-spelled but equivalent CIDR for the same network
and silently disagree about which route it named - two spellings of
one /18 could coexist as distinct routes, or a ReplaceRoute/DeleteRoute
using an equivalent spelling could miss the stored route entirely.

Canonicalize DestinationCidrBlock once, in all three verbs, before it
is matched against existing routes or stored, delegating the actual
bit-twiddling to CidrCanonicalizer rather than reimplementing it here.
DescribeRouteTables then echoes the canonical form for free, since the
stored Route never holds anything else.

DestinationIpv6CidrBlock has no equivalent canonical-form sentence in
the CreateRoute/ReplaceRoute model, so it is deliberately left out of
scope even though CidrCanonicalizer itself supports IPv6: a value that
parses as an IPv6 literal is passed through untouched, the same as any
other malformed-for-this-field input. DestinationPrefixListId is an
opaque ID rather than a CIDR and is likewise untouched.

Follow-up to the RouteAlreadyExists duplicate-destination rejection.

* fix(ec2): canonicalize a route's DestinationCidrBlock on load too

Greptile flagged a gap in the API-boundary canonicalization: a route
persisted before that fix keeps its original, non-canonical spelling
(e.g. 100.68.0.18/18) on disk. Reloading it after a restart never
re-canonicalizes that value, so it can no longer be matched by a
freshly-canonicalized incoming destination under strict string
comparison - CreateRoute could create a duplicate of the legacy route,
ReplaceRoute against its original spelling could wrongly 404, and
DeleteRoute could report success while leaving it in place.

Move the canonicalization into Route.setDestinationCidrBlock() itself,
scoped to IPv4 the same way as the API boundary (a value containing
':' is left untouched). PersistentStorage reconstructs a Route via
Jackson, which calls this setter, so a legacy on-disk route is
normalized the moment it is read back into memory and every later
in-memory comparison is apples-to-apples again. The constructor now
routes through the same setter instead of assigning the field
directly, which is a no-op for callers in Ec2Service that already
canonicalize before constructing a Route.

Ec2ServicePersistenceTest#legacyNonCanonicalRouteDestinationCanonicalizesOnRestart
hand-writes a pre-fix-shaped ec2-route-tables.json, restarts a service
over it, and asserts the reloaded route reads back canonical and that
CreateRoute/ReplaceRoute/DeleteRoute against the legacy spelling all
correctly identify the same route. Reverting the setter change alone
fails this test.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-08-27 15:26:07 -04:00
1 parent 18521edf28
commit 8f76e13dd6
6 files changed
+714 -9

No files matched your search

@@ -0,0 +1,164 @@
package io.github.hectorvent.floci.core.common;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
class CidrCanonicalizerTest {
// -----------------------------------------------------------------
// Pinned cases from the bead — exact strings, not just equality.
// -----------------------------------------------------------------
@Test
void awsDocumentedExample_rewritesHostBitsToZero() {
assertEquals(Optional.of("100.68.0.0/18"), CidrCanonicalizer.canonicalize("100.68.0.18/18"));
}
@Test
void alreadyCanonicalIpv4_isIdentityNotJustEqual() {
String input = "10.0.0.0/16";
Optional<String> result = CidrCanonicalizer.canonicalize(input);
assertEquals(Optional.of("10.0.0.0/16"), result);
// Must be the identical string value, not merely equal.
assertSame(input, result.orElseThrow());
}
@Test
void defaultRouteIpv4_zeroPrefixDoesNotDivideByZeroOrShiftBy32() {
String input = "0.0.0.0/0";
Optional<String> result = CidrCanonicalizer.canonicalize(input);
assertEquals(Optional.of("0.0.0.0/0"), result);
assertSame(input, result.orElseThrow());
}
@Test
void hostRouteIpv4_slash32IsUnchanged() {
String input = "10.1.2.3/32";
Optional<String> result = CidrCanonicalizer.canonicalize(input);
assertEquals(Optional.of("10.1.2.3/32"), result);
assertSame(input, result.orElseThrow());
}
@Test
void ipv6_rewritesHostBitsToZero() {
assertEquals(Optional.of("2001:db8::/32"), CidrCanonicalizer.canonicalize("2001:db8::1/32"));
}
@Test
void defaultRouteIpv6_zeroPrefixIsUnchanged() {
String input = "::/0";
Optional<String> result = CidrCanonicalizer.canonicalize(input);
assertEquals(Optional.of("::/0"), result);
assertSame(input, result.orElseThrow());
}
@Test
void ipv6_expandedInputCanonicalizesToCompressedForm() {
// AWS itself returns compressed IPv6; an expanded round-trip would be a diff.
assertEquals(Optional.of("2001:db8::/48"), CidrCanonicalizer.canonicalize("2001:0db8:0000::/48"));
}
@ParameterizedTest
@ValueSource(
strings = {
"",
"not-a-cidr",
"10.0.0.0",
"10.0.0.0/",
"/24",
"10.0.0.0/-1",
"10.0.0.0/33",
"2001:db8::1/129",
"2001:db8::1/-1",
"999.0.0.0/24",
"10.0.0.256/24",
"10.0.0.0/abc",
"example.com/24",
"10.0.0.0/24/extra",
})
void malformedOrOutOfRangeCidr_isDistinguishablyInvalid(String input) {
assertEquals(Optional.empty(), CidrCanonicalizer.canonicalize(input));
assertFalse(CidrCanonicalizer.isCanonical(input));
}
@Test
void nullCidr_isDistinguishablyInvalid() {
assertEquals(Optional.empty(), CidrCanonicalizer.canonicalize(null));
assertFalse(CidrCanonicalizer.isCanonical(null));
}
// -----------------------------------------------------------------
// Additional coverage.
// -----------------------------------------------------------------
@Test
void ipv6HostRoute_slash128IsUnchanged() {
String input = "2001:db8::1/128";
Optional<String> result = CidrCanonicalizer.canonicalize(input);
assertEquals(Optional.of("2001:db8::1/128"), result);
assertSame(input, result.orElseThrow());
}
@Test
void ipv4MappedIpv6Literal_ofLiteralCollapsesItToIpv4_soPrefixIsBoundedByThirtyTwo() {
// InetAddress.ofLiteral("::ffff:a.b.c.d") returns an Inet4Address, not an
// Inet6Address — Java itself collapses the IPv4-mapped form. A prefix that
// would be valid for the 128-bit IPv6 reading (e.g. /120) is therefore out of
// range once resolved, and must be rejected rather than silently accepted
// against the wrong bit width.
assertEquals(Optional.empty(), CidrCanonicalizer.canonicalize("::ffff:192.168.1.1/120"));
// A prefix within IPv4's 0-32 range works, canonicalizing as plain IPv4.
Optional<String> result = CidrCanonicalizer.canonicalize("::ffff:192.168.1.1/24");
assertEquals(Optional.of("192.168.1.0/24"), result);
// Re-canonicalizing the output must be a no-op (idempotence).
assertEquals(result, CidrCanonicalizer.canonicalize(result.orElseThrow()));
}
@ParameterizedTest
@CsvSource({
"100.68.0.18/18, 100.68.0.0/18",
"10.0.0.0/16, 10.0.0.0/16",
"0.0.0.0/0, 0.0.0.0/0",
"10.1.2.3/32, 10.1.2.3/32",
"2001:db8::1/32, 2001:db8::/32",
"::/0, ::/0",
"2001:0db8:0000::/48, 2001:db8::/48",
"192.168.1.255/24, 192.168.1.0/24",
"172.16.5.5/22, 172.16.4.0/22",
"255.255.255.255/32, 255.255.255.255/32",
"2001:db8:abcd:0012:0000:0000:0000:0001/64, 2001:db8:abcd:12::/64",
})
void canonicalize_matchesExpected(String input, String expected) {
assertEquals(Optional.of(expected), CidrCanonicalizer.canonicalize(input));
}
@Test
void isCanonical_trueOnlyForAlreadyCanonicalCidr() {
assertTrue(CidrCanonicalizer.isCanonical("10.0.0.0/16"));
assertTrue(CidrCanonicalizer.isCanonical("0.0.0.0/0"));
assertTrue(CidrCanonicalizer.isCanonical("2001:db8::/32"));
assertFalse(CidrCanonicalizer.isCanonical("100.68.0.18/18"));
assertFalse(CidrCanonicalizer.isCanonical("2001:0db8:0000::/48"));
}
@Test
void prefixLengthZero_forBothFamilies_isAccepted() {
assertEquals(Optional.of("0.0.0.0/0"), CidrCanonicalizer.canonicalize("192.168.1.1/0"));
assertEquals(Optional.of("::/0"), CidrCanonicalizer.canonicalize("2001:db8::1/0"));
}
@Test
void whitespaceOnlyCidr_isDistinguishablyInvalid() {
assertEquals(Optional.empty(), CidrCanonicalizer.canonicalize(" "));
assertFalse(CidrCanonicalizer.isCanonical(" "));
}
}
@@ -0,0 +1,196 @@
package io.github.hectorvent.floci.services.ec2;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.xml.HasXPath.hasXPath;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import io.quarkus.test.junit.QuarkusTest;
import static io.restassured.RestAssured.given;
/**
* AWS canonicalizes an IPv4 destination CIDR on input:
* https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateRoute.html — "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." This is the property that makes RouteAlreadyExists (see
* {@link Ec2DuplicateRouteTest}) actually work for the destinations people write: two operators
* spelling the same /18 network differently must collide as the same route, and
* DescribeRouteTables must always echo the canonical spelling regardless of which spelling
* CreateRoute, ReplaceRoute or DeleteRoute were called with.
*
* <p>Canonicalization is IPv4-only. DestinationIpv6CidrBlock has no equivalent sentence in the
* model and DestinationPrefixListId is an opaque ID, not a CIDR, so neither is touched — the last
* test here pins that an IPv6 destination survives byte-for-byte.
*
* <p>The XPath assertions use {@code local-name()} because EC2 responses carry a default
* namespace.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class Ec2RouteCidrCanonicalizationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private static final String VPC_CIDR = "203.0.113.0/24";
private static final String NON_CANONICAL = "100.68.0.18/18";
private static final String CANONICAL = "100.68.0.0/18";
private static final String OTHER_SPELLING_SAME_NETWORK = "100.68.63.255/18";
private static final String IPV6_ROUTE = "2001:db8::/32";
private static final String INTERNET_GATEWAY = "igw-0cidrcanon0test00";
private static final String OTHER_GATEWAY = "igw-0cidrcanon0othr00";
private static final String ROUTE_COUNT =
"count(//*[local-name()='routeSet']/*[local-name()='item'])";
private static String routeTableId;
private static io.restassured.specification.RequestSpecification ec2() {
return given().header("Authorization", AUTH_HEADER);
}
private static io.restassured.response.ValidatableResponse describe() {
return ec2()
.formParam("Action", "DescribeRouteTables")
.formParam("RouteTableId.1", routeTableId)
.when()
.post("/")
.then()
.statusCode(200);
}
private static io.restassured.specification.RequestSpecification createRoute(
String destinationCidrBlock, String gatewayId) {
return ec2()
.formParam("Action", "CreateRoute")
.formParam("RouteTableId", routeTableId)
.formParam("DestinationCidrBlock", destinationCidrBlock)
.formParam("GatewayId", gatewayId);
}
@Test
@Order(1)
void createARouteTable() {
String vpcId = ec2()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", VPC_CIDR)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
routeTableId = ec2()
.formParam("Action", "CreateRouteTable")
.formParam("VpcId", vpcId)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateRouteTableResponse.routeTable.routeTableId");
}
/** CreateRoute stores and echoes the canonical form, not the spelling the caller sent. */
@Test
@Order(2)
void createRouteCanonicalizesTheDestination() {
createRoute(NON_CANONICAL, INTERNET_GATEWAY).when().post("/").then().statusCode(200);
describe()
.body(hasXPath(ROUTE_COUNT, equalTo("2"))) // the seeded local route, plus this one
.body(hasXPath("//*[local-name()='routeSet']/*[local-name()='item']"
+ "[*[local-name()='destinationCidrBlock']='" + CANONICAL + "']"))
.body(hasXPath("count(//*[local-name()='routeSet']/*[local-name()='item']"
+ "[*[local-name()='destinationCidrBlock']='" + NON_CANONICAL + "'])", equalTo("0")));
}
/**
* A second CreateRoute spelling the same /18 network differently is the same destination as
* far as AWS is concerned, so it collides with RouteAlreadyExists exactly like a literal
* repeat would (see {@link Ec2DuplicateRouteTest}). Without canonicalizing on input, this
* would have silently created a second, functionally ambiguous route instead.
*/
@Test
@Order(3)
void anEquivalentSpellingOfTheSameNetworkCollidesAsADuplicate() {
String message = createRoute(OTHER_SPELLING_SAME_NETWORK, INTERNET_GATEWAY)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("RouteAlreadyExists"))
.extract().path("Response.Errors.Error.Message");
// The error names the canonical destination, since that is what is actually on file.
assertThat(message, containsString(CANONICAL));
describe().body(hasXPath(ROUTE_COUNT, equalTo("2")));
}
/**
* ReplaceRoute must canonicalize its own DestinationCidrBlock before matching, or an
* equivalent-but-differently-spelled request would miss the stored canonical route entirely
* and fail with InvalidRoute.NotFound instead of retargeting it.
*/
@Test
@Order(4)
void replaceRouteMatchesTheCanonicalRouteByAnEquivalentSpelling() {
ec2()
.formParam("Action", "ReplaceRoute")
.formParam("RouteTableId", routeTableId)
.formParam("DestinationCidrBlock", OTHER_SPELLING_SAME_NETWORK)
.formParam("GatewayId", OTHER_GATEWAY)
.when()
.post("/")
.then()
.statusCode(200);
describe()
.body(hasXPath(ROUTE_COUNT, equalTo("2")))
.body("DescribeRouteTablesResponse.routeTableSet.item.routeSet.item"
+ ".find { it.destinationCidrBlock == '" + CANONICAL + "' }.gatewayId",
equalTo(OTHER_GATEWAY));
}
/**
* DeleteRoute must canonicalize the same way, or an equivalent spelling would silently match
* nothing and leave the route in place while reporting success.
*/
@Test
@Order(5)
void deleteRouteMatchesTheCanonicalRouteByAnEquivalentSpelling() {
ec2()
.formParam("Action", "DeleteRoute")
.formParam("RouteTableId", routeTableId)
.formParam("DestinationCidrBlock", NON_CANONICAL)
.when()
.post("/")
.then()
.statusCode(200);
describe().body(hasXPath(ROUTE_COUNT, equalTo("1"))); // only the seeded local route remains
}
/** DestinationIpv6CidrBlock has no canonical form in the model and is stored byte-for-byte. */
@Test
@Order(6)
void ipv6DestinationsAreNotCanonicalized() {
ec2()
.formParam("Action", "CreateRoute")
.formParam("RouteTableId", routeTableId)
.formParam("DestinationIpv6CidrBlock", IPV6_ROUTE)
.formParam("GatewayId", INTERNET_GATEWAY)
.when()
.post("/")
.then()
.statusCode(200);
describe().body(hasXPath("//*[local-name()='routeSet']/*[local-name()='item']"
+ "[*[local-name()='destinationIpv6CidrBlock']='" + IPV6_ROUTE + "']"));
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ec2;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.ec2.model.Address;
@@ -32,11 +33,14 @@ import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -161,6 +165,85 @@ class Ec2ServicePersistenceTest {
assertEquals("from-source-sg", ingress.getFirst().getDescription());
}
/**
* Regression test for the RouteAlreadyExists/InvalidRoute.NotFound gap Greptile flagged on
* the DestinationCidrBlock canonicalization fix: a route persisted BEFORE that fix stores its
* destination in whatever spelling CreateRoute was originally called with (here
* {@code 100.68.0.18/18} rather than the canonical {@code 100.68.0.0/18}). Without
* canonicalizing on load, that legacy spelling never matches a newly-canonicalized incoming
* destination under strict string comparison, so CreateRoute could create a duplicate,
* ReplaceRoute could wrongly 404, and DeleteRoute could silently no-op.
*
* <p>This hand-writes a pre-fix-shaped {@code ec2-route-tables.json} directly (bypassing
* {@link io.github.hectorvent.floci.services.ec2.model.Route}'s own setter, which now
* canonicalizes) to simulate a file written by a pre-canonicalization Floci, then restarts
* over it and asserts: (a) the reloaded route reads back canonical; (b) CreateRoute with an
* equivalent-but-differently-spelled destination is detected as a duplicate rather than
* creating a second route; (c) ReplaceRoute and DeleteRoute using the legacy, non-canonical
* spelling still find the same route. Reverting the {@code Route.setDestinationCidrBlock}
* change alone fails this test: (a) reads back {@code 100.68.0.18/18} instead of
* {@code 100.68.0.0/18}, and (b)/(c) then also fail because CreateRoute/ReplaceRoute/
* DeleteRoute never see the same string as the stored legacy route.
*/
@Test
void legacyNonCanonicalRouteDestinationCanonicalizesOnRestart(@TempDir Path dir) throws IOException {
String routeTableId = "rtb-legacycidr01";
String vpcId = "vpc-legacycidr01";
String gatewayId = "igw-legacycidr01";
String legacyJson = """
{
"%s::%s": {
"routeTableId": "%s",
"vpcId": "%s",
"ownerId": "000000000000",
"region": "%s",
"routes": [
{
"destinationCidrBlock": "100.68.0.18/18",
"gatewayId": "%s",
"state": "active",
"origin": "CreateRoute"
}
],
"associations": [],
"tags": []
}
}
""".formatted(REGION, routeTableId, routeTableId, vpcId, REGION, gatewayId);
Files.writeString(dir.resolve("ec2-route-tables.json"), legacyJson);
Ec2Service restarted = newService(dir);
// (a) the loaded route's destination reads back canonical.
RouteTable loaded =
restarted.describeRouteTables(REGION, List.of(routeTableId), Map.of()).getFirst();
assertEquals(1, loaded.getRoutes().size());
assertEquals("100.68.0.0/18", loaded.getRoutes().getFirst().getDestinationCidrBlock(),
"legacy route destination must be canonicalized on load");
// (b) CreateRoute with an equivalent-but-differently-spelled destination is a duplicate,
// not a new route, of the legacy one.
AwsException duplicate = assertThrows(AwsException.class, () -> restarted.createRoute(
REGION, routeTableId, "100.68.63.255/18", null, null, "igw-other00000000000", null, null));
assertEquals("RouteAlreadyExists", duplicate.getErrorCode());
// (c) ReplaceRoute against the legacy route's original, non-canonical spelling finds the
// same route rather than throwing InvalidRoute.NotFound.
restarted.replaceRoute(REGION, routeTableId, "100.68.0.18/18", null, null, "igw-replaced0000000", null);
RouteTable afterReplace =
restarted.describeRouteTables(REGION, List.of(routeTableId), Map.of()).getFirst();
assertEquals(1, afterReplace.getRoutes().size(), "replace must update the existing route in place");
assertEquals("igw-replaced0000000", afterReplace.getRoutes().getFirst().getGatewayId());
assertEquals("100.68.0.0/18", afterReplace.getRoutes().getFirst().getDestinationCidrBlock());
// (c) DeleteRoute against the same legacy spelling actually removes the route rather than
// reporting success while leaving it behind.
restarted.deleteRoute(REGION, routeTableId, "100.68.0.18/18", null, null);
RouteTable afterDelete =
restarted.describeRouteTables(REGION, List.of(routeTableId), Map.of()).getFirst();
assertEquals(0, afterDelete.getRoutes().size(), "delete must actually remove the legacy route");
}
private BlockDeviceMapping blockDeviceMapping(String snapshotId, int volumeSize) {
EbsBlockDevice ebs = new EbsBlockDevice();
ebs.setSnapshotId(snapshotId);