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 4f6dd39952..20d90457b2 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 @@ -40,6 +40,7 @@ import io.github.hectorvent.floci.services.apigateway.model.Stage; import io.github.hectorvent.floci.services.apigateway.model.UsagePlan; import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey; 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.security.SecurityRequirement; import io.swagger.v3.oas.models.security.SecurityScheme; @@ -2228,103 +2229,141 @@ public class ApiGatewayService { // Create methods for each operation on this path var operations = pathItem.readOperationsMap(); - if (operations == null) continue; - - for (var opEntry : operations.entrySet()) { - String httpMethod = opEntry.getKey().name().toUpperCase(); - var operation = opEntry.getValue(); - - // Create the method - Map methodRequest = new HashMap<>(); - // Apply the operation's (or the API root's) security requirement, resolving the scheme - // to a method authorizationType (CUSTOM/AWS_IAM/COGNITO_USER_POOLS) + authorizerId. - List secReqs = operation.getSecurity() != null - ? operation.getSecurity() : openAPI.getSecurity(); - String authType = "NONE"; - String authorizerId = null; - if (secReqs != null) { - // AWS resolves the OR-list of security requirements to the first declared - // authorizer scheme (a method has exactly one authorizer), so stop at the first match. - resolveAuth: - for (SecurityRequirement secReq : secReqs) { - for (String schemeName : secReq.keySet()) { - String mapped = schemeToAuthType.get(schemeName); - if (mapped == null || "NONE".equals(mapped)) { - continue; - } - authType = mapped; - authorizerId = schemeToAuthorizerId.get(schemeName); - break resolveAuth; - } - } - } - methodRequest.put("authorizationType", authType); - if (authorizerId != null) { - methodRequest.put("authorizerId", authorizerId); - } - - // Link request models from operation requestBody - if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) { - Map requestModels = new HashMap<>(); - for (var contentEntry : operation.getRequestBody().getContent().entrySet()) { - String contentType = contentEntry.getKey(); - var mediaType = contentEntry.getValue(); - if (mediaType.getSchema() != null && mediaType.getSchema().get$ref() != null) { - String ref = mediaType.getSchema().get$ref(); - // Extract model name from #/components/schemas/ModelName - String modelName = ref.substring(ref.lastIndexOf('/') + 1); - requestModels.put(contentType, modelName); - } - } - if (!requestModels.isEmpty()) { - methodRequest.put("requestModels", requestModels); - } - } - - // Map OpenAPI parameters to requestParameters - if (operation.getParameters() != null && !operation.getParameters().isEmpty()) { - Map requestParameters = new HashMap<>(); - for (var param : operation.getParameters()) { - String location = switch (param.getIn()) { - case "query" -> "method.request.querystring." + param.getName(); - case "header" -> "method.request.header." + param.getName(); - case "path" -> "method.request.path." + param.getName(); - default -> null; - }; - if (location != null) { - requestParameters.put(location, param.getRequired() != null && param.getRequired()); - } - } - if (!requestParameters.isEmpty()) { - methodRequest.put("requestParameters", requestParameters); - } - } - - // Link request validator (operation-level overrides API-level default) - String opValidator = null; - if (operation.getExtensions() != null) { - opValidator = (String) operation.getExtensions() - .get("x-amazon-apigateway-request-validator"); - } - if (opValidator != null && validatorNameToId.containsKey(opValidator)) { - methodRequest.put("requestValidatorId", validatorNameToId.get(opValidator)); - } else if (validatorNameToId.containsKey("__default__")) { - methodRequest.put("requestValidatorId", validatorNameToId.get("__default__")); - } - - putMethod(region, apiId, resourceId, httpMethod, methodRequest); - - // Extract x-amazon-apigateway-integration extension - Map integrationExt = null; - if (operation.getExtensions() != null) { - integrationExt = (Map) operation.getExtensions() - .get("x-amazon-apigateway-integration"); - } - - if (integrationExt != null) { - applyIntegration(region, apiId, resourceId, httpMethod, integrationExt); + 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); } } + + // "x-amazon-apigateway-any-method" is AWS's vendor extension for a pseudo-operation that + // matches every HTTP verb (ANY). It is not a real OpenAPI operation keyword, so the swagger + // parser never surfaces it via pathItem.readOperationsMap() above. It only ends up in the + // PathItem's raw extensions map, as an untyped Map rather than a typed Operation. Convert it + // and process it the same way as a normal operation so imported ANY methods are created. + if (pathItem.getExtensions() != null) { + Object anyMethodExt = pathItem.getExtensions().get("x-amazon-apigateway-any-method"); + if (anyMethodExt != null) { + try { + Operation anyOperation = io.swagger.v3.core.util.Json.mapper() + .convertValue(anyMethodExt, Operation.class); + applyOperation(region, apiId, resourceId, "ANY", anyOperation, openAPI, + schemeToAuthorizerId, schemeToAuthType, validatorNameToId); + } catch (IllegalArgumentException e) { + throw new AwsException("BadRequestException", + "Invalid x-amazon-apigateway-any-method definition for path " + path + ": " + + e.getMessage(), + 400); + } + } + } + } + } + + private void applyOperation(String region, String apiId, String resourceId, String httpMethod, + Operation operation, OpenAPI openAPI, Map schemeToAuthorizerId, + Map schemeToAuthType, Map validatorNameToId) { + // Create the method + Map methodRequest = new HashMap<>(); + // Apply the operation's (or the API root's) security requirement, resolving the scheme + // to a method authorizationType (CUSTOM/AWS_IAM/COGNITO_USER_POOLS) + authorizerId. + List secReqs = operation.getSecurity() != null + ? operation.getSecurity() : openAPI.getSecurity(); + String authType = "NONE"; + String authorizerId = null; + if (secReqs != null) { + // AWS resolves the OR-list of security requirements to the first declared + // authorizer scheme (a method has exactly one authorizer), so stop at the first match. + resolveAuth: + for (SecurityRequirement secReq : secReqs) { + for (String schemeName : secReq.keySet()) { + String mapped = schemeToAuthType.get(schemeName); + if (mapped == null || "NONE".equals(mapped)) { + continue; + } + authType = mapped; + authorizerId = schemeToAuthorizerId.get(schemeName); + break resolveAuth; + } + } + } + methodRequest.put("authorizationType", authType); + if (authorizerId != null) { + methodRequest.put("authorizerId", authorizerId); + } + + // Link request models from operation requestBody + if (operation.getRequestBody() != null && operation.getRequestBody().getContent() != null) { + Map requestModels = new HashMap<>(); + for (var contentEntry : operation.getRequestBody().getContent().entrySet()) { + String contentType = contentEntry.getKey(); + var mediaType = contentEntry.getValue(); + if (mediaType.getSchema() != null && mediaType.getSchema().get$ref() != null) { + String ref = mediaType.getSchema().get$ref(); + // Extract model name from #/components/schemas/ModelName + String modelName = ref.substring(ref.lastIndexOf('/') + 1); + requestModels.put(contentType, modelName); + } + } + if (!requestModels.isEmpty()) { + methodRequest.put("requestModels", requestModels); + } + } + + // Map OpenAPI parameters to requestParameters + if (operation.getParameters() != null && !operation.getParameters().isEmpty()) { + Map requestParameters = new HashMap<>(); + for (var param : operation.getParameters()) { + String location = switch (param.getIn()) { + case "query" -> "method.request.querystring." + param.getName(); + case "header" -> "method.request.header." + param.getName(); + case "path" -> "method.request.path." + param.getName(); + default -> null; + }; + if (location != null) { + requestParameters.put(location, param.getRequired() != null && param.getRequired()); + } + } + if (!requestParameters.isEmpty()) { + methodRequest.put("requestParameters", requestParameters); + } + } + + // Link request validator (operation-level overrides API-level default) + String opValidator = null; + if (operation.getExtensions() != null) { + opValidator = (String) operation.getExtensions() + .get("x-amazon-apigateway-request-validator"); + } + if (opValidator != null && validatorNameToId.containsKey(opValidator)) { + methodRequest.put("requestValidatorId", validatorNameToId.get(opValidator)); + } else if (validatorNameToId.containsKey("__default__")) { + methodRequest.put("requestValidatorId", validatorNameToId.get("__default__")); + } + + putMethod(region, apiId, resourceId, httpMethod, methodRequest); + + // Extract x-amazon-apigateway-integration extension + Map integrationExt = null; + Object rawIntegrationExt = operation.getExtensions() == null + ? null + : operation.getExtensions().get("x-amazon-apigateway-integration"); + if (rawIntegrationExt != null) { + if (rawIntegrationExt instanceof Map map) { + @SuppressWarnings("unchecked") + Map typed = (Map) map; + integrationExt = typed; + } else { + throw new AwsException("BadRequestException", + "Invalid x-amazon-apigateway-integration definition for method " + httpMethod + + ": expected an object", + 400); + } + } + + if (integrationExt != null) { + applyIntegration(region, apiId, resourceId, httpMethod, integrationExt); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayOpenApiAnyMethodImportTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayOpenApiAnyMethodImportTest.java new file mode 100644 index 0000000000..9eaea1a455 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayOpenApiAnyMethodImportTest.java @@ -0,0 +1,240 @@ +package io.github.hectorvent.floci.services.apigateway; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +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.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Verifies that importing an OpenAPI spec using the AWS vendor extension + * "x-amazon-apigateway-any-method" (a pseudo-operation matching every HTTP verb, distinct + * from the standard OpenAPI "get"/"post"/... operation keywords) actually creates an ANY + * method + integration, instead of being silently dropped. + * + *

Unlike {@link ApiGatewayAnyMethodIntegrationTest} (which covers ANY methods created + * directly via PutMethod, see issue #710), this covers the OpenAPI *import* path: the + * swagger parser never surfaces "x-amazon-apigateway-any-method" via + * {@code PathItem.readOperationsMap()} since it isn't a real OpenAPI operation keyword, so + * without special handling it lands only in the PathItem's raw extensions map and is ignored. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiGatewayOpenApiAnyMethodImportTest { + + private static final ObjectMapper mapper = new ObjectMapper(); + private static String apiId; + private static String anyResourceId; + + @Test + @Order(1) + void importRestApi_withAnyMethodExtension() throws Exception { + String spec = """ + { + "openapi": "3.0.1", + "info": { + "title": "AnyMethodImportAPI", + "version": "1.0" + }, + "paths": { + "/echo": { + "x-amazon-apigateway-any-method": { + "responses": { + "200": { + "description": "200 response" + } + }, + "x-amazon-apigateway-integration": { + "type": "MOCK", + "requestTemplates": { + "application/json": "{\\"statusCode\\": 200}" + }, + "responses": { + "default": { + "statusCode": "200", + "responseTemplates": { + "application/json": "{\\"matched\\": \\"any\\"}" + } + } + } + } + } + } + } + } + """; + + String body = given() + .contentType(ContentType.JSON) + .queryParam("mode", "import") + .body(spec) + .when() + .post("/restapis") + .then() + .statusCode(201) + .body("id", notNullValue()) + .extract().body().asString(); + + JsonNode node = mapper.readTree(body); + apiId = node.get("id").asText(); + } + + @Test + @Order(2) + void importedAnyMethod_isRegisteredOnResource() throws Exception { + String body = given() + .contentType(ContentType.JSON) + .when() + .get("/restapis/" + apiId + "/resources") + .then() + .statusCode(200) + .extract().body().asString(); + + JsonNode resources = mapper.readTree(body).get("item"); + for (JsonNode r : resources) { + if ("/echo".equals(r.get("path").asText())) { + anyResourceId = r.get("id").asText(); + } + } + assertNotNull(anyResourceId, "Should have /echo resource"); + + // The method must exist as "ANY" (not silently dropped, and not e.g. "GET"). + given() + .contentType(ContentType.JSON) + .when() + .get("/restapis/" + apiId + "/resources/" + anyResourceId + "/methods/ANY") + .then() + .statusCode(200) + .body("httpMethod", equalTo("ANY")); + } + + @Test + @Order(3) + void importedAnyMethod_hasMockIntegration() { + given() + .contentType(ContentType.JSON) + .when() + .get("/restapis/" + apiId + "/resources/" + anyResourceId + "/methods/ANY/integration") + .then() + .statusCode(200) + .body("type", equalTo("MOCK")); + } + + @Test + @Order(4) + void deployAndInvoke_concreteMethodsMatchImportedAnyMethod() throws Exception { + String deploymentId = given() + .contentType(ContentType.JSON) + .body("{\"description\":\"v1\"}") + .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); + + // Concrete HTTP verbs must all be routed through the imported ANY method's mock integration. + for (String verb : new String[] { "GET", "POST", "PUT", "DELETE" }) { + String responseBody = given() + .contentType(ContentType.JSON) + .when() + .request(verb, "/execute-api/" + apiId + "/test/echo") + .then() + .statusCode(200) + .extract().body().asString(); + JsonNode node = mapper.readTree(responseBody); + assertEquals("any", node.get("matched").asText(), verb + " should hit the imported ANY method"); + } + } + + @Test + @Order(5) + void cleanup() { + given().when().delete("/restapis/" + apiId).then().statusCode(202); + } + + @Test + @Order(6) + void import_withMalformedAnyMethodExtension_returnsCleanBadRequest() { + // "x-amazon-apigateway-any-method" set to a plain string instead of an operation object. + // Json.mapper().convertValue(..., Operation.class) can't coerce this and must not be allowed + // to escape as an uncaught IllegalArgumentException (which would surface as a raw 500). + String spec = """ + { + "openapi": "3.0.1", + "info": { + "title": "MalformedAnyMethodAPI", + "version": "1.0" + }, + "paths": { + "/broken": { + "x-amazon-apigateway-any-method": "not-an-operation-object" + } + } + } + """; + + given() + .contentType(ContentType.JSON) + .queryParam("mode", "import") + .body(spec) + .when() + .post("/restapis") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + @Test + @Order(7) + void import_withMalformedIntegrationExtension_returnsCleanBadRequest() { + // "x-amazon-apigateway-integration" set to an array instead of an integration object. The + // cast to Map must be guarded so this can't escape as an uncaught + // ClassCastException (which would surface as a raw 500). + String spec = """ + { + "openapi": "3.0.1", + "info": { + "title": "MalformedIntegrationAPI", + "version": "1.0" + }, + "paths": { + "/broken": { + "get": { + "responses": { + "200": { + "description": "200 response" + } + }, + "x-amazon-apigateway-integration": ["not", "an", "object"] + } + } + } + } + """; + + given() + .contentType(ContentType.JSON) + .queryParam("mode", "import") + .body(spec) + .when() + .post("/restapis") + .then() + .statusCode(400) + .body("__type", equalTo("BadRequestException")); + } +}