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 c42dea6375..0a92a0a480 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 @@ -499,7 +499,10 @@ public class ApiGatewayService { String httpMethod, String statusCode, Map request) { MethodConfig method = getMethod(region, apiId, resourceId, httpMethod); - MethodResponse mr = new MethodResponse(statusCode, new HashMap<>()); + @SuppressWarnings("unchecked") + Map responseParameters = (Map) request.get("responseParameters"); + MethodResponse mr = new MethodResponse(statusCode, + responseParameters != null ? responseParameters : new HashMap<>()); method.getMethodResponses().put(statusCode, mr); resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId)); return mr; diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java index 685b9d94f6..f84d50a5e7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java @@ -15,6 +15,7 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -179,17 +180,65 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { apiGatewayService.putMethod(region, apiId, resourceId, httpMethod, req); r.setPhysicalId(apiId + "-" + resourceId + "-" + httpMethod); + if (props != null && props.has("MethodResponses")) { + JsonNode responses = engine.resolveNode(props.get("MethodResponses")); + if (responses != null && responses.isArray()) { + for (JsonNode response : responses) { + String statusCode = ctx.resolveOptional(response, "StatusCode"); + Map responseReq = new HashMap<>(); + Map responseParameters = new LinkedHashMap<>(); + JsonNode parameters = engine.resolveNode(response.path("ResponseParameters")); + if (parameters != null && parameters.isObject()) { + parameters.fields().forEachRemaining(entry -> responseParameters.put( + entry.getKey(), Boolean.parseBoolean(engine.resolve(entry.getValue())))); + } + responseReq.put("responseParameters", responseParameters); + apiGatewayService.putMethodResponse(region, apiId, resourceId, httpMethod, + statusCode, responseReq); + } + } + } + if (props != null && props.has("Integration")) { JsonNode integNode = engine.resolveNode(props.get("Integration")); Map integReq = new HashMap<>(); integReq.put("type", ctx.resolveOptional(integNode, "Type")); integReq.put("httpMethod", ctx.resolveOptional(integNode, "IntegrationHttpMethod")); integReq.put("uri", ctx.resolveOptional(integNode, "Uri")); + integReq.put("requestTemplates", resolveStringMap(integNode, "RequestTemplates", engine)); + integReq.put("requestParameters", resolveStringMap(integNode, "RequestParameters", engine)); + integReq.put("passthroughBehavior", ctx.resolveOptional(integNode, "PassthroughBehavior")); + integReq.put("contentHandling", ctx.resolveOptional(integNode, "ContentHandling")); apiGatewayService.putIntegration(region, apiId, resourceId, httpMethod, integReq); + + JsonNode responses = engine.resolveNode(integNode.path("IntegrationResponses")); + if (responses != null && responses.isArray()) { + for (JsonNode response : responses) { + String statusCode = ctx.resolveOptional(response, "StatusCode"); + Map responseReq = new HashMap<>(); + responseReq.put("responseParameters", resolveStringMap(response, "ResponseParameters", engine)); + responseReq.put("responseTemplates", resolveStringMap(response, "ResponseTemplates", engine)); + responseReq.put("selectionPattern", ctx.resolveOptional(response, "SelectionPattern")); + responseReq.put("contentHandling", ctx.resolveOptional(response, "ContentHandling")); + apiGatewayService.putIntegrationResponse(region, apiId, resourceId, httpMethod, + statusCode, responseReq); + } + } } } + private Map resolveStringMap(JsonNode props, String name, + CloudFormationTemplateEngine engine) { + Map result = new LinkedHashMap<>(); + JsonNode node = engine.resolveNode(props.path(name)); + if (node != null && node.isObject()) { + node.fields().forEachRemaining(entry -> + result.put(entry.getKey(), engine.resolve(entry.getValue()))); + } + return result; + } + private void provisionDeployment(StackResource r, JsonNode props, ProvisionContext ctx) { String region = ctx.region(); String apiId = ctx.resolveOptional(props, "RestApiId"); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayCfnMockCorsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayCfnMockCorsIntegrationTest.java new file mode 100644 index 0000000000..d1a598ec67 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayCfnMockCorsIntegrationTest.java @@ -0,0 +1,97 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.core.common.XmlParser; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** The Serverless Framework CORS shape: an OPTIONS method with a MOCK integration in CFN. */ +@QuarkusTest +class ApiGatewayCfnMockCorsIntegrationTest { + + private static final String STACK = "apigw-cfn-mock-cors-it"; + private static final String TEMPLATE = """ + { + "Resources": { + "Api": {"Type":"AWS::ApiGateway::RestApi", "Properties":{"Name":"cfn-mock-cors"}}, + "Items": {"Type":"AWS::ApiGateway::Resource", "Properties":{ + "RestApiId":{"Ref":"Api"}, + "ParentId":{"Fn::GetAtt":["Api","RootResourceId"]}, + "PathPart":"items"}}, + "Options": {"Type":"AWS::ApiGateway::Method", "Properties":{ + "RestApiId":{"Ref":"Api"}, "ResourceId":{"Ref":"Items"}, + "HttpMethod":"OPTIONS", "AuthorizationType":"NONE", + "MethodResponses":[{"StatusCode":"200", "ResponseParameters":{ + "method.response.header.Access-Control-Allow-Origin":true, + "method.response.header.Access-Control-Allow-Methods":true, + "method.response.header.Access-Control-Allow-Headers":true}}], + "Integration":{"Type":"MOCK", "PassthroughBehavior":"NEVER", + "RequestTemplates":{"application/json":"{\\"statusCode\\":200}"}, + "IntegrationResponses":[{"StatusCode":"200", "ResponseParameters":{ + "method.response.header.Access-Control-Allow-Origin":"'*'", + "method.response.header.Access-Control-Allow-Methods":"'GET,OPTIONS'", + "method.response.header.Access-Control-Allow-Headers":"'Content-Type,X-Api-Key'"}}]}}}, + "Deployment": {"Type":"AWS::ApiGateway::Deployment", "DependsOn":"Options", + "Properties":{"RestApiId":{"Ref":"Api"},"StageName":"dev"}} + }, + "Outputs":{"ApiId":{"Value":{"Ref":"Api"}}, + "ResourceId":{"Value":{"Ref":"Items"}}} + } + """; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void cloudFormationMockPreflightReturnsItsConfiguredCorsHeaders() { + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", STACK) + .formParam("TemplateBody", TEMPLATE) + .when().post("/").then().statusCode(200); + try { + String xml = given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", STACK) + .when().post("/").then().statusCode(200) + .body(containsString("CREATE_COMPLETE")) + .extract().asString(); + String apiId = XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue") + .get("ApiId"); + String resourceId = XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue") + .get("ResourceId"); + + given().when().get("/restapis/" + apiId + "/resources/" + resourceId + + "/methods/OPTIONS/integration/responses/200") + .then().statusCode(200) + .body("responseParameters.'method.response.header.Access-Control-Allow-Origin'", + equalTo("'*'")); + + for (String path : new String[]{"/execute-api/" + apiId + "/dev/items", + "/restapis/" + apiId + "/dev/_user_request_/items"}) { + var response = given().header("Origin", "https://example.com") + .header("Access-Control-Request-Method", "GET") + .when().options(path).then().statusCode(200) + .header("Access-Control-Allow-Origin", equalTo("*")) + .header("Access-Control-Allow-Methods", equalTo("GET,OPTIONS")) + .header("Access-Control-Allow-Headers", equalTo("Content-Type,X-Api-Key")) + .extract().response(); + assertEquals(200, response.statusCode()); + } + } finally { + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteStack") + .formParam("StackName", STACK) + .when().post("/").then().statusCode(200); + CfnStackWaits.awaitStackDeleted(STACK); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisionerTest.java index 6b9171a798..866bd27f54 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisionerTest.java @@ -15,6 +15,7 @@ import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @@ -104,6 +105,34 @@ class ApiGatewayRestApiCfnProvisionerTest { verify(api).putIntegration(eq("us-east-1"), eq("api-1"), eq("res-1"), eq("GET"), anyMap()); } + @Test + void methodProvisionsMockTemplatesAndCorsResponses() throws Exception { + StackResource r = resource("AWS::ApiGateway::Method", "Options"); + provisioner.provision(r, props(""" + {"RestApiId":"api-1","ResourceId":"res-1","HttpMethod":"OPTIONS", + "MethodResponses":[{"StatusCode":"200","ResponseParameters":{ + "method.response.header.Access-Control-Allow-Origin":true}}], + "Integration":{"Type":"MOCK","RequestTemplates":{ + "application/json":"{\\\"statusCode\\\":200}"}, + "IntegrationResponses":[{"StatusCode":"200","ResponseParameters":{ + "method.response.header.Access-Control-Allow-Origin":"'*'"}, + "ResponseTemplates":{"application/json":"{}"}}]}} + """), ctx()); + + verify(api).putMethodResponse("us-east-1", "api-1", "res-1", "OPTIONS", "200", + Map.of("responseParameters", Map.of( + "method.response.header.Access-Control-Allow-Origin", true))); + verify(api).putIntegration(eq("us-east-1"), eq("api-1"), eq("res-1"), eq("OPTIONS"), + org.mockito.ArgumentMatchers.argThat(request -> Map.of( + "application/json", "{\"statusCode\":200}") + .equals(request.get("requestTemplates")))); + verify(api).putIntegrationResponse(eq("us-east-1"), eq("api-1"), eq("res-1"), eq("OPTIONS"), eq("200"), + org.mockito.ArgumentMatchers.argThat(request -> + Map.of("method.response.header.Access-Control-Allow-Origin", "'*'") + .equals(request.get("responseParameters")) + && Map.of("application/json", "{}").equals(request.get("responseTemplates")))); + } + @Test void deploymentPublishesDeploymentIdAndCreatesTheInlineStage() throws Exception { when(api.createDeployment(eq("us-east-1"), eq("api-1"), anyMap()))