From a15dfb621eef9fc8d9dfd058ad77d30786d09572 Mon Sep 17 00:00:00 2001 From: Abhigya Date: Thu, 5 Nov 2026 14:25:16 +0530 Subject: [PATCH] fix(core): work around double decoding on routed hosts (#7559) --- docs/services/api-gateway.md | 3 + docs/services/cloudfront.md | 3 +- .../floci/core/common/RequestUriRewrite.java | 24 ++++++++ .../ApiGatewayCustomDomainFilter.java | 4 +- .../ApiGatewayExecuteApiHostFilter.java | 7 ++- .../ApiGatewayExecuteController.java | 25 ++++---- .../ApiGatewayExecuteRouteContext.java | 10 ++++ .../CloudFrontDistributionFilter.java | 3 +- .../services/s3/S3VirtualHostFilter.java | 7 +-- .../core/common/RequestUriRewriteTest.java | 35 +++++++++++ .../ApiGatewayCustomDomainFilterTest.java | 15 +++++ .../ApiGatewayExecuteApiHostFilterTest.java | 8 ++- .../ApiGatewayExecuteControllerTest.java | 35 ++++++++++- ...ayHttpProxyEncodedPathIntegrationTest.java | 59 ++++++++++++++++++- .../CloudFrontCustomOriginServingTest.java | 21 +++++++ 15 files changed, 236 insertions(+), 23 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/core/common/RequestUriRewrite.java create mode 100644 src/test/java/io/github/hectorvent/floci/core/common/RequestUriRewriteTest.java diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index a97014a920..75af11099c 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -2,6 +2,9 @@ Floci supports both API Gateway v1 (REST APIs) and API Gateway v2 (HTTP APIs). +HTTP integrations preserve path encoding through custom domains and `execute-api` hosts as well +as path-based endpoints. For example, `/files/a%25b` reaches an HTTP backend with `%25` intact. + ## JWT issuer network policy HTTP API JWT authorizers fetch the configured issuer's OIDC discovery document and JWKS. Floci diff --git a/docs/services/cloudfront.md b/docs/services/cloudfront.md index d3e8bcc6f6..10417473ba 100644 --- a/docs/services/cloudfront.md +++ b/docs/services/cloudfront.md @@ -154,7 +154,8 @@ PUT, PATCH and DELETE). - Viewer requests addressed to an enabled distribution's generated domain or alias are routed to the matching S3 or custom origin when the matched cache behavior's `AllowedMethods` includes the method; any other method returns 403 `Invalid method.`. A behavior without `AllowedMethods` allows - GET and HEAD. Origin forwarding preserves the raw path; custom-origin redirects are not followed. + GET and HEAD. Origin forwarding preserves the raw path, including `%25` for a literal percent + sign, on generated domains and aliases. Custom-origin redirects are not followed. - POST, PUT, PATCH and DELETE are forwarded to custom origins with the viewer request body and its `Content-Type`. The body is streamed to the origin with the viewer's `Content-Length`, or chunked when the viewer sent it chunked or, as HTTP/2 allows, with no length, so it is never held in diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestUriRewrite.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestUriRewrite.java new file mode 100644 index 0000000000..271b750264 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestUriRewrite.java @@ -0,0 +1,24 @@ +package io.github.hectorvent.floci.core.common; + +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.UriBuilder; + +import java.net.URI; + +/** + * Shares S3's workaround for RESTEasy Reactive's second path decode (Floci #7556). + * Raw-path consumers must retain the intended path before applying the routing escape. + */ +public final class RequestUriRewrite { + + private RequestUriRewrite() { + } + + /** Escapes percent signs once more so RESTEasy stores the intended raw routing path. */ + public static void apply(ContainerRequestContext requestContext, URI requestUri) { + URI routingUri = UriBuilder.fromUri(requestUri) + .replacePath(requestUri.getRawPath().replace("%", "%25")) + .build(); + requestContext.setRequestUri(routingUri); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java index d3211da8b2..2d74f254a6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.apigateway; import io.github.hectorvent.floci.core.common.RequestHost; import io.github.hectorvent.floci.core.common.RequestScopes; +import io.github.hectorvent.floci.core.common.RequestUriRewrite; import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping; import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; import jakarta.annotation.Priority; @@ -120,8 +121,9 @@ public class ApiGatewayCustomDomainFilter implements ContainerRequestFilter { || !apiGatewayV2Service.hasApi(mappedRegion, restApiId))); routeContext.routeToMappedApi(domain, restApi); routeContext.recordSignedRequestPath(path); + routeContext.recordRewrittenRequestPath(newUri.getRawPath()); requestContext.setProperty(ROUTED_PROPERTY, Boolean.TRUE); - requestContext.setRequestUri(newUri); + RequestUriRewrite.apply(requestContext, newUri); } private static String stripPort(String host) { diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java index 6c548e8a2a..305f3bd3a5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsPartitions; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.core.common.RequestHost; +import io.github.hectorvent.floci.core.common.RequestUriRewrite; import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer; import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; import jakarta.annotation.Priority; @@ -261,7 +262,8 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter { // AWS_IAM dispatch rebuilds the caller's canonical request, which covers the path they // signed: the virtual-host path, not the /execute-api/... form this rewrite produces. routeContext.recordSignedRequestPath(originalPath); - requestContext.setRequestUri(newUri); + routeContext.recordRewrittenRequestPath(newUri.getRawPath()); + RequestUriRewrite.apply(requestContext, newUri); } private void routeToRestApi(ContainerRequestContext requestContext, URI originalUri, @@ -273,7 +275,8 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter { LOG.debugv("REST execute-api host routing: {0} -> {1}", originalPath, newUri.getRawPath()); routeContext.routeToRestApi(); routeContext.recordSignedRequestPath(originalPath); - requestContext.setRequestUri(newUri); + routeContext.recordRewrittenRequestPath(newUri.getRawPath()); + RequestUriRewrite.apply(requestContext, newUri); } private boolean stageExists(String region, String apiId, String stageName) { 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 e1403ae78c..0e20eaa47e 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,7 +660,7 @@ public class ApiGatewayExecuteController { pathMap.putAll(extractPathParams(resource.getPath(), path)); pathMap.putAll(greedyPathParam(resource.getPath(), path)); - String rawPath = rawStagelessPath(path, uriInfo.getRequestUri().getRawPath()); + String rawPath = rawStagelessPath(path, rawRequestPath(uriInfo)); Map rawPathMap = new LinkedHashMap<>(); rawPathMap.putAll(extractPathParams(resource.getPath(), rawPath)); rawPathMap.putAll(greedyPathParam(resource.getPath(), rawPath)); @@ -969,7 +969,7 @@ 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()); + String rawPath = rawStagelessPath(path, rawRequestPath(uriInfo)); Map rawPathMap = new HashMap<>(); if (rawPath != null && pathMap.containsKey("proxy")) { rawPathMap.put("proxy", rawPath.substring(1)); @@ -1337,7 +1337,7 @@ public class ApiGatewayExecuteController { // Recover the trailing slash the JAX-RS {proxy} binding strips, so the authorizer sees // the same raw path the Lambda later receives from buildProxyEvent (AWS parity). Path // matching and path-parameter extraction keep using the normalized requestPath. - String preservedPath = preserveTrailingSlash(requestPath, uriInfo.getRequestUri().getRawPath()); + String preservedPath = preserveTrailingSlash(requestPath, rawRequestPath(uriInfo)); ObjectNode node = objectMapper.createObjectNode(); node.put("type", auth.getType()); @@ -1470,7 +1470,7 @@ public class ApiGatewayExecuteController { // significant in the delivered path (routers treat /x and /x/ as distinct routes). // Recover it from the raw request URI for the event path fields. Resource matching // and path-parameter extraction continue to use the normalized `path`. - String requestPath = preserveTrailingSlash(path, uriInfo.getRequestUri().getRawPath()); + String requestPath = preserveTrailingSlash(path, rawRequestPath(uriInfo)); ObjectNode event = objectMapper.createObjectNode(); event.put("resource", resourcePath); @@ -3025,7 +3025,7 @@ public class ApiGatewayExecuteController { queryParams.put(e.getKey(), String.join(",", e.getValue())); } Map pathParams = extractV2PathParams(route.getRouteKey(), path); - String rawPath = rawStagelessPath(path, uriInfo.getRequestUri().getRawPath()); + String rawPath = rawStagelessPath(path, rawRequestPath(uriInfo)); Map rawPathParams = rawPath == null ? Map.of() : extractV2PathParams(route.getRouteKey(), rawPath); // Reuses the claims dispatchV2 already verified via enforceJwtAuthorizer, rather than @@ -3528,7 +3528,7 @@ public class ApiGatewayExecuteController { // do NOT: an HTTP API has no REST-style resource template, so both are copies of the // request path here rather than of a matched resource, and AWS's own 1.0 payload example // shows `resource` and `path` carrying the same value. - String preservedPath = preserveTrailingSlash(path, uriInfo.getRequestUri().getRawPath()); + String preservedPath = preserveTrailingSlash(path, rawRequestPath(uriInfo)); ObjectNode event = objectMapper.createObjectNode(); event.put("version", "1.0"); @@ -3580,7 +3580,7 @@ public class ApiGatewayExecuteController { // rawPath is by contract the raw, unmodified path, so recover the trailing slash the // JAX-RS {proxy} binding stripped. routeArn keeps the normalized path for the same reason // methodArn does in the 1.0 shape above. - String preservedPath = preserveTrailingSlash(path, uriInfo.getRequestUri().getRawPath()); + String preservedPath = preserveTrailingSlash(path, rawRequestPath(uriInfo)); ObjectNode event = objectMapper.createObjectNode(); event.put("version", "2.0"); @@ -3908,7 +3908,7 @@ public class ApiGatewayExecuteController { // request URI for the event path fields. Route matching in dispatchV2 and the // pathParameters extraction below continue to use the normalized `path`, mirroring what // buildProxyEvent already does for REST (V1). - String preservedPath = preserveTrailingSlash(path, uriInfo.getRequestUri().getRawPath()); + String preservedPath = preserveTrailingSlash(path, rawRequestPath(uriInfo)); ObjectNode event = objectMapper.createObjectNode(); @@ -4405,8 +4405,13 @@ public class ApiGatewayExecuteController { return defaultStage ? path : "/" + stageName + path; } - private static String proxyTargetPath(String normalizedPath, UriInfo uriInfo, String stageName) { - return rawTargetPath(normalizedPath, uriInfo.getRequestUri().getRawPath(), stageName); + String rawRequestPath(UriInfo uriInfo) { + String rewrittenPath = routeContext.rewrittenRequestPath(); + return rewrittenPath != null ? rewrittenPath : uriInfo.getRequestUri().getRawPath(); + } + + private String proxyTargetPath(String normalizedPath, UriInfo uriInfo, String stageName) { + return rawTargetPath(normalizedPath, rawRequestPath(uriInfo), stageName); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java index 777fed939e..21f198c932 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteRouteContext.java @@ -78,6 +78,7 @@ public class ApiGatewayExecuteRouteContext { private String httpApiRegion; private boolean restApiRoute; private String signedRequestPath; + private String rewrittenRequestPath; private ApiGatewayService.CustomDomainRoute mappedDomain; void routeToMappedApi(ApiGatewayService.CustomDomainRoute domain, boolean restApi) { @@ -122,4 +123,13 @@ public class ApiGatewayExecuteRouteContext { String signedRequestPath() { return signedRequestPath; } + + /** Retains the intended execute-api path before the routing workaround adds an escape layer. */ + void recordRewrittenRequestPath(String rawPath) { + this.rewrittenRequestPath = rawPath; + } + + String rewrittenRequestPath() { + return rewrittenRequestPath; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionFilter.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionFilter.java index 04491c76b4..2f2ddbbcef 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionFilter.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionFilter.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.cloudfront; import io.github.hectorvent.floci.core.common.RequestHost; +import io.github.hectorvent.floci.core.common.RequestUriRewrite; import io.github.hectorvent.floci.services.cloudfront.model.Distribution; import jakarta.annotation.Priority; import jakarta.enterprise.inject.Instance; @@ -91,6 +92,6 @@ public class CloudFrontDistributionFilter implements ContainerRequestFilter { LOG.debugv("CloudFront distribution routing: {0}{1} -> {2}", host, rawPath, newUri.getPath()); requestContext.setProperty(ROUTED_PROPERTY, Boolean.TRUE); - requestContext.setRequestUri(newUri); + RequestUriRewrite.apply(requestContext, newUri); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilter.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilter.java index f59e2e4968..98b37ad7e7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilter.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilter.java @@ -5,6 +5,7 @@ import io.github.hectorvent.floci.config.LocalStackParity; import io.github.hectorvent.floci.core.common.AwsPartitions; import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.RequestHost; +import io.github.hectorvent.floci.core.common.RequestUriRewrite; import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer; import io.github.hectorvent.floci.core.common.docker.ContainerDetector; import io.github.hectorvent.floci.services.apigateway.ApiGatewayCustomDomainFilter; @@ -175,14 +176,12 @@ public class S3VirtualHostFilter implements ContainerRequestFilter { // Rewrite path from /key to /bucket/key String newPath = "/" + bucket + (path.startsWith("/") ? "" : "/") + path; - // RESTEasy keeps the decoded path of the URI it is given and decodes it again to route, - // so escape it once more to leave the raw path in place, as a path-style request has it. URI newUri = UriBuilder.fromUri(uri) - .replacePath(newPath.replace("%", "%25")) + .replacePath(newPath) .build(); requestContext.setProperty(ORIGINAL_REQUEST_URI_PROPERTY, uri); - requestContext.setRequestUri(newUri); + RequestUriRewrite.apply(requestContext, newUri); } /** diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RequestUriRewriteTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RequestUriRewriteTest.java new file mode 100644 index 0000000000..2578db1c97 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/RequestUriRewriteTest.java @@ -0,0 +1,35 @@ +package io.github.hectorvent.floci.core.common; + +import jakarta.ws.rs.container.ContainerRequestContext; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +import java.net.URI; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +class RequestUriRewriteTest { + + @ParameterizedTest + @ValueSource(strings = { + "plain", "x%25y", "trailing%25", "a%252Fb", "a%2Fb", "a%20b", "a%3Fb%23c", "caf%C3%A9", + "a//b", "a/./b", "a/../b", "a//x%25y" + }) + void escapesTheRoutingPathOnceAndPreservesOtherUriComponents(String suffix) { + ContainerRequestContext requestContext = mock(ContainerRequestContext.class); + URI intendedUri = URI.create("http://example.test:4566/files/" + suffix + "?q=a%2525%26b"); + + RequestUriRewrite.apply(requestContext, intendedUri); + + ArgumentCaptor capturedUri = ArgumentCaptor.forClass(URI.class); + verify(requestContext).setRequestUri(capturedUri.capture()); + URI routingUri = capturedUri.getValue(); + assertEquals(intendedUri.getRawPath(), routingUri.getPath()); + assertEquals(intendedUri.getRawQuery(), routingUri.getRawQuery()); + assertEquals(intendedUri.getScheme(), routingUri.getScheme()); + assertEquals(intendedUri.getRawAuthority(), routingUri.getRawAuthority()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilterTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilterTest.java index f4e53c59ca..7f366c3fad 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilterTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilterTest.java @@ -77,6 +77,21 @@ class ApiGatewayCustomDomainFilterTest { assertEquals(Boolean.TRUE, request.property(ApiGatewayCustomDomainFilter.ROUTED_PROPERTY)); } + @ParameterizedTest + @ValueSource(strings = {"a%25b", "a%2Fb", "a%252Fb"}) + void recordsTheIntendedPathBeforeAddingTheRoutingEscape(String suffix) { + ApiGatewayService service = serviceWithMapping("v1", "prod"); + RecordingRequest request = new RecordingRequest(DOMAIN, URI.create("http://" + DOMAIN + "/v1/" + suffix)); + ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext(); + + new ApiGatewayCustomDomainFilter(service, mock(ApiGatewayV2Service.class), routeContext) + .filter(request.context()); + + assertEquals("/execute-api/" + API_ID + "/prod/" + suffix, routeContext.rewrittenRequestPath()); + assertEquals(routeContext.rewrittenRequestPath(), request.routedUri().getPath()); + assertEquals("/v1/" + suffix, routeContext.signedRequestPath()); + } + @Test void leavesSignedPathUnsetWhenHostIsNotACustomDomain() { ApiGatewayService service = mock(ApiGatewayService.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java index 8e9b383a75..af54d8a9d7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java @@ -63,10 +63,13 @@ class ApiGatewayExecuteApiHostFilterTest { "abc123.execute-api.localhost.floci.io", URI.create("http://abc123.execute-api.localhost.floci.io/files/a%2Fb?value=a%2Fb")); - new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000")) + ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext(); + new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000"), routeContext) .filter(request.context()); - assertEquals("/execute-api/abc123/$default/files/a%2Fb", request.routedUri().getRawPath()); + assertEquals("/execute-api/abc123/$default/files/a%252Fb", request.routedUri().getRawPath()); + assertEquals("/execute-api/abc123/$default/files/a%2Fb", routeContext.rewrittenRequestPath()); + assertEquals("/files/a%2Fb", routeContext.signedRequestPath()); assertEquals("value=a%2Fb", request.routedUri().getRawQuery()); } @@ -101,6 +104,7 @@ class ApiGatewayExecuteApiHostFilterTest { assertEquals("value=a%2Fb", request.routedUri().getRawQuery()); assertNull(routeContext.httpApiRegion()); assertEquals("/dev/deep/path", routeContext.signedRequestPath()); + assertEquals("/execute-api/abc123/dev/deep/path", routeContext.rewrittenRequestPath()); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java index 91957a1c1e..0247687972 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java @@ -49,12 +49,45 @@ import static org.mockito.Mockito.when; class ApiGatewayExecuteControllerTest { private static ApiGatewayExecuteController controller(ObjectMapper objectMapper) { + return controller(objectMapper, new ApiGatewayExecuteRouteContext()); + } + + private static ApiGatewayExecuteController controller(ObjectMapper objectMapper, + ApiGatewayExecuteRouteContext routeContext) { RegionResolver regionResolver = mock(RegionResolver.class); when(regionResolver.getAccountId()).thenReturn("000000000000"); return new ApiGatewayExecuteController( null, null, null, null, regionResolver, objectMapper, null, - null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null, null, null, null); + null, null, null, null, routeContext, null, null, null, null, null, null); + } + + @ParameterizedTest + @ValueSource(strings = { + "/index/a%25b", "/index/a%2Fb", "/index/a%252Fb", "/index/a//b", "/index/a/./b", "/index/a/../b" + }) + void recordedRewritePathTakesPrecedenceOverTheEscapedRoutingUri(String resourcePath) { + ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext(); + String intendedPath = "/execute-api/api1/prod" + resourcePath; + routeContext.recordSignedRequestPath("/public" + resourcePath); + routeContext.recordRewrittenRequestPath(intendedPath); + UriInfo uriInfo = mock(UriInfo.class); + when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost:4566" + + intendedPath.replace("%", "%25"))); + ApiGatewayExecuteController controller = controller(new ObjectMapper(), routeContext); + + assertEquals(intendedPath, controller.rawRequestPath(uriInfo)); + assertEquals(resourcePath, + ApiGatewayExecuteController.rawStagelessPath(resourcePath, controller.rawRequestPath(uriInfo))); + assertEquals("/public" + resourcePath, routeContext.signedRequestPath()); + } + + @Test + void pathStyleRequestsUseTheRawUriPathWhenNoRewriteWasRecorded() { + UriInfo uriInfo = mock(UriInfo.class); + when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost:4566/execute-api/api1/prod/a%2525b")); + + assertEquals("/execute-api/api1/prod/a%2525b", controller(new ObjectMapper()).rawRequestPath(uriInfo)); } @Test 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 index 9a0174a6fb..602a013562 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpProxyEncodedPathIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayHttpProxyEncodedPathIntegrationTest.java @@ -15,6 +15,7 @@ import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; +import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; @@ -131,7 +132,9 @@ class ApiGatewayHttpProxyEncodedPathIntegrationTest { } @ParameterizedTest - @ValueSource(strings = {"NIFTY%2050/constituents", "a%3Fb", "a%23b", "a%2Fb", "a%252Fb", "a+b", "caf%C3%A9"}) + @ValueSource(strings = { + "NIFTY%2050/constituents", "x%25y", "trailing%25", "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); @@ -141,6 +144,60 @@ class ApiGatewayHttpProxyEncodedPathIntegrationTest { assertNull(lastRawQuery.get()); } + @ParameterizedTest + @ValueSource(strings = {"plain", "x%25y", "trailing%25", "a%252Fb", "a%2Fb", "a%20b", "a%3Fb%23c", "caf%C3%A9"}) + void restRoutedHostsKeepTheCallersEncoding(String suffix) { + String apiId = createRestApi("HTTP_PROXY", "/index/{proxy+}", "/backend/{proxy}", null); + String domain = createCustomDomain(apiId); + + try { + given().contentType(ContentType.JSON) + .body(Map.of("restApiId", apiId, "stage", "test", "basePath", "public")) + .when().post("/domainnames/" + domain + "/basepathmappings").then().statusCode(201); + assertRoutedHostsForwardPath(apiId, domain, suffix, "/backend/" + suffix); + } finally { + given().delete("/domainnames/" + domain).then().statusCode(202); + } + } + + @ParameterizedTest + @ValueSource(strings = {"plain", "x%25y", "trailing%25", "a%252Fb", "a%2Fb", "a%20b", "a%3Fb%23c", "caf%C3%A9"}) + void httpApiRoutedHostsKeepTheCallersEncoding(String suffix) { + String apiId = HttpProxyApiFixtures.createProxyApi("encoded-host-http-api", "", "test", backendPort, + "/index/{proxy+}"); + String domain = createCustomDomain(apiId); + + try { + given().contentType(ContentType.JSON) + .body(Map.of("apiId", apiId, "stage", "test", "apiMappingKey", "public")) + .when().post("/v2/domainnames/" + domain + "/apimappings").then().statusCode(201); + assertRoutedHostsForwardPath(apiId, domain, suffix, "/index/" + suffix); + } finally { + given().delete("/domainnames/" + domain).then().statusCode(202); + } + } + + private static String createCustomDomain(String apiId) { + String domain = apiId + ".example.test"; + given().contentType(ContentType.JSON) + .body(Map.of("domainName", domain, "endpointConfiguration", Map.of("types", List.of("REGIONAL")))) + .when().post("/domainnames").then().statusCode(201); + return domain; + } + + private static void assertRoutedHostsForwardPath(String apiId, String domain, String suffix, String expectedPath) { + given().urlEncodingEnabled(false).header("Host", domain) + .when().get("/public/index/" + suffix) + .then().statusCode(200); + assertEquals(expectedPath, lastRawPath.get()); + + lastRawPath.set(null); + given().urlEncodingEnabled(false).header("Host", apiId + ".execute-api.localhost.floci.io") + .when().get("/test/index/" + suffix) + .then().statusCode(200); + assertEquals(expectedPath, lastRawPath.get()); + } + @ParameterizedTest @ValueSource(strings = { "/execute-api/{apiId}/test/index/NIFTY%2050", diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontCustomOriginServingTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontCustomOriginServingTest.java index dbae601dfd..79737c8433 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontCustomOriginServingTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontCustomOriginServingTest.java @@ -23,6 +23,8 @@ import jakarta.inject.Inject; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.io.BufferedReader; import java.io.IOException; @@ -88,6 +90,25 @@ class CloudFrontCustomOriginServingTest { private HttpServer originServer; private CountDownLatch originRelease; + @ParameterizedTest + @ValueSource(strings = {"plain", "x%25y", "trailing%25", "a%252Fb", "a%2Fb", "a%20b", "a%3Fb%23c", "caf%C3%A9"}) + void routedHostsPreserveTheRawOriginPath(String suffix) throws IOException { + AtomicReference received = new AtomicReference<>(); + startRecordingOrigin(received, new AtomicInteger()); + Distribution distribution = customOriginDistribution(defaultBehavior("custom-origin")); + String alias = "encoded-path.example.test"; + distribution.getConfig().setAliases(List.of(alias)); + Distribution created = createDistribution(distribution); + + for (String host : List.of(alias, created.getDomainName())) { + given().urlEncodingEnabled(false).header("Host", host) + .when().get("/" + suffix) + .then().statusCode(200).body(equalTo("ok")); + + assertEquals("/" + suffix, received.get().path()); + } + } + @AfterEach void stopOrigin() { if (originRelease != null) {