diff --git a/compatibility-tests/sdk-test-awscli/test/ec2.bats b/compatibility-tests/sdk-test-awscli/test/ec2.bats index f56a6c65e9..1785574c05 100644 --- a/compatibility-tests/sdk-test-awscli/test/ec2.bats +++ b/compatibility-tests/sdk-test-awscli/test/ec2.bats @@ -11,12 +11,17 @@ setup() { TRANSIT_GATEWAY_ID="" TGW_ATTACHMENT_ID="" TGW_VPC_ID="" + TGW_ROUTE_TABLE_ID="" } teardown() { if [ -n "$PREFIX_LIST_ID" ]; then aws_cmd ec2 delete-managed-prefix-list --prefix-list-id "$PREFIX_LIST_ID" >/dev/null 2>&1 || true fi + if [ -n "$TGW_ROUTE_TABLE_ID" ]; then + aws_cmd ec2 delete-transit-gateway-route-table \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" >/dev/null 2>&1 || true + fi if [ -n "$TGW_ATTACHMENT_ID" ]; then aws_cmd ec2 delete-transit-gateway-vpc-attachment \ --transit-gateway-attachment-id "$TGW_ATTACHMENT_ID" >/dev/null 2>&1 || true @@ -441,3 +446,163 @@ create_attachment_fixture() { assert_success TRANSIT_GATEWAY_ID="" } + +# ─── transit gateway route tables, associations, propagations and routes ──── + +@test "EC2: route table associations move between tables" { + create_attachment_fixture + local out + out=$(aws_cmd ec2 create-transit-gateway-vpc-attachment --transit-gateway-id "$TRANSIT_GATEWAY_ID" \ + --vpc-id "$TGW_VPC_ID" --subnet-ids "$TGW_SUBNET_ID") + TGW_ATTACHMENT_ID=$(json_get "$out" '.TransitGatewayVpcAttachment.TransitGatewayAttachmentId') + out=$(aws_cmd ec2 describe-transit-gateways --transit-gateway-ids "$TRANSIT_GATEWAY_ID") + local default_rtb + default_rtb=$(json_get "$out" '.TransitGateways[0].Options.AssociationDefaultRouteTableId') + + run aws_cmd ec2 create-transit-gateway-route-table --transit-gateway-id "$TRANSIT_GATEWAY_ID" \ + --tag-specifications 'ResourceType=transit-gateway-route-table,Tags=[{Key=Name,Value=bats-rtb}]' + assert_success + TGW_ROUTE_TABLE_ID=$(json_get "$output" '.TransitGatewayRouteTable.TransitGatewayRouteTableId') + [ "$(json_get "$output" '.TransitGatewayRouteTable.State')" = "available" ] + [ "$(json_get "$output" '.TransitGatewayRouteTable.DefaultAssociationRouteTable')" = "false" ] + + # The attachment starts on the gateway's default table, so a second association is refused. + run aws_cmd ec2 associate-transit-gateway-route-table \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --transit-gateway-attachment-id "$TGW_ATTACHMENT_ID" + assert_failure + assert_output --partial "Resource.AlreadyAssociated" + + run aws_cmd ec2 disassociate-transit-gateway-route-table \ + --transit-gateway-route-table-id "$default_rtb" \ + --transit-gateway-attachment-id "$TGW_ATTACHMENT_ID" + assert_success + [ "$(json_get "$output" '.Association.State')" = "disassociating" ] + + run aws_cmd ec2 associate-transit-gateway-route-table \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --transit-gateway-attachment-id "$TGW_ATTACHMENT_ID" + assert_success + [ "$(json_get "$output" '.Association.State')" = "associating" ] + + run aws_cmd ec2 get-transit-gateway-route-table-associations \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" + assert_success + [ "$(json_get "$output" '.Associations[0].TransitGatewayAttachmentId')" = "$TGW_ATTACHMENT_ID" ] + [ "$(json_get "$output" '.Associations[0].ResourceType')" = "vpc" ] +} + +@test "EC2: propagation produces a route for the attached VPC" { + create_attachment_fixture + local out + out=$(aws_cmd ec2 create-transit-gateway-vpc-attachment --transit-gateway-id "$TRANSIT_GATEWAY_ID" \ + --vpc-id "$TGW_VPC_ID" --subnet-ids "$TGW_SUBNET_ID") + TGW_ATTACHMENT_ID=$(json_get "$out" '.TransitGatewayVpcAttachment.TransitGatewayAttachmentId') + out=$(aws_cmd ec2 create-transit-gateway-route-table --transit-gateway-id "$TRANSIT_GATEWAY_ID") + TGW_ROUTE_TABLE_ID=$(json_get "$out" '.TransitGatewayRouteTable.TransitGatewayRouteTableId') + + run aws_cmd ec2 enable-transit-gateway-route-table-propagation \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --transit-gateway-attachment-id "$TGW_ATTACHMENT_ID" + assert_success + [ "$(json_get "$output" '.Propagation.State')" = "enabled" ] + + run aws_cmd ec2 get-transit-gateway-route-table-propagations \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" + assert_success + [ "$(json_get "$output" '.TransitGatewayRouteTablePropagations[0].State')" = "enabled" ] + + run aws_cmd ec2 search-transit-gateway-routes \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --filters 'Name=type,Values=propagated' + assert_success + [ "$(json_get "$output" '.Routes[0].DestinationCidrBlock')" = "10.80.0.0/16" ] + [ "$(json_get "$output" '.Routes[0].Type')" = "propagated" ] + [ "$(json_get "$output" '.Routes[0].State')" = "active" ] + + run aws_cmd ec2 enable-transit-gateway-route-table-propagation \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --transit-gateway-attachment-id "$TGW_ATTACHMENT_ID" + assert_failure + assert_output --partial "TransitGatewayRouteTablePropagation.Duplicate" +} + +@test "EC2: static and blackhole transit gateway routes" { + create_attachment_fixture + local out + out=$(aws_cmd ec2 create-transit-gateway-vpc-attachment --transit-gateway-id "$TRANSIT_GATEWAY_ID" \ + --vpc-id "$TGW_VPC_ID" --subnet-ids "$TGW_SUBNET_ID") + TGW_ATTACHMENT_ID=$(json_get "$out" '.TransitGatewayVpcAttachment.TransitGatewayAttachmentId') + out=$(aws_cmd ec2 create-transit-gateway-route-table --transit-gateway-id "$TRANSIT_GATEWAY_ID") + TGW_ROUTE_TABLE_ID=$(json_get "$out" '.TransitGatewayRouteTable.TransitGatewayRouteTableId') + + run aws_cmd ec2 create-transit-gateway-route \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --destination-cidr-block 10.60.0.0/16 \ + --transit-gateway-attachment-id "$TGW_ATTACHMENT_ID" + assert_success + [ "$(json_get "$output" '.Route.Type')" = "static" ] + [ "$(json_get "$output" '.Route.State')" = "active" ] + [ "$(json_get "$output" '.Route.TransitGatewayAttachments[0].TransitGatewayAttachmentId')" = "$TGW_ATTACHMENT_ID" ] + + run aws_cmd ec2 create-transit-gateway-route \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --destination-cidr-block 10.61.0.0/16 --blackhole + assert_success + [ "$(json_get "$output" '.Route.State')" = "blackhole" ] + # A blackhole carries no attachment, so the key is absent rather than empty. + count=$(json_get "$output" '.Route.TransitGatewayAttachments // [] | length') + [ "$count" = "0" ] + + run aws_cmd ec2 search-transit-gateway-routes \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --filters 'Name=type,Values=static' + assert_success + count=$(json_get "$output" '.Routes | length') + [ "$count" = "2" ] + + run aws_cmd ec2 delete-transit-gateway-route \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --destination-cidr-block 10.61.0.0/16 + assert_success + [ "$(json_get "$output" '.Route.State')" = "deleted" ] +} + +@test "EC2: replacing a transit gateway route moves its target and upserts" { + create_attachment_fixture + local out + out=$(aws_cmd ec2 create-transit-gateway-vpc-attachment --transit-gateway-id "$TRANSIT_GATEWAY_ID" \ + --vpc-id "$TGW_VPC_ID" --subnet-ids "$TGW_SUBNET_ID") + TGW_ATTACHMENT_ID=$(json_get "$out" '.TransitGatewayVpcAttachment.TransitGatewayAttachmentId') + out=$(aws_cmd ec2 create-transit-gateway-route-table --transit-gateway-id "$TRANSIT_GATEWAY_ID") + TGW_ROUTE_TABLE_ID=$(json_get "$out" '.TransitGatewayRouteTable.TransitGatewayRouteTableId') + aws_cmd ec2 create-transit-gateway-route --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --destination-cidr-block 10.88.0.0/16 --transit-gateway-attachment-id "$TGW_ATTACHMENT_ID" >/dev/null + + run aws_cmd ec2 replace-transit-gateway-route \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --destination-cidr-block 10.88.0.0/16 --blackhole + assert_success + [ "$(json_get "$output" '.Route.State')" = "blackhole" ] + count=$(json_get "$output" '.Route.TransitGatewayAttachments // [] | length') + [ "$count" = "0" ] + + run aws_cmd ec2 replace-transit-gateway-route \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --destination-cidr-block 10.88.0.0/16 \ + --transit-gateway-attachment-id "$TGW_ATTACHMENT_ID" + assert_success + [ "$(json_get "$output" '.Route.State')" = "active" ] + + # Replacing a destination the table never held writes it. + run aws_cmd ec2 replace-transit-gateway-route \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --destination-cidr-block 10.89.0.0/16 --blackhole + assert_success + run aws_cmd ec2 search-transit-gateway-routes \ + --transit-gateway-route-table-id "$TGW_ROUTE_TABLE_ID" \ + --filters 'Name=type,Values=static' + assert_success + count=$(json_get "$output" '.Routes | length') + [ "$count" = "2" ] +} diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 4d4b39e6d6..794622da27 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -372,6 +372,54 @@ trimmed the way AWS trims them: modify omits the `tagSet`, and delete omits both the subnets. `Ipv6Support` is accepted without checking that the subnets carry IPv6 CIDRs, which real AWS rejects; Floci does not model subnet IPv6 allocation. +### Transit Gateway Route Tables + +| Action | Description | +|--------|-------------| +| CreateTransitGatewayRouteTable | Creates a route table on a transit gateway. | +| DescribeTransitGatewayRouteTables | Lists or returns stored transit gateway route tables. | +| DeleteTransitGatewayRouteTable | Deletes a route table, along with its propagations and static routes. | +| AssociateTransitGatewayRouteTable | Associates an attachment with a route table. | +| DisassociateTransitGatewayRouteTable | Removes an attachment's association. | +| GetTransitGatewayRouteTableAssociations | Lists the attachments associated with a route table. | +| EnableTransitGatewayRouteTablePropagation | Propagates an attachment's routes into a route table. | +| DisableTransitGatewayRouteTablePropagation | Stops an attachment propagating into a route table. | +| GetTransitGatewayRouteTablePropagations | Lists the propagations into a route table. | +| CreateTransitGatewayRoute | Adds a static or blackhole route to a route table. | +| DeleteTransitGatewayRoute | Removes a static route. | +| ReplaceTransitGatewayRoute | Points an existing route at a different target, or writes it if absent. | +| SearchTransitGatewayRoutes | Returns a route table's routes, static and propagated, filtered. | + +A route table asked for by name is never a default one; only the table a gateway mints for itself +carries `defaultAssociationRouteTable` or `defaultPropagationRouteTable`. Deleting a route table is +refused with `IncorrectState` while it is a gateway's default association table, and again while +attachments are still associated with it; the two cases carry different messages. Once it does go, +its propagations and static routes go with it. + +An attachment is associated with exactly one route table at a time, so associating a second time +returns `Resource.AlreadyAssociated` rather than moving it — disassociate first. Association is +recorded on the attachment itself, which is why `GetTransitGatewayRouteTableAssociations` reports +the attachment's VPC as the associated resource. + +Propagation is separate: one attachment may propagate into several route tables. Enabling twice +returns `TransitGatewayRouteTablePropagation.Duplicate`. Unlike association, which reports +`associating` and `disassociating`, propagation reports the settled `enabled` or `disabled` at +once — that is what the live API does rather than a shortcut taken here. + +`ReplaceTransitGatewayRoute` is an upsert rather than an update: replacing a destination the table +has never held writes it instead of reporting it missing, which is what the live API does. The +target moves as a unit, so a route turned into a blackhole keeps no attachment and one pointed back +at an attachment regains all of its fields. + +`SearchTransitGatewayRoutes` serves both kinds of route. Static routes are stored as written; a +blackhole is a static route in the `blackhole` state rather than a type of its own, and carries no +attachment. Propagated routes are derived when searched, from each enabled propagation joined to +the attached VPC's CIDR blocks, so a VPC's CIDRs changing cannot leave a stale route behind. A +route table's own listings drop the route table id that the mutating calls include, matching AWS. + +Route table ids follow the live API's own inconsistency: an id that does not exist is +`InvalidRouteTableID.NotFound`, while one of the wrong shape is `InvalidRouteTableId.Malformed`. + ### NAT Gateways | Action | Description | diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java index f8582c4efd..fc16e6d584 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java @@ -99,6 +99,27 @@ public class Ec2QueryHandler { handleModifyTransitGatewayVpcAttachment(params, region); case "DeleteTransitGatewayVpcAttachment" -> handleDeleteTransitGatewayVpcAttachment(params, region); + // Transit Gateway route tables, associations, propagations and routes + case "CreateTransitGatewayRouteTable" -> handleCreateTransitGatewayRouteTable(params, region); + case "DescribeTransitGatewayRouteTables" -> + handleDescribeTransitGatewayRouteTables(params, region); + case "DeleteTransitGatewayRouteTable" -> handleDeleteTransitGatewayRouteTable(params, region); + case "AssociateTransitGatewayRouteTable" -> + handleAssociateTransitGatewayRouteTable(params, region); + case "DisassociateTransitGatewayRouteTable" -> + handleDisassociateTransitGatewayRouteTable(params, region); + case "GetTransitGatewayRouteTableAssociations" -> + handleGetTransitGatewayRouteTableAssociations(params, region); + case "EnableTransitGatewayRouteTablePropagation" -> + handleEnableTransitGatewayRouteTablePropagation(params, region); + case "DisableTransitGatewayRouteTablePropagation" -> + handleDisableTransitGatewayRouteTablePropagation(params, region); + case "GetTransitGatewayRouteTablePropagations" -> + handleGetTransitGatewayRouteTablePropagations(params, region); + case "CreateTransitGatewayRoute" -> handleCreateTransitGatewayRoute(params, region); + case "DeleteTransitGatewayRoute" -> handleDeleteTransitGatewayRoute(params, region); + case "ReplaceTransitGatewayRoute" -> handleReplaceTransitGatewayRoute(params, region); + case "SearchTransitGatewayRoutes" -> handleSearchTransitGatewayRoutes(params, region); case "CreateDefaultVpc" -> handleCreateDefaultVpc(params, region); case "AssociateVpcCidrBlock" -> handleAssociateVpcCidrBlock(params, region); case "DisassociateVpcCidrBlock" -> handleDisassociateVpcCidrBlock(params, region); @@ -1381,6 +1402,234 @@ public class Ec2QueryHandler { return options; } + private Response handleCreateTransitGatewayRouteTable(MultivaluedMap p, String region) { + TransitGatewayRouteTable routeTable = service.createTransitGatewayRouteTable( + region, p.getFirst("TransitGatewayId"), + parseTagsForResource(p, "transit-gateway-route-table")); + XmlBuilder xml = new XmlBuilder() + .start("CreateTransitGatewayRouteTableResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("transitGatewayRouteTable").raw(routeTableXml(routeTable, true)) + .end("transitGatewayRouteTable") + .end("CreateTransitGatewayRouteTableResponse"); + return xmlResponse(xml.build()); + } + + private Response handleDescribeTransitGatewayRouteTables(MultivaluedMap p, String region) { + List routeTables = service.describeTransitGatewayRouteTables( + region, getList(p, "TransitGatewayRouteTableIds"), getFilters(p)); + XmlBuilder xml = new XmlBuilder() + .start("DescribeTransitGatewayRouteTablesResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("transitGatewayRouteTables"); + for (TransitGatewayRouteTable routeTable : routeTables) { + xml.start("item").raw(routeTableXml(routeTable, true)).end("item"); + } + xml.end("transitGatewayRouteTables").end("DescribeTransitGatewayRouteTablesResponse"); + return xmlResponse(xml.build()); + } + + private Response handleDeleteTransitGatewayRouteTable(MultivaluedMap p, String region) { + TransitGatewayRouteTable routeTable = service.deleteTransitGatewayRouteTable( + region, p.getFirst("TransitGatewayRouteTableId")); + XmlBuilder xml = new XmlBuilder() + .start("DeleteTransitGatewayRouteTableResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("transitGatewayRouteTable").raw(routeTableXml(routeTable, false)) + .end("transitGatewayRouteTable") + .end("DeleteTransitGatewayRouteTableResponse"); + return xmlResponse(xml.build()); + } + + private Response handleAssociateTransitGatewayRouteTable(MultivaluedMap p, String region) { + TransitGatewayVpcAttachment attachment = service.associateTransitGatewayRouteTable( + region, p.getFirst("TransitGatewayRouteTableId"), p.getFirst("TransitGatewayAttachmentId")); + // Verified live: the call reports the transitional state even though the association is + // already recorded. + return xmlResponse(new XmlBuilder() + .start("AssociateTransitGatewayRouteTableResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("association").raw(associationXml(attachment, p.getFirst("TransitGatewayRouteTableId"), + "associating", true)).end("association") + .end("AssociateTransitGatewayRouteTableResponse").build()); + } + + private Response handleDisassociateTransitGatewayRouteTable(MultivaluedMap p, String region) { + String routeTableId = p.getFirst("TransitGatewayRouteTableId"); + TransitGatewayVpcAttachment attachment = service.disassociateTransitGatewayRouteTable( + region, routeTableId, p.getFirst("TransitGatewayAttachmentId")); + return xmlResponse(new XmlBuilder() + .start("DisassociateTransitGatewayRouteTableResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("association").raw(associationXml(attachment, routeTableId, "disassociating", true)) + .end("association") + .end("DisassociateTransitGatewayRouteTableResponse").build()); + } + + private Response handleGetTransitGatewayRouteTableAssociations( + MultivaluedMap p, String region) { + String routeTableId = p.getFirst("TransitGatewayRouteTableId"); + List associated = service.associationsOf(region, routeTableId); + XmlBuilder xml = new XmlBuilder() + .start("GetTransitGatewayRouteTableAssociationsResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("associations"); + for (TransitGatewayVpcAttachment attachment : associated) { + // The listing form carries no route table id: the caller named it in the request. + xml.start("item").raw(associationXml(attachment, routeTableId, attachment.getAssociationState(), false)) + .end("item"); + } + xml.end("associations").end("GetTransitGatewayRouteTableAssociationsResponse"); + return xmlResponse(xml.build()); + } + + private Response handleEnableTransitGatewayRouteTablePropagation( + MultivaluedMap p, String region) { + TransitGatewayRouteTablePropagation propagation = service.enableTransitGatewayRouteTablePropagation( + region, p.getFirst("TransitGatewayRouteTableId"), p.getFirst("TransitGatewayAttachmentId")); + return xmlResponse(new XmlBuilder() + .start("EnableTransitGatewayRouteTablePropagationResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("propagation").raw(propagationXml(propagation, true)).end("propagation") + .end("EnableTransitGatewayRouteTablePropagationResponse").build()); + } + + private Response handleDisableTransitGatewayRouteTablePropagation( + MultivaluedMap p, String region) { + TransitGatewayRouteTablePropagation propagation = service.disableTransitGatewayRouteTablePropagation( + region, p.getFirst("TransitGatewayRouteTableId"), p.getFirst("TransitGatewayAttachmentId")); + return xmlResponse(new XmlBuilder() + .start("DisableTransitGatewayRouteTablePropagationResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("propagation").raw(propagationXml(propagation, true)).end("propagation") + .end("DisableTransitGatewayRouteTablePropagationResponse").build()); + } + + private Response handleGetTransitGatewayRouteTablePropagations( + MultivaluedMap p, String region) { + List propagations = + service.propagationsOf(region, p.getFirst("TransitGatewayRouteTableId")); + XmlBuilder xml = new XmlBuilder() + .start("GetTransitGatewayRouteTablePropagationsResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("transitGatewayRouteTablePropagations"); + for (TransitGatewayRouteTablePropagation propagation : propagations) { + // The listing form drops the route table id that enable and disable both carry. + xml.start("item").raw(propagationXml(propagation, false)).end("item"); + } + xml.end("transitGatewayRouteTablePropagations") + .end("GetTransitGatewayRouteTablePropagationsResponse"); + return xmlResponse(xml.build()); + } + + private Response handleCreateTransitGatewayRoute(MultivaluedMap p, String region) { + TransitGatewayRoute route = service.createTransitGatewayRoute( + region, + p.getFirst("TransitGatewayRouteTableId"), + p.getFirst("DestinationCidrBlock"), + p.getFirst("TransitGatewayAttachmentId"), + Boolean.parseBoolean(p.getFirst("Blackhole"))); + return xmlResponse(new XmlBuilder() + .start("CreateTransitGatewayRouteResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("route").raw(routeXml(route)).end("route") + .end("CreateTransitGatewayRouteResponse").build()); + } + + private Response handleReplaceTransitGatewayRoute(MultivaluedMap p, String region) { + TransitGatewayRoute route = service.replaceTransitGatewayRoute( + region, + p.getFirst("TransitGatewayRouteTableId"), + p.getFirst("DestinationCidrBlock"), + p.getFirst("TransitGatewayAttachmentId"), + Boolean.parseBoolean(p.getFirst("Blackhole"))); + return xmlResponse(new XmlBuilder() + .start("ReplaceTransitGatewayRouteResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("route").raw(routeXml(route)).end("route") + .end("ReplaceTransitGatewayRouteResponse").build()); + } + + private Response handleDeleteTransitGatewayRoute(MultivaluedMap p, String region) { + TransitGatewayRoute route = service.deleteTransitGatewayRoute( + region, p.getFirst("TransitGatewayRouteTableId"), p.getFirst("DestinationCidrBlock")); + return xmlResponse(new XmlBuilder() + .start("DeleteTransitGatewayRouteResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("route").raw(routeXml(route)).end("route") + .end("DeleteTransitGatewayRouteResponse").build()); + } + + private Response handleSearchTransitGatewayRoutes(MultivaluedMap p, String region) { + List routes = service.searchTransitGatewayRoutes( + region, p.getFirst("TransitGatewayRouteTableId"), getFilters(p)); + XmlBuilder xml = new XmlBuilder() + .start("SearchTransitGatewayRoutesResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .start("routeSet"); + for (TransitGatewayRoute route : routes) { + xml.start("item").raw(routeXml(route)).end("item"); + } + xml.end("routeSet") + .elem("additionalRoutesAvailable", "false") + .end("SearchTransitGatewayRoutesResponse"); + return xmlResponse(xml.build()); + } + + private String routeTableXml(TransitGatewayRouteTable routeTable, boolean includeTags) { + XmlBuilder xml = new XmlBuilder() + .elem("transitGatewayRouteTableId", routeTable.getTransitGatewayRouteTableId()) + .elem("transitGatewayId", routeTable.getTransitGatewayId()) + .elem("state", routeTable.getState()) + .elem("defaultAssociationRouteTable", String.valueOf(routeTable.isDefaultAssociationRouteTable())) + .elem("defaultPropagationRouteTable", String.valueOf(routeTable.isDefaultPropagationRouteTable())) + .elem("creationTime", routeTable.getCreationTime()); + if (includeTags) { + xml.raw(tagSetXml(routeTable.getTags())); + } + return xml.build(); + } + + private String associationXml(TransitGatewayVpcAttachment attachment, String routeTableId, + String state, boolean includeRouteTableId) { + XmlBuilder xml = new XmlBuilder(); + if (includeRouteTableId) { + xml.elem("transitGatewayRouteTableId", routeTableId); + } + return xml.elem("transitGatewayAttachmentId", attachment.getTransitGatewayAttachmentId()) + .elem("resourceId", attachment.getVpcId()) + .elem("resourceType", "vpc") + .elem("state", state) + .build(); + } + + private String propagationXml(TransitGatewayRouteTablePropagation propagation, boolean includeRouteTableId) { + XmlBuilder xml = new XmlBuilder() + .elem("transitGatewayAttachmentId", propagation.getTransitGatewayAttachmentId()) + .elem("resourceId", propagation.getResourceId()) + .elem("resourceType", propagation.getResourceType()); + if (includeRouteTableId) { + xml.elem("transitGatewayRouteTableId", propagation.getTransitGatewayRouteTableId()); + } + return xml.elem("state", propagation.getState()).build(); + } + + private String routeXml(TransitGatewayRoute route) { + XmlBuilder xml = new XmlBuilder() + .elem("destinationCidrBlock", route.getDestinationCidrBlock()); + // A blackhole route, and a deleted one, carry no attachment at all. + if (route.getTransitGatewayAttachmentId() != null) { + xml.start("transitGatewayAttachments").start("item") + .elem("resourceId", route.getResourceId()) + .elem("transitGatewayAttachmentId", route.getTransitGatewayAttachmentId()) + .elem("resourceType", route.getResourceType()) + .end("item").end("transitGatewayAttachments"); + } + return xml.elem("type", route.getType()) + .elem("state", route.getState()) + .build(); + } + private String vpcAttachmentXml(TransitGatewayVpcAttachment attachment, boolean includeSubnets, boolean includeTags) { XmlBuilder xml = new XmlBuilder() diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 9dcab763f9..6af64590da 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -7,6 +7,7 @@ import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Base64; import java.util.Collections; +import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -75,7 +76,9 @@ import io.github.hectorvent.floci.services.ec2.model.Subnet; import io.github.hectorvent.floci.services.ec2.model.Tag; import io.github.hectorvent.floci.services.ec2.model.TransitGateway; import io.github.hectorvent.floci.services.ec2.model.TransitGatewayOptions; +import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRoute; import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRouteTable; +import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRouteTablePropagation; import io.github.hectorvent.floci.services.ec2.model.TransitGatewayVpcAttachment; import io.github.hectorvent.floci.services.ec2.model.TransitGatewayVpcAttachmentOptions; import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair; @@ -104,6 +107,8 @@ public class Ec2Service implements ContainerTeardown { // The ASN AWS assigns when CreateTransitGateway omits Options.AmazonSideAsn. private static final long DEFAULT_AMAZON_SIDE_ASN = 64512L; private static final Pattern TRANSIT_GATEWAY_ID_PATTERN = Pattern.compile("^tgw-[0-9a-f]{8}([0-9a-f]{9})?$"); + private static final Pattern TRANSIT_GATEWAY_ROUTE_TABLE_ID_PATTERN = + Pattern.compile("^tgw-rtb-[0-9a-f]{8}([0-9a-f]{9})?$"); private static final Pattern TRANSIT_GATEWAY_ATTACHMENT_ID_PATTERN = Pattern.compile("^tgw-attach-[0-9a-f]{8}([0-9a-f]{9})?$"); @@ -139,6 +144,8 @@ public class Ec2Service implements ContainerTeardown { private final StorageBackend transitGateways; private final StorageBackend transitGatewayRouteTables; private final StorageBackend transitGatewayVpcAttachments; + private final StorageBackend transitGatewayPropagations; + private final StorageBackend transitGatewayRoutes; // resourceId → List private final StorageBackend> tags; private final Set seededRegions = ConcurrentHashMap.newKeySet(); @@ -174,7 +181,11 @@ public class Ec2Service implements ContainerTeardown { storageFactory.create("ec2", "ec2-transit-gateway-route-tables.json", new TypeReference>() {}), storageFactory.create("ec2", "ec2-transit-gateway-vpc-attachments.json", - new TypeReference>() {})); + new TypeReference>() {}), + storageFactory.create("ec2", "ec2-transit-gateway-propagations.json", + new TypeReference>() {}), + storageFactory.create("ec2", "ec2-transit-gateway-routes.json", + new TypeReference>() {})); } // Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly). @@ -205,7 +216,8 @@ public class Ec2Service implements ContainerTeardown { vpcs, subnets, securityGroups, securityGroupRules, internetGateways, routeTables, keyPairs, addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints, natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags, - new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>()); } // Package-private for hermetic tests, transit-gateway-aware. The shorter overload above keeps its @@ -235,7 +247,9 @@ public class Ec2Service implements ContainerTeardown { StorageBackend> tags, StorageBackend transitGateways, StorageBackend transitGatewayRouteTables, - StorageBackend transitGatewayVpcAttachments) { + StorageBackend transitGatewayVpcAttachments, + StorageBackend transitGatewayPropagations, + StorageBackend transitGatewayRoutes) { this.accountId = config.defaultAccountId(); this.config = config; this.containerManager = containerManager; @@ -265,6 +279,8 @@ public class Ec2Service implements ContainerTeardown { this.transitGateways = transitGateways; this.transitGatewayRouteTables = transitGatewayRouteTables; this.transitGatewayVpcAttachments = transitGatewayVpcAttachments; + this.transitGatewayPropagations = transitGatewayPropagations; + this.transitGatewayRoutes = transitGatewayRoutes; } @PostConstruct @@ -911,6 +927,9 @@ public class Ec2Service implements ContainerTeardown { */ public TransitGateway createTransitGateway(String region, String description, TransitGatewayOptions requested, List gatewayTags) { + // Held here too, so the rule needs no exceptions: every write to a gateway, route table, + // attachment, propagation or route happens under this one lock. + synchronized (attachmentTopologyLock(region)) { String transitGatewayId = "tgw-" + randomHex(17); TransitGateway gateway = new TransitGateway(); gateway.setTransitGatewayId(transitGatewayId); @@ -941,6 +960,7 @@ public class Ec2Service implements ContainerTeardown { } transitGateways.put(key(region, transitGatewayId), gateway); return gateway; + } } private TransitGatewayOptions resolveTransitGatewayOptions(TransitGatewayOptions requested) { @@ -1023,6 +1043,10 @@ public class Ec2Service implements ContainerTeardown { public TransitGateway modifyTransitGateway(String region, String transitGatewayId, String description, TransitGatewayOptions changes, List addCidrBlocks, List removeCidrBlocks) { + // Outermost first, as the deletes take it: this writes route tables through + // markDefaultRouteTable, and a delete running between the read and that write would be + // undone by it. + synchronized (attachmentTopologyLock(region)) { synchronized (lockFor(key(region, transitGatewayId))) { TransitGateway gateway = getRequiredTransitGateway(region, transitGatewayId); requireCoherentDefaultRouteTableChange(region, gateway, changes); @@ -1044,6 +1068,7 @@ public class Ec2Service implements ContainerTeardown { transitGateways.put(key(region, transitGatewayId), gateway); return gateway; } + } } /** @@ -1239,8 +1264,18 @@ public class Ec2Service implements ContainerTeardown { .filter(routeTable -> region.equals(routeTable.getRegion())) .filter(routeTable -> transitGatewayId.equals(routeTable.getTransitGatewayId())) .toList() - .forEach(routeTable -> transitGatewayRouteTables - .delete(key(region, routeTable.getTransitGatewayRouteTableId()))); + .forEach(routeTable -> { + // What the table owned goes with it, or the propagations and routes + // outlive the table they belong to and nothing can reach them again. + String routeTableId = routeTable.getTransitGatewayRouteTableId(); + propagationsOf(region, routeTableId).forEach(propagation -> transitGatewayPropagations + .delete(propagationKey(region, routeTableId, + propagation.getTransitGatewayAttachmentId()))); + routesOf(region, routeTableId).forEach(route -> transitGatewayRoutes + .delete(routeKey(region, routeTableId, route.getDestinationCidrBlock()))); + transitGatewayRouteTables.delete(key(region, routeTableId)); + tags.delete(routeTableId); + }); transitGateways.delete(key(region, transitGatewayId)); tags.delete(transitGatewayId); gateway.setState("deleted"); @@ -1451,9 +1486,33 @@ public class Ec2Service implements ContainerTeardown { } } + /** + * Deletes a VPC attachment and settles what pointed at it. Verified on a live account: the + * attachment's propagations disappear, while a static route that named it survives as a + * blackhole rather than being removed — the destination is still configured, it simply has + * nowhere to go now. + */ public TransitGatewayVpcAttachment deleteTransitGatewayVpcAttachment(String region, String attachmentId) { synchronized (attachmentTopologyLock(region)) { TransitGatewayVpcAttachment attachment = getRequiredVpcAttachment(region, attachmentId); + transitGatewayPropagations.scan(k -> true).stream() + .filter(propagation -> region.equals(propagation.getRegion())) + .filter(propagation -> attachmentId.equals(propagation.getTransitGatewayAttachmentId())) + .toList() + .forEach(propagation -> transitGatewayPropagations.delete(propagationKey(region, + propagation.getTransitGatewayRouteTableId(), attachmentId))); + transitGatewayRoutes.scan(k -> true).stream() + .filter(route -> region.equals(route.getRegion())) + .filter(route -> attachmentId.equals(route.getTransitGatewayAttachmentId())) + .toList() + .forEach(route -> { + route.setState("blackhole"); + route.setTransitGatewayAttachmentId(null); + route.setResourceId(null); + route.setResourceType(null); + transitGatewayRoutes.put(routeKey(region, route.getTransitGatewayRouteTableId(), + route.getDestinationCidrBlock()), route); + }); transitGatewayVpcAttachments.delete(key(region, attachmentId)); tags.delete(attachmentId); attachment.setState("deleted"); @@ -1472,6 +1531,496 @@ public class Ec2Service implements ContainerTeardown { } } + // ─── Transit Gateway Route Tables, Associations, Propagations and Routes ─── + + /** + * An attachment reached through a route table has to hang off the same gateway. Verified on a + * live account: associating, propagating or routing to an attachment of another gateway is + * refused as though the attachment did not exist, rather than with a mismatch of its own. + */ + private TransitGatewayVpcAttachment requireAttachmentOfSameGateway( + String region, TransitGatewayRouteTable routeTable, String attachmentId) { + TransitGatewayVpcAttachment attachment = getRequiredVpcAttachment(region, attachmentId); + if (!routeTable.getTransitGatewayId().equals(attachment.getTransitGatewayId())) { + throw new AwsException("InvalidTransitGatewayAttachmentID.NotFound", + "Transit Gateway Attachment " + attachmentId + " was deleted or does not exist.", 400); + } + return attachment; + } + + public TransitGatewayRouteTable createTransitGatewayRouteTable( + String region, String transitGatewayId, List routeTableTags) { + synchronized (attachmentTopologyLock(region)) { + TransitGateway gateway = getRequiredTransitGateway(region, transitGatewayId); + TransitGatewayRouteTable routeTable = new TransitGatewayRouteTable(); + String routeTableId = "tgw-rtb-" + randomHex(17); + routeTable.setTransitGatewayRouteTableId(routeTableId); + routeTable.setTransitGatewayId(gateway.getTransitGatewayId()); + // AWS reports pending and settles on available; nothing is slow locally. + routeTable.setState("available"); + // A table asked for by name is never either default; only the one the gateway mints is. + routeTable.setDefaultAssociationRouteTable(false); + routeTable.setDefaultPropagationRouteTable(false); + routeTable.setCreationTime(ISO_FMT.format(Instant.now())); + routeTable.setRegion(region); + if (routeTableTags != null && !routeTableTags.isEmpty()) { + routeTable.setTags(new ArrayList<>(routeTableTags)); + tags.put(routeTableId, new ArrayList<>(routeTableTags)); + } + transitGatewayRouteTables.put(key(region, routeTableId), routeTable); + return routeTable; + } + } + + public List describeTransitGatewayRouteTables( + String region, List routeTableIds, Map> filters) { + routeTableIds.forEach(Ec2Service::requireWellFormedRouteTableId); + List all = transitGatewayRouteTables.scan(k -> true).stream() + .filter(routeTable -> region.equals(routeTable.getRegion())) + .collect(Collectors.toList()); + for (String routeTableId : routeTableIds) { + if (all.stream().noneMatch(rt -> rt.getTransitGatewayRouteTableId().equals(routeTableId))) { + throw new AwsException("InvalidRouteTableID.NotFound", + "Transit Gateway Route Table " + routeTableId + " was deleted or does not exist.", 400); + } + } + return all.stream() + .filter(rt -> routeTableIds.isEmpty() || routeTableIds.contains(rt.getTransitGatewayRouteTableId())) + .filter(rt -> matchesFilters(rt, filters, region)) + .collect(Collectors.toList()); + } + + /** + * Verified live: a route table will not go while it is a gateway's default association table, + * nor while attachments are associated with it, and the two refusals carry different messages + * under one {@code IncorrectState} code. + */ + public TransitGatewayRouteTable deleteTransitGatewayRouteTable(String region, String routeTableId) { + synchronized (attachmentTopologyLock(region)) { + TransitGatewayRouteTable routeTable = getRequiredTransitGatewayRouteTable(region, routeTableId); + TransitGateway gateway = transitGatewayRouteTables.get(key(region, routeTableId)) + .map(TransitGatewayRouteTable::getTransitGatewayId) + .flatMap(id -> transitGateways.get(key(region, id))) + .orElse(null); + if (gateway != null + && (routeTableId.equals(gateway.getOptions().getAssociationDefaultRouteTableId()) + || routeTableId.equals(gateway.getOptions().getPropagationDefaultRouteTableId()))) { + throw new AwsException("IncorrectState", routeTableId + + " is set as default association route table for " + gateway.getTransitGatewayId(), 400); + } + if (!associationsOf(region, routeTableId).isEmpty()) { + throw new AwsException("IncorrectState", routeTableId + " has associated attachments", 400); + } + propagationsOf(region, routeTableId).forEach(propagation -> transitGatewayPropagations + .delete(propagationKey(region, routeTableId, propagation.getTransitGatewayAttachmentId()))); + routesOf(region, routeTableId).forEach(route -> transitGatewayRoutes + .delete(routeKey(region, routeTableId, route.getDestinationCidrBlock()))); + transitGatewayRouteTables.delete(key(region, routeTableId)); + tags.delete(routeTableId); + routeTable.setState("deleted"); + return routeTable; + } + } + + /** An attachment associates with exactly one route table, so a second attempt is refused. */ + public TransitGatewayVpcAttachment associateTransitGatewayRouteTable( + String region, String routeTableId, String attachmentId) { + synchronized (attachmentTopologyLock(region)) { + TransitGatewayRouteTable routeTable = getRequiredTransitGatewayRouteTable(region, routeTableId); + TransitGatewayVpcAttachment attachment = + requireAttachmentOfSameGateway(region, routeTable, attachmentId); + if (attachment.getAssociationRouteTableId() != null) { + throw new AwsException("Resource.AlreadyAssociated", "Transit Gateway Attachment " + + attachmentId + " is already associated to a route table.", 400); + } + attachment.setAssociationRouteTableId(routeTableId); + attachment.setAssociationState("associated"); + transitGatewayVpcAttachments.put(key(region, attachmentId), attachment); + return attachment; + } + } + + public TransitGatewayVpcAttachment disassociateTransitGatewayRouteTable( + String region, String routeTableId, String attachmentId) { + synchronized (attachmentTopologyLock(region)) { + TransitGatewayRouteTable routeTable = getRequiredTransitGatewayRouteTable(region, routeTableId); + TransitGatewayVpcAttachment attachment = + requireAttachmentOfSameGateway(region, routeTable, attachmentId); + if (!routeTableId.equals(attachment.getAssociationRouteTableId())) { + throw new AwsException("InvalidparameterValue", "Transit Gateway Attachment " + + attachmentId + " is not associated with route table " + routeTableId + ".", 400); + } + attachment.setAssociationRouteTableId(null); + attachment.setAssociationState(null); + transitGatewayVpcAttachments.put(key(region, attachmentId), attachment); + return attachment; + } + } + + /** The attachments associated with a route table, which is where an association is recorded. */ + public List associationsOf(String region, String routeTableId) { + return transitGatewayVpcAttachments.scan(k -> true).stream() + .filter(attachment -> region.equals(attachment.getRegion())) + .filter(attachment -> routeTableId.equals(attachment.getAssociationRouteTableId())) + .collect(Collectors.toList()); + } + + public TransitGatewayRouteTablePropagation enableTransitGatewayRouteTablePropagation( + String region, String routeTableId, String attachmentId) { + synchronized (attachmentTopologyLock(region)) { + TransitGatewayRouteTable routeTable = getRequiredTransitGatewayRouteTable(region, routeTableId); + TransitGatewayVpcAttachment attachment = + requireAttachmentOfSameGateway(region, routeTable, attachmentId); + if (transitGatewayPropagations.get(propagationKey(region, routeTableId, attachmentId)).isPresent()) { + throw new AwsException("TransitGatewayRouteTablePropagation.Duplicate", "Propagation " + + attachmentId + " already exists in Transit Gateway Route Table " + routeTableId + ".", 400); + } + TransitGatewayRouteTablePropagation propagation = new TransitGatewayRouteTablePropagation(); + propagation.setTransitGatewayRouteTableId(routeTableId); + propagation.setTransitGatewayAttachmentId(attachmentId); + propagation.setResourceId(attachment.getVpcId()); + propagation.setResourceType("vpc"); + // Verified live: propagation reports the settled state at once, where association + // reports associating first. + propagation.setState("enabled"); + propagation.setRegion(region); + transitGatewayPropagations.put(propagationKey(region, routeTableId, attachmentId), propagation); + return propagation; + } + } + + public TransitGatewayRouteTablePropagation disableTransitGatewayRouteTablePropagation( + String region, String routeTableId, String attachmentId) { + synchronized (attachmentTopologyLock(region)) { + TransitGatewayRouteTable routeTable = getRequiredTransitGatewayRouteTable(region, routeTableId); + requireAttachmentOfSameGateway(region, routeTable, attachmentId); + TransitGatewayRouteTablePropagation propagation = transitGatewayPropagations + .get(propagationKey(region, routeTableId, attachmentId)) + .orElseThrow(() -> new AwsException("InvalidparameterValue", "Propagation " + + attachmentId + " does not exist in Transit Gateway Route Table " + + routeTableId + ".", 400)); + transitGatewayPropagations.delete(propagationKey(region, routeTableId, attachmentId)); + propagation.setState("disabled"); + return propagation; + } + } + + public List propagationsOf(String region, String routeTableId) { + return transitGatewayPropagations.scan(k -> true).stream() + .filter(propagation -> region.equals(propagation.getRegion())) + .filter(propagation -> routeTableId.equals(propagation.getTransitGatewayRouteTableId())) + .collect(Collectors.toList()); + } + + public TransitGatewayRoute createTransitGatewayRoute(String region, String routeTableId, + String destinationCidrBlock, String attachmentId, + boolean blackhole) { + synchronized (attachmentTopologyLock(region)) { + getRequiredTransitGatewayRouteTable(region, routeTableId); + if (destinationCidrBlock == null || destinationCidrBlock.isBlank()) { + throw new AwsException("MissingParameter", + "The request must contain the parameter DestinationCidrBlock.", 400); + } + if (transitGatewayRoutes.get(routeKey(region, routeTableId, destinationCidrBlock)).isPresent()) { + throw new AwsException("RouteAlreadyExists", "Route " + destinationCidrBlock + + " already exists in Transit Gateway Route Table " + routeTableId + ".", 400); + } + TransitGatewayRoute route = new TransitGatewayRoute(); + route.setTransitGatewayRouteTableId(routeTableId); + route.setDestinationCidrBlock(destinationCidrBlock); + // A blackhole is a state of a static route rather than a type, and carries no + // attachment even when one was named. + route.setType("static"); + route.setState(blackhole ? "blackhole" : "active"); + route.setRegion(region); + if (!blackhole) { + TransitGatewayVpcAttachment attachment = requireAttachmentOfSameGateway(region, + getRequiredTransitGatewayRouteTable(region, routeTableId), attachmentId); + route.setTransitGatewayAttachmentId(attachmentId); + route.setResourceId(attachment.getVpcId()); + route.setResourceType("vpc"); + } + transitGatewayRoutes.put(routeKey(region, routeTableId, destinationCidrBlock), route); + return route; + } + } + + /** + * Replaces a route's target, and writes the route when it is not there. Verified on a live + * account: replacing a destination the table has never held creates it rather than reporting + * it missing, so this is an upsert and not an update. + */ + public TransitGatewayRoute replaceTransitGatewayRoute(String region, String routeTableId, + String destinationCidrBlock, String attachmentId, + boolean blackhole) { + synchronized (attachmentTopologyLock(region)) { + TransitGatewayRouteTable routeTable = getRequiredTransitGatewayRouteTable(region, routeTableId); + if (destinationCidrBlock == null || destinationCidrBlock.isBlank()) { + throw new AwsException("MissingParameter", + "The request must contain the parameter DestinationCidrBlock.", 400); + } + TransitGatewayRoute route = transitGatewayRoutes + .get(routeKey(region, routeTableId, destinationCidrBlock)) + .orElseGet(TransitGatewayRoute::new); + route.setTransitGatewayRouteTableId(routeTableId); + route.setDestinationCidrBlock(destinationCidrBlock); + route.setType("static"); + route.setRegion(region); + // The target moves as one: a blackhole keeps no attachment, and pointing the route at + // an attachment again restores all three fields together. + if (blackhole) { + route.setState("blackhole"); + route.setTransitGatewayAttachmentId(null); + route.setResourceId(null); + route.setResourceType(null); + } else { + TransitGatewayVpcAttachment attachment = + requireAttachmentOfSameGateway(region, routeTable, attachmentId); + route.setState("active"); + route.setTransitGatewayAttachmentId(attachmentId); + route.setResourceId(attachment.getVpcId()); + route.setResourceType("vpc"); + } + transitGatewayRoutes.put(routeKey(region, routeTableId, destinationCidrBlock), route); + return route; + } + } + + public TransitGatewayRoute deleteTransitGatewayRoute(String region, String routeTableId, + String destinationCidrBlock) { + synchronized (attachmentTopologyLock(region)) { + getRequiredTransitGatewayRouteTable(region, routeTableId); + TransitGatewayRoute route = transitGatewayRoutes + .get(routeKey(region, routeTableId, destinationCidrBlock)) + .orElseThrow(() -> new AwsException("InvalidRoute.NotFound", "The route " + + destinationCidrBlock + " does not exist in Transit Gateway Route Table " + + routeTableId + ".", 400)); + transitGatewayRoutes.delete(routeKey(region, routeTableId, destinationCidrBlock)); + route.setState("deleted"); + route.setTransitGatewayAttachmentId(null); + route.setResourceId(null); + route.setResourceType(null); + return route; + } + } + + /** + * The static routes written into a table, plus the propagated ones, which are a view of the + * enabled propagations joined to the attached VPC's CIDRs rather than records of their own. + * Deriving them keeps a VPC's CIDR changes from leaving a stale route behind. + */ + public List searchTransitGatewayRoutes(String region, String routeTableId, + Map> filters) { + getRequiredTransitGatewayRouteTable(region, routeTableId); + List routes = new ArrayList<>(routesOf(region, routeTableId)); + for (TransitGatewayRouteTablePropagation propagation : propagationsOf(region, routeTableId)) { + TransitGatewayVpcAttachment attachment = transitGatewayVpcAttachments + .get(key(region, propagation.getTransitGatewayAttachmentId())).orElse(null); + if (attachment == null) { + continue; + } + Vpc vpc = vpcs.get(key(region, attachment.getVpcId())).orElse(null); + if (vpc == null) { + continue; + } + for (String cidr : vpcCidrBlocks(vpc)) { + TransitGatewayRoute route = new TransitGatewayRoute(); + route.setTransitGatewayRouteTableId(routeTableId); + route.setDestinationCidrBlock(cidr); + route.setTransitGatewayAttachmentId(attachment.getTransitGatewayAttachmentId()); + route.setResourceId(attachment.getVpcId()); + route.setResourceType("vpc"); + route.setType("propagated"); + route.setState("active"); + route.setRegion(region); + routes.add(route); + } + } + return applyRouteFilters(routes, filters); + } + + /** + * The route search filters, as the live API applies them. The three CIDR relationship filters + * differ in the value they take, which is not something the reference spells out: + * {@code supernet-of-match} and {@code subnet-of-match} take a CIDR and match inclusively in + * either direction, while {@code longest-prefix-match} takes a bare address and returns the one + * most specific route covering it. Handing either the other's value form returns nothing on + * AWS, so the same holds here. + * + *

A filter name the API does not know is rejected rather than ignored: accepting it would + * answer a question that was never asked. + */ + private List applyRouteFilters(List routes, + Map> filters) { + if (filters == null || filters.isEmpty()) { + return routes; + } + List matched = new ArrayList<>(routes); + for (Map.Entry> filter : filters.entrySet()) { + String name = filter.getKey(); + List values = filter.getValue(); + switch (name) { + case "type" -> matched.removeIf(route -> !matchesValue(values, route.getType())); + case "state" -> matched.removeIf(route -> !matchesValue(values, route.getState())); + case "route-search.exact-match" -> + matched.removeIf(route -> !matchesValue(values, route.getDestinationCidrBlock())); + case "attachment.transit-gateway-attachment-id" -> + matched.removeIf(route -> !matchesValue(values, route.getTransitGatewayAttachmentId())); + case "attachment.resource-id" -> + matched.removeIf(route -> !matchesValue(values, route.getResourceId())); + case "attachment.resource-type" -> + matched.removeIf(route -> !matchesValue(values, route.getResourceType())); + case "route-search.supernet-of-match" -> matched.removeIf(route -> values.stream() + .noneMatch(value -> cidrContains(route.getDestinationCidrBlock(), value))); + case "route-search.subnet-of-match" -> matched.removeIf(route -> values.stream() + .noneMatch(value -> cidrContains(value, route.getDestinationCidrBlock()))); + case "route-search.longest-prefix-match" -> { + List longest = new ArrayList<>(); + for (String address : values) { + matched.stream() + .filter(route -> cidrContainsAddress(route.getDestinationCidrBlock(), address)) + .max(Comparator.comparingInt(route -> + prefixLengthOf(route.getDestinationCidrBlock()))) + .ifPresent(longest::add); + } + matched.retainAll(longest); + } + default -> throw new AwsException("InvalidParameterValue", + "Value (" + name + ") for parameter Filter is invalid. ", 400); + } + } + return matched; + } + + /** Whether {@code outer} covers {@code inner}, both CIDRs, an equal pair counting as covered. */ + private boolean cidrContains(String outer, String inner) { + int[] outerRange = cidrRange(outer); + int[] innerRange = cidrRange(inner); + if (outerRange == null || innerRange == null) { + return false; + } + return outerRange[1] <= innerRange[1] + && (innerRange[0] & maskOf(outerRange[1])) == outerRange[0]; + } + + /** Whether a CIDR covers a bare address, which is the form longest-prefix-match takes. */ + private boolean cidrContainsAddress(String cidr, String address) { + if (address == null || address.contains("/")) { + return false; + } + int[] range = cidrRange(cidr); + Integer packed = packIpv4(address); + if (range == null || packed == null) { + return false; + } + return (packed & maskOf(range[1])) == range[0]; + } + + private int prefixLengthOf(String cidr) { + int[] range = cidrRange(cidr); + return range == null ? -1 : range[1]; + } + + /** The network address and prefix length of an IPv4 CIDR, or null when it is neither. */ + private int[] cidrRange(String cidr) { + if (cidr == null) { + return null; + } + int slash = cidr.indexOf('/'); + if (slash < 0) { + return null; + } + Integer packed = packIpv4(cidr.substring(0, slash)); + if (packed == null) { + return null; + } + int prefix; + try { + prefix = Integer.parseInt(cidr.substring(slash + 1)); + } catch (NumberFormatException e) { + return null; + } + if (prefix < 0 || prefix > 32) { + return null; + } + return new int[] {packed & maskOf(prefix), prefix}; + } + + private int maskOf(int prefixLength) { + return prefixLength == 0 ? 0 : (int) (-1L << (32 - prefixLength)); + } + + private Integer packIpv4(String address) { + String[] octets = address.split("\\."); + if (octets.length != 4) { + return null; + } + int packed = 0; + for (String octet : octets) { + int value; + try { + value = Integer.parseInt(octet); + } catch (NumberFormatException e) { + return null; + } + if (value < 0 || value > 255) { + return null; + } + packed = (packed << 8) | value; + } + return packed; + } + + private List vpcCidrBlocks(Vpc vpc) { + List blocks = new ArrayList<>(); + if (vpc.getCidrBlock() != null) { + blocks.add(vpc.getCidrBlock()); + } + vpc.getCidrBlockAssociationSet().stream() + .map(VpcCidrBlockAssociation::getCidrBlock) + .filter(cidr -> cidr != null && !blocks.contains(cidr)) + .forEach(blocks::add); + return blocks; + } + + private List routesOf(String region, String routeTableId) { + return transitGatewayRoutes.scan(k -> true).stream() + .filter(route -> region.equals(route.getRegion())) + .filter(route -> routeTableId.equals(route.getTransitGatewayRouteTableId())) + .collect(Collectors.toList()); + } + + private String propagationKey(String region, String routeTableId, String attachmentId) { + return key(region, routeTableId + "::" + attachmentId); + } + + private String routeKey(String region, String routeTableId, String destinationCidrBlock) { + return key(region, routeTableId + "::" + destinationCidrBlock); + } + + private TransitGatewayRouteTable getRequiredTransitGatewayRouteTable(String region, String routeTableId) { + if (routeTableId == null || routeTableId.isBlank()) { + throw new AwsException("MissingParameter", + "The request must contain the parameter TransitGatewayRouteTableId.", 400); + } + requireWellFormedRouteTableId(routeTableId); + return transitGatewayRouteTables.get(key(region, routeTableId)) + .filter(routeTable -> region.equals(routeTable.getRegion())) + .orElseThrow(() -> new AwsException("InvalidRouteTableID.NotFound", + "Transit Gateway Route Table " + routeTableId + " was deleted or does not exist.", 400)); + } + + /** + * Verified live, including the casing: the not-found code spells it {@code InvalidRouteTableID} + * and the malformed one {@code InvalidRouteTableId}. + */ + private static void requireWellFormedRouteTableId(String routeTableId) { + if (!TRANSIT_GATEWAY_ROUTE_TABLE_ID_PATTERN.matcher(routeTableId).matches()) { + throw new AwsException("InvalidRouteTableId.Malformed", + "Invalid Transit Gateway Route Table id " + routeTableId + ".", 400); + } + } + private TransitGatewayVpcAttachment getRequiredVpcAttachment(String region, String attachmentId) { if (attachmentId == null || attachmentId.isBlank()) { throw new AwsException("MissingParameter", diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayRoute.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayRoute.java new file mode 100644 index 0000000000..b3b7970c4a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayRoute.java @@ -0,0 +1,60 @@ +package io.github.hectorvent.floci.services.ec2.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * A static route in a transit gateway route table. + * + *

Only static routes are stored. A propagated route is a view of an enabled propagation joined + * to the attached VPC's CIDR, so it is derived when routes are searched rather than written down — + * storing it would go stale the moment the VPC's CIDR associations change. + * + *

A blackhole route is a static route in the {@code blackhole} state rather than a type of its + * own, and carries no attachment. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class TransitGatewayRoute { + + private String transitGatewayRouteTableId; + private String destinationCidrBlock; + private String transitGatewayAttachmentId; + private String resourceId; + private String resourceType; + private String type; + private String state; + private String region; + + public TransitGatewayRoute() {} + + public String getTransitGatewayRouteTableId() { return transitGatewayRouteTableId; } + public void setTransitGatewayRouteTableId(String transitGatewayRouteTableId) { + this.transitGatewayRouteTableId = transitGatewayRouteTableId; + } + + public String getDestinationCidrBlock() { return destinationCidrBlock; } + public void setDestinationCidrBlock(String destinationCidrBlock) { + this.destinationCidrBlock = destinationCidrBlock; + } + + public String getTransitGatewayAttachmentId() { return transitGatewayAttachmentId; } + public void setTransitGatewayAttachmentId(String transitGatewayAttachmentId) { + this.transitGatewayAttachmentId = transitGatewayAttachmentId; + } + + public String getResourceId() { return resourceId; } + public void setResourceId(String resourceId) { this.resourceId = resourceId; } + + public String getResourceType() { return resourceType; } + public void setResourceType(String resourceType) { this.resourceType = resourceType; } + + public String getType() { return type; } + public void setType(String type) { this.type = type; } + + public String getState() { return state; } + public void setState(String state) { this.state = state; } + + public String getRegion() { return region; } + public void setRegion(String region) { this.region = region; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayRouteTablePropagation.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayRouteTablePropagation.java new file mode 100644 index 0000000000..5cfc32beb2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/TransitGatewayRouteTablePropagation.java @@ -0,0 +1,46 @@ +package io.github.hectorvent.floci.services.ec2.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * An attachment propagating its routes into a transit gateway route table. + * + *

Unlike an association, which lives on the attachment because an attachment has at most one, + * a propagation is its own record: one attachment may propagate into several route tables. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class TransitGatewayRouteTablePropagation { + + private String transitGatewayRouteTableId; + private String transitGatewayAttachmentId; + private String resourceId; + private String resourceType; + private String state; + private String region; + + public TransitGatewayRouteTablePropagation() {} + + public String getTransitGatewayRouteTableId() { return transitGatewayRouteTableId; } + public void setTransitGatewayRouteTableId(String transitGatewayRouteTableId) { + this.transitGatewayRouteTableId = transitGatewayRouteTableId; + } + + public String getTransitGatewayAttachmentId() { return transitGatewayAttachmentId; } + public void setTransitGatewayAttachmentId(String transitGatewayAttachmentId) { + this.transitGatewayAttachmentId = transitGatewayAttachmentId; + } + + public String getResourceId() { return resourceId; } + public void setResourceId(String resourceId) { this.resourceId = resourceId; } + + public String getResourceType() { return resourceType; } + public void setResourceType(String resourceType) { this.resourceType = resourceType; } + + public String getState() { return state; } + public void setState(String state) { this.state = state; } + + public String getRegion() { return region; } + public void setRegion(String region) { this.region = region; } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index 28cafc32b3..29550af048 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -29,7 +29,9 @@ import io.github.hectorvent.floci.services.ec2.model.Snapshot; import io.github.hectorvent.floci.services.ec2.model.Tag; import io.github.hectorvent.floci.services.ec2.model.TransitGateway; import io.github.hectorvent.floci.services.ec2.model.TransitGatewayOptions; +import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRoute; import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRouteTable; +import io.github.hectorvent.floci.services.ec2.model.TransitGatewayRouteTablePropagation; import io.github.hectorvent.floci.services.ec2.model.TransitGatewayVpcAttachment; import io.github.hectorvent.floci.services.ec2.model.TransitGatewayVpcAttachmentOptions; import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair; @@ -2195,6 +2197,404 @@ class Ec2ServiceTest { "describe serves tags added after creation"); } + // ========================================================================= + // Transit gateway route tables, associations, propagations and routes + // ========================================================================= + + /** A gateway, an attachment, and a second route table to move things onto. */ + private static String[] routeTableFixture(Ec2Service service) { + String[] fixture = attachmentFixture(service); + String attachmentId = service.createTransitGatewayVpcAttachment("us-east-1", fixture[0], + fixture[1], List.of(fixture[2]), null, List.of()).getTransitGatewayAttachmentId(); + String routeTableId = service.createTransitGatewayRouteTable("us-east-1", fixture[0], List.of()) + .getTransitGatewayRouteTableId(); + return new String[] {fixture[0], fixture[1], fixture[2], attachmentId, routeTableId}; + } + + @Test + void aRequestedRouteTableIsNeitherDefault() { + Ec2Service service = prefixListService(); + String[] fixture = attachmentFixture(service); + + TransitGatewayRouteTable routeTable = service.createTransitGatewayRouteTable("us-east-1", + fixture[0], List.of(new Tag("Name", "spoke"))); + + assertTrue(routeTable.getTransitGatewayRouteTableId().startsWith("tgw-rtb-")); + assertEquals("available", routeTable.getState()); + assertFalse(routeTable.isDefaultAssociationRouteTable()); + assertFalse(routeTable.isDefaultPropagationRouteTable()); + assertEquals(2, service.describeTransitGatewayRouteTables("us-east-1", List.of(), Map.of()).size(), + "the gateway's own default table is there too"); + } + + /** Verified live: an attachment associates with exactly one route table. */ + @Test + void anAttachmentAssociatesWithOneRouteTableAtATime() { + Ec2Service service = prefixListService(); + String[] fixture = routeTableFixture(service); + + AwsException already = assertThrows(AwsException.class, () -> service + .associateTransitGatewayRouteTable("us-east-1", fixture[4], fixture[3])); + assertEquals("Resource.AlreadyAssociated", already.getErrorCode()); + + TransitGateway gateway = service.describeTransitGateways("us-east-1", List.of(fixture[0]), Map.of()) + .getFirst(); + String defaultTable = gateway.getOptions().getAssociationDefaultRouteTableId(); + assertEquals(1, service.associationsOf("us-east-1", defaultTable).size(), + "the attachment starts on the gateway's default table"); + + service.disassociateTransitGatewayRouteTable("us-east-1", defaultTable, fixture[3]); + assertTrue(service.associationsOf("us-east-1", defaultTable).isEmpty()); + + service.associateTransitGatewayRouteTable("us-east-1", fixture[4], fixture[3]); + assertEquals(fixture[3], service.associationsOf("us-east-1", fixture[4]).getFirst() + .getTransitGatewayAttachmentId()); + } + + /** Verified live: propagation reports the settled state at once, and refuses a duplicate. */ + @Test + void propagationIsEnabledAtOnceAndOnlyOnce() { + Ec2Service service = prefixListService(); + String[] fixture = routeTableFixture(service); + + TransitGatewayRouteTablePropagation propagation = service + .enableTransitGatewayRouteTablePropagation("us-east-1", fixture[4], fixture[3]); + assertEquals("enabled", propagation.getState()); + assertEquals(fixture[1], propagation.getResourceId()); + assertEquals("vpc", propagation.getResourceType()); + + assertEquals("TransitGatewayRouteTablePropagation.Duplicate", assertThrows(AwsException.class, + () -> service.enableTransitGatewayRouteTablePropagation("us-east-1", fixture[4], fixture[3])) + .getErrorCode()); + + assertEquals("disabled", service.disableTransitGatewayRouteTablePropagation( + "us-east-1", fixture[4], fixture[3]).getState()); + assertTrue(service.propagationsOf("us-east-1", fixture[4]).isEmpty()); + } + + /** + * Verified live: enabling propagation makes the attached VPC's CIDR show up as a propagated + * route. It is derived from the VPC rather than stored, so a CIDR change cannot leave a stale + * route behind. + */ + @Test + void propagationProducesRoutesForTheAttachedVpcsCidr() { + Ec2Service service = prefixListService(); + String[] fixture = routeTableFixture(service); + service.enableTransitGatewayRouteTablePropagation("us-east-1", fixture[4], fixture[3]); + + List propagated = service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("type", List.of("propagated"))); + + assertEquals(1, propagated.size()); + assertEquals("10.90.0.0/16", propagated.getFirst().getDestinationCidrBlock()); + assertEquals("active", propagated.getFirst().getState()); + assertEquals(fixture[3], propagated.getFirst().getTransitGatewayAttachmentId()); + + service.disableTransitGatewayRouteTablePropagation("us-east-1", fixture[4], fixture[3]); + assertTrue(service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("type", List.of("propagated"))).isEmpty(), "the route goes with the propagation"); + } + + /** A blackhole is a state of a static route, not a type, and carries no attachment. */ + @Test + void staticAndBlackholeRoutesDifferByStateNotType() { + Ec2Service service = prefixListService(); + String[] fixture = routeTableFixture(service); + + TransitGatewayRoute viaAttachment = service.createTransitGatewayRoute("us-east-1", fixture[4], + "10.60.0.0/16", fixture[3], false); + assertEquals("static", viaAttachment.getType()); + assertEquals("active", viaAttachment.getState()); + assertEquals(fixture[3], viaAttachment.getTransitGatewayAttachmentId()); + + TransitGatewayRoute blackhole = service.createTransitGatewayRoute("us-east-1", fixture[4], + "10.61.0.0/16", null, true); + assertEquals("static", blackhole.getType()); + assertEquals("blackhole", blackhole.getState()); + assertNull(blackhole.getTransitGatewayAttachmentId()); + + assertEquals("RouteAlreadyExists", assertThrows(AwsException.class, + () -> service.createTransitGatewayRoute("us-east-1", fixture[4], "10.60.0.0/16", + fixture[3], false)).getErrorCode()); + + assertEquals(2, service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("type", List.of("static"))).size(), "a blackhole is still a static route"); + + TransitGatewayRoute deleted = service.deleteTransitGatewayRoute("us-east-1", fixture[4], "10.61.0.0/16"); + assertEquals("deleted", deleted.getState()); + assertNull(deleted.getTransitGatewayAttachmentId()); + assertEquals(1, service.searchTransitGatewayRoutes("us-east-1", fixture[4], Map.of()).size()); + } + + /** + * Verified live: a route table will not go while it is the gateway's default association table + * nor while attachments are associated with it, both under IncorrectState. + */ + @Test + void aRouteTableInUseCannotBeDeleted() { + Ec2Service service = prefixListService(); + String[] fixture = routeTableFixture(service); + TransitGateway gateway = service.describeTransitGateways("us-east-1", List.of(fixture[0]), Map.of()) + .getFirst(); + String defaultTable = gateway.getOptions().getAssociationDefaultRouteTableId(); + + AwsException isDefault = assertThrows(AwsException.class, + () -> service.deleteTransitGatewayRouteTable("us-east-1", defaultTable)); + assertEquals("IncorrectState", isDefault.getErrorCode()); + assertTrue(isDefault.getMessage().contains("default association route table"), isDefault.getMessage()); + + service.disassociateTransitGatewayRouteTable("us-east-1", defaultTable, fixture[3]); + service.associateTransitGatewayRouteTable("us-east-1", fixture[4], fixture[3]); + + AwsException associated = assertThrows(AwsException.class, + () -> service.deleteTransitGatewayRouteTable("us-east-1", fixture[4])); + assertEquals("IncorrectState", associated.getErrorCode()); + assertTrue(associated.getMessage().contains("has associated attachments"), associated.getMessage()); + + service.disassociateTransitGatewayRouteTable("us-east-1", fixture[4], fixture[3]); + service.createTransitGatewayRoute("us-east-1", fixture[4], "10.70.0.0/16", null, true); + assertEquals("deleted", service.deleteTransitGatewayRouteTable("us-east-1", fixture[4]).getState()); + assertEquals("InvalidRouteTableID.NotFound", assertThrows(AwsException.class, + () -> service.searchTransitGatewayRoutes("us-east-1", fixture[4], Map.of())).getErrorCode(), + "its routes went with it"); + } + + /** Verified live, casing included: NotFound spells it ID, Malformed spells it Id. */ + @Test + void routeTableIdErrorsMatchTheLiveApiIncludingCasing() { + Ec2Service service = prefixListService(); + + assertEquals("InvalidRouteTableID.NotFound", assertThrows(AwsException.class, + () -> service.describeTransitGatewayRouteTables("us-east-1", + List.of("tgw-rtb-0123456789abcdef0"), Map.of())).getErrorCode()); + assertEquals("InvalidRouteTableId.Malformed", assertThrows(AwsException.class, + () -> service.describeTransitGatewayRouteTables("us-east-1", + List.of("tgw-rtb-nope"), Map.of())).getErrorCode()); + } + + /** + * Verified on a live account: deleting an attachment removes its propagations, and a static + * route that named it survives as a blackhole rather than disappearing — the destination is + * still configured, it just has nowhere to go. + */ + @Test + void deletingAnAttachmentClearsPropagationsAndBlackholesItsRoutes() { + Ec2Service service = prefixListService(); + String[] fixture = routeTableFixture(service); + service.enableTransitGatewayRouteTablePropagation("us-east-1", fixture[4], fixture[3]); + service.createTransitGatewayRoute("us-east-1", fixture[4], "10.99.0.0/16", fixture[3], false); + + service.deleteTransitGatewayVpcAttachment("us-east-1", fixture[3]); + + assertTrue(service.propagationsOf("us-east-1", fixture[4]).isEmpty(), "propagations go"); + List routes = service.searchTransitGatewayRoutes("us-east-1", fixture[4], Map.of()); + assertEquals(1, routes.size(), "the static route stays"); + assertEquals("blackhole", routes.getFirst().getState()); + assertNull(routes.getFirst().getTransitGatewayAttachmentId()); + assertTrue(service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("type", List.of("propagated"))).isEmpty(), "and its propagated route with it"); + } + + /** A gateway's route tables take their propagations, routes and tags with them. */ + @Test + void deletingAGatewayLeavesNothingBehindItsRouteTables() { + Ec2Service service = prefixListService(); + String[] fixture = routeTableFixture(service); + service.enableTransitGatewayRouteTablePropagation("us-east-1", fixture[4], fixture[3]); + service.createTransitGatewayRoute("us-east-1", fixture[4], "10.99.0.0/16", null, true); + service.createTags("us-east-1", List.of(fixture[4]), List.of(new Tag("env", "prod"))); + service.deleteTransitGatewayVpcAttachment("us-east-1", fixture[3]); + + service.deleteTransitGateway("us-east-1", fixture[0]); + + assertTrue(service.describeTransitGatewayRouteTables("us-east-1", List.of(), Map.of()).isEmpty(), + "the tables go with the gateway"); + assertTrue(service.propagationsOf("us-east-1", fixture[4]).isEmpty()); + assertTrue(service.describeTags("us-east-1", Map.of("resource-id", List.of(fixture[4]))).isEmpty(), + "and their tags"); + } + + /** + * Modifying a gateway writes route tables through its default-table markers, so it races the + * deletes the same way tagging does. Whoever wins, a deleted table must not come back. + */ + @Test + void modifyingAGatewayCannotResurrectADeletedRouteTable() throws Exception { + for (int trial = 0; trial < 10; trial++) { + Ec2Service service = prefixListService(); + String[] fixture = attachmentFixture(service); + String spare = service.createTransitGatewayRouteTable("us-east-1", fixture[0], List.of()) + .getTransitGatewayRouteTableId(); + java.util.concurrent.CountDownLatch start = new java.util.concurrent.CountDownLatch(1); + java.util.concurrent.ExecutorService pool = + java.util.concurrent.Executors.newFixedThreadPool(2); + + pool.submit(() -> { + try { + start.await(); + TransitGatewayOptions changes = new TransitGatewayOptions(); + changes.setDefaultRouteTableAssociation("enable"); + changes.setAssociationDefaultRouteTableId(spare); + service.modifyTransitGateway("us-east-1", fixture[0], null, changes, List.of(), List.of()); + } catch (AwsException | InterruptedException ignored) { + // Losing the race is fine. + } + }); + pool.submit(() -> { + try { + start.await(); + service.deleteTransitGatewayRouteTable("us-east-1", spare); + } catch (AwsException | InterruptedException ignored) { + // Same. + } + }); + start.countDown(); + pool.shutdown(); + assertTrue(pool.awaitTermination(30, java.util.concurrent.TimeUnit.SECONDS)); + + boolean tableExists = service.describeTransitGatewayRouteTables("us-east-1", List.of(), Map.of()) + .stream().anyMatch(rt -> rt.getTransitGatewayRouteTableId().equals(spare)); + TransitGateway gateway = service.describeTransitGateways("us-east-1", List.of(fixture[0]), Map.of()) + .getFirst(); + if (!tableExists) { + assertNotEquals(spare, gateway.getOptions().getAssociationDefaultRouteTableId(), + "trial " + trial + ": the gateway names a route table that is gone"); + } + } + } + + /** + * Verified on a live account: a route table only reaches attachments of its own gateway. + * Associating, propagating or routing to another gateway's attachment is refused as though the + * attachment did not exist, which is the same shape as a subnet belonging to another VPC. + */ + @Test + void aRouteTableOnlyReachesItsOwnGatewaysAttachments() { + Ec2Service service = prefixListService(); + String[] fixture = routeTableFixture(service); + String otherGateway = service.createTransitGateway("us-east-1", "other", null, List.of()) + .getTransitGatewayId(); + String foreignTable = service.createTransitGatewayRouteTable("us-east-1", otherGateway, List.of()) + .getTransitGatewayRouteTableId(); + + for (Runnable crossGateway : List.of( + () -> service.associateTransitGatewayRouteTable("us-east-1", foreignTable, fixture[3]), + () -> service.disassociateTransitGatewayRouteTable("us-east-1", foreignTable, fixture[3]), + () -> service.enableTransitGatewayRouteTablePropagation("us-east-1", foreignTable, fixture[3]), + () -> service.disableTransitGatewayRouteTablePropagation("us-east-1", foreignTable, fixture[3]), + () -> service.createTransitGatewayRoute("us-east-1", foreignTable, "10.77.0.0/16", + fixture[3], false))) { + assertEquals("InvalidTransitGatewayAttachmentID.NotFound", + assertThrows(AwsException.class, crossGateway::run).getErrorCode()); + } + + // Nothing was recorded against the other gateway's table on the way through. + assertTrue(service.associationsOf("us-east-1", foreignTable).isEmpty()); + assertTrue(service.propagationsOf("us-east-1", foreignTable).isEmpty()); + assertTrue(service.searchTransitGatewayRoutes("us-east-1", foreignTable, Map.of()).isEmpty()); + } + + /** + * Verified on a live account: replacing a route flips its target in place, and replacing a + * destination the table has never held writes it rather than reporting it missing — an upsert + * rather than an update. + */ + @Test + void replacingARouteMovesItsTargetAndUpsertsWhenAbsent() { + Ec2Service service = prefixListService(); + String[] fixture = routeTableFixture(service); + service.createTransitGatewayRoute("us-east-1", fixture[4], "10.88.0.0/16", fixture[3], false); + + TransitGatewayRoute blackholed = service.replaceTransitGatewayRoute("us-east-1", fixture[4], + "10.88.0.0/16", null, true); + assertEquals("blackhole", blackholed.getState()); + assertNull(blackholed.getTransitGatewayAttachmentId(), "the target moves as one"); + assertNull(blackholed.getResourceId()); + + TransitGatewayRoute restored = service.replaceTransitGatewayRoute("us-east-1", fixture[4], + "10.88.0.0/16", fixture[3], false); + assertEquals("active", restored.getState()); + assertEquals(fixture[3], restored.getTransitGatewayAttachmentId()); + assertEquals(fixture[1], restored.getResourceId()); + + TransitGatewayRoute created = service.replaceTransitGatewayRoute("us-east-1", fixture[4], + "10.89.0.0/16", null, true); + assertEquals("blackhole", created.getState()); + assertEquals(2, service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("type", List.of("static"))).size(), "replacing an absent route writes it"); + + // The same ownership rule as the other route table operations. + String otherGateway = service.createTransitGateway("us-east-1", "other", null, List.of()) + .getTransitGatewayId(); + String foreignTable = service.createTransitGatewayRouteTable("us-east-1", otherGateway, List.of()) + .getTransitGatewayRouteTableId(); + assertEquals("InvalidTransitGatewayAttachmentID.NotFound", assertThrows(AwsException.class, + () -> service.replaceTransitGatewayRoute("us-east-1", foreignTable, "10.90.0.0/16", + fixture[3], false)).getErrorCode()); + + // A replaced route is still a route, so losing its attachment blackholes it. + service.deleteTransitGatewayVpcAttachment("us-east-1", fixture[3]); + TransitGatewayRoute afterDetach = service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("route-search.exact-match", List.of("10.88.0.0/16"))).getFirst(); + assertEquals("blackhole", afterDetach.getState()); + assertNull(afterDetach.getTransitGatewayAttachmentId()); + } + + /** + * The route search filters, as observed on a live account. The three CIDR relationship filters + * take different value forms: supernet-of-match and subnet-of-match take a CIDR and match + * inclusively, longest-prefix-match takes a bare address and returns the one most specific + * route covering it. Giving either the other's form returns nothing there, and here. + */ + @Test + void routeSearchFiltersMatchTheLiveApi() { + Ec2Service service = prefixListService(); + String[] fixture = routeTableFixture(service); + for (String cidr : List.of("10.0.0.0/8", "10.1.0.0/16", "10.1.1.0/24", "192.168.0.0/16")) { + service.createTransitGatewayRoute("us-east-1", fixture[4], cidr, null, true); + } + + assertEquals(List.of("10.0.0.0/8", "10.1.0.0/16", "10.1.1.0/24"), + cidrsOf(service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("route-search.supernet-of-match", List.of("10.1.1.0/24")))), + "everything containing it, the exact match included"); + + assertEquals(List.of("10.1.0.0/16", "10.1.1.0/24"), + cidrsOf(service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("route-search.subnet-of-match", List.of("10.1.0.0/16")))), + "everything it contains, the exact match included"); + + assertEquals(List.of("10.1.1.0/24"), + cidrsOf(service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("route-search.longest-prefix-match", List.of("10.1.1.5")))), + "the most specific route covering the address"); + assertEquals(List.of("10.1.0.0/16"), + cidrsOf(service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("route-search.longest-prefix-match", List.of("10.1.9.9"))))); + assertTrue(service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("route-search.longest-prefix-match", List.of("8.8.8.8"))).isEmpty(), + "nothing covers it"); + + // Each filter ignores the other's value form, exactly as the live API does. + assertTrue(service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("route-search.longest-prefix-match", List.of("10.1.1.5/32"))).isEmpty(), + "longest-prefix-match takes an address, not a CIDR"); + assertTrue(service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("route-search.supernet-of-match", List.of("10.1.1.5"))).isEmpty(), + "supernet-of-match takes a CIDR, not an address"); + + AwsException unknown = assertThrows(AwsException.class, + () -> service.searchTransitGatewayRoutes("us-east-1", fixture[4], + Map.of("nonsense", List.of("x")))); + assertEquals("InvalidParameterValue", unknown.getErrorCode()); + assertTrue(unknown.getMessage().contains("nonsense"), unknown.getMessage()); + } + + private static List cidrsOf(List routes) { + return routes.stream().map(TransitGatewayRoute::getDestinationCidrBlock).sorted().toList(); + } + private static EmulatorConfig mockConfig(boolean ec2Mock) { EmulatorConfig config = mock(EmulatorConfig.class); EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TransitGatewayRouteTableIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TransitGatewayRouteTableIntegrationTest.java new file mode 100644 index 0000000000..9fe0897420 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2TransitGatewayRouteTableIntegrationTest.java @@ -0,0 +1,251 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.quarkus.test.junit.QuarkusTest; +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 static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; + +/** + * Route tables, associations, propagations and routes over the EC2 Query protocol. + * + *

The shapes were captured from a live account, including two asymmetries that are easy to get + * wrong: the association and propagation listings drop the route table id that the mutating calls + * carry, and a blackhole route omits the attachment block entirely. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class Ec2TransitGatewayRouteTableIntegrationTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request"; + + private static String transitGatewayId; + private static String defaultRouteTableId; + private static String routeTableId; + private static String attachmentId; + private static String vpcId; + + @Test + @Order(1) + void buildAGatewayAnAttachmentAndASecondRouteTable() { + String created = given() + .formParam("Action", "CreateTransitGateway") + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200).extract().asString(); + transitGatewayId = extract(created, "transitGatewayId"); + defaultRouteTableId = extract(created, "associationDefaultRouteTableId"); + + vpcId = given() + .formParam("Action", "CreateVpc") + .formParam("CidrBlock", "10.40.0.0/16") + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200).extract().path("CreateVpcResponse.vpc.vpcId"); + + String subnetId = given() + .formParam("Action", "CreateSubnet") + .formParam("VpcId", vpcId) + .formParam("CidrBlock", "10.40.1.0/24") + .formParam("AvailabilityZone", "us-east-1a") + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200).extract().path("CreateSubnetResponse.subnet.subnetId"); + + attachmentId = given() + .formParam("Action", "CreateTransitGatewayVpcAttachment") + .formParam("TransitGatewayId", transitGatewayId) + .formParam("VpcId", vpcId) + .formParam("SubnetIds.1", subnetId) + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200) + .extract().path("CreateTransitGatewayVpcAttachmentResponse.transitGatewayVpcAttachment" + + ".transitGatewayAttachmentId"); + + routeTableId = given() + .formParam("Action", "CreateTransitGatewayRouteTable") + .formParam("TransitGatewayId", transitGatewayId) + .formParam("TagSpecification.1.ResourceType", "transit-gateway-route-table") + .formParam("TagSpecification.1.Tag.1.Key", "Name") + .formParam("TagSpecification.1.Tag.1.Value", "spoke") + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200) + .body("CreateTransitGatewayRouteTableResponse.transitGatewayRouteTable.state", equalTo("available")) + .body("CreateTransitGatewayRouteTableResponse.transitGatewayRouteTable" + + ".defaultAssociationRouteTable", equalTo("false")) + .body("CreateTransitGatewayRouteTableResponse.transitGatewayRouteTable.tagSet.item.value", + equalTo("spoke")) + .extract().path("CreateTransitGatewayRouteTableResponse.transitGatewayRouteTable" + + ".transitGatewayRouteTableId"); + } + + private String extract(String body, String element) { + int start = body.indexOf("<" + element + ">") + element.length() + 2; + return body.substring(start, body.indexOf("", start)); + } + + @Test + @Order(2) + void associationsMoveBetweenTablesAndTheListingDropsTheTableId() { + given() + .formParam("Action", "AssociateTransitGatewayRouteTable") + .formParam("TransitGatewayRouteTableId", routeTableId) + .formParam("TransitGatewayAttachmentId", attachmentId) + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("Resource.AlreadyAssociated")); + + given() + .formParam("Action", "DisassociateTransitGatewayRouteTable") + .formParam("TransitGatewayRouteTableId", defaultRouteTableId) + .formParam("TransitGatewayAttachmentId", attachmentId) + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200) + .body("DisassociateTransitGatewayRouteTableResponse.association.state", equalTo("disassociating")) + .body("DisassociateTransitGatewayRouteTableResponse.association.transitGatewayRouteTableId", + equalTo(defaultRouteTableId)); + + given() + .formParam("Action", "AssociateTransitGatewayRouteTable") + .formParam("TransitGatewayRouteTableId", routeTableId) + .formParam("TransitGatewayAttachmentId", attachmentId) + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200) + .body("AssociateTransitGatewayRouteTableResponse.association.state", equalTo("associating")); + + String listing = given() + .formParam("Action", "GetTransitGatewayRouteTableAssociations") + .formParam("TransitGatewayRouteTableId", routeTableId) + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200) + .body("GetTransitGatewayRouteTableAssociationsResponse.associations.item.resourceType", + equalTo("vpc")) + .body("GetTransitGatewayRouteTableAssociationsResponse.associations.item.state", + equalTo("associated")) + .extract().asString(); + + // The caller named the table in the request, so the listing does not repeat it. + assertThat(listing, not(containsString("transitGatewayRouteTableId"))); + } + + @Test + @Order(3) + void propagationEnablesAtOnceAndShowsUpAsARoute() { + given() + .formParam("Action", "EnableTransitGatewayRouteTablePropagation") + .formParam("TransitGatewayRouteTableId", routeTableId) + .formParam("TransitGatewayAttachmentId", attachmentId) + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200) + .body("EnableTransitGatewayRouteTablePropagationResponse.propagation.state", equalTo("enabled")) + .body("EnableTransitGatewayRouteTablePropagationResponse.propagation.transitGatewayRouteTableId", + equalTo(routeTableId)); + + String listing = given() + .formParam("Action", "GetTransitGatewayRouteTablePropagations") + .formParam("TransitGatewayRouteTableId", routeTableId) + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200) + .body("GetTransitGatewayRouteTablePropagationsResponse.transitGatewayRouteTablePropagations" + + ".item.state", equalTo("enabled")) + .extract().asString(); + assertThat(listing, not(containsString("transitGatewayRouteTableId"))); + + // The attached VPC's CIDR appears as a propagated route. + given() + .formParam("Action", "SearchTransitGatewayRoutes") + .formParam("TransitGatewayRouteTableId", routeTableId) + .formParam("Filter.1.Name", "type") + .formParam("Filter.1.Value.1", "propagated") + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200) + .body("SearchTransitGatewayRoutesResponse.routeSet.item.destinationCidrBlock", + equalTo("10.40.0.0/16")) + .body("SearchTransitGatewayRoutesResponse.routeSet.item.type", equalTo("propagated")) + .body("SearchTransitGatewayRoutesResponse.routeSet.item.state", equalTo("active")); + } + + @Test + @Order(4) + void aBlackholeRouteCarriesNoAttachment() { + given() + .formParam("Action", "CreateTransitGatewayRoute") + .formParam("TransitGatewayRouteTableId", routeTableId) + .formParam("DestinationCidrBlock", "10.60.0.0/16") + .formParam("TransitGatewayAttachmentId", attachmentId) + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200) + .body("CreateTransitGatewayRouteResponse.route.type", equalTo("static")) + .body("CreateTransitGatewayRouteResponse.route.state", equalTo("active")) + .body("CreateTransitGatewayRouteResponse.route.transitGatewayAttachments.item" + + ".transitGatewayAttachmentId", equalTo(attachmentId)); + + String blackhole = given() + .formParam("Action", "CreateTransitGatewayRoute") + .formParam("TransitGatewayRouteTableId", routeTableId) + .formParam("DestinationCidrBlock", "10.61.0.0/16") + .formParam("Blackhole", "true") + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(200) + .body("CreateTransitGatewayRouteResponse.route.type", equalTo("static")) + .body("CreateTransitGatewayRouteResponse.route.state", equalTo("blackhole")) + .extract().asString(); + assertThat(blackhole, not(containsString("transitGatewayAttachments"))); + + given() + .formParam("Action", "CreateTransitGatewayRoute") + .formParam("TransitGatewayRouteTableId", routeTableId) + .formParam("DestinationCidrBlock", "10.60.0.0/16") + .formParam("TransitGatewayAttachmentId", attachmentId) + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("RouteAlreadyExists")); + } + + @Test + @Order(5) + void aTableInUseIsRefusedAndTheIdErrorsKeepTheirCasing() { + given() + .formParam("Action", "DeleteTransitGatewayRouteTable") + .formParam("TransitGatewayRouteTableId", routeTableId) + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("IncorrectState")); + + given() + .formParam("Action", "DescribeTransitGatewayRouteTables") + .formParam("TransitGatewayRouteTableIds.1", "tgw-rtb-0123456789abcdef0") + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidRouteTableID.NotFound")); + + given() + .formParam("Action", "DescribeTransitGatewayRouteTables") + .formParam("TransitGatewayRouteTableIds.1", "tgw-rtb-nope") + .header("Authorization", AUTH_HEADER) + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidRouteTableId.Malformed")); + } +}