Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cloudformation): provision the AppSync resource types (#3424)

Anders Wasen55ada9b8a39e
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index db2bb8b423..da4c074c44 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -86,6 +86,7 @@ cross-resource references.
| Route 53 | `HostedZone`, `RecordSet` |
| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `ApiKey`, `UsagePlan`, `UsagePlanKey` |
| API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment` |
+| AppSync | `GraphQLApi`, `GraphQLSchema`, `DataSource`, `FunctionConfiguration`, `Resolver`, `ApiKey` |
| Step Functions | `StateMachine` |
| CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` |
| CodeBuild | `Project` |
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 8a25e43d11..4912116ec3 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
@@ -370,6 +370,22 @@ public class AppSyncService {
// ──────────────────────────── Resolvers ────────────────────────────
+ /**
+ * The {@code AppSyncRuntime} shape ({@code {name, runtimeVersion}}) AWS accepts on a resolver
+ * and on a pipeline function alike, or null when the request omits it. Shared so the two paths
+ * cannot drift: a pipeline whose function and resolver disagreed on the runtime would not run.
+ */
+ private Resolver.ResolverRuntime parseRuntime(Object runtimeValue) {
+ Map<String, Object> runtime = castMap(runtimeValue);
+ if (runtime == null) {
+ return null;
+ }
+ Resolver.ResolverRuntime rt = new Resolver.ResolverRuntime();
+ rt.setName(parseEnum(ResolverRuntimeName.class, runtime.get("name")));
+ rt.setRuntimeVersion((String) runtime.get("runtimeVersion"));
+ return rt;
+ }
+
public Resolver createResolver(String apiId, Map<String, Object> request, String region) {
assertSchemaNotBusy(apiId);
getGraphqlApi(apiId);
@@ -378,7 +394,17 @@ public class AppSyncService {
throw new AwsException("BadRequestException", "A resolver field name is required", 400);
}
String dataSourceName = (String) request.get("dataSourceName");
- if (dataSourceName == null || dataSourceName.isBlank()) {
+ ResolverKind kind = parseEnum(ResolverKind.class, request.getOrDefault("kind", "UNIT"));
+ // Only a UNIT resolver names a data source. A PIPELINE resolver reaches its data through the
+ // functions in pipelineConfig, and AWS refuses dataSourceName on one, so requiring it here
+ // made every pipeline resolver unprovisionable: the shape the AppSync JS resolvers that
+ // Serverless and Amplify generate use throughout.
+ if (kind == ResolverKind.PIPELINE) {
+ if (dataSourceName != null && !dataSourceName.isBlank()) {
+ throw new AwsException("BadRequestException",
+ "A PIPELINE resolver cannot specify a data source name", 400);
+ }
+ } else if (dataSourceName == null || dataSourceName.isBlank()) {
throw new AwsException("BadRequestException", "A data source name is required for the resolver", 400);
}
String typeName = (String) request.get("typeName");
@@ -386,7 +412,9 @@ public class AppSyncService {
throw new AwsException("BadRequestException", "A type name is required for the resolver", 400);
}
// Validate data source exists
- getDataSource(apiId, dataSourceName);
+ if (dataSourceName != null && !dataSourceName.isBlank()) {
+ getDataSource(apiId, dataSourceName);
+ }
Resolver resolver = new Resolver();
resolver.setApiId(apiId);
resolver.setTypeName(typeName);
@@ -395,7 +423,7 @@ public class AppSyncService {
resolver.setFunctionId((String) request.get("functionId"));
resolver.setRequestMappingTemplate((String) request.get("requestMappingTemplate"));
resolver.setResponseMappingTemplate((String) request.get("responseMappingTemplate"));
- resolver.setKind(parseEnum(ResolverKind.class, request.getOrDefault("kind", "UNIT")));
+ resolver.setKind(kind);
resolver.setCode((String) request.get("code"));
resolver.setCachingConfig(castMap(request.get("cachingConfig")));
resolver.setMaxBatchSize(castInt(request.get("maxBatchSize")));
@@ -405,13 +433,7 @@ public class AppSyncService {
resolver.setResolverArn(regionResolver.buildArn("appsync", region,
"apis/" + apiId + "/types/" + typeName + "/resolvers/" + fieldName));
- Map<String, Object> runtime = castMap(request.get("runtime"));
- if (runtime != null) {
- Resolver.ResolverRuntime rt = new Resolver.ResolverRuntime();
- rt.setName(parseEnum(ResolverRuntimeName.class, runtime.get("name")));
- rt.setRuntimeVersion((String) runtime.get("runtimeVersion"));
- resolver.setRuntime(rt);
- }
+ resolver.setRuntime(parseRuntime(request.get("runtime")));
String key = resolverKey(apiId, resolver.getTypeName(), resolver.getFieldName());
if (resolverStore.get(key).isPresent()) {
@@ -458,13 +480,7 @@ public class AppSyncService {
if (request.containsKey("metricsConfig")) existing.setMetricsConfig((String) request.get("metricsConfig"));
if (request.containsKey("pipelineConfig")) existing.setPipelineConfig((Map<String, Object>) request.get("pipelineConfig"));
if (request.containsKey("syncConfig")) existing.setSyncConfig((Map<String, Object>) request.get("syncConfig"));
- if (request.containsKey("runtime")) {
- Map<String, Object> runtime = (Map<String, Object>) request.get("runtime");
- Resolver.ResolverRuntime rt = new Resolver.ResolverRuntime();
- rt.setName(parseEnum(ResolverRuntimeName.class, runtime.get("name")));
- rt.setRuntimeVersion((String) runtime.get("runtimeVersion"));
- existing.setRuntime(rt);
- }
+ if (request.containsKey("runtime")) existing.setRuntime(parseRuntime(request.get("runtime")));
resolverStore.put(resolverKey(apiId, typeName, fieldName), existing);
return existing;
}
@@ -498,6 +514,8 @@ public class AppSyncService {
fn.setFunctionVersion((String) request.getOrDefault("functionVersion", "2018-05-29"));
fn.setFunctionArn(buildFunctionArn(apiId, fn.getFunctionId(), region));
fn.setCode((String) request.get("code"));
+ fn.setRuntime(parseRuntime(request.get("runtime")));
+ fn.setMaxBatchSize(castInt(request.get("maxBatchSize")));
functionStore.put(apiKey(apiId, fn.getFunctionId()), fn);
return fn;
@@ -516,12 +534,18 @@ public class AppSyncService {
public FunctionConfiguration updateFunction(String apiId, String functionId, Map<String, Object> request) {
assertSchemaNotBusy(apiId);
FunctionConfiguration existing = getFunction(apiId, functionId);
+ // 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.
+ if (request.containsKey("name")) existing.setName((String) request.get("name"));
if (request.containsKey("description")) existing.setDescription((String) request.get("description"));
if (request.containsKey("dataSourceName")) existing.setDataSourceName((String) request.get("dataSourceName"));
if (request.containsKey("requestMappingTemplate")) existing.setRequestMappingTemplate((String) request.get("requestMappingTemplate"));
if (request.containsKey("responseMappingTemplate")) existing.setResponseMappingTemplate((String) request.get("responseMappingTemplate"));
if (request.containsKey("functionVersion")) existing.setFunctionVersion((String) request.get("functionVersion"));
if (request.containsKey("code")) existing.setCode((String) request.get("code"));
+ if (request.containsKey("runtime")) existing.setRuntime(parseRuntime(request.get("runtime")));
+ if (request.containsKey("maxBatchSize")) existing.setMaxBatchSize(castInt(request.get("maxBatchSize")));
functionStore.put(apiKey(apiId, functionId), existing);
return existing;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/FunctionConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/FunctionConfiguration.java
index 81d78f65dc..156b0812b5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/appsync/model/FunctionConfiguration.java
+++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/FunctionConfiguration.java
@@ -17,6 +17,8 @@ public class FunctionConfiguration {
private String functionVersion;
private String functionArn;
private String code;
+ private Resolver.ResolverRuntime runtime;
+ private Integer maxBatchSize;
public String getFunctionId() { return functionId; }
public void setFunctionId(String functionId) { this.functionId = functionId; }
@@ -44,4 +46,16 @@ public class FunctionConfiguration {
public String getCode() { return code; }
public void setCode(String code) { this.code = code; }
+
+ /**
+ * The runtime a pipeline function's {@code code} is written for, {@code APPSYNC_JS} in
+ * practice. Shares {@link Resolver.ResolverRuntime} with the resolver it runs under: AWS
+ * models the two as the same {@code AppSyncRuntime} shape, and a pipeline whose function
+ * and resolver disagreed on the runtime could not execute.
+ */
+ public Resolver.ResolverRuntime getRuntime() { return runtime; }
+ public void setRuntime(Resolver.ResolverRuntime runtime) { this.runtime = runtime; }
+
+ public Integer getMaxBatchSize() { return maxBatchSize; }
+ public void setMaxBatchSize(Integer maxBatchSize) { this.maxBatchSize = maxBatchSize; }
}
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
new file mode 100644
index 0000000000..fa30eb2cd8
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppSyncCfnProvisioner.java
@@ -0,0 +1,516 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.appsync.AppSyncService;
+import io.github.hectorvent.floci.services.appsync.model.ApiKey;
+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.SchemaCreationStatus;
+import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatusType;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Provisions the AppSync resource types a GraphQL API is deployed from: the API itself, its schema,
+ * data sources, pipeline functions, resolvers and API keys.
+ *
+ * <p><b>Property names are translated, not passed through.</b> Unlike the services whose wire
+ * protocol is already PascalCase, the AppSync control plane is REST-JSON with camelCase members, so
+ * every CloudFormation property is lower-camelised on the way in ({@code AuthenticationType} →
+ * {@code authenticationType}) recursively, including inside nested config objects. One key does not
+ * follow from the rule: {@code DynamoDBConfig} is {@code dynamodbConfig} on the API, not
+ * {@code dynamoDBConfig}.
+ *
+ * <p><b>The schema resource blocks until compilation finishes.</b> {@code StartSchemaCreation} is
+ * asynchronous, and while it is PROCESSING every other AppSync call for that API is refused with a
+ * 409. A template creates the schema and its data sources and resolvers in one stack, so returning
+ * as soon as the job is submitted would fail the resources that follow, non-deterministically,
+ * depending on how fast the worker got there. Waiting for a terminal status is also what
+ * CloudFormation does: {@code AWS::AppSync::GraphQLSchema} is not CREATE_COMPLETE until the schema
+ * is active. A schema that fails to compile fails the resource, with the compiler's own message.
+ *
+ * <p><b>Physical ids follow the registry schemas' primary identifiers</b>, which for most of these
+ * types is an ARN rather than a name: the data source, function and resolver are addressed by
+ * {@code DataSourceArn}, {@code FunctionArn} and {@code ResolverArn}. The API is its {@code ApiId}
+ * and an API key its key id. Because an ARN is not enough to address any of them on the control
+ * plane, the identifying parts ({@code ApiId} plus name, function id, or type/field) are recorded as
+ * attributes at create time and read back on update and delete, hence the
+ * {@code delete(StackResource, String)} override.
+ *
+ * <p><b>Inline definitions only.</b> {@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.
+ */
+@ApplicationScoped
+public class AppSyncCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final Logger LOG = Logger.getLogger(AppSyncCfnProvisioner.class);
+
+ private static final String GRAPHQL_API = "AWS::AppSync::GraphQLApi";
+ private static final String GRAPHQL_SCHEMA = "AWS::AppSync::GraphQLSchema";
+ private static final String DATA_SOURCE = "AWS::AppSync::DataSource";
+ private static final String FUNCTION_CONFIGURATION = "AWS::AppSync::FunctionConfiguration";
+ private static final String RESOLVER = "AWS::AppSync::Resolver";
+ private static final String API_KEY = "AWS::AppSync::ApiKey";
+
+ /** The service's own "already gone", tolerated on delete and nothing else. */
+ private static final String NOT_FOUND = "NotFoundException";
+
+ /**
+ * Properties whose value is a free-form map, not a shape with member names: their keys are data
+ * and must survive verbatim. Lower-camelising them turns an environment variable called
+ * {@code STRIPE_PRODUCT_SMALL_ID} into {@code sTRIPE_PRODUCT_SMALL_ID}, which the API stores
+ * happily and no resolver can then read.
+ */
+ private static final Set<String> OPAQUE_KEY_PROPERTIES = Set.of("EnvironmentVariables");
+
+ /**
+ * 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
+ * as a resource failure rather than left in an unknown state.
+ */
+ private static final long SCHEMA_TIMEOUT_MILLIS = 120_000L;
+ private static final long SCHEMA_POLL_MILLIS = 25L;
+
+ private final AppSyncService appSyncService;
+
+ @Inject
+ public AppSyncCfnProvisioner(AppSyncService appSyncService) {
+ this.appSyncService = appSyncService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(GRAPHQL_API, GRAPHQL_SCHEMA, DATA_SOURCE, FUNCTION_CONFIGURATION, RESOLVER, API_KEY);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ switch (r.getResourceType()) {
+ case GRAPHQL_API -> provisionGraphqlApi(r, props, ctx);
+ case GRAPHQL_SCHEMA -> provisionSchema(r, props, ctx);
+ case DATA_SOURCE -> provisionDataSource(r, props, ctx);
+ case FUNCTION_CONFIGURATION -> provisionFunction(r, props, ctx);
+ case RESOLVER -> provisionResolver(r, props, ctx);
+ case API_KEY -> provisionApiKey(r, props, ctx);
+ default -> throw new IllegalStateException(
+ "AppSyncCfnProvisioner cannot handle " + r.getResourceType());
+ }
+ }
+
+ // ── GraphQLApi ───────────────────────────────────────────────────────────
+
+ private void provisionGraphqlApi(StackResource r, JsonNode props, ProvisionContext ctx) {
+ Map<String, Object> req = camelisedProperties(props, ctx);
+ // Handled separately from the create request: the API's tags arrive as CloudFormation's
+ // [{Key, Value}] list rather than the map the service takes, and its environment variables
+ // are a second call (PutGraphqlApiEnvironmentVariables) rather than a create member.
+ req.remove("tags");
+ Object environmentVariables = req.remove("environmentVariables");
+ Map<String, String> tags = ctx.resolveTags(props, "Tags");
+ // Sent on every update, empty map included: CloudFormation drives a resource to the
+ // template's desired state, so a tag the template no longer declares has to go. Omitting
+ // the member left the old tags in place. On a create an empty map is left out, so a
+ // resource with no tags keeps a null tag map rather than an empty one.
+ if (!tags.isEmpty() || ctx.isUpdate()) {
+ req.put("tags", tags);
+ }
+ if (blank(str(req.get("name")))) {
+ req.put("name", ctx.generatePhysicalName(r.getLogicalId(), 65, false));
+ }
+
+ GraphqlApi api = ctx.isUpdate()
+ ? appSyncService.updateGraphqlApi(ctx.priorPhysicalId(), req, ctx.region())
+ : appSyncService.createGraphqlApi(req, ctx.region());
+
+ Map<String, String> 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);
+ }
+
+ r.setPhysicalId(api.getApiId());
+ r.getAttributes().put("ApiId", api.getApiId());
+ r.getAttributes().put("Arn", api.getArn());
+ Map<String, String> uris = api.getUris() == null ? Map.of() : api.getUris();
+ String graphqlUrl = uris.get("GRAPHQL");
+ String realtimeUrl = uris.get("REALTIME");
+ if (!blank(graphqlUrl)) {
+ r.getAttributes().put("GraphQLUrl", graphqlUrl);
+ // The DNS attributes are the hosts of those two endpoints, which is what they are on
+ // AWS, a custom domain's CNAME target. Derived rather than stored, so they cannot
+ // drift from the URL beside them.
+ r.getAttributes().put("GraphQLDns", host(graphqlUrl));
+ }
+ if (!blank(realtimeUrl)) {
+ r.getAttributes().put("RealtimeUrl", realtimeUrl);
+ r.getAttributes().put("RealtimeDns", host(realtimeUrl));
+ }
+ }
+
+ // ── GraphQLSchema ────────────────────────────────────────────────────────
+
+ private void provisionSchema(StackResource r, JsonNode props, ProvisionContext ctx) {
+ Map<String, Object> req = camelisedProperties(props, ctx);
+ String apiId = requiredApiId(req, GRAPHQL_SCHEMA);
+ String definition = str(req.get("definition"));
+ if (blank(definition)) {
+ if (req.get("definitionS3Location") != null) {
+ throw new AwsException("ValidationError", GRAPHQL_SCHEMA
+ + " DefinitionS3Location is not supported by Floci; give the schema inline in"
+ + " Definition instead.", 400);
+ }
+ throw new AwsException("ValidationError",
+ GRAPHQL_SCHEMA + " requires Definition.", 400);
+ }
+
+ appSyncService.startSchemaCreation(apiId, definition);
+ awaitSchemaCreation(apiId);
+
+ // AWS's own id for the schema resource. Nothing references it, but it has to stay put across
+ // updates, and deriving it from the API id does that without inventing a random one.
+ // The schema resource's own id, which is what the registry schema calls its primary
+ // identifier and its one read-only property.
+ String schemaId = apiId + "GraphQLSchema";
+ r.setPhysicalId(schemaId);
+ r.getAttributes().put("Id", schemaId);
+ r.getAttributes().put("ApiId", apiId);
+ }
+
+ /**
+ * Blocks until the schema reaches a terminal status, and turns a failed compilation into a
+ * failed stack resource. SUCCESS and ACTIVE both mean done: the worker writes SUCCESS, and
+ * ACTIVE is the status a schema loaded from a previous run carries.
+ */
+ private void awaitSchemaCreation(String apiId) {
+ long deadline = System.currentTimeMillis() + SCHEMA_TIMEOUT_MILLIS;
+ while (true) {
+ SchemaCreationStatus status = appSyncService.getSchemaCreationStatus(apiId);
+ SchemaCreationStatusType type = status == null ? null : status.getStatus();
+ if (type == SchemaCreationStatusType.SUCCESS || type == SchemaCreationStatusType.ACTIVE) {
+ return;
+ }
+ if (type == SchemaCreationStatusType.FAILED) {
+ String details = status.getDetails();
+ throw new AwsException("ValidationError", "Schema creation failed for API " + apiId
+ + (blank(details) ? "" : ": " + details), 400);
+ }
+ if (System.currentTimeMillis() >= deadline) {
+ throw new AwsException("ValidationError", "Schema creation for API " + apiId
+ + " did not complete within " + (SCHEMA_TIMEOUT_MILLIS / 1000) + "s (status "
+ + type + ").", 400);
+ }
+ try {
+ Thread.sleep(SCHEMA_POLL_MILLIS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new AwsException("ValidationError",
+ "Interrupted while waiting for schema creation for API " + apiId, 400);
+ }
+ }
+ }
+
+ // ── DataSource ───────────────────────────────────────────────────────────
+
+ private void provisionDataSource(StackResource r, JsonNode props, ProvisionContext ctx) {
+ Map<String, Object> req = camelisedProperties(props, ctx);
+ String apiId = requiredApiId(req, DATA_SOURCE);
+ String name = str(req.get("name"));
+ if (blank(name)) {
+ // Name is create-only, so an unnamed data source must keep the name it already has or a
+ // second UpdateStack would strand the first one, resolvers and all.
+ name = firstNonBlank(attribute(r, "Name"),
+ ctx.generatePhysicalName(r.getLogicalId(), 65, false));
+ req.put("name", name);
+ }
+
+ DataSource ds = reusesEntity(r, ctx, apiId) && name.equals(attribute(r, "Name"))
+ ? appSyncService.updateDataSource(apiId, name, req)
+ : appSyncService.createDataSource(apiId, req, ctx.region());
+
+ r.setPhysicalId(ds.getDataSourceArn());
+ r.getAttributes().put("DataSourceArn", ds.getDataSourceArn());
+ r.getAttributes().put("Name", ds.getName());
+ r.getAttributes().put("ApiId", apiId);
+ }
+
+ // ── FunctionConfiguration ────────────────────────────────────────────────
+
+ private void provisionFunction(StackResource r, JsonNode props, ProvisionContext ctx) {
+ Map<String, Object> req = camelisedProperties(props, ctx);
+ String apiId = requiredApiId(req, FUNCTION_CONFIGURATION);
+ rejectS3Code(req, FUNCTION_CONFIGURATION);
+ if (blank(str(req.get("name")))) {
+ req.put("name", firstNonBlank(attribute(r, "Name"),
+ ctx.generatePhysicalName(r.getLogicalId(), 65, false)));
+ }
+
+ String priorFunctionId = attribute(r, "FunctionId");
+ FunctionConfiguration fn = reusesEntity(r, ctx, apiId) && !blank(priorFunctionId)
+ ? appSyncService.updateFunction(apiId, priorFunctionId, req)
+ : appSyncService.createFunction(apiId, req, ctx.region());
+
+ r.setPhysicalId(fn.getFunctionArn());
+ r.getAttributes().put("FunctionArn", fn.getFunctionArn());
+ r.getAttributes().put("FunctionId", fn.getFunctionId());
+ r.getAttributes().put("Name", fn.getName());
+ if (!blank(fn.getDataSourceName())) {
+ r.getAttributes().put("DataSourceName", fn.getDataSourceName());
+ }
+ r.getAttributes().put("ApiId", apiId);
+ }
+
+ // ── Resolver ─────────────────────────────────────────────────────────────
+
+ private void provisionResolver(StackResource r, JsonNode props, ProvisionContext ctx) {
+ Map<String, Object> req = camelisedProperties(props, ctx);
+ String apiId = requiredApiId(req, RESOLVER);
+ rejectS3Code(req, RESOLVER);
+ String typeName = str(req.get("typeName"));
+ String fieldName = str(req.get("fieldName"));
+ if (blank(typeName) || blank(fieldName)) {
+ throw new AwsException("ValidationError",
+ RESOLVER + " requires TypeName and FieldName.", 400);
+ }
+
+ boolean sameField = typeName.equals(attribute(r, "TypeName"))
+ && fieldName.equals(attribute(r, "FieldName"));
+ Resolver resolver = reusesEntity(r, ctx, apiId) && sameField
+ ? appSyncService.updateResolver(apiId, typeName, fieldName, req)
+ : appSyncService.createResolver(apiId, req, ctx.region());
+
+ r.setPhysicalId(resolver.getResolverArn());
+ r.getAttributes().put("ResolverArn", resolver.getResolverArn());
+ r.getAttributes().put("TypeName", typeName);
+ r.getAttributes().put("FieldName", fieldName);
+ r.getAttributes().put("ApiId", apiId);
+ }
+
+ // ── ApiKey ───────────────────────────────────────────────────────────────
+
+ private void provisionApiKey(StackResource r, JsonNode props, ProvisionContext ctx) {
+ Map<String, Object> req = camelisedProperties(props, ctx);
+ String apiId = requiredApiId(req, API_KEY);
+
+ ApiKey key = reusesEntity(r, ctx, apiId)
+ ? 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
+ // attributes are published: ApiKey is what a client sends as x-api-key.
+ r.getAttributes().put("ApiKey", key.getId());
+ r.getAttributes().put("ApiKeyId", key.getId());
+ r.getAttributes().put("Arn", AwsArnUtils.Arn.of("appsync", ctx.region(), ctx.accountId(),
+ "apis/" + apiId + "/apikeys/" + key.getId()).toString());
+ r.getAttributes().put("ApiId", apiId);
+ }
+
+ // ── Deletes ──────────────────────────────────────────────────────────────
+
+ /**
+ * Every type but the API is addressed by its API id plus a name or id, none of which the ARN
+ * that is the physical id can be split back into reliably, so the delete works from the
+ * attributes recorded at create time.
+ */
+ @Override
+ public void delete(StackResource r, String region) {
+ String physicalId = r.getPhysicalId();
+ if (blank(physicalId)) {
+ return;
+ }
+ String apiId = attribute(r, "ApiId");
+ switch (r.getResourceType()) {
+ case GRAPHQL_API -> CfnDeletes.safeDelete("GraphQL API", physicalId,
+ () -> appSyncService.deleteGraphqlApi(physicalId), NOT_FOUND);
+ // The schema is part of its API and goes when the API does; AWS likewise deletes the
+ // AWS::AppSync::GraphQLSchema resource without a control-plane call of its own.
+ case GRAPHQL_SCHEMA -> { }
+ case DATA_SOURCE -> deleteChild(r, apiId, "data source", attribute(r, "Name"),
+ name -> appSyncService.deleteDataSource(apiId, name));
+ case FUNCTION_CONFIGURATION -> deleteChild(r, apiId, "function",
+ attribute(r, "FunctionId"),
+ functionId -> appSyncService.deleteFunction(apiId, functionId));
+ case RESOLVER -> deleteChild(r, apiId, "resolver",
+ attribute(r, "FieldName"),
+ fieldName -> appSyncService.deleteResolver(apiId, attribute(r, "TypeName"),
+ fieldName));
+ case API_KEY -> deleteChild(r, apiId, "API key", physicalId,
+ keyId -> appSyncService.deleteApiKey(apiId, keyId));
+ default -> LOG.warnv("No delete implemented for {0}", r.getResourceType());
+ }
+ }
+
+ /**
+ * Runs a child delete when the attributes identify one. A resource whose api id or name was
+ * never recorded cannot be deleted by id alone; log it rather than throwing, which would fail a
+ * stack delete over a resource the emulator has no way to find.
+ */
+ private void deleteChild(StackResource r, String apiId, String description, String childId,
+ java.util.function.Consumer<String> delete) {
+ if (blank(apiId) || blank(childId)) {
+ LOG.warnv("Cannot delete AppSync {0} for {1}: no recorded api id/name, it is not removed",
+ description, r.getLogicalId());
+ return;
+ }
+ CfnDeletes.safeDelete("AppSync " + description, childId, () -> delete.accept(childId), NOT_FOUND);
+ }
+
+ // ── Helpers ──────────────────────────────────────────────────────────────
+
+ /**
+ * Whether this provision should update the entity the resource already points at rather than
+ * create a new one. An API id that changed means the resource was moved to a different API,
+ * which is a replacement: the old entity lives in an API this resource no longer names.
+ */
+ private boolean reusesEntity(StackResource r, ProvisionContext ctx, String apiId) {
+ return ctx.isUpdate() && apiId.equals(attribute(r, "ApiId"));
+ }
+
+ private void rejectS3Code(Map<String, Object> req, String resourceType) {
+ if (req.get("codeS3Location") != null) {
+ throw new AwsException("ValidationError", resourceType
+ + " CodeS3Location is not supported by Floci; give the resolver code inline in"
+ + " Code instead.", 400);
+ }
+ }
+
+ private String requiredApiId(Map<String, Object> req, String resourceType) {
+ String apiId = str(req.remove("apiId"));
+ if (blank(apiId)) {
+ throw new AwsException("ValidationError", resourceType + " requires ApiId.", 400);
+ }
+ return apiId;
+ }
+
+ /**
+ * The resource's properties with intrinsics resolved and every key lower-camelised into the
+ * member name the AppSync control plane uses.
+ */
+ private Map<String, Object> camelisedProperties(JsonNode props, ProvisionContext ctx) {
+ if (props == null || props.isNull() || props.isMissingNode()) {
+ return new LinkedHashMap<>();
+ }
+ JsonNode resolved = ctx.engine().resolveNode(props);
+ Map<String, Object> req = new LinkedHashMap<>();
+ if (resolved == null || !resolved.isObject()) {
+ return req;
+ }
+ Iterator<Map.Entry<String, JsonNode>> fields = resolved.fields();
+ while (fields.hasNext()) {
+ Map.Entry<String, JsonNode> field = fields.next();
+ // The property name is always translated; whether the names *inside* it are depends on
+ // whether they are member names or somebody's data.
+ req.put(apiMemberName(field.getKey()),
+ toApiValue(field.getValue(), !OPAQUE_KEY_PROPERTIES.contains(field.getKey())));
+ }
+ return req;
+ }
+
+ /**
+ * Recursively converts a resolved property node to the Java value the service expects,
+ * translating nested object keys into API member names when {@code cameliseKeys} says they are
+ * member names rather than free-form data.
+ */
+ private Object toApiValue(JsonNode node, boolean cameliseKeys) {
+ if (node == null || node.isNull() || node.isMissingNode()) {
+ return null;
+ }
+ if (node.isObject()) {
+ Map<String, Object> map = new LinkedHashMap<>();
+ Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
+ while (fields.hasNext()) {
+ Map.Entry<String, JsonNode> field = fields.next();
+ String key = cameliseKeys ? apiMemberName(field.getKey()) : field.getKey();
+ map.put(key, toApiValue(field.getValue(), cameliseKeys));
+ }
+ return map;
+ }
+ if (node.isArray()) {
+ List<Object> list = new ArrayList<>();
+ node.forEach(element -> list.add(toApiValue(element, cameliseKeys)));
+ return list;
+ }
+ if (node.isBoolean()) {
+ return node.booleanValue();
+ }
+ if (node.isIntegralNumber()) {
+ return node.longValue();
+ }
+ if (node.isNumber()) {
+ return node.doubleValue();
+ }
+ return node.asText();
+ }
+
+ /**
+ * The AppSync member name for a CloudFormation property name: the same identifier with a
+ * lower-case first letter, bar the one place AWS does not follow its own rule.
+ */
+ private static String apiMemberName(String property) {
+ if (property == null || property.isEmpty()) {
+ return property;
+ }
+ // AWS::AppSync::DataSource's DynamoDBConfig is dynamodbConfig on the API: lower-camelising
+ // it would produce dynamoDBConfig and the whole table config would be dropped on the floor.
+ if ("DynamoDBConfig".equals(property)) {
+ return "dynamodbConfig";
+ }
+ return Character.toLowerCase(property.charAt(0)) + property.substring(1);
+ }
+
+ private static Map<String, String> stringMap(Object value) {
+ if (!(value instanceof Map<?, ?> map)) {
+ return null;
+ }
+ Map<String, String> strings = new LinkedHashMap<>();
+ map.forEach((k, v) -> strings.put(String.valueOf(k), v == null ? "" : String.valueOf(v)));
+ return strings;
+ }
+
+ private static String attribute(StackResource r, String name) {
+ return r.getAttributes() == null ? null : r.getAttributes().get(name);
+ }
+
+ private static String host(String url) {
+ if (blank(url)) {
+ return null;
+ }
+ try {
+ return URI.create(url).getHost();
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ private static String firstNonBlank(String preferred, String fallback) {
+ return blank(preferred) ? fallback : preferred;
+ }
+
+ private static String str(Object value) {
+ return value == null ? null : String.valueOf(value);
+ }
+
+ private static boolean blank(String value) {
+ return value == null || value.isBlank();
+ }
+}
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 a1b3da8cbb..c2272f103c 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
@@ -50,6 +50,23 @@ class AppSyncServiceTest {
service = newService(Clock.fixed(NOW, ZoneOffset.UTC));
}
+ @Test
+ void updateFunctionAppliesANewName() {
+ GraphqlApi api = service.createGraphqlApi(
+ Map.of("name", "rename", "authenticationType", "API_KEY"), "us-east-1");
+ service.createDataSource(api.getApiId(), Map.of("name", "ds", "type", "NONE"), "us-east-1");
+ var created = service.createFunction(api.getApiId(),
+ Map.of("name", "Query_getMessages_0", "dataSourceName", "ds"), "us-east-1");
+
+ service.updateFunction(api.getApiId(), created.getFunctionId(),
+ Map.of("name", "Query_getMessages_1"));
+
+ // UpdateFunction takes a new name on AWS, and a CloudFormation rename goes through it:
+ // ignoring the member let a stack complete while GetFunction still reported the old name.
+ assertEquals("Query_getMessages_1",
+ service.getFunction(api.getApiId(), created.getFunctionId()).getName());
+ }
+
@Test
void validateApiKeyLooksUpByValue() {
GraphqlApi api = service.createGraphqlApi(Map.of("name", "a", "authenticationType", "API_KEY"), "us-east-1");
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
new file mode 100644
index 0000000000..15c839e071
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AppSyncCfnIntegrationTest.java
@@ -0,0 +1,279 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.ValidatableResponse;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+
+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.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * Deploys the AppSync shape a Serverless Framework {@code appSync:} block compiles to: an API with
+ * inline schema, a DynamoDB and a relational data source, an {@code APPSYNC_JS} pipeline function
+ * and the PIPELINE resolver that calls it, plus an API key, and asserts the control plane really
+ * holds them.
+ *
+ * <p>The point of going through a stack rather than the provisioner alone is the ordering: the data
+ * sources and resolvers are created behind the schema, whose compilation is asynchronous and locks
+ * the API while it runs. It also pins the two {@code Fn::GetAtt} attributes such a template is
+ * built on, {@code GraphQlApi.ApiId} and {@code FunctionConfiguration.FunctionId}: an unset
+ * attribute resolves to the literal string {@code "LogicalId.Attr"} and every dependent resource
+ * would then be wired to that text instead of an id.
+ */
+@QuarkusTest
+class AppSyncCfnIntegrationTest {
+
+ private static final String CFN_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
+ 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 TEMPLATE = """
+ {
+ "Parameters": {"FieldLogLevel": {"Type": "String"}},
+ "Resources": {
+ "GraphQlApi": {
+ "Type": "AWS::AppSync::GraphQLApi",
+ "Properties": {
+ "Name": "appsync-cfn-it-api",
+ "AuthenticationType": "API_KEY",
+ "XrayEnabled": false,
+ "EnvironmentVariables": {"STRIPE_PRODUCT_SMALL_ID": "prod_small"},
+ "LogConfig": {"FieldLogLevel": {"Ref": "FieldLogLevel"}}
+ }
+ },
+ "GraphQlSchema": {
+ "Type": "AWS::AppSync::GraphQLSchema",
+ "Properties": {
+ "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
+ "Definition": "type Message { id: ID! } type Query { getMessages: [Message] }"
+ }
+ },
+ "GraphQlDsAuthKeys": {
+ "Type": "AWS::AppSync::DataSource",
+ "DependsOn": "GraphQlSchema",
+ "Properties": {
+ "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
+ "Name": "publicApiAuthKeysTable",
+ "Type": "AMAZON_DYNAMODB",
+ "DynamoDBConfig": {
+ "AwsRegion": {"Ref": "AWS::Region"},
+ "TableName": "appsync-cfn-it-auth-keys",
+ "UseCallerCredentials": false
+ }
+ }
+ },
+ "GraphQlDsAccountDb": {
+ "Type": "AWS::AppSync::DataSource",
+ "DependsOn": "GraphQlSchema",
+ "Properties": {
+ "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
+ "Name": "accountDB",
+ "Type": "RELATIONAL_DATABASE",
+ "RelationalDatabaseConfig": {
+ "RelationalDatabaseSourceType": "RDS_HTTP_ENDPOINT",
+ "RdsHttpEndpointConfig": {
+ "AwsRegion": {"Ref": "AWS::Region"},
+ "DbClusterIdentifier": "appsync-cfn-it-cluster",
+ "DatabaseName": "accountdb",
+ "AwsSecretStoreArn": "arn:aws:secretsmanager:us-east-1:000000000000:secret:db"
+ }
+ }
+ }
+ },
+ "GraphQlFnGetMessages": {
+ "Type": "AWS::AppSync::FunctionConfiguration",
+ "Properties": {
+ "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
+ "Name": "Query_getMessages_0",
+ "DataSourceName": {"Fn::GetAtt": ["GraphQlDsAccountDb", "Name"]},
+ "FunctionVersion": "2018-05-29",
+ "Runtime": {"Name": "APPSYNC_JS", "RuntimeVersion": "1.0.0"},
+ "Code": "export function request(ctx) { return {}; }"
+ }
+ },
+ "GraphQlResolverQuerygetMessages": {
+ "Type": "AWS::AppSync::Resolver",
+ "Properties": {
+ "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
+ "TypeName": "Query",
+ "FieldName": "getMessages",
+ "Kind": "PIPELINE",
+ "Runtime": {"Name": "APPSYNC_JS", "RuntimeVersion": "1.0.0"},
+ "Code": "export function response(ctx) { return ctx.prev.result; }",
+ "PipelineConfig": {
+ "Functions": [{"Fn::GetAtt": ["GraphQlFnGetMessages", "FunctionId"]}]
+ }
+ }
+ },
+ "GraphQlApiKey": {
+ "Type": "AWS::AppSync::ApiKey",
+ "Properties": {
+ "ApiId": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]},
+ "Description": "integration"
+ }
+ }
+ },
+ "Outputs": {
+ "ApiId": {"Value": {"Fn::GetAtt": ["GraphQlApi", "ApiId"]}},
+ "ApiRef": {"Value": {"Ref": "GraphQlApi"}},
+ "GraphQLUrl": {"Value": {"Fn::GetAtt": ["GraphQlApi", "GraphQLUrl"]}},
+ "DataSourceName": {"Value": {"Fn::GetAtt": ["GraphQlDsAccountDb", "Name"]}},
+ "FunctionId": {"Value": {"Fn::GetAtt": ["GraphQlFnGetMessages", "FunctionId"]}},
+ "ApiKey": {"Value": {"Fn::GetAtt": ["GraphQlApiKey", "ApiKey"]}}
+ }
+ }
+ """;
+
+ @Test
+ void createUpdateAndDeleteAnAppSyncApi() throws InterruptedException {
+ cloudFormation("CreateStack", Map.of("FieldLogLevel", "ERROR"));
+ String created = describeStacks("CREATE_COMPLETE");
+
+ String apiId = outputValue(created, "ApiId");
+ String functionId = outputValue(created, "FunctionId");
+ String apiKey = outputValue(created, "ApiKey");
+
+ // Every dependent resource is wired through these; the literal "LogicalId.Attr" is what an
+ // unset attribute yields, so a real id is the assertion that matters.
+ assertNotEquals("GraphQlApi.ApiId", apiId);
+ assertNotEquals("GraphQlFnGetMessages.FunctionId", functionId);
+ assertEquals(apiId, outputValue(created, "ApiRef"));
+ assertEquals("accountDB", outputValue(created, "DataSourceName"));
+ assertTrue(outputValue(created, "GraphQLUrl").contains(apiId),
+ "GraphQLUrl should address the api: " + outputValue(created, "GraphQLUrl"));
+
+ appSync("/v1/apis/" + apiId)
+ .statusCode(200)
+ .body("graphqlApi.name", equalTo("appsync-cfn-it-api"))
+ .body("graphqlApi.authenticationType", equalTo("API_KEY"))
+ .body("graphqlApi.logConfig.fieldLogLevel", equalTo("ERROR"));
+
+ // The schema resource waits for compilation, so by the time the stack completes the SDL is
+ // queryable rather than still PROCESSING.
+ appSync("/v1/apis/" + apiId + "/schemacreation").statusCode(200).body("status", equalTo("SUCCESS"));
+
+ // Free-form map: the variable names are data and must not be camelised into oblivion.
+ appSync("/v1/apis/" + apiId + "/environmentVariables")
+ .statusCode(200)
+ .body("environmentVariables.STRIPE_PRODUCT_SMALL_ID", equalTo("prod_small"));
+
+ appSync("/v1/apis/" + apiId + "/datasources/publicApiAuthKeysTable")
+ .statusCode(200)
+ .body("dataSource.type", equalTo("AMAZON_DYNAMODB"))
+ // dynamodbConfig, not dynamoDBConfig: the one member AWS does not lower-camelise.
+ .body("dataSource.dynamodbConfig.tableName", equalTo("appsync-cfn-it-auth-keys"));
+
+ appSync("/v1/apis/" + apiId + "/datasources/accountDB")
+ .statusCode(200)
+ .body("dataSource.type", equalTo("RELATIONAL_DATABASE"))
+ .body("dataSource.relationalDatabaseConfig.rdsHttpEndpointConfig.dbClusterIdentifier",
+ equalTo("appsync-cfn-it-cluster"))
+ .body("dataSource.relationalDatabaseConfig.rdsHttpEndpointConfig.databaseName",
+ equalTo("accountdb"));
+
+ appSync("/v1/apis/" + apiId + "/functions/" + functionId)
+ .statusCode(200)
+ .body("functionConfiguration.name", equalTo("Query_getMessages_0"))
+ .body("functionConfiguration.dataSourceName", equalTo("accountDB"))
+ .body("functionConfiguration.runtime.name", equalTo("APPSYNC_JS"));
+
+ // A PIPELINE resolver names no data source and reaches its data through the function above.
+ appSync("/v1/apis/" + apiId + "/types/Query/resolvers/getMessages")
+ .statusCode(200)
+ .body("resolver.kind", equalTo("PIPELINE"))
+ .body("resolver.pipelineConfig.functions[0]", equalTo(functionId))
+ .body("resolver.runtime.name", equalTo("APPSYNC_JS"))
+ .body("resolver.code", notNullValue());
+
+ assertNotEquals("GraphQlApiKey.ApiKey", apiKey);
+ appSync("/v1/apis/" + apiId + "/apikeys")
+ .statusCode(200)
+ .body("apiKeys[0].id", equalTo(apiKey))
+ .body("apiKeys[0].description", equalTo("integration"));
+
+ cloudFormation("UpdateStack", Map.of("FieldLogLevel", "ALL"));
+ String updated = describeStacks("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.
+ assertEquals(apiId, outputValue(updated, "ApiId"));
+ assertEquals(functionId, outputValue(updated, "FunctionId"));
+ appSync("/v1/apis/" + apiId).statusCode(200).body("graphqlApi.logConfig.fieldLogLevel", equalTo("ALL"));
+ appSync("/v1/apis/" + apiId + "/types/Query/resolvers/getMessages")
+ .statusCode(200)
+ .body("resolver.pipelineConfig.functions[0]", equalTo(functionId));
+
+ cloudFormation("DeleteStack", Map.of());
+ awaitStackDeleted();
+
+ appSync("/v1/apis/" + apiId).statusCode(404);
+ }
+
+ private static void cloudFormation(String action, Map<String, String> 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);
+ }
+ int index = 1;
+ for (Map.Entry<String, String> parameter : parameters.entrySet()) {
+ request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());
+ request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());
+ index++;
+ }
+ 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)
+ .when().post("/").then().statusCode(200)
+ .body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
+ .extract().asString();
+ }
+
+ private static void awaitStackDeleted() throws InterruptedException {
+ for (int i = 0; i < 200; i++) {
+ String body = given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", STACK)
+ .when().post("/").then().extract().asString();
+ if (body.contains("does not exist")) {
+ return;
+ }
+ if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
+ fail("stack delete failed: " + body);
+ }
+ Thread.sleep(50);
+ }
+ fail("stack " + STACK + " was not deleted within the timeout");
+ }
+
+ private static String outputValue(String xml, String key) {
+ return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
+ }
+
+ private static ValidatableResponse appSync(String path) {
+ return given().header("Authorization", APPSYNC_AUTH).when().get(path).then();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
index 33c9dee042..e84bcdd307 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.acm.AcmService;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.backup.BackupService;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
+import io.github.hectorvent.floci.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
@@ -33,6 +34,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScali
import io.github.hectorvent.floci.services.cloudformation.provisioners.BackupVaultCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.BatchCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsCfnProvisioner;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.AppSyncCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudTrailCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner;
@@ -137,6 +139,7 @@ final class CfnProvisionerFixture {
private SnsService snsService;
private DynamoDbService dynamoDbService;
private LambdaService lambdaService;
+ private AppSyncService appSyncService;
private IamService iamService;
private SsmService ssmService;
private KmsService kmsService;
@@ -284,6 +287,9 @@ final class CfnProvisionerFixture {
if (acmService != null) {
discovered.add(new AcmCfnProvisioner(acmService));
}
+ if (appSyncService != null) {
+ discovered.add(new AppSyncCfnProvisioner(appSyncService));
+ }
if (lambdaService != null) {
discovered.add(new LambdaAddressingCfnProvisioner(lambdaService));
discovered.add(new LambdaEventInvokeConfigCfnProvisioner(lambdaService));
@@ -372,6 +378,11 @@ final class CfnProvisionerFixture {
return this;
}
+ public Builder appSync(AppSyncService v) {
+ this.appSyncService = v;
+ return this;
+ }
+
public Builder iam(IamService v) {
this.iamService = v;
return this;
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
new file mode 100644
index 0000000000..4b73565887
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppSyncCfnProvisionerTest.java
@@ -0,0 +1,713 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+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.model.ApiKey;
+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.SchemaCreationStatus;
+import io.github.hectorvent.floci.services.appsync.model.SchemaCreationStatusType;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.HashMap;
+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;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+/** The AppSync CFN provisioner in isolation, with only AppSyncService mocked. */
+class AppSyncCfnProvisionerTest {
+
+ private static final String API_ID = "abcd1234";
+
+ private final AppSyncService appSync = mock(AppSyncService.class);
+ private final AppSyncCfnProvisioner provisioner = new AppSyncCfnProvisioner(appSync);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private ProvisionContext ctx() {
+ // Identity resolution: these templates carry no intrinsics, and resolveNode's contract for
+ // an intrinsic-free node is to hand it back unchanged.
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null || node.isNull() ? null : node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ return new ProvisionContext(engine, "eu-west-1", "000000000000", "my-stack");
+ }
+
+ private ProvisionContext updateCtx(String priorPhysicalId) {
+ ProvisionContext create = ctx();
+ return new ProvisionContext(create.engine(), create.region(), create.accountId(),
+ create.stackName(), priorPhysicalId);
+ }
+
+ private StackResource resource(String type, String logicalId) {
+ StackResource r = new StackResource();
+ r.setLogicalId(logicalId);
+ r.setResourceType(type);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+
+ private GraphqlApi api() {
+ GraphqlApi api = new GraphqlApi();
+ api.setApiId(API_ID);
+ api.setName("account-api");
+ api.setArn("arn:aws:appsync:eu-west-1:000000000000:apis/" + API_ID);
+ api.setUris(Map.of(
+ "GRAPHQL", "http://localhost:4566/v1/apis/" + API_ID + "/graphql",
+ "REALTIME", "ws://localhost:4566/v1/apis/" + API_ID + "/graphql/realtime"));
+ return api;
+ }
+
+ private void schemaCompletesImmediately() {
+ SchemaCreationStatus success = new SchemaCreationStatus();
+ success.setStatus(SchemaCreationStatusType.SUCCESS);
+ when(appSync.getSchemaCreationStatus(API_ID)).thenReturn(success);
+ }
+
+ /** The request the provisioner handed CreateGraphqlApi. */
+ @SuppressWarnings("unchecked")
+ private Map<String, Object> capturedApiRequest() {
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(appSync).createGraphqlApi(captor.capture(), eq("eu-west-1"));
+ return captor.getValue();
+ }
+
+ @Test
+ void anUpdateThatDroppedTagsClearsThem() {
+ when(appSync.updateGraphqlApi(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(api());
+ StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi");
+ ObjectNode props = mapper.createObjectNode()
+ .put("Name", "account-api")
+ .put("AuthenticationType", "API_KEY");
+
+ provisioner.provision(r, props, updateCtx(API_ID));
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(appSync).updateGraphqlApi(eq(API_ID), captor.capture(), eq("eu-west-1"));
+ // The service only touches tags when the member is present, so an omitted one left the
+ // previous tags on an API the template no longer tags at all.
+ assertEquals(Map.of(), captor.getValue().get("tags"));
+ }
+
+ @Test
+ void aCreateWithNoTagsSendsNoTagsMember() {
+ when(appSync.createGraphqlApi(any(), eq("eu-west-1"))).thenReturn(api());
+ StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi");
+
+ provisioner.provision(r, mapper.createObjectNode()
+ .put("Name", "account-api")
+ .put("AuthenticationType", "API_KEY"), ctx());
+
+ // Nothing to drive to on a create: an untagged API keeps a null tag map, not an empty one.
+ assertFalse(capturedApiRequest().containsKey("tags"));
+ }
+
+ @Test
+ void anUpdateThatDroppedEnvironmentVariablesClearsThem() {
+ when(appSync.updateGraphqlApi(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(api());
+ StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi");
+
+ provisioner.provision(r, mapper.createObjectNode()
+ .put("Name", "account-api")
+ .put("AuthenticationType", "API_KEY"), updateCtx(API_ID));
+
+ // PutGraphqlApiEnvironmentVariables replaces the whole set, so the empty map is what clears
+ // it; skipping the call left variables the template dropped readable by every resolver.
+ verify(appSync).putEnvironmentVariables(API_ID, Map.of());
+ }
+
+ @Test
+ void aCreateWithNoEnvironmentVariablesMakesNoCall() {
+ when(appSync.createGraphqlApi(any(), eq("eu-west-1"))).thenReturn(api());
+ StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi");
+
+ provisioner.provision(r, mapper.createObjectNode()
+ .put("Name", "account-api")
+ .put("AuthenticationType", "API_KEY"), ctx());
+
+ verify(appSync, never()).putEnvironmentVariables(anyString(), any());
+ }
+
+ // ── GraphQLApi ───────────────────────────────────────────────────────────
+
+ @Test
+ void graphqlApiSetsPhysicalIdAndGetAttAttributes() {
+ when(appSync.createGraphqlApi(any(), eq("eu-west-1"))).thenReturn(api());
+ StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi");
+ ObjectNode props = mapper.createObjectNode()
+ .put("Name", "account-api")
+ .put("AuthenticationType", "API_KEY")
+ .put("XrayEnabled", false);
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals(API_ID, r.getPhysicalId());
+ assertEquals(API_ID, r.getAttributes().get("ApiId"));
+ assertEquals("arn:aws:appsync:eu-west-1:000000000000:apis/" + API_ID, r.getAttributes().get("Arn"));
+ assertEquals("http://localhost:4566/v1/apis/" + API_ID + "/graphql",
+ r.getAttributes().get("GraphQLUrl"));
+ assertEquals("ws://localhost:4566/v1/apis/" + API_ID + "/graphql/realtime",
+ r.getAttributes().get("RealtimeUrl"));
+ // The DNS attributes are the endpoints' hosts, which is what a custom domain aliases.
+ assertEquals("localhost", r.getAttributes().get("GraphQLDns"));
+ assertEquals("localhost", r.getAttributes().get("RealtimeDns"));
+ }
+
+ @Test
+ void graphqlApiLowerCamelisesPropertiesForTheApi() {
+ when(appSync.createGraphqlApi(any(), eq("eu-west-1"))).thenReturn(api());
+ StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi");
+ ObjectNode props = mapper.createObjectNode()
+ .put("Name", "account-api")
+ .put("AuthenticationType", "API_KEY")
+ .put("XrayEnabled", false);
+ ObjectNode logConfig = props.putObject("LogConfig");
+ logConfig.put("CloudWatchLogsRoleArn", "arn:aws:iam::000000000000:role/logs");
+ logConfig.put("FieldLogLevel", "ALL");
+ ObjectNode oidc = props.putArray("AdditionalAuthenticationProviders").addObject();
+ oidc.put("AuthenticationType", "OPENID_CONNECT");
+ oidc.putObject("OpenIDConnectConfig").put("Issuer", "https://issuer").put("ClientId", "cid");
+
+ provisioner.provision(r, props, ctx());
+
+ Map<String, Object> request = capturedApiRequest();
+ assertEquals("account-api", request.get("name"));
+ assertEquals("API_KEY", request.get("authenticationType"));
+ assertEquals(Boolean.FALSE, request.get("xrayEnabled"));
+ Map<?, ?> resolvedLog = (Map<?, ?>) request.get("logConfig");
+ assertEquals("arn:aws:iam::000000000000:role/logs", resolvedLog.get("cloudWatchLogsRoleArn"));
+ assertEquals("ALL", resolvedLog.get("fieldLogLevel"));
+ Map<?, ?> provider = (Map<?, ?>) ((List<?>) request.get("additionalAuthenticationProviders")).get(0);
+ assertEquals("OPENID_CONNECT", provider.get("authenticationType"));
+ // AWS keeps the acronym capitalised in this member name; the model's field is openIDConnectConfig.
+ assertEquals("https://issuer", ((Map<?, ?>) provider.get("openIDConnectConfig")).get("issuer"));
+ }
+
+ @Test
+ void graphqlApiEnvironmentVariablesGoThroughTheirOwnCall() {
+ when(appSync.createGraphqlApi(any(), eq("eu-west-1"))).thenReturn(api());
+ StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi");
+ ObjectNode props = mapper.createObjectNode()
+ .put("Name", "account-api")
+ .put("AuthenticationType", "API_KEY");
+ props.putObject("EnvironmentVariables").put("STRIPE_PRODUCT_SMALL_ID", "prod_1");
+
+ provisioner.provision(r, props, ctx());
+
+ // CreateGraphqlApi has no environment-variable member: it is PutGraphqlApiEnvironmentVariables.
+ assertFalse(capturedApiRequest().containsKey("environmentVariables"));
+ verify(appSync).putEnvironmentVariables(API_ID, Map.of("STRIPE_PRODUCT_SMALL_ID", "prod_1"));
+ }
+
+ @Test
+ void graphqlApiUpdateUpdatesInPlace() {
+ when(appSync.updateGraphqlApi(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(api());
+ StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi");
+ ObjectNode props = mapper.createObjectNode()
+ .put("Name", "account-api")
+ .put("AuthenticationType", "AWS_IAM");
+
+ provisioner.provision(r, props, updateCtx(API_ID));
+
+ verify(appSync).updateGraphqlApi(eq(API_ID), any(), eq("eu-west-1"));
+ verify(appSync, never()).createGraphqlApi(any(), anyString());
+ assertEquals(API_ID, r.getPhysicalId());
+ }
+
+ // ── GraphQLSchema ────────────────────────────────────────────────────────
+
+ @Test
+ void schemaWaitsForCompilationBeforeCompleting() {
+ SchemaCreationStatus processing = new SchemaCreationStatus();
+ processing.setStatus(SchemaCreationStatusType.PROCESSING);
+ SchemaCreationStatus success = new SchemaCreationStatus();
+ success.setStatus(SchemaCreationStatusType.SUCCESS);
+ when(appSync.getSchemaCreationStatus(API_ID)).thenReturn(processing, processing, success);
+ StackResource r = resource("AWS::AppSync::GraphQLSchema", "GraphQlSchema");
+ ObjectNode props = mapper.createObjectNode()
+ .put("ApiId", API_ID)
+ .put("Definition", "type Query { ping: String }");
+
+ provisioner.provision(r, props, ctx());
+
+ verify(appSync).startSchemaCreation(API_ID, "type Query { ping: String }");
+ // Every AppSync call for the API is refused with a 409 while the schema is PROCESSING, so a
+ // provision that returned early would fail the data sources and resolvers behind it.
+ verify(appSync, org.mockito.Mockito.times(3)).getSchemaCreationStatus(API_ID);
+ assertEquals(API_ID + "GraphQLSchema", r.getPhysicalId());
+ assertEquals(API_ID, r.getAttributes().get("ApiId"));
+ }
+
+ @Test
+ void schemaCompilationFailureFailsTheResource() {
+ SchemaCreationStatus failed = new SchemaCreationStatus();
+ failed.setStatus(SchemaCreationStatusType.FAILED);
+ failed.setDetails("Unknown type Widget");
+ when(appSync.getSchemaCreationStatus(API_ID)).thenReturn(failed);
+ StackResource r = resource("AWS::AppSync::GraphQLSchema", "GraphQlSchema");
+ ObjectNode props = mapper.createObjectNode().put("ApiId", API_ID).put("Definition", "type Q { a: Widget }");
+
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+
+ assertTrue(e.getMessage().contains("Unknown type Widget"), e.getMessage());
+ }
+
+ @Test
+ void schemaFromS3IsRefusedRatherThanSilentlyEmpty() {
+ StackResource r = resource("AWS::AppSync::GraphQLSchema", "GraphQlSchema");
+ ObjectNode props = mapper.createObjectNode().put("ApiId", API_ID);
+ props.putObject("DefinitionS3Location").put("Bucket", "b").put("Key", "schema.graphql");
+
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+
+ assertTrue(e.getMessage().contains("DefinitionS3Location"), e.getMessage());
+ verify(appSync, never()).startSchemaCreation(anyString(), anyString());
+ }
+
+ @Test
+ void schemaWithoutApiIdIsRefused() {
+ StackResource r = resource("AWS::AppSync::GraphQLSchema", "GraphQlSchema");
+ ObjectNode props = mapper.createObjectNode().put("Definition", "type Query { ping: String }");
+
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+ verifyNoInteractions(appSync);
+ }
+
+ // ── DataSource ───────────────────────────────────────────────────────────
+
+ @Test
+ void dataSourceKeepsAwsSpellingOfDynamodbConfig() {
+ DataSource ds = new DataSource();
+ ds.setName("publicApiAuthKeysTable");
+ ds.setDataSourceArn("arn:aws:appsync:eu-west-1:000000000000:apis/" + API_ID
+ + "/datasources/publicApiAuthKeysTable");
+ when(appSync.createDataSource(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(ds);
+ StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDsAuthKeys");
+ ObjectNode props = mapper.createObjectNode()
+ .put("ApiId", API_ID)
+ .put("Name", "publicApiAuthKeysTable")
+ .put("Type", "AMAZON_DYNAMODB")
+ .put("ServiceRoleArn", "arn:aws:iam::000000000000:role/ds");
+ props.putObject("DynamoDBConfig")
+ .put("AwsRegion", "eu-west-1")
+ .put("TableName", "qip-local-public-api-auth-keys")
+ .put("UseCallerCredentials", false);
+
+ provisioner.provision(r, props, ctx());
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(appSync).createDataSource(eq(API_ID), captor.capture(), eq("eu-west-1"));
+ Map<String, Object> request = captor.getValue();
+ // dynamoDBConfig, what the plain lower-camel rule would produce, is silently ignored by
+ // the service, leaving a DynamoDB data source with no table.
+ assertNull(request.get("dynamoDBConfig"));
+ Map<?, ?> dynamodb = (Map<?, ?>) request.get("dynamodbConfig");
+ assertEquals("qip-local-public-api-auth-keys", dynamodb.get("tableName"));
+ assertEquals("eu-west-1", dynamodb.get("awsRegion"));
+ assertEquals(Boolean.FALSE, dynamodb.get("useCallerCredentials"));
+ assertEquals("arn:aws:iam::000000000000:role/ds", request.get("serviceRoleArn"));
+ // The ApiId is a path parameter, not a member of the request body.
+ assertFalse(request.containsKey("apiId"));
+
+ assertEquals(ds.getDataSourceArn(), r.getPhysicalId());
+ assertEquals(ds.getDataSourceArn(), r.getAttributes().get("DataSourceArn"));
+ assertEquals("publicApiAuthKeysTable", r.getAttributes().get("Name"));
+ assertEquals(API_ID, r.getAttributes().get("ApiId"));
+ }
+
+ @Test
+ void dataSourceCamelisesNestedRelationalConfig() {
+ DataSource ds = new DataSource();
+ ds.setName("accountDB");
+ ds.setDataSourceArn("arn:ds");
+ when(appSync.createDataSource(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(ds);
+ StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb");
+ ObjectNode props = mapper.createObjectNode()
+ .put("ApiId", API_ID)
+ .put("Name", "accountDB")
+ .put("Type", "RELATIONAL_DATABASE");
+ ObjectNode relational = props.putObject("RelationalDatabaseConfig");
+ relational.put("RelationalDatabaseSourceType", "RDS_HTTP_ENDPOINT");
+ relational.putObject("RdsHttpEndpointConfig")
+ .put("AwsRegion", "eu-west-1")
+ .put("DbClusterIdentifier", "ls-db-cluster")
+ .put("DatabaseName", "accountdb")
+ .put("AwsSecretStoreArn", "arn:aws:secretsmanager:eu-west-1:000000000000:secret:db");
+
+ provisioner.provision(r, props, ctx());
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(appSync).createDataSource(eq(API_ID), captor.capture(), eq("eu-west-1"));
+ Map<?, ?> config = (Map<?, ?>) captor.getValue().get("relationalDatabaseConfig");
+ assertEquals("RDS_HTTP_ENDPOINT", config.get("relationalDatabaseSourceType"));
+ Map<?, ?> rds = (Map<?, ?>) config.get("rdsHttpEndpointConfig");
+ assertEquals("ls-db-cluster", rds.get("dbClusterIdentifier"));
+ assertEquals("accountdb", rds.get("databaseName"));
+ assertEquals("arn:aws:secretsmanager:eu-west-1:000000000000:secret:db", rds.get("awsSecretStoreArn"));
+ }
+
+ @Test
+ void dataSourceUpdateReusesTheNameItAlreadyHas() {
+ 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");
+ ObjectNode props = mapper.createObjectNode()
+ .put("ApiId", API_ID)
+ .put("Name", "accountDB")
+ .put("Type", "RELATIONAL_DATABASE");
+
+ provisioner.provision(r, props, updateCtx("arn:ds"));
+
+ verify(appSync).updateDataSource(eq(API_ID), eq("accountDB"), any());
+ verify(appSync, never()).createDataSource(anyString(), any(), anyString());
+ }
+
+ @Test
+ void dataSourceMovedToAnotherApiIsCreatedNotUpdated() {
+ DataSource ds = new DataSource();
+ ds.setName("accountDB");
+ ds.setDataSourceArn("arn:ds:new");
+ when(appSync.createDataSource(eq("other-api"), any(), eq("eu-west-1"))).thenReturn(ds);
+ StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb");
+ r.getAttributes().put("ApiId", API_ID);
+ r.getAttributes().put("Name", "accountDB");
+ ObjectNode props = mapper.createObjectNode()
+ .put("ApiId", "other-api")
+ .put("Name", "accountDB")
+ .put("Type", "RELATIONAL_DATABASE");
+
+ provisioner.provision(r, props, updateCtx("arn:ds"));
+
+ // The entity the resource pointed at lives in an API this resource no longer names, so
+ // updating it would mutate a data source belonging to a different API.
+ verify(appSync).createDataSource(eq("other-api"), any(), eq("eu-west-1"));
+ verify(appSync, never()).updateDataSource(anyString(), anyString(), any());
+ }
+
+ // ── FunctionConfiguration ────────────────────────────────────────────────
+
+ @Test
+ void functionPublishesFunctionIdAndCarriesTheJsRuntime() {
+ FunctionConfiguration fn = new FunctionConfiguration();
+ fn.setFunctionId("fn123");
+ fn.setName("Query_getMessages_0");
+ fn.setDataSourceName("accountDB");
+ fn.setFunctionArn("arn:aws:appsync:eu-west-1:000000000000:apis/" + API_ID + "/functions/fn123");
+ when(appSync.createFunction(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(fn);
+ StackResource r = resource("AWS::AppSync::FunctionConfiguration", "GraphQlFnGetMessages");
+ ObjectNode props = mapper.createObjectNode()
+ .put("ApiId", API_ID)
+ .put("Name", "Query_getMessages_0")
+ .put("DataSourceName", "accountDB")
+ .put("FunctionVersion", "2018-05-29")
+ .put("Code", "export function request() { return {}; }");
+ props.putObject("Runtime").put("Name", "APPSYNC_JS").put("RuntimeVersion", "1.0.0");
+
+ provisioner.provision(r, props, ctx());
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(appSync).createFunction(eq(API_ID), captor.capture(), eq("eu-west-1"));
+ Map<String, Object> request = captor.getValue();
+ assertEquals("2018-05-29", request.get("functionVersion"));
+ assertEquals("export function request() { return {}; }", request.get("code"));
+ assertEquals("APPSYNC_JS", ((Map<?, ?>) request.get("runtime")).get("name"));
+
+ assertEquals(fn.getFunctionArn(), r.getPhysicalId());
+ // The pipeline resolvers reference their functions by Fn::GetAtt FunctionId.
+ assertEquals("fn123", r.getAttributes().get("FunctionId"));
+ assertEquals("arn:aws:appsync:eu-west-1:000000000000:apis/" + API_ID + "/functions/fn123",
+ r.getAttributes().get("FunctionArn"));
+ assertEquals("accountDB", r.getAttributes().get("DataSourceName"));
+ }
+
+ @Test
+ void functionUpdateAddressesTheRecordedFunctionId() {
+ FunctionConfiguration fn = new FunctionConfiguration();
+ fn.setFunctionId("fn123");
+ fn.setName("Query_getMessages_0");
+ fn.setFunctionArn("arn:fn");
+ when(appSync.updateFunction(eq(API_ID), eq("fn123"), any())).thenReturn(fn);
+ StackResource r = resource("AWS::AppSync::FunctionConfiguration", "GraphQlFnGetMessages");
+ r.getAttributes().put("ApiId", API_ID);
+ r.getAttributes().put("FunctionId", "fn123");
+ ObjectNode props = mapper.createObjectNode()
+ .put("ApiId", API_ID)
+ .put("Name", "Query_getMessages_0")
+ .put("DataSourceName", "accountDB");
+
+ provisioner.provision(r, props, updateCtx("arn:fn"));
+
+ // The function id is not derivable from the ARN-shaped physical id alone in the general
+ // case, so it has to come off the attributes recorded at create time.
+ verify(appSync).updateFunction(eq(API_ID), eq("fn123"), any());
+ verify(appSync, never()).createFunction(anyString(), any(), anyString());
+ }
+
+ // ── Resolver ─────────────────────────────────────────────────────────────
+
+ @Test
+ void pipelineResolverIsProvisionedWithoutADataSource() {
+ Resolver resolver = new Resolver();
+ resolver.setResolverArn("arn:aws:appsync:eu-west-1:000000000000:apis/" + API_ID
+ + "/types/Query/resolvers/getMessages");
+ when(appSync.createResolver(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(resolver);
+ StackResource r = resource("AWS::AppSync::Resolver", "GraphQlResolverQuerygetMessages");
+ ObjectNode props = mapper.createObjectNode()
+ .put("ApiId", API_ID)
+ .put("TypeName", "Query")
+ .put("FieldName", "getMessages")
+ .put("Kind", "PIPELINE")
+ .put("Code", "export function request() { return {}; }");
+ props.putObject("Runtime").put("Name", "APPSYNC_JS").put("RuntimeVersion", "1.0.0");
+ props.putObject("PipelineConfig").putArray("Functions").add("fn123");
+
+ provisioner.provision(r, props, ctx());
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(appSync).createResolver(eq(API_ID), captor.capture(), eq("eu-west-1"));
+ Map<String, Object> request = captor.getValue();
+ assertEquals("PIPELINE", request.get("kind"));
+ assertNull(request.get("dataSourceName"));
+ assertEquals(List.of("fn123"), ((Map<?, ?>) request.get("pipelineConfig")).get("functions"));
+
+ assertEquals(resolver.getResolverArn(), r.getPhysicalId());
+ assertEquals("Query", r.getAttributes().get("TypeName"));
+ assertEquals("getMessages", r.getAttributes().get("FieldName"));
+ }
+
+ @Test
+ void resolverUpdateAddressesTypeAndField() {
+ 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", "GraphQlResolverQuerygetMessages");
+ r.getAttributes().put("ApiId", API_ID);
+ r.getAttributes().put("TypeName", "Query");
+ r.getAttributes().put("FieldName", "getMessages");
+ ObjectNode props = mapper.createObjectNode()
+ .put("ApiId", API_ID)
+ .put("TypeName", "Query")
+ .put("FieldName", "getMessages")
+ .put("Kind", "PIPELINE");
+
+ provisioner.provision(r, props, updateCtx("arn:resolver"));
+
+ verify(appSync).updateResolver(eq(API_ID), eq("Query"), eq("getMessages"), any());
+ verify(appSync, never()).createResolver(anyString(), any(), anyString());
+ }
+
+ @Test
+ void resolverOnADifferentFieldIsCreatedNotUpdated() {
+ Resolver resolver = new Resolver();
+ resolver.setResolverArn("arn:resolver:new");
+ when(appSync.createResolver(eq(API_ID), any(), eq("eu-west-1"))).thenReturn(resolver);
+ StackResource r = resource("AWS::AppSync::Resolver", "GraphQlResolverQuerygetMessages");
+ r.getAttributes().put("ApiId", API_ID);
+ r.getAttributes().put("TypeName", "Query");
+ r.getAttributes().put("FieldName", "getMessages");
+ ObjectNode props = mapper.createObjectNode()
+ .put("ApiId", API_ID)
+ .put("TypeName", "Query")
+ .put("FieldName", "getUsers")
+ .put("Kind", "PIPELINE");
+
+ provisioner.provision(r, props, updateCtx("arn:resolver"));
+
+ // TypeName and FieldName are create-only: a resolver on a new field is a new resolver.
+ verify(appSync).createResolver(eq(API_ID), any(), eq("eu-west-1"));
+ verify(appSync, never()).updateResolver(anyString(), anyString(), anyString(), any());
+ }
+
+ @Test
+ void resolverWithoutTypeOrFieldIsRefused() {
+ StackResource r = resource("AWS::AppSync::Resolver", "GraphQlResolver");
+ ObjectNode props = mapper.createObjectNode().put("ApiId", API_ID).put("TypeName", "Query");
+
+ assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+ verify(appSync, never()).createResolver(anyString(), any(), anyString());
+ }
+
+ @Test
+ void resolverCodeFromS3IsRefused() {
+ StackResource r = resource("AWS::AppSync::Resolver", "GraphQlResolver");
+ ObjectNode props = mapper.createObjectNode()
+ .put("ApiId", API_ID)
+ .put("TypeName", "Query")
+ .put("FieldName", "getMessages")
+ .put("CodeS3Location", "s3://bucket/resolver.js");
+
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
+
+ assertTrue(e.getMessage().contains("CodeS3Location"), e.getMessage());
+ }
+
+ // ── ApiKey ───────────────────────────────────────────────────────────────
+
+ @Test
+ void apiKeyPublishesTheKeyAndItsId() {
+ ApiKey key = new ApiKey();
+ key.setId("da2-abcdefghijklmnopqrstuvwxyz");
+ key.setApiId(API_ID);
+ when(appSync.createApiKey(eq(API_ID), any())).thenReturn(key);
+ StackResource r = resource("AWS::AppSync::ApiKey", "GraphQlApiqvalia");
+ ObjectNode props = mapper.createObjectNode()
+ .put("ApiId", API_ID)
+ .put("Description", "qvalia")
+ .put("Expires", 1820570400L);
+
+ provisioner.provision(r, props, ctx());
+
+ @SuppressWarnings("unchecked")
+ ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
+ verify(appSync).createApiKey(eq(API_ID), captor.capture());
+ // Expires must stay a number: the service parses it as an epoch second.
+ assertEquals(1820570400L, captor.getValue().get("expires"));
+ assertEquals("qvalia", captor.getValue().get("description"));
+
+ assertEquals("da2-abcdefghijklmnopqrstuvwxyz", r.getPhysicalId());
+ assertEquals("da2-abcdefghijklmnopqrstuvwxyz", r.getAttributes().get("ApiKey"));
+ assertEquals("da2-abcdefghijklmnopqrstuvwxyz", r.getAttributes().get("ApiKeyId"));
+ assertEquals("arn:aws:appsync:eu-west-1:000000000000:apis/" + API_ID
+ + "/apikeys/da2-abcdefghijklmnopqrstuvwxyz", r.getAttributes().get("Arn"));
+ }
+
+ // ── Deletes ──────────────────────────────────────────────────────────────
+
+ @Test
+ void deleteApiDeletesByPhysicalId() {
+ StackResource r = resource("AWS::AppSync::GraphQLApi", "GraphQlApi");
+ r.setPhysicalId(API_ID);
+
+ provisioner.delete(r, "eu-west-1");
+
+ verify(appSync).deleteGraphqlApi(API_ID);
+ }
+
+ @Test
+ void deleteDataSourceUsesTheRecordedApiIdAndName() {
+ StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDsAccountDb");
+ r.setPhysicalId("arn:aws:appsync:eu-west-1:000000000000:apis/" + API_ID + "/datasources/accountDB");
+ r.getAttributes().put("ApiId", API_ID);
+ r.getAttributes().put("Name", "accountDB");
+
+ provisioner.delete(r, "eu-west-1");
+
+ // DeleteDataSource takes the api id and the name; the ARN that is the physical id is not it.
+ verify(appSync).deleteDataSource(API_ID, "accountDB");
+ }
+
+ @Test
+ void deleteResolverUsesTheRecordedTypeAndField() {
+ StackResource r = resource("AWS::AppSync::Resolver", "GraphQlResolver");
+ r.setPhysicalId("arn:resolver");
+ r.getAttributes().put("ApiId", API_ID);
+ r.getAttributes().put("TypeName", "Query");
+ r.getAttributes().put("FieldName", "getMessages");
+
+ provisioner.delete(r, "eu-west-1");
+
+ verify(appSync).deleteResolver(API_ID, "Query", "getMessages");
+ }
+
+ @Test
+ void deleteFunctionUsesTheRecordedFunctionId() {
+ StackResource r = resource("AWS::AppSync::FunctionConfiguration", "GraphQlFn");
+ r.setPhysicalId("arn:fn");
+ r.getAttributes().put("ApiId", API_ID);
+ r.getAttributes().put("FunctionId", "fn123");
+
+ provisioner.delete(r, "eu-west-1");
+
+ verify(appSync).deleteFunction(API_ID, "fn123");
+ }
+
+ @Test
+ void deleteSchemaTouchesNothingBecauseItGoesWithItsApi() {
+ StackResource r = resource("AWS::AppSync::GraphQLSchema", "GraphQlSchema");
+ r.setPhysicalId(API_ID + "GraphQLSchema");
+ r.getAttributes().put("ApiId", API_ID);
+
+ provisioner.delete(r, "eu-west-1");
+
+ verifyNoInteractions(appSync);
+ }
+
+ @Test
+ void deleteToleratesAnAlreadyGoneResolver() {
+ doThrow(new AwsException("NotFoundException", "Resolver not found", 404))
+ .when(appSync).deleteResolver(API_ID, "Query", "getMessages");
+ StackResource r = resource("AWS::AppSync::Resolver", "GraphQlResolver");
+ r.setPhysicalId("arn:resolver");
+ r.getAttributes().put("ApiId", API_ID);
+ r.getAttributes().put("TypeName", "Query");
+ r.getAttributes().put("FieldName", "getMessages");
+
+ // A DeleteStack retry must not fail on a resolver the first attempt already removed.
+ provisioner.delete(r, "eu-west-1");
+ }
+
+ @Test
+ void deletePropagatesAFailureThatIsNotAlreadyGone() {
+ doThrow(new AwsException("ConcurrentModificationException", "Schema is being modified", 409))
+ .when(appSync).deleteDataSource(API_ID, "accountDB");
+ StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDs");
+ r.setPhysicalId("arn:ds");
+ r.getAttributes().put("ApiId", API_ID);
+ r.getAttributes().put("Name", "accountDB");
+
+ // Anything but "already gone" has to reach the stack as DELETE_FAILED.
+ assertThrows(AwsException.class, () -> provisioner.delete(r, "eu-west-1"));
+ }
+
+ @Test
+ void deleteWithoutRecordedIdentityDoesNotThrow() {
+ StackResource r = resource("AWS::AppSync::DataSource", "GraphQlDs");
+ r.setPhysicalId("arn:ds");
+
+ provisioner.delete(r, "eu-west-1");
+
+ verifyNoInteractions(appSync);
+ }
+
+ @Test
+ void resourceTypesCoverTheSixAppSyncTypes() {
+ assertEquals(Set.of("AWS::AppSync::GraphQLApi", "AWS::AppSync::GraphQLSchema",
+ "AWS::AppSync::DataSource", "AWS::AppSync::FunctionConfiguration",
+ "AWS::AppSync::Resolver", "AWS::AppSync::ApiKey"),
+ provisioner.resourceTypes());
+ }
+}
diff --git a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv
index d73b485ed7..7dde1ef54e 100644
--- a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv
+++ b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv
@@ -1,3 +1,4 @@
+AWS::AppSync::GraphQLApi GraphQLEndpointArn the private-endpoint ARN of the GraphQL endpoint; Floci serves one public endpoint and has no private-endpoint model
AWS::CertificateManager::Certificate Id schema gives no description; Ref returns the ARN and the legacy spec gives the type no attributes
AWS::CodeBuild::Project Id schema gives no description; AWS's Id may differ from the project name Floci uses
AWS::CodePipeline::CustomActionType Id schema gives no description; the custom action has no separate id in Floci
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index 99e4d8385b..acfe4a9d08 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -16,6 +16,12 @@ AWS::ApiGatewayV2::Deployment LEGACY_SWITCH
AWS::ApiGatewayV2::Integration LEGACY_SWITCH
AWS::ApiGatewayV2::Route LEGACY_SWITCH
AWS::ApiGatewayV2::Stage LEGACY_SWITCH
+AWS::AppSync::ApiKey AppSyncCfnProvisioner
+AWS::AppSync::DataSource AppSyncCfnProvisioner
+AWS::AppSync::FunctionConfiguration AppSyncCfnProvisioner
+AWS::AppSync::GraphQLApi AppSyncCfnProvisioner
+AWS::AppSync::GraphQLSchema AppSyncCfnProvisioner
+AWS::AppSync::Resolver AppSyncCfnProvisioner
AWS::AutoScaling::AutoScalingGroup LEGACY_SWITCH
AWS::AutoScaling::LaunchConfiguration LEGACY_SWITCH
AWS::AutoScaling::LifecycleHook AutoScalingLifecycleHookCfnProvisioner
diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml
index d095c052ec..8f774e50ba 100644
--- a/tools/docs/cfn_resource_types.yaml
+++ b/tools/docs/cfn_resource_types.yaml
@@ -30,6 +30,7 @@ order:
- AWS::Route53
- AWS::ApiGateway
- AWS::ApiGatewayV2
+ - AWS::AppSync
- AWS::StepFunctions
- AWS::CodePipeline
- AWS::CodeBuild
@@ -89,6 +90,7 @@ type_order:
AWS::Route53: [HostedZone, RecordSet]
AWS::ApiGateway: [RestApi, Resource, Authorizer, Method, Deployment, Stage, Account, DomainName, BasePathMapping]
AWS::ApiGatewayV2: [Api, Authorizer, Route, Integration, Stage, Deployment]
+ AWS::AppSync: [GraphQLApi, GraphQLSchema, DataSource, FunctionConfiguration, Resolver, ApiKey]
AWS::CodePipeline: [Pipeline, CustomActionType, Webhook]
AWS::Batch: [ComputeEnvironment, JobQueue, JobDefinition]
AWS::Cognito: [UserPool, UserPoolClient]
@@ -99,6 +101,7 @@ type_order:
service_labels:
AWS::ApiGateway: API Gateway (v1)
AWS::ApiGatewayV2: API Gateway v2
+ AWS::AppSync: AppSync
AWS::AutoScaling: Auto Scaling
AWS::Batch: Batch
AWS::Backup: Backup