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,204 @@
package io.github.hectorvent.floci.core.common;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.Optional;
/**
* Canonicalises IPv4 and IPv6 CIDR blocks the way AWS does on write: the address is
* rewritten so every bit outside the prefix is zero, then re-rendered in AWS's own
* textual form (dotted-decimal for IPv4, compressed form for IPv6).
*
* <p>{@code 100.68.0.18/18} becomes {@code 100.68.0.0/18} — AWS's own documented
* example — because bits 18-31 of the address are host bits and AWS zeroes them
* before storing the block. A CIDR that is already canonical is returned unchanged
* (the identical string, not merely an equal one).
*
* <p>This class draws a hard line between "malformed" and "valid but non-canonical":
* {@link #canonicalize(String)} returns {@link Optional#empty()} only for a CIDR that
* cannot be parsed at all, never as a stand-in for "already canonical". Callers that
* need to tell the two apart before rewriting anything can call
* {@link #isCanonical(String)} directly.
*
* <p>Pure function: no I/O, no DNS resolution. The address half of the CIDR is parsed
* as a literal via {@link InetAddress#ofLiteral(String)}, which never triggers a
* hostname lookup — critical here, because {@link InetAddress#getByName(String)} would
* silently turn a malformed CIDR into a DNS query.
*/
public final class CidrCanonicalizer {
private CidrCanonicalizer() {}
/**
* Parses {@code cidr}, zeroes its host bits, and re-renders it in canonical form.
*
* @param cidr an IPv4 or IPv6 CIDR block, e.g. {@code "100.68.0.18/18"} or
* {@code "2001:db8::1/32"}
* @return the canonical CIDR string, or {@link Optional#empty()} if {@code cidr} is
* null, blank, missing a prefix, has a prefix out of range for the address
* family (0-32 for IPv4, 0-128 for IPv6), or has an address half that is not a
* literal IPv4/IPv6 address
*/
public static Optional<String> canonicalize(String cidr) {
return parse(cidr).map(parsed -> {
String rendered = render(parsed);
// Preserve reference identity when the input was already canonical, so
// callers get the exact same String back rather than a merely-equal copy.
return rendered.equals(cidr) ? cidr : rendered;
});
}
/**
* Reports whether {@code cidr} is both parseable and already in canonical form,
* i.e. {@code canonicalize(cidr)} would return the identical string.
*
* @return {@code true} only when {@code cidr} is valid and already canonical;
* {@code false} both when it is malformed and when it is valid but would be
* rewritten — use {@link #canonicalize(String)} to distinguish those two cases
*/
public static boolean isCanonical(String cidr) {
return parse(cidr).map(parsed -> render(parsed).equals(cidr)).orElse(false);
}
private static Optional<ParsedCidr> parse(String cidr) {
if (cidr == null || cidr.isBlank()) {
return Optional.empty();
}
int slash = cidr.lastIndexOf('/');
if (slash < 0 || slash == cidr.length() - 1) {
return Optional.empty();
}
String addressPart = cidr.substring(0, slash);
String prefixPart = cidr.substring(slash + 1);
int prefixLength;
try {
prefixLength = Integer.parseInt(prefixPart);
} catch (NumberFormatException e) {
return Optional.empty();
}
if (prefixLength < 0) {
return Optional.empty();
}
InetAddress address;
try {
// ofLiteral never resolves a hostname; a non-literal input throws instead
// of falling through to DNS, which is exactly what a malformed address
// half of a CIDR must do.
address = InetAddress.ofLiteral(addressPart);
} catch (IllegalArgumentException e) {
return Optional.empty();
}
int maxPrefixLength = address instanceof Inet4Address ? 32 : 128;
if (prefixLength > maxPrefixLength) {
return Optional.empty();
}
return Optional.of(new ParsedCidr(address, prefixLength));
}
private static String render(ParsedCidr parsed) {
byte[] masked = maskHostBits(parsed.address().getAddress(), parsed.prefixLength());
InetAddress maskedAddress;
try {
maskedAddress = InetAddress.getByAddress(masked);
} catch (java.net.UnknownHostException e) {
// Only thrown for an address of the wrong byte length, which cannot
// happen here: `masked` is always copied from a real InetAddress.
throw new AssertionError("unreachable: masked address has invalid length", e);
}
return hostAddress(maskedAddress) + "/" + parsed.prefixLength();
}
/**
* Returns the textual form AWS uses: dotted-decimal for IPv4, RFC 5952 compressed
* form for IPv6.
*
* <p>{@link InetAddress#getHostAddress()} renders IPv6 addresses in fully expanded
* form ({@code 2001:db8:0:0:0:0:0:0}, not {@code 2001:db8::}), so the compression
* step is done here explicitly rather than delegated.
*/
private static String hostAddress(InetAddress address) {
if (address instanceof Inet6Address v6) {
return compressIpv6(v6.getAddress());
}
return address.getHostAddress();
}
/**
* Renders 16 raw IPv6 address bytes as RFC 5952 compressed text: the longest run
* of two or more consecutive all-zero 16-bit groups is collapsed to {@code ::}
* (the leftmost run wins on a tie), and remaining groups are lowercase hex with no
* leading zeros.
*/
private static String compressIpv6(byte[] bytes) {
int[] groups = new int[8];
for (int i = 0; i < 8; i++) {
groups[i] = ((bytes[i * 2] & 0xFF) << 8) | (bytes[i * 2 + 1] & 0xFF);
}
int bestStart = -1;
int bestLength = 0;
int runStart = -1;
for (int i = 0; i <= 8; i++) {
boolean zero = i < 8 && groups[i] == 0;
if (zero) {
if (runStart < 0) {
runStart = i;
}
} else if (runStart >= 0) {
int runLength = i - runStart;
if (runLength > bestLength) {
bestStart = runStart;
bestLength = runLength;
}
runStart = -1;
}
}
// A run must be at least two groups to be worth eliding (RFC 5952 §4.2.2).
if (bestLength < 2) {
bestStart = -1;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 8; ) {
if (i == bestStart) {
sb.append("::");
i += bestLength;
continue;
}
if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ':') {
sb.append(':');
}
sb.append(Integer.toHexString(groups[i]));
i++;
}
// An address with no elided run at all (e.g. all groups non-zero) never hits
// the "::" branch, so nothing above needs a leading-colon special case; a run
// starting at index 0 naturally produces the correct leading "::".
return sb.toString();
}
private static byte[] maskHostBits(byte[] addressBytes, int prefixLength) {
byte[] masked = addressBytes.clone();
int fullBytes = prefixLength / 8;
int remainderBits = prefixLength % 8;
if (remainderBits != 0 && fullBytes < masked.length) {
int keepMask = 0xFF << (8 - remainderBits) & 0xFF;
masked[fullBytes] = (byte) (masked[fullBytes] & keepMask);
fullBytes++;
}
for (int i = fullBytes; i < masked.length; i++) {
masked[i] = 0;
}
return masked;
}
private record ParsedCidr(InetAddress address, int prefixLength) {}
}
@@ -31,6 +31,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.CidrCanonicalizer;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
@@ -4634,6 +4635,36 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return isSet(destinationIpv6CidrBlock) ? destinationIpv6CidrBlock : destinationPrefixListId;
}
/**
* AWS canonicalizes an IPv4 destination CIDR on input: "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." Running every DestinationCidrBlock through this once, here, is what lets
* CreateRoute, ReplaceRoute and DeleteRoute agree on "same destination" — two spellings of the
* same network now collide as duplicates instead of coexisting as two routes with undefined
* ReplaceRoute/DeleteRoute behaviour — and it is also why DescribeRouteTables echoes back the
* canonical form: the stored Route never holds anything else.
*
* <p>DestinationIpv6CidrBlock has no equivalent sentence in the CreateRoute/ReplaceRoute model
* and is left untouched. DestinationPrefixListId is an opaque ID, not a CIDR, and is likewise
* untouched.
*
* <p>A block that is not a well-formed "IPv4/prefix" is returned unchanged: canonicalizing is
* not this method's job to validate the request, only to reduce what is already well-formed.
* The unmodified value fails downstream exactly as it did before this change.
*
* <p>Delegates the actual bit-twiddling to {@link CidrCanonicalizer}, which also understands
* IPv6. That is deliberately not used here: DestinationCidrBlock is AWS's IPv4-only field —
* the API reference's canonicalization sentence appears only under it, never under
* DestinationIpv6CidrBlock — so a value that parses as an IPv6 literal is left untouched
* rather than canonicalized, the same as any other malformed-for-this-field input.
*/
private static String canonicalizeIpv4Cidr(String destinationCidrBlock) {
if (!isSet(destinationCidrBlock) || destinationCidrBlock.contains(":")) {
return destinationCidrBlock;
}
return CidrCanonicalizer.canonicalize(destinationCidrBlock).orElse(destinationCidrBlock);
}
/**
* AWS takes one destination per route, and there are three kinds of it: DestinationCidrBlock,
* DestinationIpv6CidrBlock and DestinationPrefixListId. The CreateRoute reference is explicit
@@ -4690,6 +4721,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
requireExactlyOneDestination("CreateRoute", destinationCidrBlock, destinationIpv6CidrBlock,
destinationPrefixListId);
requireEgressOnlyGatewayIsTheOnlyTarget(gatewayId, natGatewayId, egressOnlyInternetGatewayId);
final String canonicalDestinationCidrBlock = canonicalizeIpv4Cidr(destinationCidrBlock);
ensureDefaultResources(region);
synchronized (lockFor(key(region, routeTableId))) {
RouteTable current = getRequiredRouteTable(region, routeTableId);
@@ -4698,15 +4730,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
// removes every copy, so a table holding two routes with the same destination has no
// well-defined behaviour for either. AWS rejects the second CreateRoute instead, and it
// makes no exception for the local route seeded by CreateRouteTable.
if (next.stream().anyMatch(r -> matchesDestination(r, destinationCidrBlock,
if (next.stream().anyMatch(r -> matchesDestination(r, canonicalDestinationCidrBlock,
destinationIpv6CidrBlock, destinationPrefixListId))) {
throw new AwsException("RouteAlreadyExists",
"The route identified by "
+ destinationLabel(destinationCidrBlock, destinationIpv6CidrBlock,
+ destinationLabel(canonicalDestinationCidrBlock, destinationIpv6CidrBlock,
destinationPrefixListId)
+ " already exists", 400);
}
Route route = new Route(destinationCidrBlock, gatewayId, "CreateRoute");
Route route = new Route(canonicalDestinationCidrBlock, gatewayId, "CreateRoute");
route.setDestinationIpv6CidrBlock(destinationIpv6CidrBlock);
route.setDestinationPrefixListId(destinationPrefixListId);
route.setNatGatewayId(natGatewayId);
@@ -4731,24 +4763,25 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
throw new AwsException("InvalidParameterCombination",
"ReplaceRoute takes exactly one target, and only GatewayId or NatGatewayId is supported.", 400);
}
final String canonicalDestinationCidrBlock = canonicalizeIpv4Cidr(destinationCidrBlock);
ensureDefaultResources(region);
synchronized (lockFor(key(region, routeTableId))) {
RouteTable current = getRequiredRouteTable(region, routeTableId);
List<Route> next = new ArrayList<>(current.getRoutes());
Route existing = next.stream()
.filter(r -> matchesDestination(r, destinationCidrBlock, destinationIpv6CidrBlock,
.filter(r -> matchesDestination(r, canonicalDestinationCidrBlock, destinationIpv6CidrBlock,
destinationPrefixListId))
.findFirst()
.orElseThrow(() -> new AwsException("InvalidRoute.NotFound",
"The route identified by "
+ destinationLabel(destinationCidrBlock, destinationIpv6CidrBlock,
+ destinationLabel(canonicalDestinationCidrBlock, destinationIpv6CidrBlock,
destinationPrefixListId)
+ " does not exist", 400));
// The target the request does not name is cleared rather than carried over from the
// route being replaced.
Route replacement = new Route(destinationCidrBlock, hasGateway ? gatewayId : null, existing.getOrigin());
Route replacement = new Route(canonicalDestinationCidrBlock, hasGateway ? gatewayId : null, existing.getOrigin());
replacement.setDestinationIpv6CidrBlock(destinationIpv6CidrBlock);
replacement.setDestinationPrefixListId(destinationPrefixListId);
replacement.setNatGatewayId(hasNatGateway ? natGatewayId : null);
@@ -4762,11 +4795,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
String destinationIpv6CidrBlock, String destinationPrefixListId) {
requireExactlyOneDestination("DeleteRoute", destinationCidrBlock, destinationIpv6CidrBlock,
destinationPrefixListId);
final String canonicalDestinationCidrBlock = canonicalizeIpv4Cidr(destinationCidrBlock);
ensureDefaultResources(region);
synchronized (lockFor(key(region, routeTableId))) {
RouteTable current = getRequiredRouteTable(region, routeTableId);
List<Route> next = new ArrayList<>(current.getRoutes());
next.removeIf(r -> matchesDestination(r, destinationCidrBlock, destinationIpv6CidrBlock,
next.removeIf(r -> matchesDestination(r, canonicalDestinationCidrBlock, destinationIpv6CidrBlock,
destinationPrefixListId));
current.setRoutes(next);
routeTables.put(key(region, routeTableId), current);
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.ec2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.github.hectorvent.floci.core.common.CidrCanonicalizer;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@@ -19,13 +20,36 @@ public class Route {
public Route() {}
public Route(String destinationCidrBlock, String gatewayId, String origin) {
this.destinationCidrBlock = destinationCidrBlock;
setDestinationCidrBlock(destinationCidrBlock);
this.gatewayId = gatewayId;
this.origin = origin;
}
public String getDestinationCidrBlock() { return destinationCidrBlock; }
public void setDestinationCidrBlock(String destinationCidrBlock) { this.destinationCidrBlock = destinationCidrBlock; }
/**
* Canonicalized on every set, not only via the constructor. {@link Ec2Service} already
* canonicalizes a {@code DestinationCidrBlock} before constructing a {@code Route} at the
* API boundary (CreateRoute/ReplaceRoute), so re-canonicalizing here is a no-op for that
* path. The path this setter actually fixes is Jackson deserialization: PersistentStorage
* reconstructs a {@code Route} from disk via this setter, so a route written before
* canonicalization existed (e.g. stored as {@code 100.68.0.18/18}) is normalized the moment
* it is read back into memory, and every later in-memory comparison
* ({@code matchesDestination} in CreateRoute/ReplaceRoute/DeleteRoute) is apples-to-apples
* with a freshly-canonicalized incoming destination.
*
* <p>Scoped to IPv4 only, matching the API-boundary decision: a value containing {@code ':'}
* (or anything else {@link CidrCanonicalizer} cannot parse) is left untouched, since
* DestinationCidrBlock is documented by AWS as an IPv4-only field and
* DestinationIpv6CidrBlock is a separate member with its own field/setter.
*/
public void setDestinationCidrBlock(String destinationCidrBlock) {
if (destinationCidrBlock == null || destinationCidrBlock.isBlank() || destinationCidrBlock.contains(":")) {
this.destinationCidrBlock = destinationCidrBlock;
return;
}
this.destinationCidrBlock = CidrCanonicalizer.canonicalize(destinationCidrBlock).orElse(destinationCidrBlock);
}
public String getDestinationIpv6CidrBlock() { return destinationIpv6CidrBlock; }
public void setDestinationIpv6CidrBlock(String destinationIpv6CidrBlock) { this.destinationIpv6CidrBlock = destinationIpv6CidrBlock; }