Light, fluffy, and always free - The AWS Local Emulator alternative
fix(apigateway): resolve component parameter references on REST import (#4855)
Mario Toffia0f94d6213c9a
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.javaindex 8d1b58bdaa..9c1789e356 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@@ -46,6 +46,7 @@ import io.swagger.v3.core.util.Json;import io.swagger.v3.oas.models.OpenAPI;import io.swagger.v3.oas.models.Operation;import io.swagger.v3.oas.models.PathItem;+import io.swagger.v3.oas.models.parameters.Parameter;import io.swagger.v3.oas.models.security.SecurityRequirement;import io.swagger.v3.oas.models.security.SecurityScheme;import io.swagger.v3.parser.core.models.SwaggerParseResult;@@ -3636,7 +3637,11 @@ public class ApiGatewayService implements ResourceProvider {// Map OpenAPI parameters to requestParametersif (operation.getParameters() != null && !operation.getParameters().isEmpty()) {Map<String, Boolean> requestParameters = new HashMap<>();- for (var param : operation.getParameters()) {+ for (Parameter declared : operation.getParameters()) {+ Parameter param = resolveParameter(declared, openAPI);+ if (param == null) {+ continue;+ }String location = switch (param.getIn()) {case "query" -> "method.request.querystring." + param.getName();case "header" -> "method.request.header." + param.getName();@@ -3689,6 +3694,56 @@ public class ApiGatewayService implements ResourceProvider {}}+ private static final String PARAMETER_REF_PREFIX = "#/components/parameters/";+ private static final String SWAGGER2_PARAMETER_REF_PREFIX = "#/parameters/";++ /**+ * Returns the parameter a local {@code #/components/parameters/} reference names, following a+ * component that is itself a reference. The document is parsed without reference resolution, so+ * a referenced parameter arrives carrying only its {@code $ref}. A Swagger 2 document is converted+ * to OpenAPI 3, but an ANY method is read from its raw vendor extension, so its references keep+ * the Swagger 2 form {@code #/parameters/}; they name the same converted components. A Swagger 2+ * body or form data reference returns null, because the converter files it as a request body or a+ * {@code formData_} schema, and is skipped like the in-place form.+ *+ * @throws AwsException if the reference names no component, or the references form a cycle+ */+ private static Parameter resolveParameter(Parameter param, OpenAPI openAPI) {+ Map<String, Parameter> components = openAPI.getComponents() == null+ ? null : openAPI.getComponents().getParameters();+ Set<String> seen = new HashSet<>();+ Parameter current = param;+ while (current.get$ref() != null) {+ String ref = current.get$ref();+ String prefix = ref.startsWith(SWAGGER2_PARAMETER_REF_PREFIX)+ ? SWAGGER2_PARAMETER_REF_PREFIX : PARAMETER_REF_PREFIX;+ Parameter target = components != null && ref.startsWith(prefix) && seen.add(ref)+ ? components.get(unescapeJsonPointer(ref.substring(prefix.length()))) : null;+ if (target == null) {+ if (ref.startsWith(SWAGGER2_PARAMETER_REF_PREFIX) && isSwagger2BodyOrFormDataParameter(openAPI,+ unescapeJsonPointer(ref.substring(SWAGGER2_PARAMETER_REF_PREFIX.length())))) {+ return null;+ }+ throw new AwsException("BadRequestException",+ "Unable to resolve parameter reference: " + ref, 400);+ }+ current = target;+ }+ return current;+ }++ private static boolean isSwagger2BodyOrFormDataParameter(OpenAPI openAPI, String name) {+ if (openAPI.getComponents() == null) {+ return false;+ }+ boolean body = openAPI.getComponents().getRequestBodies() != null+ && openAPI.getComponents().getRequestBodies().containsKey(name);+ // The converter keys a form data parameter's schema as formData_<name> so it cannot overwrite a model.+ boolean formData = openAPI.getComponents().getSchemas() != null+ && openAPI.getComponents().getSchemas().containsKey("formData_" + name);+ return body || formData;+ }+private String ensureResourcePath(String region, String apiId, String path,Map<String, String> pathToResourceId) {if (pathToResourceId.containsKey(path)) {diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayOpenApiParameterRefImportIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayOpenApiParameterRefImportIntegrationTest.javanew file mode 100644index 0000000000..e8fd23466d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayOpenApiParameterRefImportIntegrationTest.java@@ -0,0 +1,271 @@+package io.github.hectorvent.floci.services.apigateway;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.Test;++import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasItem;+import static org.hamcrest.Matchers.not;+import static org.junit.jupiter.api.Assertions.assertEquals;++/**+ * An OpenAPI 3 operation may list a parameter as a local reference,+ * {@code $ref: '#/components/parameters/<Name>'}, instead of writing it in place. AWS imports such a+ * definition, and the method carries the referenced parameter exactly as it would an in-place one.+ */+@QuarkusTest+class ApiGatewayOpenApiParameterRefImportIntegrationTest {++ private static final String SPEC = """+ openapi: "3.0.1"+ info:+ title: ParameterRefAPI+ version: "1.0"+ paths:+ /inline/{groupName}:+ get:+ parameters:+ - name: groupName+ in: path+ required: true+ schema: { type: string }+ - name: limit+ in: query+ schema: { type: integer }+ responses:+ "200": { description: ok }+ /ref/{groupName}:+ get:+ parameters:+ - $ref: '#/components/parameters/GroupName'+ - $ref: '#/components/parameters/Limit'+ responses:+ "200": { description: ok }+ components:+ parameters:+ GroupName: { name: groupName, in: path, required: true, schema: { type: string } }+ Limit: { name: limit, in: query, schema: { type: integer } }+ """;++ @Test+ void importResolvesComponentParameterReferencesLikeInPlaceParameters() {+ String apiId = given()+ .contentType(ContentType.JSON)+ .queryParam("mode", "import")+ .body(SPEC)+ .when().post("/restapis")+ .then()+ .statusCode(201)+ .extract().path("id");++ try {+ Map<String, Boolean> inline = requestParameters(apiId, "/inline/{groupName}", "GET");+ Map<String, Boolean> referenced = requestParameters(apiId, "/ref/{groupName}", "GET");++ assertEquals(Map.of(+ "method.request.path.groupName", true,+ "method.request.querystring.limit", false), inline);+ assertEquals(inline, referenced);+ } finally {+ given().when().delete("/restapis/" + apiId).then().statusCode(202);+ }+ }++ @Test+ void importRejectsAReferenceToAMissingComponent() {+ String spec = """+ openapi: "3.0.1"+ info:+ title: MissingParameterRefAPI+ version: "1.0"+ paths:+ /ref/{groupName}:+ get:+ parameters:+ - $ref: '#/components/parameters/Missing'+ responses:+ "200": { description: ok }+ components:+ parameters:+ GroupName: { name: groupName, in: path, required: true, schema: { type: string } }+ """;++ given()+ .contentType(ContentType.JSON)+ .queryParam("mode", "import")+ .body(spec)+ .when().post("/restapis")+ .then()+ .statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", containsString("#/components/parameters/Missing"));++ given()+ .when().get("/restapis")+ .then()+ .statusCode(200)+ .body("item.name", not(hasItem("MissingParameterRefAPI")));+ }++ @Test+ void importResolvesSwagger2ParameterReferencesInAnAnyMethod() {+ String spec = """+ swagger: "2.0"+ info:+ title: Swagger2AnyParameterRefAPI+ version: "1.0"+ paths:+ /items:+ x-amazon-apigateway-any-method:+ parameters:+ - $ref: '#/parameters/Limit'+ responses:+ "200": { description: ok }+ parameters:+ Limit: { name: limit, in: query, type: integer }+ """;++ assertImportedRequestParameters(spec, "/items", "ANY", Map.of("method.request.querystring.limit", false));+ }++ @Test+ void importDecodesAnEscapedParameterReferenceInAnAnyMethod() {+ String spec = """+ swagger: "2.0"+ info:+ title: EscapedParameterRefAPI+ version: "1.0"+ paths:+ /items:+ x-amazon-apigateway-any-method:+ parameters:+ - $ref: '#/parameters/Foo~1Bar'+ responses:+ "200": { description: ok }+ parameters:+ Foo/Bar: { name: filter, in: query, type: string }+ """;++ assertImportedRequestParameters(spec, "/items", "ANY", Map.of("method.request.querystring.filter", false));+ }++ @Test+ void importSkipsSwagger2BodyAndFormDataParameterReferencesInAnAnyMethod() {+ String spec = """+ swagger: "2.0"+ info:+ title: Swagger2AnyBodyParameterRefAPI+ version: "1.0"+ paths:+ /items:+ x-amazon-apigateway-any-method:+ parameters:+ - $ref: '#/parameters/Body'+ - $ref: '#/parameters/Form'+ - $ref: '#/parameters/Limit'+ responses:+ "200": { description: ok }+ parameters:+ Body: { name: body, in: body, schema: { type: object } }+ Form: { name: note, in: formData, type: string }+ Limit: { name: limit, in: query, type: integer }+ """;++ assertImportedRequestParameters(spec, "/items", "ANY", Map.of("method.request.querystring.limit", false));+ }++ @Test+ void importFollowsAComponentParameterThatIsItselfAReference() {+ String spec = """+ openapi: "3.0.1"+ info:+ title: ChainedParameterRefAPI+ version: "1.0"+ paths:+ /items:+ get:+ parameters:+ - $ref: '#/components/parameters/Limit'+ responses:+ "200": { description: ok }+ components:+ parameters:+ Limit: { $ref: '#/components/parameters/RealLimit' }+ RealLimit: { name: limit, in: query, schema: { type: integer } }+ """;++ assertImportedRequestParameters(spec, "/items", "GET", Map.of("method.request.querystring.limit", false));+ }++ @Test+ void importRejectsAComponentParameterThatReferencesItself() {+ String spec = """+ openapi: "3.0.1"+ info:+ title: CyclicParameterRefAPI+ version: "1.0"+ paths:+ /items:+ get:+ parameters:+ - $ref: '#/components/parameters/Loop'+ responses:+ "200": { description: ok }+ components:+ parameters:+ Loop: { $ref: '#/components/parameters/Loop' }+ """;++ given()+ .contentType(ContentType.JSON)+ .queryParam("mode", "import")+ .body(spec)+ .when().post("/restapis")+ .then()+ .statusCode(400)+ .body("__type", equalTo("BadRequestException"))+ .body("message", containsString("#/components/parameters/Loop"));++ given()+ .when().get("/restapis")+ .then()+ .statusCode(200)+ .body("item.name", not(hasItem("CyclicParameterRefAPI")));+ }++ private static void assertImportedRequestParameters(String spec, String path, String httpMethod,+ Map<String, Boolean> expected) {+ String apiId = given()+ .contentType(ContentType.JSON)+ .queryParam("mode", "import")+ .body(spec)+ .when().post("/restapis")+ .then()+ .statusCode(201)+ .extract().path("id");++ try {+ assertEquals(expected, requestParameters(apiId, path, httpMethod));+ } finally {+ given().when().delete("/restapis/" + apiId).then().statusCode(202);+ }+ }++ private static Map<String, Boolean> requestParameters(String apiId, String path, String httpMethod) {+ String resourceId = given()+ .when().get("/restapis/" + apiId + "/resources")+ .then()+ .statusCode(200)+ .extract().path("item.find { it.path == '" + path + "' }.id");+ return given()+ .when().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/" + httpMethod)+ .then()+ .statusCode(200)+ .extract().path("requestParameters");+ }+}