feat(apigateway): support HTTP and HTTP_PROXY integrations on REST APIs (#3433)

* feat(apigateway): support HTTP and HTTP_PROXY integrations on REST APIs

PutIntegration already accepted type HTTP_PROXY and HTTP, but dispatch handled
only AWS_PROXY, AWS and MOCK and fell through to a 500 "Unsupported integration
type". A REST API fronting an HTTP microservice - the shape CDK's HttpIntegration
and addProxy emit - could be created but never invoked.

HTTP_PROXY is a passthrough: the request goes to the integration URI with {param}
placeholders resolved from the matched resource's path parameters, and the
backend's status, headers and body are relayed unchanged. AWS applies neither
request templates nor integration-response selection to HTTP_PROXY, so a backend
4xx or 5xx reaches the caller verbatim rather than being remapped into a gateway
error. An unreachable backend yields 502.

HTTP is the non-proxy form and transforms in both directions. The request body is
the rendered requestTemplates entry chosen by the incoming Content-Type, and only
headers and query parameters named by integration.request.* mappings are
forwarded - unmapped inbound headers are deliberately not passed through, which
is what separates it from HTTP_PROXY. The backend's reply then runs through the
method's integration responses, where selectionPattern is matched against the
backend's HTTP status code rather than against an error message as it is for
AWS/Lambda integrations.

Both reuse the existing v2 HttpProxyInvoker for transport, so hop-by-hop header
stripping, chunked decoding and the 502-on-failure behaviour are shared. The
request-template negotiation and integration-response mapping that AWS
integrations already performed are extracted so both types use one implementation.

* fix(apigateway): preserve repeated headers and query parameters through HTTP_PROXY

A REST HTTP_PROXY integration passes the request through, and AWS supports
multi-valued headers and query strings on that path. The adapter collapsed both
into one comma-joined value before handing the request to the shared transport,
so "?tag=a&tag=b" reached the backend as "tag=a,b" and a header sent twice
arrived once. Those are not interchangeable: most servers parse the joined form
as a single value containing a comma.

The relayed response had the same defect. A backend returning two Set-Cookie
headers produced one joined header, which the client cannot split back apart,
since an Expires attribute contains a comma of its own.

The transport already stored headers and query parameters as multimaps
internally; only its boundary types flattened them. RequestContext now carries a
multi-valued view alongside the single-valued one that $request.* expressions
resolve against, ProxyResult returns multi-valued headers, and the REST proxy
path emits one header line per value. An explicit integration.request.* mapping
still overwrites, replacing repeated inbound values with the mapped one.

Non-proxy HTTP is unchanged: its integration responses resolve
integration.response.header.X to a single value, so it collapses the backend's
headers at that point instead.

* fix(apigateway): preserve repeated parameters through HTTP API HTTP_PROXY too

dispatchHttpProxyV2 is the second entry point into the HttpProxyInvoker /
RequestContext / ProxyResult transport, and it still built its request context
from comma-joined single-value maps. So after the REST path was fixed, an HTTP
API (v2) with an HTTP_PROXY integration still sent "?tag=a,b" for "?tag=a&tag=b",
and repeated request headers still arrived joined: the transport's multi-value
support was there but never populated from here.

It now builds the same two views the REST path does. The multi-value maps are
what reaches the backend, and the joined single-value maps stay the lookup
surface for $request.header.X / $request.querystring.X, which resolve to one
value in AWS. The response relay already iterated multi-valued headers, so
repeated Set-Cookie was already correct on this path; it is pinned by a test
now rather than left implicit.

Also drops ProxyResult.firstHeader(), which nothing called, puts braces on the
conditionals in RequestContext.expand(), and imports LinkedHashMap in
ApiGatewayExecuteController instead of spelling it out in full at each use.
This commit is contained in:
Abhigya authored and GitHub committed 2026-09-13 18:06:04 -04:00
1 parent f38a384e51
commit 96707f6d5a
9 files changed
+1311 -96

No files matched your search

@@ -0,0 +1,324 @@
package io.github.hectorvent.floci.services.apigateway;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterAll;
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.concurrent.atomic.AtomicReference;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Covers the REST (v1) {@code HTTP} integration type, the non-proxy form, where API Gateway builds
* the backend request from mapping templates and explicit parameter mappings, then maps the
* backend's response back through the method's integration responses.
*
* <p>This is the counterpart to {@link ApiGatewayHttpProxyIntegrationTest}: {@code HTTP_PROXY} is a
* passthrough, whereas {@code HTTP} transforms in both directions. The distinguishing AWS behaviours
* pinned here are (a) unmapped inbound headers are <em>not</em> forwarded, and (b) an integration
* response's {@code selectionPattern} is matched against the backend's <em>HTTP status code</em>,
* not against an error message as it is for {@code AWS}/Lambda integrations.
*/
@QuarkusTest
class ApiGatewayHttpNonProxyIntegrationTest {
private static HttpServer backendServer;
private static int backendPort;
private static final AtomicReference<String> lastBody = new AtomicReference<>();
private static final AtomicReference<String> lastQuery = new AtomicReference<>();
private static final AtomicReference<String> lastTenantHeader = new AtomicReference<>();
private static final AtomicReference<String> lastUnmappedHeader = new AtomicReference<>();
private static final AtomicReference<String> lastMethod = new AtomicReference<>();
private static final AtomicReference<String> lastContentType = new AtomicReference<>();
private final List<String> createdApis = new ArrayList<>();
@BeforeAll
static void startBackend() throws IOException {
backendServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
backendServer.createContext("/", ApiGatewayHttpNonProxyIntegrationTest::handle);
backendServer.start();
backendPort = backendServer.getAddress().getPort();
}
@AfterAll
static void stopBackend() {
if (backendServer != null) backendServer.stop(0);
}
private static void handle(HttpExchange exchange) throws IOException {
lastMethod.set(exchange.getRequestMethod());
lastBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
lastQuery.set(exchange.getRequestURI().getQuery());
lastTenantHeader.set(exchange.getRequestHeaders().getFirst("X-Tenant"));
lastUnmappedHeader.set(exchange.getRequestHeaders().getFirst("X-Client-Trace"));
lastContentType.set(exchange.getRequestHeaders().getFirst("Content-Type"));
String query = exchange.getRequestURI().getQuery();
String mode = query == null ? "" : query;
int status = mode.contains("mode=missing") ? 404 : mode.contains("mode=boom") ? 500 : 200;
byte[] response = ("{\"backendStatus\":" + status + ",\"widget\":\"cog\"}")
.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.getResponseHeaders().add("X-Backend-Id", "backend-7");
exchange.sendResponseHeaders(status, response.length);
exchange.getResponseBody().write(response);
exchange.close();
}
private void resetRecordings() {
lastBody.set(null);
lastQuery.set(null);
lastTenantHeader.set(null);
lastUnmappedHeader.set(null);
lastMethod.set(null);
lastContentType.set(null);
}
/**
* Creates a REST API with a POST {@code /widget} method backed by an HTTP (non-proxy)
* integration, wiring request/response templates, parameter mappings and integration responses.
*/
private String createHttpApi(String name, String integrationExtras, boolean withIntegrationResponses) {
String apiId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"" + name + "\"}")
.when().post("/restapis")
.then().statusCode(201).body("id", notNullValue())
.extract().path("id");
createdApis.add(apiId);
String rootId = given().when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item[0].id");
String resourceId = given()
.contentType(ContentType.JSON)
.body("{\"pathPart\":\"widget\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201).extract().path("id");
given().contentType(ContentType.JSON)
.body("{\"authorizationType\":\"NONE\"}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST")
.then().statusCode(201);
String backendUrl = "http://127.0.0.1:" + backendPort + "/widget";
given().contentType(ContentType.JSON)
.body("{\"type\":\"HTTP\",\"httpMethod\":\"POST\",\"uri\":\"" + backendUrl + "\""
+ integrationExtras + "}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST/integration")
.then().statusCode(201);
if (withIntegrationResponses) {
// Default (empty selectionPattern) → 200.
given().contentType(ContentType.JSON)
.body("{\"selectionPattern\":\"\"}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId
+ "/methods/POST/integration/responses/200")
.then().statusCode(201);
// Backend 404 → method 404.
given().contentType(ContentType.JSON)
.body("{\"selectionPattern\":\"404\"}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId
+ "/methods/POST/integration/responses/404")
.then().statusCode(201);
// Any backend 5xx → method 502.
given().contentType(ContentType.JSON)
.body("{\"selectionPattern\":\"5\\\\d{2}\"}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId
+ "/methods/POST/integration/responses/502")
.then().statusCode(201);
}
String deploymentId = given().contentType(ContentType.JSON)
.body("{\"description\":\"v1\"}")
.when().post("/restapis/" + apiId + "/deployments")
.then().statusCode(201).extract().path("id");
given().contentType(ContentType.JSON)
.body("{\"stageName\":\"test\",\"deploymentId\":\"" + deploymentId + "\"}")
.when().post("/restapis/" + apiId + "/stages")
.then().statusCode(201);
return apiId;
}
@AfterEach
void cleanup() {
for (String apiId : createdApis) {
given().when().delete("/restapis/" + apiId).then().statusCode(202);
}
createdApis.clear();
}
@Test
void rendersRequestTemplateBeforeSendingToTheBackend() {
resetRecordings();
String apiId = createHttpApi("http-nonproxy-reqtemplate",
",\"requestTemplates\":{\"application/json\":"
+ "\"{\\\"wrapped\\\":$input.json('$.value')}\"}", false);
given().contentType(ContentType.JSON).body("{\"value\":42}")
.when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200);
assertEquals("POST", lastMethod.get());
assertEquals("{\"wrapped\":42}", lastBody.get());
}
@Test
void forwardsOnlyExplicitlyMappedHeadersAndQueryParameters() {
resetRecordings();
String apiId = createHttpApi("http-nonproxy-params",
",\"requestParameters\":{"
+ "\"integration.request.header.X-Tenant\":\"method.request.querystring.tenant\","
+ "\"integration.request.querystring.mode\":\"method.request.querystring.mode\"}", false);
given().contentType(ContentType.JSON).body("{}")
.header("X-Client-Trace", "should-not-be-forwarded")
.when().post("/execute-api/" + apiId + "/test/widget?tenant=acme&mode=ok")
.then().statusCode(200);
assertEquals("acme", lastTenantHeader.get());
assertEquals("mode=ok", lastQuery.get());
// A non-proxy HTTP integration builds its request from mappings alone; inbound headers that
// were not mapped must not leak to the backend (that passthrough is HTTP_PROXY's job).
assertNull(lastUnmappedHeader.get(),
"unmapped inbound header leaked to backend: " + lastUnmappedHeader.get());
}
@Test
void selectionPatternMatchesTheBackendStatusCode() {
resetRecordings();
String apiId = createHttpApi("http-nonproxy-selection",
",\"requestParameters\":{"
+ "\"integration.request.querystring.mode\":\"method.request.querystring.mode\"}", true);
// Backend 200 → default integration response → 200
given().contentType(ContentType.JSON).body("{}")
.when().post("/execute-api/" + apiId + "/test/widget?mode=ok")
.then().statusCode(200);
// Backend 404 → selectionPattern "404" → 404
given().contentType(ContentType.JSON).body("{}")
.when().post("/execute-api/" + apiId + "/test/widget?mode=missing")
.then().statusCode(404);
// Backend 500 → selectionPattern "5\d{2}" → remapped to 502
given().contentType(ContentType.JSON).body("{}")
.when().post("/execute-api/" + apiId + "/test/widget?mode=boom")
.then().statusCode(502);
}
@Test
void appliesResponseTemplateToTheBackendBody() {
resetRecordings();
String apiId = createHttpApi("http-nonproxy-resptemplate", "", false);
String resourceId = given().when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item.find { it.pathPart == 'widget' }.id");
given().contentType(ContentType.JSON)
.body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":"
+ "\"{\\\"renamed\\\":$input.json('$.widget')}\"}}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId
+ "/methods/POST/integration/responses/200")
.then().statusCode(201);
given().contentType(ContentType.JSON).body("{}")
.when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200)
.body("renamed", equalTo("cog"));
}
@Test
void mapsBackendResponseHeaderToMethodResponseHeader() {
resetRecordings();
String apiId = createHttpApi("http-nonproxy-respparams", "", false);
String resourceId = given().when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item.find { it.pathPart == 'widget' }.id");
given().contentType(ContentType.JSON)
.body("{\"selectionPattern\":\"\",\"responseParameters\":"
+ "{\"method.response.header.X-Out\":\"integration.response.header.X-Backend-Id\"}}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId
+ "/methods/POST/integration/responses/200")
.then().statusCode(201);
given().contentType(ContentType.JSON).body("{}")
.when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200)
.header("X-Out", "backend-7");
}
@Test
void passthroughNeverRejectsAnUnmatchedContentType() {
resetRecordings();
String apiId = createHttpApi("http-nonproxy-passthrough",
",\"passthroughBehavior\":\"NEVER\","
+ "\"requestTemplates\":{\"application/xml\":\"<x/>\"}", false);
given().contentType(ContentType.JSON).body("{}")
.when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(415);
}
@Test
void tellsTheBackendTheMediaTypeOfTheTemplateItRendered() {
resetRecordings();
// The template is keyed under text/plain, so the rendered payload is text/plain: the
// backend must be told that, not the JSON default.
String apiId = createHttpApi("http-nonproxy-contenttype",
",\"requestTemplates\":{\"text/plain\":\"rendered-as-plain\"}", false);
given().contentType("text/plain").body("ignored")
.when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200);
assertEquals("rendered-as-plain", lastBody.get());
assertEquals("text/plain", lastContentType.get());
}
@Test
void selectsTheTemplateByBaseTypeWhenTheRequestCarriesACharset() {
resetRecordings();
String apiId = createHttpApi("http-nonproxy-charset",
",\"requestTemplates\":{\"application/json\":"
+ "\"{\\\"wrapped\\\":$input.json('$.value')}\"}", false);
given().contentType("application/json; charset=utf-8").body("{\"value\":7}")
.when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(200);
assertEquals("{\"wrapped\":7}", lastBody.get());
assertEquals("application/json", lastContentType.get());
}
@Test
void relaysBackendStatusWhenNoIntegrationResponsesAreConfigured() {
resetRecordings();
String apiId = createHttpApi("http-nonproxy-nointegresp",
",\"requestParameters\":{"
+ "\"integration.request.querystring.mode\":\"method.request.querystring.mode\"}", false);
given().contentType(ContentType.JSON).body("{}")
.when().post("/execute-api/" + apiId + "/test/widget?mode=missing")
.then().statusCode(404);
}
}
@@ -0,0 +1,330 @@
package io.github.hectorvent.floci.services.apigateway;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterAll;
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.net.ServerSocket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Covers the REST (v1) {@code HTTP_PROXY} integration type: API Gateway forwards the request to an
* arbitrary HTTP backend and relays the backend's response verbatim, with no VTL mapping and no
* integration-response selection (AWS applies neither to {@code HTTP_PROXY}).
*
* <p>{@code putIntegration} already accepted {@code "type":"HTTP_PROXY"}, but dispatch handled only
* {@code AWS_PROXY}/{@code AWS}/{@code MOCK} and fell through to a 500 "Unsupported integration
* type": so a REST API fronting an HTTP microservice, the shape CDK's
* {@code HttpIntegration}/{@code addProxy} emits, could be created but never invoked.
*/
@QuarkusTest
class ApiGatewayHttpProxyIntegrationTest {
private static HttpServer backendServer;
private static int backendPort;
/** A port nothing is listening on, for the connection-failure case. */
private static int deadPort;
private static final AtomicReference<String> lastMethod = new AtomicReference<>();
private static final AtomicReference<String> lastPath = new AtomicReference<>();
private static final AtomicReference<String> lastQuery = new AtomicReference<>();
private static final AtomicReference<String> lastBody = new AtomicReference<>();
private static final AtomicReference<String> lastForwardedHeader = new AtomicReference<>();
private static final AtomicReference<String> lastAuthorization = new AtomicReference<>();
private static final AtomicReference<String> lastHost = new AtomicReference<>();
private static final AtomicReference<List<String>> lastTraceHeaders = new AtomicReference<>();
private final List<String> createdApis = new ArrayList<>();
@BeforeAll
static void startBackend() throws IOException {
backendServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
backendServer.createContext("/", ApiGatewayHttpProxyIntegrationTest::handle);
backendServer.start();
backendPort = backendServer.getAddress().getPort();
try (ServerSocket probe = new ServerSocket(0)) {
deadPort = probe.getLocalPort();
}
}
@AfterAll
static void stopBackend() {
if (backendServer != null) backendServer.stop(0);
}
private static void handle(HttpExchange exchange) throws IOException {
lastMethod.set(exchange.getRequestMethod());
lastPath.set(exchange.getRequestURI().getPath());
lastQuery.set(exchange.getRequestURI().getQuery());
lastBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
lastForwardedHeader.set(exchange.getRequestHeaders().getFirst("X-Forwarded-Tenant"));
lastAuthorization.set(exchange.getRequestHeaders().getFirst("Authorization"));
lastHost.set(exchange.getRequestHeaders().getFirst("Host"));
List<String> trace = exchange.getRequestHeaders().get("X-Trace");
lastTraceHeaders.set(trace == null ? null : List.copyOf(trace));
// /missing exercises relaying a backend error status untouched.
int status = exchange.getRequestURI().getPath().endsWith("/missing") ? 404 : 200;
byte[] response = ("{\"from\":\"backend\",\"path\":\"" + exchange.getRequestURI().getPath() + "\"}")
.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.getResponseHeaders().add("X-Backend-Marker", "hit");
// Two separate Set-Cookie lines, the canonical repeated response header. The Expires
// attribute carries its own comma, so a comma-joined relay cannot be split back apart.
exchange.getResponseHeaders().add("Set-Cookie",
"session=abc; Path=/; Expires=Wed, 21 Oct 2026 07:28:00 GMT");
exchange.getResponseHeaders().add("Set-Cookie", "tracking=xyz; Path=/");
exchange.sendResponseHeaders(status, response.length);
exchange.getResponseBody().write(response);
exchange.close();
}
private void resetRecordings() {
lastMethod.set(null);
lastPath.set(null);
lastQuery.set(null);
lastBody.set(null);
lastForwardedHeader.set(null);
lastAuthorization.set(null);
lastHost.set(null);
lastTraceHeaders.set(null);
}
/**
* Creates a REST API with a greedy {@code /{proxy+}} resource whose ANY method is an
* HTTP_PROXY integration pointing at {@code targetUri}, deployed to stage {@code test}.
*/
private String createProxyApi(String name, String targetUri, String requestParametersJson) {
String apiId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"" + name + "\"}")
.when().post("/restapis")
.then().statusCode(201).body("id", notNullValue())
.extract().path("id");
createdApis.add(apiId);
String rootId = given().when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200).extract().path("item[0].id");
String resourceId = given()
.contentType(ContentType.JSON)
.body("{\"pathPart\":\"{proxy+}\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201).extract().path("id");
given().contentType(ContentType.JSON)
.body("{\"authorizationType\":\"NONE\"}")
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/ANY")
.then().statusCode(201);
String integrationBody = "{\"type\":\"HTTP_PROXY\",\"httpMethod\":\"ANY\",\"uri\":\"" + targetUri + "\""
+ (requestParametersJson == null ? "" : ",\"requestParameters\":" + requestParametersJson)
+ "}";
given().contentType(ContentType.JSON)
.body(integrationBody)
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/ANY/integration")
.then().statusCode(201);
String deploymentId = given().contentType(ContentType.JSON)
.body("{\"description\":\"v1\"}")
.when().post("/restapis/" + apiId + "/deployments")
.then().statusCode(201).extract().path("id");
given().contentType(ContentType.JSON)
.body("{\"stageName\":\"test\",\"deploymentId\":\"" + deploymentId + "\"}")
.when().post("/restapis/" + apiId + "/stages")
.then().statusCode(201);
return apiId;
}
private String backendUri() {
return "http://127.0.0.1:" + backendPort + "/{proxy}";
}
@AfterEach
void cleanup() {
for (String apiId : createdApis) {
given().when().delete("/restapis/" + apiId).then().statusCode(202);
}
createdApis.clear();
}
@Test
void forwardsPathAndQueryToTheBackendAndRelaysItsResponse() {
resetRecordings();
String apiId = createProxyApi("http-proxy-get-api", backendUri(), null);
given()
.when().get("/execute-api/" + apiId + "/test/orders/42?limit=5")
.then().statusCode(200)
.header("X-Backend-Marker", "hit")
.body("from", org.hamcrest.Matchers.equalTo("backend"));
assertEquals("GET", lastMethod.get());
assertEquals("/orders/42", lastPath.get());
assertEquals("limit=5", lastQuery.get());
}
@Test
void forwardsRequestBodyOnPost() {
resetRecordings();
String apiId = createProxyApi("http-proxy-post-api", backendUri(), null);
given()
.contentType(ContentType.JSON)
.body("{\"symbol\":\"ACME\"}")
.when().post("/execute-api/" + apiId + "/test/orders")
.then().statusCode(200);
assertEquals("POST", lastMethod.get());
assertEquals("/orders", lastPath.get());
assertEquals("{\"symbol\":\"ACME\"}", lastBody.get());
}
@Test
void relaysBackendErrorStatusVerbatim() {
resetRecordings();
String apiId = createProxyApi("http-proxy-error-api", backendUri(), null);
// HTTP_PROXY performs no integration-response selection, so a backend 404 must reach the
// caller as a 404 carrying the backend's own body, not be remapped to a gateway error.
given()
.when().get("/execute-api/" + apiId + "/test/orders/missing")
.then().statusCode(404)
.body("from", org.hamcrest.Matchers.equalTo("backend"));
}
@Test
void unreachableBackendYields502() {
String apiId = createProxyApi("http-proxy-dead-api", "http://127.0.0.1:" + deadPort + "/{proxy}", null);
given()
.when().get("/execute-api/" + apiId + "/test/anything")
.then().statusCode(502);
}
@Test
void appliesIntegrationRequestParameterMappingToOutgoingHeaders() {
resetRecordings();
String apiId = createProxyApi("http-proxy-params-api", backendUri(),
"{\"integration.request.header.X-Forwarded-Tenant\":\"method.request.querystring.tenant\"}");
given()
.when().get("/execute-api/" + apiId + "/test/orders?tenant=acme")
.then().statusCode(200);
assertEquals("acme", lastForwardedHeader.get());
}
@Test
void forwardsAuthorizationHeaderUnchangedOnNoneAuthRoute() {
resetRecordings();
String apiId = createProxyApi("http-proxy-auth-passthrough-api", backendUri(), null);
// A NONE-auth route must not have SigV4 applied to it; the caller's Authorization header is
// the backend's to interpret and has to arrive byte-for-byte.
given()
.header("Authorization", "Bearer caller-supplied-token")
.when().get("/execute-api/" + apiId + "/test/orders")
.then().statusCode(200);
assertEquals("Bearer caller-supplied-token", lastAuthorization.get());
}
@Test
void doesNotForwardTheInboundHostHeaderToTheBackend() {
resetRecordings();
String apiId = createProxyApi("http-proxy-host-api", backendUri(), null);
given()
.when().get("/execute-api/" + apiId + "/test/orders")
.then().statusCode(200);
// Host is hop-by-hop for this proxy: the backend must see its own authority, not the
// gateway's, or virtual-hosted backends route the request to the wrong vhost.
assertTrue(lastHost.get() != null && lastHost.get().contains(String.valueOf(backendPort)),
"backend should see its own Host authority, saw: " + lastHost.get());
}
@Test
void repeatedQueryParametersReachTheBackendSeparately() {
resetRecordings();
String apiId = createProxyApi("http-proxy-multi-query-api", backendUri(), null);
given()
.when().get("/execute-api/" + apiId + "/test/orders?tag=a&tag=b&limit=5")
.then().statusCode(200);
// AWS documents HTTP_PROXY as passing the request through, and multi-valued query strings
// are explicitly supported. Collapsing these to "tag=a,b" is a different request: most
// frameworks parse it as one value containing a comma, not as two values.
//
// Asserted per parameter rather than on the whole query string: the relative order of two
// differently named parameters is not part of the contract and is not stable across runs.
// The order of repeated values for one name is, and is checked.
Map<String, List<String>> received = parseQuery(lastQuery.get());
assertEquals(List.of("a", "b"), received.get("tag"));
assertEquals(List.of("5"), received.get("limit"));
}
/** Query string to name → values, preserving the order values appear in for a given name. */
private static Map<String, List<String>> parseQuery(String query) {
Map<String, List<String>> parsed = new LinkedHashMap<>();
if (query == null || query.isEmpty()) return parsed;
for (String pair : query.split("&")) {
int eq = pair.indexOf('=');
String name = eq < 0 ? pair : pair.substring(0, eq);
String value = eq < 0 ? "" : pair.substring(eq + 1);
parsed.computeIfAbsent(name, k -> new ArrayList<>()).add(value);
}
return parsed;
}
@Test
void repeatedRequestHeadersReachTheBackendSeparately() {
resetRecordings();
String apiId = createProxyApi("http-proxy-multi-header-api", backendUri(), null);
given()
.header("X-Trace", "first")
.header("X-Trace", "second")
.when().get("/execute-api/" + apiId + "/test/orders")
.then().statusCode(200);
assertEquals(List.of("first", "second"), lastTraceHeaders.get());
}
@Test
void repeatedResponseHeadersRelayToTheCallerSeparately() {
resetRecordings();
String apiId = createProxyApi("http-proxy-multi-response-header-api", backendUri(), null);
List<String> cookies = given()
.when().get("/execute-api/" + apiId + "/test/orders")
.then().statusCode(200)
.extract().headers().getValues("Set-Cookie");
assertEquals(2, cookies.size(), "expected both Set-Cookie headers, got: " + cookies);
assertTrue(cookies.contains("session=abc; Path=/; Expires=Wed, 21 Oct 2026 07:28:00 GMT"),
"session cookie should relay with its Expires comma intact, got: " + cookies);
assertTrue(cookies.contains("tracking=xyz; Path=/"), "got: " + cookies);
}
}
@@ -0,0 +1,178 @@
package io.github.hectorvent.floci.services.apigatewayv2;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterAll;
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.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The HTTP API (v2) counterpart of the REST multi-value coverage in
* {@code ApiGatewayHttpProxyIntegrationTest}: {@code dispatchHttpProxyV2} is a second entry point
* into the same {@code HttpProxyInvoker} / {@code RequestContext} / {@code ProxyResult} transport,
* and it built its request context from comma-joined single-value maps. So an HTTP API with an
* HTTP_PROXY integration still sent {@code ?tag=a,b} for {@code ?tag=a&tag=b} after the REST path
* was fixed, because the transport's multi-value support was never populated from here.
*
* <p>AWS documents HTTP_PROXY as passing the request through, with multi-valued headers and query
* strings explicitly supported, so the two shapes are not interchangeable: most servers parse
* {@code tag=a,b} as one value containing a comma rather than as two values.
*/
@QuarkusTest
class HttpApiHttpProxyMultiValueIntegrationTest {
private static HttpServer backendServer;
private static int backendPort;
private static final AtomicReference<String> lastQuery = new AtomicReference<>();
private static final AtomicReference<List<String>> lastTraceHeaders = new AtomicReference<>();
@BeforeAll
static void startBackend() throws IOException {
backendServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
backendServer.createContext("/", HttpApiHttpProxyMultiValueIntegrationTest::handle);
backendServer.start();
backendPort = backendServer.getAddress().getPort();
}
@AfterAll
static void stopBackend() {
if (backendServer != null) {
backendServer.stop(0);
}
}
private static void handle(HttpExchange exchange) throws IOException {
lastQuery.set(exchange.getRequestURI().getQuery());
List<String> trace = exchange.getRequestHeaders().get("X-Trace");
lastTraceHeaders.set(trace == null ? null : List.copyOf(trace));
byte[] response = "{\"from\":\"backend\"}".getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
// Two separate Set-Cookie lines, the canonical repeated response header. The Expires
// attribute carries its own comma, so a comma-joined relay cannot be split back apart.
exchange.getResponseHeaders().add("Set-Cookie",
"session=abc; Path=/; Expires=Wed, 21 Oct 2026 07:28:00 GMT");
exchange.getResponseHeaders().add("Set-Cookie", "tracking=xyz; Path=/");
exchange.sendResponseHeaders(200, response.length);
exchange.getResponseBody().write(response);
exchange.close();
}
private void resetRecordings() {
lastQuery.set(null);
lastTraceHeaders.set(null);
}
/**
* Creates an HTTP API whose {@code GET /orders} route is an HTTP_PROXY integration pointing at
* the fixture backend, deployed to stage {@code test}.
*/
private String createProxyApi(String name) {
String apiId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"" + name + "\",\"protocolType\":\"HTTP\"}")
.when().post("/v2/apis")
.then().statusCode(201)
.extract().path("apiId");
given()
.contentType(ContentType.JSON)
.body("{\"stageName\":\"test\"}")
.when().post("/v2/apis/" + apiId + "/stages")
.then().statusCode(201);
String integrationId = given()
.contentType(ContentType.JSON)
.body("{\"integrationType\":\"HTTP_PROXY\",\"integrationUri\":\"http://127.0.0.1:"
+ backendPort + "/orders\",\"payloadFormatVersion\":\"1.0\"}")
.when().post("/v2/apis/" + apiId + "/integrations")
.then().statusCode(201)
.extract().path("integrationId");
given()
.contentType(ContentType.JSON)
.body("{\"routeKey\":\"GET /orders\",\"target\":\"integrations/" + integrationId + "\"}")
.when().post("/v2/apis/" + apiId + "/routes")
.then().statusCode(201);
return apiId;
}
@Test
void repeatedQueryParametersReachTheBackendSeparately() {
resetRecordings();
String apiId = createProxyApi("v2-http-proxy-multi-query-api");
given()
.when().get("/execute-api/" + apiId + "/test/orders?tag=a&tag=b&limit=5")
.then().statusCode(200);
// Asserted per parameter rather than on the whole query string: the relative order of two
// differently named parameters is not part of the contract and is not stable across runs.
// The order of repeated values for one name is, and is checked.
Map<String, List<String>> received = parseQuery(lastQuery.get());
assertEquals(List.of("a", "b"), received.get("tag"));
assertEquals(List.of("5"), received.get("limit"));
}
@Test
void repeatedRequestHeadersReachTheBackendSeparately() {
resetRecordings();
String apiId = createProxyApi("v2-http-proxy-multi-header-api");
given()
.header("X-Trace", "first")
.header("X-Trace", "second")
.when().get("/execute-api/" + apiId + "/test/orders")
.then().statusCode(200);
assertEquals(List.of("first", "second"), lastTraceHeaders.get());
}
@Test
void repeatedResponseHeadersRelayToTheCallerSeparately() {
resetRecordings();
String apiId = createProxyApi("v2-http-proxy-multi-response-header-api");
List<String> cookies = given()
.when().get("/execute-api/" + apiId + "/test/orders")
.then().statusCode(200)
.extract().headers().getValues("Set-Cookie");
assertEquals(2, cookies.size(), "expected both Set-Cookie headers, got: " + cookies);
assertTrue(cookies.contains("session=abc; Path=/; Expires=Wed, 21 Oct 2026 07:28:00 GMT"),
"session cookie should relay with its Expires comma intact, got: " + cookies);
assertTrue(cookies.contains("tracking=xyz; Path=/"), "got: " + cookies);
}
/** Query string to name to values, preserving the order values appear in for a given name. */
private static Map<String, List<String>> parseQuery(String query) {
Map<String, List<String>> parsed = new LinkedHashMap<>();
if (query == null || query.isEmpty()) {
return parsed;
}
for (String pair : query.split("&")) {
int eq = pair.indexOf('=');
String name = eq < 0 ? pair : pair.substring(0, eq);
String value = eq < 0 ? "" : pair.substring(eq + 1);
parsed.computeIfAbsent(name, k -> new ArrayList<>()).add(value);
}
return parsed;
}
}