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

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

A literal resource that declares some methods but not the requested one
returned 405 even when a parameterised sibling could serve it. Resource
candidates are ordered exact, then parameterised, then greedy, and the
selection loop stopped at the first candidate with any methods configured.

For /users/me declaring only PATCH, GET /users/me therefore returned 405
instead of resolving against /users/{userId}, where "me" is an ordinary
parameter value. Adding a literal child for one method silently removes
every other method a parameterised sibling already served, so this surfaces
as a regression in an application that was working.

The stop was there for a narrower reason, which the existing tests pin: a
method mismatch on a concrete resource must not be absorbed by a greedy
/{proxy+} catch-all. That rule is kept. Only the concrete-to-concrete case
changes, so a literal now yields to a parameterised sibling that can serve
the method, while /devices declaring POST still returns 405 for GET rather
than falling through to /{proxy+}.

Extends ApiGatewayRoutingFallthroughIntegrationTest, which already covers
the greedy cases, with /users/{userId} GET alongside a literal /users/me
PATCH: GET /users/me resolves to the parameterised resource, PATCH still
prefers the literal, and an ordinary id is unaffected.

* fix(apigateway): resolve the method against every matching resource

The selection loop stopped considering less specific siblings once a
resource declaring methods had been passed, so a method mismatch on a
concrete resource was terminal for the greedy half of the rule.

Captured against a real REST API in us-west-2: AWS picks the most
specific resource that can serve the requested method, searching
literal, then path parameter, then greedy {proxy+}, and refuses the
request only when no candidate declares it.

Drop concreteWithMethodsSeen and the greedy break so both fallbacks
follow that single rule. /users/me declaring only PATCH no longer hides
GET /users/{userId}, and /devices declaring only POST now falls through
to GET /{proxy+}.

getDevicesReturns405 pinned the greedy half of the old behaviour and is
updated to assert the fallthrough. Adds compatibility coverage for the
sibling and greedy fallbacks from the same AWS repro.

The no-match response is unchanged: AWS returns 403 Missing
Authentication Token where floci returns 405, tracked separately.
This commit is contained in:
Ovidiu (Ovi) authored and GitHub committed 2026-09-13 14:45:50 -04:00
1 parent 28105c08ec
commit f03a716e90
3 files changed
+211 -16

No files matched your search

@@ -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');
});
});
@@ -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;
}
}
@@ -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);
}