From 0c3af7dc4bcc72f941f733c543d4e6b390e55ed2 Mon Sep 17 00:00:00 2001 From: Oleksandr Nikolaichuk <57410473+Sekator778@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:25:04 +0300 Subject: [PATCH] fix(cloudformation): roll back an AppSync update when a later resource fails (#7186) A failed stack update left AppSync entities changed or cleared by the update: the provisioner had no rollbackUpdate, so the stack ended in UPDATE_ROLLBACK_FAILED with "Rollback is not implemented". Before an in-place update of a GraphQL API, data source, function, resolver or API key, the provisioner records the members the update can change or clear. The service applies an update member by containsKey, so replaying them puts back both the changed and the cleared values. An update that fails part way undoes itself through CfnRollback.guarded, and a failed undo keeps the snapshot for ContinueUpdateRollback. GraphQLSchema and a replaced AppSync resource are not covered. tagResource, untagResource and putEnvironmentVariables change the stored API in place while updateGraphqlApi saves a copy, so a copy could overwrite a tag or variable written in between. Every method that writes a store now holds the service monitor, as startSchemaCreation does, and startSchemaCreation checks the API under it too. refreshGraphqlApiUris refreshes the stored API under the monitor instead of putting the instance it read earlier. --- docs/services/cloudformation.md | 8 +- .../services/appsync/AppSyncService.java | 131 ++++-- .../provisioners/AppSyncCfnProvisioner.java | 257 +++++++++- .../provisioners/CfnRollback.java | 10 + .../appsync/AppSyncServiceFixture.java | 97 ++++ .../services/appsync/AppSyncServiceTest.java | 307 +++++++++--- .../AppSyncCfnIntegrationTest.java | 184 ++++++++ .../AppSyncCfnProvisionerTest.java | 437 ++++++++++++++++++ 8 files changed, 1292 insertions(+), 139 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceFixture.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 9e3dd628e1..d139df9775 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -734,7 +734,13 @@ their create default (`XrayEnabled`, `AdditionalAuthenticationProviders`, a func 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`. +`Visibility`, and a UNIT resolver's `DataSourceName`. When a later resource fails the update, the +rollback puts each AppSync API, data source, function, resolver and API key that the update changed in +place back to the members it had, including the ones the update cleared. An API that had no +`AdditionalAuthenticationProviders` gets an empty list back, and an API key's `Expires` is sent again +only when the update changed it, so one now less than a day away fails the rollback and the key stays as the update left it. A `GraphQLSchema` +and a replaced AppSync resource (a changed `ApiId`, name, `TypeName` or `FieldName`) are not rolled back +and end the stack in `UPDATE_ROLLBACK_FAILED`. On the EC2 networking types (`Subnet`, `InternetGateway`, `RouteTable`, `NatGateway`, `EIP`, `PrefixList`), a `Tags` property the previous template declared and the new one drops is cleared on `UpdateStack`, and diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java index 4400309769..d1586e5da9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncService.java @@ -30,6 +30,11 @@ import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; +/** + * Writers hold the service monitor across each read, change and save, as startSchemaCreation + * does, so two writers never lose each other's changes. Readers do not take it, and the schema + * worker's own writes to the schema and schema-status stores are outside it. + */ @ApplicationScoped public class AppSyncService { private static final Logger LOG = Logger.getLogger(AppSyncService.class); @@ -97,7 +102,7 @@ public class AppSyncService { // ──────────────────────────── GraphQL API ──────────────────────────── - public GraphqlApi createGraphqlApi(Map request, String region) { + public synchronized GraphqlApi createGraphqlApi(Map request, String region) { assertNoSchemaBusyAnywhere(); String name = (String) request.get("name"); if (name == null || name.isBlank()) { @@ -168,15 +173,17 @@ public class AppSyncService { } public Page listGraphqlApis(Integer maxResults, String nextToken) { - List apis = apiStore.scan(k -> true); - apis.forEach(this::refreshGraphqlApiUris); + List apis = new ArrayList<>(); + for (GraphqlApi stored : apiStore.scan(k -> true)) { + apis.add(refreshGraphqlApiUris(stored)); + } return paginate(apis, nextToken, maxResults); } @SuppressWarnings("unchecked") - public GraphqlApi updateGraphqlApi(String apiId, Map request, String region) { + public synchronized GraphqlApi updateGraphqlApi(String apiId, Map request, String region) { assertSchemaNotBusy(apiId); - GraphqlApi existing = getGraphqlApi(apiId); + GraphqlApi existing = copyOf(getGraphqlApi(apiId), GraphqlApi.class); if (request.containsKey("name")) existing.setName((String) request.get("name")); if (request.containsKey("authenticationType")) existing.setAuthenticationType(parseEnum(AuthenticationType.class, request.get("authenticationType"))); if (request.containsKey("xrayEnabled")) { @@ -223,7 +230,7 @@ public class AppSyncService { return existing; } - public void deleteGraphqlApi(String apiId) { + public synchronized void deleteGraphqlApi(String apiId) { assertSchemaNotBusy(apiId); getGraphqlApi(apiId); apiStore.delete(apiId); @@ -244,10 +251,11 @@ public class AppSyncService { // ──────────────────────────── Schema ──────────────────────────── public SchemaCreationStatus startSchemaCreation(String apiId, String definition) { - getGraphqlApi(apiId); - String accountId = currentAccountId(); SchemaCreationStatus status; + String accountId; synchronized (this) { + getGraphqlApi(apiId); + accountId = currentAccountId(); assertSchemaNotBusy(apiId); status = new SchemaCreationStatus(); status.setStatus(SchemaCreationStatusType.PROCESSING); @@ -312,7 +320,7 @@ public class AppSyncService { // ──────────────────────────── Data Sources ──────────────────────────── - public DataSource createDataSource(String apiId, Map request, String region) { + public synchronized DataSource createDataSource(String apiId, Map request, String region) { assertSchemaNotBusy(apiId); getGraphqlApi(apiId); String name = (String) request.get("name"); @@ -355,9 +363,9 @@ public class AppSyncService { } @SuppressWarnings("unchecked") - public DataSource updateDataSource(String apiId, String dataSourceName, Map request) { + public synchronized DataSource updateDataSource(String apiId, String dataSourceName, Map request) { assertSchemaNotBusy(apiId); - DataSource existing = getDataSource(apiId, dataSourceName); + DataSource existing = copyOf(getDataSource(apiId, dataSourceName), DataSource.class); if (request.containsKey("description")) existing.setDescription((String) request.get("description")); if (request.containsKey("type")) existing.setType(parseEnum(DataSourceType.class, request.get("type"))); if (request.containsKey("serviceRoleArn")) existing.setServiceRoleArn((String) request.get("serviceRoleArn")); @@ -372,7 +380,7 @@ public class AppSyncService { return existing; } - public void deleteDataSource(String apiId, String dataSourceName) { + public synchronized void deleteDataSource(String apiId, String dataSourceName) { assertSchemaNotBusy(apiId); getDataSource(apiId, dataSourceName); dataSourceStore.delete(apiKey(apiId, dataSourceName)); @@ -396,7 +404,7 @@ public class AppSyncService { return rt; } - public Resolver createResolver(String apiId, Map request, String region) { + public synchronized Resolver createResolver(String apiId, Map request, String region) { assertSchemaNotBusy(apiId); getGraphqlApi(apiId); String fieldName = (String) request.get("fieldName"); @@ -476,9 +484,9 @@ public class AppSyncService { } @SuppressWarnings("unchecked") - public Resolver updateResolver(String apiId, String typeName, String fieldName, Map request) { + public synchronized Resolver updateResolver(String apiId, String typeName, String fieldName, Map request) { assertSchemaNotBusy(apiId); - Resolver existing = getResolver(apiId, typeName, fieldName); + Resolver existing = copyOf(getResolver(apiId, typeName, fieldName), Resolver.class); if (request.containsKey("dataSourceName")) existing.setDataSourceName((String) request.get("dataSourceName")); if (request.containsKey("functionId")) existing.setFunctionId((String) request.get("functionId")); if (request.containsKey("requestMappingTemplate")) existing.setRequestMappingTemplate((String) request.get("requestMappingTemplate")); @@ -495,7 +503,7 @@ public class AppSyncService { return existing; } - public void deleteResolver(String apiId, String typeName, String fieldName) { + public synchronized void deleteResolver(String apiId, String typeName, String fieldName) { assertSchemaNotBusy(apiId); getResolver(apiId, typeName, fieldName); resolverStore.delete(resolverKey(apiId, typeName, fieldName)); @@ -503,7 +511,7 @@ public class AppSyncService { // ──────────────────────────── Functions ──────────────────────────── - public FunctionConfiguration createFunction(String apiId, Map request, String region) { + public synchronized FunctionConfiguration createFunction(String apiId, Map request, String region) { assertSchemaNotBusy(apiId); getGraphqlApi(apiId); String name = (String) request.get("name"); @@ -541,9 +549,9 @@ public class AppSyncService { return paginate(functionStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults); } - public FunctionConfiguration updateFunction(String apiId, String functionId, Map request) { + public synchronized FunctionConfiguration updateFunction(String apiId, String functionId, Map request) { assertSchemaNotBusy(apiId); - FunctionConfiguration existing = getFunction(apiId, functionId); + FunctionConfiguration existing = copyOf(getFunction(apiId, functionId), FunctionConfiguration.class); // UpdateFunction takes a new name on AWS, and CloudFormation drives FunctionConfiguration // renames through it. Leaving the name alone let a stack complete while GetFunction still // reported the old one. @@ -560,7 +568,7 @@ public class AppSyncService { return existing; } - public void deleteFunction(String apiId, String functionId) { + public synchronized void deleteFunction(String apiId, String functionId) { assertSchemaNotBusy(apiId); getFunction(apiId, functionId); functionStore.delete(apiKey(apiId, functionId)); @@ -568,7 +576,7 @@ public class AppSyncService { // ──────────────────────────── Types ──────────────────────────── - public AppSyncType createType(String apiId, Map request) { + public synchronized AppSyncType createType(String apiId, Map request) { assertSchemaNotBusy(apiId); getGraphqlApi(apiId); String name = (String) request.get("name"); @@ -605,7 +613,7 @@ public class AppSyncService { return paginate(typeStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults); } - public AppSyncType updateType(String apiId, String typeName, Map request) { + public synchronized AppSyncType updateType(String apiId, String typeName, Map request) { assertSchemaNotBusy(apiId); AppSyncType existing = getType(apiId, typeName); if (request.containsKey("definition")) existing.setDefinition((String) request.get("definition")); @@ -615,7 +623,7 @@ public class AppSyncService { return existing; } - public void deleteType(String apiId, String typeName) { + public synchronized void deleteType(String apiId, String typeName) { assertSchemaNotBusy(apiId); getType(apiId, typeName); typeStore.delete(apiKey(apiId, typeName)); @@ -623,7 +631,7 @@ public class AppSyncService { // ──────────────────────────── API Keys ──────────────────────────── - public ApiKey createApiKey(String apiId, Map request) { + public synchronized ApiKey createApiKey(String apiId, Map request) { getGraphqlApi(apiId); long existingCount = apiKeyStore.scan(k -> k.startsWith(apiId + "::")).size(); if (existingCount >= 2) { @@ -671,19 +679,21 @@ public class AppSyncService { return Optional.empty(); } - public ApiKey updateApiKey(String apiId, String keyId, Map request) { - ApiKey existing = getApiKey(apiId, keyId); - if (request.containsKey("description")) { - existing.setDescription((String) request.get("description")); - } + public synchronized ApiKey updateApiKey(String apiId, String keyId, Map request) { + ApiKey existing = copyOf(getApiKey(apiId, keyId), ApiKey.class); + // Applied to a copy and stored last, so a refused expiry or a description of the wrong + // type leaves the stored key as it was. if (request.containsKey("expires")) { applyApiKeyExpires(existing, parseExpires(request.get("expires"))); } + if (request.containsKey("description")) { + existing.setDescription((String) request.get("description")); + } apiKeyStore.put(apiKey(apiId, keyId), existing); return existing; } - public void deleteApiKey(String apiId, String keyId) { + public synchronized void deleteApiKey(String apiId, String keyId) { getApiKey(apiId, keyId); apiKeyStore.delete(apiKey(apiId, keyId)); } @@ -695,14 +705,14 @@ public class AppSyncService { return getGraphqlApi(apiId).getTags(); } - public void tagResource(String resourceArn, Map tags) { + public synchronized void tagResource(String resourceArn, Map tags) { String apiId = extractApiIdFromArn(resourceArn); GraphqlApi api = getGraphqlApi(apiId); api.getTags().putAll(tags); apiStore.put(apiId, api); } - public void untagResource(String resourceArn, List tagKeys) { + public synchronized void untagResource(String resourceArn, List tagKeys) { String apiId = extractApiIdFromArn(resourceArn); GraphqlApi api = getGraphqlApi(apiId); tagKeys.forEach(api.getTags()::remove); @@ -717,7 +727,7 @@ public class AppSyncService { return envVars != null ? envVars : Map.of(); } - public Map putEnvironmentVariables(String apiId, Map environmentVariables) { + public synchronized Map putEnvironmentVariables(String apiId, Map environmentVariables) { assertSchemaNotBusy(apiId); GraphqlApi api = getGraphqlApi(apiId); api.setEnvironmentVariables(new HashMap<>(environmentVariables)); @@ -727,7 +737,7 @@ public class AppSyncService { // ──────────────────────────── Domain Names ──────────────────────────── - public DomainName createDomainName(Map request) { + public synchronized DomainName createDomainName(Map request) { String domainName = (String) request.get("domainName"); if (domainName == null || domainName.isBlank()) { throw new AwsException("BadRequestException", "A domain name is required", 400); @@ -777,7 +787,7 @@ public class AppSyncService { return paginate(domainStore.scan(k -> true), nextToken, maxResults); } - public DomainName updateDomainName(String domainName, Map request) { + public synchronized DomainName updateDomainName(String domainName, Map request) { DomainName existing = getDomainName(domainName); associationStore.get(domainName).ifPresent(apiId -> assertSchemaNotBusy(apiId)); if (request.containsKey("description")) existing.setDescription((String) request.get("description")); @@ -785,14 +795,14 @@ public class AppSyncService { return existing; } - public void deleteDomainName(String domainName) { + public synchronized void deleteDomainName(String domainName) { getDomainName(domainName); associationStore.get(domainName).ifPresent(apiId -> assertSchemaNotBusy(apiId)); associationStore.delete(domainName); domainStore.delete(domainName); } - public ApiAssociation associateApi(String domainName, String apiId) { + public synchronized ApiAssociation associateApi(String domainName, String apiId) { getDomainName(domainName); getGraphqlApi(apiId); if (associationStore.get(domainName).isPresent()) { @@ -820,7 +830,7 @@ public class AppSyncService { return assoc; } - public void disassociateApi(String domainName) { + public synchronized void disassociateApi(String domainName) { getDomainName(domainName); associationStore.get(domainName).ifPresent(apiId -> assertSchemaNotBusy(apiId)); associationStore.delete(domainName); @@ -828,7 +838,7 @@ public class AppSyncService { // ──────────────────────────── Channel Namespaces ──────────────────────────── - public ChannelNamespace createChannelNamespace(String apiId, Map request) { + public synchronized ChannelNamespace createChannelNamespace(String apiId, Map request) { assertSchemaNotBusy(apiId); GraphqlApi api = getGraphqlApi(apiId); String name = (String) request.get("name"); @@ -859,7 +869,7 @@ public class AppSyncService { "Channel namespace not found: " + name, 404)); } - public ChannelNamespace updateChannelNamespace(String apiId, String name, Map request) { + public synchronized ChannelNamespace updateChannelNamespace(String apiId, String name, Map request) { assertSchemaNotBusy(apiId); ChannelNamespace existing = getChannelNamespace(apiId, name); if (request.containsKey("description")) existing.setDescription((String) request.get("description")); @@ -869,7 +879,7 @@ public class AppSyncService { return existing; } - public void deleteChannelNamespace(String apiId, String name) { + public synchronized void deleteChannelNamespace(String apiId, String name) { assertSchemaNotBusy(apiId); getChannelNamespace(apiId, name); channelNamespaceStore.delete(apiKey(apiId, name)); @@ -881,7 +891,7 @@ public class AppSyncService { // ──────────────────────────── Merged API Associations ───────────────── - public SourceApiAssociation createMergedApiAssociation(String sourceApiIdentifier, Map request, String region) { + public synchronized SourceApiAssociation createMergedApiAssociation(String sourceApiIdentifier, Map request, String region) { getGraphqlApi(sourceApiIdentifier); String mergedApiIdentifier = (String) request.getOrDefault("mergedApiIdentifier", request.get("mergedApiId")); if (mergedApiIdentifier == null || mergedApiIdentifier.isBlank()) { @@ -909,7 +919,7 @@ public class AppSyncService { return assoc; } - public SourceApiAssociation createSourceApiAssociation(String mergedApiIdentifier, Map request, String region) { + public synchronized SourceApiAssociation createSourceApiAssociation(String mergedApiIdentifier, Map request, String region) { getGraphqlApi(mergedApiIdentifier); String sourceApiId = (String) request.getOrDefault("sourceApiId", request.get("sourceApiIdentifier")); if (sourceApiId == null || sourceApiId.isBlank()) { @@ -948,7 +958,7 @@ public class AppSyncService { return assoc; } - public SourceApiAssociation updateSourceApiAssociation(String mergedApiIdentifier, String associationId, + public synchronized SourceApiAssociation updateSourceApiAssociation(String mergedApiIdentifier, String associationId, Map request) { assertSchemaNotBusy(mergedApiIdentifier); SourceApiAssociation assoc = getSourceApiAssociation(mergedApiIdentifier, associationId); @@ -979,7 +989,7 @@ public class AppSyncService { return paginate(summaries, nextToken, maxResults); } - public void deleteSourceApiAssociation(String mergedApiIdentifier, String associationId) { + public synchronized void deleteSourceApiAssociation(String mergedApiIdentifier, String associationId) { assertSchemaNotBusy(mergedApiIdentifier); getSourceApiAssociation(mergedApiIdentifier, associationId); mergedApiAssociationStore.delete(associationId); @@ -997,7 +1007,7 @@ public class AppSyncService { } } - public SourceApiAssociation deleteMergedApiAssociation(String sourceApiIdentifier, String associationId) { + public synchronized SourceApiAssociation deleteMergedApiAssociation(String sourceApiIdentifier, String associationId) { assertSchemaNotBusy(sourceApiIdentifier); SourceApiAssociation assoc = mergedApiAssociationStore.get(associationId) .orElseThrow(() -> new AwsException("NotFoundException", @@ -1105,6 +1115,15 @@ public class AppSyncService { }; } + /** + * An update is applied to a copy and stored only once every member has been read and checked, + * so a request the service refuses leaves the stored entity untouched. The stores hand out + * their own instances, which a half-applied update would otherwise have changed in place. + */ + private T copyOf(T entity, Class type) { + return objectMapper.convertValue(entity, type); + } + private long parseExpires(Object expiresValue) { if (expiresValue instanceof Long l) { return l; @@ -1246,11 +1265,23 @@ public class AppSyncService { private GraphqlApi refreshGraphqlApiUris(GraphqlApi api) { Map expectedUris = graphqlApiUris(api.getApiId()); - if (!expectedUris.equals(api.getUris())) { - api.setUris(expectedUris); - apiStore.put(api.getApiId(), api); + if (expectedUris.equals(api.getUris())) { + return api; + } + synchronized (this) { + // Refresh what is stored now, never the instance read before the lock: a concurrent + // update may have saved a newer one in between. + GraphqlApi current = apiStore.get(api.getApiId()).orElse(null); + if (current == null) { + api.setUris(expectedUris); + return api; + } + if (!expectedUris.equals(current.getUris())) { + current.setUris(expectedUris); + apiStore.put(current.getApiId(), current); + } + return current; } - return api; } private Integer castInt(Object value) { 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 953672acba..5d9f7ce5af 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 @@ -1,6 +1,9 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.appsync.AppSyncService; @@ -24,8 +27,11 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; +import java.util.function.Supplier; /** * Provisions the AppSync resource types a GraphQL API is deployed from: the API itself, its schema, @@ -57,11 +63,20 @@ import java.util.function.Consumer; *

Inline definitions only. {@code DefinitionS3Location} and {@code CodeS3Location} are * refused with a clear message rather than silently producing an API with an empty schema or a * resolver with no code. Serverless Framework and the AppSync plugins inline both. + * + *

An in-place update is undone from a snapshot. Before the update call of an API, data + * source, function, resolver or API key, the members the update can change or clear are read back + * from the service and kept on the resource ({@link CfnRollback#APPSYNC_UPDATE_SNAPSHOT_ATTR}). + * The service applies an update member by {@code containsKey}, so replaying every recorded member, + * an old value or an explicit null, puts back what the update changed and what it cleared. A + * stack update that fails afterwards, or the update call itself failing part way, restores it. */ @ApplicationScoped public class AppSyncCfnProvisioner implements CfnResourceProvisioner { private static final Logger LOG = Logger.getLogger(AppSyncCfnProvisioner.class); + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final TypeReference> OBJECT_MAP = new TypeReference<>() { }; private static final String GRAPHQL_API = "AWS::AppSync::GraphQLApi"; private static final String GRAPHQL_SCHEMA = "AWS::AppSync::GraphQLSchema"; @@ -115,6 +130,29 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { FUNCTION_CONFIGURATION, Map.of("FunctionVersion", "2018-05-29"), RESOLVER, Map.of("Kind", "UNIT")); + /** + * The members an update of each type can change or clear, which a snapshot records and a + * restore replays. A GraphQL API's {@code apiType} and {@code visibility} are here because a + * template that changes them reaches the update request, which applies both. An API key's + * {@code expires} joins when the update sends it. + */ + private static final Map> ROLLBACK_MEMBERS = Map.of( + GRAPHQL_API, List.of("name", "authenticationType", "apiType", "visibility", "xrayEnabled", + "logConfig", "additionalAuthenticationProviders", "tags", "owner", "ownerContact", + "introspectionConfig", "queryDepthLimit", "resolverCountLimit", + "enhancedMetricsConfig", "lambdaAuthorizerConfig", "openIDConnectConfig", + "userPoolConfig", "dns", "wafWebAclArn", "mergedApiExecutionRoleArn"), + DATA_SOURCE, List.of("description", "type", "serviceRoleArn", "dynamodbConfig", + "lambdaConfig", "httpConfig", "eventBridgeConfig", "relationalDatabaseConfig", + "openSearchServiceConfig", "amazonBedrockRuntimeConfig"), + FUNCTION_CONFIGURATION, List.of("name", "description", "dataSourceName", + "requestMappingTemplate", "responseMappingTemplate", "functionVersion", "code", + "runtime", "maxBatchSize"), + RESOLVER, List.of("dataSourceName", "functionId", "requestMappingTemplate", + "responseMappingTemplate", "kind", "code", "runtime", "cachingConfig", + "maxBatchSize", "metricsConfig", "pipelineConfig", "syncConfig"), + API_KEY, List.of("description")); + /** * 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 @@ -137,6 +175,8 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { @Override public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale. + r.getAttributes().remove(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR); switch (r.getResourceType()) { case GRAPHQL_API -> provisionGraphqlApi(r, props, ctx); case GRAPHQL_SCHEMA -> provisionSchema(r, props, ctx); @@ -173,19 +213,29 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { clearDropped(req, props, ctx, GRAPHQL_API); } - GraphqlApi api = ctx.isUpdate() - ? appSyncService.updateGraphqlApi(ctx.priorPhysicalId(), req, ctx.region()) - : appSyncService.createGraphqlApi(req, ctx.region()); - - Map resolvedEnvironment = stringMap(environmentVariables); - if (resolvedEnvironment == null && ctx.isUpdate()) { - // The property was dropped from the template. The call replaces the whole set, so an - // empty map is what clears it; skipping the call left the old variables readable by - // every resolver. - resolvedEnvironment = Map.of(); - } - if (resolvedEnvironment != null) { - appSyncService.putEnvironmentVariables(api.getApiId(), resolvedEnvironment); + Map templateEnvironment = stringMap(environmentVariables); + // The property was dropped from the template. The call replaces the whole set, so an + // empty map is what clears it; skipping the call left the old variables readable by + // every resolver. + Map resolvedEnvironment = templateEnvironment == null && ctx.isUpdate() + ? Map.of() : templateEnvironment; + GraphqlApi api; + if (ctx.isUpdate()) { + String priorApiId = ctx.priorPhysicalId(); + snapshotBeforeUpdate(r, ctx, appSyncService.getGraphqlApi(priorApiId), + Map.of("apiId", priorApiId), req, appSyncService.getEnvironmentVariables(priorApiId)); + api = updateInPlace(r, ctx, () -> { + GraphqlApi updated = appSyncService.updateGraphqlApi(priorApiId, req, ctx.region()); + if (resolvedEnvironment != null) { + appSyncService.putEnvironmentVariables(updated.getApiId(), resolvedEnvironment); + } + return updated; + }); + } else { + api = appSyncService.createGraphqlApi(req, ctx.region()); + if (resolvedEnvironment != null) { + appSyncService.putEnvironmentVariables(api.getApiId(), resolvedEnvironment); + } } r.setPhysicalId(api.getApiId()); @@ -284,12 +334,16 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { } boolean update = reusesEntity(r, ctx, apiId) && name.equals(attribute(r, "Name")); + DataSource ds; if (update) { clearDropped(req, props, ctx, DATA_SOURCE); + String dataSourceName = name; + snapshotBeforeUpdate(r, ctx, appSyncService.getDataSource(apiId, dataSourceName), + Map.of("apiId", apiId, "name", dataSourceName), req, null); + ds = updateInPlace(r, ctx, () -> appSyncService.updateDataSource(apiId, dataSourceName, req)); + } else { + ds = appSyncService.createDataSource(apiId, req, ctx.region()); } - DataSource ds = update - ? appSyncService.updateDataSource(apiId, name, req) - : appSyncService.createDataSource(apiId, req, ctx.region()); r.setPhysicalId(ds.getDataSourceArn()); r.getAttributes().put("DataSourceArn", ds.getDataSourceArn()); @@ -310,12 +364,15 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { String priorFunctionId = attribute(r, "FunctionId"); boolean update = reusesEntity(r, ctx, apiId) && !blank(priorFunctionId); + FunctionConfiguration fn; if (update) { clearDropped(req, props, ctx, FUNCTION_CONFIGURATION); + snapshotBeforeUpdate(r, ctx, appSyncService.getFunction(apiId, priorFunctionId), + Map.of("apiId", apiId, "functionId", priorFunctionId), req, null); + fn = updateInPlace(r, ctx, () -> appSyncService.updateFunction(apiId, priorFunctionId, req)); + } else { + fn = appSyncService.createFunction(apiId, req, ctx.region()); } - FunctionConfiguration fn = update - ? appSyncService.updateFunction(apiId, priorFunctionId, req) - : appSyncService.createFunction(apiId, req, ctx.region()); r.setPhysicalId(fn.getFunctionArn()); r.getAttributes().put("FunctionArn", fn.getFunctionArn()); @@ -343,6 +400,7 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { boolean sameField = typeName.equals(attribute(r, "TypeName")) && fieldName.equals(attribute(r, "FieldName")); boolean update = reusesEntity(r, ctx, apiId) && sameField; + Resolver resolver; if (update) { clearDropped(req, props, ctx, RESOLVER); // A UNIT resolver needs its data source (createResolver refuses none): clear it only on a pipeline. @@ -350,10 +408,13 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { && isPipeline(req, apiId, typeName, fieldName)) { req.put("dataSourceName", null); } + snapshotBeforeUpdate(r, ctx, appSyncService.getResolver(apiId, typeName, fieldName), + Map.of("apiId", apiId, "typeName", typeName, "fieldName", fieldName), req, null); + resolver = updateInPlace(r, ctx, + () -> appSyncService.updateResolver(apiId, typeName, fieldName, req)); + } else { + resolver = appSyncService.createResolver(apiId, req, ctx.region()); } - Resolver resolver = update - ? appSyncService.updateResolver(apiId, typeName, fieldName, req) - : appSyncService.createResolver(apiId, req, ctx.region()); r.setPhysicalId(resolver.getResolverArn()); r.getAttributes().put("ResolverArn", resolver.getResolverArn()); @@ -369,12 +430,16 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { String apiId = requiredApiId(req, API_KEY); boolean update = reusesEntity(r, ctx, apiId); + ApiKey key; if (update) { clearDropped(req, props, ctx, API_KEY); + String priorKeyId = ctx.priorPhysicalId(); + snapshotBeforeUpdate(r, ctx, appSyncService.getApiKey(apiId, priorKeyId), + Map.of("apiId", apiId, "keyId", priorKeyId), req, null); + key = updateInPlace(r, ctx, () -> appSyncService.updateApiKey(apiId, priorKeyId, req)); + } else { + key = appSyncService.createApiKey(apiId, req); } - ApiKey key = update - ? appSyncService.updateApiKey(apiId, ctx.priorPhysicalId(), req) - : appSyncService.createApiKey(apiId, req); r.setPhysicalId(key.getId()); // On AWS the key id and the key value are the same string (the da2-… secret), and both @@ -386,6 +451,148 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { r.getAttributes().put("ApiId", apiId); } + // ── Rollback ───────────────────────────────────────────────────────────── + + /** + * Puts an entity this update changed in place back to the members it had before, and answers + * false for one it did not: a resource the failed update created is deleted by the engine, and + * a replacement leaves no snapshot. The snapshot is spent only once the restore succeeded, so + * a restore that throws keeps it for the next attempt. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (!resource.getAttributes().containsKey(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR)) { + return false; + } + restoreSnapshot(resource); + return true; + } + + /** + * Keeps the snapshot of an in-place update whose own undo did not complete. The engine restores + * the previous resource and reports the rollback failure once; with the snapshot of the state + * the update started from, a ContinueUpdateRollback restores that state. + */ + @Override + public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { + String snapshot = attempted.getAttributes().get(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR); + if (snapshot != null && attempted.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)) { + previous.getAttributes().put(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR, snapshot); + } + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + resource.getAttributes().remove(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR); + return UpdateCleanupResult.notApplicable(); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR); + } + + /** + * Runs an in-place update so that a failure inside it, the call or a step after it, puts the + * entity back from the snapshot before the failure propagates. The engine discards the + * attempted resource, snapshot included, when the resource itself fails. + */ + private T updateInPlace(StackResource r, ProvisionContext ctx, Supplier update) { + AtomicReference updated = new AtomicReference<>(); + CfnRollback.guarded(r, ctx, false, () -> { }, () -> restoreSnapshot(r), + () -> updated.set(update.get())); + return updated.get(); + } + + /** + * Records what the entity looks like now, before the update call about to change it. The + * service's getters throw NotFound for an entity that is gone, so the null guard only covers a + * service that answers with nothing, as the mocked one in the unit tests does; the update then + * runs without a snapshot. A member the entity does not carry is recorded as null, which the + * restore sends as a clear. {@code environment} is a GraphQL API's variables, which have a + * call of their own. + */ + private void snapshotBeforeUpdate(StackResource r, ProvisionContext ctx, Object current, + Map identity, Map request, + Map environment) { + if (current == null) { + return; + } + Map entity = MAPPER.convertValue(current, OBJECT_MAP); + Map members = new LinkedHashMap<>(); + for (String member : ROLLBACK_MEMBERS.get(r.getResourceType())) { + members.put(member, entity.get(member)); + } + if (API_KEY.equals(r.getResourceType()) && request.containsKey("expires")) { + members.put("expires", entity.get("expires")); + } + Map snapshot = new LinkedHashMap<>(); + snapshot.put("region", ctx.region()); + snapshot.putAll(identity); + snapshot.put("members", members); + if (environment != null) { + snapshot.put("environmentVariables", environment); + } + try { + r.getAttributes().put(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR, MAPPER.writeValueAsString(snapshot)); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Could not record the AppSync update snapshot for " + + r.getLogicalId(), e); + } + } + + /** + * Replays the snapshot through the update call that changed the entity, if the resource carries + * one, and spends it. A GraphQL API's {@code xrayEnabled}, {@code additionalAuthenticationProviders} + * and tags are not cleared by a null, so an API that had none gets {@code false}, an empty list + * and an empty map back. + */ + @SuppressWarnings("unchecked") + private void restoreSnapshot(StackResource r) { + JsonNode node = CfnRollback.updateSnapshot(r, CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR); + if (node == null) { + return; + } + Map snapshot = MAPPER.convertValue(node, OBJECT_MAP); + Map members = (Map) snapshot.get("members"); + String apiId = str(snapshot.get("apiId")); + switch (r.getResourceType()) { + case GRAPHQL_API -> { + members.computeIfAbsent("xrayEnabled", name -> false); + members.computeIfAbsent("additionalAuthenticationProviders", name -> List.of()); + members.computeIfAbsent("tags", name -> Map.of()); + appSyncService.updateGraphqlApi(apiId, members, str(snapshot.get("region"))); + appSyncService.putEnvironmentVariables(apiId, stringMap(snapshot.get("environmentVariables"))); + } + case DATA_SOURCE -> appSyncService.updateDataSource(apiId, str(snapshot.get("name")), members); + case FUNCTION_CONFIGURATION -> { + appSyncService.updateFunction(apiId, str(snapshot.get("functionId")), members); + r.getAttributes().put("Name", str(members.get("name"))); + if (blank(str(members.get("dataSourceName")))) { + r.getAttributes().remove("DataSourceName"); + } else { + r.getAttributes().put("DataSourceName", str(members.get("dataSourceName"))); + } + } + case RESOLVER -> appSyncService.updateResolver(apiId, str(snapshot.get("typeName")), + str(snapshot.get("fieldName")), members); + case API_KEY -> { + String keyId = str(snapshot.get("keyId")); + // The service refuses an expiry inside the next day, so one that has not moved is + // not sent again. + Object expires = members.get("expires"); + if (expires instanceof Number prior + && Objects.equals(prior.longValue(), appSyncService.getApiKey(apiId, keyId).getExpires())) { + members.remove("expires"); + } + appSyncService.updateApiKey(apiId, keyId, members); + } + default -> throw new IllegalStateException( + "AppSyncCfnProvisioner cannot restore " + r.getResourceType()); + } + r.getAttributes().remove(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR); + } + // ── Deletes ────────────────────────────────────────────────────────────── /** diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java index 5bec066154..1dc45654f4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java @@ -219,6 +219,16 @@ public final class CfnRollback { */ public static final String APPCONFIG_UPDATE_SNAPSHOT_ATTR = "__FlociAppConfigUpdateSnapshot"; + /** + * Holds the members an AppSync GraphQL API, data source, function, resolver or API key carried + * before an in-place update changed or cleared them, in the request shape its update call takes, + * with the identifiers that address it, so a failed stack update can put them back. Written by + * {@code AppSyncCfnProvisioner} before its update call and spent by its {@code rollbackUpdate}; + * when its own undo did not complete, the provisioner carries it onto the restored resource + * through {@code mergeFailedUpdateResourceTracking}. + */ + public static final String APPSYNC_UPDATE_SNAPSHOT_ATTR = "__FlociAppSyncUpdateSnapshot"; + /** * Holds the name and tags an API Gateway V2 VPC link carried before an in-place update changed * them, so a failed stack update can put them back. Written by {@code ApiGatewayV2CfnProvisioner} diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceFixture.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceFixture.java new file mode 100644 index 0000000000..e2ec6560a1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceFixture.java @@ -0,0 +1,97 @@ +package io.github.hectorvent.floci.services.appsync; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.RequestContext; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker; +import io.github.hectorvent.floci.services.appsync.graphql.SchemaRegistry; +import io.github.hectorvent.floci.services.appsync.graphql.auth.LambdaAuthorizerCache; +import io.github.hectorvent.floci.services.appsync.model.ApiKey; +import io.github.hectorvent.floci.services.appsync.model.GraphqlApi; +import io.github.hectorvent.floci.testing.InMemoryStorageFactory; +import jakarta.enterprise.inject.Instance; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Optional; + +import static org.mockito.Answers.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** A real {@link AppSyncService} over in-memory storage, shared by the tests that need one. */ +public final class AppSyncServiceFixture { + + private AppSyncServiceFixture() { + } + + public static AppSyncService create(Clock clock) { + return create(clock, "http://localhost:4566", "us-east-1", null, + AccountAwareStorageBackend.inMemory("000000000000"), null, + mock(SchemaRegistry.class), new LambdaAuthorizerCache()); + } + + /** + * @param partition the deployment partition, or null to derive it from {@code region} + * @param apiKeyStore the store for API keys, or null for a fresh in-memory one + */ + @SuppressWarnings("unchecked") + public static AppSyncService create(Clock clock, String baseUrl, String region, String partition, + AccountAwareStorageBackend apiStore, AccountAwareStorageBackend apiKeyStore, + SchemaRegistry schemaRegistry, LambdaAuthorizerCache lambdaAuthorizerCache) { + InMemoryStorageFactory storageFactory = new InMemoryStorageFactory("000000000000") + .withStore("appsync-apis.json", apiStore); + if (apiKeyStore != null) { + storageFactory.withStore("appsync-apikeys.json", apiKeyStore); + } + Instance requestContext = mock(Instance.class); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.effectiveBaseUrl()).thenReturn(baseUrl); + when(config.services().cloudfront().domainSuffix()).thenReturn(Optional.empty()); + return new AppSyncService( + storageFactory, + config, + partition == null ? new RegionResolver(region, "000000000000") + : new RegionResolver(region, "000000000000", partition), + schemaRegistry, + mock(SchemaCreationWorker.class), + requestContext, + new ObjectMapper(), + AccountAwareStorageBackend.inMemory("000000000000"), + AccountAwareStorageBackend.inMemory("000000000000"), + clock, + lambdaAuthorizerCache); + } + + /** A clock a test moves by hand. */ + public static final class MutableClock extends Clock { + private Instant instant; + + public MutableClock(Instant instant) { + this.instant = instant; + } + + public void set(Instant instant) { + this.instant = instant; + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return instant; + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceTest.java index a665df7d7b..7f684fba99 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncServiceTest.java @@ -1,12 +1,7 @@ package io.github.hectorvent.floci.services.appsync; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; -import io.github.hectorvent.floci.core.common.RegionResolver; -import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; -import io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker; import io.github.hectorvent.floci.services.appsync.graphql.SchemaRegistry; import io.github.hectorvent.floci.services.appsync.graphql.auth.LambdaAuthorizerCache; import io.github.hectorvent.floci.services.appsync.graphql.auth.LambdaAuthorizerResult; @@ -15,9 +10,8 @@ import io.github.hectorvent.floci.services.appsync.model.AuthenticationType; import io.github.hectorvent.floci.services.appsync.model.DomainName; 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.SchemaCreationStatus; -import io.github.hectorvent.floci.testing.InMemoryStorageFactory; -import jakarta.enterprise.inject.Instance; +import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatusType; +import io.github.hectorvent.floci.testing.ParkingStore; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -26,18 +20,24 @@ import org.junit.jupiter.params.provider.CsvSource; import java.time.Clock; import java.time.Duration; import java.time.Instant; -import java.time.ZoneId; import java.time.ZoneOffset; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Answers.RETURNS_DEEP_STUBS; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -152,7 +152,7 @@ class AppSyncServiceTest { @Test void validateApiKeyExpiresAtBoundaryFails() { - MutableClock clock = new MutableClock(NOW); + AppSyncServiceFixture.MutableClock clock = new AppSyncServiceFixture.MutableClock(NOW); AppSyncService svc = newService(clock); GraphqlApi api = svc.createGraphqlApi(Map.of("name", "b", "authenticationType", "API_KEY"), "us-east-1"); long expires = NOW.getEpochSecond() + Duration.ofDays(1).getSeconds(); @@ -193,6 +193,89 @@ class AppSyncServiceTest { assertEquals("ApiKeyValidityOutOfBoundsException", tooFar.getErrorCode()); } + @Test + void aRefusedApiKeyUpdateLeavesTheDescriptionAsItWas() { + GraphqlApi api = service.createGraphqlApi(Map.of("name", "refuse-key", "authenticationType", "API_KEY"), "us-east-1"); + ApiKey created = service.createApiKey(api.getApiId(), Map.of("description", "kept")); + long expires = created.getExpires(); + + AwsException refused = assertThrows(AwsException.class, () -> service.updateApiKey(api.getApiId(), + created.getId(), Map.of("description", "changed", "expires", NOW.getEpochSecond()))); + + assertEquals("ApiKeyValidityOutOfBoundsException", refused.getErrorCode()); + ApiKey stored = service.getApiKey(api.getApiId(), created.getId()); + assertEquals("kept", stored.getDescription()); + assertEquals(expires, stored.getExpires()); + } + + @Test + void aRefusedApiKeyDescriptionLeavesTheExpiryAsItWas() { + GraphqlApi api = service.createGraphqlApi(Map.of("name", "refuse-desc", "authenticationType", "API_KEY"), "us-east-1"); + long original = NOW.getEpochSecond() + Duration.ofDays(10).getSeconds(); + ApiKey created = service.createApiKey(api.getApiId(), Map.of("description", "kept", "expires", original)); + ApiKey before = service.getApiKey(api.getApiId(), created.getId()); + Long expiresBefore = before.getExpires(); + Long deletesBefore = before.getDeletes(); + long newExpires = NOW.getEpochSecond() + Duration.ofDays(30).getSeconds(); + + assertThrows(RuntimeException.class, () -> service.updateApiKey(api.getApiId(), created.getId(), + Map.of("expires", newExpires, "description", 42))); + + ApiKey stored = service.getApiKey(api.getApiId(), created.getId()); + assertEquals(expiresBefore, stored.getExpires()); + assertEquals(deletesBefore, stored.getDeletes()); + assertEquals("kept", stored.getDescription()); + } + + @Test + void aRefusedDataSourceUpdateLeavesTheDescriptionAsItWas() { + GraphqlApi api = service.createGraphqlApi(Map.of("name", "refuse-ds", "authenticationType", "API_KEY"), "us-east-1"); + service.createDataSource(api.getApiId(), Map.of("name", "ds", "type", "NONE", "description", "kept"), "us-east-1"); + + assertThrows(AwsException.class, () -> service.updateDataSource(api.getApiId(), "ds", + Map.of("description", "changed", "type", "NOT_A_TYPE"))); + + assertEquals("kept", service.getDataSource(api.getApiId(), "ds").getDescription()); + } + + @Test + void aRefusedFunctionUpdateLeavesTheNameAsItWas() { + GraphqlApi api = service.createGraphqlApi(Map.of("name", "refuse-fn", "authenticationType", "API_KEY"), "us-east-1"); + FunctionConfiguration created = service.createFunction(api.getApiId(), Map.of("name", "kept"), "us-east-1"); + + assertThrows(AwsException.class, () -> service.updateFunction(api.getApiId(), created.getFunctionId(), + Map.of("name", "changed", "runtime", Map.of("name", "NOT_A_RUNTIME")))); + + assertEquals("kept", service.getFunction(api.getApiId(), created.getFunctionId()).getName()); + } + + @Test + void aRefusedResolverUpdateLeavesTheDataSourceAsItWas() { + GraphqlApi api = service.createGraphqlApi(Map.of("name", "refuse-rs", "authenticationType", "API_KEY"), "us-east-1"); + service.createDataSource(api.getApiId(), Map.of("name", "ds", "type", "NONE"), "us-east-1"); + service.createResolver(api.getApiId(), Map.of("typeName", "Query", "fieldName", "hello", + "dataSourceName", "ds"), "us-east-1"); + + assertThrows(AwsException.class, () -> service.updateResolver(api.getApiId(), "Query", "hello", + Map.of("dataSourceName", "other", "kind", "NOT_A_KIND"))); + + assertEquals("ds", service.getResolver(api.getApiId(), "Query", "hello").getDataSourceName()); + } + + @Test + void aRefusedGraphqlApiUpdateLeavesTheNameAsItWas() { + GraphqlApi api = service.createGraphqlApi(Map.of("name", "kept", "authenticationType", "API_KEY"), "us-east-1"); + Map pool = Map.of("userPoolId", "pool-1", "awsRegion", "us-east-1"); + Map provider = Map.of("authenticationType", "AMAZON_COGNITO_USER_POOLS", + "userPoolConfig", pool); + + assertThrows(AwsException.class, () -> service.updateGraphqlApi(api.getApiId(), + Map.of("name", "changed", "additionalAuthenticationProviders", List.of(provider, provider)), + "us-east-1")); + + assertEquals("kept", service.getGraphqlApi(api.getApiId()).getName()); + } + @Test void validateApiKeyWrongApiFails() { GraphqlApi a = service.createGraphqlApi(Map.of("name", "c", "authenticationType", "API_KEY"), "us-east-1"); @@ -364,7 +447,9 @@ class AppSyncServiceTest { apiId, Map.of("name", "updated-api"), "us-east-1"); assertEquals("updated-api", updated.getName()); assertEquals(expectedUris, updated.getUris()); - verify(apiStore, times(2)).put(apiId, api); + // The URI repair on read stores the persisted instance; the update then stores its own copy. + verify(apiStore).put(apiId, api); + verify(apiStore, times(2)).put(eq(apiId), any(GraphqlApi.class)); } @Test @@ -408,60 +493,12 @@ class AppSyncServiceTest { return newService(clock, baseUrl, AccountAwareStorageBackend.inMemory("000000000000")); } - @SuppressWarnings("unchecked") private AppSyncService newService(Clock clock, String baseUrl, AccountAwareStorageBackend apiStore) { - InMemoryStorageFactory storageFactory = new InMemoryStorageFactory("000000000000") - .withStore("appsync-apis.json", apiStore); - if (apiKeyStoreOverride != null) { - storageFactory.withStore("appsync-apikeys.json", apiKeyStoreOverride); - } - Instance requestContext = mock(Instance.class); schemaRegistry = mock(SchemaRegistry.class); lambdaAuthorizerCache = new LambdaAuthorizerCache(); - EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); - when(config.effectiveBaseUrl()).thenReturn(baseUrl); - when(config.services().cloudfront().domainSuffix()).thenReturn(Optional.empty()); - return new AppSyncService( - storageFactory, - config, - partition == null ? new RegionResolver(region, "000000000000") - : new RegionResolver(region, "000000000000", partition), - schemaRegistry, - mock(SchemaCreationWorker.class), - requestContext, - new ObjectMapper(), - AccountAwareStorageBackend.inMemory("000000000000"), - AccountAwareStorageBackend.inMemory("000000000000"), - clock, - lambdaAuthorizerCache); - } - - private static final class MutableClock extends Clock { - private Instant instant; - - private MutableClock(Instant instant) { - this.instant = instant; - } - - void set(Instant instant) { - this.instant = instant; - } - - @Override - public ZoneId getZone() { - return ZoneOffset.UTC; - } - - @Override - public Clock withZone(ZoneId zone) { - return this; - } - - @Override - public Instant instant() { - return instant; - } + return AppSyncServiceFixture.create(clock, baseUrl, region, partition, apiStore, + apiKeyStoreOverride, schemaRegistry, lambdaAuthorizerCache); } /** @@ -524,4 +561,148 @@ class AppSyncServiceTest { assertThrows(AwsException.class, () -> service.tagResource("apis/abc", Map.of())); assertThrows(AwsException.class, () -> service.tagResource(null, Map.of())); } + + /** + * Parks {@code first} in its next write to {@code store}, starts {@code second} on another + * thread, waits until it is blocked behind the first or done, then lets the first go and waits + * for both. The second can only be blocked if a lock covers the first's read, change and write; + * the callers assert the final state. + */ + private static void secondWriterRunsAroundTheFirst(ParkingStore store, Runnable first, Runnable second) + throws Exception { + secondCallRunsAroundTheFirst(store, store::parkNextWrite, first, second); + } + + /** As above, with the caller choosing which store call of the first one is parked. */ + private static void secondCallRunsAroundTheFirst(ParkingStore store, Runnable arm, Runnable first, + Runnable second) throws Exception { + arm.run(); + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + Future firstWrite = pool.submit(first); + assertTrue(store.awaitParked(), "the first write must reach the store"); + AtomicReference secondThread = new AtomicReference<>(); + Future secondWrite = pool.submit(() -> { + secondThread.set(Thread.currentThread()); + second.run(); + }); + awaitBlockedOrDone(secondThread, secondWrite); + + store.release(); + firstWrite.get(2, TimeUnit.SECONDS); + secondWrite.get(2, TimeUnit.SECONDS); + } catch (ExecutionException e) { + throw new AssertionError(e.getCause()); + } finally { + store.release(); + pool.shutdownNow(); + } + } + + private AppSyncService serviceWithApiStore(ParkingStore apiStore) { + return newService(Clock.fixed(NOW, ZoneOffset.UTC), "http://localhost:4566", + new AccountAwareStorageBackend<>(apiStore, null, "000000000000")); + } + + private static String arnOf(GraphqlApi api) { + return "arn:aws:appsync:us-east-1:000000000000:apis/" + api.getApiId(); + } + + private static Map apiRequest(String name) { + return Map.of("name", name, "authenticationType", "API_KEY"); + } + + @Test + void aTagDuringAnApiUpdateSurvivesTheUpdate() throws Exception { + ParkingStore store = new ParkingStore<>(); + AppSyncService svc = serviceWithApiStore(store); + GraphqlApi api = svc.createGraphqlApi(apiRequest("before"), "us-east-1"); + + secondWriterRunsAroundTheFirst(store, + () -> svc.updateGraphqlApi(api.getApiId(), apiRequest("after"), "us-east-1"), + () -> svc.tagResource(arnOf(api), Map.of("env", "test"))); + + assertEquals("after", svc.getGraphqlApi(api.getApiId()).getName()); + assertEquals("test", svc.getTags(arnOf(api)).get("env")); + } + + @Test + void anUntagDuringAnApiUpdateStaysRemoved() throws Exception { + ParkingStore store = new ParkingStore<>(); + AppSyncService svc = serviceWithApiStore(store); + GraphqlApi api = svc.createGraphqlApi(apiRequest("before"), "us-east-1"); + svc.tagResource(arnOf(api), Map.of("drop", "1", "keep", "2")); + + secondWriterRunsAroundTheFirst(store, + () -> svc.updateGraphqlApi(api.getApiId(), apiRequest("after"), "us-east-1"), + () -> svc.untagResource(arnOf(api), List.of("drop"))); + + assertEquals("after", svc.getGraphqlApi(api.getApiId()).getName()); + assertFalse(svc.getTags(arnOf(api)).containsKey("drop"), svc.getTags(arnOf(api)).toString()); + assertEquals("2", svc.getTags(arnOf(api)).get("keep")); + } + + @Test + void environmentVariablesWrittenDuringAnApiUpdateSurviveTheUpdate() throws Exception { + ParkingStore store = new ParkingStore<>(); + AppSyncService svc = serviceWithApiStore(store); + GraphqlApi api = svc.createGraphqlApi(apiRequest("before"), "us-east-1"); + + secondWriterRunsAroundTheFirst(store, + () -> svc.updateGraphqlApi(api.getApiId(), apiRequest("after"), "us-east-1"), + () -> svc.putEnvironmentVariables(api.getApiId(), Map.of("TABLE_NAME", "my-table"))); + + assertEquals("after", svc.getGraphqlApi(api.getApiId()).getName()); + assertEquals("my-table", svc.getEnvironmentVariables(api.getApiId()).get("TABLE_NAME")); + } + + @Test + void twoUpdatesOfDifferentApiKeyMembersBothLand() throws Exception { + ParkingStore keyStore = new ParkingStore<>(); + apiKeyStoreOverride = new AccountAwareStorageBackend<>(keyStore, null, "000000000000"); + AppSyncService svc = newService(Clock.fixed(NOW, ZoneOffset.UTC)); + GraphqlApi api = svc.createGraphqlApi(apiRequest("keys"), "us-east-1"); + ApiKey created = svc.createApiKey(api.getApiId(), Map.of()); + long expires = NOW.plus(Duration.ofDays(30)).getEpochSecond(); + + secondWriterRunsAroundTheFirst(keyStore, + () -> svc.updateApiKey(api.getApiId(), created.getId(), Map.of("description", "renewed")), + () -> svc.updateApiKey(api.getApiId(), created.getId(), Map.of("expires", expires))); + + ApiKey result = svc.getApiKey(api.getApiId(), created.getId()); + assertEquals("renewed", result.getDescription()); + assertEquals(expires, result.getExpires()); + } + + /** + * StartSchemaCreation checks the API and writes its PROCESSING status as one step under the + * service monitor that DeleteGraphqlApi holds, so a delete arriving between the two waits. It + * then finds the schema busy and is refused with a 409, leaving the API and its PROCESSING + * status in place. Without the shared hold the delete would succeed and leave a PROCESSING + * status for a deleted API. The schema creation worker is the fixture's mock, so the status + * stays PROCESSING. + */ + @Test + void anApiDeleteDuringSchemaStartIsRefusedAndKeepsTheApi() throws Exception { + ParkingStore store = new ParkingStore<>(); + AppSyncService svc = serviceWithApiStore(store); + GraphqlApi api = svc.createGraphqlApi(apiRequest("kept"), "us-east-1"); + AtomicReference deleteFailure = new AtomicReference<>(); + + secondCallRunsAroundTheFirst(store, store::parkNextRead, + () -> svc.startSchemaCreation(api.getApiId(), "type Query { a: String }"), + () -> { + try { + svc.deleteGraphqlApi(api.getApiId()); + } catch (AwsException e) { + deleteFailure.set(e); + } + }); + + assertTrue(deleteFailure.get() instanceof AwsException, "the delete must be refused: " + deleteFailure.get()); + assertEquals(409, ((AwsException) deleteFailure.get()).getHttpStatus()); + assertEquals("kept", svc.getGraphqlApi(api.getApiId()).getName()); + assertEquals(SchemaCreationStatusType.PROCESSING, + svc.getSchemaCreationStatus(api.getApiId()).getStatus()); + } } 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 cf7c9db49b..1e2b4fd4a2 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 @@ -10,6 +10,8 @@ import io.restassured.specification.RequestSpecification; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.Map; import static io.github.hectorvent.floci.testing.CfnRequests.cfn; @@ -54,6 +56,7 @@ class AppSyncCfnIntegrationTest { "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 ROLLBACK_STACK = "appsync-cfn-rollback-it"; private static final String TEMPLATE = """ { @@ -185,6 +188,140 @@ class AppSyncCfnIntegrationTest { } """; + private static final String ROLLBACK_FIRST = """ + { + "Resources": { + "GraphQlApi": { + "Type": "AWS::AppSync::GraphQLApi", + "Properties": { + "Name": "appsync-cfn-rollback-it-api", + "AuthenticationType": "API_KEY", + "OwnerContact": "platform-team", + "QueryDepthLimit": 10 + } + }, + "GraphQlDs": { + "Type": "AWS::AppSync::DataSource", + "Properties": { + "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}, + "Name": "rollbackDs", + "Type": "NONE", + "Description": "first", + "ServiceRoleArn": "arn:aws:iam::000000000000:role/rollback-it" + } + }, + "GraphQlFn": { + "Type": "AWS::AppSync::FunctionConfiguration", + "Properties": { + "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}, + "Name": "rollbackFn", + "DataSourceName": {"Fn::GetAtt": ["GraphQlDs", "Name"]}, + "FunctionVersion": "2018-05-29", + "RequestMappingTemplate": "first request", + "ResponseMappingTemplate": "first response" + } + }, + "GraphQlResolver": { + "Type": "AWS::AppSync::Resolver", + "Properties": { + "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}, + "TypeName": "Query", + "FieldName": "getMessages", + "DataSourceName": {"Fn::GetAtt": ["GraphQlDs", "Name"]}, + "RequestMappingTemplate": "first request", + "ResponseMappingTemplate": "first response" + } + }, + "GraphQlApiKey": { + "Type": "AWS::AppSync::ApiKey", + "Properties": { + "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}, + "Description": "first" + } + } + }, + "Outputs": { + "ApiId": {"Value": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}}, + "FunctionId": {"Value": {"Fn::GetAtt": ["GraphQlFn", "FunctionId"]}} + } + } + """; + + /** + * Changes one member and drops another on every type, adds a data source, then fails on a + * resolver that names resolver code in S3, which the provisioner refuses. {@code %d} is the + * API key's new expiry. + */ + private static final String ROLLBACK_SECOND = """ + { + "Resources": { + "GraphQlApi": { + "Type": "AWS::AppSync::GraphQLApi", + "Properties": { + "Name": "appsync-cfn-rollback-it-api", + "AuthenticationType": "API_KEY", + "QueryDepthLimit": 20 + } + }, + "GraphQlDs": { + "Type": "AWS::AppSync::DataSource", + "Properties": { + "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}, + "Name": "rollbackDs", + "Type": "NONE", + "Description": "second" + } + }, + "GraphQlFn": { + "Type": "AWS::AppSync::FunctionConfiguration", + "Properties": { + "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}, + "Name": "rollbackFn", + "DataSourceName": {"Fn::GetAtt": ["GraphQlDs", "Name"]}, + "FunctionVersion": "2018-05-29", + "RequestMappingTemplate": "second request" + } + }, + "GraphQlResolver": { + "Type": "AWS::AppSync::Resolver", + "Properties": { + "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}, + "TypeName": "Query", + "FieldName": "getMessages", + "DataSourceName": {"Fn::GetAtt": ["GraphQlDs", "Name"]}, + "RequestMappingTemplate": "second request" + } + }, + "GraphQlApiKey": { + "Type": "AWS::AppSync::ApiKey", + "Properties": { + "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}, + "Expires": %d + } + }, + "GraphQlDsCreated": { + "Type": "AWS::AppSync::DataSource", + "Properties": { + "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}, + "Name": "createdByTheUpdate", + "Type": "NONE" + } + }, + "GraphQlResolverLater": { + "Type": "AWS::AppSync::Resolver", + "DependsOn": ["GraphQlResolver", "GraphQlApiKey", "GraphQlDsCreated"], + "Properties": { + "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}, + "TypeName": "Query", + "FieldName": "later", + "DataSourceName": {"Fn::GetAtt": ["GraphQlDs", "Name"]}, + "CodeS3Location": "s3://rollback-it/resolver.js" + } + } + } + } + """; + @Test void createUpdateAndDeleteAnAppSyncApi() { cloudFormation("CreateStack", STACK, TEMPLATE, Map.of("FieldLogLevel", "ERROR")); @@ -305,6 +442,53 @@ class AppSyncCfnIntegrationTest { CfnStackWaits.awaitStackDeleted(REMOVAL_STACK); } + /** + * A failing later resource rolls an AppSync stack back: each type gets back the member the + * update changed and the member it cleared, an API key its expiry and description, and the + * data source the update created is deleted. + */ + @Test + void aFailingLaterResourceRestoresWhatTheUpdateChangedAndCleared() { + cloudFormation("CreateStack", ROLLBACK_STACK, ROLLBACK_FIRST, Map.of()); + CfnStackWaits.awaitStatus(ROLLBACK_STACK, "CREATE_COMPLETE"); + String created = describeStacks(ROLLBACK_STACK, "CREATE_COMPLETE"); + String apiId = outputValue(created, "ApiId"); + String functionId = outputValue(created, "FunctionId"); + String keyId = appSync("/v1/apis/" + apiId + "/apikeys").extract().path("apiKeys[0].id"); + long expires = ((Number) appSync("/v1/apis/" + apiId + "/apikeys").extract() + .path("apiKeys[0].expires")).longValue(); + + long newExpiry = Instant.now().plus(30, ChronoUnit.DAYS).getEpochSecond(); + cloudFormation("UpdateStack", ROLLBACK_STACK, ROLLBACK_SECOND.formatted(newExpiry), Map.of()); + CfnStackWaits.awaitStatus(ROLLBACK_STACK, "UPDATE_ROLLBACK_COMPLETE"); + + appSync("/v1/apis/" + apiId) + .statusCode(200) + .body("graphqlApi.queryDepthLimit", equalTo(10)) + .body("graphqlApi.ownerContact", equalTo("platform-team")); + appSync("/v1/apis/" + apiId + "/datasources/rollbackDs") + .statusCode(200) + .body("dataSource.description", equalTo("first")) + .body("dataSource.serviceRoleArn", equalTo("arn:aws:iam::000000000000:role/rollback-it")); + appSync("/v1/apis/" + apiId + "/functions/" + functionId) + .statusCode(200) + .body("functionConfiguration.requestMappingTemplate", equalTo("first request")) + .body("functionConfiguration.responseMappingTemplate", equalTo("first response")); + appSync("/v1/apis/" + apiId + "/types/Query/resolvers/getMessages") + .statusCode(200) + .body("resolver.requestMappingTemplate", equalTo("first request")) + .body("resolver.responseMappingTemplate", equalTo("first response")); + appSync("/v1/apis/" + apiId + "/apikeys") + .statusCode(200) + .body("apiKeys[0].id", equalTo(keyId)) + .body("apiKeys[0].description", equalTo("first")) + .body("apiKeys[0].expires", equalTo((int) expires)); + appSync("/v1/apis/" + apiId + "/datasources/createdByTheUpdate").statusCode(404); + + cloudFormation("DeleteStack", ROLLBACK_STACK, null, Map.of()); + CfnStackWaits.awaitStackDeleted(ROLLBACK_STACK); + } + private static void cloudFormation(String action, String stackName, String template, Map parameters) { RequestSpecification request = cfn(action, stackName).header("Authorization", CFN_AUTH); 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 eab58d1df7..d555e134cd 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 @@ -5,8 +5,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.appsync.AppSyncService; +import io.github.hectorvent.floci.services.appsync.AppSyncServiceFixture; import io.github.hectorvent.floci.services.appsync.model.ApiKey; +import io.github.hectorvent.floci.services.appsync.model.AuthenticationType; import io.github.hectorvent.floci.services.appsync.model.DataSource; +import io.github.hectorvent.floci.services.appsync.model.DataSourceType; 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; @@ -19,6 +22,10 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -973,6 +980,436 @@ class AppSyncCfnProvisionerTest { assertTrue(updateRequest(captor).isEmpty()); } + // ── Rollback of an in-place update ─────────────────────────────────────── + + private static final String SNAPSHOT = CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR; + + /** Every request the mock received on an update method, oldest first. */ + @SuppressWarnings("unchecked") + private static List> requests(ArgumentCaptor> captor) { + return captor.getAllValues(); + } + + @Test + void graphqlApiRollbackPutsBackWhatTheUpdateChangedAndCleared() throws Exception { + GraphqlApi before = api(); + before.setAuthenticationType(AuthenticationType.API_KEY); + before.setOwnerContact("team"); + before.setXrayEnabled(true); + before.setTags(Map.of("env", "dev")); + before.setUserPoolConfig(Map.of("awsRegion", "eu-west-1")); + before.setApiType("MERGED"); + before.setVisibility("PRIVATE"); + when(appSync.getGraphqlApi(API_ID)).thenReturn(before); + when(appSync.getEnvironmentVariables(API_ID)).thenReturn(Map.of("STAGE", "dev")); + 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\":\"renamed-api\",\"AuthenticationType\":\"AWS_IAM\"," + + "\"ApiType\":\"GRAPHQL\",\"Visibility\":\"GLOBAL\"," + + "\"EnvironmentVariables\":{\"STAGE\":\"prod\"}}"), + updateCtx(API_ID, "{\"Name\":\"account-api\",\"AuthenticationType\":\"API_KEY\"," + + "\"OwnerContact\":\"team\",\"UserPoolConfig\":{\"AwsRegion\":\"eu-west-1\"}}")); + assertTrue(r.getAttributes().containsKey(SNAPSHOT)); + + assertTrue(provisioner.rollbackUpdate(r)); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync, Mockito.times(2)).updateGraphqlApi(eq(API_ID), captor.capture(), eq("eu-west-1")); + Map restore = requests(captor).get(1); + assertEquals("account-api", restore.get("name")); + assertEquals("API_KEY", restore.get("authenticationType")); + assertEquals("team", restore.get("ownerContact")); + assertEquals(Map.of("awsRegion", "eu-west-1"), restore.get("userPoolConfig")); + assertEquals(true, restore.get("xrayEnabled")); + assertEquals(Map.of("env", "dev"), restore.get("tags")); + // The service ignores a null list, so an API that had none gets an empty one back. + assertEquals(List.of(), restore.get("additionalAuthenticationProviders")); + // A member the API never had is replayed as a clear. + assertTrue(restore.containsKey("introspectionConfig")); + assertNull(restore.get("introspectionConfig")); + // ApiType and Visibility are applied by the update, so the restore puts them back too. + assertEquals("MERGED", restore.get("apiType")); + assertEquals("PRIVATE", restore.get("visibility")); + verify(appSync).putEnvironmentVariables(API_ID, Map.of("STAGE", "dev")); + assertFalse(r.getAttributes().containsKey(SNAPSHOT)); + } + + @Test + void dataSourceRollbackPutsBackWhatTheUpdateChangedAndCleared() throws Exception { + DataSource before = new DataSource(); + before.setName("accountDB"); + before.setDataSourceArn("arn:ds"); + before.setType(DataSourceType.AMAZON_DYNAMODB); + before.setDescription("old"); + before.setDynamodbConfig(Map.of("tableName", "t")); + when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(before); + when(appSync.updateDataSource(eq(API_ID), eq("accountDB"), any())).thenReturn(before); + 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\":\"HTTP\"," + + "\"HttpConfig\":{\"Endpoint\":\"https://example.com\"}}"), + updateCtx("arn:ds", "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\"," + + "\"Type\":\"AMAZON_DYNAMODB\",\"Description\":\"old\"," + + "\"DynamoDBConfig\":{\"TableName\":\"t\"}}")); + + assertTrue(provisioner.rollbackUpdate(r)); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync, Mockito.times(2)).updateDataSource(eq(API_ID), eq("accountDB"), captor.capture()); + Map restore = requests(captor).get(1); + assertEquals("AMAZON_DYNAMODB", restore.get("type")); + assertEquals("old", restore.get("description")); + assertEquals(Map.of("tableName", "t"), restore.get("dynamodbConfig")); + // The config the update added is cleared again. + assertTrue(restore.containsKey("httpConfig")); + assertNull(restore.get("httpConfig")); + assertFalse(r.getAttributes().containsKey(SNAPSHOT)); + } + + @Test + void functionRollbackPutsBackWhatTheUpdateChangedAndCleared() throws Exception { + FunctionConfiguration before = new FunctionConfiguration(); + before.setFunctionId("fn1"); + before.setFunctionArn("arn:fn"); + before.setName("old-name"); + before.setDataSourceName("accountDB"); + before.setDescription("old"); + before.setFunctionVersion("2018-05-29"); + before.setCode("export function request() {}"); + when(appSync.getFunction(API_ID, "fn1")).thenReturn(before); + FunctionConfiguration after = new FunctionConfiguration(); + after.setFunctionId("fn1"); + after.setFunctionArn("arn:fn"); + after.setName("new-name"); + after.setDataSourceName("otherDB"); + when(appSync.updateFunction(eq(API_ID), eq("fn1"), any())).thenReturn(after); + StackResource r = resource("AWS::AppSync::FunctionConfiguration", "GraphQlFn"); + r.getAttributes().put("ApiId", API_ID); + r.getAttributes().put("FunctionId", "fn1"); + + provisioner.provision(r, mapper.readTree( + "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"new-name\",\"DataSourceName\":\"otherDB\"}"), + updateCtx("arn:fn", "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"old-name\"," + + "\"DataSourceName\":\"accountDB\",\"Description\":\"old\"," + + "\"Code\":\"export function request() {}\"}")); + assertEquals("new-name", r.getAttributes().get("Name")); + + assertTrue(provisioner.rollbackUpdate(r)); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync, Mockito.times(2)).updateFunction(eq(API_ID), eq("fn1"), captor.capture()); + Map restore = requests(captor).get(1); + assertEquals("old-name", restore.get("name")); + assertEquals("accountDB", restore.get("dataSourceName")); + assertEquals("old", restore.get("description")); + assertEquals("export function request() {}", restore.get("code")); + assertEquals("2018-05-29", restore.get("functionVersion")); + // The engine keeps the attempted resource, so its attributes name the restored function. + assertEquals("old-name", r.getAttributes().get("Name")); + assertEquals("accountDB", r.getAttributes().get("DataSourceName")); + assertFalse(r.getAttributes().containsKey(SNAPSHOT)); + } + + @Test + void functionRollbackDropsADataSourceNameTheFunctionDidNotHave() throws Exception { + FunctionConfiguration before = new FunctionConfiguration(); + before.setFunctionId("fn1"); + before.setFunctionArn("arn:fn"); + before.setName("fn-name"); + when(appSync.getFunction(API_ID, "fn1")).thenReturn(before); + FunctionConfiguration after = new FunctionConfiguration(); + after.setFunctionId("fn1"); + after.setFunctionArn("arn:fn"); + after.setName("fn-name"); + after.setDataSourceName("otherDB"); + when(appSync.updateFunction(eq(API_ID), eq("fn1"), any())).thenReturn(after); + StackResource r = resource("AWS::AppSync::FunctionConfiguration", "GraphQlFn"); + r.getAttributes().put("ApiId", API_ID); + r.getAttributes().put("FunctionId", "fn1"); + + provisioner.provision(r, mapper.readTree( + "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"fn-name\",\"DataSourceName\":\"otherDB\"}"), + updateCtx("arn:fn", "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"fn-name\"}")); + assertEquals("otherDB", r.getAttributes().get("DataSourceName")); + + assertTrue(provisioner.rollbackUpdate(r)); + + assertFalse(r.getAttributes().containsKey("DataSourceName")); + } + + @Test + void resolverRollbackPutsBackWhatTheUpdateChangedAndCleared() throws Exception { + Resolver before = new Resolver(); + before.setApiId(API_ID); + before.setTypeName("Query"); + before.setFieldName("getMessages"); + before.setKind(ResolverKind.UNIT); + before.setDataSourceName("accountDB"); + before.setRequestMappingTemplate("old request"); + before.setResponseMappingTemplate("old response"); + when(appSync.getResolver(API_ID, "Query", "getMessages")).thenReturn(before); + Resolver after = new Resolver(); + after.setResolverArn("arn:resolver"); + when(appSync.updateResolver(eq(API_ID), eq("Query"), eq("getMessages"), any())).thenReturn(after); + 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\",\"RequestMappingTemplate\":\"old request\"," + + "\"ResponseMappingTemplate\":\"old response\"}"; + + provisioner.provision(r, mapper.readTree("{\"ApiId\":\"" + API_ID + "\",\"TypeName\":\"Query\"," + + "\"FieldName\":\"getMessages\",\"DataSourceName\":\"accountDB\"," + + "\"RequestMappingTemplate\":\"new request\"}"), + updateCtx("arn:resolver", declared)); + + assertTrue(provisioner.rollbackUpdate(r)); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync, Mockito.times(2)).updateResolver(eq(API_ID), eq("Query"), eq("getMessages"), + captor.capture()); + Map restore = requests(captor).get(1); + assertEquals("old request", restore.get("requestMappingTemplate")); + assertEquals("old response", restore.get("responseMappingTemplate")); + assertEquals("UNIT", restore.get("kind")); + assertEquals("accountDB", restore.get("dataSourceName")); + // A member the resolver never carried is replayed as a clear. + assertTrue(restore.containsKey("pipelineConfig")); + assertNull(restore.get("pipelineConfig")); + assertFalse(r.getAttributes().containsKey(SNAPSHOT)); + } + + @Test + void apiKeyRollbackPutsBackADroppedDescriptionAndSkipsAnExpiryThatDidNotMove() throws Exception { + ApiKey before = new ApiKey(); + before.setId("da2-key"); + before.setDescription("old"); + before.setExpires(1_900_000_000L); + when(appSync.getApiKey(API_ID, "da2-key")).thenReturn(before); + when(appSync.updateApiKey(eq(API_ID), eq("da2-key"), any())).thenReturn(before); + StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey"); + r.getAttributes().put("ApiId", API_ID); + + provisioner.provision(r, mapper.readTree("{\"ApiId\":\"" + API_ID + "\",\"Expires\":1900000000}"), + updateCtx("da2-key", "{\"ApiId\":\"" + API_ID + "\",\"Description\":\"old\"," + + "\"Expires\":1900000000}")); + + assertTrue(provisioner.rollbackUpdate(r)); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync, Mockito.times(2)).updateApiKey(eq(API_ID), eq("da2-key"), captor.capture()); + Map restore = requests(captor).get(1); + assertEquals("old", restore.get("description")); + // The store still holds the prior expiry, so sending it again could only trip the service's bounds. + assertFalse(restore.containsKey("expires")); + } + + @Test + void apiKeyRollbackPutsBackAnExpiryTheUpdateMoved() throws Exception { + ApiKey before = new ApiKey(); + before.setId("da2-key"); + before.setExpires(1_900_000_000L); + ApiKey moved = new ApiKey(); + moved.setId("da2-key"); + moved.setExpires(1_950_000_000L); + when(appSync.getApiKey(API_ID, "da2-key")).thenReturn(before, moved); + when(appSync.updateApiKey(eq(API_ID), eq("da2-key"), any())).thenReturn(moved); + StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey"); + r.getAttributes().put("ApiId", API_ID); + + provisioner.provision(r, mapper.readTree("{\"ApiId\":\"" + API_ID + "\",\"Expires\":1950000000}"), + updateCtx("da2-key", "{\"ApiId\":\"" + API_ID + "\",\"Expires\":1900000000}")); + provisioner.rollbackUpdate(r); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync, Mockito.times(2)).updateApiKey(eq(API_ID), eq("da2-key"), captor.capture()); + assertEquals(1_900_000_000L, ((Number) requests(captor).get(1).get("expires")).longValue()); + } + + @Test + void aRollbackThatTheServiceRefusesLeavesTheApiKeyAsTheUpdateLeftItAndKeepsTheSnapshot() throws Exception { + Instant start = Instant.parse("2026-01-01T00:00:00Z"); + AppSyncServiceFixture.MutableClock clock = new AppSyncServiceFixture.MutableClock(start); + AppSyncService real = AppSyncServiceFixture.create(clock); + AppSyncCfnProvisioner onRealService = new AppSyncCfnProvisioner(real); + GraphqlApi created = real.createGraphqlApi(Map.of("name", "keys", "authenticationType", "API_KEY"), "eu-west-1"); + long soonExpiry = start.getEpochSecond() + Duration.ofHours(25).getSeconds(); + long laterExpiry = start.getEpochSecond() + Duration.ofDays(100).getSeconds(); + ApiKey key = real.createApiKey(created.getApiId(), Map.of("description", "before", "expires", soonExpiry)); + StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey"); + r.getAttributes().put("ApiId", created.getApiId()); + + onRealService.provision(r, mapper.readTree("{\"ApiId\":\"" + created.getApiId() + + "\",\"Description\":\"after\",\"Expires\":" + laterExpiry + "}"), + updateCtx(key.getId(), "{\"ApiId\":\"" + created.getApiId() + "\",\"Description\":\"before\"," + + "\"Expires\":" + soonExpiry + "}")); + // Three hours on, the prior expiry is under a day away, which the service no longer accepts. + clock.set(start.plus(Duration.ofHours(3))); + + AwsException refused = assertThrows(AwsException.class, () -> onRealService.rollbackUpdate(r)); + + assertEquals("ApiKeyValidityOutOfBoundsException", refused.getErrorCode()); + ApiKey stored = real.getApiKey(created.getApiId(), key.getId()); + assertEquals("after", stored.getDescription()); + assertEquals(laterExpiry - laterExpiry % 3600, stored.getExpires()); + assertTrue(r.getAttributes().containsKey(SNAPSHOT)); + } + + @Test + void aSnapshotThatIsNotJsonFailsTheRollbackNamingTheResourceAndChangesNothing() { + AppSyncService real = AppSyncServiceFixture.create(Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC)); + AppSyncCfnProvisioner onRealService = new AppSyncCfnProvisioner(real); + GraphqlApi created = real.createGraphqlApi(Map.of("name", "corrupt", "authenticationType", "API_KEY"), "eu-west-1"); + real.createDataSource(created.getApiId(), Map.of("name", "ds", "type", "NONE", "description", "kept"), "eu-west-1"); + StackResource r = resource("AWS::AppSync::DataSource", "CorruptSnapshotDs"); + r.getAttributes().put("ApiId", created.getApiId()); + r.getAttributes().put("Name", "ds"); + r.getAttributes().put(SNAPSHOT, "this is { not json"); + + Exception failure = assertThrows(Exception.class, () -> onRealService.rollbackUpdate(r)); + + assertTrue(failure.getMessage().contains("CorruptSnapshotDs")); + DataSource stored = real.getDataSource(created.getApiId(), "ds"); + assertEquals("kept", stored.getDescription()); + assertEquals(DataSourceType.NONE, stored.getType()); + } + + @Test + void anUpdateThatFailsPartWayPutsTheEntityBackBeforeItFails() throws Exception { + DataSource before = new DataSource(); + before.setName("accountDB"); + before.setType(DataSourceType.AMAZON_DYNAMODB); + before.setDescription("old"); + when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(before); + when(appSync.updateDataSource(eq(API_ID), eq("accountDB"), any())) + .thenThrow(new AwsException("BadRequestException", "refused", 400)) + .thenReturn(before); + StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb"); + r.getAttributes().put("ApiId", API_ID); + r.getAttributes().put("Name", "accountDB"); + + assertThrows(AwsException.class, () -> provisioner.provision(r, mapper.readTree( + "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\",\"Type\":\"HTTP\"}"), + updateCtx("arn:ds", "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\"}"))); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(appSync, Mockito.times(2)).updateDataSource(eq(API_ID), eq("accountDB"), captor.capture()); + assertEquals("AMAZON_DYNAMODB", requests(captor).get(1).get("type")); + assertEquals("old", requests(captor).get(1).get("description")); + assertFalse(r.getAttributes().containsKey(SNAPSHOT)); + assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)); + } + + @Test + void anUndoThatFailsKeepsTheSnapshotAndReportsWhyForAContinueUpdateRollback() throws Exception { + DataSource before = new DataSource(); + before.setName("accountDB"); + before.setType(DataSourceType.AMAZON_DYNAMODB); + when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(before); + when(appSync.updateDataSource(eq(API_ID), eq("accountDB"), any())) + .thenThrow(new AwsException("BadRequestException", "refused", 400)) + .thenThrow(new AwsException("ConcurrentModificationException", "busy", 409)); + StackResource attempted = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb"); + attempted.getAttributes().put("ApiId", API_ID); + attempted.getAttributes().put("Name", "accountDB"); + + assertThrows(AwsException.class, () -> provisioner.provision(attempted, mapper.readTree( + "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\",\"Type\":\"HTTP\"}"), + updateCtx("arn:ds", "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\"}"))); + + assertTrue(attempted.getAttributes().containsKey(SNAPSHOT)); + assertTrue(attempted.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR).contains("busy")); + StackResource previous = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb"); + provisioner.mergeFailedUpdateResourceTracking(previous, attempted); + assertEquals(attempted.getAttributes().get(SNAPSHOT), previous.getAttributes().get(SNAPSHOT)); + } + + @Test + void aRestoreThatFailsKeepsTheSnapshotForTheNextAttempt() throws Exception { + DataSource before = new DataSource(); + before.setName("accountDB"); + before.setType(DataSourceType.AMAZON_DYNAMODB); + when(appSync.getDataSource(API_ID, "accountDB")).thenReturn(before); + when(appSync.updateDataSource(eq(API_ID), eq("accountDB"), any())) + .thenReturn(before) + .thenThrow(new AwsException("ConcurrentModificationException", "busy", 409)) + .thenReturn(before); + 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\":\"HTTP\"}"), + updateCtx("arn:ds", "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\"}")); + + assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); + assertTrue(r.getAttributes().containsKey(SNAPSHOT)); + + assertTrue(provisioner.rollbackUpdate(r)); + assertFalse(r.getAttributes().containsKey(SNAPSHOT)); + } + + @Test + void aResourceTheFailedUpdateCreatedHasNothingToRestore() throws Exception { + DataSource created = new DataSource(); + created.setName("accountDB"); + created.setDataSourceArn("arn:ds"); + when(appSync.createDataSource(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(created); + StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb"); + + provisioner.provision(r, mapper.readTree( + "{\"ApiId\":\"" + API_ID + "\",\"Name\":\"accountDB\",\"Type\":\"HTTP\"}"), ctx()); + + // The engine deletes it from the recorded attributes; the provisioner answers no restore. + assertFalse(r.getAttributes().containsKey(SNAPSHOT)); + assertFalse(provisioner.rollbackUpdate(r)); + verify(appSync, never()).updateDataSource(anyString(), anyString(), any()); + } + + @Test + void aReplacementLeavesNoSnapshotAndKeepsTheUnsupportedAnswer() throws Exception { + ApiKey created = new ApiKey(); + created.setId("da2-new"); + when(appSync.createApiKey(eq("other-api"), any())).thenReturn(created); + StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey"); + r.getAttributes().put("ApiId", API_ID); + + provisioner.provision(r, mapper.readTree("{\"ApiId\":\"other-api\"}"), updateCtx("da2-key")); + + assertFalse(r.getAttributes().containsKey(SNAPSHOT)); + assertFalse(provisioner.rollbackUpdate(r)); + } + + @Test + void aSnapshotAnEarlierUpdateLeftBehindIsDroppedWhenTheNextProvisionStarts() throws Exception { + ApiKey created = new ApiKey(); + created.setId("da2-new"); + when(appSync.createApiKey(eq(API_ID), any())).thenReturn(created); + StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey"); + r.getAttributes().put(SNAPSHOT, "{}"); + + provisioner.provision(r, mapper.readTree("{\"ApiId\":\"" + API_ID + "\"}"), ctx()); + + assertFalse(r.getAttributes().containsKey(SNAPSHOT)); + } + + @Test + void aCommittedUpdateDropsItsSnapshotAndOwesNoCleanup() { + StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiKey"); + r.getAttributes().put(SNAPSHOT, "{}"); + + assertFalse(provisioner.completeUpdate(r).applicable()); + assertFalse(r.getAttributes().containsKey(SNAPSHOT)); + r.getAttributes().put(SNAPSHOT, "{}"); + provisioner.clearUpdate(r); + assertFalse(r.getAttributes().containsKey(SNAPSHOT)); + } + // ── Deletes ────────────────────────────────────────────────────────────── @Test