Light, fluffy, and always free - The AWS Local Emulator alternative
feat(apigatewayv2): route VPC link integrations to Cloud Map service instances (#6753)
Liron Cohen4fffb5a8c18b
diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.mdindex e3bce9be6a..21cd3193ea 100644--- a/docs/services/api-gateway.md+++ b/docs/services/api-gateway.md@@ -796,6 +796,34 @@ Conditions can test `aws:SourceIp` (IPv4 and IPv6 CIDR ranges), `aws:SecureTranscaller-supplied `X-Forwarded-For` header does not override it. An empty `Condition`object places no condition on its statement, as in IAM.+### HTTP API private integrations++An `HTTP_PROXY` integration with `connectionType: VPC_LINK` reaches a private backend through a v2+VPC link. Floci has no real VPC, so the link only has to exist and be `AVAILABLE`. An unknown link+answers `502` with `Invalid VPC link identifier specified: <id>`, a link that is not `AVAILABLE`+answers `502`, and a missing `connectionId` answers `500`, the same as a REST (v1) VPC link+integration.++API Gateway includes the stage in the path it sends to the backend, so a request to the `prod`+stage arrives as `/prod/<route-path>`. The `$default` stage has no stage segment, so its requests+arrive as `/<route-path>`.++The `integrationUri` names the backend:++- An ALB or NLB listener ARN forwards through that listener.+- An AWS Cloud Map service ARN (`arn:aws:servicediscovery:<region>:<account>:service/srv-...`)+ forwards to one registered instance of the service. The instance must have the+ `AWS_INSTANCE_IPV4` and `AWS_INSTANCE_PORT` attributes, which ECS service discovery sets for each+ task. Floci picks one at random for each request, because `DiscoverInstances` returns a randomized+ list and API Gateway distributes requests across it. A service with a health check (`HealthCheckConfig`+ or `HealthCheckCustomConfig`) offers only `HEALTHY` instances. A service without one offers all+ instances. A query string on the ARN, such as `?stage=prod`, keeps only the instances that have+ those attribute values. A service with no usable instance answers `503` with+ `{"message":"Service Unavailable"}`, and a Cloud Map service that does not exist answers `502`.++The request path is forwarded as received. The stage name is not added to it, and `tlsConfig` is not+applied: the call to a Cloud Map instance uses plain HTTP.+### Supported Operations| Category | Operations |diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.javaindex 851ab77a84..f05c53acfc 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java@@ -43,6 +43,7 @@ import io.github.hectorvent.floci.services.apigatewayv2.JwtSignatureVerifier;import io.github.hectorvent.floci.services.apigatewayv2.model.Api;import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;import io.github.hectorvent.floci.services.apigatewayv2.model.Route;+import io.github.hectorvent.floci.services.apigatewayv2.proxy.CloudMapInstanceResolver;import io.github.hectorvent.floci.services.apigatewayv2.websocket.ConnectionInfo;import io.github.hectorvent.floci.services.apigatewayv2.websocket.WebSocketConnectionManager;import io.github.hectorvent.floci.services.elbv2.ElbV2Service;@@ -91,6 +92,8 @@ import java.util.regex.Pattern;import java.util.regex.PatternSyntaxException;import java.util.stream.Collectors;+// apigatewayv2.model.Integration (HTTP API) clashes with the imported REST Integration, so it is written in full.+/*** Executes API Gateway stage requests, routing them through the configured* integration (AWS_PROXY, AWS, HTTP_PROXY, HTTP or MOCK).@@ -107,6 +110,8 @@ public class ApiGatewayExecuteController {private static final Logger LOG = Logger.getLogger(ApiGatewayExecuteController.class);private static final TypeReference<Map<String, Object>> MAP_TYPE = new TypeReference<>() {};+ private static final String DEFAULT_STAGE = "$default";+ private static final int EXECUTE_API_PREFIX_SEGMENTS = 2;private static final Set<String> V2_TEXT_CONTENT_TYPES = Set.of(MediaType.TEXT_PLAIN,MediaType.TEXT_HTML,@@ -135,6 +140,7 @@ public class ApiGatewayExecuteController {private final ExecuteApiSigV4Authorizer sigV4Authorizer;private final RestLambdaAuthorizer restLambdaAuthorizer;private final AuthorizerPolicyEvaluator authorizerPolicyEvaluator;+ private final CloudMapInstanceResolver cloudMapInstanceResolver;@Injectpublic ApiGatewayExecuteController(ApiGatewayService apiGatewayService, CognitoUserPoolAuthorizer cognitoAuthorizer,@@ -149,7 +155,8 @@ public class ApiGatewayExecuteController {JwtSignatureVerifier jwtSignatureVerifier,RequestContext requestContext,ExecuteApiSigV4Authorizer sigV4Authorizer, RestLambdaAuthorizer restLambdaAuthorizer,- AuthorizerPolicyEvaluator authorizerPolicyEvaluator) {+ AuthorizerPolicyEvaluator authorizerPolicyEvaluator,+ CloudMapInstanceResolver cloudMapInstanceResolver) {this.apiGatewayService = apiGatewayService;this.cognitoAuthorizer = cognitoAuthorizer;this.apiGatewayV2Service = apiGatewayV2Service;@@ -171,6 +178,7 @@ public class ApiGatewayExecuteController {this.sigV4Authorizer = sigV4Authorizer;this.restLambdaAuthorizer = restLambdaAuthorizer;this.authorizerPolicyEvaluator = authorizerPolicyEvaluator;+ this.cloudMapInstanceResolver = cloudMapInstanceResolver;}/** Matches an ELBv2 listener ARN (ALB {@code app/} or NLB {@code net/}); group 1 = region. */@@ -791,27 +799,46 @@ public class ApiGatewayExecuteController {connectionId = scope.stage().getVariables().get(stageVariable.group(1));}}+ VpcLinkFailure failure = checkVpcLink(region, connectionId, true);+ if (failure == null) {+ return null;+ }+ if (failure.status() == 500) {+ return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500, failure.message());+ }+ return httpApiError(failure.status(), failure.message());+ }++ private record VpcLinkFailure(int status, String message) {+ }++ /**+ * The checks shared by the REST and HTTP API paths: the connection id is present, names an+ * existing link ({@code includeRestLinks} also searches the REST API VPC links), and the link is+ * {@code AVAILABLE}. Returns {@code null} when the request may proceed.+ */+ private VpcLinkFailure checkVpcLink(String region, String connectionId, boolean includeRestLinks) {if (connectionId == null || connectionId.isBlank()) {- return gatewayResponse(scope, GatewayResponseType.API_CONFIGURATION_ERROR, 500,- "VPC_LINK integration is missing a connectionId");+ return new VpcLinkFailure(500, "VPC_LINK integration is missing a connectionId");}- String status;- try {- status = apiGatewayService.getVpcLink(region, connectionId).getStatus();- } catch (AwsException e) {+ String status = null;+ if (includeRestLinks) {try {- status = apiGatewayV2Service.getVpcLink(region, connectionId).getVpcLinkStatus();+ status = apiGatewayService.getVpcLink(region, connectionId).getStatus();} catch (AwsException ignored) {+ // not a REST API VPC link: fall through to the HTTP API links+ }+ }+ if (status == null) {+ try {+ status = apiGatewayV2Service.getVpcLink(region, connectionId).getVpcLinkStatus();+ } catch (AwsException e) {LOG.warnv("VPC_LINK integration references unknown link {0} in {1}", connectionId, region);- return Response.status(502)- .entity(jsonMessage("Invalid VPC link identifier specified: " + connectionId))- .type(MediaType.APPLICATION_JSON).build();+ return new VpcLinkFailure(502, "Invalid VPC link identifier specified: " + connectionId);}}if (!"AVAILABLE".equalsIgnoreCase(status)) {- return Response.status(502)- .entity(jsonMessage("VPC link is not available: " + status))- .type(MediaType.APPLICATION_JSON).build();+ return new VpcLinkFailure(502, "VPC link is not available: " + status);}return null;}@@ -2837,7 +2864,7 @@ public class ApiGatewayExecuteController {if ("HTTP_PROXY".equalsIgnoreCase(integrationType)) {return dispatchHttpProxyV2(integration, route, httpMethod, path, headers, uriInfo, body,- apiId, stageName, jwtClaims);+ apiId, stageName, jwtClaims, region);}String functionName = functionNameFromUri(integration.getIntegrationUri());@@ -2890,7 +2917,8 @@ public class ApiGatewayExecuteController {private Response dispatchHttpProxyV2(io.github.hectorvent.floci.services.apigatewayv2.model.Integration integration,Route route, String httpMethod, String path,HttpHeaders headers, UriInfo uriInfo, byte[] body,- String apiId, String stageName, Map<String, String> jwtClaims) {+ String apiId, String stageName, Map<String, String> jwtClaims,+ String region) {// CDK HttpAlbIntegration sets integrationUri to an ALB listener ARN. Resolve it// to the listener's bound localhost port so HttpProxyInvoker (which assumes a// concrete http(s) URL) can forward through the listener's data plane.@@ -2907,9 +2935,31 @@ public class ApiGatewayExecuteController {.entity(jsonMessage("Bad Gateway: cannot resolve ALB listener: " + integrationUri)).type(MediaType.APPLICATION_JSON).build();}- String resolvedUrl = "http://127.0.0.1:" + listenerEndpoint.port() + path;+ String resolvedUrl = "http://127.0.0.1:" + listenerEndpoint.port() + proxyTargetPath(path, uriInfo, stageName);effective = withResolvedUriAndHost(integration, resolvedUrl, listenerEndpoint.host());LOG.debugv("ALB integration: listener {0} → {1}", integrationUri, resolvedUrl);+ } else if (isCloudMapIntegration(integration)) {+ Response vpcLinkError = validateVpcLinkV2(region, integration);+ if (vpcLinkError != null) {+ return vpcLinkError;+ }+ CloudMapInstanceResolver.Endpoint instance;+ try {+ instance = cloudMapInstanceResolver.pickInstance(integrationUri).orElse(null);+ } catch (AwsException e) {+ LOG.warnv("Cloud Map service unresolvable for v2 integration: {0}: {1}",+ integrationUri, e.getMessage());+ return Response.status(502)+ .entity(jsonMessage("Bad Gateway: cannot resolve Cloud Map service: " + integrationUri))+ .type(MediaType.APPLICATION_JSON).build();+ }+ if (instance == null) {+ LOG.debugv("Cloud Map service {0} has no healthy instance to route to", integrationUri);+ return httpApiError(503, "Service Unavailable");+ }+ String resolvedUrl = "http://" + instance.address() + ":" + instance.port() + proxyTargetPath(path, uriInfo, stageName);+ effective = withResolvedUri(integration, resolvedUrl);+ LOG.debugv("Cloud Map integration: {0} → {1}:{2}", integrationUri, instance.address(), instance.port());}}@@ -2973,6 +3023,22 @@ public class ApiGatewayExecuteController {return rb.build();}+ private static boolean isCloudMapIntegration(+ io.github.hectorvent.floci.services.apigatewayv2.model.Integration integration) {+ return "VPC_LINK".equalsIgnoreCase(integration.getConnectionType())+ && CloudMapInstanceResolver.isServiceArn(integration.getIntegrationUri());+ }++ /**+ * The HTTP API counterpart of {@link #validateVpcLink}: a {@code VPC_LINK} integration must name+ * a v2 VPC link that exists and is {@code AVAILABLE}, with the same statuses and messages.+ */+ private Response validateVpcLinkV2(String region,+ io.github.hectorvent.floci.services.apigatewayv2.model.Integration integration) {+ VpcLinkFailure failure = checkVpcLink(region, integration.getConnectionId(), false);+ return failure == null ? null : httpApiError(failure.status(), failure.message());+ }+/** Returns listener endpoint details, or null if the ARN is unknown or lookups fail. */private AlbListenerEndpoint resolveAlbListenerEndpoint(String region, String listenerArn) {try {@@ -4270,6 +4336,33 @@ public class ApiGatewayExecuteController {// ──────────────────────────── Path matching ────────────────────────────+ /**+ * The request path a private integration sends to its backend, as the caller encoded it. API Gateway keeps+ * the stage segment in it, except for {@code $default}, which has none.+ */+ static String rawTargetPath(String normalizedPath, String rawRequestPath, String stageName) {+ boolean defaultStage = DEFAULT_STAGE.equals(stageName);+ if (rawRequestPath != null) {+ int start = 0;+ int segments = EXECUTE_API_PREFIX_SEGMENTS + (defaultStage ? 1 : 0);+ for (int segment = 0; segment < segments && start >= 0; segment++) {+ start = rawRequestPath.indexOf('/', start + 1);+ }+ if (start >= 0) {+ return rawRequestPath.substring(start);+ }+ if (defaultStage && rawRequestPath.startsWith("/execute-api/")) {+ return "/";+ }+ }+ String path = preserveTrailingSlash(normalizedPath, rawRequestPath);+ return defaultStage ? path : "/" + stageName + path;+ }++ private static String proxyTargetPath(String normalizedPath, UriInfo uriInfo, String stageName) {+ return rawTargetPath(normalizedPath, uriInfo.getRequestUri().getRawPath(), stageName);+ }+/*** Re-appends a trailing slash that the JAX-RS {@code {proxy}} path-param binding strips.* A trailing slash is significant in the proxy event path (many routers treat {@code /x}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/CloudMapInstanceResolver.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/CloudMapInstanceResolver.javanew file mode 100644index 0000000000..dbb49453b7--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/CloudMapInstanceResolver.java@@ -0,0 +1,106 @@+package io.github.hectorvent.floci.services.apigatewayv2.proxy;++import io.github.hectorvent.floci.core.common.AwsArnUtils;+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 jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.net.URLDecoder;+import java.nio.charset.StandardCharsets;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.concurrent.ThreadLocalRandom;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++/**+ * Picks one instance of a Cloud Map service for an HTTP API private integration. The pick is random:+ * DiscoverInstances returns a randomized list (AWS Cloud Map API reference, DiscoverInstances).+ */+@ApplicationScoped+public class CloudMapInstanceResolver {++ // group 1 = service id, group 2 = optional attribute filter query+ static final Pattern CLOUD_MAP_SERVICE_ARN = Pattern.compile(+ "^arn:" + AwsArnUtils.PARTITION_REGEX + ":servicediscovery:[^:]+:[^:]*:service/([^/?]+)(?:\\?(.*))?$");++ private static final String ATTRIBUTE_IPV4 = "AWS_INSTANCE_IPV4";+ private static final String ATTRIBUTE_PORT = "AWS_INSTANCE_PORT";+ private static final String HEALTHY = "HEALTHY";+ private static final String ALL = "ALL";+ private static final Pattern IPV4 = Pattern.compile("^(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)$");+ private static final int MAX_PORT = 65_535;++ public record Endpoint(String address, int port) {}++ private final CloudMapService cloudMapService;++ @Inject+ public CloudMapInstanceResolver(CloudMapService cloudMapService) {+ this.cloudMapService = cloudMapService;+ }++ public static boolean isServiceArn(String integrationUri) {+ return integrationUri != null && CLOUD_MAP_SERVICE_ARN.matcher(integrationUri).matches();+ }++ public Optional<Endpoint> pickInstance(String serviceArn) {+ Matcher arn = CLOUD_MAP_SERVICE_ARN.matcher(serviceArn);+ if (!arn.matches()) {+ throw new IllegalArgumentException("Not a Cloud Map service ARN: " + serviceArn);+ }+ Service service = cloudMapService.getService(arn.group(1));+ // DiscoverInstances HealthStatus: a service without a health check reports none, so all instances count+ boolean healthChecked = isPresent(service.getHealthCheckConfig())+ || isPresent(service.getHealthCheckCustomConfig());+ String healthFilter = healthChecked ? HEALTHY : ALL;++ List<Endpoint> candidates = new ArrayList<>();+ for (Instance instance : cloudMapService.filterInstances(service.getId(), healthFilter, parseQuery(arn.group(2)))) {+ toEndpoint(instance.getAttributes() != null ? instance.getAttributes() : Map.of()).ifPresent(candidates::add);+ }+ if (candidates.isEmpty()) {+ return Optional.empty();+ }+ return Optional.of(candidates.get(ThreadLocalRandom.current().nextInt(candidates.size())));+ }++ private static Optional<Endpoint> toEndpoint(Map<String, String> attributes) {+ String address = attributes.get(ATTRIBUTE_IPV4);+ String portText = attributes.get(ATTRIBUTE_PORT);+ if (address == null || !IPV4.matcher(address).matches() || portText == null) {+ return Optional.empty();+ }+ try {+ int port = Integer.parseInt(portText);+ return port >= 1 && port <= MAX_PORT ? Optional.of(new Endpoint(address, port)) : Optional.empty();+ } catch (NumberFormatException e) {+ return Optional.empty();+ }+ }++ private static Map<String, String> parseQuery(String query) {+ Map<String, String> filters = new LinkedHashMap<>();+ if (query == null || query.isBlank()) {+ return filters;+ }+ for (String pair : query.split("&")) {+ int equals = pair.indexOf('=');+ if (equals <= 0) {+ continue;+ }+ filters.put(URLDecoder.decode(pair.substring(0, equals), StandardCharsets.UTF_8),+ URLDecoder.decode(pair.substring(equals + 1), StandardCharsets.UTF_8));+ }+ return filters;+ }++ private static boolean isPresent(String rawJson) {+ return rawJson != null && !rawJson.isBlank();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.javaindex a2348f5ab7..e3e8d2db81 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java@@ -394,18 +394,27 @@ public class CloudMapService {String healthFilter, Map<String, String> queryParameters,Integer maxResults, String region) {Service service = resolveService(namespaceName, serviceName, region);- List<Instance> all = scanInstances(service.getId());- List<Instance> filtered = applyHealthFilter(all, healthFilter);+ List<Instance> filtered = filterInstances(service.getId(), healthFilter, queryParameters);+ if (maxResults != null && maxResults > 0 && filtered.size() > maxResults) {+ filtered = filtered.subList(0, maxResults);+ }+ return new DiscoverResult(filtered, service.getRevision());+ }++ public List<Instance> filterInstances(String serviceId, String healthFilter,+ Map<String, String> queryParameters) {+ List<Instance> filtered = applyHealthFilter(listInstances(serviceId), healthFilter);if (queryParameters != null && !queryParameters.isEmpty()) {filtered = filtered.stream().filter(i -> queryParameters.entrySet().stream()- .allMatch(e -> e.getValue().equals(i.getAttributes().get(e.getKey()))))+ .allMatch(e -> e.getValue().equals(attributesOf(i).get(e.getKey())))).toList();}- if (maxResults != null && maxResults > 0 && filtered.size() > maxResults) {- filtered = filtered.subList(0, maxResults);- }- return new DiscoverResult(filtered, service.getRevision());+ return filtered;+ }++ private static Map<String, String> attributesOf(Instance instance) {+ return instance.getAttributes() != null ? instance.getAttributes() : Map.of();}public long discoverInstancesRevision(String namespaceName, String serviceName, String region) {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.javaindex 5e224bb80d..91957a1c1e 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java@@ -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);diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.javaindex 65bebbe1d8..24e513073a 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java@@ -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) {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2AuthorizerEventTrailingSlashTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2AuthorizerEventTrailingSlashTest.javaindex fa948c94dc..8138a6f867 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2AuthorizerEventTrailingSlashTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2AuthorizerEventTrailingSlashTest.java@@ -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 {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.javaindex 6d1f6ee7c6..6d478fb944 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventBodyEncodingTest.java@@ -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}")diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.javaindex 1d0f5a8ec0..7eff49cf60 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventJwtClaimsTest.java@@ -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);}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventLambdaAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventLambdaAuthorizerTest.javaindex 0f67ed306c..10df8081c4 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventLambdaAuthorizerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventLambdaAuthorizerTest.java@@ -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);}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventMultiValueTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventMultiValueTest.javaindex 361ceae765..c180821eec 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventMultiValueTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventMultiValueTest.java@@ -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 }diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.javaindex a69497a8bb..5bfa91854b 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventPathParametersTest.java@@ -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);}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventStageVariablesTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventStageVariablesTest.javaindex d64d5feed7..c53b0cb1ed 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventStageVariablesTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventStageVariablesTest.java@@ -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);}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventTrailingSlashTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventTrailingSlashTest.javaindex fcd94d0374..4f74d1a4ba 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventTrailingSlashTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/BuildV2ProxyEventTrailingSlashTest.java@@ -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 {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/HttpApiAuthorizerPolicyTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/HttpApiAuthorizerPolicyTest.javaindex b02b797ea0..8eeb49e6db 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/HttpApiAuthorizerPolicyTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/HttpApiAuthorizerPolicyTest.java@@ -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) {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.javaindex a4fefb2f6a..3e3d91ec29 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/JwtClaimsWireFormatTest.java@@ -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) {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.javaindex a6e7fc4e9e..deb9835507 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventIamIdentityTest.java@@ -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);}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventPathParametersTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventPathParametersTest.javaindex 6014c106ee..0bd6ab94a4 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventPathParametersTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventPathParametersTest.java@@ -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 {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/RawTargetPathTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/RawTargetPathTest.javanew file mode 100644index 0000000000..135d14cc38--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/RawTargetPathTest.java@@ -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"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.javaindex 8cda98fa20..b453d5cc21 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.java@@ -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() {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2CloudMapIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2CloudMapIntegrationTest.javanew file mode 100644index 0000000000..cb339c8b40--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2CloudMapIntegrationTest.java@@ -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;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/CloudMapInstanceResolverTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/CloudMapInstanceResolverTest.javanew file mode 100644index 0000000000..59b7838006--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/CloudMapInstanceResolverTest.java@@ -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());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapIntegrationTest.javaindex b488bd6482..107c292c2b 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapIntegrationTest.java@@ -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"));}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapServiceTest.javaindex 1870f0e7af..d345f61449 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapServiceTest.java@@ -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)