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
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user