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

@@ -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<String> lastRawPath = new AtomicReference<>();
private static final AtomicReference<String> 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());
}
}
@@ -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));
}
}
@@ -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 + "}")
@@ -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());
}
}
@@ -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));
}
}
@@ -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<String, String> pathParams, Map<String, String> 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<String, String> 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<String, String> 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());
}
}
@@ -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));
}
}