Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(apigateway): fall through to less specific resources on method mi… (#1630)

MAN$I VERMA96c7aa68ee58
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 c5ff93829a..f298e119d3 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
@@ -39,6 +39,7 @@ import org.jboss.logging.Logger;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
+import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
@@ -266,18 +267,32 @@ public class ApiGatewayExecuteController {
// Find matching resource and method
List<ApiGatewayResource> resources = apiGatewayService.getResources(region, apiId);
- ApiGatewayResource matched = matchResource(resources, path);
- if (matched == null) {
+ List<ApiGatewayResource> matchedResources = matchResources(resources, path);
+ if (matchedResources.isEmpty()) {
return Response.status(404)
.entity(jsonMessage("Not Found"))
.type(MediaType.APPLICATION_JSON).build();
}
- MethodConfig method = matched.getResourceMethods().get(httpMethod.toUpperCase());
- if (method == null) {
- method = matched.getResourceMethods().get("ANY");
+ ApiGatewayResource matched = null;
+ MethodConfig method = null;
+ for (ApiGatewayResource r : matchedResources) {
+ if (r.getResourceMethods() != null && !r.getResourceMethods().isEmpty()) {
+ MethodConfig m = r.getResourceMethods().get(httpMethod.toUpperCase());
+ if (m == null) {
+ m = r.getResourceMethods().get("ANY");
+ }
+ if (m != null) {
+ matched = r;
+ method = m;
+ }
+ // Once we match a path that has methods configured, we must not fall back
+ // to less specific sibling resources (e.g. /{proxy+}), even on method mismatch.
+ break;
+ }
}
- if (method == null) {
+
+ if (matched == null) {
return Response.status(405)
.entity(jsonMessage("Method Not Allowed"))
.type(MediaType.APPLICATION_JSON).build();
@@ -1890,48 +1905,59 @@ public class ApiGatewayExecuteController {
// ──────────────────────────── Path matching ────────────────────────────
/**
- * Finds the best-matching resource for {@code requestPath}.
+ * Finds all matching resources for {@code requestPath}, sorted by specificity.
* Priority: exact match > template path match (e.g. /items/{id}) > proxy+ wildcard.
*/
- ApiGatewayResource matchResource(List<ApiGatewayResource> resources, String requestPath) {
+ List<ApiGatewayResource> matchResources(List<ApiGatewayResource> resources, String requestPath) {
+ List<ApiGatewayResource> matches = new ArrayList<>();
// 1. Exact match
for (ApiGatewayResource r : resources) {
if (requestPath.equals(r.getPath())) {
- return r;
+ matches.add(r);
}
}
// 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 (pathMatchesTemplate(r.getPath(), requestPath)) {
- return r;
+ matches.add(r);
}
}
}
// 3. Proxy+ wildcard — {proxy+} matches longest parent prefix
// Requires at least one path segment after the parent prefix (except root /{proxy+})
- ApiGatewayResource best = null;
- int bestLen = -1;
+ 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+}"));
// Root /{proxy+} matches everything including /
if ("/".equals(parentPrefix)) {
- if (best == null) {
- best = r;
- bestLen = 0;
- }
+ proxyMatches.add(r);
continue;
}
// Non-root proxy+ requires at least one char after the prefix
if (requestPath.startsWith(parentPrefix)
- && requestPath.length() > parentPrefix.length()
- && parentPrefix.length() > bestLen) {
- best = r;
- bestLen = parentPrefix.length();
+ && requestPath.length() > parentPrefix.length()) {
+ proxyMatches.add(r);
}
}
- return best;
+ // 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+}"));
+ return Integer.compare(p2.length(), p1.length());
+ });
+ matches.addAll(proxyMatches);
+ return matches;
+ }
+
+ /**
+ * Finds the best-matching resource for {@code requestPath}.
+ * Priority: exact match > template path match (e.g. /items/{id}) > proxy+ wildcard.
+ */
+ ApiGatewayResource matchResource(List<ApiGatewayResource> resources, String requestPath) {
+ List<ApiGatewayResource> matches = matchResources(resources, requestPath);
+ return matches.isEmpty() ? null : matches.get(0);
}
/**
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 0411f19b64..89d1fff155 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
@@ -128,6 +128,32 @@ class ApiGatewayProxyMatchTest {
assertNull(ctrl.matchResource(List.of(authProxy), "/other/path"));
}
+ @Test
+ void testMatchResourcesPrecedence() {
+ ApiGatewayResource widgets = resource("r1", "root", "widgets", "/widgets");
+ ApiGatewayResource rootProxy = resource("r2", "root", "{proxy+}", "/{proxy+}");
+ List<ApiGatewayResource> resources = List.of(rootProxy, widgets);
+
+ List<ApiGatewayResource> matched = ctrl.matchResources(resources, "/widgets");
+ assertEquals(2, matched.size());
+ assertSame(widgets, matched.get(0));
+ assertSame(rootProxy, matched.get(1));
+ }
+
+ @Test
+ void testMatchResourcesMultipleProxies() {
+ ApiGatewayResource rootProxy = resource("r1", "root", "{proxy+}", "/{proxy+}");
+ ApiGatewayResource authProxy = resource("r2", "root", "{proxy+}", "/auth/{proxy+}");
+ ApiGatewayResource usersProxy = resource("r3", "root", "{proxy+}", "/auth/users/{proxy+}");
+ List<ApiGatewayResource> resources = List.of(rootProxy, authProxy, usersProxy);
+
+ List<ApiGatewayResource> matched = ctrl.matchResources(resources, "/auth/users/details");
+ assertEquals(3, matched.size());
+ assertSame(usersProxy, matched.get(0));
+ assertSame(authProxy, matched.get(1));
+ assertSame(rootProxy, matched.get(2));
+ }
+
// ──────────────────────────── ELB_LISTENER_ARN ────────────────────────────
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRoutingFallthroughIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRoutingFallthroughIntegrationTest.java
new file mode 100644
index 0000000000..7180d7c58f
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRoutingFallthroughIntegrationTest.java
@@ -0,0 +1,213 @@
+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.*;
+
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class ApiGatewayRoutingFallthroughIntegrationTest {
+
+ private static String apiId;
+ private static String rootId;
+ private static String proxyResourceId;
+ private static String concreteResourceId;
+ private static String deploymentId;
+
+ @Test @Order(1)
+ void createRestApi() {
+ apiId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"routing-fallthrough-test-api\"}")
+ .when().post("/restapis")
+ .then()
+ .statusCode(201)
+ .body("id", notNullValue())
+ .extract().path("id");
+ }
+
+ @Test @Order(2)
+ void setupResourcesAndMethods() {
+ rootId = given()
+ .when().get("/restapis/" + apiId + "/resources")
+ .then()
+ .statusCode(200)
+ .extract().path("item[0].id");
+
+ // Create /{proxy+} resource
+ proxyResourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"{proxy+}\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+
+ // Create method ANY on /{proxy+}
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + proxyResourceId + "/methods/ANY")
+ .then()
+ .statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"responseParameters\":{}}")
+ .when().put("/restapis/" + apiId + "/resources/" + proxyResourceId + "/methods/ANY/responses/200")
+ .then()
+ .statusCode(201);
+
+ // Put MOCK integration for /{proxy+} ANY
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + proxyResourceId + "/methods/ANY/integration")
+ .then()
+ .statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{\\\"matched\\\":\\\"proxy\\\"}\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + proxyResourceId + "/methods/ANY/integration/responses/200")
+ .then()
+ .statusCode(201);
+
+ // Create /widgets resource
+ concreteResourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"widgets\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+
+ // NOTE: We do NOT create any methods on the /widgets resource! It is method-less.
+
+ // Create /devices resource
+ String devicesResourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"devices\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+
+ // Create method POST on /devices
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put("/restapis/" + apiId + "/resources/" + devicesResourceId + "/methods/POST")
+ .then()
+ .statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"responseParameters\":{}}")
+ .when().put("/restapis/" + apiId + "/resources/" + devicesResourceId + "/methods/POST/responses/200")
+ .then()
+ .statusCode(201);
+
+ // Put MOCK integration for /devices POST
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + devicesResourceId + "/methods/POST/integration")
+ .then()
+ .statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{\\\"matched\\\":\\\"devices-post\\\"}\"}}")
+ .when().put("/restapis/" + apiId + "/resources/" + devicesResourceId + "/methods/POST/integration/responses/200")
+ .then()
+ .statusCode(201);
+ }
+
+ @Test @Order(3)
+ void createDeploymentAndStage() {
+ 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 getWidgetsFallsThroughToProxy() {
+ // Request GET /widgets.
+ // /widgets has no GET method, so it should fall through to /{proxy+} ANY
+ given()
+ .when().get("/execute-api/" + apiId + "/test/widgets")
+ .then()
+ .statusCode(200)
+ .body("matched", equalTo("proxy"));
+ }
+
+ @Test @Order(5)
+ void postWidgetsFallsThroughToProxy() {
+ // Request POST /widgets.
+ // /widgets has no POST method, so it should fall through to /{proxy+} ANY
+ given()
+ .contentType(ContentType.JSON)
+ .when().post("/execute-api/" + apiId + "/test/widgets")
+ .then()
+ .statusCode(200)
+ .body("matched", equalTo("proxy"));
+ }
+
+ @Test @Order(6)
+ void otherPathMatchesProxy() {
+ // Request GET /other.
+ // /other matches /{proxy+} ANY
+ given()
+ .when().get("/execute-api/" + apiId + "/test/other")
+ .then()
+ .statusCode(200)
+ .body("matched", equalTo("proxy"));
+ }
+
+ @Test @Order(7)
+ void getDevicesReturns405() {
+ // Request GET /devices.
+ // /devices has POST but no GET, so it should return 405 Method Not Allowed,
+ // and NOT fall back to /{proxy+} ANY.
+ given()
+ .when().get("/execute-api/" + apiId + "/test/devices")
+ .then()
+ .statusCode(405)
+ .body("message", equalTo("Method Not Allowed"));
+ }
+
+ @Test @Order(8)
+ void postDevicesSucceeds() {
+ // Request POST /devices.
+ // /devices has POST, so it should succeed.
+ given()
+ .contentType(ContentType.JSON)
+ .when().post("/execute-api/" + apiId + "/test/devices")
+ .then()
+ .statusCode(200)
+ .body("matched", equalTo("devices-post"));
+ }
+
+ @Test @Order(9)
+ void cleanup() {
+ given().when().delete("/restapis/" + apiId).then().statusCode(202);
+ }
+}