mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(route53resolver): set endpoint HostVPCId from its subnets and allocate IPs from subnet CIDR (#6886)
* fix(route53resolver): set endpoint HostVPCId from its subnets and allocate IPs from subnet CIDR
HostVPCId was derived from the endpoint id, naming a VPC that does not exist.
An IpAddress given only a SubnetId had no Ip. Resolve the subnets through EC2,
use their VPC, and allocate a free address (skipping the first four and last
of the CIDR) when Ip is omitted. Subnets EC2 does not know are still accepted.
* fix(route53resolver): follow-ups for endpoint subnet resolution
Take HostVPCId from the first subnet in request order, reuse Cidr4 for
address math, import instead of fully qualifying names, document the
unknown-subnet fallback and allocation limits, and cover replay, delete
and mixed explicit/allocated addresses.
* fix(route53resolver): allocate endpoint IPs per subnet and reject an exhausted subnet
Addresses were tracked account-wide, so two VPCs with the same subnet CIDR
skipped each other's addresses. Track them per subnet instead.
When a subnet had no free address, allocateIps stored null and the endpoint
still came back OPERATIONAL. Allocate before writing the endpoint and throw
InvalidRequestException so nothing is stored.
* fix(route53resolver): back each endpoint address with an EC2 network interface
Replaces the endpoint's own address allocator with EC2's, as AWS does
("Resolver creates a network interface for each subnet and IP address") and
as ECS already does for awsvpc tasks. Each address in a subnet EC2 knows
becomes one interface created with ec2Service.createNetworkInterface, with
the request's Ip (or one EC2 picks) and the endpoint's security groups, then
held with holdNetworkInterfaceForService. Instances, other interfaces and
other endpoints can no longer get the same address, and EC2 refuses an
explicit Ip already in use, which CreateResolverEndpoint raises as
InvalidRequestException (the model lists it and names no closer error; a
full subnet maps the same way, other EC2 refusals to
InvalidParameterException). A refusal deletes the interfaces already made.
DeleteResolverEndpoint releases and deletes the endpoint's interfaces.
ListResolverEndpointIpAddresses reports each interface's address, reading
the record once, and a JSON null Ip no longer hides it. Subnets EC2 does not
know are still accepted without an interface, and records written before
this change list and delete as before. HostVPCId still comes from the
subnets.
* fix(route53resolver): close two interface-leak windows in endpoint create and delete
DeleteResolverEndpoint was not synchronized while CreateResolverEndpoint
was. Create stores the endpoint before its record, so a delete between the
two found no interfaces to delete and the create then stored the record,
leaving an orphan record and the endpoint's interfaces behind. Delete now
takes the same lock.
The create rollback caught only AwsException, so any other failure from EC2
partway through left the interfaces already made. It now rolls back on any
RuntimeException and rethrows it; EC2 refusals are still translated.
* fix(route53resolver): create an endpoint's explicit addresses before its automatic ones
Interfaces were created in the stored (sorted) order of the address list.
An explicit IPv4 Ip happens to sort before an entry that leaves the address
to EC2, but nothing guaranteed it, and an automatic entry created first could
take the address a later entry asks for, failing the create with
InvalidRequestException though both fit. Interfaces with an explicit Ip are
now created first; the stored list keeps the request order.
* fix(route53resolver): log an endpoint interface cleanup failure instead of dropping it
The cleanup that deletes an endpoint's interfaces swallowed every EC2
error. Only an interface that is already gone is expected and stays silent;
any other failure is now logged as a warning, and the remaining interfaces
are still deleted.
* test(route53resolver): wait on the racing delete with ThreadStates and use Ec2Requests for EC2 calls
* test(route53resolver): assert the racing delete finished and route EC2 calls through one Ec2Requests helper
This commit is contained in:
1 parent
9b69b3dac3
commit
3d455d02ad
5 files changed
+546
-17
No files matched your search
+155
@@ -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<String, ObjectNode> endpoints = new InMemoryStorage<>();
|
||||
private final Ec2Service ec2 = mock(Ec2Service.class);
|
||||
private final AtomicInteger eniCount = new AtomicInteger();
|
||||
|
||||
private Route53ResolverService service(InMemoryStorage<String, ObjectNode> 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<String, ObjectNode> 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<Throwable> 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<LogRecord> records = LogCapture.capture(Route53ResolverService.class,
|
||||
() -> service.deleteResolverEndpoint(id));
|
||||
|
||||
List<LogRecord> 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");
|
||||
}
|
||||
}
|
||||
+152
@@ -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<String> eniIps = new ArrayList<>(enis.getList(ENI_ITEMS + ".privateIpAddress", String.class));
|
||||
List<String> 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)
|
||||
|
||||
+50
@@ -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<String, ObjectNode> readOnce = new InMemoryStorage<>() {
|
||||
private boolean read;
|
||||
|
||||
@Override
|
||||
public Optional<ObjectNode> 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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user