fix(apigateway): only emit the greedy path parameter for greedy resources (#3397)

* fix(apigateway): only emit the greedy path parameter for greedy resources

REST (V1) proxy events carried a "proxy" key in pathParameters on every
request, not just for greedy resources. The value came from the controller's
own JAX-RS binding - the class is mounted at @Path("/{proxy: .*}"), so
`proxy` is non-empty for every request regardless of which API Gateway
resource matched.

AWS emits pathParameters.proxy only when the matched resource itself declares
a greedy parameter. For /datasets/{datasetId} it sends {"datasetId": "..."}
and nothing else. Integrations that validate the event against a strict
schema (JSON Schema additionalProperties: false) therefore rejected every
request to a parameterised resource, which made every findOne/updateOne/
deleteOne style route unusable behind such an integration.

The two meanings of "proxy" coincide only for a root-level /{proxy+}
resource, which is why this went unnoticed: that is the shape the code was
originally written for. extractPathParams already skips greedy params
deliberately, and the V2 builder derives them from the route key, so V1 was
the odd one out.

Replace the unconditional put with putGreedyPathParam, which:

  - adds the parameter only when the matched resource declares a greedy
    segment;
  - takes the value from the remainder after the literal prefix, so
    /files/{proxy+} matching /files/a/b/c yields "a/b/c" rather than the
    whole request path; and
  - reads the parameter name from the template, since {proxy+} is only the
    conventional spelling and AWS permits any name.

The now-unused JAX-RS capture is dropped from the buildProxyEvent signature
so it cannot leak into the event again.

* fix(apigateway): route greedy resources named other than {proxy+}

AWS does not reserve the greedy path parameter name - "you can use any
string for the greedy path parameter name" - and /parent/{name+} matches
every descendant below that parent.

buildProxyEvent already reads the name from the template, but the REST
router still keyed on the literal {proxy+} in three places: the exclusion
in the template-match arm, the guard in the greedy-match arm, and the
parent-prefix extraction used by both that arm and its specificity sort.

A resource such as /assets/{rest+} therefore only half routed. It fell to
the template arm, where pathMatchesTemplate compares segment counts and
treats {rest+} as an ordinary single-segment wildcard, so /assets/foo
matched while /assets/img/logo.png - the whole point of a greedy resource
- matched nothing at all. A quick manual check passes, which is why the
unit test added with the previous commit stayed green: it calls
buildProxyEvent directly and never exercises routing.

Recognise a greedy segment by its trailing "+" rather than by name, via
greedyParentPrefix, and route on that. Only a terminal greedy segment
counts, matching AWS, where a greedy parameter is allowed solely as the
last segment of a resource path. Specificity is unchanged: exact beats
template beats greedy, and greedy resources still sort by longest parent
prefix.

extractPathParams already generalised on the trailing "+", so it needed no
change. putGreedyPathParam becomes greedyPathParam, returning a map like
its extractPathParams companion and sharing the same terminal-segment
detection instead of scanning for the first greedy part.

Tested through the real request path, per AGENTS.md: the new
ApiGatewayGreedyPathParameterIntegrationTest stands up /assets/{rest+}
with a MOCK integration and drives it over HTTP. Without this change its
multi-segment and deeply-nested cases fail while the single-segment case
passes, reproducing the half-routing exactly. ApiGatewayProxyMatchTest
adds five routing assertions for non-proxy greedy names, four of which
fail without it.

* fix(apigateway): emit the greedy path parameter to mapping templates too

The same rule the previous two commits applied to the Lambda proxy event
was wrong in the two mapping-template paths, in opposite directions.

invokeAwsIntegration built its pathParameters from the JAX-RS capture,
exactly as buildProxyEvent used to, so $input.params('proxy') and a
method.request.path.proxy mapping resolved on every request rather than
only for a greedy resource, and carried the whole request path instead of
the remainder after the prefix.

invokeMock had the opposite gap: it used extractPathParams alone, which
deliberately skips greedy parameters, so $input.params('proxy') was empty
for a greedy resource where AWS supplies the captured remainder.

Both now compose extractPathParams with greedyPathParam, matching
buildProxyEvent, so the three paths agree on what a matched resource
declares. AGENTS.md asks for compatibility to be checked across alternate
protocol paths; these are the alternates for this behaviour.

As with buildProxyEvent, the JAX-RS capture was invokeAwsIntegration's only
use of the proxy argument, so it is dropped from the signature rather than
left available to leak back in.

ApiGatewayGreedyPathParameterIntegrationTest now asserts the captured value
over HTTP and not merely the route: its MOCK response template echoes
$input.params('rest'), so the greedy value must arrive under the name the
template declares. All three assertions fail without this change.
This commit is contained in:
Ovidiu authored and GitHub committed 2026-09-12 13:32:20 -04:00
1 parent 99c19d03d2
commit 547090bdfb
5 files changed
+408 -17

No files matched your search

@@ -44,6 +44,7 @@ import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
@@ -405,7 +406,7 @@ public class ApiGatewayExecuteController {
case "AWS_PROXY" -> invokeProxy(region, apiId, httpMethod, path, proxy, stageName,
matched, stage, integration, headers, uriInfo, body, authorizerResult, resolvedApiKey,
iamIdentity);
case "AWS" -> invokeAwsIntegration(region, httpMethod, path, proxy, stageName,
case "AWS" -> invokeAwsIntegration(region, httpMethod, path, stageName,
matched, integration, headers, uriInfo, body);
case "MOCK" -> invokeMock(region, httpMethod, path, stageName, matched, integration, headers, uriInfo, body);
default -> Response.status(500)
@@ -436,7 +437,7 @@ public class ApiGatewayExecuteController {
}
String requestId = UUID.randomUUID().toString();
String eventJson = buildProxyEvent(region, apiId, httpMethod, path, proxy, resource.getPath(),
String eventJson = buildProxyEvent(region, apiId, httpMethod, path, resource.getPath(),
resource.getId(), stageName, stage, headers, uriInfo, body, requestId,
authorizerResult.principalId(), authorizerResult.context(), resolvedApiKey, iamIdentity);
@@ -725,7 +726,7 @@ public class ApiGatewayExecuteController {
// Package-private rather than private so a focused unit test can assert the event's wire shape
// without standing up a Lambda runtime, mirroring the buildV2ProxyEvent tests.
String buildProxyEvent(String region, String apiId,
String httpMethod, String path, String proxy,
String httpMethod, String path,
String resourcePath, String resourceId,
String stageName, Stage stage,
HttpHeaders headers, UriInfo uriInfo,
@@ -750,12 +751,10 @@ public class ApiGatewayExecuteController {
putMultiValueQueryStringParameters(event, uriInfo);
// pathParameters come from the matcher, which ran on the normalized path, so the greedy
// {proxy+} value has no trailing slash on real AWS even when event.path keeps one.
// value has no trailing slash on real AWS even when event.path keeps one.
ObjectNode pathParams = event.putObject("pathParameters");
if (proxy != null && !proxy.isEmpty()) {
pathParams.put("proxy", proxy);
}
extractPathParams(resourcePath, path).forEach(pathParams::put);
greedyPathParam(resourcePath, path).forEach(pathParams::put);
// stageVariables: populate from the Stage object (null if no variables configured)
Map<String, String> stageVars = stage != null ? stage.getVariables() : null;
@@ -988,7 +987,7 @@ public class ApiGatewayExecuteController {
return params;
}
private Response invokeAwsIntegration(String region, String httpMethod, String path, String proxy,
private Response invokeAwsIntegration(String region, String httpMethod, String path,
String stageName, ApiGatewayResource resource,
Integration integration, HttpHeaders headers,
UriInfo uriInfo, byte[] body) {
@@ -1012,8 +1011,8 @@ public class ApiGatewayExecuteController {
if (!e.getValue().isEmpty()) queryMap.put(e.getKey(), e.getValue().get(0));
}
Map<String, String> pathMap = new HashMap<>();
if (proxy != null && !proxy.isEmpty()) pathMap.put("proxy", proxy);
pathMap.putAll(extractPathParams(resource.getPath(), path));
pathMap.putAll(greedyPathParam(resource.getPath(), path));
String incomingContentType = headerMap.getOrDefault("Content-Type",
headerMap.getOrDefault("content-type", "application/json"));
@@ -1371,6 +1370,7 @@ public class ApiGatewayExecuteController {
}
}
Map<String, String> pathMap = new HashMap<>(extractPathParams(resource.getPath(), path));
pathMap.putAll(greedyPathParam(resource.getPath(), path));
VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
@@ -2703,18 +2703,18 @@ public class ApiGatewayExecuteController {
}
// 2. Template path match — /items/{id} matches /items/anything
for (ApiGatewayResource r : resources) {
if (r.getPath() != null && r.getPath().contains("{") && !r.getPath().contains("{proxy+}")) {
if (r.getPath() != null && r.getPath().contains("{") && greedyParentPrefix(r.getPath()) == null) {
if (pathMatchesTemplate(r.getPath(), requestPath)) {
matches.add(r);
}
}
}
// 3. Proxy+ wildcard — {proxy+} matches longest parent prefix
// 3. Greedy wildcard: {proxy+}, or any other {name+}, matches longest parent prefix
// Requires at least one path segment after the parent prefix (except root /{proxy+})
List<ApiGatewayResource> proxyMatches = new ArrayList<>();
for (ApiGatewayResource r : resources) {
if (r.getPath() == null || !r.getPath().contains("{proxy+}")) continue;
String parentPrefix = r.getPath().substring(0, r.getPath().indexOf("{proxy+}"));
String parentPrefix = greedyParentPrefix(r.getPath());
if (parentPrefix == null) continue;
// Root /{proxy+} matches everything including /
if ("/".equals(parentPrefix)) {
proxyMatches.add(r);
@@ -2728,8 +2728,8 @@ public class ApiGatewayExecuteController {
}
// Sort proxy matches by parentPrefix length descending
proxyMatches.sort((r1, r2) -> {
String p1 = r1.getPath().substring(0, r1.getPath().indexOf("{proxy+}"));
String p2 = r2.getPath().substring(0, r2.getPath().indexOf("{proxy+}"));
String p1 = greedyParentPrefix(r1.getPath());
String p2 = greedyParentPrefix(r2.getPath());
return Integer.compare(p2.length(), p1.length());
});
matches.addAll(proxyMatches);
@@ -2760,6 +2760,65 @@ public class ApiGatewayExecuteController {
return true;
}
/**
* True for a greedy path segment: {@code {proxy+}}, {@code {rest+}}, any {@code {name+}}.
*
* <p>AWS does not reserve the name: "you can use any string for the greedy path parameter
* name", so the segment is recognised by its trailing {@code +} rather than by the
* conventional {@code proxy} spelling. {@code {+}} is not greedy: the name must be present.
*/
private static boolean isGreedySegment(String segment) {
return segment.length() > 3 && segment.startsWith("{") && segment.endsWith("+}");
}
/**
* Returns the literal prefix preceding a resource's greedy segment, or {@code null} when the
* resource declares none. {@code /assets/{rest+}} yields {@code /assets/}, and the root greedy
* resource {@code /{proxy+}} yields {@code /}.
*
* <p>Only a <em>terminal</em> greedy segment counts, matching AWS, where a greedy parameter is
* allowed solely as the last segment of a resource path and captures every descendant below
* the parent. This is what lets routing treat {@code /assets/{rest+}} as greedy: keying on the
* literal {@code {proxy+}} left such a resource to the single-segment template matcher, which
* compares segment counts, so {@code /assets/foo} matched but {@code /assets/img/logo.png}
* matched nothing at all.
*/
private static String greedyParentPrefix(String resourcePath) {
if (resourcePath == null) return null;
int lastSlash = resourcePath.lastIndexOf('/');
if (lastSlash < 0) return null;
if (!isGreedySegment(resourcePath.substring(lastSlash + 1))) return null;
return resourcePath.substring(0, lastSlash + 1);
}
/**
* Returns the greedy path parameter for a matched resource, or an empty map when the resource
* declares none. It is the companion to {@link #extractPathParams}, which skips it deliberately.
*
* <p>AWS emits it solely for a greedy resource such as {@code /files/{proxy+}}, and its value
* is the remainder after the literal prefix: {@code a/b/c} for {@code /files/a/b/c}, not the
* whole request path. A plain parameterised resource such as {@code /datasets/{datasetId}}
* receives no extra key, so integrations validating the event against a strict schema
* (JSON Schema {@code additionalProperties: false}) do not see an undeclared property.
*
* <p>The parameter is named by the template, since {@code {proxy+}} is only the conventional
* spelling, so the name is read from the resource rather than hardcoded.
*/
private static Map<String, String> greedyPathParam(String resourcePath, String requestPath) {
if (requestPath == null || greedyParentPrefix(resourcePath) == null) return Map.of();
String[] tParts = resourcePath.split("/", -1);
int greedyIndex = tParts.length - 1; // terminal by definition of greedyParentPrefix
String greedy = tParts[greedyIndex];
String name = greedy.substring(1, greedy.length() - 2);
String[] rParts = requestPath.split("/", -1);
if (rParts.length <= greedyIndex) return Map.of();
String remainder = String.join("/", Arrays.copyOfRange(rParts, greedyIndex, rParts.length));
return remainder.isEmpty() ? Map.of() : Map.of(name, remainder);
}
/**
* Extracts named path parameters from a matched template path.
* Given template {@code /items/{id}} and request {@code /items/item-1}, returns {@code {id=item-1}}.
@@ -0,0 +1,165 @@
package io.github.hectorvent.floci.services.apigateway;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
/**
* A greedy resource whose parameter is not named {@code proxy} must route and capture like one.
*
* <p>AWS does not reserve the name: "you can use any string for the greedy path parameter name",
* and {@code /parent/{name+}} matches every descendant below the parent. Exercised through the real
* request path rather than the event builder, because the defect this covers was in routing: keying
* on the literal {@code {proxy+}} left {@code /assets/{rest+}} to the single-segment template
* matcher, so {@code /assets/foo} matched while the multi-segment {@code /assets/img/logo.png},
* the whole point of a greedy resource, matched nothing at all.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ApiGatewayGreedyPathParameterIntegrationTest {
private static String apiId;
private static String greedyResourceId;
@Test @Order(1)
void createRestApi() {
apiId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"greedy-path-parameter-test-api\"}")
.when().post("/restapis")
.then()
.statusCode(201)
.extract().path("id");
}
@Test @Order(2)
void setupAssetsGreedyResource() {
String rootId = given()
.when().get("/restapis/" + apiId + "/resources")
.then()
.statusCode(200)
.extract().path("item[0].id");
String assetsId = given()
.contentType(ContentType.JSON)
.body("{\"pathPart\":\"assets\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then()
.statusCode(201)
.extract().path("id");
// /assets/{rest+}: greedy, deliberately not named "proxy"
greedyResourceId = given()
.contentType(ContentType.JSON)
.body("{\"pathPart\":\"{rest+}\"}")
.when().post("/restapis/" + apiId + "/resources/" + assetsId)
.then()
.statusCode(201)
.body("path", equalTo("/assets/{rest+}"))
.extract().path("id");
given()
.contentType(ContentType.JSON)
.body("{\"authorizationType\":\"NONE\"}")
.when().put("/restapis/" + apiId + "/resources/" + greedyResourceId + "/methods/ANY")
.then()
.statusCode(201);
given()
.contentType(ContentType.JSON)
.body("{\"responseParameters\":{}}")
.when().put("/restapis/" + apiId + "/resources/" + greedyResourceId + "/methods/ANY/responses/200")
.then()
.statusCode(201);
given()
.contentType(ContentType.JSON)
.body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}")
.when().put("/restapis/" + apiId + "/resources/" + greedyResourceId + "/methods/ANY/integration")
.then()
.statusCode(201);
given()
.contentType(ContentType.JSON)
.body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":"
+ "\"{\\\"matched\\\":\\\"assets-greedy\\\","
+ "\\\"rest\\\":\\\"$input.params('rest')\\\"}\"}}")
.when().put("/restapis/" + apiId + "/resources/" + greedyResourceId
+ "/methods/ANY/integration/responses/200")
.then()
.statusCode(201);
}
@Test @Order(3)
void createDeploymentAndStage() {
String deploymentId = given()
.contentType(ContentType.JSON)
.body("{\"description\":\"v1\"}")
.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);
}
@Test @Order(4)
void multiSegmentRequestReachesTheGreedyResource() {
// The case that used to 404: more segments than the template, so the single-segment
// template matcher rejected it and greedy matching never considered a non-"proxy" name.
given()
.when().get("/execute-api/" + apiId + "/test/assets/img/logo.png")
.then()
.statusCode(200)
.body("matched", equalTo("assets-greedy"))
// The captured value is the remainder after the literal prefix, under the name the
// template declares - not "proxy", and not the whole request path.
.body("rest", equalTo("img/logo.png"));
}
@Test @Order(5)
void singleSegmentRequestStillReachesTheGreedyResource() {
// This one passed even before the fix, by accident, which is why a manual check looked fine.
given()
.when().get("/execute-api/" + apiId + "/test/assets/logo.png")
.then()
.statusCode(200)
.body("matched", equalTo("assets-greedy"))
.body("rest", equalTo("logo.png"));
}
@Test @Order(6)
void deeplyNestedRequestReachesTheGreedyResource() {
given()
.when().get("/execute-api/" + apiId + "/test/assets/a/b/c/d")
.then()
.statusCode(200)
.body("matched", equalTo("assets-greedy"))
.body("rest", equalTo("a/b/c/d"));
}
@Test @Order(7)
void pathOutsideTheParentPrefixDoesNotMatch() {
// The greedy resource must not have become a catch-all for the whole API.
given()
.when().get("/execute-api/" + apiId + "/test/other/img/logo.png")
.then()
.statusCode(404);
}
@Test @Order(99)
void cleanup() {
given().when().delete("/restapis/" + apiId).then().statusCode(202);
}
}
@@ -155,6 +155,71 @@ class ApiGatewayProxyMatchTest {
assertSame(rootProxy, matched.get(2));
}
// ──────────────────────────── arbitrary greedy parameter names ────────────────────────────
// AWS: "you can use any string for the greedy path parameter name". Routing must key on the
// trailing "+", not on the literal {proxy+}, or a resource such as /assets/{rest+} only half
// routes: the single-segment template matcher accepts /assets/foo while the multi-segment
// /assets/img/logo.png, the whole point of a greedy resource, matches nothing.
@Test
void greedyResourceMatchesRegardlessOfParameterName() {
ApiGatewayResource assets = resource("r1", "root", "{rest+}", "/assets/{rest+}");
List<ApiGatewayResource> resources = List.of(assets);
assertSame(assets, ctrl.matchResource(resources, "/assets/img/logo.png"));
assertSame(assets, ctrl.matchResource(resources, "/assets/foo"));
assertNull(ctrl.matchResource(resources, "/assets/"));
assertNull(ctrl.matchResource(resources, "/other/thing"));
}
@Test
void rootGreedyWithNonProxyNameMatchesEverything() {
ApiGatewayResource rootGreedy = resource("r1", "root", "{path+}", "/{path+}");
assertSame(rootGreedy, ctrl.matchResource(List.of(rootGreedy), "/anything"));
assertSame(rootGreedy, ctrl.matchResource(List.of(rootGreedy), "/"));
assertSame(rootGreedy, ctrl.matchResource(List.of(rootGreedy), "/a/b/c"));
}
@Test
void specificityRulesHoldForNonProxyGreedyNames() {
ApiGatewayResource exact = resource("r1", "root", "logo.png", "/assets/logo.png");
ApiGatewayResource template = resource("r2", "root", "{id}", "/assets/{id}");
ApiGatewayResource greedy = resource("r3", "root", "{rest+}", "/assets/{rest+}");
List<ApiGatewayResource> resources = List.of(greedy, template, exact);
// exact > template > greedy, unchanged by the parameter's name
assertSame(exact, ctrl.matchResource(resources, "/assets/logo.png"));
assertSame(template, ctrl.matchResource(resources, "/assets/banner.png"));
assertSame(greedy, ctrl.matchResource(resources, "/assets/img/logo.png"));
}
@Test
void longestParentPrefixWinsAcrossMixedGreedyNames() {
ApiGatewayResource apiGreedy = resource("r1", "root", "{proxy+}", "/api/{proxy+}");
ApiGatewayResource apiV1Greedy = resource("r2", "root", "{rest+}", "/api/v1/{rest+}");
List<ApiGatewayResource> resources = List.of(apiGreedy, apiV1Greedy);
assertSame(apiV1Greedy, ctrl.matchResource(resources, "/api/v1/users"));
assertSame(apiGreedy, ctrl.matchResource(resources, "/api/v2/users"));
List<ApiGatewayResource> matched = ctrl.matchResources(resources, "/api/v1/users/1");
assertEquals(2, matched.size());
assertSame(apiV1Greedy, matched.get(0));
assertSame(apiGreedy, matched.get(1));
}
@Test
void aParameterNamedWithATrailingPlusIsNotConfusedWithAnOrdinaryOne() {
// {id} is a single-segment template; it must keep matching exactly one segment even when a
// greedy sibling exists, and must not be mistaken for greedy by the new prefix helper.
ApiGatewayResource template = resource("r1", "root", "{id}", "/items/{id}");
List<ApiGatewayResource> resources = List.of(template);
assertSame(template, ctrl.matchResource(resources, "/items/1"));
assertNull(ctrl.matchResource(resources, "/items/1/sub"));
}
// ──────────────────────────── trailing-slash preservation (#1557) ────────────────────────────
@Test
@@ -56,7 +56,7 @@ class ProxyEventIamIdentityTest {
@Test
void restIdentityCarriesTheVerifiedIamCaller() throws Exception {
JsonNode identity = MAPPER.readTree(controller.buildProxyEvent(
"us-east-1", "api1", "GET", "/iam", "iam", "/iam", "res1", "test", null,
"us-east-1", "api1", "GET", "/iam", "/iam", "res1", "test", null,
headers, uriInfo, null, "req-1", null, null, null, CALLER))
.path("requestContext").path("identity");
@@ -70,7 +70,7 @@ class ProxyEventIamIdentityTest {
@Test
void restIdentityStaysExplicitlyNullWithoutIamAuthorization() throws Exception {
JsonNode identity = MAPPER.readTree(controller.buildProxyEvent(
"us-east-1", "api1", "GET", "/open", "open", "/open", "res2", "test", null,
"us-east-1", "api1", "GET", "/open", "/open", "res2", "test", null,
headers, uriInfo, null, "req-2", null, null, null, null))
.path("requestContext").path("identity");
@@ -0,0 +1,102 @@
package io.github.hectorvent.floci.services.apigateway;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.RegionResolver;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* REST (V1) pathParameters must contain exactly the parameters declared by the matched resource.
* AWS only emits a "proxy" key when the matched resource itself is greedy ({proxy+}); for a plain
* parameterised resource such as /datasets/{datasetId} it sends {"datasetId": "..."} and nothing
* else. Integrations that validate the event against a strict schema
* (additionalProperties: false) reject the request outright when an undeclared key appears.
*/
class ProxyEventPathParametersTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private ApiGatewayExecuteController controller;
private HttpHeaders headers;
private UriInfo uriInfo;
@BeforeEach
void setUp() throws Exception {
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
headers = mock(HttpHeaders.class);
when(headers.getRequestHeaders()).thenReturn(new MultivaluedHashMap<>());
uriInfo = mock(UriInfo.class);
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
when(uriInfo.getRequestUri()).thenReturn(
new URI("http://localhost:4566/execute-api/api1/v1/datasets/abc123"));
controller = new ApiGatewayExecuteController(
null, null, null,
regionResolver, MAPPER, null,
null, null, null, null, new ApiGatewayExecuteRouteContext(), null, null, null);
}
private JsonNode pathParametersFor(String path, String resourcePath) throws Exception {
return MAPPER.readTree(controller.buildProxyEvent(
"us-east-1", "api1", "GET", path, resourcePath, "res1", "v1", null,
headers, uriInfo, null, "req-1", null, null, null, null))
.get("pathParameters");
}
private static List<String> keysOf(JsonNode node) {
List<String> keys = new ArrayList<>();
node.fieldNames().forEachRemaining(keys::add);
java.util.Collections.sort(keys);
return keys;
}
@Test
void nonGreedyResourceEmitsOnlyItsDeclaredPathParameters() throws Exception {
JsonNode pp = pathParametersFor("/datasets/abc123", "/datasets/{datasetId}");
assertEquals(List.of("datasetId"), keysOf(pp),
"a non-greedy resource must not receive an undeclared \"proxy\" key");
assertEquals("abc123", pp.get("datasetId").asText());
}
@Test
void greedyResourceReceivesTheRemainderAfterItsLiteralPrefix() throws Exception {
JsonNode pp = pathParametersFor("/files/a/b/c", "/files/{proxy+}");
assertEquals(List.of("proxy"), keysOf(pp));
assertEquals("a/b/c", pp.get("proxy").asText(),
"the greedy value is the remainder, not the whole request path");
}
@Test
void rootGreedyResourceReceivesTheWholePath() throws Exception {
JsonNode pp = pathParametersFor("/files/a/b", "/{proxy+}");
assertEquals(List.of("proxy"), keysOf(pp));
assertEquals("files/a/b", pp.get("proxy").asText());
}
@Test
void greedyParameterIsNamedByTheTemplate() throws Exception {
JsonNode pp = pathParametersFor("/assets/img/logo.png", "/assets/{rest+}");
assertEquals(List.of("rest"), keysOf(pp));
assertEquals("img/logo.png", pp.get("rest").asText());
}
}