mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(apigatewayv2): store and apply integration ResponseParameters (#9090)
This commit is contained in:
1 parent
7b88a31956
commit
d427b31e07
15 files changed
+693
-32
No files matched your search
@@ -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));
|
||||
}
|
||||
}
|
||||
+43
-1
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user