diff --git a/docs/services/route53resolver.md b/docs/services/route53resolver.md index 352e0720ce..abd6ffce77 100644 --- a/docs/services/route53resolver.md +++ b/docs/services/route53resolver.md @@ -9,11 +9,11 @@ | `GetFirewallDomainList` | Returns a single DNS Firewall domain list by id, whether AWS-managed or custom. | | `CreateFirewallDomainList` | Creates a custom DNS Firewall domain list with a random-suffix `rslvr-fdl-` id. | | `DeleteFirewallDomainList` | Deletes a custom DNS Firewall domain list; AWS-managed lists cannot be deleted. | -| `CreateResolverEndpoint` | Creates an inbound (`rslvr-in-`) or outbound (`rslvr-out-`) resolver endpoint, returned immediately as `OPERATIONAL`. | -| `DeleteResolverEndpoint` | Deletes a resolver endpoint and returns its final description. | +| `CreateResolverEndpoint` | Creates an inbound (`rslvr-in-`) or outbound (`rslvr-out-`) resolver endpoint, returned immediately as `OPERATIONAL`. `HostVPCId` is the VPC of its subnets. Each address in a subnet EC2 knows gets its own EC2 network interface, with the requested `Ip` or one EC2 picks and the endpoint's security groups, held `in-use` for the endpoint; an `Ip` already in use is refused with `InvalidRequestException`. | +| `DeleteResolverEndpoint` | Deletes a resolver endpoint and its network interfaces, and returns its final description. | | `GetResolverEndpoint` | Returns a resolver endpoint by id. | | `ListResolverEndpoints` | Lists all resolver endpoints. | -| `ListResolverEndpointIpAddresses` | Lists a resolver endpoint's IP addresses from those it was created with, each `ATTACHED`; an address left for AWS to choose has no `Ip`. Not paginated. | +| `ListResolverEndpointIpAddresses` | Lists a resolver endpoint's IP addresses, each `ATTACHED`, with the address of the network interface behind it; an address in a subnet EC2 does not know keeps the requested `Ip`, or none. Not paginated. | | `UpdateResolverEndpoint` | Updates a resolver endpoint's `Name` and `ResolverEndpointType`; `IpAddresses` changes are not modelled. | | `CreateResolverRule` | Creates a resolver rule, returned immediately as `COMPLETE`; `ResolverEndpointId` is not validated against an existing endpoint. | | `DeleteResolverRule` | Deletes a resolver rule and returns its final description. | diff --git a/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java index 93deb14e59..52038012d2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java +++ b/src/main/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverService.java @@ -14,13 +14,18 @@ import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.NetworkInterface; +import io.github.hectorvent.floci.services.ec2.model.Subnet; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import org.jboss.logging.Logger; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -46,6 +51,8 @@ import java.util.function.Predicate; @ApplicationScoped public class Route53ResolverService { + private static final Logger LOG = Logger.getLogger(Route53ResolverService.class); + public static final String MANAGED_OWNER_NAME = "Route 53 Resolver DNS Firewall"; /** @@ -87,6 +94,8 @@ public class Route53ResolverService { * carries {@code IpAddressCount} and no IP list, and the handlers return the stored node * verbatim, so holding the addresses on the resource would put an unmodeled member on the * wire. Read by the CreatorRequestId conflict check and ListResolverEndpointIpAddresses. + * Also holds the endpoint's region and, in {@code NetworkInterfaces}, the EC2 interface + * behind each address (see {@link #createEndpointInterfaces}). */ private final StorageBackend endpointIpRequestStore; /** @@ -96,9 +105,11 @@ public class Route53ResolverService { */ private final StorageBackend tagStore; private final ObjectMapper objectMapper; + /** Null only in hermetic tests built without one; subnets are then treated as unknown. */ + private final Ec2Service ec2Service; @Inject - public Route53ResolverService(StorageFactory storageFactory, ObjectMapper objectMapper) { + public Route53ResolverService(StorageFactory storageFactory, ObjectMapper objectMapper, Ec2Service ec2Service) { this.domainListStore = storageFactory.create("route53resolver", "route53resolver-domain-lists.json", new TypeReference>() {}); this.endpointStore = storageFactory.create("route53resolver", "route53resolver-endpoints.json", @@ -113,6 +124,7 @@ public class Route53ResolverService { this.tagStore = storageFactory.create("route53resolver", "route53resolver-tags.json", new TypeReference>() {}); this.objectMapper = objectMapper; + this.ec2Service = ec2Service; } // Package-private for hermetic tests: pass in-memory StorageBackends directly, so a test @@ -125,6 +137,17 @@ public class Route53ResolverService { StorageBackend endpointIpRequestStore, StorageBackend tagStore, ObjectMapper objectMapper) { + this(domainListStore, endpointStore, ruleStore, ruleAssociationStore, endpointIpRequestStore, tagStore, + objectMapper, null); + } + + Route53ResolverService(StorageBackend domainListStore, + StorageBackend endpointStore, + StorageBackend ruleStore, + StorageBackend ruleAssociationStore, + StorageBackend endpointIpRequestStore, + StorageBackend tagStore, + ObjectMapper objectMapper, Ec2Service ec2Service) { this.domainListStore = domainListStore; this.endpointStore = endpointStore; this.ruleStore = ruleStore; @@ -132,6 +155,7 @@ public class Route53ResolverService { this.endpointIpRequestStore = endpointIpRequestStore; this.tagStore = tagStore; this.objectMapper = objectMapper; + this.ec2Service = ec2Service; } public List listFirewallDomainLists(String region) { @@ -228,20 +252,156 @@ public class Route53ResolverService { endpoint.put("Direction", direction); endpoint.set("SecurityGroupIds", request.path("SecurityGroupIds").deepCopy()); endpoint.put("IpAddressCount", ipAddresses.size()); - endpoint.put("HostVPCId", "vpc-" + deterministicHex(id, 8)); + ArrayNode normalized = normalizedIpRequests(ipAddresses); + Map subnets = subnetsOf(normalized, region); + // AWS: HostVPCId is the VPC of the endpoint's subnets (first subnet in request order). + // When EC2 knows none of them the invented vpc- is kept purely for back-compat with + // Floci's earlier accept-any-subnet behaviour; what AWS does there is unverified. + String hostVpc = null; + for (JsonNode r : ipAddresses) { + Subnet known = subnets.get(text(r, "SubnetId")); + if (known != null) { + hostVpc = known.getVpcId(); + break; + } + } + endpoint.put("HostVPCId", hostVpc != null ? hostVpc : "vpc-" + deterministicHex(id, 8)); endpoint.put("Status", "OPERATIONAL"); endpoint.put("CreatorRequestId", text(request, "CreatorRequestId")); endpoint.put("CreationTime", Instant.now().toString()); endpoint.put("ModificationTime", Instant.now().toString()); + // Before anything is stored, so an address EC2 refuses leaves no endpoint behind. + ArrayNode interfaces = createEndpointInterfaces(id, normalized, subnets, + securityGroupIdsOf(request), region); endpointStore.put(id, endpoint); - endpointIpRequestStore.put(id, - objectMapper.createObjectNode().set("IpAddressRequests", normalizedIpRequests(ipAddresses))); + ObjectNode record = objectMapper.createObjectNode(); + record.set("IpAddressRequests", normalized); + record.put("Region", region); + record.set("NetworkInterfaces", interfaces); + endpointIpRequestStore.put(id, record); putTags(endpoint, tags); return endpoint.deepCopy(); } - public ObjectNode deleteResolverEndpoint(String id) { + private Map subnetsOf(JsonNode requests, String region) { + List ids = new ArrayList<>(); + requests.forEach(r -> { + String subnetId = text(r, "SubnetId"); + if (subnetId != null && !ids.contains(subnetId)) { + ids.add(subnetId); + } + }); + Map found = new LinkedHashMap<>(); + if (ec2Service != null && !ids.isEmpty()) { + ec2Service.describeSubnets(region, ids, Map.of()).forEach(sn -> found.put(sn.getSubnetId(), sn)); + } + return found; + } + + private List securityGroupIdsOf(JsonNode request) { + List ids = new ArrayList<>(); + request.path("SecurityGroupIds").forEach(sg -> ids.add(sg.asText())); + return ids; + } + + /** + * One EC2 network interface per address, which is how AWS backs a resolver endpoint ("Resolver + * creates a network interface for each subnet and IP address", Route 53 developer guide), made + * the way ECS makes an awsvpc task's: created in the address's subnet with the request's + * {@code Ip}, or one EC2 picks, and the endpoint's security groups, then held for the service so + * the account cannot delete it from under the endpoint. EC2's allocator then keeps instances, + * other interfaces and other endpoints off the address, and refuses an explicit one in use. + * + *

Entries line up with {@code requests}: the interface's id and address, or null where none + * is made, for a subnet EC2 does not know (Floci has always accepted those) or an IPv6-only + * request. ponytail: Floci's EC2 interfaces are IPv4 only; IPv6 addresses are kept as given. + * A refusal deletes the interfaces already made and is raised in Route 53 Resolver's codes. + */ + private ArrayNode createEndpointInterfaces(String endpointId, JsonNode requests, Map subnets, + List securityGroupIds, String region) { + ArrayNode out = objectMapper.createArrayNode(); + requests.forEach(r -> out.addNull()); + List created = new ArrayList<>(); + try { + // Explicit addresses first, so an address EC2 picks for one entry is never one that a + // later entry asks for; the stored list keeps the request order. + for (boolean explicitPass : new boolean[] {true, false}) { + for (int i = 0; i < requests.size(); i++) { + JsonNode r = requests.get(i); + String subnetId = text(r, "SubnetId"); + String ip = text(r, "Ip"); + if ((ip != null) != explicitPass || !subnets.containsKey(subnetId) + || (ip == null && text(r, "Ipv6") != null)) { + continue; + } + NetworkInterface eni = ec2Service.createNetworkInterface(region, subnetId, + "Route 53 Resolver: " + endpointId, ip, List.of(), securityGroupIds, List.of()); + created.add(eni.getNetworkInterfaceId()); + ec2Service.holdNetworkInterfaceForService(region, eni.getNetworkInterfaceId()); + out.set(i, objectMapper.createObjectNode() + .put("NetworkInterfaceId", eni.getNetworkInterfaceId()) + .put("Ip", eni.getPrivateIpAddress())); + } + } + } catch (RuntimeException e) { + // Any failure, not only EC2's refusals, would otherwise leave the interfaces made so far. + deleteEndpointInterfaces(region, created); + throw e instanceof AwsException refusal ? asResolverRejection(refusal) : e; + } + return out; + } + + /** + * EC2's refusal in a code CreateResolverEndpoint models. The model names no error for an + * address already in use or a subnet with none left, so those take InvalidRequestException + * ("The request is invalid"); anything else EC2 refuses here (an address outside the subnet, a + * security group it does not know) is a parameter that is not valid. + */ + private static AwsException asResolverRejection(AwsException e) { + String code = switch (e.getErrorCode()) { + case "InvalidIPAddress.InUse", "InsufficientFreeAddressesInSubnet" -> "InvalidRequestException"; + default -> INVALID_PARAMETER; + }; + return new AwsException(code, e.getMessage(), 400); + } + + /** + * Releases and deletes the interfaces, the way ECS tears down a task's. One that is already gone + * is skipped silently; any other failure is logged and the rest are still deleted, so one + * interface EC2 will not delete does not strand the others. + */ + private void deleteEndpointInterfaces(String region, List interfaceIds) { + for (String eniId : interfaceIds) { + try { + ec2Service.releaseNetworkInterfaceFromService(region, eniId); + ec2Service.deleteNetworkInterface(region, eniId); + } catch (AwsException e) { + if ("InvalidNetworkInterfaceID.NotFound".equals(e.getErrorCode())) { + // Expected: the interface is already deleted, so there is nothing left to free. + continue; + } + LOG.warnv("Could not delete network interface {0} of a Route 53 Resolver endpoint: {1}", + eniId, e.getMessage()); + } + } + } + + // Synchronized with createResolverEndpoint, which stores the endpoint before its record: a delete + // between the two would find no interfaces to delete, and the create would then store the record. + public synchronized ObjectNode deleteResolverEndpoint(String id) { ObjectNode endpoint = require(endpointStore, id, "resolver endpoint"); + // A record written before endpoints had interfaces has no NetworkInterfaces, so none to delete. + endpointIpRequestStore.get(id).ifPresent(record -> { + List interfaceIds = new ArrayList<>(); + record.path("NetworkInterfaces").forEach(eni -> { + if (text(eni, "NetworkInterfaceId") != null) { + interfaceIds.add(text(eni, "NetworkInterfaceId")); + } + }); + if (ec2Service != null) { + deleteEndpointInterfaces(text(record, "Region"), interfaceIds); + } + }); endpointStore.delete(id); endpointIpRequestStore.delete(id); tagStore.delete(text(endpoint, "Arn")); @@ -261,19 +421,22 @@ public class Route53ResolverService { /** * The endpoint's addresses as AWS {@code IpAddressResponse} entries, built from the * {@code IpAddresses} recorded at create time. {@code IpId} is derived from the endpoint, - * the entry and its position in the recorded list, so it is stable across calls. An - * address the request left for AWS to pick has no {@code Ip}: Floci does not allocate - * from the subnet. + * the entry and its position in the recorded list, so it is stable across calls. {@code Ip} + * is the address of the EC2 interface behind the entry; an entry with no interface (see + * {@link #createEndpointInterfaces}) has the request's {@code Ip}, or none. */ public List listResolverEndpointIpAddresses(String id) { ObjectNode endpoint = require(endpointStore, id, "resolver endpoint"); + // Read once, so the requests and their interfaces come from the same record. + JsonNode record = endpointIpRequestStore.get(id).orElse(null); + JsonNode recorded = record == null ? null : record.get("IpAddressRequests"); // A missing record would otherwise read as an empty list beside a nonzero // IpAddressCount; fail loudly with the modeled InternalServiceErrorException instead. - JsonNode recorded = endpointIpRequestStore.get(id) - .map(node -> node.get("IpAddressRequests")) - .filter(JsonNode::isArray) - .orElseThrow(() -> new AwsException("InternalServiceErrorException", - "No IP addresses recorded for resolver endpoint: " + id, 400)); + if (recorded == null || !recorded.isArray()) { + throw new AwsException("InternalServiceErrorException", + "No IP addresses recorded for resolver endpoint: " + id, 400); + } + JsonNode interfaces = record.path("NetworkInterfaces"); List addresses = new ArrayList<>(); for (int i = 0; i < recorded.size(); i++) { JsonNode request = recorded.get(i); @@ -281,7 +444,10 @@ public class Route53ResolverService { // The index keeps repeated entries (two addresses in one subnet, both left for AWS // to pick) distinct; the stored list is normalised once at create, so it is stable. address.put("IpId", "rni-" + deterministicHex(id + "|" + i + "|" + canonicalKey(request), 17)); - copyIfPresent(request, address, "SubnetId", "Ip", "Ipv6"); + String ip = text(interfaces.path(i), "Ip"); + putIfSet(address, "SubnetId", text(request, "SubnetId")); + putIfSet(address, "Ip", ip != null ? ip : text(request, "Ip")); + putIfSet(address, "Ipv6", text(request, "Ipv6")); address.put("Status", "ATTACHED"); address.put("StatusMessage", "This IP address is operational."); address.set("CreationTime", endpoint.get("CreationTime")); @@ -291,6 +457,12 @@ public class Route53ResolverService { return addresses; } + private static void putIfSet(ObjectNode target, String field, String value) { + if (value != null) { + target.put(field, value); + } + } + public ObjectNode updateResolverEndpoint(String id, JsonNode request) { ObjectNode endpoint = require(endpointStore, id, "resolver endpoint"); String endpointType = text(request, "ResolverEndpointType"); diff --git a/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverEndpointInterfacesTest.java b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverEndpointInterfacesTest.java new file mode 100644 index 0000000000..d61ba9d51d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverEndpointInterfacesTest.java @@ -0,0 +1,155 @@ +package io.github.hectorvent.floci.services.route53resolver; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.NetworkInterface; +import io.github.hectorvent.floci.services.ec2.model.Subnet; +import io.github.hectorvent.floci.testing.ThreadStates; +import io.github.hectorvent.floci.testutil.LogCapture; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** How a resolver endpoint's EC2 interfaces are cleaned up when its create fails or races a delete. */ +class Route53ResolverEndpointInterfacesTest { + + private static final String REGION = "us-east-1"; + + private final ObjectMapper objectMapper = new ObjectMapper(); + private final InMemoryStorage endpoints = new InMemoryStorage<>(); + private final Ec2Service ec2 = mock(Ec2Service.class); + private final AtomicInteger eniCount = new AtomicInteger(); + + private Route53ResolverService service(InMemoryStorage ipRequests) { + Subnet subnet = new Subnet(); + subnet.setSubnetId("subnet-aaa"); + subnet.setVpcId("vpc-aaa"); + when(ec2.describeSubnets(eq(REGION), anyList(), any())).thenReturn(List.of(subnet)); + return new Route53ResolverService(new InMemoryStorage<>(), endpoints, new InMemoryStorage<>(), + new InMemoryStorage<>(), ipRequests, new InMemoryStorage<>(), objectMapper, ec2); + } + + private NetworkInterface eni() { + int n = eniCount.incrementAndGet(); + NetworkInterface eni = new NetworkInterface(); + eni.setNetworkInterfaceId("eni-" + n); + eni.setPrivateIpAddress("10.0.0." + (10 + n)); + return eni; + } + + private ObjectNode request() { + ObjectNode request = objectMapper.createObjectNode(); + request.put("Name", "ep"); + request.put("Direction", "INBOUND"); + request.putArray("SecurityGroupIds").add("sg-aaa"); + request.putArray("IpAddresses").add(objectMapper.createObjectNode().put("SubnetId", "subnet-aaa")) + .add(objectMapper.createObjectNode().put("SubnetId", "subnet-aaa")); + return request; + } + + @Test + void aFailureThatIsNotAnEc2RefusalStillDeletesTheInterfacesAlreadyMade() { + Route53ResolverService service = service(new InMemoryStorage<>()); + IllegalStateException boom = new IllegalStateException("boom"); + when(ec2.createNetworkInterface(any(), any(), any(), any(), any(), any(), any())) + .thenAnswer(call -> eni()) + .thenThrow(boom); + + assertSame(boom, assertThrows(IllegalStateException.class, + () -> service.createResolverEndpoint(request(), REGION, "000000000000"))); + + verify(ec2).releaseNetworkInterfaceFromService(REGION, "eni-1"); + verify(ec2).deleteNetworkInterface(REGION, "eni-1"); + assertTrue(endpoints.scan(k -> true).isEmpty()); + } + + @Test + void aDeleteThatRacesTheCreateStillDeletesTheEndpointsInterfaces() throws Exception { + CountDownLatch inPut = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + InMemoryStorage ipRequests = new InMemoryStorage<>() { + @Override + public void put(String key, ObjectNode value) { + inPut.countDown(); + try { + release.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + super.put(key, value); + } + }; + Route53ResolverService service = service(ipRequests); + when(ec2.createNetworkInterface(any(), any(), any(), any(), any(), any(), any())) + .thenAnswer(call -> eni()); + + Thread create = new Thread(() -> service.createResolverEndpoint(request(), REGION, "000000000000")); + create.start(); + assertTrue(inPut.await(10, TimeUnit.SECONDS)); + // The endpoint is stored; its record, naming the interfaces, is not yet. + String id = endpoints.scan(k -> true).getFirst().get("Id").asText(); + AtomicReference deleteError = new AtomicReference<>(); + Thread delete = new Thread(() -> { + try { + service.deleteResolverEndpoint(id); + } catch (Throwable t) { + deleteError.set(t); + } + }); + delete.start(); + ThreadStates.awaitBlockedOrDone(delete); + release.countDown(); + create.join(10_000); + delete.join(10_000); + assertFalse(delete.isAlive(), "the delete must finish once the create is released"); + + assertEquals(null, deleteError.get()); + verify(ec2).deleteNetworkInterface(REGION, "eni-1"); + verify(ec2).deleteNetworkInterface(REGION, "eni-2"); + assertTrue(ipRequests.scan(k -> true).isEmpty(), "no orphan record may outlive the endpoint"); + assertTrue(endpoints.scan(k -> true).isEmpty()); + } + + @Test + void aCleanupFailureOtherThanAMissingInterfaceIsLoggedAndTheRestAreStillDeleted() { + Route53ResolverService service = service(new InMemoryStorage<>()); + when(ec2.createNetworkInterface(any(), any(), any(), any(), any(), any(), any())) + .thenAnswer(call -> eni()); + String id = service.createResolverEndpoint(request(), REGION, "000000000000").get("Id").asText(); + doThrow(new AwsException("InvalidParameterValue", "Network interface 'eni-1' is currently in use", 400)) + .when(ec2).deleteNetworkInterface(REGION, "eni-1"); + doThrow(new AwsException("InvalidNetworkInterfaceID.NotFound", "The network interface ID 'eni-2' does not exist", + 400)).when(ec2).deleteNetworkInterface(REGION, "eni-2"); + + List records = LogCapture.capture(Route53ResolverService.class, + () -> service.deleteResolverEndpoint(id)); + + List warnings = records.stream().filter(r -> r.getLevel().intValue() == Level.WARNING.intValue()).toList(); + assertEquals(1, warnings.size(), "only the unexpected failure is logged"); + assertTrue(Arrays.asList(warnings.getFirst().getParameters()).contains("eni-1")); + verify(ec2).deleteNetworkInterface(REGION, "eni-2"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverIntegrationTest.java index 81cf7c0447..c14719f7f4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverIntegrationTest.java @@ -3,12 +3,18 @@ package io.github.hectorvent.floci.services.route53resolver; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; import io.restassured.path.json.JsonPath; +import io.restassured.path.xml.XmlPath; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashSet; import java.util.List; +import static io.github.hectorvent.floci.testing.Ec2Requests.ec2; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; @@ -18,6 +24,7 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Integration tests for Route 53 Resolver DNS Firewall operations @@ -180,6 +187,151 @@ class Route53ResolverIntegrationTest { // The Terraform provider calls this right after CreateResolverEndpoint to read the // endpoint's ip_address set, so an unimplemented operation fails every endpoint create. + @Test + void createResolverEndpoint_backsEachAddressWithAHeldEc2Interface() { + String vpc = ec2Ok("CreateVpc", "CidrBlock", "10.77.0.0/16").extract().path("CreateVpcResponse.vpc.vpcId"); + String subA = ec2Ok("CreateSubnet", "VpcId", vpc, "CidrBlock", "10.77.1.0/24", "AvailabilityZone", "us-east-1a") + .extract().path("CreateSubnetResponse.subnet.subnetId"); + String subB = ec2Ok("CreateSubnet", "VpcId", vpc, "CidrBlock", "10.77.2.0/28", "AvailabilityZone", "us-east-1b") + .extract().path("CreateSubnetResponse.subnet.subnetId"); + String sg = securityGroup(vpc, "ep-iface"); + // "Ip": null is a request that leaves the address to AWS, the same as one with no Ip. + String id = createEndpoint("{\"Name\":\"ep-iface\",\"Direction\":\"INBOUND\",\"SecurityGroupIds\":[\"" + sg + + "\"],\"IpAddresses\":[{\"SubnetId\":\"" + subA + "\"},{\"SubnetId\":\"" + subA + + "\",\"Ip\":\"10.77.1.40\"},{\"SubnetId\":\"" + subB + "\",\"Ip\":null}]}"); + + given().contentType(CONTENT_TYPE).header("X-Amz-Target", "Route53Resolver.GetResolverEndpoint") + .header("Authorization", AUTH_HEADER).body("{\"ResolverEndpointId\":\"" + id + "\"}") + .when().post("/").then().statusCode(200).body("ResolverEndpoint.HostVPCId", equalTo(vpc)); + JsonPath listed = JsonPath.from(listIpAddresses(id)); + for (String subnet : List.of(subA, subB)) { + XmlPath enis = describeInterfaces(subnet); + List eniIps = new ArrayList<>(enis.getList(ENI_ITEMS + ".privateIpAddress", String.class)); + List listedIps = new ArrayList<>( + listed.getList("IpAddresses.findAll { it.SubnetId == '" + subnet + "' }.Ip", String.class)); + Collections.sort(eniIps); + Collections.sort(listedIps); + assertEquals(subnet.equals(subA) ? 2 : 1, eniIps.size(), subnet); + assertEquals(eniIps, listedIps, "ListResolverEndpointIpAddresses must report the interfaces' addresses"); + assertEquals(List.of(sg), enis.getList(ENI_ITEMS + ".groupSet.item.groupId", String.class) + .stream().distinct().toList()); + assertEquals(List.of("in-use"), enis.getList(ENI_ITEMS + ".status", String.class) + .stream().distinct().toList()); + } + assertTrue(listed.getList("IpAddresses.Ip").contains("10.77.1.40")); + + // The endpoint holds its interfaces, so the account cannot delete one from under it. + String held = describeInterfaces(subA).getString(ENI_ITEMS + "[0].networkInterfaceId"); + ec2("DeleteNetworkInterface", "AKID", "us-east-1") + .formParam("NetworkInterfaceId", held) + .when().post("/").then().statusCode(400); + } + + @Test + void createResolverEndpoint_explicitIpAnotherEndpointHoldsIsRefused_deleteFreesIt() { + String vpc = ec2Ok("CreateVpc", "CidrBlock", "10.78.0.0/16").extract().path("CreateVpcResponse.vpc.vpcId"); + String sub = ec2Ok("CreateSubnet", "VpcId", vpc, "CidrBlock", "10.78.1.0/24", "AvailabilityZone", "us-east-1a") + .extract().path("CreateSubnetResponse.subnet.subnetId"); + String sg = securityGroup(vpc, "ep-taken"); + String first = createEndpoint("{\"Name\":\"ep-taken-1\",\"Direction\":\"INBOUND\",\"SecurityGroupIds\":[\"" + + sg + "\"],\"IpAddresses\":[{\"SubnetId\":\"" + sub + "\",\"Ip\":\"10.78.1.30\"},{\"SubnetId\":\"" + + sub + "\"}]}"); + // .20 is free and is made first, so the refusal of .30 has an interface to roll back. + String second = "{\"Name\":\"ep-taken-2\",\"Direction\":\"INBOUND\",\"SecurityGroupIds\":[\"" + sg + + "\"],\"IpAddresses\":[{\"SubnetId\":\"" + sub + "\",\"Ip\":\"10.78.1.30\"},{\"SubnetId\":\"" + + sub + "\",\"Ip\":\"10.78.1.20\"}]}"; + + given().contentType(CONTENT_TYPE).header("X-Amz-Target", "Route53Resolver.CreateResolverEndpoint") + .header("Authorization", AUTH_HEADER).body(second) + .when().post("/").then().statusCode(400).body("__type", equalTo("InvalidRequestException")); + assertEquals(2, describeInterfaces(sub).getList(ENI_ITEMS + ".networkInterfaceId").size(), + "a refused endpoint must leave no interface behind"); + given().contentType(CONTENT_TYPE).header("X-Amz-Target", "Route53Resolver.ListResolverEndpoints") + .header("Authorization", AUTH_HEADER).body("{}") + .when().post("/").then().statusCode(200) + .body("ResolverEndpoints.findAll { it.Name == 'ep-taken-2' }.size()", equalTo(0)); + + given().contentType(CONTENT_TYPE).header("X-Amz-Target", "Route53Resolver.DeleteResolverEndpoint") + .header("Authorization", AUTH_HEADER).body("{\"ResolverEndpointId\":\"" + first + "\"}") + .when().post("/").then().statusCode(200); + assertTrue(describeInterfaces(sub).getList(ENI_ITEMS + ".networkInterfaceId").isEmpty(), + "deleting the endpoint deletes its interfaces"); + String again = createEndpoint(second); + assertEquals(List.of("10.78.1.20", "10.78.1.30"), JsonPath.from(listIpAddresses(again)) + .getList("IpAddresses.Ip", String.class).stream().sorted().toList()); + } + + @Test + void createResolverEndpoint_anAutomaticAddressDoesNotTakeOneRequestedLaterInTheList() { + String vpc = ec2Ok("CreateVpc", "CidrBlock", "10.81.0.0/16").extract().path("CreateVpcResponse.vpc.vpcId"); + String sub = ec2Ok("CreateSubnet", "VpcId", vpc, "CidrBlock", "10.81.1.0/24", "AvailabilityZone", "us-east-1a") + .extract().path("CreateSubnetResponse.subnet.subnetId"); + String sg = securityGroup(vpc, "ep-order"); + // A fresh subnet's first automatic address, which a later entry asks for explicitly. + String probe = ec2Ok("CreateNetworkInterface", "SubnetId", sub) + .extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId"); + String first = describeInterfaces(sub).getString(ENI_ITEMS + ".privateIpAddress"); + ec2Ok("DeleteNetworkInterface", "NetworkInterfaceId", probe); + String next = first.substring(0, first.lastIndexOf('.') + 1) + + (Integer.parseInt(first.substring(first.lastIndexOf('.') + 1)) + 1); + + for (String auto : List.of("{\"SubnetId\":\"" + sub + "\"}", "{\"SubnetId\":\"" + sub + "\",\"Ip\":null}")) { + String id = createEndpoint("{\"Name\":\"ep-order\",\"Direction\":\"INBOUND\",\"SecurityGroupIds\":[\"" + + sg + "\"],\"IpAddresses\":[" + auto + ",{\"SubnetId\":\"" + sub + "\",\"Ip\":\"" + next + "\"}]}"); + assertTrue(JsonPath.from(listIpAddresses(id)).getList("IpAddresses.Ip").contains(next), auto); + given().contentType(CONTENT_TYPE).header("X-Amz-Target", "Route53Resolver.DeleteResolverEndpoint") + .header("Authorization", AUTH_HEADER).body("{\"ResolverEndpointId\":\"" + id + "\"}") + .when().post("/").then().statusCode(200); + } + } + + @Test + void createResolverEndpoint_exhaustedSubnetIsRejectedAndStoresNothing() { + String vpc = ec2Ok("CreateVpc", "CidrBlock", "10.80.0.0/16").extract().path("CreateVpcResponse.vpc.vpcId"); + // /28 = 16 addresses, minus 4 reserved at the bottom and 1 at the top = 11 assignable. + String sub = ec2Ok("CreateSubnet", "VpcId", vpc, "CidrBlock", "10.80.1.0/28", "AvailabilityZone", "us-east-1a") + .extract().path("CreateSubnetResponse.subnet.subnetId"); + String sg = securityGroup(vpc, "ep-exhausted"); + String requests = String.join(",", Collections.nCopies(12, "{\"SubnetId\":\"" + sub + "\"}")); + given().contentType(CONTENT_TYPE).header("X-Amz-Target", "Route53Resolver.CreateResolverEndpoint") + .header("Authorization", AUTH_HEADER) + .body("{\"Name\":\"ep-exhausted\",\"Direction\":\"INBOUND\",\"SecurityGroupIds\":[\"" + sg + "\"]," + + "\"IpAddresses\":[" + requests + "]}") + .when().post("/").then().statusCode(400).body("__type", equalTo("InvalidRequestException")); + assertTrue(describeInterfaces(sub).getList(ENI_ITEMS + ".networkInterfaceId").isEmpty()); + given().contentType(CONTENT_TYPE).header("X-Amz-Target", "Route53Resolver.ListResolverEndpoints") + .header("Authorization", AUTH_HEADER).body("{}") + .when().post("/").then().statusCode(200) + .body("ResolverEndpoints.findAll { it.Name == 'ep-exhausted' }.size()", equalTo(0)); + } + + private static final String ENI_ITEMS = "DescribeNetworkInterfacesResponse.networkInterfaceSet.item"; + + private static String securityGroup(String vpc, String name) { + return ec2Ok("CreateSecurityGroup", "GroupName", name, "GroupDescription", name, "VpcId", vpc) + .extract().path("CreateSecurityGroupResponse.groupId"); + } + + private static XmlPath describeInterfaces(String subnet) { + return ec2Ok("DescribeNetworkInterfaces", "Filter.1.Name", "subnet-id", "Filter.1.Value.1", subnet) + .extract().xmlPath(); + } + + private static String createEndpoint(String body) { + return given().contentType(CONTENT_TYPE).header("X-Amz-Target", "Route53Resolver.CreateResolverEndpoint") + .header("Authorization", AUTH_HEADER).body(body) + .when().post("/").then().statusCode(200).extract().path("ResolverEndpoint.Id"); + } + + /** An EC2 Query call through {@link io.github.hectorvent.floci.testing.Ec2Requests}, expecting 200. */ + private static ValidatableResponse ec2Ok(String action, String... params) { + RequestSpecification spec = ec2(action, "AKID", "us-east-1"); + for (int i = 0; i < params.length; i += 2) { + spec = spec.formParam(params[i], params[i + 1]); + } + return spec.post("/").then().statusCode(200); + } + private static String listIpAddresses(String endpointId) { return given() .contentType(CONTENT_TYPE) diff --git a/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverReplayFallbackTest.java b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverReplayFallbackTest.java index 097875f521..83788d0962 100644 --- a/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverReplayFallbackTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/route53resolver/Route53ResolverReplayFallbackTest.java @@ -9,8 +9,12 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.List; +import java.util.Optional; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * What {@code CreateResolverEndpoint} does when a stored endpoint has no recorded @@ -110,4 +114,50 @@ class Route53ResolverReplayFallbackTest { ObjectNode second = service.createResolverEndpoint(createRequest(token, "10.0.0.5"), REGION, ACCOUNT); assertEquals(first.get("Id").asText(), second.get("Id").asText()); } + + @Test + void aRecordFromBeforeEndpointsHadInterfacesStillListsAndDeletes() { + ObjectNode created = service.createResolverEndpoint(createRequest("tok-legacy", "10.0.0.5"), REGION, ACCOUNT); + String id = created.get("Id").asText(); + ObjectNode legacy = objectMapper.createObjectNode(); + legacy.set("IpAddressRequests", endpointIpRequests.get(id).orElseThrow().get("IpAddressRequests")); + endpointIpRequests.put(id, legacy); + + assertEquals(List.of("10.0.0.5", "10.0.0.6"), service.listResolverEndpointIpAddresses(id).stream() + .map(a -> a.get("Ip").asText()).sorted().toList()); + assertEquals("DELETING", service.deleteResolverEndpoint(id).get("Status").asText()); + assertTrue(endpointIpRequests.get(id).isEmpty()); + } + + @Test + void listingTakesTheAddressesAndTheirInterfacesFromOneRead() { + // A delete landing between two reads must not leave ATTACHED addresses without their Ip. + InMemoryStorage readOnce = new InMemoryStorage<>() { + private boolean read; + + @Override + public Optional get(String key) { + if (read) { + return Optional.empty(); + } + read = true; + return super.get(key); + } + }; + Route53ResolverService racing = new Route53ResolverService(new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), readOnce, new InMemoryStorage<>(), objectMapper); + ObjectNode created = racing.createResolverEndpoint(createRequest("tok-race", "10.0.0.5"), REGION, ACCOUNT); + String id = created.get("Id").asText(); + ObjectNode record = objectMapper.createObjectNode(); + ArrayNode requests = record.putArray("IpAddressRequests"); + requests.addObject().put("SubnetId", "subnet-aaa"); + requests.addObject().put("SubnetId", "subnet-aaa"); + ArrayNode interfaces = record.putArray("NetworkInterfaces"); + interfaces.addObject().put("NetworkInterfaceId", "eni-1").put("Ip", "10.0.0.20"); + interfaces.addObject().put("NetworkInterfaceId", "eni-2").put("Ip", "10.0.0.21"); + readOnce.put(id, record); + + assertEquals(List.of("10.0.0.20", "10.0.0.21"), racing.listResolverEndpointIpAddresses(id).stream() + .map(a -> a.path("Ip").asText("missing")).sorted().toList()); + } }