diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java index 0f1acc5017..7f79c1d2c4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java @@ -797,6 +797,25 @@ public class ApiGatewayV2Service { return integration; } + /** + * Sets the method, template selection expression, timeout and the two mapping tables exactly as + * given, null included. A timeout of 0 is the unset value. UpdateIntegration keeps a field the + * request leaves out, so it cannot remove one that CloudFormation dropped. + */ + public Integration replaceIntegrationSettings(String region, String apiId, String integrationId, + String integrationMethod, String templateSelectionExpression, + int timeoutInMillis, Map requestParameters, + Map requestTemplates) { + Integration integration = getIntegration(region, apiId, integrationId); + integration.setIntegrationMethod(integrationMethod); + integration.setTemplateSelectionExpression(templateSelectionExpression); + integration.setTimeoutInMillis(timeoutInMillis); + integration.setRequestParameters(requestParameters); + integration.setRequestTemplates(requestTemplates); + integrationStore.put(integrationKey(region, apiId, integrationId), integration); + return integration; + } + // ──────────────────────────── Stage CRUD ──────────────────────────── public Stage createStage(String region, String apiId, Map request) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayV2CfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayV2CfnProvisioner.java index b6ed526199..46f1ff0791 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayV2CfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ApiGatewayV2CfnProvisioner.java @@ -867,6 +867,27 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { String connectionId = ctx.resolveOptional(props, "ConnectionId"); req.put("connectionType", connectionType); req.put("connectionId", connectionId); + req.put("integrationMethod", ctx.resolveOrDefault(props, "IntegrationMethod", null)); + req.put("templateSelectionExpression", + ctx.resolveOrDefault(props, "TemplateSelectionExpression", null)); + String timeout = ctx.resolveOrDefault(props, "TimeoutInMillis", null); + int timeoutInMillis = 0; + if (timeout != null) { + try { + timeoutInMillis = Integer.parseInt(timeout); + req.put("timeoutInMillis", timeoutInMillis); + } catch (NumberFormatException e) { + throw new AwsException("ValidationError", "TimeoutInMillis must be an integer", 400); + } + } + Map requestParameters = resolveStringMap(props, "RequestParameters", ctx.engine()); + if (requestParameters != null) { + req.put("requestParameters", requestParameters); + } + Map requestTemplates = resolveStringMap(props, "RequestTemplates", ctx.engine()); + if (requestTemplates != null) { + req.put("requestTemplates", requestTemplates); + } // A snapshot describes the update in flight; one an earlier update left behind is stale. r.getAttributes().remove(CfnRollback.INTEGRATION_CONNECTION_SNAPSHOT_ATTR); @@ -883,6 +904,12 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { // A connection removed from the template is removed here too. INTERNET is the AWS default. apiGatewayV2Service.replaceIntegrationConnection(region, apiId, r.getPhysicalId(), connectionType != null ? connectionType : "INTERNET", connectionId); + // These fields are exactly what the template says: one it dropped is removed, and a + // dropped TimeoutInMillis is 0, the value CreateIntegration stores when it is absent. + apiGatewayV2Service.replaceIntegrationSettings(region, apiId, r.getPhysicalId(), + (String) req.get("integrationMethod"), + (String) req.get("templateSelectionExpression"), timeoutInMillis, + requestParameters, requestTemplates); integration = apiGatewayV2Service.updateIntegration(region, apiId, r.getPhysicalId(), req); } catch (RuntimeException failure) { // The stack skips rollbackUpdate for a resource whose own update failed, so undo it here. @@ -890,7 +917,7 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { rollbackIntegrationConnection(r); } catch (RuntimeException restoreFailure) { r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, - "Could not roll back the connection of integration " + r.getPhysicalId() + ": " + "Could not roll back integration " + r.getPhysicalId() + ": " + restoreFailure.getMessage()); if (restoreFailure != failure) { failure.addSuppressed(restoreFailure); @@ -904,9 +931,9 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { } /** - * The connection the integration had before this update, and whether the update also changes - * another field. UpdateIntegration keeps a field the request leaves out, so only a value that - * is set and differs counts as a change. + * The connection and the five settings the integration had before this update, and whether the + * update also changes another field. UpdateIntegration keeps a field the request leaves out, so + * only a value that is set and differs counts as a change. */ private String integrationConnectionSnapshot(String region, String apiId, Integration prior, Map req) { @@ -918,6 +945,11 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { snapshot.put("apiId", apiId); snapshot.put("connectionType", prior.getConnectionType()); snapshot.put("connectionId", prior.getConnectionId()); + snapshot.put("integrationMethod", prior.getIntegrationMethod()); + snapshot.put("templateSelectionExpression", prior.getTemplateSelectionExpression()); + snapshot.put("timeoutInMillis", prior.getTimeoutInMillis()); + snapshot.set("requestParameters", objectMapper.valueToTree(prior.getRequestParameters())); + snapshot.set("requestTemplates", objectMapper.valueToTree(prior.getRequestTemplates())); snapshot.put("otherFieldChanged", otherFieldChanged); return snapshot.toString(); } @@ -927,9 +959,9 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { } /** - * Puts the connection back from the snapshot taken before the update. Answers true only when the - * update changed nothing else: this provisioner keeps no copy of the other fields, so the stack - * must still report that their rollback is not implemented. + * Puts the connection and the settings back from the snapshot taken before the update. Answers + * true only when the update changed nothing else: this provisioner keeps no copy of the other + * fields, so the stack must still report that their rollback is not implemented. */ private boolean rollbackIntegrationConnection(StackResource resource) { String raw = resource.getAttributes().get(CfnRollback.INTEGRATION_CONNECTION_SNAPSHOT_ATTR); @@ -947,11 +979,25 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { apiGatewayV2Service.replaceIntegrationConnection(snapshot.path("region").asText(), snapshot.path("apiId").asText(), resource.getPhysicalId(), textOrNull(snapshot, "connectionType"), textOrNull(snapshot, "connectionId")); + apiGatewayV2Service.replaceIntegrationSettings(snapshot.path("region").asText(), + snapshot.path("apiId").asText(), resource.getPhysicalId(), + textOrNull(snapshot, "integrationMethod"), textOrNull(snapshot, "templateSelectionExpression"), + snapshot.path("timeoutInMillis").asInt(), stringMapOrNull(snapshot.path("requestParameters")), + stringMapOrNull(snapshot.path("requestTemplates"))); // Spent only once the restore succeeded, so a restore that throws can be tried again. resource.getAttributes().remove(CfnRollback.INTEGRATION_CONNECTION_SNAPSHOT_ATTR); return !snapshot.path("otherFieldChanged").asBoolean(); } + private static Map stringMapOrNull(JsonNode node) { + if (node == null || !node.isObject()) { + return null; + } + Map out = new LinkedHashMap<>(); + node.fields().forEachRemaining(e -> out.put(e.getKey(), e.getValue().asText())); + return out; + } + // ── Stage ──────────────────────────────────────────────────────────────── private void provisionStage(StackResource r, JsonNode props, ProvisionContext ctx) { @@ -1155,10 +1201,19 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner { } private Map parseStageVariables(JsonNode props, CloudFormationTemplateEngine engine) { - if (props == null || !props.has("StageVariables") || props.get("StageVariables").isNull()) { + return resolveStringMap(props, "StageVariables", engine); + } + + /** + * Resolves an object property to a string map in template order, or null when absent or not an + * object. An entry whose value is a selected {@code AWS::NoValue} is left out. + */ + private static Map resolveStringMap(JsonNode props, String name, + CloudFormationTemplateEngine engine) { + if (props == null || !props.has(name) || props.get(name).isNull()) { return null; } - JsonNode resolved = engine.resolveNode(props.get("StageVariables")); + JsonNode resolved = engine.resolveNodeOmittingNoValue(props.get(name)); if (resolved == null || !resolved.isObject()) { return null; } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java index cec9a2cd39..c70cb66af5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2CfnProvisionerTest.java @@ -715,6 +715,209 @@ class ApiGatewayV2CfnProvisionerTest { assertFalse(integration.getAttributes().containsKey("__FlociIntegrationConnectionSnapshot")); } + @Test + void integrationCreatePassesMethodParametersTemplatesTimeoutAndSelectionExpression() throws Exception { + Integration integration = new Integration(); + integration.setIntegrationId("int-1"); + when(apiGatewayV2Service.createIntegration(eq(REGION), eq(API_ID), anyMap())).thenReturn(integration); + + provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration", mapper.readTree(INTEGRATION_PROPERTIES), + engine(), REGION, "000000000000", "test-stack", null, Map.of()); + + verify(apiGatewayV2Service).createIntegration(eq(REGION), eq(API_ID), argThat(this::carriesIntegrationProperties)); + } + + @Test + void integrationUpdatePassesMethodParametersTemplatesTimeoutAndSelectionExpression() throws Exception { + stubIntegrationUpdate(priorVpcLinkIntegration()); + + StackResource integration = provisionIntegration(INTEGRATION_PROPERTIES); + + assertTrue(integration.getStatus().endsWith("_COMPLETE"), integration.getStatus()); + verify(apiGatewayV2Service).updateIntegration(eq(REGION), eq(API_ID), eq("int-1"), + argThat(this::carriesIntegrationProperties)); + } + + @Test + void integrationRequestParametersResolveIntrinsics() throws Exception { + Integration integration = new Integration(); + integration.setIntegrationId("int-1"); + when(apiGatewayV2Service.createIntegration(eq(REGION), eq(API_ID), anyMap())).thenReturn(integration); + + provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration", mapper.readTree(""" + {"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend", + "RequestParameters":{"overwrite:header.x-stack":{"Ref":"AWS::StackName"}}} + """), + engine(), REGION, "000000000000", "test-stack", null, Map.of()); + + verify(apiGatewayV2Service).createIntegration(eq(REGION), eq(API_ID), argThat(req -> + Map.of("overwrite:header.x-stack", "test-stack").equals(req.get("requestParameters")))); + } + + @Test + void integrationWithNonNumericTimeoutIsRejected() throws Exception { + StackResource integration = provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration", + mapper.readTree(""" + {"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend", + "TimeoutInMillis":"soon"} + """), + engine(), REGION, "000000000000", "test-stack", null, Map.of()); + + assertEquals("CREATE_FAILED", integration.getStatus()); + verify(apiGatewayV2Service, never()).createIntegration(any(), any(), anyMap()); + } + + @Test + void integrationUpdateWithoutSettingsReplacesThemWithNull() throws Exception { + stubIntegrationUpdate(priorVpcLinkIntegration()); + + StackResource integration = provisionIntegration(""" + {"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend", + "ConnectionType":"VPC_LINK","ConnectionId":"vl-1"} + """); + + assertTrue(integration.getStatus().endsWith("_COMPLETE"), integration.getStatus()); + verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", null, null, 0, null, null); + } + + @Test + void integrationUpdateKeepsTheSettingsTheTemplateStillSets() throws Exception { + stubIntegrationUpdate(priorVpcLinkIntegration()); + + provisionIntegration(INTEGRATION_PROPERTIES); + + verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", "ANY", + "${request.method}", 15000, Map.of("append:header.x-request-id", "$context.requestId", + "overwrite:header.x-example", "static-value"), + Map.of("application/json", "{\"a\":1}")); + } + + @Test + void integrationMappingEntryWithNoValueIsOmitted() throws Exception { + Integration integration = new Integration(); + integration.setIntegrationId("int-1"); + when(apiGatewayV2Service.createIntegration(eq(REGION), eq(API_ID), anyMap())).thenReturn(integration); + + provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration", mapper.readTree(""" + {"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend", + "RequestParameters":{"overwrite:header.x-on":"yes", + "overwrite:header.x-off":{"Fn::If":["Off",{"Ref":"AWS::NoValue"},"no"]}}} + """), + engine(Map.of("Off", true)), REGION, "000000000000", "test-stack", null, Map.of()); + + verify(apiGatewayV2Service).createIntegration(eq(REGION), eq(API_ID), argThat(req -> + Map.of("overwrite:header.x-on", "yes").equals(req.get("requestParameters")))); + } + + @Test + void rollbackOfAnIntegrationUpdateRestoresItsSettings() throws Exception { + Integration prior = priorVpcLinkIntegration(); + prior.setIntegrationMethod("GET"); + prior.setTemplateSelectionExpression("${request.method}"); + prior.setTimeoutInMillis(15000); + prior.setRequestParameters(Map.of("overwrite:header.x-example", "old")); + prior.setRequestTemplates(Map.of("application/json", "{}")); + stubIntegrationUpdate(prior); + StackResource integration = provisionIntegration(""" + {"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend", + "ConnectionType":"VPC_LINK","ConnectionId":"vl-1","IntegrationMethod":"POST", + "TimeoutInMillis":"3000","RequestParameters":{"overwrite:header.x-example":"new"}} + """); + + assertTrue(provisioner.rollbackUpdate(integration)); + + InOrder order = inOrder(apiGatewayV2Service); + order.verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", "POST", null, 3000, + Map.of("overwrite:header.x-example", "new"), null); + order.verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", "GET", + "${request.method}", 15000, Map.of("overwrite:header.x-example", "old"), + Map.of("application/json", "{}")); + } + + @Test + void failedIntegrationUpdateRestoresItsSettings() throws Exception { + Integration prior = priorVpcLinkIntegration(); + prior.setRequestParameters(Map.of("overwrite:header.x-example", "old")); + stubIntegrationUpdate(prior); + when(apiGatewayV2Service.updateIntegration(eq(REGION), eq(API_ID), eq("int-1"), anyMap())) + .thenThrow(new AwsException("NotFoundException", "Integration not found", 404)); + + StackResource integration = provisionIntegration(""" + {"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend", + "ConnectionType":"VPC_LINK","ConnectionId":"vl-1"} + """); + + assertTrue(integration.getStatus().endsWith("_FAILED"), integration.getStatus()); + verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", null, null, 0, null, null); + verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", null, null, 0, + Map.of("overwrite:header.x-example", "old"), null); + } + + private static final String NO_VALUE_SETTINGS = """ + {"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend", + "IntegrationMethod":{"Fn::If":["Off",{"Ref":"AWS::NoValue"},"ANY"]}, + "TemplateSelectionExpression":{"Ref":"AWS::NoValue"}, + "TimeoutInMillis":{"Fn::If":["Off",{"Ref":"AWS::NoValue"},"15000"]}} + """; + + @Test + void integrationCreateTreatsNoValueScalarsAsAbsent() throws Exception { + Integration integration = new Integration(); + integration.setIntegrationId("int-1"); + when(apiGatewayV2Service.createIntegration(eq(REGION), eq(API_ID), anyMap())).thenReturn(integration); + + StackResource resource = provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration", + mapper.readTree(NO_VALUE_SETTINGS), engine(Map.of("Off", true)), REGION, "000000000000", + "test-stack", null, Map.of()); + + assertTrue(resource.getStatus().endsWith("_COMPLETE"), resource.getStatus()); + verify(apiGatewayV2Service).createIntegration(eq(REGION), eq(API_ID), argThat(req -> + req.get("integrationMethod") == null && req.get("templateSelectionExpression") == null + && !req.containsKey("timeoutInMillis"))); + } + + @Test + void integrationUpdateTreatsNoValueScalarsAsAbsent() throws Exception { + stubIntegrationUpdate(priorVpcLinkIntegration()); + + StackResource resource = provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration", + mapper.readTree(NO_VALUE_SETTINGS), engine(Map.of("Off", true)), REGION, "000000000000", + "test-stack", "int-1", Map.of("IntegrationId", "int-1")); + + assertTrue(resource.getStatus().endsWith("_COMPLETE"), resource.getStatus()); + verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", null, null, 0, null, null); + } + + @Test + void integrationScalarsKeepTheBranchAnFnIfSelects() throws Exception { + stubIntegrationUpdate(priorVpcLinkIntegration()); + + provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration", + mapper.readTree(NO_VALUE_SETTINGS), engine(Map.of("Off", false)), REGION, "000000000000", + "test-stack", "int-1", Map.of("IntegrationId", "int-1")); + + verify(apiGatewayV2Service).replaceIntegrationSettings(REGION, API_ID, "int-1", "ANY", null, 15000, + null, null); + } + + private static final String INTEGRATION_PROPERTIES = """ + {"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend", + "IntegrationMethod":"ANY","PayloadFormatVersion":"1.0","TimeoutInMillis":"15000", + "TemplateSelectionExpression":"${request.method}", + "RequestParameters":{"append:header.x-request-id":"$context.requestId", + "overwrite:header.x-example":"static-value"}, + "RequestTemplates":{"application/json":"{\\"a\\":1}"}} + """; + + private boolean carriesIntegrationProperties(Map req) { + return "ANY".equals(req.get("integrationMethod")) + && Integer.valueOf(15000).equals(req.get("timeoutInMillis")) + && "${request.method}".equals(req.get("templateSelectionExpression")) + && Map.of("append:header.x-request-id", "$context.requestId", + "overwrite:header.x-example", "static-value").equals(req.get("requestParameters")) + && Map.of("application/json", "{\"a\":1}").equals(req.get("requestTemplates")); + } + private static Integration priorVpcLinkIntegration() { Integration prior = new Integration(); prior.setIntegrationId("int-1"); @@ -771,8 +974,12 @@ class ApiGatewayV2CfnProvisionerTest { } private CloudFormationTemplateEngine engine() { + return engine(Map.of()); + } + + private CloudFormationTemplateEngine engine(Map conditions) { return new CloudFormationTemplateEngine("000000000000", REGION, "test-stack", "stack/id", - Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper, + Map.of(), Map.of(), Map.of(), conditions, Map.of(), mapper, (Function) name -> null); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2StackTestSupport.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2StackTestSupport.java new file mode 100644 index 0000000000..40eaaa7130 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/ApiGatewayV2StackTestSupport.java @@ -0,0 +1,71 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; +import io.github.hectorvent.floci.services.apigatewayv2.model.Integration; +import io.github.hectorvent.floci.services.cloudformation.model.Stack; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.restassured.specification.RequestSpecification; + +import static io.restassured.RestAssured.given; + +/** + * What the AWS::ApiGatewayV2 stack integration tests share: driving a stack through the query API, + * waiting for its status, and reading back the stack and its {@code Integration} resource. + */ +final class ApiGatewayV2StackTestSupport { + + static final String REGION = "us-east-1"; + + /** A resource that fails to create, so an update that adds it rolls back. */ + static final String FAILING_RESOURCE = + ",\"Broken\":{\"Type\":\"AWS::ApiGatewayV2::VpcLink\",\"DependsOn\":\"Integration\"," + + "\"Properties\":{\"Name\":\"broken\"}}"; + + private ApiGatewayV2StackTestSupport() { + } + + static Integration integration(ApiGatewayV2Service apiGatewayV2Service, Stack stack) { + StackResource api = stack.getResources().get("HttpApi"); + StackResource integration = stack.getResources().get("Integration"); + return apiGatewayV2Service.getIntegration(REGION, api.getPhysicalId(), integration.getPhysicalId()); + } + + static Stack stack(CloudFormationService cloudFormationService, String stackName) { + return cloudFormationService.describeStacks(stackName, REGION).getFirst(); + } + + static void stackAction(String action, String stackName, String template) { + RequestSpecification request = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", action) + .formParam("StackName", stackName); + if (template != null) { + request.formParam("TemplateBody", template); + } + request.when().post("/").then().statusCode(200); + } + + static void waitForStackStatus(CloudFormationService cloudFormationService, String stackName, + String expected) { + String status = null; + for (int attempt = 0; attempt < 200; attempt++) { + try { + status = cloudFormationService.describeStacks(stackName, REGION).getFirst().getStatus(); + } catch (AwsException e) { + // A deleted stack can no longer be described by name. + status = "DELETE_COMPLETE"; + } + if (expected.equals(status)) { + return; + } + try { + Thread.sleep(25); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError("Interrupted while waiting for stack status", e); + } + } + throw new AssertionError("Stack did not reach " + expected + ", last status " + status); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest.java new file mode 100644 index 0000000000..e2468a37c6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest.java @@ -0,0 +1,134 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; +import io.github.hectorvent.floci.services.apigatewayv2.model.Integration; +import io.github.hectorvent.floci.services.cloudformation.model.Stack; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.FAILING_RESOURCE; +import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.REGION; +import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.integration; +import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.stack; +import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.stackAction; +import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.waitForStackStatus; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * The settings of an AWS::ApiGatewayV2::Integration through a real stack: a setting the template + * drops on update is removed from the stored integration and from GetIntegration, and a failed + * update puts the earlier settings back. + */ +@QuarkusTest +class CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest { + + private static final String PARAMETERS = + ",\"RequestParameters\":{\"overwrite:header.x-example\":\"%s\"}"; + private static final String TIMEOUT = ",\"TimeoutInMillis\":15000"; + + @Inject + ApiGatewayV2Service apiGatewayV2Service; + + @Inject + CloudFormationService cloudFormationService; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void removingSettingsFromTheTemplateRemovesThemFromTheIntegration() { + String stackName = "integration-settings-removal-stack"; + stackAction("CreateStack", stackName, template(PARAMETERS.formatted("value-1") + TIMEOUT, "")); + waitForStackStatus(cloudFormationService, stackName, "CREATE_COMPLETE"); + Integration created = integration(apiGatewayV2Service, stack(cloudFormationService, stackName)); + assertEquals(Map.of("overwrite:header.x-example", "value-1"), created.getRequestParameters()); + assertEquals(15000, created.getTimeoutInMillis()); + + stackAction("UpdateStack", stackName, template(TIMEOUT, "")); + waitForStackStatus(cloudFormationService, stackName, "UPDATE_COMPLETE"); + + Stack updated = stack(cloudFormationService, stackName); + Integration integration = integration(apiGatewayV2Service, updated); + assertNull(integration.getRequestParameters()); + assertEquals(15000, integration.getTimeoutInMillis()); + assertEquals("ANY", integration.getIntegrationMethod()); + assertEquals("http://backend.example", integration.getIntegrationUri()); + getIntegrationResponse(updated) + .body("requestParameters", nullValue()) + .body("timeoutInMillis", equalTo(15000)); + + stackAction("UpdateStack", stackName, template("", "")); + waitForStackStatus(cloudFormationService, stackName, "UPDATE_COMPLETE"); + + Stack withoutTimeout = stack(cloudFormationService, stackName); + assertEquals(0, integration(apiGatewayV2Service, withoutTimeout).getTimeoutInMillis()); + getIntegrationResponse(withoutTimeout).body("timeoutInMillis", nullValue()); + } + + @Test + void aTimeoutThatBecomesNoValueIsRemoved() { + String stackName = "integration-settings-novalue-stack"; + stackAction("CreateStack", stackName, template(TIMEOUT, "")); + waitForStackStatus(cloudFormationService, stackName, "CREATE_COMPLETE"); + assertEquals(15000, integration(apiGatewayV2Service, stack(cloudFormationService, stackName)).getTimeoutInMillis()); + + stackAction("UpdateStack", stackName, template( + ",\"TimeoutInMillis\":{\"Fn::If\":[\"Off\",{\"Ref\":\"AWS::NoValue\"},15000]}", "")); + waitForStackStatus(cloudFormationService, stackName, "UPDATE_COMPLETE"); + + assertEquals(0, integration(apiGatewayV2Service, stack(cloudFormationService, stackName)).getTimeoutInMillis()); + } + + @Test + void failedUpdateRestoresTheEarlierRequestParameters() { + String stackName = "integration-settings-rollback-stack"; + stackAction("CreateStack", stackName, template(PARAMETERS.formatted("original") + TIMEOUT, "")); + waitForStackStatus(cloudFormationService, stackName, "CREATE_COMPLETE"); + + stackAction("UpdateStack", stackName, template(PARAMETERS.formatted("changed"), FAILING_RESOURCE)); + waitForStackStatus(cloudFormationService, stackName, "UPDATE_ROLLBACK_COMPLETE"); + + Stack rolledBack = stack(cloudFormationService, stackName); + Integration integration = integration(apiGatewayV2Service, rolledBack); + assertEquals(Map.of("overwrite:header.x-example", "original"), integration.getRequestParameters()); + assertEquals(15000, integration.getTimeoutInMillis()); + getIntegrationResponse(rolledBack) + .body("requestParameters.'overwrite:header.x-example'", equalTo("original")); + } + + private ValidatableResponse getIntegrationResponse(Stack stack) { + String apiId = stack.getResources().get("HttpApi").getPhysicalId(); + String integrationId = stack.getResources().get("Integration").getPhysicalId(); + return given().when().get("/v2/apis/" + apiId + "/integrations/" + integrationId) + .then().statusCode(200); + } + + /** + * An HTTP API and an HTTP_PROXY integration to a plain URL, so no container starts. + * {@code settings} adds integration properties and {@code extraResources} adds resources, both + * as JSON fragments that start with a comma. + */ + private static String template(String settings, String extraResources) { + return """ + {"Conditions":{"Off":{"Fn::Equals":["a","a"]}}, + "Resources":{ + "HttpApi":{"Type":"AWS::ApiGatewayV2::Api","Properties":{ + "Name":"integration-settings-api","ProtocolType":"HTTP"}}, + "Integration":{"Type":"AWS::ApiGatewayV2::Integration","Properties":{ + "ApiId":{"Ref":"HttpApi"},"IntegrationType":"HTTP_PROXY","IntegrationMethod":"ANY", + "IntegrationUri":"http://backend.example","PayloadFormatVersion":"1.0"%s}}%s}} + """.formatted(settings, extraResources); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationApiGatewayV2VpcLinkIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationApiGatewayV2VpcLinkIntegrationTest.java index af8feea138..ff8ffc31b5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationApiGatewayV2VpcLinkIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationApiGatewayV2VpcLinkIntegrationTest.java @@ -5,10 +5,8 @@ import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; import io.github.hectorvent.floci.services.apigatewayv2.model.Integration; import io.github.hectorvent.floci.services.apigatewayv2.model.VpcLink; import io.github.hectorvent.floci.services.cloudformation.model.Stack; -import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; -import io.restassured.specification.RequestSpecification; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -16,7 +14,12 @@ import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; -import static io.restassured.RestAssured.given; +import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.FAILING_RESOURCE; +import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.REGION; +import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.integration; +import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.stack; +import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.stackAction; +import static io.github.hectorvent.floci.services.cloudformation.ApiGatewayV2StackTestSupport.waitForStackStatus; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -31,13 +34,9 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @QuarkusTest class CloudFormationApiGatewayV2VpcLinkIntegrationTest { - private static final String REGION = "us-east-1"; private static final String STACK_NAME = "vpclink-stack"; private static final String VPC_LINK_CONNECTION = ",\"ConnectionType\":\"VPC_LINK\",\"ConnectionId\":{\"Ref\":\"VpcLink\"}"; - private static final String FAILING_RESOURCE = - ",\"Broken\":{\"Type\":\"AWS::ApiGatewayV2::VpcLink\",\"DependsOn\":\"Integration\"," - + "\"Properties\":{\"Name\":\"broken\"}}"; @Inject ApiGatewayV2Service apiGatewayV2Service; @@ -53,35 +52,35 @@ class CloudFormationApiGatewayV2VpcLinkIntegrationTest { @Test void vpcLinkLifecycleFollowsTheCloudFormationUpdateRules() { stackAction("CreateStack", STACK_NAME, template("first-name", "subnet-aaaa1111")); - waitForStackStatus(STACK_NAME, "CREATE_COMPLETE"); + waitForStackStatus(cloudFormationService, STACK_NAME, "CREATE_COMPLETE"); - Stack created = stack(STACK_NAME); + Stack created = stack(cloudFormationService, STACK_NAME); String vpcLinkId = created.getOutputs().get("VpcLinkRef"); assertEquals(vpcLinkId, created.getOutputs().get("VpcLinkIdAttr")); VpcLink link = apiGatewayV2Service.getVpcLink(REGION, vpcLinkId); assertEquals("first-name", link.getName()); assertEquals(List.of("subnet-aaaa1111"), link.getSubnetIds()); assertEquals(Map.of("Env", "test"), link.getTags()); - Integration integration = integration(created); + Integration integration = integration(apiGatewayV2Service, created); assertEquals("VPC_LINK", integration.getConnectionType()); assertEquals(vpcLinkId, integration.getConnectionId()); stackAction("UpdateStack", STACK_NAME, template("second-name", "subnet-aaaa1111")); - waitForStackStatus(STACK_NAME, "UPDATE_COMPLETE"); - assertEquals(vpcLinkId, stack(STACK_NAME).getOutputs().get("VpcLinkRef"), "a Name change keeps the same link"); + waitForStackStatus(cloudFormationService, STACK_NAME, "UPDATE_COMPLETE"); + assertEquals(vpcLinkId, stack(cloudFormationService, STACK_NAME).getOutputs().get("VpcLinkRef"), "a Name change keeps the same link"); assertEquals("second-name", apiGatewayV2Service.getVpcLink(REGION, vpcLinkId).getName()); stackAction("UpdateStack", STACK_NAME, template("second-name", "subnet-bbbb2222")); - waitForStackStatus(STACK_NAME, "UPDATE_COMPLETE"); - Stack replaced = stack(STACK_NAME); + waitForStackStatus(cloudFormationService, STACK_NAME, "UPDATE_COMPLETE"); + Stack replaced = stack(cloudFormationService, STACK_NAME); String newVpcLinkId = replaced.getOutputs().get("VpcLinkRef"); assertNotEquals(vpcLinkId, newVpcLinkId, "a SubnetIds change replaces the link"); assertEquals(List.of("subnet-bbbb2222"), apiGatewayV2Service.getVpcLink(REGION, newVpcLinkId).getSubnetIds()); assertNotFound(vpcLinkId); - assertEquals(newVpcLinkId, integration(replaced).getConnectionId()); + assertEquals(newVpcLinkId, integration(apiGatewayV2Service, replaced).getConnectionId()); stackAction("DeleteStack", STACK_NAME, null); - waitForStackStatus(STACK_NAME, "DELETE_COMPLETE"); + waitForStackStatus(cloudFormationService, STACK_NAME, "DELETE_COMPLETE"); assertNotFound(newVpcLinkId); } @@ -90,17 +89,17 @@ class CloudFormationApiGatewayV2VpcLinkIntegrationTest { String stackName = "vpclink-rollback-stack"; stackAction("CreateStack", stackName, template("rollback-link", "subnet-aaaa1111", "{}", VPC_LINK_CONNECTION, "")); - waitForStackStatus(stackName, "CREATE_COMPLETE"); - String vpcLinkId = stack(stackName).getOutputs().get("VpcLinkRef"); + waitForStackStatus(cloudFormationService, stackName, "CREATE_COMPLETE"); + String vpcLinkId = stack(cloudFormationService, stackName).getOutputs().get("VpcLinkRef"); stackAction("UpdateStack", stackName, template("rollback-link", "subnet-bbbb2222", "{}", VPC_LINK_CONNECTION, FAILING_RESOURCE)); - waitForStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE"); + waitForStackStatus(cloudFormationService, stackName, "UPDATE_ROLLBACK_COMPLETE"); - Stack rolledBack = stack(stackName); + Stack rolledBack = stack(cloudFormationService, stackName); assertEquals(vpcLinkId, rolledBack.getOutputs().get("VpcLinkRef")); assertEquals(List.of("subnet-aaaa1111"), apiGatewayV2Service.getVpcLink(REGION, vpcLinkId).getSubnetIds()); - Integration integration = integration(rolledBack); + Integration integration = integration(apiGatewayV2Service, rolledBack); assertEquals("VPC_LINK", integration.getConnectionType()); assertEquals(vpcLinkId, integration.getConnectionId()); assertEquals(1, apiGatewayV2Service.getVpcLinks(REGION).stream() @@ -113,12 +112,12 @@ class CloudFormationApiGatewayV2VpcLinkIntegrationTest { String stackName = "vpclink-connection-stack"; stackAction("CreateStack", stackName, template("connection-link", "subnet-aaaa1111", "{}", VPC_LINK_CONNECTION, "")); - waitForStackStatus(stackName, "CREATE_COMPLETE"); + waitForStackStatus(cloudFormationService, stackName, "CREATE_COMPLETE"); stackAction("UpdateStack", stackName, template("connection-link", "subnet-aaaa1111", "{}", "", "")); - waitForStackStatus(stackName, "UPDATE_COMPLETE"); + waitForStackStatus(cloudFormationService, stackName, "UPDATE_COMPLETE"); - Integration integration = integration(stack(stackName)); + Integration integration = integration(apiGatewayV2Service, stack(cloudFormationService, stackName)); assertEquals("INTERNET", integration.getConnectionType()); assertNull(integration.getConnectionId()); } @@ -128,11 +127,11 @@ class CloudFormationApiGatewayV2VpcLinkIntegrationTest { String stackName = "vpclink-reserved-tag-stack"; String tags = "{\"floci:note\":\"kept\",\"Env\":\"test\"}"; stackAction("CreateStack", stackName, template("reserved-v1", "subnet-aaaa1111", tags, "", "")); - waitForStackStatus(stackName, "CREATE_COMPLETE"); - String vpcLinkId = stack(stackName).getOutputs().get("VpcLinkRef"); + waitForStackStatus(cloudFormationService, stackName, "CREATE_COMPLETE"); + String vpcLinkId = stack(cloudFormationService, stackName).getOutputs().get("VpcLinkRef"); stackAction("UpdateStack", stackName, template("reserved-v2", "subnet-aaaa1111", tags, "", "")); - waitForStackStatus(stackName, "UPDATE_COMPLETE"); + waitForStackStatus(cloudFormationService, stackName, "UPDATE_COMPLETE"); VpcLink link = apiGatewayV2Service.getVpcLink(REGION, vpcLinkId); assertEquals("reserved-v2", link.getName()); @@ -144,49 +143,6 @@ class CloudFormationApiGatewayV2VpcLinkIntegrationTest { assertEquals("NotFoundException", e.getErrorCode()); } - private Integration integration(Stack stack) { - StackResource api = stack.getResources().get("HttpApi"); - StackResource integration = stack.getResources().get("Integration"); - return apiGatewayV2Service.getIntegration(REGION, api.getPhysicalId(), integration.getPhysicalId()); - } - - private Stack stack(String stackName) { - return cloudFormationService.describeStacks(stackName, REGION).getFirst(); - } - - private static void stackAction(String action, String stackName, String template) { - RequestSpecification request = given() - .contentType("application/x-www-form-urlencoded") - .formParam("Action", action) - .formParam("StackName", stackName); - if (template != null) { - request.formParam("TemplateBody", template); - } - request.when().post("/").then().statusCode(200); - } - - private void waitForStackStatus(String stackName, String expected) { - String status = null; - for (int attempt = 0; attempt < 200; attempt++) { - try { - status = cloudFormationService.describeStacks(stackName, REGION).getFirst().getStatus(); - } catch (AwsException e) { - // A deleted stack can no longer be described by name. - status = "DELETE_COMPLETE"; - } - if (expected.equals(status)) { - return; - } - try { - Thread.sleep(25); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new AssertionError("Interrupted while waiting for stack status", e); - } - } - throw new AssertionError("Stack did not reach " + expected + ", last status " + status); - } - private static String template(String linkName, String subnetId) { return """ {"Resources":{