fix(apigatewayv2): store and apply integration ResponseParameters (#9090)

This commit is contained in:
Ignas authored and GitHub committed 2026-11-20 20:19:51 -04:00
1 parent 7b88a31956
commit d427b31e07
15 files changed
+693 -32

No files matched your search

+25
View File
@@ -897,6 +897,31 @@ control character besides tab, as is a mapped `Host`: the request never reaches
caller receives `502` with
`{"message":"Bad Gateway: invalid request header value for <name>"}`.
HTTP API integrations store and return `responseParameters`, and an `HTTP_PROXY` integration
applies the mappings keyed by the backend's status code to its response. `overwrite:statuscode`
replaces the status, and `append:header.<name>`, `overwrite:header.<name>` and
`remove:header.<name>` edit the response headers, matching the name case-insensitively. A value is a
static string, `$response.header.<name>` (repeated values joined with commas), `$response.body`,
`$response.body.<JSONPath>`, `$stageVariables.<name>` or one of the `$context` variables above, and
every value reads the backend response as it arrived. A value that resolves to nothing skips its
mapping. So does an `overwrite:statuscode` source that resolves to anything but a status from 100 to
599, and a header value holding CR, LF, NUL or any other control character besides tab, such as a
pretty-printed `$response.body`, while the other mappings still apply. Floci
evaluates the whole body, where AWS reads only its first 100 KB, and does not resolve the braced
`${response.header.<name>}` form. The `502` Floci answers for an unreachable backend goes through
the same mappings as a backend's own `502`. Lambda (`AWS_PROXY`) integrations store
`responseParameters` without applying them.
Create, update and OpenAPI import reject `responseParameters` that is not an object, a status code
key outside 200 to 599, a mapping key other than `overwrite:statuscode` or an `append`, `overwrite`
or `remove` of `header.<name>`, a header name that is not an HTTP token, and a static
`overwrite:statuscode` value that is not a status from 100 to 599, with `400 BadRequestException`.
The headers AWS reserves from mapping, such as `Content-Length`, are not checked. `UpdateIntegration` merges by status code: a status code with mappings replaces that status
code's mappings, an empty map such as `{"500": {}}` removes it, and a status code the update leaves
out is kept. CloudFormation carries `ResponseParameters` from an `AWS::ApiGatewayV2::Integration`,
each status code's `Destination` and `Source` pairs becoming its mappings, and from the
`x-amazon-apigateway-integration` extension of an `AWS::ApiGatewayV2::Api` `Body`.
HTTP API `AWS_PROXY` integrations accept every `integrationSubtype` AWS defines:
`EventBridge-PutEvents`, `SQS-SendMessage`, `SQS-ReceiveMessage`, `SQS-DeleteMessage`,
`SQS-PurgeQueue`, `AppConfig-GetConfiguration`, `Kinesis-PutRecord`,
@@ -2897,6 +2897,9 @@ public class ApiGatewayController {
ObjectNode requestParameters = node.putObject("requestParameters");
i.getRequestParameters().forEach(requestParameters::put);
}
if (i.getResponseParameters() != null) {
node.set("responseParameters", objectMapper.valueToTree(i.getResponseParameters()));
}
if (i.getTemplateSelectionExpression() != null) {
node.put("templateSelectionExpression", i.getTemplateSelectionExpression());
}
@@ -47,8 +47,10 @@ import io.floci.aws.services.apigatewayv2.model.IntegrationSubtype;
import io.floci.aws.services.apigatewayv2.model.Route;
import io.floci.aws.services.apigatewayv2.proxy.AwsServiceIntegrationMapper;
import io.floci.aws.services.apigatewayv2.proxy.CloudMapInstanceResolver;
import io.floci.aws.services.apigatewayv2.proxy.ContextValueResolver;
import io.floci.aws.services.apigatewayv2.proxy.HttpApiForwardedHeaders;
import io.floci.aws.services.apigatewayv2.proxy.HttpProxyInvoker;
import io.floci.aws.services.apigatewayv2.proxy.ResponseParameterMapper;
import io.floci.aws.services.apigatewayv2.websocket.ConnectionInfo;
import io.floci.aws.services.apigatewayv2.websocket.WebSocketConnectionManager;
import io.floci.aws.services.elbv2.ElbV2Service;
@@ -149,6 +151,8 @@ public class ApiGatewayExecuteController {
private final CloudMapInstanceResolver cloudMapInstanceResolver;
private final AwsServiceIntegrationMapper awsServiceIntegrationMapper;
private final HttpProxyInvoker httpProxyInvoker;
private final ResponseParameterMapper responseParameterMapper =
new ResponseParameterMapper(new ContextValueResolver());
@Inject
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, CognitoUserPoolAuthorizer cognitoAuthorizer,
@@ -3204,8 +3208,8 @@ public class ApiGatewayExecuteController {
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → HTTP_PROXY {4}",
httpMethod, apiId, stageName, path, effective.getIntegrationUri());
io.floci.aws.services.apigatewayv2.proxy.ProxyResult result =
httpProxyInvoker.invoke(effective, ctx);
io.floci.aws.services.apigatewayv2.proxy.ProxyResult result = responseParameterMapper.apply(
integration.getResponseParameters(), httpProxyInvoker.invoke(effective, ctx), ctx);
Response.ResponseBuilder rb = Response.status(result.statusCode());
if (result.body() != null) rb.entity(result.body());
@@ -267,8 +267,10 @@ public class ApiGatewayV2JsonHandler {
}
/**
* The integration request with lower-camel-case member names. RequestParameters keys keep
* their case, since an integration subtype's parameters are named by its action's members.
* The integration request with lower-camel-case member names. RequestParameters and
* ResponseParameters keys keep their case, since an integration subtype's parameters are named
* by its action's members and a response mapping key is validated as sent. ResponseParameters
* of any JSON type reaches the service, which rejects anything but an object.
*/
private Map<String, Object> integrationRequest(JsonNode request) {
@SuppressWarnings("unchecked")
@@ -278,6 +280,9 @@ public class ApiGatewayV2JsonHandler {
map.put("requestParameters",
objectMapper.convertValue(requestParameters, new TypeReference<Map<String, Object>>() {}));
}
if (request.has("ResponseParameters")) {
map.put("responseParameters", objectMapper.convertValue(request.get("ResponseParameters"), Object.class));
}
return map;
}
@@ -676,6 +681,9 @@ public class ApiGatewayV2JsonHandler {
ObjectNode requestParameters = node.putObject("RequestParameters");
i.getRequestParameters().forEach(requestParameters::put);
}
if (i.getResponseParameters() != null) {
node.set("ResponseParameters", objectMapper.valueToTree(i.getResponseParameters()));
}
if (i.getTemplateSelectionExpression() != null) {
node.put("TemplateSelectionExpression", i.getTemplateSelectionExpression());
}
@@ -189,7 +189,7 @@ public class ApiGatewayV2OpenApiImporter {
// rejected reimport leave the previous definition intact.
List<AuthorizerSpec> authorizerSpecs = authorizerSpecs(openAPI);
collectUnresolvedSecurity(openAPI, authorizerSpecs, warnings);
validateIntegrationSubtypes(openAPI);
validateIntegrations(openAPI);
if (failOnWarnings && !warnings.isEmpty()) {
throw new AwsException("BadRequestException",
@@ -665,10 +665,11 @@ public class ApiGatewayV2OpenApiImporter {
// ──────────────────────────── Integrations ────────────────────────────
/**
* Validates every integration's subtype as CreateIntegration will, while planning, so a document
* with an invalid subtype is rejected before an import or reimport changes anything.
* Validates every integration's subtype and response parameters as CreateIntegration will, while
* planning, so a document with an invalid one is rejected before an import or reimport changes
* anything.
*/
private static void validateIntegrationSubtypes(OpenAPI openAPI) {
private static void validateIntegrations(OpenAPI openAPI) {
forEachImportedOperation(openAPI, (method, path, operation) -> {
Map<String, Object> definition = extensionAsMap(
operation == null ? null : operation.getExtensions(), EXT_INTEGRATION);
@@ -683,6 +684,7 @@ public class ApiGatewayV2OpenApiImporter {
integrationSubtype, (String) request.getOrDefault("payloadFormatVersion",
ApiGatewayV2Service.defaultPayloadFormatVersion(integrationSubtype)),
requestParameters);
ApiGatewayV2Service.responseParameters(request.get("responseParameters"));
});
}
@@ -711,6 +713,9 @@ public class ApiGatewayV2OpenApiImporter {
}
copyStringMap(definition, request, "requestParameters");
if (definition.get("responseParameters") != null) {
request.put("responseParameters", definition.get("responseParameters"));
}
copyStringMap(definition, request, "requestTemplates");
copyStringMap(definition, request, "responseTemplates");
@@ -15,6 +15,8 @@ import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.core.storage.StorageOperations;
import io.floci.aws.services.apigatewayv2.model.*;
import io.floci.aws.services.apigatewayv2.proxy.AwsServiceIntegrationMapper;
import io.floci.aws.services.apigatewayv2.proxy.PinnedHttpClient;
import io.floci.aws.services.apigatewayv2.proxy.ResponseParameterMapper;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -788,9 +790,10 @@ public class ApiGatewayV2Service {
String payloadFormatVersion = request.get("payloadFormatVersion") != null
? (String) request.get("payloadFormatVersion")
: defaultPayloadFormatVersion(integrationSubtype);
Map<String, String> requestParameters = stringParameters(request.get("requestParameters"));
Map<String, String> requestParameters = stringParameters(request.get("requestParameters"), "RequestParameters");
validateIntegrationSubtype(api.getProtocolType(), (String) request.get("integrationType"),
integrationSubtype, payloadFormatVersion, requestParameters);
Map<String, Map<String, String>> responseParameters = responseParameters(request.get("responseParameters"));
Integration integration = new Integration();
integration.setIntegrationId(shortId(8));
@@ -817,6 +820,7 @@ public class ApiGatewayV2Service {
integration.setResponseTemplates(responseTemplates);
integration.setRequestParameters(requestParameters);
integration.setResponseParameters(responseParameters);
integration.setConnectionId((String) request.get("connectionId"));
@@ -851,7 +855,9 @@ public class ApiGatewayV2Service {
Map<String, Object> request) {
Integration integration = getIntegration(region, apiId, integrationId);
Map<String, String> requestParameters = mergedParameters(integration.getRequestParameters(),
stringParameters(request.get("requestParameters")));
stringParameters(request.get("requestParameters"), "RequestParameters"));
Map<String, Map<String, String>> responseParameters = mergedResponseParameters(
integration.getResponseParameters(), responseParameters(request.get("responseParameters")));
String payloadFormatVersion = (String) request.get("payloadFormatVersion");
if (payloadFormatVersion == null) {
payloadFormatVersion = request.get("integrationSubtype") != null
@@ -904,6 +910,7 @@ public class ApiGatewayV2Service {
integration.setResponseTemplates(responseTemplates);
}
integration.setRequestParameters(requestParameters);
integration.setResponseParameters(responseParameters);
if (request.containsKey("connectionId") && request.get("connectionId") != null) {
integration.setConnectionId((String) request.get("connectionId"));
}
@@ -956,22 +963,96 @@ public class ApiGatewayV2Service {
}
/**
* RequestParameters with every number or boolean value read as its text. An object or array
* value is a {@code BadRequestException}.
* The stored ResponseParameters with the update's status codes merged in: a status code whose
* mappings are empty is removed, and any other replaces that status code's mappings. An update
* without ResponseParameters keeps the stored map, and a merge that removes every status code
* leaves none.
*/
private static Map<String, String> stringParameters(Object requestParameters) {
if (!(requestParameters instanceof Map<?, ?> map)) {
private static Map<String, Map<String, String>> mergedResponseParameters(
Map<String, Map<String, String>> stored, Map<String, Map<String, String>> update) {
if (update == null) {
return stored;
}
Map<String, Map<String, String>> merged = stored != null ? new LinkedHashMap<>(stored) : new LinkedHashMap<>();
update.forEach((statusCode, mappings) -> {
if (mappings.isEmpty()) {
merged.remove(statusCode);
} else {
merged.put(statusCode, mappings);
}
});
return merged.isEmpty() ? null : merged;
}
/**
* Parameters with every number or boolean value read as its text. An object or array value is a
* {@code BadRequestException} naming {@code member}.
*/
private static Map<String, String> stringParameters(Object parameters, String member) {
if (!(parameters instanceof Map<?, ?> map)) {
return null;
}
Map<String, String> parameters = new LinkedHashMap<>();
Map<String, String> strings = new LinkedHashMap<>();
map.forEach((key, value) -> {
if (value instanceof Map<?, ?> || value instanceof Collection<?>) {
throw new AwsException("BadRequestException",
"RequestParameters value for " + key + " must be a string.", 400);
member + " value for " + key + " must be a string.", 400);
}
parameters.put(String.valueOf(key), value == null ? null : String.valueOf(value));
strings.put(String.valueOf(key), value == null ? null : String.valueOf(value));
});
return parameters;
return strings;
}
private static final Pattern RESPONSE_STATUS_CODE = Pattern.compile("[2-5][0-9]{2}");
private static final String STATUS_CODE_OVERWRITE = "overwrite:statuscode";
private static final Pattern RESPONSE_HEADER_KEY = Pattern.compile("(?:append|overwrite|remove):header\\.(.+)");
/**
* ResponseParameters as CreateIntegration and UpdateIntegration accept them: a map whose keys
* are status codes from 200 to 599, and each of its mappings {@code overwrite:statuscode} or an
* {@code append}, {@code overwrite} or {@code remove} of {@code header.<name>} with a valid
* header name. A static {@code overwrite:statuscode} value must be a status code from 100 to
* 599. Anything else is a {@code BadRequestException}.
*/
static Map<String, Map<String, String>> responseParameters(Object responseParameters) {
if (responseParameters == null) {
return null;
}
if (!(responseParameters instanceof Map<?, ?> map)) {
throw new AwsException("BadRequestException", "ResponseParameters must be a map.", 400);
}
Map<String, Map<String, String>> parsed = new LinkedHashMap<>();
map.forEach((key, value) -> {
String statusCode = String.valueOf(key);
if (!RESPONSE_STATUS_CODE.matcher(statusCode).matches()) {
throw new AwsException("BadRequestException",
"The selection key must be a valid HTTP status code within the range of 200-599.", 400);
}
if (!(value instanceof Map<?, ?>)) {
throw new AwsException("BadRequestException",
"ResponseParameters value for " + statusCode + " must be a map.", 400);
}
Map<String, String> mappings = stringParameters(value, "ResponseParameters");
mappings.forEach((mapping, source) -> {
if (STATUS_CODE_OVERWRITE.equals(mapping)) {
if ((source == null || !source.startsWith("$")) && ResponseParameterMapper.statusCode(source) == null) {
throw new AwsException("BadRequestException",
"ResponseParameters overwrite:statuscode value for status code " + statusCode
+ " must be a status code from 100 to 599.", 400);
}
return;
}
Matcher header = RESPONSE_HEADER_KEY.matcher(mapping);
if (!header.matches() || !PinnedHttpClient.isValidHeaderName(header.group(1))) {
throw new AwsException("BadRequestException",
"ResponseParameters key " + mapping + " for status code " + statusCode
+ " must be overwrite:statuscode or append, overwrite or remove of header.<name>.",
400);
}
});
parsed.put(statusCode, mappings);
});
return parsed;
}
/**
@@ -1057,19 +1138,21 @@ public class ApiGatewayV2Service {
}
/**
* Sets the method, template selection expression, timeout and the two mapping tables exactly as
* Sets the method, template selection expression, timeout and the three mapping tables exactly as
* given, null included. A timeout of 0 is the unset value. UpdateIntegration keeps a field the
* request leaves out, so it cannot remove one that CloudFormation dropped.
*/
public Integration replaceIntegrationSettings(String region, String apiId, String integrationId,
String integrationMethod, String templateSelectionExpression,
int timeoutInMillis, Map<String, String> requestParameters,
Map<String, Map<String, String>> responseParameters,
Map<String, String> requestTemplates) {
Integration integration = getIntegration(region, apiId, integrationId);
integration.setIntegrationMethod(integrationMethod);
integration.setTemplateSelectionExpression(templateSelectionExpression);
integration.setTimeoutInMillis(timeoutInMillis);
integration.setRequestParameters(requestParameters);
integration.setResponseParameters(responseParameters);
integration.setRequestTemplates(requestTemplates);
integrationStore.put(integrationKey(region, apiId, integrationId), integration);
return integration;
@@ -21,6 +21,7 @@ public class Integration {
private Map<String, String> responseTemplates;
private String templateSelectionExpression;
private Map<String, String> requestParameters;
private Map<String, Map<String, String>> responseParameters;
private String connectionId;
private String credentialsArn;
@@ -46,6 +47,7 @@ public class Integration {
this.responseTemplates = src.responseTemplates;
this.templateSelectionExpression = src.templateSelectionExpression;
this.requestParameters = src.requestParameters;
this.responseParameters = src.responseParameters;
this.connectionId = src.connectionId;
}
@@ -88,6 +90,9 @@ public class Integration {
public Map<String, String> getRequestParameters() { return requestParameters; }
public void setRequestParameters(Map<String, String> requestParameters) { this.requestParameters = requestParameters; }
public Map<String, Map<String, String>> getResponseParameters() { return responseParameters; }
public void setResponseParameters(Map<String, Map<String, String>> responseParameters) { this.responseParameters = responseParameters; }
public String getConnectionId() { return connectionId; }
public void setConnectionId(String connectionId) { this.connectionId = connectionId; }
}
@@ -108,7 +108,15 @@ public class ContextValueResolver {
}
private String bodyPath(RequestContext ctx, String path) {
String body = bodyText(ctx);
return jsonPath(bodyText(ctx), path);
}
/**
* The value a JSONPath selects from a JSON document, relative to its root: a scalar as its text
* and an object or array as its JSON. Null when the document is empty, is not JSON, or has
* nothing at the path.
*/
public String jsonPath(String body, String path) {
if (body == null || body.isBlank()) {
return null;
}
@@ -80,6 +80,11 @@ public final class PinnedHttpClient {
}
}
/** Whether {@code name} is an RFC 9110 field name. */
public static boolean isValidHeaderName(String name) {
return name != null && HEADER_NAME.matcher(name).matches();
}
/**
* Rejects a header that would not survive as one HTTP/1.1 header line: a name that is not a
* token, or a value carrying NUL, CR, LF or any other control character besides horizontal tab.
@@ -92,7 +97,7 @@ public final class PinnedHttpClient {
* @throws InvalidRequestHeaderException when the name or value cannot be sent
*/
public static void requireValidHeader(String name, String value) throws InvalidRequestHeaderException {
if (name == null || !HEADER_NAME.matcher(name).matches()) {
if (!isValidHeaderName(name)) {
throw new InvalidRequestHeaderException("invalid request header name");
}
if (value == null) {
@@ -0,0 +1,134 @@
package io.floci.aws.services.apigatewayv2.proxy;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Applies HTTP API v2 integration ResponseParameters to a backend response.
*
* <p>The mappings applied are the ones keyed by the backend's status code. Each has the form
* {@code overwrite:statuscode -> sourceValue} or {@code (action):header.(name) -> sourceValue}
* with {@code action} ∈ {overwrite, append, remove}. Header names match case-insensitively.
*
* <p>Source values read the backend response as it arrived, before any mapping:
* <ul>
* <li>{@code $response.header.<name>}: the header's values joined with commas</li>
* <li>{@code $response.body}: the body as text, null when it is empty</li>
* <li>{@code $response.body.<JSONPath>}: a value selected from a JSON body</li>
* <li>anything else, such as {@code $context.<name>}, {@code $stageVariables.<name>} or a
* literal, as {@link ContextValueResolver} resolves it</li>
* </ul>
*
* <p>As for RequestParameters, an overwrite or append whose source resolves to {@code null} is
* skipped. So is an {@code overwrite:statuscode} whose value is not a status code from 100 to 599,
* and a header whose value {@link PinnedHttpClient#requireValidHeader} rejects.
*/
public class ResponseParameterMapper {
private static final Logger LOG = Logger.getLogger(ResponseParameterMapper.class);
private static final String RESPONSE_HEADER = "$response.header.";
private static final String RESPONSE_BODY = "$response.body";
private final ContextValueResolver resolver;
public ResponseParameterMapper(ContextValueResolver resolver) {
this.resolver = resolver;
}
public ProxyResult apply(Map<String, Map<String, String>> responseParameters, ProxyResult result,
RequestContext ctx) {
Map<String, String> mappings = responseParameters == null ? null
: responseParameters.get(String.valueOf(result.statusCode()));
if (mappings == null || mappings.isEmpty()) {
return result;
}
int statusCode = result.statusCode();
Map<String, List<String>> headers = new LinkedHashMap<>();
if (result.headers() != null) {
result.headers().forEach((name, values) -> headers.put(name, new ArrayList<>(values)));
}
for (Map.Entry<String, String> mapping : mappings.entrySet()) {
String key = mapping.getKey();
if (key.equals("overwrite:statuscode")) {
Integer status = statusCode(resolve(mapping.getValue(), result, ctx));
if (status != null) {
statusCode = status;
}
continue;
}
int colonIdx = key.indexOf(':');
String action = key.substring(0, colonIdx);
String headerName = key.substring(colonIdx + 1 + "header.".length());
if (action.equals("remove")) {
removeHeader(headers, headerName);
continue;
}
String value = resolve(mapping.getValue(), result, ctx);
if (value == null) {
continue;
}
try {
PinnedHttpClient.requireValidHeader(headerName, value);
} catch (PinnedHttpClient.InvalidRequestHeaderException e) {
LOG.warnv("HTTP_PROXY: skipping response mapping {0}: its value is not a valid header value", key);
continue;
}
if (action.equals("overwrite")) {
removeHeader(headers, headerName);
}
headers.computeIfAbsent(existingName(headers, headerName), k -> new ArrayList<>()).add(value);
}
return new ProxyResult(statusCode, headers, result.body());
}
private String resolve(String source, ProxyResult result, RequestContext ctx) {
if (source == null) {
return null;
}
if (source.startsWith(RESPONSE_HEADER)) {
String name = source.substring(RESPONSE_HEADER.length());
List<String> values = result.headers() == null ? null
: result.headers().get(existingName(result.headers(), name));
return values == null || values.isEmpty() ? null : String.join(",", values);
}
if (source.equals(RESPONSE_BODY)) {
return bodyText(result);
}
if (source.startsWith(RESPONSE_BODY + ".")) {
return resolver.jsonPath(bodyText(result), source.substring(RESPONSE_BODY.length() + 1));
}
return resolver.resolve(source, ctx);
}
private static String bodyText(ProxyResult result) {
return result.body() == null || result.body().length == 0
? null : new String(result.body(), StandardCharsets.UTF_8);
}
/** The status code {@code value} spells, from 100 to 599, or null when it spells none. */
public static Integer statusCode(String value) {
if (value == null || !value.matches("[0-9]{3}")) {
return null;
}
int status = Integer.parseInt(value);
return status >= 100 && status <= 599 ? status : null;
}
/** The name the header is stored under, matched case-insensitively, or {@code name} when absent. */
private static String existingName(Map<String, List<String>> headers, String name) {
for (String existing : headers.keySet()) {
if (existing.equalsIgnoreCase(name)) {
return existing;
}
}
return name;
}
private static void removeHeader(Map<String, List<String>> headers, String name) {
headers.keySet().removeIf(existing -> existing.equalsIgnoreCase(name));
}
}
@@ -329,6 +329,11 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
objectMapper.convertValue(requestParameters,
new TypeReference<Map<String, Object>>() {})));
}
JsonNode responseParameters = integration.path("responseParameters");
if (!responseParameters.isMissingNode() && !responseParameters.isNull()) {
integrationRequest.put("responseParameters",
objectMapper.convertValue(responseParameters, Object.class));
}
Integration createdIntegration = apiGatewayV2Service.createIntegration(region, apiId,
integrationRequest);
integrationIds.add(createdIntegration.getIntegrationId());
@@ -947,6 +952,10 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
if (requestParameters != null) {
req.put("requestParameters", requestParameters);
}
Map<String, Map<String, String>> responseParameters = resolveResponseParameters(props, ctx.engine());
if (responseParameters != null) {
req.put("responseParameters", responseParameters);
}
Map<String, String> requestTemplates = resolveStringMap(props, "RequestTemplates", ctx.engine());
if (requestTemplates != null) {
req.put("requestTemplates", requestTemplates);
@@ -972,7 +981,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
apiGatewayV2Service.replaceIntegrationSettings(region, apiId, r.getPhysicalId(),
(String) req.get("integrationMethod"),
(String) req.get("templateSelectionExpression"), timeoutInMillis,
requestParameters, requestTemplates);
requestParameters, responseParameters, requestTemplates);
if (integrationSubtype == null && prior.getIntegrationSubtype() != null) {
apiGatewayV2Service.replaceIntegrationSubtype(region, apiId, r.getPhysicalId(), null);
}
@@ -1015,6 +1024,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
snapshot.put("templateSelectionExpression", prior.getTemplateSelectionExpression());
snapshot.put("timeoutInMillis", prior.getTimeoutInMillis());
snapshot.set("requestParameters", objectMapper.valueToTree(prior.getRequestParameters()));
snapshot.set("responseParameters", objectMapper.valueToTree(prior.getResponseParameters()));
snapshot.set("requestTemplates", objectMapper.valueToTree(prior.getRequestTemplates()));
snapshot.put("integrationSubtype", prior.getIntegrationSubtype());
snapshot.put("otherFieldChanged", otherFieldChanged);
@@ -1050,6 +1060,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
snapshot.path("apiId").asText(), resource.getPhysicalId(),
textOrNull(snapshot, "integrationMethod"), textOrNull(snapshot, "templateSelectionExpression"),
snapshot.path("timeoutInMillis").asInt(), stringMapOrNull(snapshot.path("requestParameters")),
responseParametersOrNull(snapshot.path("responseParameters")),
stringMapOrNull(snapshot.path("requestTemplates")));
if (snapshot.has("integrationSubtype")) {
apiGatewayV2Service.replaceIntegrationSubtype(snapshot.path("region").asText(),
@@ -1070,6 +1081,13 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
return out;
}
private Map<String, Map<String, String>> responseParametersOrNull(JsonNode node) {
if (node == null || !node.isObject()) {
return null;
}
return objectMapper.convertValue(node, new TypeReference<Map<String, Map<String, String>>>() {});
}
// ── Stage ────────────────────────────────────────────────────────────────
private void provisionStage(StackResource r, JsonNode props, ProvisionContext ctx) {
@@ -1297,4 +1315,28 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
resolved.fields().forEachRemaining(e -> out.put(e.getKey(), e.getValue().asText()));
return out;
}
/**
* Resolves ResponseParameters from its template shape, a {@code ResponseParameters} list of
* Destination and Source pairs under each status code, to the API's map of status code to
* mappings, or null when absent or not an object.
*/
private static Map<String, Map<String, String>> resolveResponseParameters(JsonNode props,
CloudFormationTemplateEngine engine) {
if (props == null || !props.has("ResponseParameters") || props.get("ResponseParameters").isNull()) {
return null;
}
JsonNode resolved = engine.resolveNodeOmittingNoValue(props.get("ResponseParameters"));
if (resolved == null || !resolved.isObject()) {
return null;
}
Map<String, Map<String, String>> out = new LinkedHashMap<>();
resolved.fields().forEachRemaining(statusCode -> {
Map<String, String> mappings = new LinkedHashMap<>();
statusCode.getValue().path("ResponseParameters").forEach(parameter ->
mappings.put(parameter.path("Destination").asText(), parameter.path("Source").asText()));
out.put(statusCode.getKey(), mappings);
});
return out;
}
}
@@ -693,4 +693,53 @@ class ApiGatewayV2OpenApiImportTest {
assertEquals(1, authorizers.size());
assertEquals(300, authorizers.get(0).get("authorizerResultTtlInSeconds").asInt());
}
@Test
@Order(20)
void importedResponseParametersAreStoredAndAnInvalidOneLeavesThePreviousDefinitionIntact() throws Exception {
String spec = """
{
"openapi": "3.0.1",
"info": {"title": "ResponseParametersImport", "version": "1.0"},
"paths": {
"/orders": {
"get": {
"x-amazon-apigateway-integration": {
"type": "http_proxy",
"httpMethod": "ANY",
"uri": "https://api.example.com/orders",
"payloadFormatVersion": "1.0",
"responseParameters": {
"500": {"overwrite:statuscode": "403", "append:header.header1": "$context.requestId"}
}
}
}
}
}
}
""";
String created = given().contentType(ContentType.JSON)
.body(envelope(spec))
.when().put("/v2/apis")
.then().statusCode(201).extract().asString();
String apiId = mapper.readTree(created).get("apiId").asText();
JsonNode responseParameters = get("/v2/apis/" + apiId + "/integrations")
.get("items").get(0).get("responseParameters");
assertEquals("403", responseParameters.path("500").path("overwrite:statuscode").asText());
assertEquals("$context.requestId", responseParameters.path("500").path("append:header.header1").asText());
given().contentType(ContentType.JSON)
.body(envelope(spec.replace("\"500\":", "\"700\":")))
.when().put("/v2/apis/" + apiId)
.then().statusCode(400);
given().contentType(ContentType.JSON)
.body(envelope(spec.replace("\"responseParameters\": {",
"\"responseParameters\": [\"500\"], \"unused\": {")))
.when().put("/v2/apis/" + apiId)
.then().statusCode(400);
assertEquals("403", get("/v2/apis/" + apiId + "/integrations").get("items").get(0)
.path("responseParameters").path("500").path("overwrite:statuscode").asText());
}
}
@@ -0,0 +1,268 @@
package io.floci.aws.services.apigatewayv2;
import com.sun.net.httpserver.HttpServer;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@QuarkusTest
class HttpProxyResponseParametersIntegrationTest {
private HttpServer backend;
private String apiId;
private String integrationId;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void startBackend() throws Exception {
backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
backend.createContext("/", exchange -> {
String query = exchange.getRequestURI().getQuery();
int status = query != null && query.startsWith("status=") ? Integer.parseInt(query.substring(7)) : 200;
exchange.getResponseHeaders().add("X-Backend", "one");
exchange.getResponseHeaders().add("X-Drop", "gone");
exchange.getResponseHeaders().add("Content-Type", "application/json");
String body = "pretty=1".equals(query) ? "{\n \"error\": {\"code\": \"E-7\"}\n}" : "{\"error\":{\"code\":\"E-7\"}}";
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, bytes.length);
exchange.getResponseBody().write(bytes);
exchange.close();
});
backend.start();
apiId = HttpProxyApiFixtures.createProxyApi("response-parameters", "", "test",
backend.getAddress().getPort(), "/orders");
integrationId = given().get("/v2/apis/" + apiId + "/integrations").then().statusCode(200)
.extract().path("items[0].integrationId");
}
@AfterEach
void cleanUp() {
try {
given().delete("/v2/apis/" + apiId).then().statusCode(204);
} finally {
backend.stop(0);
}
}
@Test
void createReturnsAndGetReadsResponseParameters() {
Map<String, Object> responseParameters = Map.of(
"500", Map.of("overwrite:statuscode", "403", "append:header.header1", "$context.requestId"),
"404", Map.of("append:header.error", "$stageVariables.environmentId"));
String createdId = given().contentType(ContentType.JSON)
.body(Map.of("integrationType", "HTTP_PROXY", "integrationUri", "https://api.example.com",
"integrationMethod", "ANY", "payloadFormatVersion", "1.0",
"responseParameters", responseParameters))
.post("/v2/apis/" + apiId + "/integrations")
.then().statusCode(201)
.body("responseParameters", equalTo(responseParameters))
.extract().path("integrationId");
given().get("/v2/apis/" + apiId + "/integrations/" + createdId)
.then().statusCode(200)
.body("responseParameters", equalTo(responseParameters));
given().get("/v2/apis/" + apiId + "/integrations")
.then().statusCode(200)
.body("items.find { it.integrationId == '" + createdId + "' }.responseParameters",
equalTo(responseParameters));
}
@Test
void updateReplacesAStatusCodesMappingsAndAnEmptyMapRemovesIt() {
patchResponseParameters(Map.of(
"500", Map.of("overwrite:statuscode", "403"),
"502", Map.of("overwrite:statuscode", "200")));
patchResponseParameters(Map.of(
"500", Map.of(),
"502", Map.of("append:header.x-retry", "later"),
"404", Map.of("remove:header.x-drop", "")));
given().get("/v2/apis/" + apiId + "/integrations/" + integrationId)
.then().statusCode(200)
.body("responseParameters", equalTo(Map.of(
"502", Map.of("append:header.x-retry", "later"),
"404", Map.of("remove:header.x-drop", ""))));
patchResponseParameters(Map.of("502", Map.of(), "404", Map.of()));
assertNull(given().get("/v2/apis/" + apiId + "/integrations/" + integrationId)
.then().statusCode(200).extract().path("responseParameters"));
}
@Test
void json11CreateAndGetKeepResponseParameters() {
String target = "AmazonApiGatewayV2.";
String json11 = "application/x-amz-json-1.1";
String auth = "AWS4-HMAC-SHA256 Credential=test/20260413/us-east-1/apigatewayv2/aws4_request";
String createdId = given().contentType(json11).header("X-Amz-Target", target + "CreateIntegration")
.header("Authorization", auth)
.body("""
{"ApiId":"%s","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://example.com",
"PayloadFormatVersion":"1.0","ResponseParameters":{"500":{"overwrite:statuscode":"200"}}}
""".formatted(apiId))
.post("/")
.then().statusCode(201)
.body("ResponseParameters.'500'.'overwrite:statuscode'", equalTo("200"))
.extract().path("IntegrationId");
given().contentType(json11).header("X-Amz-Target", target + "GetIntegration")
.header("Authorization", auth)
.body("{\"ApiId\":\"%s\",\"IntegrationId\":\"%s\"}".formatted(apiId, createdId))
.post("/")
.then().statusCode(200)
.body("ResponseParameters.'500'.'overwrite:statuscode'", equalTo("200"));
}
@Test
void statusCodeOutsideTwoHundredToFiveNinetyNineIsRejected() {
given().contentType(ContentType.JSON)
.body(Map.of("responseParameters", Map.of("600", Map.of("overwrite:statuscode", "200"))))
.patch("/v2/apis/" + apiId + "/integrations/" + integrationId)
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("The selection key must be a valid HTTP status code within the range of 200-599."));
}
@Test
void unknownMappingIsRejectedAndLeavesTheIntegrationUnchanged() {
patchResponseParameters(Map.of("500", Map.of("overwrite:statuscode", "403")));
given().contentType(ContentType.JSON)
.body(Map.of("responseParameters", Map.of(
"500", Map.of("overwrite:statuscode", "200"),
"404", Map.of("overwrite:querystring.page", "1"))))
.patch("/v2/apis/" + apiId + "/integrations/" + integrationId)
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", containsString("ResponseParameters key overwrite:querystring.page"));
given().get("/v2/apis/" + apiId + "/integrations/" + integrationId)
.then().statusCode(200)
.body("responseParameters", equalTo(Map.of("500", Map.of("overwrite:statuscode", "403"))));
}
@Test
void staticStatusCodeOverwriteThatIsNotAStatusIsRejected() {
patchResponseParameters(Map.of("500", Map.of("overwrite:statuscode", "$response.header.x-status")));
given().contentType(ContentType.JSON)
.body(Map.of("responseParameters", Map.of("500", Map.of("overwrite:statuscode", "abc"))))
.patch("/v2/apis/" + apiId + "/integrations/" + integrationId)
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", containsString("overwrite:statuscode value for status code 500"));
given().get("/v2/apis/" + apiId + "/integrations/" + integrationId)
.then().statusCode(200)
.body("responseParameters",
equalTo(Map.of("500", Map.of("overwrite:statuscode", "$response.header.x-status"))));
}
@Test
void headerNameThatIsNotATokenIsRejected() {
given().contentType(ContentType.JSON)
.body(Map.of("responseParameters", Map.of("200", Map.of("append:header.x bad", "v"))))
.patch("/v2/apis/" + apiId + "/integrations/" + integrationId)
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", containsString("ResponseParameters key append:header.x bad"));
}
@Test
void responseParametersThatIsNotAnObjectIsRejected() {
given().contentType(ContentType.JSON)
.body(Map.of("integrationType", "HTTP_PROXY", "integrationUri", "https://api.example.com",
"payloadFormatVersion", "1.0", "responseParameters", List.of("500")))
.post("/v2/apis/" + apiId + "/integrations")
.then().statusCode(400)
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("ResponseParameters must be a map."));
given().contentType(ContentType.JSON)
.body(Map.of("responseParameters", "500"))
.patch("/v2/apis/" + apiId + "/integrations/" + integrationId)
.then().statusCode(400)
.body("message", equalTo("ResponseParameters must be a map."));
given().contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", "AmazonApiGatewayV2.UpdateIntegration")
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260413/us-east-1/apigatewayv2/aws4_request")
.body("{\"ApiId\":\"%s\",\"IntegrationId\":\"%s\",\"ResponseParameters\":[\"500\"]}"
.formatted(apiId, integrationId))
.post("/")
.then().statusCode(400)
.body("message", equalTo("ResponseParameters must be a map."));
}
@Test
void headerValueWithALineBreakIsSkippedAndTheResponseIsRelayed() {
patchResponseParameters(Map.of("200", Map.of(
"append:header.x-body", "$response.body",
"append:header.x-code", "$response.body.error.code")));
Response response = given().get("/execute-api/" + apiId + "/test/orders?pretty=1");
assertEquals(200, response.statusCode());
assertEquals("E-7", response.jsonPath().getString("error.code"));
assertNull(response.header("x-body"));
assertEquals("E-7", response.header("x-code"));
}
@Test
void statusCodeOverwriteAppliesOnlyToTheMatchingBackendStatus() {
patchResponseParameters(Map.of("500", Map.of("overwrite:statuscode", "200")));
given().get("/execute-api/" + apiId + "/test/orders?status=500")
.then().statusCode(200)
.body("error.code", equalTo("E-7"));
given().get("/execute-api/" + apiId + "/test/orders?status=502")
.then().statusCode(502);
}
@Test
void headerActionsReadTheBackendResponseAndTheRequestContext() {
patchResponseParameters(Map.of("200", Map.of(
"append:header.x-copy", "$response.header.x-backend",
"overwrite:header.X-Backend", "two",
"remove:header.x-drop", "''",
"append:header.x-code", "$response.body.error.code",
"append:header.x-stage", "$context.stage",
"append:header.x-missing", "$response.header.x-absent")));
Response response = given().get("/execute-api/" + apiId + "/test/orders");
assertEquals(200, response.statusCode());
assertEquals("one", response.header("x-copy"));
assertEquals("two", response.header("x-backend"));
assertEquals(1, response.headers().getValues("x-backend").size());
assertNull(response.header("x-drop"));
assertEquals("E-7", response.header("x-code"));
assertEquals("test", response.header("x-stage"));
assertNull(response.header("x-missing"));
}
private void patchResponseParameters(Map<String, Object> responseParameters) {
given().contentType(ContentType.JSON).body(Map.of("responseParameters", responseParameters))
.patch("/v2/apis/" + apiId + "/integrations/" + integrationId)
.then().statusCode(200);
}
}
@@ -941,7 +941,7 @@ class ApiGatewayV2CfnProvisionerTest {
""");
assertTrue(integration.getStatus().endsWith("_COMPLETE"), integration.getStatus());
verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", null, null, 0, null, null);
verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", null, null, 0, null, null, null);
}
@Test
@@ -952,10 +952,29 @@ class ApiGatewayV2CfnProvisionerTest {
verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", "ANY",
"${request.method}", 15000, Map.of("append:header.x-request-id", "$context.requestId",
"overwrite:header.x-example", "static-value"),
"overwrite:header.x-example", "static-value"), null,
Map.of("application/json", "{\"a\":1}"));
}
@Test
void integrationResponseParametersBecomeAMapOfDestinationToSource() throws Exception {
Integration integration = new Integration();
integration.setIntegrationId("int-1");
when(apiGatewayV2Service.createIntegration(eq(REGION), eq(API_ID), anyMap())).thenReturn(integration);
provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration", mapper.readTree("""
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend",
"ResponseParameters":{"500":{"ResponseParameters":[
{"Destination":"overwrite:statuscode","Source":"403"},
{"Destination":"append:header.x-stack","Source":{"Ref":"AWS::StackName"}}]}}}
"""),
engine(), REGION, "000000000000", "test-stack", null, Map.of());
verify(apiGatewayV2Service).createIntegration(eq(REGION), eq(API_ID), argThat(req ->
Map.of("500", Map.of("overwrite:statuscode", "403", "append:header.x-stack", "test-stack"))
.equals(req.get("responseParameters"))));
}
@Test
void integrationMappingEntryWithNoValueIsOmitted() throws Exception {
Integration integration = new Integration();
@@ -980,22 +999,26 @@ class ApiGatewayV2CfnProvisionerTest {
prior.setTemplateSelectionExpression("${request.method}");
prior.setTimeoutInMillis(15000);
prior.setRequestParameters(Map.of("overwrite:header.x-example", "old"));
prior.setResponseParameters(Map.of("500", Map.of("overwrite:statuscode", "200")));
prior.setRequestTemplates(Map.of("application/json", "{}"));
stubIntegrationUpdate(prior);
StackResource integration = provisionIntegration("""
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend",
"ConnectionType":"VPC_LINK","ConnectionId":"vl-1","IntegrationMethod":"POST",
"TimeoutInMillis":"3000","RequestParameters":{"overwrite:header.x-example":"new"}}
"TimeoutInMillis":"3000","RequestParameters":{"overwrite:header.x-example":"new"},
"ResponseParameters":{"404":{"ResponseParameters":[
{"Destination":"overwrite:statuscode","Source":"200"}]}}}
""");
assertTrue(provisioner.rollbackUpdate(integration));
InOrder order = inOrder(apiGatewayV2Service);
order.verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", "POST", null, 3000,
Map.of("overwrite:header.x-example", "new"), null);
Map.of("overwrite:header.x-example", "new"), Map.of("404", Map.of("overwrite:statuscode", "200")),
null);
order.verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", "GET",
"${request.method}", 15000, Map.of("overwrite:header.x-example", "old"),
Map.of("application/json", "{}"));
Map.of("500", Map.of("overwrite:statuscode", "200")), Map.of("application/json", "{}"));
}
@Test
@@ -1012,9 +1035,9 @@ class ApiGatewayV2CfnProvisionerTest {
""");
assertTrue(integration.getStatus().endsWith("_FAILED"), integration.getStatus());
verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", null, null, 0, null, null);
verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", null, null, 0, null, null, null);
verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", null, null, 0,
Map.of("overwrite:header.x-example", "old"), null);
Map.of("overwrite:header.x-example", "old"), null, null);
}
private static final String NO_VALUE_SETTINGS = """
@@ -1049,7 +1072,7 @@ class ApiGatewayV2CfnProvisionerTest {
"test-stack", "int-1", Map.of("IntegrationId", "int-1"));
assertTrue(resource.getStatus().endsWith("_COMPLETE"), resource.getStatus());
verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", null, null, 0, null, null);
verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", null, null, 0, null, null, null);
}
@Test
@@ -1061,7 +1084,7 @@ class ApiGatewayV2CfnProvisionerTest {
"test-stack", "int-1", Map.of("IntegrationId", "int-1"));
verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", "ANY", null, 15000,
null, null);
null, null, null);
}
@Test
@@ -50,7 +50,6 @@ AWS::ApiGatewayV2::Integration ContentHandlingStrategy accepted and ignored
AWS::ApiGatewayV2::Integration CredentialsArn accepted and ignored
AWS::ApiGatewayV2::Integration Description accepted and ignored
AWS::ApiGatewayV2::Integration PassthroughBehavior accepted and ignored
AWS::ApiGatewayV2::Integration ResponseParameters accepted and ignored
AWS::ApiGatewayV2::Integration TlsConfig accepted and ignored
AWS::ApiGatewayV2::Route ApiKeyRequired accepted and ignored
AWS::ApiGatewayV2::Route ModelSelectionExpression accepted and ignored
1 AWS::ApiGateway::ApiKey StageKeys accepted and ignored, as the ApiGatewayApiKeyCfnProvisioner javadoc records
50 AWS::ApiGatewayV2::Integration CredentialsArn accepted and ignored
51 AWS::ApiGatewayV2::Integration Description accepted and ignored
52 AWS::ApiGatewayV2::Integration PassthroughBehavior accepted and ignored
AWS::ApiGatewayV2::Integration ResponseParameters accepted and ignored
53 AWS::ApiGatewayV2::Integration TlsConfig accepted and ignored
54 AWS::ApiGatewayV2::Route ApiKeyRequired accepted and ignored
55 AWS::ApiGatewayV2::Route ModelSelectionExpression accepted and ignored