fix(apigateway): keep the caller's path encoding on HTTP integrations (#7489)

The controller read path parameters from the decoded JAX-RS path and
substituted them into the integration URI, so a path with an encoded space
threw from URI.create and answered 500 without reaching the backend. An
encoded ? or # cut the backend path short, %2F became a separator and %252F
lost a level of encoding.

Read the target URL's path parameters from the raw request path, for REST
HTTP_PROXY, REST HTTP and HTTP API HTTP_PROXY integrations. A value mapped
from elsewhere is percent-encoded. $request.path.X and header mappings keep
the decoded value. An integration URI that cannot be parsed now answers 502.

Routes match on the decoded path, so an encoded slash ahead of a parameter
shifts the segments read off the raw path. /a%2Fb/c/d on /a/b/{proxy+} called
the backend with /backend/d. A raw value that does not decode to the decoded
parameter is now ignored, and the decoded value is encoded instead. Comparing
values rather than literal segments also covers templates with no literals,
such as /{x}/{y}/{z+} and the HTTP API route /{x}/{y+}.
This commit is contained in:
Abhigya authored and GitHub committed 2026-11-04 13:24:51 -04:00
1 parent 05eed7a0a9
commit 861d2ea259
13 files changed
+589 -20

No files matched your search

@@ -660,8 +660,13 @@ public class ApiGatewayExecuteController {
pathMap.putAll(extractPathParams(resource.getPath(), path));
pathMap.putAll(greedyPathParam(resource.getPath(), path));
String rawPath = rawStagelessPath(path, uriInfo.getRequestUri().getRawPath());
Map<String, String> rawPathMap = new LinkedHashMap<>();
rawPathMap.putAll(extractPathParams(resource.getPath(), rawPath));
rawPathMap.putAll(greedyPathParam(resource.getPath(), rawPath));
HttpRequestParameters mapped = mapHttpRequestParameters(scope, integration, mappingContext,
pathMap, multiValueHeaders, multiValueQuery);
pathMap, rawPathMap, multiValueHeaders, multiValueQuery);
Map<String, String> outHeaders = joinedParameterValues(mapped.headers());
Map<String, String> outQuery = joinedParameterValues(mapped.query());
Map<String, String> outPath = mapped.path();
@@ -685,7 +690,7 @@ public class ApiGatewayExecuteController {
routeContext.sourceIp(),
outHeaders, outQuery, outPath, body,
Map.of(), Map.of(),
multiValueHeaders, multiValueQuery);
multiValueHeaders, multiValueQuery, mapped.rawPath());
LOG.debugv("execute-api: {0} {1}/{2}{3} → HTTP_PROXY {4}",
httpMethod, apiId, stageName, path, uri);
@@ -964,6 +969,13 @@ public class ApiGatewayExecuteController {
if (proxy != null && !proxy.isEmpty()) pathMap.put("proxy", proxy);
pathMap.putAll(extractPathParams(resource.getPath(), path));
String rawPath = rawStagelessPath(path, uriInfo.getRequestUri().getRawPath());
Map<String, String> rawPathMap = new HashMap<>();
if (rawPath != null && pathMap.containsKey("proxy")) {
rawPathMap.put("proxy", rawPath.substring(1));
}
rawPathMap.putAll(extractPathParams(resource.getPath(), rawPath));
String incomingContentType = headerMap.getOrDefault("Content-Type",
headerMap.getOrDefault("content-type", "application/json"));
@@ -978,7 +990,7 @@ public class ApiGatewayExecuteController {
// Only explicitly mapped parameters reach the backend — the defining difference from
// HTTP_PROXY, which seeds the outgoing request with every inbound header and query param.
HttpRequestParameters mapped = mapHttpRequestParameters(scope, integration, mappingContext,
pathMap, Map.of(), Map.of());
pathMap, rawPathMap, Map.of(), Map.of());
Map<String, String> outHeaders = joinedParameterValues(mapped.headers());
Map<String, String> outQuery = joinedParameterValues(mapped.query());
Map<String, String> outPath = mapped.path();
@@ -1012,7 +1024,7 @@ public class ApiGatewayExecuteController {
outPath.getOrDefault("proxy", ""), resource.getPath(),
requestId, routeContext.sourceIp(),
outHeaders, outQuery, outPath, payload,
Map.of(), Map.of(), mapped.headers(), mapped.query());
Map.of(), Map.of(), mapped.headers(), mapped.query(), mapped.rawPath());
LOG.debugv("execute-api: {0} {1}/{2}{3} → HTTP {4}", httpMethod, apiId, stageName, path, uri);
@@ -2313,18 +2325,20 @@ public class ApiGatewayExecuteController {
}
private record HttpRequestParameters(Map<String, List<String>> headers, Map<String, List<String>> query,
Map<String, String> path) { }
Map<String, String> path, Map<String, String> rawPath) { }
private HttpRequestParameters mapHttpRequestParameters(GatewayResponseScope scope, Integration integration,
Map<String, Object> context, Map<String, String> path,
Map<String, String> rawPath,
Map<String, List<String>> headers,
Map<String, List<String>> query) {
Map<String, List<String>> outHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
outHeaders.putAll(headers);
Map<String, List<String>> outQuery = new LinkedHashMap<>(query);
Map<String, String> outPath = new LinkedHashMap<>(path);
Map<String, String> outRawPath = new LinkedHashMap<>(rawPath);
if (integration.getRequestParameters() == null) {
return new HttpRequestParameters(outHeaders, outQuery, outPath);
return new HttpRequestParameters(outHeaders, outQuery, outPath, outRawPath);
}
for (Map.Entry<String, String> mapping : integration.getRequestParameters().entrySet()) {
String destination = mapping.getKey();
@@ -2342,10 +2356,19 @@ public class ApiGatewayExecuteController {
} else if (values != null && destination.startsWith("integration.request.querystring.")) {
outQuery.put(destination.substring("integration.request.querystring.".length()), values);
} else if (values != null && destination.startsWith("integration.request.path.")) {
outPath.put(destination.substring("integration.request.path.".length()), String.join(",", values));
String name = destination.substring("integration.request.path.".length());
outPath.put(name, String.join(",", values));
// Only a value copied from the request path has a caller's encoding to keep.
String rawValue = source.startsWith("method.request.path.")
? rawPath.get(source.substring("method.request.path.".length())) : null;
if (rawValue != null) {
outRawPath.put(name, rawValue);
} else {
outRawPath.remove(name);
}
}
}
return new HttpRequestParameters(outHeaders, outQuery, outPath);
return new HttpRequestParameters(outHeaders, outQuery, outPath, outRawPath);
}
private static Map<String, String> joinedParameterValues(Map<String, List<String>> parameters) {
@@ -3002,6 +3025,8 @@ public class ApiGatewayExecuteController {
queryParams.put(e.getKey(), String.join(",", e.getValue()));
}
Map<String, String> pathParams = extractV2PathParams(route.getRouteKey(), path);
String rawPath = rawStagelessPath(path, uriInfo.getRequestUri().getRawPath());
Map<String, String> rawPathParams = rawPath == null ? Map.of() : extractV2PathParams(route.getRouteKey(), rawPath);
// Reuses the claims dispatchV2 already verified via enforceJwtAuthorizer, rather than
// independently re-extracting a token and re-parsing it here: extractBearerToken only
@@ -3024,7 +3049,7 @@ public class ApiGatewayExecuteController {
pathParams.getOrDefault("proxy", ""), route.getRouteKey(),
UUID.randomUUID().toString(), sourceIp,
requestHeaders, queryParams, pathParams, body,
claims, authorizerContext, backendHeaders, multiValueQueryParams);
claims, authorizerContext, backendHeaders, multiValueQueryParams, rawPathParams);
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → HTTP_PROXY {4}",
httpMethod, apiId, stageName, path, effective.getIntegrationUri());
@@ -4384,6 +4409,33 @@ public class ApiGatewayExecuteController {
return rawTargetPath(normalizedPath, uriInfo.getRequestUri().getRawPath(), stageName);
}
/**
* The request path after the stage, as the caller encoded it, for reading path parameters off.
* A trailing slash goes only when {@code normalizedPath} lost it too, so the segments line up with
* the path the route was matched on. Null for a raw path in no known execute-api URL form, whose
* parameters are then encoded from their decoded values.
*/
static String rawStagelessPath(String normalizedPath, String rawRequestPath) {
if (rawRequestPath == null) {
return null;
}
int prefixSegments;
if (rawRequestPath.startsWith("/execute-api/")) {
prefixSegments = 3;
} else if (rawRequestPath.startsWith("/_aws/execute-api/") || rawRequestPath.startsWith("/restapis/")) {
prefixSegments = 4;
} else {
return null;
}
int start = 0;
for (int segment = 0; segment < prefixSegments && start >= 0; segment++) {
start = rawRequestPath.indexOf('/', start + 1);
}
String stageless = start >= 0 ? rawRequestPath.substring(start) : "/";
boolean slashLost = stageless.length() > 1 && stageless.endsWith("/") && !normalizedPath.endsWith("/");
return slashLost ? stageless.substring(0, stageless.length() - 1) : stageless;
}
/**
* Re-appends a trailing slash that the JAX-RS {@code {proxy}} path-param binding strips.
* A trailing slash is significant in the proxy event path (many routers treat {@code /x}
@@ -290,7 +290,7 @@ public class HttpProxyInvoker {
public ProxyResult invoke(Integration integration, RequestContext ctx, ProxyOptions options) {
// 1. Resolve target URL from IntegrationUri template + captured path params
String resolvedUrl = PathTemplateResolver.resolve(integration.getIntegrationUri(), ctx.pathParams());
String resolvedUrl = PathTemplateResolver.resolve(integration.getIntegrationUri(), ctx.targetPathParams());
// 2. Determine HTTP method (integration.method=ANY/null means use the inbound method)
String method = integration.getIntegrationMethod();
@@ -316,12 +316,21 @@ public class HttpProxyInvoker {
}
builder.setBody(ctx.body());
// 4. Apply RequestParameters
mapper.apply(integration.getRequestParameters(), builder, ctx);
// 4. Apply RequestParameters and settle the target URL. Everything here parses the URL, and
// an integration URI or mapped path that does not parse is the backend call failing.
String finalUrl;
boolean pinned;
try {
mapper.apply(integration.getRequestParameters(), builder, ctx);
finalUrl = buildFinalUrl(builder);
pinned = finalUrl.startsWith("http://") && (hasHeader(builder, "Host") || isNamedHost(finalUrl));
} catch (IllegalArgumentException e) {
LOG.warnv("HTTP_PROXY: invalid target URL: {0}", e.getMessage());
return errorResult("Bad Gateway: invalid target URL: " + e.getMessage());
}
// 5. Build java.net.http.HttpRequest
String finalUrl = buildFinalUrl(builder);
if (finalUrl.startsWith("http://") && (hasHeader(builder, "Host") || isNamedHost(finalUrl))) {
if (pinned) {
try {
return invokeHttpPinned(finalUrl, method, builder, options.timeout());
} catch (PinnedHttpClient.ResponseTooLargeException ignored) {
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.apigatewayv2.proxy;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -23,6 +24,10 @@ import java.util.regex.Pattern;
public final class PathTemplateResolver {
private static final Pattern PLACEHOLDER = Pattern.compile("\\{([a-zA-Z_][a-zA-Z0-9_]*)\\+?\\}");
/** RFC 3986 pchar without pct-encoded, plus the {@code /} a greedy value carries between segments. */
private static final String PATH_SAFE = "-._~!$&'()*+,;=:@/";
private static final char[] HEX = "0123456789ABCDEF".toCharArray();
private PathTemplateResolver() {}
public static String resolve(String template, Map<String, String> pathParams) {
@@ -37,4 +42,25 @@ public final class PathTemplateResolver {
m.appendTail(out);
return out.toString();
}
/** Percent-encodes a decoded value for a URL path, keeping the {@code /} between its segments. */
public static String encodePathValue(String value) {
if (value == null) {
return null;
}
StringBuilder out = new StringBuilder(value.length());
for (byte b : value.getBytes(StandardCharsets.UTF_8)) {
char c = (char) (b & 0xFF);
if (isAsciiAlphanumeric(c) || PATH_SAFE.indexOf(c) >= 0) {
out.append(c);
} else {
out.append('%').append(HEX[c >> 4]).append(HEX[c & 0xF]);
}
}
return out.toString();
}
private static boolean isAsciiAlphanumeric(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
}
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.apigatewayv2.proxy;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -17,6 +19,13 @@ import java.util.Map;
* and they keep repeated values separate: REST HTTP_PROXY passes the request
* through, and {@code ?tag=a&tag=b} must not reach the backend as
* {@code ?tag=a,b}, which is a different request to most servers.
*
* <p>Path parameters appear twice for the same reason. {@code pathParams} holds the decoded values
* that {@code $request.path.X} resolves against, and {@code rawPathParams} holds the same parameters
* as the caller encoded them, which is what the target URL needs: decoding and re-encoding cannot
* 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.
*/
public record RequestContext(
String apiId,
@@ -34,7 +43,20 @@ public record RequestContext(
Map<String, Object> authorizerClaims,
Map<String, Object> authorizerContext,
Map<String, List<String>> multiValueHeaders,
Map<String, List<String>> multiValueQueryParams) {
Map<String, List<String>> multiValueQueryParams,
Map<String, String> rawPathParams) {
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) {
this(apiId, stageName, httpMethod, path, proxy, routeKey, requestId, sourceIp,
requestHeaders, queryParams, pathParams, body, authorizerClaims, authorizerContext,
multiValueHeaders, multiValueQueryParams, null);
}
/**
* For callers whose headers and query parameters are single-valued by
@@ -51,6 +73,35 @@ public record RequestContext(
expand(requestHeaders), expand(queryParams));
}
/** The path parameters as they go into the target URL, every value percent-encoded. */
public Map<String, String> targetPathParams() {
if (pathParams == null) {
return null;
}
Map<String, String> target = new LinkedHashMap<>();
pathParams.forEach((name, value) -> {
String raw = rawPathParams == null ? null : rawPathParams.get(name);
target.put(name, decodesTo(raw, value) ? raw : PathTemplateResolver.encodePathValue(value));
});
return target;
}
/**
* Routes match on the decoded path, where an encoded slash splits a segment, so segments read off
* the raw path can belong to a different parameter than the decoded value of the same name.
*/
private static boolean decodesTo(String raw, String value) {
if (raw == null) {
return false;
}
try {
return URLDecoder.decode(raw.replace("+", "%2B"), StandardCharsets.UTF_8).equals(value);
} catch (IllegalArgumentException expected) {
// Not valid percent-encoding, so it cannot stand for the decoded value: encode that instead.
return false;
}
}
private static Map<String, List<String>> expand(Map<String, String> single) {
if (single == null) {
return null;
@@ -18,7 +18,8 @@ import java.util.regex.Pattern;
* </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.
* {@code $request.path.X} / {@code $context.X} substrings which are resolved in-place. They land in
* a URL, so a path parameter keeps the caller's encoding and any other value is percent-encoded.
*
* <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}
@@ -27,6 +28,7 @@ import java.util.regex.Pattern;
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 REQUEST_PATH_PREFIX = "$request.path.";
private final ContextValueResolver resolver;
@@ -83,10 +85,18 @@ public class RequestParameterMapper {
private String substituteEmbeddedVars(String template, RequestContext ctx) {
if (template == null) return null;
if (!template.contains("$")) return template;
Map<String, String> targetPathParams = ctx.targetPathParams();
Matcher m = EMBEDDED_VAR.matcher(template);
StringBuilder out = new StringBuilder();
while (m.find()) {
String resolved = resolver.resolve(m.group(), ctx);
String variable = m.group();
String resolved;
if (variable.startsWith(REQUEST_PATH_PREFIX)) {
resolved = targetPathParams == null ? null
: targetPathParams.get(variable.substring(REQUEST_PATH_PREFIX.length()));
} else {
resolved = PathTemplateResolver.encodePathValue(resolver.resolve(variable, ctx));
}
m.appendReplacement(out, Matcher.quoteReplacement(resolved == null ? "" : resolved));
}
m.appendTail(out);