Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(apigateway): fall back to a parameterised sibling on method mismatch (#3399)

Ovidiu (Ovi)f03a716e9092
diff --git a/compatibility-tests/sdk-test-node/tests/apigateway.test.ts b/compatibility-tests/sdk-test-node/tests/apigateway.test.ts
index 381f9377f1..fb215942ab 100644
--- a/compatibility-tests/sdk-test-node/tests/apigateway.test.ts
+++ b/compatibility-tests/sdk-test-node/tests/apigateway.test.ts
@@ -745,3 +745,97 @@ describe('API Gateway v1 — execute-api data plane', () => {
});
});
});
+
+// ──────────────────────────── Resource/method resolution precedence ────────────────────────────
+
+/**
+ * AWS selects the most specific resource that can serve the requested method, searching
+ * literal, then path parameter, then greedy {proxy+}. A resource that declares methods but
+ * not the requested one yields to a less specific sibling that declares it.
+ *
+ * Captured against a real REST API in us-west-2 (MOCK integrations, no authorizer): with
+ * /users/{userId} GET and a literal /users/me PATCH deployed, GET /users/me is served by
+ * /users/{userId} with userId="me", and with /things/real GET and /things/{proxy+} ANY,
+ * POST /things/real is served by /things/{proxy+}.
+ */
+describe('API Gateway v1 — resource/method resolution precedence', () => {
+ let gw: APIGatewayClient;
+ let apiId: string;
+
+ /** Wire a MOCK method that echoes which resource served the request. */
+ async function mockMethod(resourceId: string, httpMethod: string, marker: string): Promise<void> {
+ await apigwFetch(`/restapis/${apiId}/resources/${resourceId}/methods/${httpMethod}`, 'PUT', {
+ authorizationType: 'NONE',
+ });
+ await apigwFetch(`/restapis/${apiId}/resources/${resourceId}/methods/${httpMethod}/responses/200`, 'PUT', {});
+ await apigwFetch(`/restapis/${apiId}/resources/${resourceId}/methods/${httpMethod}/integration`, 'PUT', {
+ type: 'MOCK',
+ requestTemplates: { 'application/json': '{"statusCode": 200}' },
+ });
+ await apigwFetch(
+ `/restapis/${apiId}/resources/${resourceId}/methods/${httpMethod}/integration/responses/200`,
+ 'PUT',
+ { selectionPattern: '', responseTemplates: { 'application/json': `{"servedBy":"${marker}"}` } }
+ );
+ }
+
+ /** Create a child resource and return its id. */
+ async function child(parentId: string, pathPart: string): Promise<string> {
+ const res = await apigwFetch(`/restapis/${apiId}/resources/${parentId}`, 'POST', { pathPart });
+ return (await res.json() as { id: string }).id;
+ }
+
+ beforeAll(async () => {
+ gw = makeClient(APIGatewayClient);
+
+ const api = await gw.send(new CreateRestApiCommand({ name: uniqueName('routing-precedence') }));
+ apiId = api.id!;
+
+ const resources = await gw.send(new GetResourcesCommand({ restApiId: apiId }));
+ const rootId = resources.items![0].id!;
+
+ // /users/{userId} GET alongside a literal /users/me carrying only PATCH.
+ const usersId = await child(rootId, 'users');
+ await mockMethod(await child(usersId, '{userId}'), 'GET', 'users-by-id');
+ await mockMethod(await child(usersId, 'me'), 'PATCH', 'users-me');
+
+ // /things/real carrying only GET alongside a greedy /things/{proxy+} ANY.
+ const thingsId = await child(rootId, 'things');
+ await mockMethod(await child(thingsId, 'real'), 'GET', 'things-real');
+ await mockMethod(await child(thingsId, '{proxy+}'), 'ANY', 'things-proxy');
+
+ const depRes = await apigwFetch(`/restapis/${apiId}/deployments`, 'POST', { description: 'compat-test' });
+ const depId = (await depRes.json() as { id: string }).id;
+ await apigwFetch(`/restapis/${apiId}/stages`, 'POST', { stageName: 'prod', deploymentId: depId });
+ });
+
+ afterAll(async () => {
+ try { if (apiId) await gw.send(new DeleteRestApiCommand({ restApiId: apiId })); } catch { /* ignore */ }
+ });
+
+ async function servedBy(path: string, method: string): Promise<string> {
+ const res = await executeApi(apiId, 'prod', path, { method });
+ expect(res.status).toBe(200);
+ return (await res.json() as { servedBy: string }).servedBy;
+ }
+
+ it('should serve GET /users/me from the parameterised sibling', async () => {
+ expect(await servedBy('/users/me', 'GET')).toBe('users-by-id');
+ });
+
+ it('should keep the literal resource for the method it declares', async () => {
+ expect(await servedBy('/users/me', 'PATCH')).toBe('users-me');
+ });
+
+ it('should serve an ordinary id from the parameterised resource', async () => {
+ expect(await servedBy('/users/abc123', 'GET')).toBe('users-by-id');
+ });
+
+ it('should keep the literal resource for GET /things/real', async () => {
+ expect(await servedBy('/things/real', 'GET')).toBe('things-real');
+ });
+
+ it('should serve POST /things/real from the greedy proxy', async () => {
+ expect(await servedBy('/things/real', 'POST')).toBe('things-proxy');
+ });
+});
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 a7853303b0..1c00ff1baf 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
@@ -338,18 +338,24 @@ public class ApiGatewayExecuteController {
ApiGatewayResource matched = null;
MethodConfig method = null;
+ // Candidates are ordered exact, then parameterised, then greedy. 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
+ // GET /{proxy+}. The request is refused only when no candidate declares the method.
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.
+ Map<String, MethodConfig> resourceMethods = r.getResourceMethods();
+ if (resourceMethods == null || resourceMethods.isEmpty()) {
+ continue;
+ }
+
+ MethodConfig m = resourceMethods.get(httpMethod.toUpperCase());
+ if (m == null) {
+ m = resourceMethods.get("ANY");
+ }
+ if (m != null) {
+ matched = r;
+ method = m;
break;
}
}
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
index 7180d7c58f..ae58032b6b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRoutingFallthroughIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayRoutingFallthroughIntegrationTest.java
@@ -128,6 +128,70 @@ class ApiGatewayRoutingFallthroughIntegrationTest {
.when().put("/restapis/" + apiId + "/resources/" + devicesResourceId + "/methods/POST/integration/responses/200")
.then()
.statusCode(201);
+
+ // Create /users, then a parameterised /users/{userId} with GET and a literal
+ // /users/me carrying only PATCH. A request for GET /users/me matches the literal
+ // first, which cannot serve it; AWS resolves it against the {userId} sibling.
+ String usersResourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"users\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+
+ String userIdResourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"{userId}\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + usersResourceId)
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+
+ createMockMethod(userIdResourceId, "GET", "users-get");
+
+ String usersMeResourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"me\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + usersResourceId)
+ .then()
+ .statusCode(201)
+ .extract().path("id");
+
+ createMockMethod(usersMeResourceId, "PATCH", "users-me-patch");
+ }
+
+ /** Wires {@code httpMethod} on {@code resourceId} to a MOCK integration echoing {@code marker}. */
+ private static void createMockMethod(String resourceId, String httpMethod, String marker) {
+ String base = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/" + httpMethod;
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\"}")
+ .when().put(base)
+ .then()
+ .statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"responseParameters\":{}}")
+ .when().put(base + "/responses/200")
+ .then()
+ .statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}")
+ .when().put(base + "/integration")
+ .then()
+ .statusCode(201);
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{\\\"matched\\\":\\\"" + marker + "\\\"}\"}}")
+ .when().put(base + "/integration/responses/200")
+ .then()
+ .statusCode(201);
}
@Test @Order(3)
@@ -183,15 +247,15 @@ class ApiGatewayRoutingFallthroughIntegrationTest {
}
@Test @Order(7)
- void getDevicesReturns405() {
+ void getDevicesFallsThroughToProxy() {
// Request GET /devices.
- // /devices has POST but no GET, so it should return 405 Method Not Allowed,
- // and NOT fall back to /{proxy+} ANY.
+ // /devices declares POST but no GET. AWS picks the most specific resource that can
+ // serve the method, so this falls through to /{proxy+} ANY rather than being refused.
given()
.when().get("/execute-api/" + apiId + "/test/devices")
.then()
- .statusCode(405)
- .body("message", equalTo("Method Not Allowed"));
+ .statusCode(200)
+ .body("matched", equalTo("proxy"));
}
@Test @Order(8)
@@ -207,6 +271,37 @@ class ApiGatewayRoutingFallthroughIntegrationTest {
}
@Test @Order(9)
+ void getUsersMeFallsBackToTheParameterisedSibling() {
+ // /users/me exists but declares only PATCH. GET must resolve against
+ // /users/{userId} rather than 405 - "me" is an ordinary parameter value.
+ given()
+ .when().get("/execute-api/" + apiId + "/test/users/me")
+ .then()
+ .statusCode(200)
+ .body("matched", equalTo("users-get"));
+ }
+
+ @Test @Order(10)
+ void patchUsersMeStillPrefersTheLiteralResource() {
+ // The literal keeps priority for the method it does declare.
+ given()
+ .contentType(ContentType.JSON)
+ .when().patch("/execute-api/" + apiId + "/test/users/me")
+ .then()
+ .statusCode(200)
+ .body("matched", equalTo("users-me-patch"));
+ }
+
+ @Test @Order(11)
+ void getUsersOtherIdUsesTheParameterisedResource() {
+ given()
+ .when().get("/execute-api/" + apiId + "/test/users/abc123")
+ .then()
+ .statusCode(200)
+ .body("matched", equalTo("users-get"));
+ }
+
+ @Test @Order(12)
void cleanup() {
given().when().delete("/restapis/" + apiId).then().statusCode(202);
}