feat(apigatewayv2): route VPC link integrations to Cloud Map service instances (#6753)

This commit is contained in:
Liron Cohen authored and GitHub committed 2026-10-27 19:06:02 -04:00
1 parent a8151ff56b
commit 4fffb5a8c1
24 files changed
+998 -48

No files matched your search

@@ -54,7 +54,7 @@ class ApiGatewayExecuteControllerTest {
return new ApiGatewayExecuteController(
null, null, null, null,
regionResolver, objectMapper, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null);
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null, null);
}
@Test
@@ -457,7 +457,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, null, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null);
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null, null);
Response response = controller.dispatch("GET", "abc123", "prod", "hello", headers, null, null);
@@ -489,7 +489,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, null, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, requestContext, null, null, null);
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, requestContext, null, null, null, null);
controller.dispatch("GET", "abc123", "prod", "hello", headers, null, null);
@@ -524,7 +524,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = new ApiGatewayExecuteController(
apiGatewayService, null, apiGatewayV2Service, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null);
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null, null);
controller.dispatch("GET", "restapi1", "prod", "hello", headers, null, null);
@@ -36,7 +36,7 @@ class ApiGatewayProxyMatchTest {
ctrl = new ApiGatewayExecuteController(apiGatewayService, null, apiGatewayV2Service, lambdaService,
new RegionResolver("us-east-1", "000000000000"),
new ObjectMapper(), vtlEngine, serviceRouter, webSocketConnectionManager, elbV2Service, null,
new ApiGatewayExecuteRouteContext(), null, null, null, null, null);
new ApiGatewayExecuteRouteContext(), null, null, null, null, null, null);
}
private ApiGatewayResource resource(String id, String parentId, String pathPart, String path) {
@@ -48,7 +48,7 @@ class BuildV2AuthorizerEventTrailingSlashTest {
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
null, null
, null, null);
, null, null, null);
}
private JsonNode buildEvent(String normalizedPath, String rawRequestUri) throws Exception {
@@ -51,7 +51,7 @@ class BuildV2ProxyEventBodyEncodingTest {
null, null, null, null,
regionResolver, objectMapper, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
, null, null);
, null, null, null);
}
@ParameterizedTest(name = "{0}")
@@ -47,7 +47,7 @@ class BuildV2ProxyEventJwtClaimsTest {
null, null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
, null, null);
, null, null, null);
}
@Test
@@ -51,7 +51,7 @@ class BuildV2ProxyEventLambdaAuthorizerTest {
null, null, null, null,
regionResolver, MAPPER, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
, null, null);
, null, null, null);
}
@Test
@@ -54,7 +54,7 @@ class BuildV2ProxyEventMultiValueTest {
controller = new ApiGatewayExecuteController(
null, null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null);
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null, null);
}
enum Builder { INTEGRATION, AUTHORIZER }
@@ -42,7 +42,7 @@ class BuildV2ProxyEventPathParametersTest {
null, null, null, null,
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null
, null, null);
, null, null, null);
}
@Test
@@ -42,7 +42,7 @@ class BuildV2ProxyEventStageVariablesTest {
controller = new ApiGatewayExecuteController(
null, null, null, null,
regionResolver, MAPPER, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null);
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null, null);
}
@Test
@@ -47,7 +47,7 @@ class BuildV2ProxyEventTrailingSlashTest {
regionResolver, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
null, null
, null, null);
, null, null, null);
}
private JsonNode buildEvent(String normalizedPath, String rawRequestUri, String routeKey) throws Exception {
@@ -182,7 +182,7 @@ class HttpApiAuthorizerPolicyTest {
routeContext.routeToHttpApi("us-east-1");
return new ApiGatewayExecuteController(null, null, gateway, lambda,
new RegionResolver("us-east-1", "000000000000"), mapper, null, null, null, null, null,
routeContext, null, null, null, null, new AuthorizerPolicyEvaluator(new IamPolicyEvaluator(mapper)));
routeContext, null, null, null, null, new AuthorizerPolicyEvaluator(new IamPolicyEvaluator(mapper)), null);
}
private InvokeResult result(String payload) {
@@ -29,7 +29,7 @@ class JwtClaimsWireFormatTest {
null, new ObjectMapper(), null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null,
null, null
, null, null);
, null, null, null);
}
private static String unsignedToken(String claimsJson) {
@@ -63,7 +63,7 @@ class ProxyEventIamIdentityTest {
controller = new ApiGatewayExecuteController(
null, null, null, null,
regionResolver, MAPPER, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null);
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null, null);
}
@Test
@@ -50,7 +50,7 @@ class ProxyEventPathParametersTest {
controller = new ApiGatewayExecuteController(
null, null, null, null,
regionResolver, MAPPER, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null);
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null, null);
}
private JsonNode pathParametersFor(String path, String resourcePath) throws Exception {
@@ -0,0 +1,35 @@
package io.github.hectorvent.floci.services.apigateway;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class RawTargetPathTest {
@Test
void namedStageStaysInTheTargetPathAsTheCallerEncodedIt() {
assertEquals("/prod/a%3Fb", ApiGatewayExecuteController.rawTargetPath("/a?b", "/execute-api/api1/prod/a%3Fb", "prod"));
assertEquals("/prod/x/", ApiGatewayExecuteController.rawTargetPath("/x", "/execute-api/api1/prod/x/", "prod"));
assertEquals("/test/a%20b/c", ApiGatewayExecuteController.rawTargetPath("/a b/c", "/execute-api/api1/test/a%20b/c", "test"));
}
@Test
void defaultStageIsNotPartOfTheTargetPath() {
assertEquals("/a%3Fb", ApiGatewayExecuteController.rawTargetPath("/a?b", "/execute-api/api1/$default/a%3Fb", "$default"));
assertEquals("/x/", ApiGatewayExecuteController.rawTargetPath("/x", "/execute-api/api1/$default/x/", "$default"));
}
@Test
void emptyRemainderIsTheStageRootOrTheRootPath() {
assertEquals("/prod", ApiGatewayExecuteController.rawTargetPath("/", "/execute-api/api1/prod", "prod"));
assertEquals("/prod/", ApiGatewayExecuteController.rawTargetPath("/", "/execute-api/api1/prod/", "prod"));
assertEquals("/", ApiGatewayExecuteController.rawTargetPath("/", "/execute-api/api1/$default", "$default"));
assertEquals("/", ApiGatewayExecuteController.rawTargetPath("/", "/execute-api/api1/$default/", "$default"));
}
@Test
void missingRawPathFallsBackToTheNormalizedPath() {
assertEquals("/x", ApiGatewayExecuteController.rawTargetPath("/x", null, "$default"));
assertEquals("/prod/x", ApiGatewayExecuteController.rawTargetPath("/x", null, "prod"));
}
}
@@ -56,7 +56,8 @@ class ApiGatewayV2AlbIntegrationTest {
stub = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
stub.createContext("/", exchange -> {
String reqPath = exchange.getRequestURI().getPath();
byte[] body = ("{\"status\":\"ok\",\"path\":\"" + reqPath + "\"}").getBytes(StandardCharsets.UTF_8);
String rawPath = exchange.getRequestURI().getRawPath();
byte[] body = ("{\"status\":\"ok\",\"path\":\"" + reqPath + "\",\"rawPath\":\"" + rawPath + "\"}").getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(200, body.length);
try (OutputStream os = exchange.getResponseBody()) {
@@ -332,6 +333,29 @@ class ApiGatewayV2AlbIntegrationTest {
@Test
@Order(12)
void albListenerIgnoresUnknownVpcLinkConnectionId() {
patchConnectionId("vpclink-missing");
try {
given().when().get("/execute-api/" + apiId + "/$default/health")
.then().statusCode(200).body("path", equalTo("/health"));
} finally {
patchConnectionId(vpcLinkId);
}
}
private static void patchConnectionId(String connectionId) {
given()
.contentType(ContentType.JSON)
.body("""
{"connectionId":"%s"}
""".formatted(connectionId))
.when().patch("/v2/apis/" + apiId + "/integrations/" + integrationId)
.then()
.statusCode(200);
}
@Test
@Order(13)
void unresolvableListenerArnReturns502() {
// Replace the integrationUri with a listener ARN that doesn't exist.
// The ALB resolver must return a clean 502, not crash.
@@ -351,6 +375,34 @@ class ApiGatewayV2AlbIntegrationTest {
.statusCode(502);
}
@Test
@Order(14)
void albTargetReceivesEncodedPathAndTrailingSlashAsTheCallerSentThem() {
given().contentType(ContentType.JSON)
.body("{\"integrationUri\":\"" + listenerArn + "\"}")
.when().patch("/v2/apis/" + apiId + "/integrations/" + integrationId)
.then().statusCode(200);
given().contentType(ContentType.JSON)
.body("{\"routeKey\":\"GET /{proxy+}\",\"target\":\"integrations/" + integrationId + "\"}")
.when().post("/v2/apis/" + apiId + "/routes").then().statusCode(201);
given().urlEncodingEnabled(false).when().get("/execute-api/" + apiId + "/$default/a%3Fb")
.then().statusCode(200).body("rawPath", equalTo("/a%3Fb"));
given().urlEncodingEnabled(false).when().get("/execute-api/" + apiId + "/$default/x/")
.then().statusCode(200).body("rawPath", equalTo("/x/"));
}
@Test
@Order(15)
void albTargetReceivesTheNamedStageInThePathButNotTheDefaultStage() {
given().urlEncodingEnabled(false).when().get("/execute-api/" + apiId + "/prod/a%3Fb")
.then().statusCode(200).body("rawPath", equalTo("/prod/a%3Fb"));
given().urlEncodingEnabled(false).when().get("/execute-api/" + apiId + "/prod/x/")
.then().statusCode(200).body("rawPath", equalTo("/prod/x/"));
given().urlEncodingEnabled(false).when().get("/execute-api/" + apiId + "/$default/a%3Fb")
.then().statusCode(200).body("rawPath", equalTo("/a%3Fb"));
}
@Test
@Order(90)
void cleanup() {
@@ -0,0 +1,377 @@
package io.github.hectorvent.floci.services.apigatewayv2;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
/** End-to-end: HTTP API HTTP_PROXY over a VPC link, integrationUri = Cloud Map service ARN. */
@QuarkusTest
class ApiGatewayV2CloudMapIntegrationTest {
private static final String CLOUD_MAP_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String CLOUD_MAP_TARGET_PREFIX = "Route53AutoNaming_v20170314.";
private static final int REQUESTS_PER_SPREAD_CHECK = 40;
private static final String REGION = "us-east-1";
private static String namespaceId;
@Inject
ApiGatewayV2Service apiGatewayV2Service;
private final List<Stub> stubs = new ArrayList<>();
private final List<String> apiIds = new ArrayList<>();
private final List<String> vpcLinkIds = new ArrayList<>();
private record Received(String method, String path, String query, String body, String header) {}
/** An in-test backend on 127.0.0.1 that answers with its own name and records what it received. */
private static final class Stub {
final String name;
final HttpServer server;
final List<Received> received = new CopyOnWriteArrayList<>();
final List<String> rawRequestTargets = new CopyOnWriteArrayList<>();
Stub(String name) throws IOException {
this.name = name;
this.server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
rawRequestTargets.add(exchange.getRequestURI().getRawPath());
received.add(new Received(exchange.getRequestMethod(), exchange.getRequestURI().getPath(),
exchange.getRequestURI().getRawQuery(), body,
exchange.getRequestHeaders().getFirst("X-Probe")));
byte[] reply = ("{\"stub\":\"" + name + "\"}").getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(200, reply.length);
exchange.getResponseBody().write(reply);
exchange.close();
});
server.start();
}
int port() {
return server.getAddress().getPort();
}
}
@BeforeAll
static void configureContentTypes() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static synchronized String namespaceId() {
if (namespaceId == null) {
String name = "apigw-" + shortId();
cloudMap("CreateHttpNamespace", "{\"Name\":\"" + name + "\"}").then().statusCode(200);
namespaceId = cloudMap("ListNamespaces", "{}").then().statusCode(200)
.extract().jsonPath().getString("Namespaces.find { it.Name == '" + name + "' }.Id");
}
return namespaceId;
}
@AfterEach
void cleanup() {
stubs.forEach(stub -> stub.server.stop(0));
stubs.clear();
apiIds.forEach(id -> given().when().delete("/v2/apis/" + id));
apiIds.clear();
vpcLinkIds.forEach(id -> given().when().delete("/v2/vpclinks/" + id));
vpcLinkIds.clear();
}
@Test
void requestReachesRegisteredInstanceWithMethodPathQueryBodyAndHeaders() throws IOException {
Stub stub = startStub("only");
String serviceId = createService(null);
register(serviceId, "i-1", stub, "");
String apiId = createApi(serviceArn(serviceId), "VPC_LINK", createVpcLink());
given().header("X-Probe", "probe-value").contentType(ContentType.TEXT).body("hello")
.when().post("/execute-api/" + apiId + "/$default/orders?tag=a&tag=b")
.then().statusCode(200).body("stub", equalTo("only"));
assertThat(stub.received, hasSize(1));
assertThat(stub.received.get(0), equalTo(
new Received("POST", "/orders", "tag=a&tag=b", "hello", "probe-value")));
}
@Test
void encodedPathAndTrailingSlashReachTheInstanceAsTheCallerSentThem() throws IOException {
Stub stub = startStub("raw");
String serviceId = createService(null);
register(serviceId, "i-1", stub, "");
String apiId = createApi(serviceArn(serviceId), "VPC_LINK", createVpcLink());
given().urlEncodingEnabled(false).when().get("/execute-api/" + apiId + "/$default/a%3Fb")
.then().statusCode(200);
given().urlEncodingEnabled(false).when().get("/execute-api/" + apiId + "/$default/x/")
.then().statusCode(200);
given().urlEncodingEnabled(false).when().get("/execute-api/" + apiId + "/$default/a%20b?k=v")
.then().statusCode(200);
assertThat(stub.rawRequestTargets, contains("/a%3Fb", "/x/", "/a%20b"));
assertThat(stub.received.get(0).query(), nullValue());
assertThat(stub.received.get(2).query(), equalTo("k=v"));
}
@Test
void namedStageStaysInThePathTheInstanceReceives() throws IOException {
Stub stub = startStub("staged");
String serviceId = createService(null);
register(serviceId, "i-1", stub, "");
String apiId = createApi(serviceArn(serviceId), "VPC_LINK", createVpcLink());
given().urlEncodingEnabled(false).when().get("/execute-api/" + apiId + "/prod/a%3Fb")
.then().statusCode(200);
given().urlEncodingEnabled(false).when().get("/execute-api/" + apiId + "/prod/x/")
.then().statusCode(200);
given().urlEncodingEnabled(false).when().get("/execute-api/" + apiId + "/prod/a%20b?k=v")
.then().statusCode(200);
assertThat(stub.rawRequestTargets, contains("/prod/a%3Fb", "/prod/x/", "/prod/a%20b"));
assertThat(stub.received.get(2).query(), equalTo("k=v"));
}
@Test
void defaultStageIsNotInThePathTheInstanceReceives() throws IOException {
Stub stub = startStub("unstaged");
String serviceId = createService(null);
register(serviceId, "i-1", stub, "");
String apiId = createApi(serviceArn(serviceId), "VPC_LINK", createVpcLink());
given().when().get("/execute-api/" + apiId + "/$default/orders").then().statusCode(200);
assertThat(stub.rawRequestTargets, contains("/orders"));
}
@Test
void serviceWithoutInstancesAnswers503() {
String serviceId = createService(null);
String apiId = createApi(serviceArn(serviceId), "VPC_LINK", createVpcLink());
given().when().get("/execute-api/" + apiId + "/$default/anything")
.then().statusCode(503).body("message", equalTo("Service Unavailable"));
}
@Test
void serviceOfOnlyUnroutableInstancesAnswers503() {
String serviceId = createService(null);
cloudMap("RegisterInstance", "{\"ServiceId\":\"" + serviceId + "\",\"InstanceId\":\"no-port\","
+ "\"Attributes\":{\"AWS_INSTANCE_IPV4\":\"127.0.0.1\"}}").then().statusCode(200);
String apiId = createApi(serviceArn(serviceId), "VPC_LINK", createVpcLink());
given().when().get("/execute-api/" + apiId + "/$default/anything").then().statusCode(503);
}
@Test
void requestsSpreadOverEveryRegisteredHealthyInstance() throws IOException {
Stub first = startStub("first");
Stub second = startStub("second");
String serviceId = createService("{\"FailureThreshold\":1}");
register(serviceId, "i-1", first, "");
register(serviceId, "i-2", second, "");
String apiId = createApi(serviceArn(serviceId), "VPC_LINK", createVpcLink());
List<String> answers = new ArrayList<>();
for (int i = 0; i < REQUESTS_PER_SPREAD_CHECK; i++) {
answers.add(given().when().get("/execute-api/" + apiId + "/$default/ping")
.then().statusCode(200).extract().path("stub"));
}
assertThat(first.received.size() + second.received.size(), equalTo(REQUESTS_PER_SPREAD_CHECK));
assertThat(answers.stream().distinct().toList(), containsInAnyOrder("first", "second"));
}
@Test
void arnQueryStringSelectsInstancesByAttribute() throws IOException {
Stub prod = startStub("prod");
Stub dev = startStub("dev");
String serviceId = createService(null);
register(serviceId, "i-prod", prod, ",\"stage\":\"prod\"");
register(serviceId, "i-dev", dev, ",\"stage\":\"dev\"");
String apiId = createApi(serviceArn(serviceId) + "?stage=prod", "VPC_LINK", createVpcLink());
for (int i = 0; i < 10; i++) {
given().when().get("/execute-api/" + apiId + "/$default/ping")
.then().statusCode(200).body("stub", equalTo("prod"));
}
assertThat(dev.received, hasSize(0));
}
@Test
void unknownCloudMapServiceAnswers502() {
String missingArn = "arn:aws:servicediscovery:us-east-1:000000000000:service/srv-doesnotexist";
String apiId = createApi(missingArn, "VPC_LINK", createVpcLink());
given().when().get("/execute-api/" + apiId + "/$default/anything")
.then().statusCode(502)
.body("message", equalTo("Bad Gateway: cannot resolve Cloud Map service: " + missingArn));
}
@Test
void unknownVpcLinkAnswers502BeforeAnyInstanceIsChosen() throws IOException {
Stub stub = startStub("untouched");
String serviceId = createService(null);
register(serviceId, "i-1", stub, "");
String apiId = createApi(serviceArn(serviceId), "VPC_LINK", "vpclink-missing");
given().when().get("/execute-api/" + apiId + "/$default/anything")
.then().statusCode(502)
.body("message", equalTo("Invalid VPC link identifier specified: vpclink-missing"));
assertThat(stub.received, hasSize(0));
}
@Test
void vpcLinkIntegrationWithoutConnectionIdAnswers500() {
String serviceId = createService(null);
String apiId = createApi(serviceArn(serviceId), "VPC_LINK", null);
given().when().get("/execute-api/" + apiId + "/$default/anything")
.then().statusCode(500)
.body("message", equalTo("VPC_LINK integration is missing a connectionId"));
}
@Test
void vpcLinkNotAvailableAnswers502BeforeAnyInstanceIsChosen() throws IOException {
Stub stub = startStub("untouched");
String serviceId = createService(null);
register(serviceId, "i-1", stub, "");
String vpcLinkId = createVpcLink();
apiGatewayV2Service.getVpcLink(REGION, vpcLinkId).setVpcLinkStatus("PENDING");
String apiId = createApi(serviceArn(serviceId), "VPC_LINK", vpcLinkId);
given().when().get("/execute-api/" + apiId + "/$default/anything")
.then().statusCode(502).body("message", equalTo("VPC link is not available: PENDING"));
assertThat(stub.received, hasSize(0));
}
@Test
void plainUrlOverUnknownVpcLinkStillProxies() throws IOException {
Stub stub = startStub("plain");
String apiId = createApi("http://127.0.0.1:" + stub.port() + "/x", "VPC_LINK", "vpclink-missing");
given().when().get("/execute-api/" + apiId + "/$default/anything")
.then().statusCode(200).body("stub", equalTo("plain"));
}
@Test
void cloudMapArnOverInternetConnectionIsNotResolvedThroughCloudMap() throws IOException {
Stub stub = startStub("untouched");
String serviceId = createService(null);
register(serviceId, "i-1", stub, "");
String apiId = createApi(serviceArn(serviceId), "INTERNET", null);
given().when().get("/execute-api/" + apiId + "/$default/anything")
.then().statusCode(502);
assertThat(stub.received, hasSize(0));
}
@Test
void cloudMapArnWithoutConnectionTypeIsNotResolvedThroughCloudMap() throws IOException {
Stub stub = startStub("untouched");
String serviceId = createService(null);
register(serviceId, "i-1", stub, "");
String apiId = createApi(serviceArn(serviceId), null, null);
given().when().get("/execute-api/" + apiId + "/$default/anything")
.then().statusCode(502);
assertThat(stub.received, hasSize(0));
}
@Test
void plainUrlWithoutVpcLinkStillProxies() throws IOException {
Stub stub = startStub("plain");
String apiId = createApi("http://127.0.0.1:" + stub.port() + "/x", null, null);
given().when().get("/execute-api/" + apiId + "/$default/anything")
.then().statusCode(200).body("stub", equalTo("plain"));
}
private Stub startStub(String name) throws IOException {
Stub stub = new Stub(name);
stubs.add(stub);
return stub;
}
private static Response cloudMap(String action, String body) {
return given().contentType(CLOUD_MAP_CONTENT_TYPE)
.header("X-Amz-Target", CLOUD_MAP_TARGET_PREFIX + action)
.body(body).when().post("/");
}
private static String shortId() {
return UUID.randomUUID().toString().substring(0, 8);
}
private static String createService(String healthCheckCustomConfig) {
String extra = healthCheckCustomConfig == null ? ""
: ",\"HealthCheckCustomConfig\":" + healthCheckCustomConfig;
return cloudMap("CreateService", "{\"Name\":\"svc-" + shortId() + "\",\"NamespaceId\":\""
+ namespaceId() + "\"" + extra + "}")
.then().statusCode(200).body("Service.Id", startsWith("srv-"))
.extract().jsonPath().getString("Service.Id");
}
private static String serviceArn(String serviceId) {
return cloudMap("GetService", "{\"Id\":\"" + serviceId + "\"}")
.then().statusCode(200).extract().jsonPath().getString("Service.Arn");
}
private static void register(String serviceId, String instanceId, Stub stub, String extraAttributes) {
cloudMap("RegisterInstance", "{\"ServiceId\":\"" + serviceId + "\",\"InstanceId\":\"" + instanceId
+ "\",\"Attributes\":{\"AWS_INSTANCE_IPV4\":\"127.0.0.1\",\"AWS_INSTANCE_PORT\":\""
+ stub.port() + "\"" + extraAttributes + "}}").then().statusCode(200);
}
private String createVpcLink() {
String id = given().contentType(ContentType.JSON)
.body("{\"name\":\"cm-link\",\"subnetIds\":[\"subnet-1\"],\"securityGroupIds\":[\"sg-1\"]}")
.when().post("/v2/vpclinks").then().statusCode(201).extract().path("vpcLinkId");
vpcLinkIds.add(id);
return id;
}
private String createApi(String integrationUri, String connectionType, String connectionId) {
String apiId = given().contentType(ContentType.JSON)
.body("{\"name\":\"cm-api\",\"protocolType\":\"HTTP\"}")
.when().post("/v2/apis").then().statusCode(201).extract().path("apiId");
apiIds.add(apiId);
String connection = (connectionType == null ? "" : ",\"connectionType\":\"" + connectionType + "\"")
+ (connectionId == null ? "" : ",\"connectionId\":\"" + connectionId + "\"");
String integrationId = given().contentType(ContentType.JSON)
.body("{\"integrationType\":\"HTTP_PROXY\",\"integrationUri\":\"" + integrationUri
+ "\",\"payloadFormatVersion\":\"1.0\",\"integrationMethod\":\"ANY\"" + connection + "}")
.when().post("/v2/apis/" + apiId + "/integrations")
.then().statusCode(201).extract().path("integrationId");
given().contentType(ContentType.JSON)
.body("{\"routeKey\":\"ANY /{proxy+}\",\"target\":\"integrations/" + integrationId + "\"}")
.when().post("/v2/apis/" + apiId + "/routes").then().statusCode(201);
return apiId;
}
}
@@ -0,0 +1,192 @@
package io.github.hectorvent.floci.services.apigatewayv2.proxy;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.apigatewayv2.proxy.CloudMapInstanceResolver.Endpoint;
import io.github.hectorvent.floci.services.cloudmap.CloudMapService;
import io.github.hectorvent.floci.services.cloudmap.model.Instance;
import io.github.hectorvent.floci.services.cloudmap.model.Service;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CloudMapInstanceResolverTest {
private static final String REGION = "us-east-1";
private static final String CUSTOM_HEALTH_CHECK = "{\"FailureThreshold\":1}";
private static final String HEALTH_CHECK_CONFIG = "{\"Type\":\"HTTP\"}";
@Inject
CloudMapService cloudMap;
@Inject
CloudMapInstanceResolver resolver;
private String createService(String healthCheckConfig, String healthCheckCustomConfig) {
String name = "resolver-" + UUID.randomUUID();
Service service = cloudMap.createService(name, null, null, null, null, healthCheckConfig,
healthCheckCustomConfig, null, null, REGION);
return service.getId();
}
private static String arnOf(String serviceId) {
return "arn:aws:servicediscovery:" + REGION + ":000000000000:service/" + serviceId;
}
private void register(String serviceId, String instanceId, Map<String, String> attributes) {
cloudMap.registerInstance(serviceId, instanceId, null, attributes, REGION);
}
// Floci has no API that marks an instance UNHEALTHY, so the test flips the stored instance directly
private void markUnhealthy(String serviceId, String instanceId) {
Instance instance = cloudMap.getInstance(serviceId, instanceId);
instance.setHealthStatus("UNHEALTHY");
assertEquals("UNHEALTHY", cloudMap.getInstance(serviceId, instanceId).getHealthStatus());
}
private static Map<String, String> address(String ip, String port) {
return Map.of("AWS_INSTANCE_IPV4", ip, "AWS_INSTANCE_PORT", port);
}
private static Map<String, String> address(String ip, String port, String stage, String deployment) {
return Map.of("AWS_INSTANCE_IPV4", ip, "AWS_INSTANCE_PORT", port, "stage", stage, "deployment", deployment);
}
private void assertEveryPickIs(Endpoint expected, String serviceArn) {
for (int i = 0; i < 50; i++) {
assertEquals(expected, resolver.pickInstance(serviceArn).orElseThrow());
}
}
private void assertUnhealthyInstanceIsNeverPicked(String serviceId) {
register(serviceId, "up", address("10.0.0.1", "8080"));
register(serviceId, "down", address("10.0.0.2", "8080"));
markUnhealthy(serviceId, "down");
assertEveryPickIs(new Endpoint("10.0.0.1", 8080), arnOf(serviceId));
}
@Test
void recognizesCloudMapServiceArnsOnly() {
String serviceArn = arnOf("srv-abc123");
assertTrue(CloudMapInstanceResolver.isServiceArn(serviceArn));
assertTrue(CloudMapInstanceResolver.isServiceArn(serviceArn + "?stage=prod&deployment=green"));
assertFalse(CloudMapInstanceResolver.isServiceArn(
"arn:aws:servicediscovery:us-east-1:000000000000:namespace/ns-abc"));
assertFalse(CloudMapInstanceResolver.isServiceArn(
"arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/lb/1/2"));
assertFalse(CloudMapInstanceResolver.isServiceArn("http://10.0.0.1:8080/"));
assertFalse(CloudMapInstanceResolver.isServiceArn(null));
}
@Test
void serviceWithACustomHealthCheckNeverPicksAnUnhealthyInstance() {
assertUnhealthyInstanceIsNeverPicked(createService(null, CUSTOM_HEALTH_CHECK));
}
@Test
void serviceWithAHealthCheckConfigNeverPicksAnUnhealthyInstance() {
assertUnhealthyInstanceIsNeverPicked(createService(HEALTH_CHECK_CONFIG, null));
}
@Test
void healthCheckedServiceWithOnlyUnhealthyInstancesHasNoCandidate() {
String serviceId = createService(null, CUSTOM_HEALTH_CHECK);
register(serviceId, "down", address("10.0.0.2", "8080"));
markUnhealthy(serviceId, "down");
assertEquals(Optional.empty(), resolver.pickInstance(arnOf(serviceId)));
}
@Test
void serviceWithoutHealthCheckPicksAnUnhealthyInstance() {
String serviceId = createService(null, null);
register(serviceId, "down", address("10.0.0.2", "8080"));
markUnhealthy(serviceId, "down");
assertEveryPickIs(new Endpoint("10.0.0.2", 8080), arnOf(serviceId));
}
@Test
void serviceWithNoInstanceHasNoCandidate() {
String serviceId = createService(null, CUSTOM_HEALTH_CHECK);
assertEquals(Optional.empty(), resolver.pickInstance(arnOf(serviceId)));
}
@Test
void picksAmongEveryRegisteredInstance() {
String serviceId = createService(null, null);
register(serviceId, "a", address("10.0.0.1", "8080"));
register(serviceId, "b", address("10.0.0.2", "8080"));
Set<Endpoint> picked = new HashSet<>();
for (int i = 0; i < 200; i++) {
picked.add(resolver.pickInstance(arnOf(serviceId)).orElseThrow());
}
assertEquals(Set.of(new Endpoint("10.0.0.1", 8080), new Endpoint("10.0.0.2", 8080)), picked);
}
@Test
void instanceWithoutAddressOrPortOrWithBadValuesIsNotACandidate() {
String serviceId = createService(null, null);
register(serviceId, "no-port", Map.of("AWS_INSTANCE_IPV4", "10.0.0.1"));
register(serviceId, "no-ip", Map.of("AWS_INSTANCE_PORT", "8080"));
register(serviceId, "not-an-ip", address("evil.example/@x", "8080"));
register(serviceId, "port-text", address("10.0.0.2", "http"));
register(serviceId, "port-range", address("10.0.0.3", "70000"));
register(serviceId, "port-zero", address("10.0.0.5", "0"));
register(serviceId, "good", address("10.0.0.4", "9090"));
assertEveryPickIs(new Endpoint("10.0.0.4", 9090), arnOf(serviceId));
}
@Test
void addressWithAnOctetAboveTheIpv4RangeIsNotACandidate() {
String serviceId = createService(null, null);
register(serviceId, "big-first", address("999.1.1.1", "8080"));
register(serviceId, "big-last", address("10.0.0.256", "8080"));
register(serviceId, "big-middle", address("10.300.0.1", "8080"));
register(serviceId, "edge", address("255.255.255.255", "9090"));
assertEveryPickIs(new Endpoint("255.255.255.255", 9090), arnOf(serviceId));
}
@Test
void arnQueryStringKeepsOnlyInstancesWithMatchingAttributes() {
String serviceId = createService(null, null);
register(serviceId, "prod-green", address("10.0.0.1", "8080", "prod", "green"));
register(serviceId, "prod-blue", address("10.0.0.2", "8080", "prod", "blue"));
register(serviceId, "dev-green", address("10.0.0.3", "8080", "dev", "green"));
assertEveryPickIs(new Endpoint("10.0.0.1", 8080), arnOf(serviceId) + "?stage=prod&deployment=green");
}
@Test
void arnQueryStringMatchingNoInstanceHasNoCandidate() {
String serviceId = createService(null, null);
register(serviceId, "dev", address("10.0.0.3", "8080", "dev", "green"));
assertEquals(Optional.empty(), resolver.pickInstance(arnOf(serviceId) + "?stage=prod"));
}
@Test
void missingCloudMapServicePropagatesNotFound() {
AwsException error = assertThrows(AwsException.class,
() -> resolver.pickInstance(arnOf("srv-doesnotexist")));
assertEquals("ServiceNotFound", error.getErrorCode());
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudmap;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
@@ -9,8 +10,13 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.ArrayList;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
@@ -137,10 +143,19 @@ class CloudMapIntegrationTest {
@Test
@Order(8)
void listOperationsFilteredByNamespace() {
call("ListOperations",
"{\"Filters\":[{\"Name\":\"NAMESPACE_ID\",\"Condition\":\"EQ\",\"Values\":[\"" + namespaceId + "\"]}]}")
.then().statusCode(200)
.body("Operations.find { it.Status == 'SUCCESS' }", notNullValue());
// AWS pages before it filters, so a match can sit behind an empty page when other tests made operations.
String filters = "\"Filters\":[{\"Name\":\"NAMESPACE_ID\",\"Condition\":\"EQ\",\"Values\":[\"" + namespaceId + "\"]}]";
List<String> statuses = new ArrayList<>();
String nextToken = null;
do {
String token = nextToken == null ? "" : ",\"NextToken\":\"" + nextToken + "\"";
JsonPath page = call("ListOperations", "{" + filters + token + "}")
.then().statusCode(200).extract().jsonPath();
statuses.addAll(page.getList("Operations.Status", String.class));
nextToken = page.getString("NextToken");
} while (nextToken != null);
assertThat(statuses, hasItem("SUCCESS"));
}
@Test
@@ -1,11 +1,13 @@
package io.github.hectorvent.floci.services.cloudmap;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudmap.model.Instance;
import io.github.hectorvent.floci.services.cloudmap.model.Service;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -100,6 +102,47 @@ class CloudMapServiceTest {
assertNull(cloudMapService.getService(service.getId()).getDnsConfig());
}
@Test
void filterInstancesKeepsOnlyInstancesWithEveryRequestedAttribute() {
Service service = createService(privateDnsNamespace(), "attrs", null, null);
register(service, "prod", Map.of("AWS_INSTANCE_IPV4", "10.0.0.1", "stage", "prod", "tier", "web"));
register(service, "dev", Map.of("AWS_INSTANCE_IPV4", "10.0.0.2", "stage", "dev", "tier", "web"));
assertEquals(List.of("prod"), instanceIds(cloudMapService.filterInstances(
service.getId(), "ALL", Map.of("stage", "prod", "tier", "web"))));
assertEquals(List.of(), cloudMapService.filterInstances(service.getId(), "ALL", Map.of("stage", "qa")));
assertEquals(2, cloudMapService.filterInstances(service.getId(), "ALL", Map.of()).size());
assertEquals(2, cloudMapService.filterInstances(service.getId(), null, null).size());
}
@Test
void filterInstancesAppliesTheHealthFilter() {
Service service = createService(privateDnsNamespace(), "health", null, null);
register(service, "up", Map.of("AWS_INSTANCE_IPV4", "10.0.0.1"));
register(service, "down", Map.of("AWS_INSTANCE_IPV4", "10.0.0.2"));
cloudMapService.getInstance(service.getId(), "down").setHealthStatus("UNHEALTHY");
assertEquals(List.of("up"), instanceIds(cloudMapService.filterInstances(service.getId(), "HEALTHY", Map.of())));
assertEquals(List.of("down"), instanceIds(cloudMapService.filterInstances(service.getId(), "UNHEALTHY", Map.of())));
assertEquals(2, cloudMapService.filterInstances(service.getId(), "ALL", Map.of()).size());
}
@Test
void filterInstancesRejectsAnUnknownService() {
AwsException error = assertThrows(AwsException.class,
() -> cloudMapService.filterInstances("srv-missing", "ALL", Map.of()));
assertEquals("ServiceNotFound", error.getErrorCode());
}
private void register(Service service, String instanceId, Map<String, String> attributes) {
cloudMapService.registerInstance(service.getId(), instanceId, null, attributes, REGION);
}
private static List<String> instanceIds(List<Instance> instances) {
return instances.stream().map(Instance::getInstanceId).sorted().toList();
}
private String privateDnsNamespace() {
String name = "svctest" + UUID.randomUUID().toString().substring(0, 8) + ".internal";
return cloudMapService.createPrivateDnsNamespace(name, "vpc-dns", null, null, Map.of(), REGION)