From 861d2ea259c87e58cdc90603377540c03605d156 Mon Sep 17 00:00:00 2001 From: Abhigya Date: Wed, 4 Nov 2026 22:54:51 +0530 Subject: [PATCH] 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+}. --- docs/services/api-gateway.md | 2 +- .../ApiGatewayExecuteController.java | 70 ++++- .../apigatewayv2/proxy/HttpProxyInvoker.java | 19 +- .../proxy/PathTemplateResolver.java | 26 ++ .../apigatewayv2/proxy/RequestContext.java | 53 +++- .../proxy/RequestParameterMapper.java | 14 +- ...ayHttpProxyEncodedPathIntegrationTest.java | 275 ++++++++++++++++++ .../apigateway/RawTargetPathTest.java | 27 ++ .../apigatewayv2/HttpProxyApiFixtures.java | 4 +- .../proxy/HttpProxyInvokerTest.java | 23 ++ .../proxy/PathTemplateResolverTest.java | 13 + .../proxy/RequestContextTest.java | 48 +++ .../proxy/RequestParameterMapperTest.java | 35 +++ 13 files changed, 589 insertions(+), 20 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpProxyEncodedPathIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestContextTest.java diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index f872425c42..a97014a920 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -413,7 +413,7 @@ and mappings. It supports these integration types; others return an error: A `MOCK` integration renders its request template and uses the `statusCode` it produces to pick the integration response, exactly as AWS does: the first response whose `selectionPattern` matches wins, otherwise the response without a pattern (the default) answers. This is what makes CORS preflights declared with a `204` response (CDK's `addCorsPreflight`) carry their `Access-Control-*` headers. -`HTTP_PROXY` forwards the request to the integration's `uri` — with `{param}` placeholders resolved from the matched resource's path parameters — and relays the backend's status, headers and body unchanged. Per AWS, no request templates and no integration-response selection apply to `HTTP_PROXY`, so a backend `4xx`/`5xx` reaches the caller verbatim rather than being remapped. `integration.request.{header,querystring,path}.*` → `method.request.*` mappings are applied. Hop-by-hop headers (including `Host`) are stripped. An unreachable or failing backend yields `502`. +`HTTP_PROXY` forwards the request to the integration's `uri` — with `{param}` placeholders resolved from the matched resource's path parameters — and relays the backend's status, headers and body unchanged. Per AWS, no request templates and no integration-response selection apply to `HTTP_PROXY`, so a backend `4xx`/`5xx` reaches the caller verbatim rather than being remapped. `integration.request.{header,querystring,path}.*` → `method.request.*` mappings are applied. Hop-by-hop headers (including `Host`) are stripped. An unreachable or failing backend yields `502`, and so does an integration URI that cannot be parsed. A path parameter copied from the request path keeps the caller's percent-encoding, so `/index/NIFTY%2050` and `/files/a%2Fb` reach the backend as sent, and a path value mapped from anywhere else, such as a header, is percent-encoded. HTTP API `HTTP_PROXY` integrations treat path parameters the same way. A greedy resource captures only the path segments after its parent. For example, `/api/v1/auth/signup/{proxy+}` captures `checkpoint/status` from diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java index c7b8f510d2..e1403ae78c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java @@ -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 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 outHeaders = joinedParameterValues(mapped.headers()); Map outQuery = joinedParameterValues(mapped.query()); Map 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 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 outHeaders = joinedParameterValues(mapped.headers()); Map outQuery = joinedParameterValues(mapped.query()); Map 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> headers, Map> query, - Map path) { } + Map path, Map rawPath) { } private HttpRequestParameters mapHttpRequestParameters(GatewayResponseScope scope, Integration integration, Map context, Map path, + Map rawPath, Map> headers, Map> query) { Map> outHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); outHeaders.putAll(headers); Map> outQuery = new LinkedHashMap<>(query); Map outPath = new LinkedHashMap<>(path); + Map outRawPath = new LinkedHashMap<>(rawPath); if (integration.getRequestParameters() == null) { - return new HttpRequestParameters(outHeaders, outQuery, outPath); + return new HttpRequestParameters(outHeaders, outQuery, outPath, outRawPath); } for (Map.Entry 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 joinedParameterValues(Map> parameters) { @@ -3002,6 +3025,8 @@ public class ApiGatewayExecuteController { queryParams.put(e.getKey(), String.join(",", e.getValue())); } Map pathParams = extractV2PathParams(route.getRouteKey(), path); + String rawPath = rawStagelessPath(path, uriInfo.getRequestUri().getRawPath()); + Map 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} diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java index 30819f8580..35d46d4533 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvoker.java @@ -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) { diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolver.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolver.java index 57719c4d7b..0b53e96728 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolver.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolver.java @@ -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 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'); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestContext.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestContext.java index a9bf413b5f..02e1f95845 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestContext.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestContext.java @@ -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. + * + *

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 authorizerClaims, Map authorizerContext, Map> multiValueHeaders, - Map> multiValueQueryParams) { + Map> multiValueQueryParams, + Map rawPathParams) { + + public RequestContext(String apiId, String stageName, String httpMethod, String path, String proxy, + String routeKey, String requestId, String sourceIp, + Map requestHeaders, Map queryParams, + Map pathParams, byte[] body, + Map authorizerClaims, Map authorizerContext, + Map> multiValueHeaders, + Map> 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 targetPathParams() { + if (pathParams == null) { + return null; + } + Map 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> expand(Map single) { if (single == null) { return null; diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapper.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapper.java index c3ea56b1b8..849dbae79d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapper.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapper.java @@ -18,7 +18,8 @@ import java.util.regex.Pattern; * * *

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. * *

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 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpProxyEncodedPathIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpProxyEncodedPathIntegrationTest.java new file mode 100644 index 0000000000..9a0174a6fb --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpProxyEncodedPathIntegrationTest.java @@ -0,0 +1,275 @@ +package io.github.hectorvent.floci.services.apigateway; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import io.github.hectorvent.floci.services.apigatewayv2.HttpProxyApiFixtures; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * A caller's percent-encoding has to reach an HTTP backend as the caller wrote it. JAX-RS hands the + * controller a decoded path, and substituting that into an integration URI threw on a space, so + * {@code /index/NIFTY%2050} answered 500 without reaching the backend, and turned an encoded + * {@code ?} into the start of the backend's query string. + */ +@QuarkusTest +class ApiGatewayHttpProxyEncodedPathIntegrationTest { + + private static HttpServer backendServer; + private static int backendPort; + + private static final AtomicReference lastRawPath = new AtomicReference<>(); + private static final AtomicReference lastRawQuery = new AtomicReference<>(); + + @BeforeAll + static void startBackend() throws IOException { + backendServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + backendServer.createContext("/", ApiGatewayHttpProxyEncodedPathIntegrationTest::handle); + backendServer.start(); + backendPort = backendServer.getAddress().getPort(); + } + + @AfterAll + static void stopBackend() { + if (backendServer != null) { + backendServer.stop(0); + } + } + + private static void handle(HttpExchange exchange) throws IOException { + lastRawPath.set(exchange.getRequestURI().getRawPath()); + lastRawQuery.set(exchange.getRequestURI().getRawQuery()); + byte[] response = "{\"from\":\"backend\"}".getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, response.length); + exchange.getResponseBody().write(response); + exchange.close(); + } + + @BeforeEach + void resetRecordings() { + lastRawPath.set(null); + lastRawQuery.set(null); + } + + private String createRestApi(String type, String resourcePath, String targetPath, String requestParametersJson) { + return createRestApi(type, resourcePath, "http://127.0.0.1:" + backendPort, targetPath, requestParametersJson); + } + + private String createRestApi(String type, String resourcePath, String targetOrigin, String targetPath, + String requestParametersJson) { + String apiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"encoded-path-api\"}") + .when().post("/restapis") + .then().statusCode(201) + .extract().path("id"); + + String resourceId = given().when().get("/restapis/" + apiId + "/resources") + .then().statusCode(200).extract().path("item[0].id"); + for (String pathPart : resourcePath.substring(1).split("/")) { + resourceId = given() + .contentType(ContentType.JSON) + .body(Map.of("pathPart", pathPart)) + .when().post("/restapis/" + apiId + "/resources/" + resourceId) + .then().statusCode(201).extract().path("id"); + } + String method = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET"; + + given().contentType(ContentType.JSON) + .body("{\"authorizationType\":\"NONE\"}") + .when().put(method) + .then().statusCode(201); + given().contentType(ContentType.JSON) + .body("{\"type\":\"" + type + "\",\"httpMethod\":\"GET\",\"uri\":\"" + targetOrigin + targetPath + "\"" + + (requestParametersJson == null ? "" : ",\"requestParameters\":" + requestParametersJson) + + "}") + .when().put(method + "/integration") + .then().statusCode(201); + if ("HTTP".equals(type)) { + given().contentType(ContentType.JSON) + .body("{}") + .when().put(method + "/responses/200") + .then().statusCode(201); + given().contentType(ContentType.JSON) + .body("{}") + .when().put(method + "/integration/responses/200") + .then().statusCode(201); + } + + String deploymentId = given().contentType(ContentType.JSON) + .body("{}") + .when().post("/restapis/" + apiId + "/deployments") + .then().statusCode(201).extract().path("id"); + given().contentType(ContentType.JSON) + .body("{\"stageName\":\"test\",\"deploymentId\":\"" + deploymentId + "\"}") + .when().post("/restapis/" + apiId + "/stages") + .then().statusCode(201); + return apiId; + } + + private static void getExpecting200(String path) { + given().urlEncodingEnabled(false) + .when().get(path) + .then().statusCode(200); + } + + @ParameterizedTest + @ValueSource(strings = {"NIFTY%2050/constituents", "a%3Fb", "a%23b", "a%2Fb", "a%252Fb", "a+b", "caf%C3%A9"}) + void restGreedyParameterKeepsTheCallersEncoding(String suffix) { + String apiId = createRestApi("HTTP_PROXY", "/index/{proxy+}", "/backend/{proxy}", null); + + getExpecting200("/execute-api/" + apiId + "/test/index/" + suffix); + + assertEquals("/backend/" + suffix, lastRawPath.get()); + assertNull(lastRawQuery.get()); + } + + @ParameterizedTest + @ValueSource(strings = { + "/execute-api/{apiId}/test/index/NIFTY%2050", + "/_aws/execute-api/{apiId}/test/index/NIFTY%2050", + "/restapis/{apiId}/test/_user_request_/index/NIFTY%2050" + }) + void everyExecuteApiUrlFormKeepsTheCallersEncoding(String urlTemplate) { + String apiId = createRestApi("HTTP_PROXY", "/index/{proxy+}", "/backend/{proxy}", null); + + getExpecting200(urlTemplate.replace("{apiId}", apiId)); + + assertEquals("/backend/NIFTY%2050", lastRawPath.get()); + } + + @Test + void restNamedParameterMappedFromMethodRequestKeepsTheCallersEncoding() { + String apiId = createRestApi("HTTP_PROXY", "/index/{name}", "/backend/{target}", + "{\"integration.request.path.target\":\"method.request.path.name\"}"); + + getExpecting200("/execute-api/" + apiId + "/test/index/NIFTY%2050"); + + assertEquals("/backend/NIFTY%2050", lastRawPath.get()); + } + + @Test + void restRequestWithQueryKeepsTheEncodedPathAndForwardsTheQuery() { + String apiId = createRestApi("HTTP_PROXY", "/index/{proxy+}", "/backend/{proxy}", null); + + getExpecting200("/execute-api/" + apiId + "/test/index/NIFTY%2050/price/history?range=1d"); + + assertEquals("/backend/NIFTY%2050/price/history", lastRawPath.get()); + assertEquals("range=1d", lastRawQuery.get()); + } + + @Test + void restNamedBackendHostKeepsTheEncodedPath() { + String apiId = createRestApi("HTTP_PROXY", "/index/{proxy+}", "http://localhost:" + backendPort, + "/backend/{proxy}", null); + + getExpecting200("/execute-api/" + apiId + "/test/index/NIFTY%2050"); + + assertEquals("/backend/NIFTY%2050", lastRawPath.get()); + } + + @Test + void restPathValueMappedFromAHeaderIsEncoded() { + String apiId = createRestApi("HTTP_PROXY", "/index", "/backend/{tenant}", + "{\"integration.request.path.tenant\":\"method.request.header.X-Tenant\"}"); + + given().header("X-Tenant", "acme corp?x") + .when().get("/execute-api/" + apiId + "/test/index") + .then().statusCode(200); + + assertEquals("/backend/acme%20corp%3Fx", lastRawPath.get()); + assertNull(lastRawQuery.get()); + } + + @Test + void restTrailingSlashDoesNotLoseTheNamedParameter() { + String apiId = createRestApi("HTTP_PROXY", "/index/{name}", "/backend/{name}", null); + + getExpecting200("/execute-api/" + apiId + "/test/index/NIFTY%2050/"); + + assertEquals("/backend/NIFTY%2050", lastRawPath.get()); + } + + @Test + void restNonProxyIntegrationKeepsTheCallersEncoding() { + String apiId = createRestApi("HTTP", "/index/{name}", "/backend/{name}", null); + + getExpecting200("/execute-api/" + apiId + "/test/index/NIFTY%2050"); + + assertEquals("/backend/NIFTY%2050", lastRawPath.get()); + } + + @Test + void restEncodedSlashBeforeTheGreedyParameterKeepsItsWholeValue() { + String apiId = createRestApi("HTTP_PROXY", "/a/b/{proxy+}", "/backend/{proxy}", null); + + getExpecting200("/execute-api/" + apiId + "/test/a%2Fb/c/d"); + + assertEquals("/backend/c/d", lastRawPath.get()); + } + + @Test + void restEncodedSlashAheadOfOnlyParametersKeepsTheirDecodedValues() { + String apiId = createRestApi("HTTP_PROXY", "/{x}/{y}/{z+}", "/backend/{y}/{z}", null); + + getExpecting200("/execute-api/" + apiId + "/test/a%2Fb/c/d"); + + assertEquals("/backend/b/c/d", lastRawPath.get()); + } + + @Test + void restEncodedSlashInsideTheGreedyParameterAfterLiteralsIsKept() { + String apiId = createRestApi("HTTP_PROXY", "/a/b/{proxy+}", "/backend/{proxy}", null); + + getExpecting200("/execute-api/" + apiId + "/test/a/b/c%2Fd"); + + assertEquals("/backend/c%2Fd", lastRawPath.get()); + } + + @Test + void restIntegrationUriThatCannotBeParsedYields502() { + String apiId = createRestApi("HTTP_PROXY", "/index/{proxy+}", "/not a uri/{proxy}", null); + + given().when().get("/execute-api/" + apiId + "/test/index/x") + .then().statusCode(502); + } + + @ParameterizedTest + @ValueSource(strings = {"NIFTY%2050/constituents", "a%3Fb", "a%2Fb"}) + void httpApiGreedyParameterKeepsTheCallersEncoding(String suffix) { + String apiId = HttpProxyApiFixtures.createProxyApi("encoded-path-http-api", "", "test", backendPort, + "/index/{proxy+}"); + + getExpecting200("/execute-api/" + apiId + "/test/index/" + suffix); + + assertEquals("/index/" + suffix, lastRawPath.get()); + assertNull(lastRawQuery.get()); + } + + @Test + void httpApiNamedParameterKeepsTheCallersEncoding() { + String apiId = HttpProxyApiFixtures.createProxyApi("encoded-path-http-api", "", "test", backendPort, + "/index/{name}"); + + getExpecting200("/execute-api/" + apiId + "/test/index/NIFTY%2050"); + + assertEquals("/index/NIFTY%2050", lastRawPath.get()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/RawTargetPathTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/RawTargetPathTest.java index 135d14cc38..5315764f13 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/RawTargetPathTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/RawTargetPathTest.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.apigateway; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; class RawTargetPathTest { @@ -32,4 +33,30 @@ class RawTargetPathTest { assertEquals("/x", ApiGatewayExecuteController.rawTargetPath("/x", null, "$default")); assertEquals("/prod/x", ApiGatewayExecuteController.rawTargetPath("/x", null, "prod")); } + + @Test + void stagelessPathDropsThePrefixOfEveryExecuteApiUrlForm() { + assertEquals("/a%20b/c", ApiGatewayExecuteController.rawStagelessPath("/a b/c", "/execute-api/api1/prod/a%20b/c")); + assertEquals("/a%20b/c", ApiGatewayExecuteController.rawStagelessPath("/a b/c", "/_aws/execute-api/api1/prod/a%20b/c")); + assertEquals("/a%20b/c", ApiGatewayExecuteController.rawStagelessPath("/a b/c", "/restapis/api1/prod/_user_request_/a%20b/c")); + } + + @Test + void stagelessPathOfTheStageRootIsTheRootPath() { + assertEquals("/", ApiGatewayExecuteController.rawStagelessPath("/", "/execute-api/api1/prod")); + assertEquals("/", ApiGatewayExecuteController.rawStagelessPath("/", "/execute-api/api1/prod/")); + assertEquals("/", ApiGatewayExecuteController.rawStagelessPath("/", "/restapis/api1/prod/_user_request_")); + } + + @Test + void stagelessPathDropsATrailingSlashOnlyWhenTheNormalizedPathLostIt() { + assertEquals("/x", ApiGatewayExecuteController.rawStagelessPath("/x", "/execute-api/api1/prod/x/")); + assertEquals("/x/", ApiGatewayExecuteController.rawStagelessPath("/x/", "/execute-api/api1/prod/x/")); + } + + @Test + void stagelessPathOfAnUnknownUrlFormIsNull() { + assertNull(ApiGatewayExecuteController.rawStagelessPath("/x", "/other/api1/prod/x")); + assertNull(ApiGatewayExecuteController.rawStagelessPath("/x", null)); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyApiFixtures.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyApiFixtures.java index c72bc216db..2ba8c02ac6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyApiFixtures.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyApiFixtures.java @@ -5,7 +5,7 @@ import io.restassured.http.ContentType; 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. */ -final class HttpProxyApiFixtures { +public final class HttpProxyApiFixtures { private HttpProxyApiFixtures() { } @@ -15,7 +15,7 @@ final class HttpProxyApiFixtures { * stage {@code stageName} and a {@code GET path} route to an {@code HTTP_PROXY} integration on * {@code http://127.0.0.1:backendPort path}; returns its id. */ - static String createProxyApi(String name, String apiFields, String stageName, int backendPort, String path) { + public static String createProxyApi(String name, String apiFields, String stageName, int backendPort, String path) { String apiId = given() .contentType(ContentType.JSON) .body("{\"name\":\"" + name + "\",\"protocolType\":\"HTTP\"" + apiFields + "}") diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java index 109762ddfe..7fffa31a5c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/HttpProxyInvokerTest.java @@ -478,4 +478,27 @@ class HttpProxyInvokerTest { thread.start(); return server; } + + @Test + void encodesADecodedPathParameterWithNoRawValue() { + Integration integration = httpProxyIntegration( + "http://127.0.0.1:" + backendPort + "/public/{proxy}", null); + RequestContext ctx = ctxFor("GET", "/wallet/NIFTY 50", "NIFTY 50", Map.of(), Map.of(), null, Map.of()); + + ProxyResult result = new HttpProxyInvoker().invoke(integration, ctx); + + assertEquals(200, result.statusCode()); + assertEquals("/public/NIFTY 50", received.get().path()); + } + + @Test + void integrationUriThatCannotBeParsedYields502() { + Integration integration = httpProxyIntegration("http://127.0.0.1:" + backendPort + "/not a uri", null); + RequestContext ctx = ctxFor("GET", "/wallet/x", "x", Map.of(), Map.of(), null, Map.of()); + + ProxyResult result = new HttpProxyInvoker().invoke(integration, ctx); + + assertEquals(502, result.statusCode()); + assertNull(received.get()); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolverTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolverTest.java index 9d89d132ae..01d71ead4f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolverTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/PathTemplateResolverTest.java @@ -78,4 +78,17 @@ class PathTemplateResolverTest { void missingGreedyPlaceholderBecomesEmpty() { assertEquals("/x/", PathTemplateResolver.resolve("/x/{missing+}", Map.of())); } + + @Test + void encodePathValueEncodesWhatCannotAppearInAPathAndKeepsSegmentSeparators() { + assertEquals("NIFTY%2050/constituents", PathTemplateResolver.encodePathValue("NIFTY 50/constituents")); + assertEquals("a%3Fb%23c%25d", PathTemplateResolver.encodePathValue("a?b#c%d")); + assertEquals("caf%C3%A9", PathTemplateResolver.encodePathValue("caf\u00e9")); + assertEquals("a-b_c.d~e+f:g@h", PathTemplateResolver.encodePathValue("a-b_c.d~e+f:g@h")); + } + + @Test + void encodePathValueOfNullIsNull() { + assertNull(PathTemplateResolver.encodePathValue(null)); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestContextTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestContextTest.java new file mode 100644 index 0000000000..aea681c578 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestContextTest.java @@ -0,0 +1,48 @@ +package io.github.hectorvent.floci.services.apigatewayv2.proxy; + +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class RequestContextTest { + + private static RequestContext context(Map pathParams, Map rawPathParams) { + return new RequestContext("api1", "test", "GET", "/", "", "GET /", "req-1", "1.2.3.4", + Map.of(), Map.of(), pathParams, null, Map.of(), Map.of(), Map.of(), Map.of(), rawPathParams); + } + + @Test + void rawValueThatDecodesToTheParameterIsKept() { + Map target = context(Map.of("proxy", "a/b c+d"), Map.of("proxy", "a%2Fb%20c+d")) + .targetPathParams(); + + assertEquals(Map.of("proxy", "a%2Fb%20c+d"), target); + } + + @Test + void rawValueReadFromShiftedSegmentsIsEncodedFromTheDecodedValue() { + Map target = context(Map.of("x", "a", "y", "b c/d"), Map.of("x", "a%2Fb%20c", "y", "d")) + .targetPathParams(); + + assertEquals(Map.of("x", "a", "y", "b%20c/d"), target); + } + + @Test + void parameterWithoutARawValueIsEncoded() { + assertEquals(Map.of("name", "a%3Fb"), context(Map.of("name", "a?b"), Map.of()).targetPathParams()); + assertEquals(Map.of("name", "a%3Fb"), context(Map.of("name", "a?b"), null).targetPathParams()); + } + + @Test + void rawValueThatIsNotValidPercentEncodingIsEncodedFromTheDecodedValue() { + assertEquals(Map.of("name", "a%25zz"), context(Map.of("name", "a%zz"), Map.of("name", "a%zz")).targetPathParams()); + } + + @Test + void absentPathParametersStayAbsent() { + assertNull(context(null, Map.of("name", "a")).targetPathParams()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapperTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapperTest.java index 49361c4175..2f29352601 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapperTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/proxy/RequestParameterMapperTest.java @@ -129,4 +129,39 @@ class RequestParameterMapperTest { mapper.apply(Map.of("not-a-valid-key", "value"), builder, ctx); assertEquals("http://backend.local/foo", builder.url()); } + + @Test + void overwritePathKeepsTheCallersEncodingOfAPathParameter() { + RequestContext encoded = new RequestContext("api1", "$default", "GET", "/index/a/b c", "a/b c", + "ANY /index/{proxy+}", "req-1", "1.2.3.4", Map.of(), Map.of(), + Map.of("proxy", "a/b c"), null, Map.of(), Map.of(), Map.of(), Map.of(), + Map.of("proxy", "a%2Fb%20c")); + + mapper.apply(Map.of("overwrite:path", "/public/$request.path.proxy"), builder, encoded); + + assertEquals("http://backend.local/public/a%2Fb%20c", builder.url()); + } + + @Test + void overwritePathEncodesAValueThatDidNotComeFromTheRequestPath() { + RequestContext withClaim = new RequestContext("api1", "$default", "GET", "/wallet/balance", "balance", + "ANY /wallet/{proxy+}", "req-1", "1.2.3.4", Map.of(), Map.of(), Map.of(), null, + Map.of("tenant", "acme corp?x"), Map.of()); + + mapper.apply(Map.of("overwrite:path", "/t/$context.authorizer.claims.tenant"), builder, withClaim); + + assertEquals("http://backend.local/t/acme%20corp%3Fx", builder.url()); + } + + @Test + void headerMappingKeepsTheDecodedPathParameter() { + RequestContext encoded = new RequestContext("api1", "$default", "GET", "/index/b c", "b c", + "ANY /index/{proxy+}", "req-1", "1.2.3.4", Map.of(), Map.of(), + Map.of("proxy", "b c"), null, Map.of(), Map.of(), Map.of(), Map.of(), + Map.of("proxy", "b%20c")); + + mapper.apply(Map.of("overwrite:header.x-name", "$request.path.proxy"), builder, encoded); + + assertEquals("b c", builder.headers().get("x-name").get(0)); + } }