From 5f4dd43b5a821e43f388d2ac3d3e04ae516ade3e Mon Sep 17 00:00:00 2001 From: Marvelous Ikponmwosa <46595957+marvikomo@users.noreply.github.com> Date: Thu, 21 May 2026 00:00:30 +0100 Subject: [PATCH] feat(apigatewayv2): forward HTTP API requests through ALB listener (#941) * feat(apigatewayv2): forward HTTP API requests through ALB listener * implemented copilot feedbacks * refactor(apigatewayv2): apply maintainer feedback --- .../apigateway/ApiGatewayController.java | 69 ++++ .../ApiGatewayExecuteController.java | 67 +++- .../apigatewayv2/ApiGatewayV2JsonHandler.java | 1 + .../apigatewayv2/ApiGatewayV2Service.java | 57 +++ .../apigatewayv2/model/Integration.java | 20 + .../services/apigatewayv2/model/VpcLink.java | 43 +++ .../apigatewayv2/proxy/HttpProxyInvoker.java | 4 + .../apigateway/ApiGatewayProxyMatchTest.java | 65 +++- .../ApiGatewayV2AlbIntegrationTest.java | 353 ++++++++++++++++++ .../ApiGatewayV2VpcLinkRestTest.java | 231 ++++++++++++ 10 files changed, 906 insertions(+), 4 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/VpcLink.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2VpcLinkRestTest.java diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java index afb530f919..21476ee39a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.apigateway; import java.io.IOException; +import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -32,6 +33,7 @@ import io.github.hectorvent.floci.services.apigatewayv2.model.Model; import io.github.hectorvent.floci.services.apigatewayv2.model.Route; import io.github.hectorvent.floci.services.apigatewayv2.model.RouteResponse; import io.github.hectorvent.floci.services.apigatewayv2.model.Stage; +import io.github.hectorvent.floci.services.apigatewayv2.model.VpcLink; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; @@ -1028,6 +1030,49 @@ public class ApiGatewayController { } } + // ──────────────────────────── VPC Links (v2) ──────────────────────────── + + @POST + @Path("/v2/vpclinks") + public Response createVpcLink(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + try { + @SuppressWarnings("unchecked") + Map request = objectMapper.readValue(body, Map.class); + VpcLink link = v2Service.createVpcLink(region, request); + return Response.status(201).entity(toV2VpcLinkNode(link).toString()).type(MediaType.APPLICATION_JSON).build(); + } catch (IOException e) { + throw new AwsException("BadRequestException", e.getMessage(), 400); + } + } + + @GET + @Path("/v2/vpclinks") + public Response getVpcLinks(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + List links = v2Service.getVpcLinks(region); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("items"); + links.forEach(l -> items.add(toV2VpcLinkNode(l))); + return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build(); + } + + @GET + @Path("/v2/vpclinks/{vpcLinkId}") + public Response getVpcLink(@Context HttpHeaders headers, @PathParam("vpcLinkId") String vpcLinkId) { + String region = regionResolver.resolveRegion(headers); + return Response.ok(toV2VpcLinkNode(v2Service.getVpcLink(region, vpcLinkId)).toString()) + .type(MediaType.APPLICATION_JSON).build(); + } + + @DELETE + @Path("/v2/vpclinks/{vpcLinkId}") + public Response deleteVpcLink(@Context HttpHeaders headers, @PathParam("vpcLinkId") String vpcLinkId) { + String region = regionResolver.resolveRegion(headers); + v2Service.deleteVpcLink(region, vpcLinkId); + return Response.accepted().build(); + } + // ──────────────────────────── Route Responses (v2) ──────────────────────────── @POST @@ -1694,6 +1739,7 @@ public class ApiGatewayController { node.put("integrationId", i.getIntegrationId()); node.put("integrationType", i.getIntegrationType()); if (i.getConnectionType() != null) node.put("connectionType", i.getConnectionType()); + if (i.getConnectionId() != null) node.put("connectionId", i.getConnectionId()); node.put("payloadFormatVersion", i.getPayloadFormatVersion()); if (i.getIntegrationUri() != null) node.put("integrationUri", i.getIntegrationUri()); if (i.getRequestTemplates() != null) { @@ -1720,6 +1766,29 @@ public class ApiGatewayController { return node; } + private ObjectNode toV2VpcLinkNode(VpcLink v) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("vpcLinkId", v.getVpcLinkId()); + if (v.getName() != null) node.put("name", v.getName()); + if (v.getVpcLinkStatus() != null) node.put("vpcLinkStatus", v.getVpcLinkStatus()); + node.put("vpcLinkVersion", "V2"); + node.put("createdDate", Instant.ofEpochMilli(v.getCreatedDate()).toString()); + if (v.getSubnetIds() != null) { + ArrayNode subnets = node.putArray("subnetIds"); + v.getSubnetIds().forEach(subnets::add); + } + if (v.getSecurityGroupIds() != null) { + ArrayNode sgs = node.putArray("securityGroupIds"); + v.getSecurityGroupIds().forEach(sgs::add); + } + if (v.getTags() != null && !v.getTags().isEmpty()) { + ObjectNode tagsNode = objectMapper.createObjectNode(); + v.getTags().forEach(tagsNode::put); + node.set("tags", tagsNode); + } + return node; + } + private ObjectNode toV2StageNode(Stage s) { ObjectNode node = objectMapper.createObjectNode(); node.put("stageName", s.getStageName()); 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.java index 8396cf6055..8f8bb12b61 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 @@ -13,6 +13,8 @@ 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.websocket.ConnectionInfo; import io.github.hectorvent.floci.services.apigatewayv2.websocket.WebSocketConnectionManager; +import io.github.hectorvent.floci.services.elbv2.ElbV2Service; +import io.github.hectorvent.floci.services.elbv2.model.Listener; import io.github.hectorvent.floci.services.lambda.LambdaArnUtils; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.InvocationType; @@ -21,6 +23,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.smallrye.common.annotation.Blocking; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.*; @@ -64,13 +67,15 @@ public class ApiGatewayExecuteController { private final VtlTemplateEngine vtlEngine; private final AwsServiceRouter serviceRouter; private final WebSocketConnectionManager webSocketConnectionManager; + private final ElbV2Service elbV2Service; @Inject public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service, LambdaService lambdaService, RegionResolver regionResolver, ObjectMapper objectMapper, VtlTemplateEngine vtlEngine, AwsServiceRouter serviceRouter, - WebSocketConnectionManager webSocketConnectionManager) { + WebSocketConnectionManager webSocketConnectionManager, + ElbV2Service elbV2Service) { this.apiGatewayService = apiGatewayService; this.apiGatewayV2Service = apiGatewayV2Service; this.lambdaService = lambdaService; @@ -79,8 +84,13 @@ public class ApiGatewayExecuteController { this.vtlEngine = vtlEngine; this.serviceRouter = serviceRouter; this.webSocketConnectionManager = webSocketConnectionManager; + this.elbV2Service = elbV2Service; } + /** Matches an ELBv2 listener ARN (ALB {@code app/} or NLB {@code net/}); group 1 = region. */ + static final Pattern ELB_LISTENER_ARN = Pattern.compile( + "^arn:aws[^:]*:elasticloadbalancing:([^:]+):[^:]*:listener/(?:app|net)/.+$"); + private record AuthorizerResult(Response errorResponse, String principalId, Map context) {} // ──────────────────────────── @connections API ──────────────────────────── @@ -143,6 +153,7 @@ public class ApiGatewayExecuteController { } @GET + @Blocking @Path("/{proxy: .*}") public Response handleGet(@Context HttpHeaders headers, @Context UriInfo uriInfo, @PathParam("apiId") String apiId, @@ -156,6 +167,7 @@ public class ApiGatewayExecuteController { } @POST + @Blocking @Path("/{proxy: .*}") public Response handlePost(@Context HttpHeaders headers, @Context UriInfo uriInfo, @PathParam("apiId") String apiId, @@ -170,6 +182,7 @@ public class ApiGatewayExecuteController { } @PUT + @Blocking @Path("/{proxy: .*}") public Response handlePut(@Context HttpHeaders headers, @Context UriInfo uriInfo, @PathParam("apiId") String apiId, @@ -180,6 +193,7 @@ public class ApiGatewayExecuteController { } @DELETE + @Blocking @Path("/{proxy: .*}") public Response handleDelete(@Context HttpHeaders headers, @Context UriInfo uriInfo, @PathParam("apiId") String apiId, @@ -193,6 +207,7 @@ public class ApiGatewayExecuteController { } @PATCH + @Blocking @Path("/{proxy: .*}") public Response handlePatch(@Context HttpHeaders headers, @Context UriInfo uriInfo, @PathParam("apiId") String apiId, @@ -1024,6 +1039,31 @@ public class ApiGatewayExecuteController { Route route, String httpMethod, String path, HttpHeaders headers, UriInfo uriInfo, byte[] body, String apiId, String stageName) { + // 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. + io.github.hectorvent.floci.services.apigatewayv2.model.Integration effective = integration; + String integrationUri = integration.getIntegrationUri(); + if (integrationUri != null) { + Matcher m = ELB_LISTENER_ARN.matcher(integrationUri); + if (m.matches()) { + String albRegion = m.group(1); + Integer listenerPort = resolveAlbListenerPort(albRegion, integrationUri); + if (listenerPort == null) { + LOG.warnv("ALB listener ARN unresolvable for v2 integration: {0}", integrationUri); + return Response.status(502) + .entity(jsonMessage("Bad Gateway: cannot resolve ALB listener: " + integrationUri)) + .type(MediaType.APPLICATION_JSON).build(); + } + // Use 127.0.0.1 explicitly: ElbV2DataPlane binds the listener on 0.0.0.0 + // (IPv4-only). "localhost" resolves to ::1 first on IPv6-preferred systems, + // which would fail to connect. + String resolvedUrl = "http://127.0.0.1:" + listenerPort + path; + effective = withResolvedUri(integration, resolvedUrl); + LOG.debugv("ALB integration: listener {0} → {1}", integrationUri, resolvedUrl); + } + } + Map requestHeaders = new java.util.LinkedHashMap<>(); for (Map.Entry> e : headers.getRequestHeaders().entrySet()) { requestHeaders.put(e.getKey(), String.join(",", e.getValue())); @@ -1053,10 +1093,10 @@ public class ApiGatewayExecuteController { claims, Map.of()); LOG.debugv("execute-api v2: {0} {1}/{2}{3} → HTTP_PROXY {4}", - httpMethod, apiId, stageName, path, integration.getIntegrationUri()); + httpMethod, apiId, stageName, path, effective.getIntegrationUri()); io.github.hectorvent.floci.services.apigatewayv2.proxy.ProxyResult result = - httpProxyInvoker.invoke(integration, ctx); + httpProxyInvoker.invoke(effective, ctx); Response.ResponseBuilder rb = Response.status(result.statusCode()); if (result.body() != null) rb.entity(result.body()); @@ -1068,6 +1108,27 @@ public class ApiGatewayExecuteController { return rb.build(); } + /** Returns the listener's bound port, or null if the ARN is unknown or describeListeners throws. */ + private Integer resolveAlbListenerPort(String region, String listenerArn) { + try { + List matches = elbV2Service.describeListeners(region, null, List.of(listenerArn)); + if (matches.isEmpty()) return null; + return matches.get(0).getPort(); + } catch (Exception e) { + LOG.warnv("describeListeners failed for {0}: {1}", listenerArn, e.getMessage()); + return null; + } + } + + /** Shallow copy with {@code integrationUri} replaced; never mutate the stored Integration. */ + private static io.github.hectorvent.floci.services.apigatewayv2.model.Integration withResolvedUri( + io.github.hectorvent.floci.services.apigatewayv2.model.Integration original, String targetUri) { + io.github.hectorvent.floci.services.apigatewayv2.model.Integration copy = + new io.github.hectorvent.floci.services.apigatewayv2.model.Integration(original); + copy.setIntegrationUri(targetUri); + return copy; + } + private static String extractBearerToken(HttpHeaders headers) { String auth = headers.getHeaderString("Authorization"); if (auth == null) return null; diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java index 908df7d5c0..03c9ab5c4e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java @@ -589,6 +589,7 @@ public class ApiGatewayV2JsonHandler { node.put("IntegrationId", i.getIntegrationId()); node.put("IntegrationType", i.getIntegrationType()); if (i.getConnectionType() != null) node.put("ConnectionType", i.getConnectionType()); + if (i.getConnectionId() != null) node.put("ConnectionId", i.getConnectionId()); node.put("PayloadFormatVersion", i.getPayloadFormatVersion()); if (i.getIntegrationUri() != null) node.put("IntegrationUri", i.getIntegrationUri()); if (i.getRequestTemplates() != null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java index 5d2fafc20f..925115821e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java @@ -30,6 +30,7 @@ public class ApiGatewayV2Service { private final StorageBackend routeResponseStore; private final StorageBackend integrationResponseStore; private final StorageBackend modelStore; + private final StorageBackend vpcLinkStore; private final RegionResolver regionResolver; @Inject @@ -52,6 +53,8 @@ public class ApiGatewayV2Service { new TypeReference<>() {}); this.modelStore = storageFactory.create("apigatewayv2", "apigatewayv2-models.json", new TypeReference<>() {}); + this.vpcLinkStore = storageFactory.create("apigatewayv2", "apigatewayv2-vpclinks.json", + new TypeReference<>() {}); this.regionResolver = regionResolver; } @@ -418,6 +421,8 @@ public class ApiGatewayV2Service { Map requestParameters = (Map) request.get("requestParameters"); integration.setRequestParameters(requestParameters); + integration.setConnectionId((String) request.get("connectionId")); + integrationStore.put(integrationKey(region, apiId, integration.getIntegrationId()), integration); return integration; } @@ -477,6 +482,9 @@ public class ApiGatewayV2Service { Map requestParameters = (Map) request.get("requestParameters"); integration.setRequestParameters(requestParameters); } + if (request.containsKey("connectionId") && request.get("connectionId") != null) { + integration.setConnectionId((String) request.get("connectionId")); + } integrationStore.put(integrationKey(region, apiId, integrationId), integration); return integration; @@ -775,6 +783,51 @@ public class ApiGatewayV2Service { modelStore.delete(modelKey(region, apiId, modelId)); } + // ──────────────────────────── VPC Link CRUD ──────────────────────────── + + public VpcLink createVpcLink(String region, Map request) { + VpcLink link = new VpcLink(); + link.setVpcLinkId(shortId(10)); + link.setName((String) request.get("name")); + + @SuppressWarnings("unchecked") + List subnetIds = (List) request.get("subnetIds"); + link.setSubnetIds(subnetIds); + + @SuppressWarnings("unchecked") + List securityGroupIds = (List) request.get("securityGroupIds"); + link.setSecurityGroupIds(securityGroupIds); + + // Floci has no real VPC — provision the link as AVAILABLE immediately. + link.setVpcLinkStatus("AVAILABLE"); + link.setCreatedDate(System.currentTimeMillis()); + + @SuppressWarnings("unchecked") + Map tags = (Map) request.get("tags"); + if (tags != null) { + link.setTags(tags); + } + + vpcLinkStore.put(vpcLinkKey(region, link.getVpcLinkId()), link); + LOG.infov("Created VPC Link: {0} ({1}) in {2}", link.getName(), link.getVpcLinkId(), region); + return link; + } + + public VpcLink getVpcLink(String region, String vpcLinkId) { + return vpcLinkStore.get(vpcLinkKey(region, vpcLinkId)) + .orElseThrow(() -> new AwsException("NotFoundException", "VpcLink not found", 404)); + } + + public List getVpcLinks(String region) { + String prefix = region + "::"; + return vpcLinkStore.scan(k -> k.startsWith(prefix)); + } + + public void deleteVpcLink(String region, String vpcLinkId) { + getVpcLink(region, vpcLinkId); + vpcLinkStore.delete(vpcLinkKey(region, vpcLinkId)); + } + // ──────────────────────────── Standalone Tagging ──────────────────────────── /** @@ -875,6 +928,10 @@ public class ApiGatewayV2Service { return region + "::" + apiId + "::" + modelId; } + private String vpcLinkKey(String region, String vpcLinkId) { + return region + "::" + vpcLinkId; + } + private static String shortId(int length) { return UUID.randomUUID().toString().replace("-", "").substring(0, length); } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Integration.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Integration.java index 7c91c8dd3b..49d09d2964 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Integration.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Integration.java @@ -19,9 +19,26 @@ public class Integration { private Map responseTemplates; private String templateSelectionExpression; private Map requestParameters; + private String connectionId; public Integration() {} + /** Shallow copy. Add new fields here so callers like {@code withResolvedUri} keep them. */ + public Integration(Integration src) { + this.integrationId = src.integrationId; + this.integrationType = src.integrationType; + this.connectionType = src.connectionType; + this.integrationUri = src.integrationUri; + this.payloadFormatVersion = src.payloadFormatVersion; + this.integrationMethod = src.integrationMethod; + this.timeoutInMillis = src.timeoutInMillis; + this.requestTemplates = src.requestTemplates; + this.responseTemplates = src.responseTemplates; + this.templateSelectionExpression = src.templateSelectionExpression; + this.requestParameters = src.requestParameters; + this.connectionId = src.connectionId; + } + public String getIntegrationId() { return integrationId; } public void setIntegrationId(String integrationId) { this.integrationId = integrationId; } @@ -54,4 +71,7 @@ public class Integration { public Map getRequestParameters() { return requestParameters; } public void setRequestParameters(Map requestParameters) { this.requestParameters = requestParameters; } + + public String getConnectionId() { return connectionId; } + public void setConnectionId(String connectionId) { this.connectionId = connectionId; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/VpcLink.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/VpcLink.java new file mode 100644 index 0000000000..8d440b787d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/VpcLink.java @@ -0,0 +1,43 @@ +package io.github.hectorvent.floci.services.apigatewayv2.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; +import java.util.Map; + +/** API Gateway v2 VPC Link; Floci has no real VPC so it's provisioned AVAILABLE immediately. */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class VpcLink { + private String vpcLinkId; + private String name; + private List subnetIds; + private List securityGroupIds; + private String vpcLinkStatus; // PENDING, AVAILABLE, DELETING, FAILED, INACTIVE + private long createdDate; + private Map tags; + + public VpcLink() {} + + public String getVpcLinkId() { return vpcLinkId; } + public void setVpcLinkId(String vpcLinkId) { this.vpcLinkId = vpcLinkId; } + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public List getSubnetIds() { return subnetIds; } + public void setSubnetIds(List subnetIds) { this.subnetIds = subnetIds; } + + public List getSecurityGroupIds() { return securityGroupIds; } + public void setSecurityGroupIds(List securityGroupIds) { this.securityGroupIds = securityGroupIds; } + + public String getVpcLinkStatus() { return vpcLinkStatus; } + public void setVpcLinkStatus(String vpcLinkStatus) { this.vpcLinkStatus = vpcLinkStatus; } + + public long getCreatedDate() { return createdDate; } + public void setCreatedDate(long createdDate) { this.createdDate = createdDate; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java index 4061f364d0..62b8b5d765 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java @@ -41,7 +41,11 @@ public class HttpProxyInvoker { private static final Set RESTRICTED = Set.of( "connection", "content-length", "expect", "host", "upgrade"); + // Pin to HTTP/1.1: the default HTTP_2 setting attempts cleartext-HTTP/2 negotiation + // against http:// backends, which hangs against plain HTTP/1.1 servers (notably the + // in-JVM Vertx HttpServer used by ELBv2 listeners for HttpAlbIntegration). private final HttpClient client = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) .connectTimeout(Duration.ofSeconds(10)) .followRedirects(HttpClient.Redirect.NEVER) .build(); 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.java index 4420c9a35e..ee63729a10 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 @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigateway; import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource; import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; import io.github.hectorvent.floci.services.apigatewayv2.websocket.WebSocketConnectionManager; +import io.github.hectorvent.floci.services.elbv2.ElbV2Service; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.core.common.RegionResolver; import com.fasterxml.jackson.databind.ObjectMapper; @@ -13,6 +14,7 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.List; +import java.util.regex.Matcher; import static org.junit.jupiter.api.Assertions.*; @@ -25,6 +27,7 @@ class ApiGatewayProxyMatchTest { @Mock VtlTemplateEngine vtlEngine; @Mock AwsServiceRouter serviceRouter; @Mock WebSocketConnectionManager webSocketConnectionManager; + @Mock ElbV2Service elbV2Service; private ApiGatewayExecuteController ctrl; @@ -32,7 +35,7 @@ class ApiGatewayProxyMatchTest { void setUp() { ctrl = new ApiGatewayExecuteController(apiGatewayService, apiGatewayV2Service, lambdaService, new RegionResolver("us-east-1", "000000000000"), - new ObjectMapper(), vtlEngine, serviceRouter, webSocketConnectionManager); + new ObjectMapper(), vtlEngine, serviceRouter, webSocketConnectionManager, elbV2Service); } private ApiGatewayResource resource(String id, String parentId, String pathPart, String path) { @@ -124,4 +127,64 @@ class ApiGatewayProxyMatchTest { assertNull(ctrl.matchResource(List.of(authProxy), "/")); assertNull(ctrl.matchResource(List.of(authProxy), "/other/path")); } + + // ──────────────────────────── ELB_LISTENER_ARN ──────────────────────────── + + @Test + void elbListenerArnMatchesAlbAndExtractsRegion() { + Matcher m = ApiGatewayExecuteController.ELB_LISTENER_ARN.matcher( + "arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/my-lb/abcdef0123456789/0011223344556677"); + assertTrue(m.matches()); + assertEquals("us-east-1", m.group(1)); + } + + @Test + void elbListenerArnMatchesNlb() { + Matcher m = ApiGatewayExecuteController.ELB_LISTENER_ARN.matcher( + "arn:aws:elasticloadbalancing:us-west-2:000000000000:listener/net/my-nlb/abcdef0123456789/0011223344556677"); + assertTrue(m.matches()); + assertEquals("us-west-2", m.group(1)); + } + + @Test + void elbListenerArnMatchesGovAndChinaPartitions() { + assertTrue(ApiGatewayExecuteController.ELB_LISTENER_ARN.matcher( + "arn:aws-us-gov:elasticloadbalancing:us-gov-west-1:0:listener/app/lb/a/b").matches()); + assertTrue(ApiGatewayExecuteController.ELB_LISTENER_ARN.matcher( + "arn:aws-cn:elasticloadbalancing:cn-north-1:0:listener/net/lb/a/b").matches()); + } + + @Test + void elbListenerArnRejectsNonListenerElbArns() { + // LoadBalancer ARN, not a listener + assertFalse(ApiGatewayExecuteController.ELB_LISTENER_ARN.matcher( + "arn:aws:elasticloadbalancing:us-east-1:0:loadbalancer/app/my-lb/abc").matches()); + // Target group ARN + assertFalse(ApiGatewayExecuteController.ELB_LISTENER_ARN.matcher( + "arn:aws:elasticloadbalancing:us-east-1:0:targetgroup/my-tg/abc").matches()); + // Listener rule ARN + assertFalse(ApiGatewayExecuteController.ELB_LISTENER_ARN.matcher( + "arn:aws:elasticloadbalancing:us-east-1:0:listener-rule/app/lb/a/b/c").matches()); + } + + @Test + void elbListenerArnRejectsUnsupportedListenerSubtypes() { + // gateway / unknown lb subtypes — not yet supported by HttpAlbIntegration in CDK + assertFalse(ApiGatewayExecuteController.ELB_LISTENER_ARN.matcher( + "arn:aws:elasticloadbalancing:us-east-1:0:listener/gwy/lb/a/b").matches()); + assertFalse(ApiGatewayExecuteController.ELB_LISTENER_ARN.matcher( + "arn:aws:elasticloadbalancing:us-east-1:0:listener/unknown/lb/a/b").matches()); + } + + @Test + void elbListenerArnRejectsOtherServiceArns() { + // Lambda function ARN — what AWS_PROXY integrations use; must NOT trigger ELB resolution + assertFalse(ApiGatewayExecuteController.ELB_LISTENER_ARN.matcher( + "arn:aws:lambda:us-east-1:0:function:my-fn").matches()); + // Plain http URL — what regular HTTP_PROXY integrations use + assertFalse(ApiGatewayExecuteController.ELB_LISTENER_ARN.matcher( + "http://example.com/path").matches()); + // Empty / blank + assertFalse(ApiGatewayExecuteController.ELB_LISTENER_ARN.matcher("").matches()); + } } 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.java new file mode 100644 index 0000000000..347657e441 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2AlbIntegrationTest.java @@ -0,0 +1,353 @@ +package io.github.hectorvent.floci.services.apigatewayv2; + +import com.sun.net.httpserver.HttpServer; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +/** End-to-end: HTTP API → ALB listener ARN → ELBv2 data plane → registered stub target. */ +@QuarkusTest +@TestProfile(ApiGatewayV2AlbIntegrationTest.RealElbV2Profile.class) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiGatewayV2AlbIntegrationTest { + + /** Overrides the default {@code elbv2.mock=true} so the listener actually binds. */ + public static class RealElbV2Profile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.elbv2.mock", "false"); + } + } + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260520/us-east-1/elasticloadbalancing/aws4_request"; + + /** Fixed listener port. Distinct from {@code ElbV2LambdaTargetIntegrationTest} (7780). */ + private static final int LISTENER_PORT = 7792; + + private static HttpServer stub; + private static int stubPort; + + private static String lbArn; + private static String tgArn; + private static String listenerArn; + private static String vpcLinkId; + private static String apiId; + private static String integrationId; + + @BeforeAll + static void startStubBackend() throws IOException { + // Ephemeral-port HTTP stub that echoes the requested path. Acts as the + // "ECS container" sitting behind the ALB. + 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); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, body.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(body); + } + }); + stub.start(); + stubPort = stub.getAddress().getPort(); + } + + @AfterAll + static void stopStubBackend() { + if (stub != null) { + stub.stop(0); + } + } + + @Test + @Order(1) + void createLoadBalancer() { + lbArn = given() + .formParam("Action", "CreateLoadBalancer") + .formParam("Name", "apigw-alb-test") + .formParam("Type", "application") + .formParam("Scheme", "internet-facing") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .extract() + .path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn"); + } + + @Test + @Order(2) + void createTargetGroup() { + tgArn = given() + .formParam("Action", "CreateTargetGroup") + .formParam("Name", "apigw-alb-tg") + .formParam("Protocol", "HTTP") + .formParam("Port", String.valueOf(stubPort)) + .formParam("TargetType", "ip") + .formParam("HealthCheckPath", "/") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .extract() + .path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn"); + } + + @Test + @Order(3) + void registerStubAsTarget() { + given() + .formParam("Action", "RegisterTargets") + .formParam("TargetGroupArn", tgArn) + .formParam("Targets.member.1.Id", "127.0.0.1") + .formParam("Targets.member.1.Port", String.valueOf(stubPort)) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(4) + void createListenerOnFixedPort() { + listenerArn = given() + .formParam("Action", "CreateListener") + .formParam("LoadBalancerArn", lbArn) + .formParam("Protocol", "HTTP") + .formParam("Port", String.valueOf(LISTENER_PORT)) + .formParam("DefaultActions.member.1.Type", "forward") + .formParam("DefaultActions.member.1.TargetGroupArn", tgArn) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .extract() + .path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn"); + } + + @Test + @Order(5) + void createVpcLink() { + vpcLinkId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"alb-vpc-link","subnetIds":["subnet-1"],"securityGroupIds":["sg-1"]} + """) + .when().post("/v2/vpclinks") + .then() + .statusCode(201) + .extract().path("vpcLinkId"); + } + + @Test + @Order(6) + void createHttpApi() { + apiId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"alb-test-api","protocolType":"HTTP"} + """) + .when().post("/v2/apis") + .then() + .statusCode(201) + .extract().path("apiId"); + } + + @Test + @Order(7) + void createAlbIntegration() { + integrationId = given() + .contentType(ContentType.JSON) + .body(""" + {"integrationType":"HTTP_PROXY", + "integrationUri":"%s", + "connectionType":"VPC_LINK", + "connectionId":"%s", + "payloadFormatVersion":"1.0", + "integrationMethod":"ANY"} + """.formatted(listenerArn, vpcLinkId)) + .when().post("/v2/apis/" + apiId + "/integrations") + .then() + .statusCode(201) + .body("integrationUri", equalTo(listenerArn)) + .body("connectionType", equalTo("VPC_LINK")) + .extract().path("integrationId"); + } + + @Test + @Order(8) + void createHealthRoute() { + given() + .contentType(ContentType.JSON) + .body(""" + {"routeKey":"GET /health","target":"integrations/%s"} + """.formatted(integrationId)) + .when().post("/v2/apis/" + apiId + "/routes") + .then() + .statusCode(201); + } + + @Test + @Order(9) + void httpProxyToStubDirectlyWorksThroughDispatch() { + // Baseline: bypass the ALB chain and prove the v2 HTTP_PROXY dispatch path + // works when integrationUri is a plain http://127.0.0.1 URL. If this hangs, + // it's a pre-existing pipeline issue independent of the ALB resolver. + // PATCH the integration to bypass the listener, GET execute-api, then PATCH it back. + given() + .contentType(ContentType.JSON) + .body(""" + {"integrationUri":"http://127.0.0.1:%d/probe"} + """.formatted(stubPort)) + .when().patch("/v2/apis/" + apiId + "/integrations/" + integrationId) + .then() + .statusCode(200); + + given() + .when().get("/execute-api/" + apiId + "/$default/health") + .then() + .statusCode(200) + .body("status", equalTo("ok")); + + // Restore the listener-ARN integrationUri for the ALB tests that follow. + given() + .contentType(ContentType.JSON) + .body(""" + {"integrationUri":"%s"} + """.formatted(listenerArn)) + .when().patch("/v2/apis/" + apiId + "/integrations/" + integrationId) + .then() + .statusCode(200); + } + + @Test + @Order(10) + void listenerForwardsDirectlyToStub() throws Exception { + // Verifies the ALB data plane independently of the API Gateway path: hit the + // listener directly. Polls because server.listen() is async — if the listener + // never accepts a connection we get a fast ConnectException and retry. + HttpClient client = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(2)) + .build(); + HttpRequest req = HttpRequest.newBuilder() + .uri(URI.create("http://127.0.0.1:" + LISTENER_PORT + "/health")) + .timeout(Duration.ofSeconds(3)) + .GET() + .build(); + long deadline = System.currentTimeMillis() + 15_000; + Exception lastErr = null; + while (System.currentTimeMillis() < deadline) { + try { + HttpResponse resp = client.send(req, HttpResponse.BodyHandlers.ofString()); + if (resp.statusCode() == 200 && resp.body().contains("\"status\":\"ok\"")) { + return; + } + lastErr = new IllegalStateException("status=" + resp.statusCode() + " body=" + resp.body()); + } catch (Exception e) { + lastErr = e; + } + Thread.sleep(250); + } + Assertions.fail("listener direct probe never succeeded: " + lastErr); + } + + /** Full HttpAlbIntegration happy path: execute-api → ALB resolver → listener → stub returns 200. */ + @Test + @Order(11) + void executeApiReachesStubViaAlb() { + // Now go through the actual HttpAlbIntegration path: dispatchHttpProxyV2 must + // detect the listener ARN, resolve it to the bound port, and forward to it. + Response last = null; + long deadline = System.currentTimeMillis() + 15_000; + while (System.currentTimeMillis() < deadline) { + last = given().when().get("/execute-api/" + apiId + "/$default/health"); + if (last.statusCode() == 200) { + last.then() + .body("status", equalTo("ok")) + .body("path", equalTo("/health")); + return; + } + try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } + } + Assertions.fail("execute-api → ALB → stub never returned 200; last status=" + + (last != null ? last.statusCode() : "n/a") + + " body=" + (last != null ? last.body().asString() : "n/a")); + } + + @Test + @Order(12) + void unresolvableListenerArnReturns502() { + // Replace the integrationUri with a listener ARN that doesn't exist. + // The ALB resolver must return a clean 502, not crash. + String ghostArn = "arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/ghost-lb/0000000000000000/0000000000000000"; + given() + .contentType(ContentType.JSON) + .body(""" + {"integrationUri":"%s"} + """.formatted(ghostArn)) + .when().patch("/v2/apis/" + apiId + "/integrations/" + integrationId) + .then() + .statusCode(200); + + given() + .when().get("/execute-api/" + apiId + "/$default/health") + .then() + .statusCode(502); + } + + @Test + @Order(90) + void cleanup() { + if (integrationId != null) { + given().when().delete("/v2/apis/" + apiId + "/integrations/" + integrationId); + } + if (apiId != null) { + given().when().delete("/v2/apis/" + apiId); + } + if (vpcLinkId != null) { + given().when().delete("/v2/vpclinks/" + vpcLinkId); + } + if (listenerArn != null) { + given() + .formParam("Action", "DeleteListener") + .formParam("ListenerArn", listenerArn) + .header("Authorization", AUTH) + .when().post("/"); + } + if (lbArn != null) { + given() + .formParam("Action", "DeleteLoadBalancer") + .formParam("LoadBalancerArn", lbArn) + .header("Authorization", AUTH) + .when().post("/"); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2VpcLinkRestTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2VpcLinkRestTest.java new file mode 100644 index 0000000000..7b19f32a2c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2VpcLinkRestTest.java @@ -0,0 +1,231 @@ +package io.github.hectorvent.floci.services.apigatewayv2; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; + +/** REST tests for {@code /v2/vpclinks} CRUD + Integration {@code connectionId} round-trip. */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiGatewayV2VpcLinkRestTest { + + private static String vpcLinkId; + private static String apiId; + private static String integrationId; + + @BeforeAll + static void configureRestAssured() { + // Register encoder for application/x-amz-json-1.1 so the JSON 1.1 round-trip + // below can post a raw body string. + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + @Order(1) + void createVpcLink() { + vpcLinkId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"my-vpc-link", + "subnetIds":["subnet-aaaa1111","subnet-bbbb2222"], + "securityGroupIds":["sg-cccc3333"], + "tags":{"Env":"test"}} + """) + .when().post("/v2/vpclinks") + .then() + .statusCode(201) + .body("vpcLinkId", notNullValue()) + .body("name", equalTo("my-vpc-link")) + .body("vpcLinkStatus", equalTo("AVAILABLE")) + .body("vpcLinkVersion", equalTo("V2")) + .body("subnetIds", hasItems("subnet-aaaa1111", "subnet-bbbb2222")) + .body("securityGroupIds", hasItem("sg-cccc3333")) + .body("tags.Env", equalTo("test")) + .extract().path("vpcLinkId"); + } + + @Test + @Order(2) + void getVpcLink() { + given() + .when().get("/v2/vpclinks/" + vpcLinkId) + .then() + .statusCode(200) + .body("vpcLinkId", equalTo(vpcLinkId)) + .body("name", equalTo("my-vpc-link")); + } + + @Test + @Order(3) + void listVpcLinksIncludesCreated() { + given() + .when().get("/v2/vpclinks") + .then() + .statusCode(200) + .body("items.vpcLinkId", hasItem(vpcLinkId)); + } + + @Test + @Order(4) + void getNonexistentVpcLinkReturns404() { + given() + .when().get("/v2/vpclinks/does-not-exist") + .then() + .statusCode(404); + } + + @Test + @Order(10) + void createApi() { + apiId = given() + .contentType(ContentType.JSON) + .body(""" + {"name":"vpc-link-api","protocolType":"HTTP"} + """) + .when().post("/v2/apis") + .then() + .statusCode(201) + .extract().path("apiId"); + } + + @Test + @Order(11) + void createIntegrationWithVpcLinkEchoesConnectionFields() { + // VPC_LINK + connectionId pointing at our VpcLink + listener-ARN integrationUri: + // CreateIntegration must persist + echo connectionType, connectionId, integrationUri. + integrationId = given() + .contentType(ContentType.JSON) + .body(""" + {"integrationType":"HTTP_PROXY", + "integrationUri":"arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/my-lb/abcdef0123456789/0011223344556677", + "connectionType":"VPC_LINK", + "connectionId":"%s", + "payloadFormatVersion":"1.0", + "integrationMethod":"ANY"} + """.formatted(vpcLinkId)) + .when().post("/v2/apis/" + apiId + "/integrations") + .then() + .statusCode(201) + .body("integrationId", notNullValue()) + .body("integrationType", equalTo("HTTP_PROXY")) + .body("connectionType", equalTo("VPC_LINK")) + .body("connectionId", equalTo(vpcLinkId)) + .body("integrationUri", containsString("listener/app/my-lb")) + .extract().path("integrationId"); + } + + @Test + @Order(12) + void getIntegrationStillEchoesConnectionId() { + given() + .when().get("/v2/apis/" + apiId + "/integrations/" + integrationId) + .then() + .statusCode(200) + .body("connectionType", equalTo("VPC_LINK")) + .body("connectionId", equalTo(vpcLinkId)); + } + + @Test + @Order(13) + void updateIntegrationPreservesConnectionId() { + // PATCH unrelated field; connectionType + connectionId must survive merge-patch. + given() + .contentType(ContentType.JSON) + .body(""" + {"integrationMethod":"GET"} + """) + .when().patch("/v2/apis/" + apiId + "/integrations/" + integrationId) + .then() + .statusCode(200) + .body("integrationMethod", equalTo("GET")) + .body("connectionType", equalTo("VPC_LINK")) + .body("connectionId", equalTo(vpcLinkId)); + } + + @Test + @Order(14) + void connectionIdRoundTripsViaJson11() { + // Mirrors IntegrationConnectionTypeAndAuthorizerSimpleResponsesTest#connectionTypeReturnedViaJson11 + // to make sure the JSON 1.1 (X-Amz-Target) response path also emits ConnectionId. + String amzJson = "application/x-amz-json-1.1"; + String authHeader = "AWS4-HMAC-SHA256 Credential=test/20260520/us-east-1/apigateway/aws4_request"; + String targetPrefix = "AmazonApiGatewayV2."; + + String localApiId = given() + .contentType(amzJson) + .header("X-Amz-Target", targetPrefix + "CreateApi") + .header("Authorization", authHeader) + .body(""" + {"Name":"conn-id-json11","ProtocolType":"HTTP"} + """) + .when().post("/") + .then().statusCode(201) + .extract().path("ApiId"); + + String localIntegrationId = given() + .contentType(amzJson) + .header("X-Amz-Target", targetPrefix + "CreateIntegration") + .header("Authorization", authHeader) + .body(""" + {"ApiId":"%s","IntegrationType":"HTTP_PROXY","IntegrationUri":"https://example.com","IntegrationMethod":"GET","ConnectionType":"VPC_LINK","ConnectionId":"%s","PayloadFormatVersion":"1.0"} + """.formatted(localApiId, vpcLinkId)) + .when().post("/") + .then().statusCode(201) + .body("ConnectionType", equalTo("VPC_LINK")) + .body("ConnectionId", equalTo(vpcLinkId)) + .extract().path("IntegrationId"); + + given() + .contentType(amzJson) + .header("X-Amz-Target", targetPrefix + "GetIntegration") + .header("Authorization", authHeader) + .body(""" + {"ApiId":"%s","IntegrationId":"%s"} + """.formatted(localApiId, localIntegrationId)) + .when().post("/") + .then().statusCode(200) + .body("ConnectionId", equalTo(vpcLinkId)); + + // cleanup the locally-scoped api so it doesn't leak into the next test + given().when().delete("/v2/apis/" + localApiId).then().statusCode(anyOf(equalTo(204), equalTo(404))); + } + + @Test + @Order(20) + void deleteVpcLink() { + given() + .when().delete("/v2/vpclinks/" + vpcLinkId) + .then() + .statusCode(202); + } + + @Test + @Order(21) + void getDeletedVpcLinkReturns404() { + given() + .when().get("/v2/vpclinks/" + vpcLinkId) + .then() + .statusCode(404); + } + + @Test + @Order(99) + void cleanup() { + if (integrationId != null) { + given().when().delete("/v2/apis/" + apiId + "/integrations/" + integrationId) + .then().statusCode(anyOf(equalTo(204), equalTo(404))); + } + if (apiId != null) { + given().when().delete("/v2/apis/" + apiId) + .then().statusCode(anyOf(equalTo(204), equalTo(404))); + } + } +}