From 7ca109b595edc671f2d94f51f81102fa17b52605 Mon Sep 17 00:00:00 2001 From: Mario Toffia Date: Tue, 27 Oct 2026 15:24:07 +0100 Subject: [PATCH] fix(apigateway): route greedy resources below a path parameter (#6690) A REST API resource such as /v1/admin/catalog/{kind}/{name+} never matched: greedy resources were matched by the literal text prefix "/v1/admin/catalog/{kind}/", which no request path starts with, and the template matcher skipped greedy resources. Every parameterised resource also ranked ahead of every greedy one. Match every resource segment by segment and rank all matches the way AWS does: more literal segments, then more segments before the greedy parameter, then the leftmost literal. extractPathParams now yields the parameters before a greedy one, so {kind} reaches the proxy event, $input.params and integration parameter mappings. Closes #6686 --- docs/services/api-gateway.md | 6 + .../ApiGatewayExecuteController.java | 109 ++++++++++-------- ...wayGreedyPathParameterIntegrationTest.java | 57 ++++++++- .../apigateway/ApiGatewayProxyMatchTest.java | 71 ++++++++++++ .../ProxyEventPathParametersTest.java | 10 ++ 5 files changed, 202 insertions(+), 51 deletions(-) diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index 8012fffb59..6e2d839370 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -397,6 +397,12 @@ A greedy resource captures only the path segments after its parent. For example, `/api/v1/auth/signup/{proxy}` forwards the prefix once. Greedy parameter names other than `proxy` are supported, including in `integration.request.path.*` mappings. +A greedy resource may sit below ordinary path parameters: `/catalog/{kind}/{name+}` serves +`/catalog/scopes/a/b` with `kind` set to `scopes` and `name` to `a/b`. When several resources +match a request, they are ranked as on AWS: more literal segments first, then more segments +before the greedy parameter, then the resource whose literal comes first at the first position +where they differ. A resource that does not declare the request's method yields to the next one. + REST `HTTP_PROXY` and `HTTP` integrations also accept `context.*` sources in header, query and path parameter mappings. Supported request fields are `accountId`, `apiId`, `deploymentId`, `httpMethod`, `path` (including the stage), `protocol`, `requestId`, `resourceId`, `resourcePath`, 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 362571ceb9..0ff13511a0 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 @@ -434,7 +434,7 @@ public class ApiGatewayExecuteController { ApiGatewayResource matched = null; MethodConfig method = null; - // Candidates are ordered exact, then parameterised, then greedy. AWS picks the most + // Candidates are ordered most specific first (see matchResources). AWS picks the most // specific resource that can serve the method, so one declaring methods but not this // one yields to a less specific sibling that declares it: /users/me carrying only PATCH // does not hide GET /users/{userId}, and /devices carrying only POST falls through to @@ -4257,55 +4257,28 @@ public class ApiGatewayExecuteController { } /** - * Finds all matching resources for {@code requestPath}, sorted by specificity. - * Priority: exact match > template path match (e.g. /items/{id}) > proxy+ wildcard. + * Finds all matching resources for {@code requestPath}, most specific first. + * + *

Ranked as measured on AWS, with exact, parameterised and greedy resources in one list: + * more literal segments first, then more segments before any greedy parameter, then the + * resource whose literal sits further left at the first position where the two differ. So + * {@code /s/b/{proxy+}} beats {@code /s/{x}/{y}} for {@code /s/b/c}, and + * {@code /a/{x}/c/{z+}} beats {@code /a/b/{proxy+}} for {@code /a/b/c/d}. */ List matchResources(List resources, String requestPath) { + String[] rParts = requestPath.split("/", -1); List matches = new ArrayList<>(); - // 1. Exact match for (ApiGatewayResource r : resources) { - if (requestPath.equals(r.getPath())) { + if (r.getPath() != null && pathMatches(r.getPath(), rParts)) { matches.add(r); } } - // 2. Template path match — /items/{id} matches /items/anything - for (ApiGatewayResource r : resources) { - if (r.getPath() != null && r.getPath().contains("{") && greedyParentPrefix(r.getPath()) == null) { - if (pathMatchesTemplate(r.getPath(), requestPath)) { - matches.add(r); - } - } - } - // 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 proxyMatches = new ArrayList<>(); - for (ApiGatewayResource r : resources) { - String parentPrefix = greedyParentPrefix(r.getPath()); - if (parentPrefix == null) continue; - // Root /{proxy+} matches everything including / - if ("/".equals(parentPrefix)) { - proxyMatches.add(r); - continue; - } - // Non-root proxy+ requires at least one char after the prefix - if (requestPath.startsWith(parentPrefix) - && requestPath.length() > parentPrefix.length()) { - proxyMatches.add(r); - } - } - // Sort proxy matches by parentPrefix length descending - proxyMatches.sort((r1, r2) -> { - String p1 = greedyParentPrefix(r1.getPath()); - String p2 = greedyParentPrefix(r2.getPath()); - return Integer.compare(p2.length(), p1.length()); - }); - matches.addAll(proxyMatches); + matches.sort(ApiGatewayExecuteController::compareSpecificity); return matches; } /** - * Finds the best-matching resource for {@code requestPath}. - * Priority: exact match > template path match (e.g. /items/{id}) > proxy+ wildcard. + * Finds the best-matching resource for {@code requestPath}, the first of {@link #matchResources}. */ ApiGatewayResource matchResource(List resources, String requestPath) { List matches = matchResources(resources, requestPath); @@ -4313,18 +4286,51 @@ public class ApiGatewayExecuteController { } /** - * Returns true if {@code requestPath} matches the template path (e.g. {@code /items/{id}}). - * Segments wrapped in {@code {}} match any single path segment. + * True when every segment before any greedy parameter matches: a literal matches itself, a + * {@code {param}} any one segment. A greedy resource then needs a non-empty remainder, except + * the root {@code /{proxy+}}, which also serves {@code /}; any other resource needs no more + * segments. */ - private boolean pathMatchesTemplate(String templatePath, String requestPath) { - String[] tParts = templatePath.split("/", -1); - String[] rParts = requestPath.split("/", -1); - if (tParts.length != rParts.length) return false; - for (int i = 0; i < tParts.length; i++) { - if (tParts[i].startsWith("{") && tParts[i].endsWith("}")) continue; // wildcard segment - if (!tParts[i].equals(rParts[i])) return false; + private static boolean pathMatches(String resourcePath, String[] rParts) { + String[] fixed = fixedSegments(resourcePath); + boolean greedy = greedyParentPrefix(resourcePath) != null; + if (greedy ? rParts.length < fixed.length : rParts.length != fixed.length) { + return false; } - return true; + for (int i = 0; i < fixed.length; i++) { + if (!isPathParameter(fixed[i]) && !fixed[i].equals(rParts[i])) { + return false; + } + } + return !greedy || fixed.length == 1 + || !String.join("/", Arrays.copyOfRange(rParts, fixed.length, rParts.length)).isEmpty(); + } + + private static int compareSpecificity(ApiGatewayResource a, ApiGatewayResource b) { + String[] fa = fixedSegments(a.getPath()); + String[] fb = fixedSegments(b.getPath()); + int order = Long.compare(literalCount(fb), literalCount(fa)); + if (order == 0) { + order = Integer.compare(fb.length, fa.length); + } + for (int i = 0; order == 0 && i < fa.length; i++) { + order = Boolean.compare(isPathParameter(fa[i]), isPathParameter(fb[i])); + } + return order; + } + + /** The segments of {@code resourcePath} before its greedy parameter, or all of them. */ + private static String[] fixedSegments(String resourcePath) { + String[] parts = resourcePath.split("/", -1); + return greedyParentPrefix(resourcePath) == null ? parts : Arrays.copyOf(parts, parts.length - 1); + } + + private static long literalCount(String[] segments) { + return Arrays.stream(segments).filter(s -> !isPathParameter(s)).count(); + } + + private static boolean isPathParameter(String segment) { + return segment.startsWith("{") && segment.endsWith("}"); } /** @@ -4389,13 +4395,16 @@ public class ApiGatewayExecuteController { /** * 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}}. + * A greedy template such as {@code /catalog/{kind}/{name+}} also yields the parameters before + * its greedy one from a longer request: {@code {kind=scopes}} for {@code /catalog/scopes/a/b}. */ private Map extractPathParams(String templatePath, String requestPath) { Map params = new HashMap<>(); if (templatePath == null || requestPath == null) return params; String[] tParts = templatePath.split("/", -1); String[] rParts = requestPath.split("/", -1); - if (tParts.length != rParts.length) return params; + boolean greedy = greedyParentPrefix(templatePath) != null; + if (greedy ? rParts.length < tParts.length : tParts.length != rParts.length) return params; for (int i = 0; i < tParts.length; i++) { String t = tParts[i]; if (t.startsWith("{") && t.endsWith("}")) { diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayGreedyPathParameterIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayGreedyPathParameterIntegrationTest.java index dd1f6533d1..d2975ef7d9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayGreedyPathParameterIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayGreedyPathParameterIntegrationTest.java @@ -39,7 +39,7 @@ class ApiGatewayGreedyPathParameterIntegrationTest { } @Test @Order(2) - void setupAssetsGreedyResource() { + void setupGreedyResources() { String rootId = given() .when().get("/restapis/" + apiId + "/resources") .then() @@ -94,6 +94,38 @@ class ApiGatewayGreedyPathParameterIntegrationTest { + "/methods/ANY/integration/responses/200") .then() .statusCode(201); + + // /v1/admin/catalog/{kind} lists, /v1/admin/catalog/{kind}/{name+} serves one item + String catalogId = createResource(createResource(createResource(rootId, "v1"), "admin"), "catalog"); + String kindId = createResource(catalogId, "{kind}"); + mockEcho(kindId, "{\"matched\":\"catalog-list\",\"kind\":\"$input.params('kind')\"}"); + mockEcho(createResource(kindId, "{name+}"), "{\"matched\":\"catalog-item\"," + + "\"kind\":\"$input.params('kind')\",\"name\":\"$input.params('name')\"}"); + } + + private static String createResource(String parentId, String pathPart) { + return given() + .contentType(ContentType.JSON) + .body("{\"pathPart\":\"" + pathPart + "\"}") + .when().post("/restapis/" + apiId + "/resources/" + parentId) + .then() + .statusCode(201) + .extract().path("id"); + } + + private static void mockEcho(String resourceId, String responseTemplate) { + 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("{\"responseParameters\":{}}") + .when().put(method + "/responses/200").then().statusCode(201); + given().contentType(ContentType.JSON) + .body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}") + .when().put(method + "/integration").then().statusCode(201); + given().contentType(ContentType.JSON) + .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"" + + responseTemplate.replace("\"", "\\\"") + "\"}}") + .when().put(method + "/integration/responses/200").then().statusCode(201); } @Test @Order(3) @@ -161,6 +193,29 @@ class ApiGatewayGreedyPathParameterIntegrationTest { .body("message", equalTo("Missing Authentication Token")); } + @Test @Order(8) + void greedyResourceBelowAPathParameterReceivesBothParameters() { + // Used to fall through to the no-match 403: the greedy matcher compared the request with + // the literal text "/v1/admin/catalog/{kind}/", which no real path starts with. + given() + .when().get("/execute-api/" + apiId + "/test/v1/admin/catalog/scopes/teos/sur-df") + .then() + .statusCode(200) + .body("matched", equalTo("catalog-item")) + .body("kind", equalTo("scopes")) + .body("name", equalTo("teos/sur-df")); + } + + @Test @Order(9) + void parentResourceStillServesItsOwnPath() { + given() + .when().get("/execute-api/" + apiId + "/test/v1/admin/catalog/scopes") + .then() + .statusCode(200) + .body("matched", equalTo("catalog-list")) + .body("kind", equalTo("scopes")); + } + @Test @Order(99) void cleanup() { given().when().delete("/restapis/" + apiId).then().statusCode(202); diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java index c37d0890a1..65bebbe1d8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayProxyMatchTest.java @@ -220,6 +220,77 @@ class ApiGatewayProxyMatchTest { assertNull(ctrl.matchResource(resources, "/items/1/sub")); } + // ──────────────────────────── greedy below a path parameter ──────────────────────────── + // Measured on AWS: every matching resource, exact, parameterised or greedy, is ranked by its + // literal segments, then by its segments before the greedy parameter, then by the leftmost + // literal. A greedy resource is no longer special-cased behind every parameterised one. + + @Test + void greedyResourceBelowAPathParameterMatches() { + ApiGatewayResource list = resource("r1", "root", "{kind}", "/v1/admin/catalog/{kind}"); + ApiGatewayResource item = resource("r2", "r1", "{name+}", "/v1/admin/catalog/{kind}/{name+}"); + List resources = List.of(item, list); + + assertSame(item, ctrl.matchResource(resources, "/v1/admin/catalog/scopes/teos/sur-df")); + assertSame(item, ctrl.matchResource(resources, "/v1/admin/catalog/scopes/teos")); + assertSame(list, ctrl.matchResource(resources, "/v1/admin/catalog/scopes")); + assertNull(ctrl.matchResource(List.of(item), "/v1/admin/catalog/scopes/")); + assertNull(ctrl.matchResource(List.of(item), "/v1/admin/other/scopes/teos")); + } + + @Test + void moreLiteralSegmentsWinAcrossParameterisedAndGreedyResources() { + ApiGatewayResource greedy = resource("r1", "root", "{proxy+}", "/s/b/{proxy+}"); + ApiGatewayResource template = resource("r2", "root", "{y}", "/s/{x}/{y}"); + ApiGatewayResource deepTemplate = resource("r3", "root", "{v}", "/s/{x}/{y}/{z}/{v}"); + List resources = List.of(template, deepTemplate, greedy); + + assertSame(greedy, ctrl.matchResource(resources, "/s/b/c")); + assertSame(greedy, ctrl.matchResource(resources, "/s/b/c/d/e")); + assertSame(template, ctrl.matchResource(resources, "/s/a/c")); + } + + @Test + void moreLiteralSegmentsBeatADeeperGreedyParent() { + ApiGatewayResource shallow = resource("r1", "root", "{proxy+}", "/q/b/{proxy+}"); + ApiGatewayResource deep = resource("r2", "root", "{p+}", "/q/{x}/{y}/{p+}"); + ApiGatewayResource early = resource("r3", "root", "{p+}", "/m/b/{y}/{z}/{p+}"); + ApiGatewayResource late = resource("r4", "root", "{q+}", "/m/{x}/c/d/{q+}"); + List resources = List.of(deep, shallow, early, late); + + assertSame(shallow, ctrl.matchResource(resources, "/q/b/c/d")); + assertSame(deep, ctrl.matchResource(resources, "/q/a/c/d")); + assertSame(late, ctrl.matchResource(resources, "/m/b/c/d/e")); + } + + @Test + void deeperGreedyParentWinsAtEqualLiteralSegments() { + ApiGatewayResource nested = resource("r1", "root", "{y+}", "/a/{x}/{y+}"); + ApiGatewayResource literal = resource("r2", "root", "{proxy+}", "/a/b/{proxy+}"); + ApiGatewayResource deeper = resource("r3", "root", "{z+}", "/a/{x}/c/{z+}"); + List resources = List.of(nested, literal, deeper); + + assertSame(nested, ctrl.matchResource(resources, "/a/one/two/three")); + assertSame(literal, ctrl.matchResource(resources, "/a/b/c")); + assertEquals(List.of(deeper, literal, nested), ctrl.matchResources(resources, "/a/b/c/d")); + } + + @Test + void leftmostLiteralBreaksATie() { + ApiGatewayResource leftLiteral = resource("r1", "root", "{p+}", "/n/b/{y}/{p+}"); + ApiGatewayResource rightLiteral = resource("r2", "root", "{q+}", "/n/{x}/c/{q+}"); + + assertSame(leftLiteral, ctrl.matchResource(List.of(rightLiteral, leftLiteral), "/n/b/c/d")); + assertSame(leftLiteral, ctrl.matchResource(List.of(leftLiteral, rightLiteral), "/n/b/c/d")); + } + + @Test + void pathParameterMatchesAnEmptySegment() { + ApiGatewayResource template = resource("r1", "root", "two", "/a/{x}/two"); + + assertSame(template, ctrl.matchResource(List.of(template), "/a//two")); + } + // ──────────────────────────── trailing-slash preservation (#1557) ──────────────────────────── @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventPathParametersTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventPathParametersTest.java index a906e3d3ab..6014c106ee 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventPathParametersTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ProxyEventPathParametersTest.java @@ -112,4 +112,14 @@ class ProxyEventPathParametersTest { assertEquals(List.of("rest"), keysOf(pp)); assertEquals("img/logo.png", pp.get("rest").asText()); } + + @Test + void greedyResourceBelowAPathParameterReceivesBothParameters() throws Exception { + JsonNode pp = pathParametersFor("/v1/admin/catalog/scopes/teos/sur-df", + "/v1/admin/catalog/{kind}/{name+}"); + + assertEquals(List.of("kind", "name"), keysOf(pp)); + assertEquals("scopes", pp.get("kind").asText()); + assertEquals("teos/sur-df", pp.get("name").asText()); + } }