mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
f38a384e51
commit
96707f6d5a
9 files changed
+1311
-96
No files matched your search
@@ -186,7 +186,26 @@ These management-plane operations have no handler in v1. Calls will return `404`
|
||||
- Client Certificates (5 operations)
|
||||
- `GetExport` / `ImportDocumentationParts`
|
||||
|
||||
The execute plane (actual proxied HTTP traffic via `/restapis/{id}/{stage}/_user_request_/…`) is implemented separately and is not counted as management-plane operations. It supports `AWS_PROXY` (Lambda proxy), `AWS` (Lambda with VTL request/response templates), and `MOCK` integrations; other integration types return an error. A `MOCK` integration renders its request template and uses the `statusCode` it produces to pick the integration response, exactly as AWS does: the first response whose `selectionPattern` matches wins, otherwise the response without a pattern (the default) answers. This is what makes CORS preflights declared with a `204` response (CDK's `addCorsPreflight`) carry their `Access-Control-*` headers.
|
||||
The execute plane (actual proxied HTTP traffic via `/restapis/{id}/{stage}/_user_request_/…`) is implemented separately and is not counted as management-plane operations. It supports these integration types; others return an error:
|
||||
|
||||
| Type | Support |
|
||||
| --- | --- |
|
||||
| `AWS_PROXY` (Lambda proxy) | ✅ |
|
||||
| `AWS` (Lambda / AWS service with VTL request/response templates) | ✅ |
|
||||
| `HTTP_PROXY` (passthrough to an arbitrary HTTP backend) | ✅ |
|
||||
| `HTTP` (non-proxy, with VTL request/response templates) | ✅ |
|
||||
| `MOCK` | ✅ |
|
||||
|
||||
A `MOCK` integration renders its request template and uses the `statusCode` it produces to pick the integration response, exactly as AWS does: the first response whose `selectionPattern` matches wins, otherwise the response without a pattern (the default) answers. This is what makes CORS preflights declared with a `204` response (CDK's `addCorsPreflight`) carry their `Access-Control-*` headers.
|
||||
|
||||
`HTTP_PROXY` forwards the request to the integration's `uri` — with `{param}` placeholders resolved from the matched resource's path parameters — and relays the backend's status, headers and body unchanged. Per AWS, no request templates and no integration-response selection apply to `HTTP_PROXY`, so a backend `4xx`/`5xx` reaches the caller verbatim rather than being remapped. `integration.request.{header,querystring,path}.*` → `method.request.*` mappings are applied. Hop-by-hop headers (including `Host`) are stripped. An unreachable or failing backend yields `502`.
|
||||
|
||||
Passthrough keeps repeated values repeated, in both directions: `?tag=a&tag=b` reaches the backend as two `tag` parameters rather than one `tag=a,b`, a header sent twice arrives twice, and a backend that returns two `Set-Cookie` headers relays two to the caller. Comma-joining them would not be reversible, since a cookie's `Expires` attribute contains a comma of its own. An explicit `integration.request.header.X` or `integration.request.querystring.X` mapping overwrites, so it replaces any repeated inbound values with the single mapped one.
|
||||
|
||||
`HTTP` (non-proxy) transforms in both directions instead:
|
||||
|
||||
- **Request** — the body is the rendered `requestTemplates` entry selected by the incoming `Content-Type` (falling back to the type without its charset), subject to `passthroughBehavior` (`NEVER` and `WHEN_NO_TEMPLATES` return `415`). Only headers and query parameters named by `integration.request.*` mappings are forwarded; unmapped inbound headers are **not** passed through — that passthrough is `HTTP_PROXY`'s job.
|
||||
- **Response** — the backend's reply runs through the method's integration responses. As in AWS, `selectionPattern` is matched against the backend's **HTTP status code** (for `AWS`/Lambda integrations it is matched against the error message instead), so `"5\\d{2}"` on a `502` integration response remaps any backend `5xx` to `502`. The matched response's `responseTemplates` render the body, `responseParameters` map `integration.response.header.*` (case-insensitively) or `integration.response.body.<jsonpath>` onto `method.response.header.*`, and `$context.responseOverride` assignments take precedence. With no integration responses configured, the backend's status and body are relayed as-is.
|
||||
|
||||
### Examples
|
||||
|
||||
|
||||
+376
-81
@@ -49,6 +49,7 @@ import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
@@ -63,7 +64,7 @@ import java.util.regex.PatternSyntaxException;
|
||||
|
||||
/**
|
||||
* Executes API Gateway stage requests, routing them through the configured
|
||||
* integration (AWS_PROXY or MOCK).
|
||||
* integration (AWS_PROXY, AWS, HTTP_PROXY, HTTP or MOCK).
|
||||
*
|
||||
* <p>Endpoint: {@code /{apiId}/{stageName}/{proxy+}}
|
||||
*
|
||||
@@ -414,6 +415,10 @@ public class ApiGatewayExecuteController {
|
||||
iamIdentity);
|
||||
case "AWS" -> invokeAwsIntegration(region, httpMethod, path, stageName,
|
||||
matched, integration, headers, uriInfo, body, authorizerResult);
|
||||
case "HTTP_PROXY" -> invokeHttpProxy(apiId, httpMethod, path, proxy, stageName,
|
||||
matched, integration, headers, uriInfo, body);
|
||||
case "HTTP" -> invokeHttpIntegration(apiId, httpMethod, path, proxy, stageName,
|
||||
matched, integration, headers, uriInfo, body, authorizerResult);
|
||||
case "MOCK" -> invokeMock(region, httpMethod, path, stageName,
|
||||
matched, integration, headers, uriInfo, body, authorizerResult);
|
||||
default -> Response.status(500)
|
||||
@@ -462,6 +467,246 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── HTTP_PROXY ────────────────────────────
|
||||
|
||||
/**
|
||||
* Forwards the request to an arbitrary HTTP backend and relays that backend's response.
|
||||
*
|
||||
* <p>HTTP_PROXY is a passthrough: AWS applies neither request templates nor integration-response
|
||||
* selection to it, so the backend's status, headers and body come back untouched — including
|
||||
* error statuses, which must not be remapped into a gateway error. Only
|
||||
* {@code integration.request.*} parameter mapping applies on the way out.
|
||||
*/
|
||||
private Response invokeHttpProxy(String apiId, String httpMethod, String path, String proxy,
|
||||
String stageName, ApiGatewayResource resource,
|
||||
Integration integration, HttpHeaders headers,
|
||||
UriInfo uriInfo, byte[] body) {
|
||||
String uri = integration.getUri();
|
||||
if (uri == null || uri.isBlank()) {
|
||||
return Response.status(500)
|
||||
.entity(jsonMessage("No integration URI configured"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
// Two views of the same inbound data. The multi-value maps are what gets forwarded: a
|
||||
// proxy integration passes the request through, so "?tag=a&tag=b" has to arrive as two
|
||||
// tag parameters and not as "tag=a,b". The joined single-value maps are only the lookup
|
||||
// surface for method.request.* parameter mapping, which resolves to one value in AWS too.
|
||||
Map<String, List<String>> multiValueHeaders = new LinkedHashMap<>();
|
||||
Map<String, String> headerMap = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, List<String>> e : headers.getRequestHeaders().entrySet()) {
|
||||
if (e.getValue().isEmpty()) continue;
|
||||
multiValueHeaders.put(e.getKey(), List.copyOf(e.getValue()));
|
||||
headerMap.put(e.getKey(), String.join(",", e.getValue()));
|
||||
}
|
||||
Map<String, List<String>> multiValueQuery = new LinkedHashMap<>();
|
||||
Map<String, String> queryMap = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {
|
||||
if (e.getValue().isEmpty()) continue;
|
||||
multiValueQuery.put(e.getKey(), List.copyOf(e.getValue()));
|
||||
queryMap.put(e.getKey(), String.join(",", e.getValue()));
|
||||
}
|
||||
Map<String, String> pathMap = new LinkedHashMap<>();
|
||||
if (proxy != null && !proxy.isEmpty()) pathMap.put("proxy", proxy);
|
||||
pathMap.putAll(extractPathParams(resource.getPath(), path));
|
||||
|
||||
// integration.request.{header,querystring,path}.X ← method.request.*, applied here rather
|
||||
// than by the v2 RequestParameterMapper: that mapper reads the unrelated v2 syntax
|
||||
// ("append:header.x" → "$request.header.y") and would silently ignore these REST mappings.
|
||||
Map<String, String> requestParameters = integration.getRequestParameters();
|
||||
if (requestParameters != null) {
|
||||
for (Map.Entry<String, String> param : requestParameters.entrySet()) {
|
||||
String dest = param.getKey();
|
||||
String resolved = resolveRequestParameter(param.getValue(), queryMap, pathMap, headerMap);
|
||||
if (resolved == null) continue;
|
||||
// An explicit mapping overwrites, so it replaces any repeated inbound values too.
|
||||
if (dest.startsWith("integration.request.header.")) {
|
||||
String name = dest.substring("integration.request.header.".length());
|
||||
headerMap.put(name, resolved);
|
||||
multiValueHeaders.put(name, List.of(resolved));
|
||||
} else if (dest.startsWith("integration.request.querystring.")) {
|
||||
String name = dest.substring("integration.request.querystring.".length());
|
||||
queryMap.put(name, resolved);
|
||||
multiValueQuery.put(name, List.of(resolved));
|
||||
} else if (dest.startsWith("integration.request.path.")) {
|
||||
pathMap.put(dest.substring("integration.request.path.".length()), resolved);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// HttpProxyInvoker speaks the v2 integration model. The REST parameter mapping above is
|
||||
// already folded into the header/query/path maps, so this adapter deliberately carries no
|
||||
// requestParameters of its own — leaving them set would re-apply them under v2 semantics.
|
||||
io.github.hectorvent.floci.services.apigatewayv2.model.Integration target =
|
||||
new io.github.hectorvent.floci.services.apigatewayv2.model.Integration();
|
||||
target.setIntegrationType("HTTP_PROXY");
|
||||
target.setIntegrationUri(uri);
|
||||
target.setIntegrationMethod(integration.getHttpMethod());
|
||||
|
||||
io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext ctx =
|
||||
new io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext(
|
||||
apiId, stageName, httpMethod, path,
|
||||
pathMap.getOrDefault("proxy", ""), resource.getPath(),
|
||||
UUID.randomUUID().toString(),
|
||||
headerMap.getOrDefault("X-Forwarded-For", "127.0.0.1"),
|
||||
headerMap, queryMap, pathMap, body,
|
||||
Map.of(), Map.of(),
|
||||
multiValueHeaders, multiValueQuery);
|
||||
|
||||
LOG.debugv("execute-api: {0} {1}/{2}{3} → HTTP_PROXY {4}",
|
||||
httpMethod, apiId, stageName, path, uri);
|
||||
|
||||
io.github.hectorvent.floci.services.apigatewayv2.proxy.ProxyResult result =
|
||||
httpProxyInvoker.invoke(target, ctx);
|
||||
|
||||
Response.ResponseBuilder rb = Response.status(result.statusCode());
|
||||
if (result.body() != null) rb.entity(result.body());
|
||||
if (result.headers() != null) {
|
||||
// One header line per value, so a backend that sent two Set-Cookie headers relays as
|
||||
// two. Joining them would be lossy: a cookie's Expires attribute contains a comma.
|
||||
for (Map.Entry<String, List<String>> e : result.headers().entrySet()) {
|
||||
for (String value : e.getValue()) {
|
||||
rb.header(e.getKey(), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return rb.build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── HTTP (non-proxy) ────────────────────────────
|
||||
|
||||
/**
|
||||
* Invokes an arbitrary HTTP backend with VTL request/response mapping applied.
|
||||
*
|
||||
* <p>Unlike {@code HTTP_PROXY}, a non-proxy {@code HTTP} integration builds its backend request
|
||||
* entirely from mapping templates and explicit {@code integration.request.*} parameter
|
||||
* mappings — inbound headers and query parameters that were <em>not</em> mapped are not
|
||||
* forwarded. The backend's response then runs through the method's integration responses, where
|
||||
* {@code selectionPattern} is matched against the backend's HTTP status code (for
|
||||
* {@code AWS}/Lambda integrations it is matched against the error message instead).
|
||||
*/
|
||||
private Response invokeHttpIntegration(String apiId, String httpMethod, String path, String proxy,
|
||||
String stageName, ApiGatewayResource resource,
|
||||
Integration integration, HttpHeaders headers,
|
||||
UriInfo uriInfo, byte[] body,
|
||||
AuthorizerResult authorizerResult) {
|
||||
String uri = integration.getUri();
|
||||
if (uri == null || uri.isBlank()) {
|
||||
return Response.status(500)
|
||||
.entity(jsonMessage("No integration URI configured"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String bodyStr = body != null && body.length > 0 ? new String(body, StandardCharsets.UTF_8) : null;
|
||||
|
||||
Map<String, String> headerMap = new HashMap<>();
|
||||
for (Map.Entry<String, List<String>> e : headers.getRequestHeaders().entrySet()) {
|
||||
if (!e.getValue().isEmpty()) headerMap.put(e.getKey(), e.getValue().get(0));
|
||||
}
|
||||
Map<String, String> queryMap = new HashMap<>();
|
||||
for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {
|
||||
if (!e.getValue().isEmpty()) queryMap.put(e.getKey(), e.getValue().get(0));
|
||||
}
|
||||
Map<String, String> pathMap = new HashMap<>();
|
||||
if (proxy != null && !proxy.isEmpty()) pathMap.put("proxy", proxy);
|
||||
pathMap.putAll(extractPathParams(resource.getPath(), path));
|
||||
|
||||
String incomingContentType = headerMap.getOrDefault("Content-Type",
|
||||
headerMap.getOrDefault("content-type", "application/json"));
|
||||
|
||||
Map<String, Object> vtlAuthorizerContext = vtlAuthorizerContext(
|
||||
authorizerResult.principalId(), authorizerResult.context());
|
||||
|
||||
VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
|
||||
bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), null,
|
||||
vtlAuthorizerContext);
|
||||
|
||||
// Only explicitly mapped parameters reach the backend — the defining difference from
|
||||
// HTTP_PROXY, which seeds the outgoing request with every inbound header and query param.
|
||||
Map<String, String> outHeaders = new LinkedHashMap<>();
|
||||
Map<String, String> outQuery = new LinkedHashMap<>();
|
||||
Map<String, String> outPath = new LinkedHashMap<>(pathMap);
|
||||
Map<String, String> requestParameters = integration.getRequestParameters();
|
||||
if (requestParameters != null) {
|
||||
for (Map.Entry<String, String> param : requestParameters.entrySet()) {
|
||||
String dest = param.getKey();
|
||||
String resolved = resolveRequestParameter(param.getValue(), queryMap, pathMap, headerMap);
|
||||
if (resolved == null) continue;
|
||||
if (dest.startsWith("integration.request.header.")) {
|
||||
outHeaders.put(dest.substring("integration.request.header.".length()), resolved);
|
||||
} else if (dest.startsWith("integration.request.querystring.")) {
|
||||
outQuery.put(dest.substring("integration.request.querystring.".length()), resolved);
|
||||
} else if (dest.startsWith("integration.request.path.")) {
|
||||
outPath.put(dest.substring("integration.request.path.".length()), resolved);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RequestTemplateResult requestTemplateResult =
|
||||
applyRequestTemplates(integration, incomingContentType, bodyStr, vtlCtx);
|
||||
if (requestTemplateResult.rejection() != null) return requestTemplateResult.rejection();
|
||||
String transformedBody = requestTemplateResult.body();
|
||||
|
||||
// The payload is the rendered template, so the backend is told the media type that template
|
||||
// was keyed under — unless a requestParameters mapping already set one explicitly.
|
||||
outHeaders.putIfAbsent("Content-Type",
|
||||
requestTemplateResult.contentType() != null
|
||||
? requestTemplateResult.contentType() : MediaType.APPLICATION_JSON);
|
||||
|
||||
// Reuses the HTTP_PROXY transport (hop-by-hop stripping, chunked decoding, 502-on-failure).
|
||||
// The non-proxy semantics live in what this hands it: a mapped header/query set and a
|
||||
// VTL-rendered body, rather than the inbound request verbatim.
|
||||
io.github.hectorvent.floci.services.apigatewayv2.model.Integration target =
|
||||
new io.github.hectorvent.floci.services.apigatewayv2.model.Integration();
|
||||
target.setIntegrationType("HTTP_PROXY");
|
||||
target.setIntegrationUri(uri);
|
||||
target.setIntegrationMethod(integration.getHttpMethod());
|
||||
|
||||
byte[] payload = transformedBody != null
|
||||
? transformedBody.getBytes(StandardCharsets.UTF_8) : new byte[0];
|
||||
|
||||
io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext ctx =
|
||||
new io.github.hectorvent.floci.services.apigatewayv2.proxy.RequestContext(
|
||||
apiId, stageName, httpMethod, path,
|
||||
outPath.getOrDefault("proxy", ""), resource.getPath(),
|
||||
requestId, headerMap.getOrDefault("X-Forwarded-For", "127.0.0.1"),
|
||||
outHeaders, outQuery, outPath, payload,
|
||||
Map.of(), Map.of());
|
||||
|
||||
LOG.debugv("execute-api: {0} {1}/{2}{3} → HTTP {4}", httpMethod, apiId, stageName, path, uri);
|
||||
|
||||
io.github.hectorvent.floci.services.apigatewayv2.proxy.ProxyResult result =
|
||||
httpProxyInvoker.invoke(target, ctx);
|
||||
|
||||
String responseBodyStr = result.body() != null
|
||||
? new String(result.body(), StandardCharsets.UTF_8) : "";
|
||||
// java.net.http lowercases response header names, so this must be case-insensitive for an
|
||||
// integration.response.header.X-Backend-Id mapping to resolve.
|
||||
// Non-proxy responses run through integration responses, whose
|
||||
// integration.response.header.X mappings resolve to a single value, so the multi-valued
|
||||
// backend headers collapse here rather than on the way out of the transport.
|
||||
Map<String, String> responseHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
||||
if (result.headers() != null) {
|
||||
result.headers().forEach((name, values) -> responseHeaders.put(name, String.join(",", values)));
|
||||
}
|
||||
|
||||
VtlTemplateEngine.VtlContext responseMappingCtx = new VtlTemplateEngine.VtlContext(
|
||||
responseBodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), null,
|
||||
vtlAuthorizerContext);
|
||||
|
||||
// responseHeaders is already case-insensitive, so a plain lookup suffices.
|
||||
String defaultContentType =
|
||||
responseHeaders.getOrDefault("Content-Type", MediaType.APPLICATION_JSON);
|
||||
|
||||
// For HTTP integrations selectionPattern is matched against the backend's status code.
|
||||
return mapIntegrationResponse(integration, String.valueOf(result.statusCode()),
|
||||
responseBodyStr, result.statusCode(), responseHeaders, responseMappingCtx,
|
||||
defaultContentType);
|
||||
}
|
||||
|
||||
private AuthorizerResult invokeAuthorizer(String region, String apiId, String stageName,
|
||||
String httpMethod, String requestPath, String resourcePath,
|
||||
String resourceId,
|
||||
@@ -1073,49 +1318,10 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
|
||||
// Content-Type negotiation and passthrough behavior
|
||||
String transformedBody;
|
||||
Map<String, String> requestTemplates = integration.getRequestTemplates();
|
||||
|
||||
if (requestTemplates != null && !requestTemplates.isEmpty()) {
|
||||
// Try exact match first, then wildcard fallback
|
||||
String template = requestTemplates.get(incomingContentType);
|
||||
if (template == null) {
|
||||
// Try without charset: "application/json; charset=utf-8" → "application/json"
|
||||
String baseType = incomingContentType.contains(";")
|
||||
? incomingContentType.substring(0, incomingContentType.indexOf(';')).trim()
|
||||
: incomingContentType;
|
||||
template = requestTemplates.get(baseType);
|
||||
}
|
||||
|
||||
if (template != null) {
|
||||
transformedBody = vtlEngine.evaluate(template, vtlCtx).body();
|
||||
} else {
|
||||
// No matching template for this Content-Type
|
||||
String behavior = integration.getPassthroughBehavior();
|
||||
if ("NEVER".equalsIgnoreCase(behavior)) {
|
||||
return Response.status(415)
|
||||
.entity(jsonMessage("Unsupported Media Type"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
} else if ("WHEN_NO_TEMPLATES".equalsIgnoreCase(behavior)) {
|
||||
// Templates exist but none match → reject
|
||||
return Response.status(415)
|
||||
.entity(jsonMessage("Unsupported Media Type"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
} else {
|
||||
// WHEN_NO_MATCH (default) — passthrough
|
||||
transformedBody = bodyStr != null ? bodyStr : "";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// No templates defined at all
|
||||
String behavior = integration.getPassthroughBehavior();
|
||||
if ("NEVER".equalsIgnoreCase(behavior)) {
|
||||
return Response.status(415)
|
||||
.entity(jsonMessage("Unsupported Media Type"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
transformedBody = bodyStr != null ? bodyStr : "";
|
||||
}
|
||||
RequestTemplateResult requestTemplateResult =
|
||||
applyRequestTemplates(integration, incomingContentType, bodyStr, vtlCtx);
|
||||
if (requestTemplateResult.rejection() != null) return requestTemplateResult.rejection();
|
||||
String transformedBody = requestTemplateResult.body();
|
||||
|
||||
// Dispatch to service.
|
||||
//
|
||||
@@ -1218,25 +1424,112 @@ public class ApiGatewayExecuteController {
|
||||
errorType != null ? errorType : "UnknownError");
|
||||
}
|
||||
|
||||
// Select integration response
|
||||
Map<String, IntegrationResponse> integrationResponses = integration.getIntegrationResponses();
|
||||
IntegrationResponse matchedResponse = null;
|
||||
IntegrationResponse defaultResponse = null;
|
||||
|
||||
// Build the error string to match selectionPattern against.
|
||||
// AWS matches against the error response body/message. We match against
|
||||
// both errorType and errorMessage to catch patterns like ".*ResourceNotFoundException.*".
|
||||
// AWS matches selectionPattern against the error response body/message for AWS/Lambda
|
||||
// integrations. We match against both errorType and errorMessage to catch patterns like
|
||||
// ".*ResourceNotFoundException.*". (HTTP integrations match the status code instead —
|
||||
// see invokeHttpIntegration.)
|
||||
String errorMatchString = errorType != null
|
||||
? errorType + (errorMessage != null ? ": " + errorMessage : "")
|
||||
: errorMessage;
|
||||
|
||||
// Case-insensitive: an integration.response.header.X-Foo mapping must resolve regardless of
|
||||
// the casing the backend or client library used for the header name.
|
||||
Map<String, String> serviceResponseHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
||||
if (serviceResponse != null) {
|
||||
for (Map.Entry<String, List<String>> e : serviceResponse.getStringHeaders().entrySet()) {
|
||||
if (!e.getValue().isEmpty()) serviceResponseHeaders.put(e.getKey(), e.getValue().get(0));
|
||||
}
|
||||
}
|
||||
|
||||
VtlTemplateEngine.VtlContext responseMappingCtx = new VtlTemplateEngine.VtlContext(
|
||||
responseBodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), null,
|
||||
vtlAuthorizerContext);
|
||||
|
||||
int fallbackStatus = errorType != null ? 500 : (serviceStatus >= 400 ? serviceStatus : 200);
|
||||
return mapIntegrationResponse(integration, errorMatchString, responseBodyStr, fallbackStatus,
|
||||
serviceResponseHeaders, responseMappingCtx, MediaType.APPLICATION_JSON);
|
||||
}
|
||||
|
||||
/**
|
||||
* Outcome of request-template negotiation: either a rendered request body plus the media type
|
||||
* it was rendered as, or a ready-made rejection when {@code passthroughBehavior} forbids
|
||||
* passing the payload through untransformed.
|
||||
*/
|
||||
private record RequestTemplateResult(String body, String contentType, Response rejection) {}
|
||||
|
||||
/**
|
||||
* Selects a request template by the incoming {@code Content-Type} and renders it, applying
|
||||
* {@code passthroughBehavior} when no template matches. Shared by the {@code AWS} and
|
||||
* {@code HTTP} (non-proxy) integration types, which negotiate identically.
|
||||
*/
|
||||
private RequestTemplateResult applyRequestTemplates(Integration integration, String incomingContentType,
|
||||
String bodyStr, VtlTemplateEngine.VtlContext vtlCtx) {
|
||||
Response unsupportedMediaType = Response.status(415)
|
||||
.entity(jsonMessage("Unsupported Media Type"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
Map<String, String> requestTemplates = integration.getRequestTemplates();
|
||||
|
||||
if (requestTemplates == null || requestTemplates.isEmpty()) {
|
||||
// No templates defined at all
|
||||
if ("NEVER".equalsIgnoreCase(integration.getPassthroughBehavior())) {
|
||||
return new RequestTemplateResult(null, null, unsupportedMediaType);
|
||||
}
|
||||
return new RequestTemplateResult(bodyStr != null ? bodyStr : "", incomingContentType, null);
|
||||
}
|
||||
|
||||
// Try exact match first, then without charset: "application/json; charset=utf-8" → "application/json"
|
||||
String matchedType = incomingContentType;
|
||||
String template = requestTemplates.get(incomingContentType);
|
||||
if (template == null) {
|
||||
String baseType = incomingContentType.contains(";")
|
||||
? incomingContentType.substring(0, incomingContentType.indexOf(';')).trim()
|
||||
: incomingContentType;
|
||||
template = requestTemplates.get(baseType);
|
||||
if (template != null) matchedType = baseType;
|
||||
}
|
||||
|
||||
if (template != null) {
|
||||
// The template's own key is the media type the backend should be told it is receiving.
|
||||
return new RequestTemplateResult(vtlEngine.evaluate(template, vtlCtx).body(), matchedType, null);
|
||||
}
|
||||
|
||||
// No matching template for this Content-Type. NEVER forbids passthrough outright;
|
||||
// WHEN_NO_TEMPLATES rejects because templates exist but none matched.
|
||||
String behavior = integration.getPassthroughBehavior();
|
||||
if ("NEVER".equalsIgnoreCase(behavior) || "WHEN_NO_TEMPLATES".equalsIgnoreCase(behavior)) {
|
||||
return new RequestTemplateResult(null, null, unsupportedMediaType);
|
||||
}
|
||||
// WHEN_NO_MATCH (default) — passthrough
|
||||
return new RequestTemplateResult(bodyStr != null ? bodyStr : "", incomingContentType, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps an integration result onto the method response: selects the matching
|
||||
* {@link IntegrationResponse}, renders its response template, then applies
|
||||
* {@code $context.responseOverride} assignments and {@code responseParameters} header mappings.
|
||||
*
|
||||
* @param selectionMatchString what {@code selectionPattern} regexes are tested against — the
|
||||
* error message for {@code AWS}/Lambda integrations, the backend's
|
||||
* HTTP status code for {@code HTTP} integrations
|
||||
* @param fallbackStatus status used when no integration response is configured or matched
|
||||
*/
|
||||
private Response mapIntegrationResponse(Integration integration, String selectionMatchString,
|
||||
String responseBodyStr, int fallbackStatus,
|
||||
Map<String, String> integrationResponseHeaders,
|
||||
VtlTemplateEngine.VtlContext responseMappingCtx,
|
||||
String defaultContentType) {
|
||||
Map<String, IntegrationResponse> integrationResponses = integration.getIntegrationResponses();
|
||||
IntegrationResponse matchedResponse = null;
|
||||
IntegrationResponse defaultResponse = null;
|
||||
|
||||
if (integrationResponses != null && !integrationResponses.isEmpty()) {
|
||||
for (IntegrationResponse ir : integrationResponses.values()) {
|
||||
if (ir.selectionPattern() == null || ir.selectionPattern().isEmpty()) {
|
||||
defaultResponse = ir;
|
||||
} else if (errorMatchString != null) {
|
||||
} else if (selectionMatchString != null) {
|
||||
try {
|
||||
if (Pattern.matches(ir.selectionPattern(), errorMatchString)) {
|
||||
if (Pattern.matches(ir.selectionPattern(), selectionMatchString)) {
|
||||
matchedResponse = ir;
|
||||
break;
|
||||
}
|
||||
@@ -1263,10 +1556,6 @@ public class ApiGatewayExecuteController {
|
||||
String responseTemplate = responseTemplates.getOrDefault("application/json",
|
||||
responseTemplates.values().iterator().next());
|
||||
if (responseTemplate != null && !responseTemplate.isEmpty()) {
|
||||
VtlTemplateEngine.VtlContext responseMappingCtx = new VtlTemplateEngine.VtlContext(
|
||||
responseBodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
|
||||
resource.getPath(), requestId, regionResolver.getAccountId(), null,
|
||||
vtlAuthorizerContext);
|
||||
templateResult = vtlEngine.evaluate(responseTemplate, responseMappingCtx);
|
||||
finalBody = templateResult.body();
|
||||
} else {
|
||||
@@ -1276,15 +1565,13 @@ public class ApiGatewayExecuteController {
|
||||
finalBody = responseBodyStr;
|
||||
}
|
||||
} else {
|
||||
finalStatus = errorType != null ? 500 : (serviceStatus >= 400 ? serviceStatus : 200);
|
||||
finalStatus = fallbackStatus;
|
||||
finalBody = responseBodyStr;
|
||||
}
|
||||
|
||||
// Apply $context.responseOverride assignments from the response template (if any).
|
||||
if (templateResult != null) {
|
||||
if (templateResult.statusOverride() != null) {
|
||||
finalStatus = templateResult.statusOverride();
|
||||
}
|
||||
if (templateResult != null && templateResult.statusOverride() != null) {
|
||||
finalStatus = templateResult.statusOverride();
|
||||
}
|
||||
|
||||
Response.ResponseBuilder rb = Response.status(finalStatus)
|
||||
@@ -1305,20 +1592,12 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
// Apply response parameter mapping (header mapping from responseParameters config).
|
||||
if (matchedResponse != null && matchedResponse.responseParameters() != null) {
|
||||
// Case-insensitive: an integration.response.header.X-Foo mapping must resolve
|
||||
// regardless of the casing the backend or client library used for the header name.
|
||||
Map<String, String> serviceResponseHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
||||
if (serviceResponse != null) {
|
||||
for (Map.Entry<String, List<String>> e : serviceResponse.getStringHeaders().entrySet()) {
|
||||
if (!e.getValue().isEmpty()) serviceResponseHeaders.put(e.getKey(), e.getValue().get(0));
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, String> param : matchedResponse.responseParameters().entrySet()) {
|
||||
String dest = param.getKey(); // method.response.header.X-Foo
|
||||
String source = param.getValue(); // integration.response.header.X-Bar or 'static' or integration.response.body.jsonpath
|
||||
if (!dest.startsWith("method.response.header.")) continue;
|
||||
String headerName = dest.substring("method.response.header.".length());
|
||||
String headerValue = resolveResponseParameter(source, serviceResponseHeaders, responseBodyStr);
|
||||
String headerValue = resolveResponseParameter(source, integrationResponseHeaders, responseBodyStr);
|
||||
if (headerValue != null) {
|
||||
if ("Content-Type".equalsIgnoreCase(headerName)) {
|
||||
contentType = headerValue;
|
||||
@@ -1329,7 +1608,7 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
}
|
||||
|
||||
rb.type(contentType != null ? contentType : MediaType.APPLICATION_JSON);
|
||||
rb.type(contentType != null ? contentType : defaultContentType);
|
||||
return rb.build();
|
||||
}
|
||||
|
||||
@@ -1791,12 +2070,26 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, String> requestHeaders = new java.util.LinkedHashMap<>();
|
||||
// Same two views of the inbound data as the REST proxy path: the multi-value maps are what
|
||||
// reaches the backend, so "?tag=a&tag=b" stays two parameters, while the joined single-value
|
||||
// maps are the lookup surface for $request.header.X / $request.querystring.X, which resolve
|
||||
// to one value in AWS.
|
||||
Map<String, List<String>> multiValueHeaders = new LinkedHashMap<>();
|
||||
Map<String, String> requestHeaders = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, List<String>> e : headers.getRequestHeaders().entrySet()) {
|
||||
if (e.getValue().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
multiValueHeaders.put(e.getKey(), List.copyOf(e.getValue()));
|
||||
requestHeaders.put(e.getKey(), String.join(",", e.getValue()));
|
||||
}
|
||||
Map<String, String> queryParams = new java.util.LinkedHashMap<>();
|
||||
Map<String, List<String>> multiValueQueryParams = new LinkedHashMap<>();
|
||||
Map<String, String> queryParams = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {
|
||||
if (e.getValue().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
multiValueQueryParams.put(e.getKey(), List.copyOf(e.getValue()));
|
||||
queryParams.put(e.getKey(), String.join(",", e.getValue()));
|
||||
}
|
||||
Map<String, String> pathParams = extractV2PathParams(route.getRouteKey(), path);
|
||||
@@ -1817,7 +2110,7 @@ public class ApiGatewayExecuteController {
|
||||
pathParams.getOrDefault("proxy", ""), route.getRouteKey(),
|
||||
UUID.randomUUID().toString(), sourceIp,
|
||||
requestHeaders, queryParams, pathParams, body,
|
||||
claims, Map.of());
|
||||
claims, Map.of(), multiValueHeaders, multiValueQueryParams);
|
||||
|
||||
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → HTTP_PROXY {4}",
|
||||
httpMethod, apiId, stageName, path, effective.getIntegrationUri());
|
||||
@@ -1828,8 +2121,10 @@ public class ApiGatewayExecuteController {
|
||||
Response.ResponseBuilder rb = Response.status(result.statusCode());
|
||||
if (result.body() != null) rb.entity(result.body());
|
||||
if (result.headers() != null) {
|
||||
for (Map.Entry<String, String> e : result.headers().entrySet()) {
|
||||
rb.header(e.getKey(), e.getValue());
|
||||
for (Map.Entry<String, List<String>> e : result.headers().entrySet()) {
|
||||
for (String value : e.getValue()) {
|
||||
rb.header(e.getKey(), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return rb.build();
|
||||
@@ -1865,7 +2160,7 @@ public class ApiGatewayExecuteController {
|
||||
private static io.github.hectorvent.floci.services.apigatewayv2.model.Integration withResolvedUriAndHost(
|
||||
io.github.hectorvent.floci.services.apigatewayv2.model.Integration original, String targetUri, String host) {
|
||||
io.github.hectorvent.floci.services.apigatewayv2.model.Integration copy = withResolvedUri(original, targetUri);
|
||||
Map<String, String> requestParameters = new java.util.LinkedHashMap<>();
|
||||
Map<String, String> requestParameters = new LinkedHashMap<>();
|
||||
if (copy.getRequestParameters() != null) {
|
||||
requestParameters.putAll(copy.getRequestParameters());
|
||||
}
|
||||
@@ -1890,7 +2185,7 @@ public class ApiGatewayExecuteController {
|
||||
Matcher m = compiled.pattern().matcher(actualPath);
|
||||
if (!m.matches()) return Map.of();
|
||||
|
||||
Map<String, String> result = new java.util.LinkedHashMap<>();
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
for (int i = 0; i < compiled.parameterNames().size(); i++) {
|
||||
result.put(compiled.parameterNames().get(i), m.group(i + 1));
|
||||
}
|
||||
@@ -2423,7 +2718,7 @@ public class ApiGatewayExecuteController {
|
||||
// - mirrored here rather than dropping or restructuring anything, since callers may
|
||||
// read any claim name, not just the ones this method itself validates. The exact
|
||||
// per-type rendering is renderClaimValue's (measured, not JSON for arrays/nulls).
|
||||
Map<String, String> raw = new java.util.LinkedHashMap<>();
|
||||
Map<String, String> raw = new LinkedHashMap<>();
|
||||
java.util.Iterator<Map.Entry<String, JsonNode>> fields = claims.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> field = fields.next();
|
||||
|
||||
+13
-10
@@ -69,17 +69,19 @@ public class HttpProxyInvoker {
|
||||
method = ctx.httpMethod();
|
||||
}
|
||||
|
||||
// 3. Build mutable request, seed with inbound headers/query (excluding hop-by-hop)
|
||||
// 3. Build mutable request, seed with inbound headers/query (excluding hop-by-hop).
|
||||
// Seeded from the multi-valued view so repeated inbound headers and query parameters
|
||||
// reach the backend repeated rather than comma-joined.
|
||||
ProxyRequestBuilder builder = new ProxyRequestBuilder(resolvedUrl, method);
|
||||
if (ctx.requestHeaders() != null) {
|
||||
for (Map.Entry<String, String> e : ctx.requestHeaders().entrySet()) {
|
||||
if (ctx.multiValueHeaders() != null) {
|
||||
for (Map.Entry<String, List<String>> e : ctx.multiValueHeaders().entrySet()) {
|
||||
if (!HOP_BY_HOP.contains(e.getKey().toLowerCase())) {
|
||||
builder.overwriteHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ctx.queryParams() != null) {
|
||||
for (Map.Entry<String, String> e : ctx.queryParams().entrySet()) {
|
||||
if (ctx.multiValueQueryParams() != null) {
|
||||
for (Map.Entry<String, List<String>> e : ctx.multiValueQueryParams().entrySet()) {
|
||||
builder.overwriteQuery(e.getKey(), e.getValue());
|
||||
}
|
||||
}
|
||||
@@ -129,10 +131,10 @@ public class HttpProxyInvoker {
|
||||
|
||||
try {
|
||||
HttpResponse<byte[]> resp = client.send(hrb.build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
Map<String, String> respHeaders = new LinkedHashMap<>();
|
||||
Map<String, List<String>> respHeaders = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, List<String>> e : resp.headers().map().entrySet()) {
|
||||
if (HOP_BY_HOP.contains(e.getKey().toLowerCase())) continue;
|
||||
respHeaders.put(e.getKey(), String.join(",", e.getValue()));
|
||||
respHeaders.put(e.getKey(), List.copyOf(e.getValue()));
|
||||
}
|
||||
return new ProxyResult(resp.statusCode(), respHeaders, resp.body());
|
||||
} catch (Exception e) {
|
||||
@@ -221,7 +223,7 @@ public class HttpProxyInvoker {
|
||||
}
|
||||
String[] status = lines[0].split(" ", 3);
|
||||
int statusCode = Integer.parseInt(status[1]);
|
||||
Map<String, String> headers = new LinkedHashMap<>();
|
||||
Map<String, List<String>> headers = new LinkedHashMap<>();
|
||||
String transferEncoding = null;
|
||||
int contentLength = -1;
|
||||
for (int i = 1; i < lines.length; i++) {
|
||||
@@ -238,7 +240,8 @@ public class HttpProxyInvoker {
|
||||
contentLength = Integer.parseInt(value);
|
||||
}
|
||||
if (!HOP_BY_HOP.contains(name.toLowerCase(Locale.ROOT))) {
|
||||
headers.put(name, value);
|
||||
// Repeated header lines (Set-Cookie) accumulate rather than overwrite.
|
||||
headers.computeIfAbsent(name, k -> new java.util.ArrayList<>()).add(value);
|
||||
}
|
||||
}
|
||||
byte[] body = transferEncoding != null && transferEncoding.toLowerCase(Locale.ROOT).contains("chunked")
|
||||
@@ -319,7 +322,7 @@ public class HttpProxyInvoker {
|
||||
|
||||
private static ProxyResult errorResult(String message) {
|
||||
String body = "{\"message\":\"" + message.replace("\"", "\\\"") + "\"}";
|
||||
return new ProxyResult(502,
|
||||
return ProxyResult.withSingleValueHeaders(502,
|
||||
Map.of("Content-Type", "application/json"),
|
||||
body.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
+8
@@ -35,6 +35,10 @@ public class ProxyRequestBuilder {
|
||||
list.add(value);
|
||||
headers.put(name, list);
|
||||
}
|
||||
public void overwriteHeader(String name, List<String> values) {
|
||||
if (values == null) { headers.remove(name); return; }
|
||||
headers.put(name, new ArrayList<>(values));
|
||||
}
|
||||
public void appendHeader(String name, String value) {
|
||||
if (value == null) return;
|
||||
headers.computeIfAbsent(name, k -> new ArrayList<>()).add(value);
|
||||
@@ -47,6 +51,10 @@ public class ProxyRequestBuilder {
|
||||
list.add(value);
|
||||
queryParams.put(name, list);
|
||||
}
|
||||
public void overwriteQuery(String name, List<String> values) {
|
||||
if (values == null) { queryParams.remove(name); return; }
|
||||
queryParams.put(name, new ArrayList<>(values));
|
||||
}
|
||||
public void appendQuery(String name, String value) {
|
||||
if (value == null) return;
|
||||
queryParams.computeIfAbsent(name, k -> new ArrayList<>()).add(value);
|
||||
|
||||
+19
-3
@@ -1,10 +1,26 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.proxy;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Result of an HTTP_PROXY integration invocation. Carries the backend's
|
||||
* response status, headers (combined when multi-valued), and body bytes
|
||||
* back to the API Gateway dispatcher for relay to the original caller.
|
||||
* response status, headers and body bytes back to the API Gateway dispatcher
|
||||
* for relay to the original caller.
|
||||
*
|
||||
* <p>Headers are multi-valued: a backend may legitimately send the same header
|
||||
* name more than once (most commonly {@code Set-Cookie}), and a proxy that
|
||||
* folds those into one comma-joined value corrupts them. Cookie values may
|
||||
* themselves contain commas (an {@code Expires} date does), so the joined form
|
||||
* cannot be split back apart by the client.
|
||||
*/
|
||||
public record ProxyResult(int statusCode, Map<String, String> headers, byte[] body) {}
|
||||
public record ProxyResult(int statusCode, Map<String, List<String>> headers, byte[] body) {
|
||||
|
||||
/** Convenience for a response whose headers are all single-valued. */
|
||||
public static ProxyResult withSingleValueHeaders(int statusCode, Map<String, String> headers, byte[] body) {
|
||||
Map<String, List<String>> expanded = new LinkedHashMap<>();
|
||||
headers.forEach((name, value) -> expanded.put(name, List.of(value)));
|
||||
return new ProxyResult(statusCode, expanded, body);
|
||||
}
|
||||
}
|
||||
+43
-1
@@ -1,10 +1,22 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.proxy;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Bundles the inbound request data and authorizer-derived context that an
|
||||
* HTTP_PROXY integration may reference via $context.* / $request.* expressions.
|
||||
*
|
||||
* <p>Headers and query parameters appear twice, in two different shapes, because
|
||||
* the two consumers want different things. {@code requestHeaders} /
|
||||
* {@code queryParams} are the single-valued view that {@code $request.header.X}
|
||||
* and {@code $request.querystring.X} resolve against, matching AWS, where those
|
||||
* expressions yield one value. {@code multiValueHeaders} /
|
||||
* {@code multiValueQueryParams} are what actually gets forwarded to the backend,
|
||||
* and they keep repeated values separate: REST HTTP_PROXY passes the request
|
||||
* through, and {@code ?tag=a&tag=b} must not reach the backend as
|
||||
* {@code ?tag=a,b}, which is a different request to most servers.
|
||||
*/
|
||||
public record RequestContext(
|
||||
String apiId,
|
||||
@@ -20,5 +32,35 @@ public record RequestContext(
|
||||
Map<String, String> pathParams,
|
||||
byte[] body,
|
||||
Map<String, Object> authorizerClaims,
|
||||
Map<String, Object> authorizerContext) {
|
||||
Map<String, Object> authorizerContext,
|
||||
Map<String, List<String>> multiValueHeaders,
|
||||
Map<String, List<String>> multiValueQueryParams) {
|
||||
|
||||
/**
|
||||
* For callers whose headers and query parameters are single-valued by
|
||||
* construction, such as a non-proxy HTTP integration that forwards only the
|
||||
* parameters its {@code requestParameters} mapping named.
|
||||
*/
|
||||
public RequestContext(String apiId, String stageName, String httpMethod, String path, String proxy,
|
||||
String routeKey, String requestId, String sourceIp,
|
||||
Map<String, String> requestHeaders, Map<String, String> queryParams,
|
||||
Map<String, String> pathParams, byte[] body,
|
||||
Map<String, Object> authorizerClaims, Map<String, Object> authorizerContext) {
|
||||
this(apiId, stageName, httpMethod, path, proxy, routeKey, requestId, sourceIp,
|
||||
requestHeaders, queryParams, pathParams, body, authorizerClaims, authorizerContext,
|
||||
expand(requestHeaders), expand(queryParams));
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> expand(Map<String, String> single) {
|
||||
if (single == null) {
|
||||
return null;
|
||||
}
|
||||
Map<String, List<String>> expanded = new LinkedHashMap<>();
|
||||
single.forEach((name, value) -> {
|
||||
if (value != null) {
|
||||
expanded.put(name, List.of(value));
|
||||
}
|
||||
});
|
||||
return expanded;
|
||||
}
|
||||
}
|
||||
+324
@@ -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);
|
||||
}
|
||||
}
|
||||
+330
@@ -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);
|
||||
}
|
||||
}
|
||||
+178
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user