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
This commit is contained in:
Marvelous Ikponmwosa authored and GitHub committed 2026-05-20 18:00:30 -05:00
1 parent 0a8732b349
commit 5f4dd43b5a
10 files changed
+906 -4

No files matched your search

@@ -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<String, Object> 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<VpcLink> 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());
@@ -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<String, Object> 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<String, String> requestHeaders = new java.util.LinkedHashMap<>();
for (Map.Entry<String, List<String>> 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<Listener> 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;
@@ -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) {
@@ -30,6 +30,7 @@ public class ApiGatewayV2Service {
private final StorageBackend<String, RouteResponse> routeResponseStore;
private final StorageBackend<String, IntegrationResponse> integrationResponseStore;
private final StorageBackend<String, Model> modelStore;
private final StorageBackend<String, VpcLink> 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<String, String> requestParameters = (Map<String, String>) 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<String, String> requestParameters = (Map<String, String>) 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<String, Object> request) {
VpcLink link = new VpcLink();
link.setVpcLinkId(shortId(10));
link.setName((String) request.get("name"));
@SuppressWarnings("unchecked")
List<String> subnetIds = (List<String>) request.get("subnetIds");
link.setSubnetIds(subnetIds);
@SuppressWarnings("unchecked")
List<String> securityGroupIds = (List<String>) 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<String, String> tags = (Map<String, String>) 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<VpcLink> 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);
}
@@ -19,9 +19,26 @@ public class Integration {
private Map<String, String> responseTemplates;
private String templateSelectionExpression;
private Map<String, String> 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<String, String> getRequestParameters() { return requestParameters; }
public void setRequestParameters(Map<String, String> requestParameters) { this.requestParameters = requestParameters; }
public String getConnectionId() { return connectionId; }
public void setConnectionId(String connectionId) { this.connectionId = connectionId; }
}
@@ -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<String> subnetIds;
private List<String> securityGroupIds;
private String vpcLinkStatus; // PENDING, AVAILABLE, DELETING, FAILED, INACTIVE
private long createdDate;
private Map<String, String> 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<String> getSubnetIds() { return subnetIds; }
public void setSubnetIds(List<String> subnetIds) { this.subnetIds = subnetIds; }
public List<String> getSecurityGroupIds() { return securityGroupIds; }
public void setSecurityGroupIds(List<String> 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<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
}
@@ -41,7 +41,11 @@ public class HttpProxyInvoker {
private static final Set<String> 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();