mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(apigatewayv2): resolve body, stage and context sources in HTTP_PROXY parameter mapping (#8062)
HTTP_PROXY request parameter mappings on HTTP APIs now read $request.body, $request.body.<JSONPath>, $stageVariables.<name> and $context.<name>, the sources the AWS service integration subtypes already read, resolved by ContextValueResolver for both integration types. A header mapping that carries a control character is refused with 502 before anything reaches the backend, and an overwrite:path reads each embedded source expression whole, bracketed JSONPath selectors included. Signed-off-by: Tyler Webb <tyler.webb@verkada.com>
This commit is contained in:
1 parent
0999528349
commit
63124253f2
13 files changed
+620
-118
No files matched your search
@@ -847,6 +847,25 @@ authorizer's context into request headers, query strings, and paths. For a retur
|
||||
`requestParameters`. String, numeric, and boolean context values are rendered as
|
||||
text. This works with format `1.0` policy responses and format `2.0` simple responses.
|
||||
|
||||
HTTP API `HTTP_PROXY` header, query string and path mappings also read `$request.body`,
|
||||
`$request.body.<JSONPath>`, `$stageVariables.<name>` and the `$context` variables `accountId`,
|
||||
`apiId`, `domainName`, `domainPrefix`, `extendedRequestId`, `httpMethod`, `path`, `protocol`,
|
||||
`requestTime`, `requestTimeEpoch`, `routeKey` and `stage`, alongside `requestId`,
|
||||
`identity.sourceIp` and the authorizer values above. A JSONPath that selects a scalar maps its text,
|
||||
and one that selects an object or array maps its JSON. A missing field, an empty body or a body
|
||||
that is not JSON resolves to nothing, so that header or query mapping is skipped, and the same
|
||||
expression embedded in an `overwrite:path` value such as `/orders/$request.body.order.id` becomes
|
||||
an empty string. Floci evaluates the whole body, where AWS reads only its first 100 KB.
|
||||
An expression embedded in a path is read whole before it is resolved: a body JSONPath takes dotted
|
||||
names, `[n]` indexes and `['key']` selectors, so `/orders/$request.body.items[0].id` selects the
|
||||
first item's `id`, a stage variable name ends at the first character that is not a letter, digit or
|
||||
underscore, and a `$request.path`, `$request.header` or `$request.querystring` name ends at the next
|
||||
`.`, so `/files/$request.path.name.json` keeps its `.json` suffix. A header value mapped from any
|
||||
source, including the whole `$request.body`, is rejected when it contains CR, LF, NUL or any other
|
||||
control character besides tab, as is a mapped `Host`: the request never reaches the backend and the
|
||||
caller receives `502` with
|
||||
`{"message":"Bad Gateway: invalid request header value for <name>"}`.
|
||||
|
||||
HTTP API `AWS_PROXY` integrations accept every `integrationSubtype` AWS defines:
|
||||
`EventBridge-PutEvents`, `SQS-SendMessage`, `SQS-ReceiveMessage`, `SQS-DeleteMessage`,
|
||||
`SQS-PurgeQueue`, `AppConfig-GetConfiguration`, `Kinesis-PutRecord`,
|
||||
|
||||
@@ -2935,7 +2935,7 @@ public class ApiGatewayExecuteController {
|
||||
|
||||
if ("HTTP_PROXY".equalsIgnoreCase(integrationType)) {
|
||||
return dispatchHttpProxyV2(integration, route, httpMethod, path, headers, uriInfo, body,
|
||||
apiId, stageName, jwtClaims, lambdaAuthorizerContext, region);
|
||||
apiId, stageName, stageVariables, jwtClaims, lambdaAuthorizerContext, region);
|
||||
}
|
||||
|
||||
if (integration.getIntegrationSubtype() != null && !integration.getIntegrationSubtype().isEmpty()) {
|
||||
@@ -3016,29 +3016,16 @@ public class ApiGatewayExecuteController {
|
||||
route.getRouteKey(), requestId, routeContext.sourceIp(),
|
||||
requestHeaders, queryParams, pathParams, body, claims, authorizerContext);
|
||||
|
||||
Instant requestTime = routeContext.requestTime();
|
||||
String hostRegion = region != null ? region : regionResolver.getDefaultRegion();
|
||||
String domain = restDomainName(apiId, hostRegion, headers);
|
||||
Map<String, String> contextVariables = new LinkedHashMap<>();
|
||||
contextVariables.put("accountId", regionResolver.getAccountId());
|
||||
contextVariables.put("apiId", apiId);
|
||||
contextVariables.put("domainName", domain);
|
||||
contextVariables.put("domainPrefix", domain.split("\\.")[0]);
|
||||
contextVariables.put("extendedRequestId", routeContext.extendedRequestId());
|
||||
contextVariables.put("httpMethod", httpMethod);
|
||||
contextVariables.put("path", ("$default".equals(stageName) ? "" : "/" + stageName) + path);
|
||||
contextVariables.put("protocol", "HTTP/1.1");
|
||||
contextVariables.put("requestTime", GATEWAY_REQUEST_TIME.format(requestTime.atZone(ZoneOffset.UTC)));
|
||||
contextVariables.put("requestTimeEpoch", Long.toString(requestTime.toEpochMilli()));
|
||||
contextVariables.put("routeKey", route.getRouteKey());
|
||||
contextVariables.put("stage", stageName);
|
||||
Map<String, String> contextVariables =
|
||||
httpApiContextVariables(apiId, stageName, httpMethod, path, route, hostRegion, headers);
|
||||
|
||||
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → {4}", httpMethod, apiId, stageName, path,
|
||||
subtype.subtypeName());
|
||||
|
||||
try {
|
||||
Map<String, String> parameters = awsServiceIntegrationMapper.resolveParameters(subtype,
|
||||
integration.getRequestParameters(), ctx, stageVariables, contextVariables);
|
||||
integration.getRequestParameters(), ctx.withVariables(stageVariables, contextVariables));
|
||||
String serviceRegion = parameters.get(IntegrationSubtype.REGION_PARAMETER);
|
||||
if (serviceRegion == null || serviceRegion.isEmpty()) {
|
||||
serviceRegion = hostRegion;
|
||||
@@ -3060,6 +3047,28 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
}
|
||||
|
||||
/** The {@code $context.<name>} values an HTTP API parameter mapping can read for this request. */
|
||||
private Map<String, String> httpApiContextVariables(String apiId, String stageName, String httpMethod,
|
||||
String path, Route route, String region,
|
||||
HttpHeaders headers) {
|
||||
Instant requestTime = routeContext.requestTime();
|
||||
String domain = restDomainName(apiId, region, headers);
|
||||
Map<String, String> contextVariables = new LinkedHashMap<>();
|
||||
contextVariables.put("accountId", regionResolver.getAccountId());
|
||||
contextVariables.put("apiId", apiId);
|
||||
contextVariables.put("domainName", domain);
|
||||
contextVariables.put("domainPrefix", domain.split("\\.")[0]);
|
||||
contextVariables.put("extendedRequestId", routeContext.extendedRequestId());
|
||||
contextVariables.put("httpMethod", httpMethod);
|
||||
contextVariables.put("path", ("$default".equals(stageName) ? "" : "/" + stageName) + path);
|
||||
contextVariables.put("protocol", "HTTP/1.1");
|
||||
contextVariables.put("requestTime", GATEWAY_REQUEST_TIME.format(requestTime.atZone(ZoneOffset.UTC)));
|
||||
contextVariables.put("requestTimeEpoch", Long.toString(requestTime.toEpochMilli()));
|
||||
contextVariables.put("routeKey", route.getRouteKey());
|
||||
contextVariables.put("stage", stageName);
|
||||
return contextVariables;
|
||||
}
|
||||
|
||||
private Response awsServiceErrorV2(String code, String message, int status, String requestId) {
|
||||
return Response.status(status)
|
||||
.entity(awsServiceIntegrationMapper.actionError(code, message, status, requestId).toString())
|
||||
@@ -3080,8 +3089,8 @@ public class ApiGatewayExecuteController {
|
||||
private Response dispatchHttpProxyV2(io.floci.aws.services.apigatewayv2.model.Integration integration,
|
||||
Route route, String httpMethod, String path,
|
||||
HttpHeaders headers, UriInfo uriInfo, byte[] body,
|
||||
String apiId, String stageName, Map<String, String> jwtClaims,
|
||||
ObjectNode lambdaAuthorizerContext,
|
||||
String apiId, String stageName, Map<String, String> stageVariables,
|
||||
Map<String, String> jwtClaims, ObjectNode lambdaAuthorizerContext,
|
||||
String region) {
|
||||
// CDK HttpAlbIntegration sets integrationUri to an ALB listener ARN. Resolve it
|
||||
// to the listener's bound localhost port so HttpProxyInvoker (which assumes a
|
||||
@@ -3174,7 +3183,9 @@ public class ApiGatewayExecuteController {
|
||||
pathParams.getOrDefault("proxy", ""), route.getRouteKey(),
|
||||
UUID.randomUUID().toString(), sourceIp,
|
||||
requestHeaders, queryParams, pathParams, body,
|
||||
claims, authorizerContext, backendHeaders, multiValueQueryParams, rawPathParams);
|
||||
claims, authorizerContext, backendHeaders, multiValueQueryParams, rawPathParams)
|
||||
.withVariables(stageVariables, httpApiContextVariables(apiId, stageName, httpMethod, path,
|
||||
route, region != null ? region : regionResolver.getDefaultRegion(), headers));
|
||||
|
||||
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → HTTP_PROXY {4}",
|
||||
httpMethod, apiId, stageName, path, effective.getIntegrationUri());
|
||||
|
||||
+15
-76
@@ -7,15 +7,9 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.databind.node.TextNode;
|
||||
import com.jayway.jsonpath.Configuration;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.jayway.jsonpath.JsonPathException;
|
||||
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
|
||||
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.apigatewayv2.model.IntegrationSubtype;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -28,10 +22,8 @@ import java.util.regex.Pattern;
|
||||
*
|
||||
* <p>A parameter value is a static string, a whole source expression such as
|
||||
* {@code $request.body}, or a string with source expressions embedded as {@code ${request.header.X}}.
|
||||
* Beyond the sources {@link ContextValueResolver} reads, it resolves {@code $request.body},
|
||||
* {@code $request.body.<JSONPath>}, {@code $stageVariables.<name>} and the {@code $context.<name>}
|
||||
* values the caller supplies. An embedded expression that resolves to nothing is replaced by the
|
||||
* empty string.
|
||||
* Expressions resolve through {@link ContextValueResolver}. An embedded expression that resolves to
|
||||
* nothing is replaced by the empty string.
|
||||
*/
|
||||
public class AwsServiceIntegrationMapper {
|
||||
|
||||
@@ -45,15 +37,11 @@ public class AwsServiceIntegrationMapper {
|
||||
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final Configuration jsonPathConfiguration;
|
||||
private final ContextValueResolver contextValueResolver = new ContextValueResolver();
|
||||
private final ContextValueResolver contextValueResolver;
|
||||
|
||||
public AwsServiceIntegrationMapper(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.jsonPathConfiguration = Configuration.builder()
|
||||
.jsonProvider(new JacksonJsonNodeJsonProvider(objectMapper))
|
||||
.mappingProvider(new JacksonMappingProvider(objectMapper))
|
||||
.build();
|
||||
this.contextValueResolver = new ContextValueResolver(objectMapper);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,20 +49,17 @@ public class AwsServiceIntegrationMapper {
|
||||
* whose value is a JSON object is parsed before anything is resolved, and expressions are
|
||||
* resolved only inside its string values, so a request value cannot add or change members. A
|
||||
* JSON parameter that is neither a whole source expression nor a JSON object is an
|
||||
* {@code InvalidParameterValue} error. {@code contextVariables} holds the
|
||||
* {@code $context.<name>} values of this request.
|
||||
* {@code InvalidParameterValue} error.
|
||||
*/
|
||||
public Map<String, String> resolveParameters(IntegrationSubtype subtype, Map<String, String> parameters,
|
||||
RequestContext ctx, Map<String, String> stageVariables,
|
||||
Map<String, String> contextVariables) {
|
||||
RequestContext ctx) {
|
||||
Map<String, String> resolved = new LinkedHashMap<>();
|
||||
if (parameters == null) {
|
||||
return resolved;
|
||||
}
|
||||
Sources sources = new Sources(ctx, stageVariables, contextVariables);
|
||||
parameters.forEach((name, value) -> {
|
||||
if (!subtype.isJsonParameter(name) || value == null || isWholeExpression(value)) {
|
||||
resolved.put(name, resolveValue(value, sources));
|
||||
resolved.put(name, resolveValue(value, ctx));
|
||||
return;
|
||||
}
|
||||
JsonNode template = jsonTemplate(value);
|
||||
@@ -82,7 +67,7 @@ public class AwsServiceIntegrationMapper {
|
||||
throw new AwsException("InvalidParameterValue",
|
||||
"Value for parameter " + name + " is invalid. Reason: Must be a JSON object.", 400);
|
||||
}
|
||||
resolved.put(name, resolveLeaves(template, sources).toString());
|
||||
resolved.put(name, resolveLeaves(template, ctx).toString());
|
||||
});
|
||||
return resolved;
|
||||
}
|
||||
@@ -152,9 +137,6 @@ public class AwsServiceIntegrationMapper {
|
||||
|| EMBEDDED_EXPRESSION.matcher(value).matches();
|
||||
}
|
||||
|
||||
private record Sources(RequestContext ctx, Map<String, String> stageVariables,
|
||||
Map<String, String> contextVariables) {}
|
||||
|
||||
private static JsonNode jsonTemplate(String value) {
|
||||
try {
|
||||
JsonNode node = TEMPLATE_READER.readTree(value);
|
||||
@@ -164,84 +146,41 @@ public class AwsServiceIntegrationMapper {
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode resolveLeaves(JsonNode node, Sources sources) {
|
||||
private JsonNode resolveLeaves(JsonNode node, RequestContext ctx) {
|
||||
if (node.isTextual()) {
|
||||
String resolved = resolveValue(node.asText(), sources);
|
||||
String resolved = resolveValue(node.asText(), ctx);
|
||||
return TextNode.valueOf(resolved != null ? resolved : "");
|
||||
}
|
||||
if (node.isObject()) {
|
||||
ObjectNode copy = objectMapper.createObjectNode();
|
||||
node.properties().forEach(e -> copy.set(e.getKey(), resolveLeaves(e.getValue(), sources)));
|
||||
node.properties().forEach(e -> copy.set(e.getKey(), resolveLeaves(e.getValue(), ctx)));
|
||||
return copy;
|
||||
}
|
||||
if (node.isArray()) {
|
||||
ArrayNode copy = objectMapper.createArrayNode();
|
||||
node.forEach(element -> copy.add(resolveLeaves(element, sources)));
|
||||
node.forEach(element -> copy.add(resolveLeaves(element, ctx)));
|
||||
return copy;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private String resolveValue(String value, Sources sources) {
|
||||
private String resolveValue(String value, RequestContext ctx) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (value.startsWith("$") && !value.startsWith("${")) {
|
||||
return resolveExpression(value, sources);
|
||||
return contextValueResolver.resolve(value, ctx);
|
||||
}
|
||||
Matcher m = EMBEDDED_EXPRESSION.matcher(value);
|
||||
StringBuilder out = new StringBuilder();
|
||||
while (m.find()) {
|
||||
String resolved = resolveExpression("$" + m.group(1), sources);
|
||||
String resolved = contextValueResolver.resolve("$" + m.group(1), ctx);
|
||||
m.appendReplacement(out, Matcher.quoteReplacement(resolved != null ? resolved : ""));
|
||||
}
|
||||
m.appendTail(out);
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private String resolveExpression(String expression, Sources sources) {
|
||||
RequestContext ctx = sources.ctx();
|
||||
if (expression.equals(BODY)) {
|
||||
return bodyText(ctx);
|
||||
}
|
||||
if (expression.startsWith(BODY + ".")) {
|
||||
return bodyPath(ctx, expression.substring(BODY.length() + 1));
|
||||
}
|
||||
if (expression.startsWith(STAGE_VARIABLES)) {
|
||||
Map<String, String> stageVariables = sources.stageVariables();
|
||||
return stageVariables == null ? null : stageVariables.get(expression.substring(STAGE_VARIABLES.length()));
|
||||
}
|
||||
if (expression.startsWith(CONTEXT) && sources.contextVariables() != null) {
|
||||
String value = sources.contextVariables().get(expression.substring(CONTEXT.length()));
|
||||
if (value != null) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return contextValueResolver.resolve(expression, ctx);
|
||||
}
|
||||
|
||||
private static String bodyText(RequestContext ctx) {
|
||||
return ctx.body() == null ? "" : new String(ctx.body(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private String bodyPath(RequestContext ctx, String path) {
|
||||
String body = bodyText(ctx);
|
||||
if (body.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
JsonNode value;
|
||||
try {
|
||||
Object read = JsonPath.using(jsonPathConfiguration).parse(body).read("$." + path);
|
||||
value = read instanceof JsonNode node ? node : objectMapper.valueToTree(read);
|
||||
} catch (JsonPathException | IllegalArgumentException | ClassCastException e) {
|
||||
return null;
|
||||
}
|
||||
if (value == null || value.isNull() || value.isMissingNode()) {
|
||||
return null;
|
||||
}
|
||||
return value.isValueNode() ? value.asText() : value.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The action's JSON input from the resolved parameters. A required parameter that resolved to
|
||||
* nothing is a {@code MissingParameter} error, an optional one is left out, and {@code Region}
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
package io.floci.aws.services.apigatewayv2.proxy;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.jayway.jsonpath.Configuration;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
import com.jayway.jsonpath.JsonPathException;
|
||||
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
|
||||
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
@@ -10,22 +19,55 @@ import java.util.Map;
|
||||
*
|
||||
* <p>Supported expressions:
|
||||
* <ul>
|
||||
* <li>{@code $context.authorizer.claims.<name>} — JWT claim from authorizer</li>
|
||||
* <li>{@code $context.authorizer.<name>} — authorizer context value</li>
|
||||
* <li>{@code $context.requestId} — UUID assigned per request</li>
|
||||
* <li>{@code $context.identity.sourceIp} — client IP</li>
|
||||
* <li>{@code $request.header.<name>} — case-insensitive header lookup</li>
|
||||
* <li>{@code $request.querystring.<name>} — query parameter</li>
|
||||
* <li>{@code $request.path.<name>} — captured path parameter</li>
|
||||
* <li>literal strings — returned unchanged</li>
|
||||
* <li>{@code $context.authorizer.claims.<name>}: JWT claim from authorizer</li>
|
||||
* <li>{@code $context.authorizer.<name>}: authorizer context value</li>
|
||||
* <li>{@code $context.requestId}: UUID assigned per request</li>
|
||||
* <li>{@code $context.identity.sourceIp}: client IP</li>
|
||||
* <li>{@code $context.<name>}: any other context variable the request carries</li>
|
||||
* <li>{@code $request.header.<name>}: case-insensitive header lookup</li>
|
||||
* <li>{@code $request.querystring.<name>}: query parameter</li>
|
||||
* <li>{@code $request.path.<name>}: captured path parameter</li>
|
||||
* <li>{@code $request.body}: the request body as text, null when it is empty</li>
|
||||
* <li>{@code $request.body.<JSONPath>}: a value selected from a JSON request body</li>
|
||||
* <li>{@code $stageVariables.<name>}: stage variable</li>
|
||||
* <li>literal strings: returned unchanged</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class ContextValueResolver {
|
||||
|
||||
private static final String BODY = "$request.body";
|
||||
private static final String STAGE_VARIABLES = "$stageVariables.";
|
||||
private static final String CONTEXT = "$context.";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final Configuration jsonPathConfiguration;
|
||||
|
||||
public ContextValueResolver() {
|
||||
this(new ObjectMapper());
|
||||
}
|
||||
|
||||
public ContextValueResolver(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.jsonPathConfiguration = Configuration.builder()
|
||||
.jsonProvider(new JacksonJsonNodeJsonProvider(objectMapper))
|
||||
.mappingProvider(new JacksonMappingProvider(objectMapper))
|
||||
.build();
|
||||
}
|
||||
|
||||
public String resolve(String expression, RequestContext ctx) {
|
||||
if (expression == null) return null;
|
||||
if (!expression.startsWith("$")) return expression;
|
||||
|
||||
if (expression.equals(BODY)) {
|
||||
return bodyText(ctx);
|
||||
}
|
||||
if (expression.startsWith(BODY + ".")) {
|
||||
return bodyPath(ctx, expression.substring(BODY.length() + 1));
|
||||
}
|
||||
if (expression.startsWith(STAGE_VARIABLES)) {
|
||||
Map<String, String> stageVariables = ctx.stageVariables();
|
||||
return stageVariables == null ? null : stageVariables.get(expression.substring(STAGE_VARIABLES.length()));
|
||||
}
|
||||
if (expression.startsWith("$context.authorizer.claims.")) {
|
||||
String claim = expression.substring("$context.authorizer.claims.".length());
|
||||
Object v = ctx.authorizerClaims() == null ? null : ctx.authorizerClaims().get(claim);
|
||||
@@ -38,6 +80,10 @@ public class ContextValueResolver {
|
||||
}
|
||||
if (expression.equals("$context.requestId")) return ctx.requestId();
|
||||
if (expression.equals("$context.identity.sourceIp")) return ctx.sourceIp();
|
||||
if (expression.startsWith(CONTEXT)) {
|
||||
Map<String, String> contextVariables = ctx.contextVariables();
|
||||
return contextVariables == null ? null : contextVariables.get(expression.substring(CONTEXT.length()));
|
||||
}
|
||||
if (expression.startsWith("$request.header.")) {
|
||||
String name = expression.substring("$request.header.".length());
|
||||
return getCaseInsensitive(ctx.requestHeaders(), name);
|
||||
@@ -53,6 +99,28 @@ public class ContextValueResolver {
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String bodyText(RequestContext ctx) {
|
||||
return ctx.body() == null || ctx.body().length == 0 ? null : new String(ctx.body(), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private String bodyPath(RequestContext ctx, String path) {
|
||||
String body = bodyText(ctx);
|
||||
if (body == null || body.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
JsonNode value;
|
||||
try {
|
||||
Object read = JsonPath.using(jsonPathConfiguration).parse(body).read("$." + path);
|
||||
value = read instanceof JsonNode node ? node : objectMapper.valueToTree(read);
|
||||
} catch (JsonPathException | IllegalArgumentException | ClassCastException e) {
|
||||
return null;
|
||||
}
|
||||
if (value == null || value.isNull() || value.isMissingNode()) {
|
||||
return null;
|
||||
}
|
||||
return value.isValueNode() ? value.asText() : value.toString();
|
||||
}
|
||||
|
||||
private static String getCaseInsensitive(Map<String, String> headers, String name) {
|
||||
if (headers == null) return null;
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
|
||||
@@ -49,8 +49,10 @@ import java.util.StringJoiner;
|
||||
* request and the response. Java's HttpClient also restricts certain headers
|
||||
* (Content-Length, etc.) — those are skipped silently.
|
||||
*
|
||||
* <p>If the backend is unreachable or times out, returns a 502 Bad Gateway
|
||||
* ProxyResult so the controller can relay a clean error to the original client.
|
||||
* <p>If the backend is unreachable or times out, or a mapped header name or value cannot be
|
||||
* written as a single header line (a control character such as CR or LF in a value mapped from the
|
||||
* caller's request), returns a 502 Bad Gateway ProxyResult so the controller can relay a clean
|
||||
* error to the original client. Nothing is sent to the backend in the header case.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class HttpProxyInvoker {
|
||||
@@ -357,6 +359,9 @@ public class HttpProxyInvoker {
|
||||
if (pinned) {
|
||||
try {
|
||||
return invokeHttpPinned(finalUrl, method, builder, options.timeout());
|
||||
} catch (PinnedHttpClient.InvalidRequestHeaderException e) {
|
||||
LOG.warnv("HTTP_PROXY: {0}", e.getMessage());
|
||||
return errorResult("Bad Gateway: " + e.getMessage());
|
||||
} catch (PinnedHttpClient.ResponseTooLargeException ignored) {
|
||||
return tooLargeResult();
|
||||
} catch (Exception e) {
|
||||
@@ -385,11 +390,20 @@ public class HttpProxyInvoker {
|
||||
: HttpRequest.BodyPublishers.noBody());
|
||||
}
|
||||
|
||||
for (Map.Entry<String, List<String>> e : builder.headers().entrySet()) {
|
||||
if (RESTRICTED.contains(e.getKey().toLowerCase())) continue;
|
||||
for (String v : e.getValue()) {
|
||||
hrb.header(e.getKey(), v);
|
||||
try {
|
||||
for (Map.Entry<String, List<String>> e : builder.headers().entrySet()) {
|
||||
if (RESTRICTED.contains(e.getKey().toLowerCase())) continue;
|
||||
for (String v : e.getValue()) {
|
||||
PinnedHttpClient.requireValidHeader(e.getKey(), v);
|
||||
hrb.header(e.getKey(), v);
|
||||
}
|
||||
}
|
||||
} catch (PinnedHttpClient.InvalidRequestHeaderException e) {
|
||||
LOG.warnv("HTTP_PROXY: {0}", e.getMessage());
|
||||
return errorResult("Bad Gateway: " + e.getMessage());
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOG.warnv("HTTP_PROXY: invalid request header: {0}", e.getMessage());
|
||||
return errorResult("Bad Gateway: invalid request header");
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -16,6 +16,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Sends one plain-HTTP request to an already checked {@link InetAddress} and reads the response
|
||||
@@ -49,6 +50,12 @@ public final class PinnedHttpClient {
|
||||
private static final Set<String> BODYLESS_METHODS =
|
||||
Set.of("GET", "HEAD", "OPTIONS", "DELETE", "TRACE");
|
||||
|
||||
/** An RFC 9110 field name: a token, so it cannot carry a separator or a line break. */
|
||||
private static final Pattern HEADER_NAME = Pattern.compile("[!#$%&'*+.^_`|~0-9A-Za-z-]+");
|
||||
|
||||
private static final char HORIZONTAL_TAB = '\t';
|
||||
private static final char DELETE = 0x7F;
|
||||
|
||||
private PinnedHttpClient() {
|
||||
}
|
||||
|
||||
@@ -66,6 +73,39 @@ public final class PinnedHttpClient {
|
||||
}
|
||||
}
|
||||
|
||||
/** Raised before anything is sent when a request header would not stay a single header line. */
|
||||
public static final class InvalidRequestHeaderException extends IOException {
|
||||
public InvalidRequestHeaderException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Mapped values can come from the caller's request body or query string, so writing them as
|
||||
* given would let a caller add header lines of its own or smuggle a second request. The
|
||||
* messages name the header but never echo the value.
|
||||
*
|
||||
* @param name the header name
|
||||
* @param value the header value
|
||||
* @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()) {
|
||||
throw new InvalidRequestHeaderException("invalid request header name");
|
||||
}
|
||||
if (value == null) {
|
||||
throw new InvalidRequestHeaderException("invalid request header value for " + name);
|
||||
}
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char c = value.charAt(i);
|
||||
if ((c < ' ' && c != HORIZONTAL_TAB) || c == DELETE) {
|
||||
throw new InvalidRequestHeaderException("invalid request header value for " + name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to {@code address} and exchanges one request/response pair.
|
||||
*
|
||||
@@ -77,6 +117,8 @@ public final class PinnedHttpClient {
|
||||
* because this client writes them itself
|
||||
* @param body the request body, may be null or empty
|
||||
* @param timeout how long to wait for the backend to respond
|
||||
* @throws InvalidRequestHeaderException before connecting, when the Host header or any header
|
||||
* that would be written fails {@link #requireValidHeader}
|
||||
*/
|
||||
public static Response send(InetAddress address, URI target, String method, String hostHeader,
|
||||
Map<String, List<String>> headers, byte[] body, Duration timeout)
|
||||
@@ -84,6 +126,10 @@ public final class PinnedHttpClient {
|
||||
byte[] payload = body == null ? new byte[0] : body;
|
||||
String upperMethod = method.toUpperCase(Locale.ROOT);
|
||||
int port = target.getPort() == -1 ? DEFAULT_HTTP_PORT : target.getPort();
|
||||
if (hostHeader != null) {
|
||||
requireValidHeader("Host", hostHeader);
|
||||
}
|
||||
requireValidHeaders(headers);
|
||||
|
||||
try (Socket socket = new Socket()) {
|
||||
socket.connect(new InetSocketAddress(address, port), CONNECT_TIMEOUT_MILLIS);
|
||||
@@ -102,6 +148,21 @@ public final class PinnedHttpClient {
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireValidHeaders(Map<String, List<String>> headers)
|
||||
throws InvalidRequestHeaderException {
|
||||
if (headers == null) {
|
||||
return;
|
||||
}
|
||||
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
|
||||
if (CLIENT_OWNED_HEADERS.contains(header.getKey().toLowerCase(Locale.ROOT))) {
|
||||
continue;
|
||||
}
|
||||
for (String value : header.getValue()) {
|
||||
requireValidHeader(header.getKey(), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The authority to advertise as Host, without any {@code user:pass@} the URI carries. */
|
||||
private static String hostAndPort(URI target) {
|
||||
String host = target.getHost();
|
||||
|
||||
@@ -26,6 +26,9 @@ import java.util.Map;
|
||||
* tell {@code %2F} from {@code /}. It may be null, lack a parameter that did not come from the
|
||||
* request path, or hold a value that does not decode to the parameter's, and
|
||||
* {@link #targetPathParams()} encodes the decoded value in those cases.
|
||||
*
|
||||
* <p>{@code stageVariables} and {@code contextVariables} hold what {@code $stageVariables.X} and
|
||||
* {@code $context.X} resolve against. Either may be null when the caller has none to offer.
|
||||
*/
|
||||
public record RequestContext(
|
||||
String apiId,
|
||||
@@ -44,7 +47,22 @@ public record RequestContext(
|
||||
Map<String, Object> authorizerContext,
|
||||
Map<String, List<String>> multiValueHeaders,
|
||||
Map<String, List<String>> multiValueQueryParams,
|
||||
Map<String, String> rawPathParams) {
|
||||
Map<String, String> rawPathParams,
|
||||
Map<String, String> stageVariables,
|
||||
Map<String, String> contextVariables) {
|
||||
|
||||
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,
|
||||
Map<String, List<String>> multiValueHeaders,
|
||||
Map<String, List<String>> multiValueQueryParams,
|
||||
Map<String, String> rawPathParams) {
|
||||
this(apiId, stageName, httpMethod, path, proxy, routeKey, requestId, sourceIp,
|
||||
requestHeaders, queryParams, pathParams, body, authorizerClaims, authorizerContext,
|
||||
multiValueHeaders, multiValueQueryParams, rawPathParams, null, null);
|
||||
}
|
||||
|
||||
public RequestContext(String apiId, String stageName, String httpMethod, String path, String proxy,
|
||||
String routeKey, String requestId, String sourceIp,
|
||||
@@ -73,6 +91,13 @@ public record RequestContext(
|
||||
expand(requestHeaders), expand(queryParams));
|
||||
}
|
||||
|
||||
/** A copy of this context carrying the given stage and context variables. */
|
||||
public RequestContext withVariables(Map<String, String> stageVariables, Map<String, String> contextVariables) {
|
||||
return new RequestContext(apiId, stageName, httpMethod, path, proxy, routeKey, requestId, sourceIp,
|
||||
requestHeaders, queryParams, pathParams, body, authorizerClaims, authorizerContext,
|
||||
multiValueHeaders, multiValueQueryParams, rawPathParams, stageVariables, contextVariables);
|
||||
}
|
||||
|
||||
/** The path parameters as they go into the target URL, every value percent-encoded. */
|
||||
public Map<String, String> targetPathParams() {
|
||||
if (pathParams == null) {
|
||||
|
||||
@@ -17,17 +17,31 @@ import java.util.regex.Pattern;
|
||||
* <li>{@code sourceValue} is a literal or expression resolved by {@link ContextValueResolver}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>For {@code overwrite:path}, the source value may contain embedded
|
||||
* {@code $request.path.X} / {@code $context.X} substrings which are resolved in-place. They land in
|
||||
* <p>For {@code overwrite:path}, the source value may contain embedded expressions such as
|
||||
* {@code $request.path.X}, {@code $request.body.X}, {@code $stageVariables.X} or {@code $context.X},
|
||||
* which are resolved in-place; one that resolves to nothing becomes the empty string. They land in
|
||||
* a URL, so a path parameter keeps the caller's encoding and any other value is percent-encoded.
|
||||
* Each embedded expression is read whole before it is resolved: a body JSONPath runs through dotted
|
||||
* names, {@code [n]} indexes and {@code ['key']} or {@code ["key"]} selectors, so
|
||||
* {@code /orders/$request.body.items[0].id} selects one item's id; a stage variable name runs
|
||||
* through letters, digits and underscores; a request path, header or query string name is a single
|
||||
* segment, so {@code /files/$request.path.name.json} keeps its {@code .json} suffix.
|
||||
*
|
||||
* <p>When a source resolves to {@code null} (missing claim, missing header, etc.),
|
||||
* overwrite/append actions are silently skipped to match AWS behavior. {@code remove}
|
||||
* is unconditional.
|
||||
*/
|
||||
public class RequestParameterMapper {
|
||||
private static final Pattern EMBEDDED_VAR =
|
||||
Pattern.compile("\\$[a-zA-Z]+(\\.[a-zA-Z][a-zA-Z0-9_-]*)+");
|
||||
private static final String NAME = "[A-Za-z0-9_-]+";
|
||||
private static final String JSON_PATH_SELECTOR = "\\[(?:-?[0-9]+|'[^'\\]]*'|\"[^\"\\]]*\")\\]";
|
||||
private static final String JSON_PATH_STEP = "\\.(?:" + NAME + "|" + JSON_PATH_SELECTOR + ")";
|
||||
private static final String JSON_PATH = JSON_PATH_STEP + "(?:" + JSON_PATH_STEP + "|" + JSON_PATH_SELECTOR + ")*";
|
||||
private static final Pattern EMBEDDED_VAR = Pattern.compile(
|
||||
"\\$request\\.body(?:" + JSON_PATH + "|(?![A-Za-z0-9_-]))"
|
||||
+ "|\\$request\\.(?:path|header|querystring)\\." + NAME
|
||||
+ "|\\$stageVariables\\.[A-Za-z0-9_]+"
|
||||
+ "|\\$context(?:\\." + NAME + ")+"
|
||||
+ "|\\$[A-Za-z]+(?:\\." + NAME + ")+");
|
||||
private static final String REQUEST_PATH_PREFIX = "$request.path.";
|
||||
|
||||
private final ContextValueResolver resolver;
|
||||
|
||||
@@ -2,6 +2,9 @@ package io.floci.aws.services.apigatewayv2;
|
||||
|
||||
import io.restassured.http.ContentType;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
|
||||
/** A deployed HTTP API whose one route is an {@code HTTP_PROXY} integration on a test's fixture backend. */
|
||||
@@ -16,15 +19,31 @@ public final class HttpProxyApiFixtures {
|
||||
* {@code http://127.0.0.1:backendPort path}; returns its id.
|
||||
*/
|
||||
public static String createProxyApi(String name, String apiFields, String stageName, int backendPort, String path) {
|
||||
return createProxyApi(name, apiFields, stageName, Map.of(), "GET", backendPort, path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an HTTP API as {@link #createProxyApi(String, String, String, int, String)} does, with
|
||||
* {@code stageVariables} on its stage and a {@code routeMethod path} route; returns its id.
|
||||
*/
|
||||
public static String createProxyApi(String name, String apiFields, String stageName,
|
||||
Map<String, String> stageVariables, String routeMethod, int backendPort,
|
||||
String path) {
|
||||
String apiId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"name\":\"" + name + "\",\"protocolType\":\"HTTP\"" + apiFields + "}")
|
||||
.when().post("/v2/apis")
|
||||
.then().statusCode(201)
|
||||
.extract().path("apiId");
|
||||
Map<String, Object> stage = new LinkedHashMap<>();
|
||||
stage.put("stageName", stageName);
|
||||
stage.put("autoDeploy", true);
|
||||
if (!stageVariables.isEmpty()) {
|
||||
stage.put("stageVariables", stageVariables);
|
||||
}
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"stageName\":\"" + stageName + "\",\"autoDeploy\":true}")
|
||||
.body(stage)
|
||||
.when().post("/v2/apis/" + apiId + "/stages")
|
||||
.then().statusCode(201);
|
||||
String integrationId = given()
|
||||
@@ -36,7 +55,8 @@ public final class HttpProxyApiFixtures {
|
||||
.extract().path("integrationId");
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("{\"routeKey\":\"GET " + path + "\",\"target\":\"integrations/" + integrationId + "\"}")
|
||||
.body("{\"routeKey\":\"" + routeMethod + " " + path + "\",\"target\":\"integrations/"
|
||||
+ integrationId + "\"}")
|
||||
.when().post("/v2/apis/" + apiId + "/routes")
|
||||
.then().statusCode(201);
|
||||
return apiId;
|
||||
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
package io.floci.aws.services.apigatewayv2;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
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 java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class HttpProxyRequestSourceMappingIntegrationTest {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final List<String> HEADERS = List.of("x-order", "x-backend", "x-stage", "x-route", "x-api",
|
||||
"x-account", "x-path", "x-epoch", "x-missing", "x-missing-stage");
|
||||
private final AtomicReference<JsonNode> received = new AtomicReference<>();
|
||||
private HttpServer backend;
|
||||
private String apiId;
|
||||
|
||||
@BeforeEach
|
||||
void startBackend() throws Exception {
|
||||
backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
backend.createContext("/", exchange -> {
|
||||
ObjectNode request = MAPPER.createObjectNode();
|
||||
for (String header : HEADERS) {
|
||||
request.put(header, exchange.getRequestHeaders().getFirst(header));
|
||||
}
|
||||
request.put("path", exchange.getRequestURI().getPath());
|
||||
request.put("query", exchange.getRequestURI().getRawQuery());
|
||||
received.set(request);
|
||||
byte[] bytes = "ok".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
exchange.close();
|
||||
});
|
||||
backend.start();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUp() {
|
||||
try {
|
||||
if (apiId != null) {
|
||||
given().delete("/v2/apis/" + apiId).then().statusCode(204);
|
||||
}
|
||||
} finally {
|
||||
if (backend != null) {
|
||||
backend.stop(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapsBodyStageVariablesAndContextToHeadersQueryAndPath() {
|
||||
configureApi();
|
||||
long before = System.currentTimeMillis();
|
||||
invoke("{\"order\":{\"id\":\"o-42\"}}");
|
||||
JsonNode request = received.get();
|
||||
assertNotNull(request);
|
||||
assertEquals("o-42", request.path("x-order").asText());
|
||||
assertEquals("blue", request.path("x-backend").asText());
|
||||
assertEquals("test", request.path("x-stage").asText());
|
||||
assertEquals("POST /orders", request.path("x-route").asText());
|
||||
assertEquals(apiId, request.path("x-api").asText());
|
||||
assertEquals("000000000000", request.path("x-account").asText());
|
||||
assertEquals("/test/orders", request.path("x-path").asText());
|
||||
assertTrue(Long.parseLong(request.path("x-epoch").asText()) >= before - 1000);
|
||||
assertTrue(request.path("x-missing").isNull());
|
||||
assertTrue(request.path("x-missing-stage").isNull());
|
||||
assertEquals("/orders/o-42/test", request.path("path").asText());
|
||||
assertEquals("order=o-42", request.path("query").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void bodyThatIsNotJsonSkipsBodyMappings() {
|
||||
configureApi();
|
||||
invoke("not json");
|
||||
JsonNode request = received.get();
|
||||
assertTrue(request.path("x-order").isNull());
|
||||
assertTrue(request.path("query").isNull());
|
||||
assertEquals("blue", request.path("x-backend").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void indexedBodyValueFillsAnEmbeddedPath() {
|
||||
configureApi(Map.of("overwrite:path", "/orders/$request.body.items[1].id/lines"));
|
||||
invoke("{\"items\":[{\"id\":\"i-1\"},{\"id\":\"i-2\"}]}");
|
||||
assertEquals("/orders/i-2/lines", received.get().path("path").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void wholeBodyCarryingALineBreakIsRejectedBeforeTheBackend() {
|
||||
configureApi(Map.of("overwrite:header.x-order", "$request.body"));
|
||||
invokeExpectingRejectedHeader("o-1\r\nX-Injected: 1", "x-order");
|
||||
}
|
||||
|
||||
@Test
|
||||
void wholeBodyCarryingALineBreakIsRejectedWhenTheHostIsMapped() {
|
||||
configureApi(Map.of("overwrite:header.Host", "orders.internal",
|
||||
"overwrite:header.x-order", "$request.body"));
|
||||
invokeExpectingRejectedHeader("o-1\r\nX-Injected: 1", "x-order");
|
||||
}
|
||||
|
||||
private void configureApi() {
|
||||
configureApi(Map.ofEntries(
|
||||
Map.entry("overwrite:header.x-order", "$request.body.order.id"),
|
||||
Map.entry("overwrite:header.x-backend", "$stageVariables.backend"),
|
||||
Map.entry("overwrite:header.x-stage", "$context.stage"),
|
||||
Map.entry("overwrite:header.x-route", "$context.routeKey"),
|
||||
Map.entry("overwrite:header.x-api", "$context.apiId"),
|
||||
Map.entry("overwrite:header.x-account", "$context.accountId"),
|
||||
Map.entry("overwrite:header.x-path", "$context.path"),
|
||||
Map.entry("overwrite:header.x-epoch", "$context.requestTimeEpoch"),
|
||||
Map.entry("overwrite:header.x-missing", "$request.body.order.missing"),
|
||||
Map.entry("overwrite:header.x-missing-stage", "$stageVariables.missing"),
|
||||
Map.entry("overwrite:querystring.order", "$request.body.order.id"),
|
||||
Map.entry("overwrite:path", "/orders/$request.body.order.id/$context.stage")));
|
||||
}
|
||||
|
||||
private void configureApi(Map<String, String> requestParameters) {
|
||||
apiId = HttpProxyApiFixtures.createProxyApi("request-source-mapping", "", "test", Map.of("backend", "blue"),
|
||||
"POST", backend.getAddress().getPort(), "/orders");
|
||||
String apiPath = "/v2/apis/" + apiId;
|
||||
String integrationId = given().get(apiPath + "/integrations").then().statusCode(200)
|
||||
.extract().path("items[0].integrationId");
|
||||
given().contentType(ContentType.JSON).body(Map.of("requestParameters", requestParameters))
|
||||
.patch(apiPath + "/integrations/" + integrationId).then().statusCode(200);
|
||||
}
|
||||
|
||||
private void invoke(String body) {
|
||||
given().contentType(ContentType.JSON).body(body)
|
||||
.post("/execute-api/" + apiId + "/test/orders").then().statusCode(200);
|
||||
}
|
||||
|
||||
private void invokeExpectingRejectedHeader(String body, String header) {
|
||||
given().contentType(ContentType.TEXT).body(body)
|
||||
.post("/execute-api/" + apiId + "/test/orders").then().statusCode(502)
|
||||
.body("message", equalTo("Bad Gateway: invalid request header value for " + header));
|
||||
assertNull(received.get());
|
||||
}
|
||||
}
|
||||
+67
-1
@@ -2,6 +2,7 @@ package io.floci.aws.services.apigatewayv2.proxy;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -9,7 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
/**
|
||||
* Verifies {@link ContextValueResolver} resolves the documented HTTP API v2
|
||||
* source value expressions: $context.*, $request.*, and literal pass-through.
|
||||
* source value expressions: $context.*, $request.*, $stageVariables.*, and literal pass-through.
|
||||
*/
|
||||
class ContextValueResolverTest {
|
||||
|
||||
@@ -20,6 +21,16 @@ class ContextValueResolverTest {
|
||||
"req-1", "1.2.3.4", headers, query, pathParams, null, claims, authContext);
|
||||
}
|
||||
|
||||
private RequestContext withBody(String body) {
|
||||
return new RequestContext("api1", "$default", "POST", "/foo", "foo", "POST /foo",
|
||||
"req-1", "1.2.3.4", Map.of(), Map.of(), Map.of(),
|
||||
body == null ? null : body.getBytes(StandardCharsets.UTF_8), Map.of(), Map.of());
|
||||
}
|
||||
|
||||
private RequestContext withVariables(Map<String, String> stageVariables, Map<String, String> contextVariables) {
|
||||
return ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of()).withVariables(stageVariables, contextVariables);
|
||||
}
|
||||
|
||||
@Test
|
||||
void literalValuePassesThrough() {
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
@@ -100,4 +111,59 @@ class ContextValueResolverTest {
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
assertNull(r.resolve(null, ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestBodyResolvesToTheWholeBody() {
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
assertEquals("{\"order\":{\"id\":\"o-42\"}}",
|
||||
r.resolve("$request.body", withBody("{\"order\":{\"id\":\"o-42\"}}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyRequestBodyReturnsNull() {
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
assertNull(r.resolve("$request.body", withBody(null)));
|
||||
assertNull(r.resolve("$request.body", withBody("")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestBodyPathResolvesScalarsAndJson() {
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
RequestContext c = withBody("{\"order\":{\"id\":\"o-42\",\"qty\":3,\"tags\":[\"a\",\"b\"]}}");
|
||||
assertEquals("o-42", r.resolve("$request.body.order.id", c));
|
||||
assertEquals("3", r.resolve("$request.body.order.qty", c));
|
||||
assertEquals("a", r.resolve("$request.body.order.tags[0]", c));
|
||||
assertEquals("[\"a\",\"b\"]", r.resolve("$request.body.order.tags", c));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestBodyPathMissingOrUnreadableReturnsNull() {
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
assertNull(r.resolve("$request.body.order.missing", withBody("{\"order\":{\"id\":\"o-42\"}}")));
|
||||
assertNull(r.resolve("$request.body.order.id", withBody("not json")));
|
||||
assertNull(r.resolve("$request.body.order.id", withBody(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stageVariableResolves() {
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
RequestContext c = withVariables(Map.of("backend", "blue"), null);
|
||||
assertEquals("blue", r.resolve("$stageVariables.backend", c));
|
||||
assertNull(r.resolve("$stageVariables.missing", c));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stageVariableWithoutStageVariablesReturnsNull() {
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
assertNull(r.resolve("$stageVariables.backend", ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void contextVariableResolves() {
|
||||
ContextValueResolver r = new ContextValueResolver();
|
||||
RequestContext c = withVariables(null, Map.of("stage", "prod", "routeKey", "ANY /foo"));
|
||||
assertEquals("prod", r.resolve("$context.stage", c));
|
||||
assertEquals("ANY /foo", r.resolve("$context.routeKey", c));
|
||||
assertNull(r.resolve("$context.unknown", c));
|
||||
}
|
||||
}
|
||||
@@ -501,4 +501,66 @@ class HttpProxyInvokerTest {
|
||||
assertEquals(502, result.statusCode());
|
||||
assertNull(received.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAWholeBodyMappingCarryingALineBreakToANamedHost() {
|
||||
HttpProxyInvoker invoker = new HttpProxyInvoker(
|
||||
host -> new InetAddress[] {InetAddress.getByAddress(new byte[] {127, 0, 0, 1})});
|
||||
Integration integration = httpProxyIntegration("http://named.example.test:" + backendPort + "/ok",
|
||||
Map.of("overwrite:header.x-payload", "$request.body"));
|
||||
RequestContext ctx = ctxFor("POST", "/wallet/x", "x", Map.of(), Map.of(),
|
||||
"a\r\nX-Injected: 1".getBytes(StandardCharsets.UTF_8), Map.of());
|
||||
|
||||
ProxyResult result = invoker.invoke(integration, ctx);
|
||||
|
||||
assertEquals(502, result.statusCode());
|
||||
assertEquals("{\"message\":\"Bad Gateway: invalid request header value for x-payload\"}",
|
||||
new String(result.body(), StandardCharsets.UTF_8));
|
||||
assertNull(received.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAMappedHostHeaderCarryingALineBreak() {
|
||||
Integration integration = httpProxyIntegration("http://127.0.0.1:" + backendPort + "/ok",
|
||||
Map.of("overwrite:header.Host", "$request.querystring.host"));
|
||||
RequestContext ctx = ctxFor("GET", "/wallet/x", "x", Map.of(),
|
||||
Map.of("host", "lb.localhost.test\r\nX-Injected: 1"), null, Map.of());
|
||||
|
||||
ProxyResult result = new HttpProxyInvoker().invoke(integration, ctx);
|
||||
|
||||
assertEquals(502, result.statusCode());
|
||||
assertEquals("{\"message\":\"Bad Gateway: invalid request header value for Host\"}",
|
||||
new String(result.body(), StandardCharsets.UTF_8));
|
||||
assertNull(received.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAMappedBodyFieldCarryingAControlCharacterToAnAddressTarget() {
|
||||
Integration integration = httpProxyIntegration("http://127.0.0.1:" + backendPort + "/ok",
|
||||
Map.of("overwrite:header.x-note", "$request.body.note"));
|
||||
for (String note : new String[] {"a\\r\\nX-Injected: 1", "a\\nb", "a\\u0000b", "a\\u007fb"}) {
|
||||
RequestContext ctx = ctxFor("POST", "/wallet/x", "x", Map.of(), Map.of(),
|
||||
("{\"note\":\"" + note + "\"}").getBytes(StandardCharsets.UTF_8), Map.of());
|
||||
|
||||
ProxyResult result = new HttpProxyInvoker().invoke(integration, ctx);
|
||||
|
||||
assertEquals(502, result.statusCode());
|
||||
assertEquals("{\"message\":\"Bad Gateway: invalid request header value for x-note\"}",
|
||||
new String(result.body(), StandardCharsets.UTF_8));
|
||||
assertNull(received.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void forwardsAMappedHeaderValueContainingATab() {
|
||||
Integration integration = httpProxyIntegration("http://127.0.0.1:" + backendPort + "/ok",
|
||||
Map.of("overwrite:header.x-note", "$request.body.note"));
|
||||
RequestContext ctx = ctxFor("POST", "/wallet/x", "x", Map.of(), Map.of(),
|
||||
"{\"note\":\"a\\tb\"}".getBytes(StandardCharsets.UTF_8), Map.of());
|
||||
|
||||
ProxyResult result = new HttpProxyInvoker().invoke(integration, ctx);
|
||||
|
||||
assertEquals(200, result.statusCode());
|
||||
assertTrue(received.get().headers().getFirst("x-note").matches("a[\\t ]b"));
|
||||
}
|
||||
}
|
||||
+48
@@ -3,6 +3,7 @@ package io.floci.aws.services.apigatewayv2.proxy;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -164,4 +165,51 @@ class RequestParameterMapperTest {
|
||||
|
||||
assertEquals("b c", builder.headers().get("x-name").get(0));
|
||||
}
|
||||
|
||||
private RequestContext withBody(String body, Map<String, String> stageVariables) {
|
||||
return new RequestContext("api1", "$default", "POST", "/orders", null, "POST /orders", "req-1", "1.2.3.4",
|
||||
Map.of(), Map.of(), Map.of("proxy", "balance"), body.getBytes(StandardCharsets.UTF_8),
|
||||
Map.of(), Map.of()).withVariables(stageVariables, Map.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void overwritePathSelectsAnIndexedBodyValue() {
|
||||
RequestContext withItems = withBody("{\"items\":[{\"id\":\"i-1\"},{\"id\":\"i-2\"}]}", Map.of());
|
||||
|
||||
mapper.apply(Map.of("overwrite:path", "/orders/$request.body.items[1].id/lines"), builder, withItems);
|
||||
|
||||
assertEquals("http://backend.local/orders/i-2/lines", builder.url());
|
||||
}
|
||||
|
||||
@Test
|
||||
void overwritePathSelectsQuotedKeys() {
|
||||
RequestContext withKeys = withBody("{\"order id\":\"o 42\",\"meta\":{\"a.b\":\"v\"}}", Map.of());
|
||||
|
||||
mapper.apply(Map.of("overwrite:path", "/o/$request.body.['order id']/$request.body.meta[\"a.b\"]/x"),
|
||||
builder, withKeys);
|
||||
|
||||
assertEquals("http://backend.local/o/o%2042/v/x", builder.url());
|
||||
}
|
||||
|
||||
@Test
|
||||
void overwritePathReadsNamesThatStartWithAnUnderscoreOrDigit() {
|
||||
RequestContext withNames = withBody("{\"_id\":\"x1\",\"2nd\":\"two\"}",
|
||||
Map.of("_backend", "blue", "1st", "one"));
|
||||
|
||||
mapper.apply(Map.of("overwrite:path",
|
||||
"/$stageVariables._backend/$stageVariables.1st/$request.body._id/$request.body.2nd"),
|
||||
builder, withNames);
|
||||
|
||||
assertEquals("http://backend.local/blue/one/x1/two", builder.url());
|
||||
}
|
||||
|
||||
@Test
|
||||
void overwritePathEndsAnEmbeddedNameWhereItsSyntaxEnds() {
|
||||
RequestContext withEnv = withBody("{\"id\":\"o-1\"}", Map.of("env", "blue"));
|
||||
|
||||
mapper.apply(Map.of("overwrite:path", "/$stageVariables.env-v2/$request.path.proxy.json"),
|
||||
builder, withEnv);
|
||||
|
||||
assertEquals("http://backend.local/blue-v2/balance.json", builder.url());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user