From fb82fb29aed79e79850c1dd3616089310e3f002e Mon Sep 17 00:00:00 2001 From: "Ovidiu (Ovi)" <163712869+ovi-fabric@users.noreply.github.com> Date: Mon, 14 Sep 2026 16:42:36 +0300 Subject: [PATCH] fix(apigateway): answer an unmatched REST request with 403, not 404/405 (#3547) * 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. * fix(apigateway): answer an unmatched REST request with 403, not 404/405 A REST request that reached no method returned 404 "Not Found" when the path matched nothing and 405 "Method Not Allowed" when it matched resources declaring no usable method. AWS returns neither. Captured against a real REST API in us-west-2 with /users/{userId} GET and a literal /users/me PATCH deployed. POST /users/me, DELETE /users/abc123, GET /zzz, GET /users/a/b/c and GET / all answered: 403 {"message":"Missing Authentication Token"} x-amzn-ErrorType: MissingAuthenticationTokenException AWS resolves the path and the method as one step, so an unknown path and a known path carrying no usable method are the same failure and share one response. This is the well-known "Missing Authentication Token" result of calling a REST API with the wrong verb, which callers match on. Route both branches through restNoMatch(), rendering the status, body and error-type header AWS pairs with this failure, alongside the existing AWS_IAM MISSING rejection that already returns that shape. HTTP APIs are untouched: they answer an unmatched route with 404 {"message":"Not Found"}, which the v2 dispatch path continues to do. * test(apigateway): expect 403 for a path that reaches no resource ApiGatewayGreedyPathParameterIntegrationTest arrived on main after this branch was cut, and pinned the old 404 for a REST path matching no resource. This branch changes that contract to 403 "Missing Authentication Token", so the assertion was stale rather than a real regression. The test's intent is unchanged: /other/img/logo.png must not be swallowed by the greedy resource. Only the no-match response it asserts moves. HTTP API v2 is untouched and still answers an unmatched route with 404 "Not Found". --- .../sdk-test-node/tests/apigateway.test.ts | 15 ++ .../ApiGatewayExecuteController.java | 28 +++- ...wayGreedyPathParameterIntegrationTest.java | 7 +- .../ApiGatewayNoMatchIntegrationTest.java | 150 ++++++++++++++++++ 4 files changed, 192 insertions(+), 8 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayNoMatchIntegrationTest.java diff --git a/compatibility-tests/sdk-test-node/tests/apigateway.test.ts b/compatibility-tests/sdk-test-node/tests/apigateway.test.ts index 8779901547..89a72764b2 100644 --- a/compatibility-tests/sdk-test-node/tests/apigateway.test.ts +++ b/compatibility-tests/sdk-test-node/tests/apigateway.test.ts @@ -933,4 +933,19 @@ describe('API Gateway v1 — resource/method resolution precedence', () => { it('should serve POST /things/real from the greedy proxy', async () => { expect(await servedBy('/things/real', 'POST')).toBe('things-proxy'); }); + + // AWS resolves path and method together, so "no such path" and "a path whose resources + // declare no usable method" are one failure: 403 Missing Authentication Token, not 404/405. + it('should answer 403 when no candidate resource declares the method', async () => { + const res = await executeApi(apiId, 'prod', '/users/me', { method: 'POST' }); + expect(res.status).toBe(403); + expect(res.headers.get('x-amzn-errortype')).toBe('MissingAuthenticationTokenException'); + expect(await res.json()).toEqual({ message: 'Missing Authentication Token' }); + }); + + it('should answer 403 for a path that matches no resource', async () => { + const res = await executeApi(apiId, 'prod', '/zzz', { method: 'GET' }); + expect(res.status).toBe(403); + expect(await res.json()).toEqual({ message: 'Missing Authentication Token' }); + }); }); 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 14e3c3dcea..5b8aed82d8 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 @@ -332,9 +332,7 @@ public class ApiGatewayExecuteController { List resources = apiGatewayService.getResources(region, apiId); List matchedResources = matchResources(resources, path); if (matchedResources.isEmpty()) { - return Response.status(404) - .entity(jsonMessage("Not Found")) - .type(MediaType.APPLICATION_JSON).build(); + return restNoMatch(); } ApiGatewayResource matched = null; @@ -362,9 +360,7 @@ public class ApiGatewayExecuteController { } if (matched == null) { - return Response.status(405) - .entity(jsonMessage("Method Not Allowed")) - .type(MediaType.APPLICATION_JSON).build(); + return restNoMatch(); } // 1. Authorizer @@ -2363,6 +2359,26 @@ public class ApiGatewayExecuteController { .type(MediaType.APPLICATION_JSON).build(); } + /** + * Renders an execute-api request that reached no method the way a REST API does. + * + *

AWS resolves the path and the method as one step, so "no such path" and "a path whose + * resources declare no usable method" are the same failure and share one response: {@code 403} + * with {@code MissingAuthenticationTokenException}, never {@code 404} or {@code 405}. This is + * the well-known "Missing Authentication Token" result of calling a REST API with the wrong + * verb. Captured against a real REST API in us-west-2; the cases are pinned in + * {@code ApiGatewayNoMatchIntegrationTest}. + * + *

HTTP APIs are unaffected: they answer an unmatched route with {@code 404} + * {@code {"message":"Not Found"}}, which the v2 dispatch path continues to do. + */ + private Response restNoMatch() { + return Response.status(403) + .header("x-amzn-ErrorType", "MissingAuthenticationTokenException") + .entity(jsonMessage("Missing Authentication Token")) + .type(MediaType.APPLICATION_JSON).build(); + } + /** * HTTP APIs collapse every IAM failure into {@code 403 {"message":"Forbidden"}} rather than * naming the reason, matching both real AWS and the JWT/REQUEST authorizer rejections above. 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 8350250601..dd1f6533d1 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 @@ -151,11 +151,14 @@ class ApiGatewayGreedyPathParameterIntegrationTest { @Test @Order(7) void pathOutsideTheParentPrefixDoesNotMatch() { - // The greedy resource must not have become a catch-all for the whole API. + // The greedy resource must not have become a catch-all for the whole API. Reaching no + // resource at all is the no-match response, which AWS renders as 403 "Missing + // Authentication Token" rather than 404. given() .when().get("/execute-api/" + apiId + "/test/other/img/logo.png") .then() - .statusCode(404); + .statusCode(403) + .body("message", equalTo("Missing Authentication Token")); } @Test @Order(99) diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayNoMatchIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayNoMatchIntegrationTest.java new file mode 100644 index 0000000000..8a961ce160 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayNoMatchIntegrationTest.java @@ -0,0 +1,150 @@ +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 REST API request that reaches no method answers 403 "Missing Authentication Token", whether the + * path matched nothing at all or matched resources that declare no usable method. AWS resolves path + * and method together, so both are the same failure. + * + *

Captured against a real REST API in us-west-2 with /users/{userId} GET and a literal /users/me + * PATCH deployed: POST /users/me, DELETE /users/abc123, GET /zzz, GET /users/a/b/c and GET / all + * returned 403 with x-amzn-ErrorType: MissingAuthenticationTokenException. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiGatewayNoMatchIntegrationTest { + + private static String apiId; + + 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 createMockMethod(String resourceId, String httpMethod, String marker) { + given().contentType(ContentType.JSON) + .body("{\"authorizationType\":\"NONE\"}") + .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/" + httpMethod) + .then().statusCode(201); + + given().contentType(ContentType.JSON) + .body("{}") + .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/" + httpMethod + "/responses/200") + .then().statusCode(201); + + given().contentType(ContentType.JSON) + .body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}") + .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/" + httpMethod + "/integration") + .then().statusCode(201); + + given().contentType(ContentType.JSON) + .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{\\\"matched\\\":\\\"" + + marker + "\\\"}\"}}") + .when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/" + httpMethod + + "/integration/responses/200") + .then().statusCode(201); + } + + @Test @Order(1) + void setupApi() { + apiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"no-match-test-api\"}") + .when().post("/restapis") + .then() + .statusCode(201) + .body("id", notNullValue()) + .extract().path("id"); + + String rootId = given() + .when().get("/restapis/" + apiId + "/resources") + .then() + .statusCode(200) + .extract().path("item[0].id"); + + // /users/{userId} carries GET, and a literal /users/me carries only PATCH. There is no + // {proxy+} anywhere, so an unmatched path really matches no resource at all. + String usersId = createResource(rootId, "users"); + createMockMethod(createResource(usersId, "{userId}"), "GET", "users-get"); + createMockMethod(createResource(usersId, "me"), "PATCH", "users-me-patch"); + + String deploymentId = given() + .contentType(ContentType.JSON) + .body("{\"stageName\":\"test\"}") + .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(2) + void methodDeclaredByNoCandidateReturns403() { + // /users/me declares PATCH and /users/{userId} declares GET, so neither can serve POST. + given() + .contentType(ContentType.JSON) + .when().post("/execute-api/" + apiId + "/test/users/me") + .then() + .statusCode(403) + .header("x-amzn-ErrorType", equalTo("MissingAuthenticationTokenException")) + .body("message", equalTo("Missing Authentication Token")); + } + + @Test @Order(3) + void methodMissingOnTheParameterisedResourceReturns403() { + given() + .when().delete("/execute-api/" + apiId + "/test/users/abc123") + .then() + .statusCode(403) + .body("message", equalTo("Missing Authentication Token")); + } + + @Test @Order(4) + void unmatchedPathReturns403RatherThan404() { + given() + .when().get("/execute-api/" + apiId + "/test/zzz") + .then() + .statusCode(403) + .header("x-amzn-ErrorType", equalTo("MissingAuthenticationTokenException")) + .body("message", equalTo("Missing Authentication Token")); + } + + @Test @Order(5) + void pathDeeperThanAnyResourceReturns403() { + given() + .when().get("/execute-api/" + apiId + "/test/users/a/b/c") + .then() + .statusCode(403) + .body("message", equalTo("Missing Authentication Token")); + } + + @Test @Order(6) + void aMatchingMethodStillSucceeds() { + // The no-match response must not swallow requests that do resolve. + given() + .when().get("/execute-api/" + apiId + "/test/users/me") + .then() + .statusCode(200) + .body("matched", equalTo("users-get")); + } +}