Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(apigateway): reject method request parameter names AWS refuses (#3549)

Ovidiu (Ovi)ce5c5b4cfa02
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
index 210ad0d6c8..3dc3b1c509 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java
@@ -10,6 +10,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
+import java.util.regex.Pattern;
import io.github.hectorvent.floci.services.apigateway.model.EndpointConfiguration;
import io.github.hectorvent.floci.services.apigateway.model.EndpointType;
@@ -378,6 +379,61 @@ public class ApiGatewayService {
// ──────────────────────────── Method CRUD ────────────────────────────
+ /**
+ * The character set API Gateway allows in a method request parameter name. Measured against real
+ * AWS (us-west-2): {@code PutMethod} and an OpenAPI import both reject anything outside it with
+ * {@link #PARAMETER_NAME_ERROR}, quoting this exact expression. {@code $ : . _ -} are allowed,
+ * so {@code filter.a} imports; brackets are not, so a JSON:API style {@code filter[a]} does not.
+ *
+ * <p>This limitation is undocumented, and the runtime behaves differently: a request carrying
+ * {@code ?filter[a]=1} reaches a Lambda proxy integration with the brackets intact. Only the
+ * declared parameter name is restricted.
+ */
+ private static final Pattern REQUEST_PARAMETER_NAME = Pattern.compile("^[a-zA-Z0-9:._$-]+$");
+
+ private static final String PARAMETER_NAME_ERROR =
+ "Invalid mapping expression specified: Validation Result: warnings : [], errors : "
+ + "[Parameter name should match the following regular expression: ^[a-zA-Z0-9:._$-]+$]";
+
+ private static final List<String> REQUEST_PARAMETER_PREFIXES = List.of(
+ "method.request.querystring.", "method.request.header.", "method.request.path.");
+
+ /**
+ * Rethrows a parameter-name rejection using the envelope an import reports it under. Direct
+ * {@code PutMethod} surfaces the bare message; {@code ImportRestApi}/{@code PutRestApi} name the
+ * method and path first, both measured against real AWS.
+ */
+ private static AwsException importParameterNameFailure(String httpMethod, String path, AwsException cause) {
+ return new AwsException("BadRequestException",
+ "Errors found during import:\tUnable to put method '" + httpMethod
+ + "' on resource at path '" + path + "': " + cause.getMessage(),
+ 400);
+ }
+
+ /**
+ * Validates the names in a method's {@code requestParameters} map, which are of the form
+ * {@code method.request.<location>.<name>}. A name may itself contain dots ({@code filter.a}),
+ * so everything after the location prefix is the name. Keys that do not carry a recognised
+ * prefix are left alone: AWS rejects those with a different message that is not measured here.
+ *
+ * @throws AwsException if any parameter name falls outside {@link #REQUEST_PARAMETER_NAME}
+ */
+ private static void validateRequestParameterNames(Map<String, ?> requestParameters) {
+ if (requestParameters == null) return;
+ for (String key : requestParameters.keySet()) {
+ if (key == null) continue;
+ for (String prefix : REQUEST_PARAMETER_PREFIXES) {
+ if (key.startsWith(prefix)) {
+ String name = key.substring(prefix.length());
+ if (!REQUEST_PARAMETER_NAME.matcher(name).matches()) {
+ throw new AwsException("BadRequestException", PARAMETER_NAME_ERROR, 400);
+ }
+ break;
+ }
+ }
+ }
+ }
+
public MethodConfig putMethod(String region, String apiId, String resourceId, String httpMethod, Map<String, Object> request) {
ApiGatewayResource resource = getResource(region, apiId, resourceId);
MethodConfig method = new MethodConfig();
@@ -389,6 +445,7 @@ public class ApiGatewayService {
@SuppressWarnings("unchecked")
Map<String, Boolean> reqParams = (Map<String, Boolean>) request.get("requestParameters");
+ validateRequestParameterNames(reqParams);
if (reqParams != null) method.setRequestParameters(reqParams);
@SuppressWarnings("unchecked")
@@ -2671,8 +2728,15 @@ public class ApiGatewayService {
if (operations != null) {
for (var opEntry : operations.entrySet()) {
String httpMethod = opEntry.getKey().name().toUpperCase();
- applyOperation(region, apiId, resourceId, httpMethod, opEntry.getValue(), openAPI,
- schemeToAuthorizerId, schemeToAuthType, validatorNameToId);
+ try {
+ applyOperation(region, apiId, resourceId, httpMethod, opEntry.getValue(), openAPI,
+ schemeToAuthorizerId, schemeToAuthType, validatorNameToId);
+ } catch (AwsException e) {
+ if (PARAMETER_NAME_ERROR.equals(e.getMessage())) {
+ throw importParameterNameFailure(httpMethod, path, e);
+ }
+ throw e;
+ }
}
}
@@ -2687,8 +2751,15 @@ public class ApiGatewayService {
try {
Operation anyOperation = io.swagger.v3.core.util.Json.mapper()
.convertValue(anyMethodExt, Operation.class);
- applyOperation(region, apiId, resourceId, "ANY", anyOperation, openAPI,
- schemeToAuthorizerId, schemeToAuthType, validatorNameToId);
+ try {
+ applyOperation(region, apiId, resourceId, "ANY", anyOperation, openAPI,
+ schemeToAuthorizerId, schemeToAuthType, validatorNameToId);
+ } catch (AwsException e) {
+ if (PARAMETER_NAME_ERROR.equals(e.getMessage())) {
+ throw importParameterNameFailure("ANY", path, e);
+ }
+ throw e;
+ }
} catch (IllegalArgumentException e) {
throw new AwsException("BadRequestException",
"Invalid x-amazon-apigateway-any-method definition for path " + path + ": "
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayParameterNameValidationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayParameterNameValidationTest.java
new file mode 100644
index 0000000000..aff770ccc2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayParameterNameValidationTest.java
@@ -0,0 +1,159 @@
+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.*;
+
+/**
+ * API Gateway restricts a method request parameter name to {@code ^[a-zA-Z0-9:._$-]+$}. The
+ * limitation is undocumented, so it is captured here from real AWS (us-west-2): both
+ * {@code PutMethod} and an OpenAPI import reject a name outside that set, quoting the expression.
+ *
+ * <p>A JSON:API style {@code filter[a]} is therefore not importable, while {@code filter.a} is,
+ * which is the workaround applications end up adopting. The restriction covers query string, header
+ * and path parameters alike.
+ *
+ * <p>Only the declared name is restricted. At runtime a request carrying {@code ?filter[a]=1}
+ * reaches a proxy integration with the brackets intact, so this is not a general ban on the
+ * character in a query string.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class ApiGatewayParameterNameValidationTest {
+
+ private static final String EXPECTED_REGEX_MESSAGE =
+ "Parameter name should match the following regular expression: ^[a-zA-Z0-9:._$-]+$";
+
+ private static String specWithQueryParam(String paramName) {
+ return """
+ {
+ "openapi": "3.0.1",
+ "info": { "title": "ParamNameAPI", "version": "1.0" },
+ "paths": {
+ "/items": {
+ "get": {
+ "parameters": [
+ { "name": "%s", "in": "query", "required": true,
+ "schema": { "type": "string" } }
+ ],
+ "responses": { "200": { "description": "ok" } },
+ "x-amazon-apigateway-integration": {
+ "type": "MOCK",
+ "requestTemplates": { "application/json": "{\\"statusCode\\": 200}" },
+ "responses": { "default": { "statusCode": "200" } }
+ }
+ }
+ }
+ }
+ }
+ """.formatted(paramName);
+ }
+
+ private static String createApiWithItemsResource() {
+ String apiId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"param-name-validation-api\"}")
+ .when().post("/restapis")
+ .then().statusCode(201)
+ .extract().path("id");
+
+ String rootId = given()
+ .when().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200)
+ .extract().path("item[0].id");
+
+ String resourceId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"items\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201)
+ .extract().path("id");
+
+ return apiId + "|" + resourceId;
+ }
+
+ // ──────────────────────────── OpenAPI import ────────────────────────────
+
+ @Test @Order(1)
+ void importRejectsABracketedQueryParameterName() {
+ // Real AWS names the method and the path before the validation message.
+ given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(specWithQueryParam("filter[a]"))
+ .when().post("/restapis")
+ .then()
+ .statusCode(400)
+ .body("message", containsString("Errors found during import:"))
+ .body("message", containsString("Unable to put method 'GET' on resource at path '/items'"))
+ .body("message", containsString(EXPECTED_REGEX_MESSAGE));
+ }
+
+ @Test @Order(2)
+ void importAcceptsADottedQueryParameterName() {
+ // filter.a is the workaround, and it is genuinely accepted by AWS.
+ given()
+ .contentType(ContentType.JSON)
+ .queryParam("mode", "import")
+ .body(specWithQueryParam("filter.a"))
+ .when().post("/restapis")
+ .then()
+ .statusCode(201)
+ .body("id", notNullValue());
+ }
+
+ // ──────────────────────────── PutMethod ────────────────────────────
+
+ @Test @Order(3)
+ void putMethodRejectsABracketedQueryParameterName() {
+ String[] ids = createApiWithItemsResource().split("\\|");
+
+ // Called directly, AWS returns the bare validation message with no import envelope.
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\","
+ + "\"requestParameters\":{\"method.request.querystring.filter[a]\":true}}")
+ .when().put("/restapis/" + ids[0] + "/resources/" + ids[1] + "/methods/GET")
+ .then()
+ .statusCode(400)
+ .body("message", containsString(EXPECTED_REGEX_MESSAGE))
+ .body("message", not(containsString("Errors found during import")));
+ }
+
+ @Test @Order(4)
+ void putMethodRejectsABracketedHeaderParameterName() {
+ String[] ids = createApiWithItemsResource().split("\\|");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\","
+ + "\"requestParameters\":{\"method.request.header.x[a]\":true}}")
+ .when().put("/restapis/" + ids[0] + "/resources/" + ids[1] + "/methods/POST")
+ .then()
+ .statusCode(400)
+ .body("message", containsString(EXPECTED_REGEX_MESSAGE));
+ }
+
+ @Test @Order(5)
+ void putMethodAcceptsEveryCharacterInTheAllowedSet() {
+ String[] ids = createApiWithItemsResource().split("\\|");
+
+ // $ : - . _ are all inside the expression, and a name may contain dots of its own.
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"authorizationType\":\"NONE\","
+ + "\"requestParameters\":{\"method.request.querystring.a$b:c-d.e_f\":true}}")
+ .when().put("/restapis/" + ids[0] + "/resources/" + ids[1] + "/methods/PUT")
+ .then()
+ // Accepted rather than rejected is the whole assertion here. The response is not
+ // checked for the parameter itself: toMethodNode does not serialise
+ // requestParameters at all, which is a separate gap from this validation.
+ .statusCode(201);
+ }
+}