From 5e9df931e3b606f3b0b1437f8c962db6c9775bb5 Mon Sep 17 00:00:00 2001 From: Oleksandr Nikolaichuk <57410473+Sekator778@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:22:30 +0300 Subject: [PATCH] fix(cloudformation): clear an AppSync property the new template drops on update (#6995) * fix(cloudformation): clear an AppSync property the new template drops on update An update whose template drops a property the previous template declared now clears it on the five AppSync types, and one the stack never declared keeps the value set outside it. ProvisionContext.droppedProperties names the dropped properties. * test(cloudformation): move the AppSync removal case into AppSyncCfnIntegrationTest The case reuses the class's helpers, now built on CfnRequests.cfn, instead of a second copy. Documents the AppSync update rule next to the AWS::NoValue section. --- docs/services/cloudformation.md | 9 + .../provisioners/AppSyncCfnProvisioner.java | 100 ++++- .../provisioners/ProvisionContext.java | 27 ++ .../AppSyncCfnIntegrationTest.java | 102 ++++- .../AppSyncCfnProvisionerTest.java | 367 ++++++++++++++++++ .../provisioners/ProvisionContextTest.java | 24 ++ 6 files changed, 606 insertions(+), 23 deletions(-) diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 27e4bcea26..516c013494 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -695,6 +695,15 @@ Where the registry schema corpus is present under `local/aws/cfn-resource-schema (gitignored, so not in CI), `CfnSchemaCoverageTest` fails when a writable property is neither read nor listed, and when a listed property has started to be read, so closing a gap deletes its row. +On AppSync resources, a property the previous template declared and the new template drops is cleared +on `UpdateStack`; one the stack never declared keeps the value set outside it. A few members go back to +their create default (`XrayEnabled`, `AdditionalAuthenticationProviders`, a function's `FunctionVersion`, +a resolver's `Kind`). Not cleared: the identifiers, `Tags` and `EnvironmentVariables`, which the +provisioner already drives to the template, required members (`AuthenticationType`, `Type`, a function's +`DataSourceName`), create-only members, an API key's `Expires`, a GraphQL API's `ApiType` and +`Visibility`, and a UNIT resolver's `DataSourceName`. Other services follow +[#6606](https://github.com/floci-io/floci/issues/6606). + ## Template URLs A `TemplateURL` names an object in Floci's S3, virtual-hosted or path-style. As on AWS, one whose diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppSyncCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppSyncCfnProvisioner.java index 28a51c206e..953672acba 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppSyncCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppSyncCfnProvisioner.java @@ -9,8 +9,10 @@ import io.github.hectorvent.floci.services.appsync.model.DataSource; import io.github.hectorvent.floci.services.appsync.model.FunctionConfiguration; import io.github.hectorvent.floci.services.appsync.model.GraphqlApi; import io.github.hectorvent.floci.services.appsync.model.Resolver; +import io.github.hectorvent.floci.services.appsync.model.ResolverKind; import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatus; import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatusType; +import io.github.hectorvent.floci.services.cloudformation.CfnCreateOnlyProperties; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -79,6 +81,40 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { */ private static final Set OPAQUE_KEY_PROPERTIES = Set.of("EnvironmentVariables"); + /** + * Properties the provisioner fills itself, so a template that drops one still has it on the + * request: the identifiers, and the two the provisioner handles in its own call ({@code Tags} + * as a map, {@code EnvironmentVariables} as a second call). + */ + private static final Set NEVER_CLEARED = + Set.of("ApiId", "Name", "TypeName", "FieldName", "Tags", "EnvironmentVariables"); + + /** + * Required properties of a type, which a template cannot drop and the service cannot hold as + * null, {@code Expires}, whose update the service parses as a date (null is refused), and the + * GraphQLApi {@code ApiType} and {@code Visibility}, which UpdateGraphqlApi does not take + * (CreateGraphqlApi: visibility "cannot be changed once the API has been created"): the stored + * value stays. A resolver's {@code DataSourceName} stays here too and is cleared only for + * a pipeline resolver, in {@link #provisionResolver}. + */ + private static final Map> KEPT_ON_DROP = Map.of( + GRAPHQL_API, Set.of("AuthenticationType", "ApiType", "Visibility"), + DATA_SOURCE, Set.of("Type"), + FUNCTION_CONFIGURATION, Set.of("DataSourceName"), + RESOLVER, Set.of("DataSourceName"), + API_KEY, Set.of("Expires")); + + /** + * What a dropped property goes back to where the service's update does not take null as a + * clear: it ignores a null boolean or list, or the member has a default on create that a null + * would turn into an absent value. + */ + private static final Map> DEFAULT_ON_DROP = Map.of( + GRAPHQL_API, Map.of("XrayEnabled", false, + "AdditionalAuthenticationProviders", List.of()), + FUNCTION_CONFIGURATION, Map.of("FunctionVersion", "2018-05-29"), + RESOLVER, Map.of("Kind", "UNIT")); + /** * How long a stack resource waits for a schema to compile. Generous: the wait is bounded only so * a wedged worker cannot hang a stack operation forever, and a schema that hits this is reported @@ -133,6 +169,9 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { if (blank(str(req.get("name")))) { req.put("name", ctx.generatePhysicalName(r.getLogicalId(), 65, false)); } + if (ctx.isUpdate()) { + clearDropped(req, props, ctx, GRAPHQL_API); + } GraphqlApi api = ctx.isUpdate() ? appSyncService.updateGraphqlApi(ctx.priorPhysicalId(), req, ctx.region()) @@ -244,7 +283,11 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { req.put("name", name); } - DataSource ds = reusesEntity(r, ctx, apiId) && name.equals(attribute(r, "Name")) + boolean update = reusesEntity(r, ctx, apiId) && name.equals(attribute(r, "Name")); + if (update) { + clearDropped(req, props, ctx, DATA_SOURCE); + } + DataSource ds = update ? appSyncService.updateDataSource(apiId, name, req) : appSyncService.createDataSource(apiId, req, ctx.region()); @@ -266,7 +309,11 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { } String priorFunctionId = attribute(r, "FunctionId"); - FunctionConfiguration fn = reusesEntity(r, ctx, apiId) && !blank(priorFunctionId) + boolean update = reusesEntity(r, ctx, apiId) && !blank(priorFunctionId); + if (update) { + clearDropped(req, props, ctx, FUNCTION_CONFIGURATION); + } + FunctionConfiguration fn = update ? appSyncService.updateFunction(apiId, priorFunctionId, req) : appSyncService.createFunction(apiId, req, ctx.region()); @@ -295,7 +342,16 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { boolean sameField = typeName.equals(attribute(r, "TypeName")) && fieldName.equals(attribute(r, "FieldName")); - Resolver resolver = reusesEntity(r, ctx, apiId) && sameField + boolean update = reusesEntity(r, ctx, apiId) && sameField; + if (update) { + clearDropped(req, props, ctx, RESOLVER); + // A UNIT resolver needs its data source (createResolver refuses none): clear it only on a pipeline. + if (ctx.droppedProperties(props).contains("DataSourceName") + && isPipeline(req, apiId, typeName, fieldName)) { + req.put("dataSourceName", null); + } + } + Resolver resolver = update ? appSyncService.updateResolver(apiId, typeName, fieldName, req) : appSyncService.createResolver(apiId, req, ctx.region()); @@ -312,7 +368,11 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { Map req = camelisedProperties(props, ctx); String apiId = requiredApiId(req, API_KEY); - ApiKey key = reusesEntity(r, ctx, apiId) + boolean update = reusesEntity(r, ctx, apiId); + if (update) { + clearDropped(req, props, ctx, API_KEY); + } + ApiKey key = update ? appSyncService.updateApiKey(apiId, ctx.priorPhysicalId(), req) : appSyncService.createApiKey(apiId, req); @@ -387,6 +447,38 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { return ctx.isUpdate() && apiId.equals(attribute(r, "ApiId")); } + /** + * Puts each property the previous template declared and this one drops on an update request as + * its API member with a null value, which the service's update reads as a clear (it applies a + * member by {@code containsKey}), so the entity stops carrying what the template no longer + * names. A property the stack never declared is not on the request and keeps whatever was set + * outside it. Left out: what the provisioner fills or handles itself, a create-only property + * (dropping one is a replacement question), and the few {@link #KEPT_ON_DROP} properties the + * service cannot hold as null; a few {@link #DEFAULT_ON_DROP} go back to their create default. + */ + private void clearDropped(Map req, JsonNode props, ProvisionContext ctx, + String resourceType) { + Set kept = KEPT_ON_DROP.getOrDefault(resourceType, Set.of()); + Map defaults = DEFAULT_ON_DROP.getOrDefault(resourceType, Map.of()); + for (String name : ctx.droppedProperties(props)) { + if (NEVER_CLEARED.contains(name) || kept.contains(name) + || CfnCreateOnlyProperties.isCreateOnly(resourceType, name)) { + continue; + } + req.put(apiMemberName(name), defaults.get(name)); + } + } + + private boolean isPipeline(Map req, String apiId, String typeName, + String fieldName) { + Object kind = req.get("kind"); + if (kind == null) { + Resolver stored = appSyncService.getResolver(apiId, typeName, fieldName); + return stored != null && stored.getKind() == ResolverKind.PIPELINE; + } + return "PIPELINE".equals(kind.toString()); + } + private void rejectS3Code(Map req, String resourceType) { if (req.get("codeS3Location") != null) { throw new AwsException("ValidationError", resourceType diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java index f718e86843..310269551a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java @@ -7,8 +7,10 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackEvent; import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; import java.util.function.Consumer; @@ -73,6 +75,31 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio && !priorProperties.get(name).isNull(); } + /** + * The top-level properties the previous template declared and {@code props}, the properties + * this update applies, no longer has: the ones an update that removes a property has to clear. + * A property the stack never declared is not in the set, so a value set outside the stack + * survives, and a property whose {@code Fn::If} chose {@code AWS::NoValue} on either template + * counts as not declared there, as in {@link #previouslyDeclared}. Empty for a create, and for + * a resource whose previous template did not declare it. + * + *

The rule only says which names went; what clearing one means is the service's own. A + * provisioner clears each by the call its service offers and leaves out the ones AWS keeps + * (a create-only property is a replacement question, not a clear). + */ + public Set droppedProperties(JsonNode props) { + Set dropped = new LinkedHashSet<>(); + if (!isUpdate() || priorProperties == null) { + return dropped; + } + priorProperties.fieldNames().forEachRemaining(name -> { + if (previouslyDeclared(name) && (props == null || !props.has(name))) { + dropped.add(name); + } + }); + return dropped; + } + /** * Resolves a CloudFormation tag property to a map, preserving template order. Both registry * shapes are read: the {@code [{Key, Value}]} list most types declare, and the diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/AppSyncCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AppSyncCfnIntegrationTest.java index 48a0c61e7b..cf7c9db49b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/AppSyncCfnIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AppSyncCfnIntegrationTest.java @@ -12,10 +12,12 @@ import org.junit.jupiter.api.Test; import java.util.Map; +import static io.github.hectorvent.floci.testing.CfnRequests.cfn; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -51,6 +53,7 @@ class AppSyncCfnIntegrationTest { private static final String APPSYNC_AUTH = "AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/appsync/aws4_request"; private static final String STACK = "appsync-cfn-it"; + private static final String REMOVAL_STACK = "appsync-cfn-removal-it"; private static final String TEMPLATE = """ { @@ -149,10 +152,43 @@ class AppSyncCfnIntegrationTest { } """; + private static final String REMOVAL_FIRST = """ + { + "Conditions": {"Off": {"Fn::Equals": ["a", "b"]}}, + "Resources": { + "GraphQlApi": { + "Type": "AWS::AppSync::GraphQLApi", + "Properties": { + "Name": "appsync-cfn-removal-it-api", + "AuthenticationType": "API_KEY", + "OwnerContact": "platform-team", + "IntrospectionConfig": {"Fn::If": ["Off", "DISABLED", {"Ref": "AWS::NoValue"}]} + } + } + }, + "Outputs": {"ApiId": {"Value": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}}} + } + """; + + private static final String REMOVAL_SECOND = """ + { + "Resources": { + "GraphQlApi": { + "Type": "AWS::AppSync::GraphQLApi", + "Properties": { + "Name": "appsync-cfn-removal-it-api", + "AuthenticationType": "API_KEY" + } + } + }, + "Outputs": {"ApiId": {"Value": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}}} + } + """; + @Test void createUpdateAndDeleteAnAppSyncApi() { - cloudFormation("CreateStack", Map.of("FieldLogLevel", "ERROR")); - String created = describeStacks("CREATE_COMPLETE"); + cloudFormation("CreateStack", STACK, TEMPLATE, Map.of("FieldLogLevel", "ERROR")); + String created = describeStacks(STACK, "CREATE_COMPLETE"); String apiId = outputValue(created, "ApiId"); String functionId = outputValue(created, "FunctionId"); @@ -216,8 +252,8 @@ class AppSyncCfnIntegrationTest { .body("apiKeys[0].id", equalTo(apiKey)) .body("apiKeys[0].description", equalTo("integration")); - cloudFormation("UpdateStack", Map.of("FieldLogLevel", "ALL")); - String updated = describeStacks("UPDATE_COMPLETE"); + cloudFormation("UpdateStack", STACK, TEMPLATE, Map.of("FieldLogLevel", "ALL")); + String updated = describeStacks(STACK, "UPDATE_COMPLETE"); // Nothing is replaced by a second deploy: the same API, data source and function, updated // in place. Re-creating instead would answer 400 on the duplicate name. @@ -228,20 +264,52 @@ class AppSyncCfnIntegrationTest { .statusCode(200) .body("resolver.pipelineConfig.functions[0]", equalTo(functionId)); - cloudFormation("DeleteStack", Map.of()); + cloudFormation("DeleteStack", STACK, null, Map.of()); CfnStackWaits.awaitStackDeleted(STACK); appSync("/v1/apis/" + apiId).statusCode(404); } - private static void cloudFormation(String action, Map parameters) { - RequestSpecification request = given() - .contentType("application/x-www-form-urlencoded") - .header("Authorization", CFN_AUTH) - .formParam("Action", action) - .formParam("StackName", STACK); - if (!"DeleteStack".equals(action)) { - request.formParam("TemplateBody", TEMPLATE); + /** + * An update that drops an AppSync property clears it, and one the stack never declared keeps + * the value set outside it. Run through CreateStack and UpdateStack so the previous template's + * properties, evaluated under its conditions, reach the provisioner the way they do for a user: + * a {@code Fn::If} that chose {@code AWS::NoValue} on the first template counts as not declared. + */ + @Test + void anUpdateClearsWhatTheNewTemplateDropsAndKeepsWhatTheStackNeverDeclared() { + cloudFormation("CreateStack", REMOVAL_STACK, REMOVAL_FIRST, Map.of()); + CfnStackWaits.awaitStatus(REMOVAL_STACK, "CREATE_COMPLETE"); + String apiId = outputValue(describeStacks(REMOVAL_STACK, "CREATE_COMPLETE"), "ApiId"); + + appSync("/v1/apis/" + apiId) + .statusCode(200) + .body("graphqlApi.ownerContact", equalTo("platform-team")) + .body("graphqlApi.introspectionConfig", nullValue()); + + // Set outside the stack, which the first template left to AWS::NoValue. + given().contentType("application/json").header("Authorization", APPSYNC_AUTH) + .body("{\"name\":\"appsync-cfn-removal-it-api\",\"authenticationType\":\"API_KEY\"," + + "\"introspectionConfig\":\"DISABLED\"}") + .when().post("/v1/apis/" + apiId).then().statusCode(200); + + cloudFormation("UpdateStack", REMOVAL_STACK, REMOVAL_SECOND, Map.of()); + CfnStackWaits.awaitStatus(REMOVAL_STACK, "UPDATE_COMPLETE"); + + appSync("/v1/apis/" + apiId) + .statusCode(200) + .body("graphqlApi.ownerContact", nullValue()) + .body("graphqlApi.introspectionConfig", equalTo("DISABLED")); + + cloudFormation("DeleteStack", REMOVAL_STACK, null, Map.of()); + CfnStackWaits.awaitStackDeleted(REMOVAL_STACK); + } + + private static void cloudFormation(String action, String stackName, String template, + Map parameters) { + RequestSpecification request = cfn(action, stackName).header("Authorization", CFN_AUTH); + if (template != null) { + request.formParam("TemplateBody", template); } int index = 1; for (Map.Entry parameter : parameters.entrySet()) { @@ -252,12 +320,8 @@ class AppSyncCfnIntegrationTest { request.when().post("/").then().statusCode(200); } - private static String describeStacks(String expectedStatus) { - return given() - .contentType("application/x-www-form-urlencoded") - .header("Authorization", CFN_AUTH) - .formParam("Action", "DescribeStacks") - .formParam("StackName", STACK) + private static String describeStacks(String stackName, String expectedStatus) { + return cfn("DescribeStacks", stackName).header("Authorization", CFN_AUTH) .when().post("/").then().statusCode(200) .body(containsString("" + expectedStatus + "")) .extract().asString(); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppSyncCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppSyncCfnProvisionerTest.java index 8b48110fab..eab58d1df7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppSyncCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppSyncCfnProvisionerTest.java @@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.appsync.model.DataSource; import io.github.hectorvent.floci.services.appsync.model.FunctionConfiguration; import io.github.hectorvent.floci.services.appsync.model.GraphqlApi; import io.github.hectorvent.floci.services.appsync.model.Resolver; +import io.github.hectorvent.floci.services.appsync.model.ResolverKind; import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatus; import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatusType; import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; @@ -65,6 +66,13 @@ class AppSyncCfnProvisionerTest { create.stackName(), priorPhysicalId); } + /** The update path, with the properties the previous template declared (as the stack hands them over). */ + private ProvisionContext updateCtx(String priorPhysicalId, String priorProperties) throws Exception { + ProvisionContext create = ctx(); + return new ProvisionContext(create.engine(), create.region(), create.accountId(), + create.stackName(), priorPhysicalId, event -> { }, mapper.readTree(priorProperties)); + } + private StackResource resource(String type, String logicalId) { StackResource r = new StackResource(); r.setLogicalId(logicalId); @@ -606,6 +614,365 @@ class AppSyncCfnProvisionerTest { + "/apikeys/da2-abcdefghijklmnopqrstuvwxyz", r.getAttributes().get("Arn")); } + // ── A property the new template drops ──────────────────────────────────── + + @SuppressWarnings("unchecked") + private Map updateRequest(ArgumentCaptor> captor) { + return captor.getValue(); + } + + @Test + void graphqlApiUpdateClearsAPropertyTheNewTemplateDrops() throws Exception { + when(appSync.updateGraphqlApi(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(api()); + StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi"); + + provisioner.provision(r, mapper.readTree( + "{\"Name\":\"account-api\",\"AuthenticationType\":\"API_KEY\"}"), + updateCtx(API_ID, "{\"Name\":\"account-api\",\"AuthenticationType\":\"API_KEY\"," + + "\"OwnerContact\":\"team\",\"UserPoolConfig\":{\"AwsRegion\":\"eu-west-1\"}}")); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateGraphqlApi(eq(API_ID), captor.capture(), eq("eu-west-1")); + Map req = updateRequest(captor); + // A null value on a present key is how the service's update clears a member. + assertTrue(req.containsKey("ownerContact")); + assertNull(req.get("ownerContact")); + assertTrue(req.containsKey("userPoolConfig")); + assertNull(req.get("userPoolConfig")); + } + + @Test + void graphqlApiUpdateLeavesAPropertyTheStackNeverDeclaredAlone() throws Exception { + when(appSync.updateGraphqlApi(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(api()); + StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi"); + + provisioner.provision(r, mapper.readTree( + "{\"Name\":\"account-api\",\"AuthenticationType\":\"API_KEY\"}"), + updateCtx(API_ID, "{\"Name\":\"account-api\",\"AuthenticationType\":\"API_KEY\"}")); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateGraphqlApi(eq(API_ID), captor.capture(), eq("eu-west-1")); + // Only what the template names, and the tags the provisioner always drives: ownerContact set + // outside the stack is not on the request, so the service does not touch it. + assertEquals(Set.of("name", "authenticationType", "tags"), updateRequest(captor).keySet()); + } + + @Test + void graphqlApiUpdateTreatsAPreviousNoValueAsNotDeclared() throws Exception { + when(appSync.updateGraphqlApi(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(api()); + StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi"); + + // The stack hands over the previous template's properties with every top-level Fn::If that + // chose AWS::NoValue already taken out, so OwnerContact is simply not among them. + provisioner.provision(r, mapper.readTree( + "{\"Name\":\"account-api\",\"AuthenticationType\":\"API_KEY\"}"), + updateCtx(API_ID, "{\"Name\":\"account-api\",\"AuthenticationType\":\"API_KEY\"}")); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateGraphqlApi(eq(API_ID), captor.capture(), eq("eu-west-1")); + assertFalse(updateRequest(captor).containsKey("ownerContact")); + } + + @Test + void graphqlApiUpdateSendsTheCreateDefaultWhereNullIsNotAClear() throws Exception { + when(appSync.updateGraphqlApi(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(api()); + StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi"); + + provisioner.provision(r, mapper.readTree( + "{\"Name\":\"account-api\",\"AuthenticationType\":\"API_KEY\"}"), + updateCtx(API_ID, "{\"Name\":\"account-api\",\"AuthenticationType\":\"API_KEY\"," + + "\"XrayEnabled\":true,\"Visibility\":\"PRIVATE\",\"ApiType\":\"MERGED\"," + + "\"AdditionalAuthenticationProviders\":[{\"AuthenticationType\":\"AWS_IAM\"}]}")); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateGraphqlApi(eq(API_ID), captor.capture(), eq("eu-west-1")); + Map req = updateRequest(captor); + // The service reads a null boolean or list as "not given", so these carry what a create gives. + assertEquals(false, req.get("xrayEnabled")); + // UpdateGraphqlApi takes no visibility and a created value cannot change: the dropped one stays. + assertFalse(req.containsKey("visibility")); + assertFalse(req.containsKey("apiType")); + assertEquals(List.of(), req.get("additionalAuthenticationProviders")); + } + + @Test + void graphqlApiUpdateKeepsWhatAnEmptyTemplateCannotDrop() throws Exception { + when(appSync.updateGraphqlApi(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(api()); + StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi"); + + provisioner.provision(r, mapper.readTree("{}"), + updateCtx(API_ID, "{\"Name\":\"account-api\",\"AuthenticationType\":\"API_KEY\"," + + "\"Tags\":[{\"Key\":\"a\",\"Value\":\"b\"}]," + + "\"EnvironmentVariables\":{\"A\":\"b\"}}")); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateGraphqlApi(eq(API_ID), captor.capture(), eq("eu-west-1")); + Map req = updateRequest(captor); + // Required and handled-elsewhere names never become a null: the generated name stays a name, + // the authentication type stays, tags are the empty map and the variables their own call. + assertEquals(Set.of("name", "tags"), req.keySet()); + verify(appSync).putEnvironmentVariables(API_ID, Map.of()); + } + + @Test + void dataSourceUpdateClearsAPropertyTheNewTemplateDrops() throws Exception { + DataSource ds = new DataSource(); + ds.setName("accountDB"); + ds.setDataSourceArn("arn:ds"); + when(appSync.updateDataSource(eq(API_ID), eq("accountDB"), any())).thenReturn(ds); + StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb"); + r.getAttributes().put("ApiId", API_ID); + r.getAttributes().put("Name", "accountDB"); + + provisioner.provision(r, mapper.readTree( + "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\",\"Type\":\"AMAZON_DYNAMODB\"}"), + updateCtx("arn:ds", "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\"," + + "\"Type\":\"AMAZON_DYNAMODB\",\"Description\":\"old\"," + + "\"DynamoDBConfig\":{\"TableName\":\"t\"}}")); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateDataSource(eq(API_ID), eq("accountDB"), captor.capture()); + Map req = updateRequest(captor); + assertTrue(req.containsKey("description")); + assertNull(req.get("description")); + // The AWS spelling of the one member that does not lower-camelise. + assertTrue(req.containsKey("dynamodbConfig")); + assertNull(req.get("dynamodbConfig")); + assertEquals("AMAZON_DYNAMODB", req.get("type")); + } + + @Test + void dataSourceUpdateLeavesAPropertyTheStackNeverDeclaredAlone() throws Exception { + DataSource ds = new DataSource(); + ds.setName("accountDB"); + ds.setDataSourceArn("arn:ds"); + when(appSync.updateDataSource(eq(API_ID), eq("accountDB"), any())).thenReturn(ds); + StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb"); + r.getAttributes().put("ApiId", API_ID); + r.getAttributes().put("Name", "accountDB"); + String declared = "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\",\"Type\":\"AMAZON_DYNAMODB\"}"; + + // The previous template has no NoValue-chosen Description either: it was filtered out. + provisioner.provision(r, mapper.readTree(declared), updateCtx("arn:ds", declared)); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateDataSource(eq(API_ID), eq("accountDB"), captor.capture()); + assertFalse(updateRequest(captor).containsKey("description")); + assertFalse(updateRequest(captor).containsKey("serviceRoleArn")); + } + + @Test + void dataSourceCreateAfterAMoveClearsNothing() throws Exception { + DataSource ds = new DataSource(); + ds.setName("accountDB"); + ds.setDataSourceArn("arn:ds"); + when(appSync.createDataSource(anyString(), any(), anyString())).thenReturn(ds); + StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb"); + r.getAttributes().put("ApiId", "otherApi"); + r.getAttributes().put("Name", "accountDB"); + + provisioner.provision(r, mapper.readTree( + "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\",\"Type\":\"AMAZON_DYNAMODB\"}"), + updateCtx("arn:ds", "{\"ApiId\":\"otherApi\",\"Name\":\"accountDB\"," + + "\"Type\":\"AMAZON_DYNAMODB\",\"Description\":\"old\"}")); + + // A replacement builds a new entity from the template: there is nothing to clear on it. + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).createDataSource(eq(API_ID), captor.capture(), eq("eu-west-1")); + assertFalse(updateRequest(captor).containsKey("description")); + } + + @Test + void functionUpdateClearsAPropertyTheNewTemplateDrops() throws Exception { + FunctionConfiguration fn = new FunctionConfiguration(); + fn.setFunctionId("fn123"); + fn.setName("fn"); + fn.setFunctionArn("arn:fn"); + when(appSync.updateFunction(eq(API_ID), eq("fn123"), any())).thenReturn(fn); + StackResource r = resource("AWS::AppSync::FunctionConfiguration", "GraphQlFn"); + r.getAttributes().put("ApiId", API_ID); + r.getAttributes().put("FunctionId", "fn123"); + String now = "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"fn\",\"DataSourceName\":\"accountDB\"}"; + + provisioner.provision(r, mapper.readTree(now), updateCtx("arn:fn", + "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"fn\",\"DataSourceName\":\"accountDB\"," + + "\"Description\":\"old\",\"FunctionVersion\":\"2018-05-29\"," + + "\"MaxBatchSize\":5}")); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateFunction(eq(API_ID), eq("fn123"), captor.capture()); + Map req = updateRequest(captor); + assertTrue(req.containsKey("description")); + assertNull(req.get("description")); + assertTrue(req.containsKey("maxBatchSize")); + assertNull(req.get("maxBatchSize")); + assertEquals("2018-05-29", req.get("functionVersion")); + assertEquals("accountDB", req.get("dataSourceName")); + } + + @Test + void functionUpdateLeavesAPropertyTheStackNeverDeclaredAlone() throws Exception { + FunctionConfiguration fn = new FunctionConfiguration(); + fn.setFunctionId("fn123"); + fn.setName("fn"); + fn.setFunctionArn("arn:fn"); + when(appSync.updateFunction(eq(API_ID), eq("fn123"), any())).thenReturn(fn); + StackResource r = resource("AWS::AppSync::FunctionConfiguration", "GraphQlFn"); + r.getAttributes().put("ApiId", API_ID); + r.getAttributes().put("FunctionId", "fn123"); + String declared = "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"fn\",\"DataSourceName\":\"accountDB\"}"; + + provisioner.provision(r, mapper.readTree(declared), updateCtx("arn:fn", declared)); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateFunction(eq(API_ID), eq("fn123"), captor.capture()); + assertEquals(Set.of("name", "dataSourceName"), updateRequest(captor).keySet()); + } + + @Test + void resolverUpdateClearsAPropertyTheNewTemplateDrops() throws Exception { + Resolver resolver = new Resolver(); + resolver.setResolverArn("arn:resolver"); + when(appSync.updateResolver(eq(API_ID), eq("Query"), eq("getMessages"), any())).thenReturn(resolver); + StackResource r = resource("AWS::AppSync::Resolver", "GraphQlResolver"); + r.getAttributes().put("ApiId", API_ID); + r.getAttributes().put("TypeName", "Query"); + r.getAttributes().put("FieldName", "getMessages"); + String head = "\"ApiId\":\"" + API_ID + "\",\"TypeName\":\"Query\",\"FieldName\":\"getMessages\""; + + provisioner.provision(r, mapper.readTree("{" + head + ",\"DataSourceName\":\"accountDB\"}"), + updateCtx("arn:resolver", "{" + head + ",\"DataSourceName\":\"accountDB\"," + + "\"ResponseMappingTemplate\":\"old\",\"Kind\":\"PIPELINE\"," + + "\"CachingConfig\":{\"Ttl\":60}}")); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateResolver(eq(API_ID), eq("Query"), eq("getMessages"), captor.capture()); + Map req = updateRequest(captor); + assertTrue(req.containsKey("responseMappingTemplate")); + assertNull(req.get("responseMappingTemplate")); + assertTrue(req.containsKey("cachingConfig")); + assertNull(req.get("cachingConfig")); + // A null kind would leave a resolver of no kind; the create default is UNIT. + assertEquals("UNIT", req.get("kind")); + assertEquals("Query", req.get("typeName")); + assertEquals("getMessages", req.get("fieldName")); + } + + @Test + void resolverUpdateKeepsTheDataSourceOfAUnitResolverThatDropsIt() throws Exception { + Resolver resolver = new Resolver(); + resolver.setResolverArn("arn:resolver"); + when(appSync.updateResolver(eq(API_ID), eq("Query"), eq("getMessages"), any())).thenReturn(resolver); + Resolver stored = new Resolver(); + stored.setKind(ResolverKind.UNIT); + when(appSync.getResolver(API_ID, "Query", "getMessages")).thenReturn(stored); + StackResource r = resource("AWS::AppSync::Resolver", "GraphQlResolver"); + r.getAttributes().put("ApiId", API_ID); + r.getAttributes().put("TypeName", "Query"); + r.getAttributes().put("FieldName", "getMessages"); + String head = "\"ApiId\":\"" + API_ID + "\",\"TypeName\":\"Query\",\"FieldName\":\"getMessages\""; + + provisioner.provision(r, mapper.readTree("{" + head + "}"), + updateCtx("arn:resolver", "{" + head + ",\"DataSourceName\":\"accountDB\"}")); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateResolver(eq(API_ID), eq("Query"), eq("getMessages"), captor.capture()); + assertFalse(updateRequest(captor).containsKey("dataSourceName")); + } + + @Test + void resolverUpdateClearsTheDataSourceOfAResolverThatBecomesPipeline() throws Exception { + Resolver resolver = new Resolver(); + resolver.setResolverArn("arn:resolver"); + when(appSync.updateResolver(eq(API_ID), eq("Query"), eq("getMessages"), any())).thenReturn(resolver); + StackResource r = resource("AWS::AppSync::Resolver", "GraphQlResolver"); + r.getAttributes().put("ApiId", API_ID); + r.getAttributes().put("TypeName", "Query"); + r.getAttributes().put("FieldName", "getMessages"); + String head = "\"ApiId\":\"" + API_ID + "\",\"TypeName\":\"Query\",\"FieldName\":\"getMessages\""; + + provisioner.provision(r, mapper.readTree("{" + head + ",\"Kind\":\"PIPELINE\"}"), + updateCtx("arn:resolver", "{" + head + ",\"DataSourceName\":\"accountDB\"}")); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateResolver(eq(API_ID), eq("Query"), eq("getMessages"), captor.capture()); + Map req = updateRequest(captor); + assertTrue(req.containsKey("dataSourceName")); + assertNull(req.get("dataSourceName")); + } + + @Test + void resolverUpdateLeavesAPropertyTheStackNeverDeclaredAlone() throws Exception { + Resolver resolver = new Resolver(); + resolver.setResolverArn("arn:resolver"); + when(appSync.updateResolver(eq(API_ID), eq("Query"), eq("getMessages"), any())).thenReturn(resolver); + StackResource r = resource("AWS::AppSync::Resolver", "GraphQlResolver"); + r.getAttributes().put("ApiId", API_ID); + r.getAttributes().put("TypeName", "Query"); + r.getAttributes().put("FieldName", "getMessages"); + String declared = "{\"ApiId\":\"" + API_ID + "\",\"TypeName\":\"Query\"," + + "\"FieldName\":\"getMessages\",\"DataSourceName\":\"accountDB\"}"; + + provisioner.provision(r, mapper.readTree(declared), updateCtx("arn:resolver", declared)); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateResolver(eq(API_ID), eq("Query"), eq("getMessages"), captor.capture()); + assertEquals(Set.of("typeName", "fieldName", "dataSourceName"), updateRequest(captor).keySet()); + } + + @Test + void apiKeyUpdateClearsADroppedDescriptionButKeepsItsExpiry() throws Exception { + ApiKey key = new ApiKey(); + key.setId("da2-key"); + when(appSync.updateApiKey(eq(API_ID), eq("da2-key"), any())).thenReturn(key); + StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey"); + r.getAttributes().put("ApiId", API_ID); + + provisioner.provision(r, mapper.readTree("{\"ApiId\":\"" + API_ID + "\"}"), + updateCtx("da2-key", "{\"ApiId\":\"" + API_ID + "\",\"Description\":\"old\"," + + "\"Expires\":1900000000}")); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateApiKey(eq(API_ID), eq("da2-key"), captor.capture()); + Map req = updateRequest(captor); + assertTrue(req.containsKey("description")); + assertNull(req.get("description")); + // The service parses a given expiry as a date and refuses null, so a dropped one keeps its value. + assertFalse(req.containsKey("expires")); + } + + @Test + void apiKeyUpdateLeavesAPropertyTheStackNeverDeclaredAlone() throws Exception { + ApiKey key = new ApiKey(); + key.setId("da2-key"); + when(appSync.updateApiKey(eq(API_ID), eq("da2-key"), any())).thenReturn(key); + StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey"); + r.getAttributes().put("ApiId", API_ID); + String declared = "{\"ApiId\":\"" + API_ID + "\"}"; + + provisioner.provision(r, mapper.readTree(declared), updateCtx("da2-key", declared)); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync).updateApiKey(eq(API_ID), eq("da2-key"), captor.capture()); + assertTrue(updateRequest(captor).isEmpty()); + } + // ── Deletes ────────────────────────────────────────────────────────────── @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java index afb366bedc..4f23580a11 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -69,6 +70,29 @@ class ProvisionContextTest { assertFalse(ctx.previouslyDeclared("Absent")); } + @Test + void droppedPropertiesAreTheOnesThePreviousTemplateDeclaredAndThisOneLacks() { + ProvisionContext ctx = contextWithPriorProperties(""" + {"Kept": "a", "Dropped": "b", "DroppedIf": {"Fn::If": ["C", "x", "y"]}, "ExplicitNull": null} + """); + + assertEquals(Set.of("Dropped", "DroppedIf"), + ctx.droppedProperties(props("{\"Kept\": \"a\", \"NewOne\": \"c\"}")), + "a property the stack never declared, or declared as null, is not dropped"); + assertEquals(Set.of("Kept", "Dropped", "DroppedIf"), ctx.droppedProperties(props("{}"))); + assertEquals(Set.of("Kept", "Dropped", "DroppedIf"), ctx.droppedProperties(null)); + } + + @Test + void nothingIsDroppedOnACreateOrWithoutAPreviousTemplate() { + ProvisionContext create = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", null, + event -> { }, props("{\"Declared\": \"value\"}")); + + assertTrue(create.droppedProperties(props("{}")).isEmpty()); + assertTrue(contextWithPriorProperties(null).droppedProperties(props("{}")).isEmpty()); + assertTrue(context("prior-id").droppedProperties(props("{}")).isEmpty()); + } + /** A resource the previous deployment never provisioned, such as one its Condition kept out, declared nothing. */ @Test void aResourceWithoutAPriorPhysicalIdDeclaredNothing() {