Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1351,6 +1351,51 @@ void createSourceApiAssociationDuplicateThrowsConcurrentModificationException()
}
}

// ── Events API ──────────────────────────────────────────────────────

@Test
@Order(140)
@DisplayName("Events API: CreateApi, GetApi, UpdateApi, ListApis, channel namespace and DeleteApi")
void eventsApiLifecycle() {
EventConfig eventConfig = EventConfig.builder()
.authProviders(AuthProvider.builder().authType(AuthenticationType.AWS_IAM).build(),
AuthProvider.builder().authType(AuthenticationType.API_KEY).build())
.connectionAuthModes(AuthMode.builder().authType(AuthenticationType.API_KEY).build())
.defaultPublishAuthModes(AuthMode.builder().authType(AuthenticationType.AWS_IAM).build())
.defaultSubscribeAuthModes(AuthMode.builder().authType(AuthenticationType.API_KEY).build())
.build();
Api created = client.createApi(r -> r.name("sdk-events-api").eventConfig(eventConfig)).api();
String eventsApiId = created.apiId();
try {
assertThat(created.apiArn()).startsWith("arn:" + TestFixtures.partition() + ":appsync:")
.endsWith(":apis/" + eventsApiId);
assertThat(created.dns()).containsKeys("HTTP", "REALTIME");
assertThat(created.dns().get("HTTP")).startsWith(eventsApiId + ".appsync-api.");
assertThat(created.dns().get("REALTIME")).startsWith(eventsApiId + ".appsync-realtime-api.");
assertThat(created.created()).isAfter(Instant.now().minus(Duration.ofHours(1)));

assertThat(client.getApi(r -> r.apiId(eventsApiId)).api().name()).isEqualTo("sdk-events-api");
assertThat(client.listApis(r -> r.maxResults(25)).apis()).extracting(Api::apiId).contains(eventsApiId);

Api updated = client.updateApi(r -> r.apiId(eventsApiId).name("sdk-events-renamed")
.eventConfig(eventConfig)).api();
assertThat(updated.name()).isEqualTo("sdk-events-renamed");

ChannelNamespace ns = client.createChannelNamespace(r -> r.apiId(eventsApiId).name("sdk-ns")
.publishAuthModes(AuthMode.builder().authType(AuthenticationType.AWS_IAM).build()))
.channelNamespace();
assertThat(ns.channelNamespaceArn()).endsWith(":apis/" + eventsApiId + "/channelNamespace/sdk-ns");
assertThat(ns.publishAuthModes()).extracting(AuthMode::authType).containsExactly(AuthenticationType.AWS_IAM);

assertThatThrownBy(() -> client.createChannelNamespace(r -> r.apiId(eventsApiId).name("sdk-lambda")
.subscribeAuthModes(AuthMode.builder().authType(AuthenticationType.AWS_LAMBDA).build())))
.isInstanceOf(BadRequestException.class);
} finally {
client.deleteApi(r -> r.apiId(eventsApiId));
}
assertThatThrownBy(() -> client.getApi(r -> r.apiId(eventsApiId))).isInstanceOf(NotFoundException.class);
}

@Test
@Order(200)
void startSchemaCreation_syntaxError_throwsBadRequestWithExtendedBody() throws Exception {
Expand Down
76 changes: 69 additions & 7 deletions docs/services/appsync.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# AppSync

**Protocol:** REST JSON
**Endpoint:** `http://localhost:4566/v1/apis/...`
**Endpoint:** `http://localhost:4566/v1/apis/...` (GraphQL APIs), `http://localhost:4566/v2/apis/...` (Events APIs)

Floci implements the AWS AppSync Management API, providing local emulation of GraphQL API configuration, schema management, data source binding, resolver mapping, API key provisioning, custom domains, and channel namespaces.
Floci implements the AWS AppSync Management API, providing local emulation of GraphQL API configuration, schema management, data source binding, resolver mapping, API key provisioning, custom domains, Events APIs, and channel namespaces.

## OIDC issuer network policy

Expand All @@ -25,6 +25,32 @@ targets and HTTP URLs that use a literal private or loopback address.
| `DeleteGraphqlApi` | Delete a GraphQL API and all child resources |
| `ListGraphqlApis` | List all GraphQL APIs |

### Events API

| Operation | Description |
|---|---|
| `CreateApi` | Create an Events API with its auth providers and default auth modes |
| `GetApi` | Get an Events API by ID |
| `UpdateApi` | Update an Events API name, owner contact or event configuration |
| `DeleteApi` | Delete an Events API, its channel namespaces, API keys and domain association |
| `ListApis` | List all Events APIs |

API Gateway v2 serves the same `/v2/apis` and `/v2/apis/{apiId}` paths. Floci routes a request
by the service it is signed for: one signed for `appsync` reaches AppSync, and one signed for
`apigateway` reaches API Gateway.

`CreateApi` and `UpdateApi` require at least one auth provider. Every mode in
`connectionAuthModes`, `defaultPublishAuthModes` and `defaultSubscribeAuthModes` must name one of
those providers, or the request fails with `BadRequestException`. An `AWS_LAMBDA` provider needs
`lambdaAuthorizerConfig.authorizerUri`, a Cognito provider needs `cognitoConfig.userPoolId` and
`awsRegion`, and an OIDC provider needs `openIDConnectConfig.issuer`.

`dns.HTTP` and `dns.REALTIME` carry the AWS host names,
`<apiId>.appsync-api.<region>.<dnsSuffix>` and `<apiId>.appsync-realtime-api.<region>.<dnsSuffix>`,
with the DNS suffix of the region's partition. Floci does not serve the Events data plane on
those hosts yet; see [Not Implemented](#not-implemented). `logConfig` is stored and returned, but
no logs are delivered.

### Schema

| Operation | Description |
Expand Down Expand Up @@ -120,12 +146,19 @@ As on AWS, `ApiKey.id` is the key value itself (`da2-` followed by 26 lowercase

| Operation | Description |
|---|---|
| `CreateChannelNamespace` | Create a channel namespace |
| `CreateChannelNamespace` | Create a channel namespace, with its publish and subscribe auth modes, handler configuration and tags |
| `GetChannelNamespace` | Get a channel namespace by name |
| `UpdateChannelNamespace` | Update a channel namespace description |
| `UpdateChannelNamespace` | Update a channel namespace's auth modes, code handlers and handler configuration |
| `ListChannelNamespaces` | List all channel namespaces for an API |
| `DeleteChannelNamespace` | Delete a channel namespace |

A channel namespace belongs to an Events API. Floci also accepts a GraphQL API's id here, as
earlier releases did. Each of its `publishAuthModes` and `subscribeAuthModes` must name one of
the parent API's auth types. Its ARN is
`arn:<partition>:appsync:<region>:<account>:apis/<apiId>/channelNamespace/<name>`, in the
region of its API. `handlerConfigs` and `codeHandlers` are stored and returned, but no handler
runs.

### Merged API Associations

| Operation | Description |
Expand Down Expand Up @@ -558,7 +591,9 @@ Deleting a GraphQL API (`DeleteGraphqlApi`) automatically deletes all child reso
- All channel namespaces
- All domain name associations

This matches AWS behavior where deleting an API removes its entire configuration.
This matches AWS behavior where deleting an API removes its entire configuration. Deleting an
Events API (`DeleteApi`) likewise removes its channel namespaces, API keys and domain name
association.

## CloudFormation

Expand All @@ -572,6 +607,8 @@ Floci provisions these AppSync resource types:
| `AWS::AppSync::FunctionConfiguration` | the function ARN | `FunctionArn`, `FunctionId`, `Name`, `DataSourceName` |
| `AWS::AppSync::Resolver` | the resolver ARN | `ResolverArn`, `TypeName`, `FieldName` |
| `AWS::AppSync::ApiKey` | the key id, `da2-...` (AWS: the key ARN) | `ApiKey`, `ApiKeyId`, `Arn` |
| `AWS::AppSync::Api` | the Events API ARN | `ApiId`, `ApiArn`, `Dns.Http`, `Dns.Realtime` |
| `AWS::AppSync::ChannelNamespace` | the channel namespace ARN | `ChannelNamespaceArn` |

`GraphQLEndpointArn` returns
`arn:<partition>:appsync:<region>:<account>:endpoints/graphql-api/<apiId>`. Use it to
Expand Down Expand Up @@ -608,8 +645,26 @@ A `GraphQLSchema` with `DefinitionS3Location` and no inline `Definition`, and `C
a `Resolver` or `FunctionConfiguration`, fail the resource with `ValidationError`. Give the schema
inline in `Definition` and the code inline in `Code`.

`AWS::AppSync::Api`, `ApiCache`, `ChannelNamespace`, `DomainName`, `DomainNameApiAssociation`,
`SourceApiAssociation` and `Type` are not provisioned. By default such a resource is stubbed: it
### Events APIs

`AWS::AppSync::Api` and `AWS::AppSync::ChannelNamespace` follow the type's registry schema: `Ref`
returns the ARN, the schema's primary identifier, and the `Fn::GetAtt` attributes are the schema's
read-only properties. These two types were checked against the registry schema and the
CloudFormation documentation, not deployed to AWS.

- An `Api` update is always in place, `Name` included: the API keeps its id, ARN and DNS hosts.
`EventConfig` is replaced as a whole. A template without `EventConfig` fails the resource, since
`CreateApi` requires one.
Comment on lines +656 to +657

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Informational

7. Docs promise a failure that updates never raise 🐞 Bug ⚙ Maintainability

The new docs say a template without EventConfig fails the resource, but the provisioner lists
EventConfig as kept-on-drop for AWS::AppSync::Api, so clearDropped leaves it out of the
UpdateApi request. Only a create fails. An UpdateStack that drops EventConfig succeeds and
keeps the old config, so a reader who trusts the docs gets the wrong result.
Agent Prompt
## Issue description
The docs say a template without `EventConfig` fails the resource. That only happens on create. On update, a dropped `EventConfig` is kept.

## Fix Focus Areas
- docs/services/appsync.md[655-657]

## Recommended Fix
Rewrite the sentence: "A create without `EventConfig` fails the resource, since `CreateApi` requires one; an update that drops it keeps the API's current event config."

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

- `ApiId` and `Name` of a `ChannelNamespace` are create-only, so changing either replaces the
namespace. Any other change is an in-place update, and dropping `PublishAuthModes` or
`SubscribeAuthModes` returns the namespace to the API's default modes.
- `Tags` on both types are set to exactly the template's tags on every update.
- `CodeS3Location` on a `ChannelNamespace` fails the resource with `ValidationError`; give the
handler code inline in `CodeHandlers`.
- An `AWS::AppSync::ApiKey` whose `ApiId` names an Events API creates a key for that API.

`AWS::AppSync::ApiCache`, `DomainName`, `DomainNameApiAssociation`, `SourceApiAssociation` and
`Type` are not provisioned. By default such a resource is stubbed: it
reaches `CREATE_COMPLETE` and nothing is created for it. Set
`allow-stub-unsupported-resource-types` to `false` to fail it instead, see
[CloudFormation](cloudformation.md#supported-resource-types).
Expand All @@ -622,6 +677,7 @@ These AWS AppSync capabilities are not yet implemented and are tracked in future
- **Data source adapters**: EventBridge, OpenSearch, and Bedrock connectors
- **Guardrails** (Phase 10): query depth / complexity limits and related errors
- **Realtime subscriptions** (Phase 11+): WebSocket real-time subscriptions
- **Events data plane**: `POST /event` publishing and the `/event/realtime` WebSocket of an Events API, and the `onPublish` and `onSubscribe` handlers of a channel namespace
- **Caching**: API-level and per-resolver caching
- **Merged API source management**: `AssociateMergedGraphqlApi`, `AssociateSourceGraphqlApi`, `StartSchemaMerge`, `ListTypesByAssociation`
- **Data source introspection**: `StartDataSourceIntrospection`, `GetDataSourceIntrospection`
Expand Down Expand Up @@ -704,6 +760,12 @@ curl -s -X POST "$AWS_ENDPOINT_URL/v1/apis/API_ID/graphql" \
-H "x-api-key: da2-YOUR_API_KEY" \
-d '{"query":"{ hello }"}'

# Create an Events API with IAM publishing and API key connections and subscriptions
aws appsync create-api \
--name my-events \
--event-config '{"authProviders":[{"authType":"AWS_IAM"},{"authType":"API_KEY"}],"connectionAuthModes":[{"authType":"API_KEY"}],"defaultPublishAuthModes":[{"authType":"AWS_IAM"}],"defaultSubscribeAuthModes":[{"authType":"API_KEY"}]}' \
--endpoint-url $AWS_ENDPOINT_URL

# Create a channel namespace
aws appsync create-channel-namespace \
--api-id API_ID \
Expand Down
2 changes: 1 addition & 1 deletion docs/services/cloudformation.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ cross-resource references.
| Cloud Map | `HttpNamespace`, `PrivateDnsNamespace`, `PublicDnsNamespace`, `Service` |
| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `GatewayResponse`, `ApiKey`, `UsagePlan`, `UsagePlanKey` |
| API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment`, `DomainName`, `ApiMapping`, `VpcLink` |
| AppSync | `GraphQLApi`, `GraphQLSchema`, `DataSource`, `FunctionConfiguration`, `Resolver`, `ApiKey`. `Ref` on `GraphQLApi` and `ApiKey` returns the id where AWS returns the ARN. See [AppSync](appsync.md#cloudformation) for `Ref` and `Fn::GetAtt` compared with AWS. |
| AppSync | `GraphQLApi`, `GraphQLSchema`, `DataSource`, `FunctionConfiguration`, `Resolver`, `ApiKey`, `Api`, `ChannelNamespace`. `Ref` on `GraphQLApi` and `ApiKey` returns the id where AWS returns the ARN; on the Events `Api` and `ChannelNamespace` it returns the ARN, as on AWS. See [AppSync](appsync.md#cloudformation) for `Ref` and `Fn::GetAtt` compared with AWS. |
| AppConfig | `Application`, `Environment` (`Tags` and `DeletionProtectionCheck` are accepted and not stored), `ConfigurationProfile` (`Tags`, `KmsKeyIdentifier`, `RetrievalRoleArn`, `Validators` and `DeletionProtectionCheck` are accepted and not stored), `DeploymentStrategy` (`Tags` are accepted and not stored; `ReplicateTo: SSM_DOCUMENT` writes no SSM document). `Ref` returns the AppConfig ID of each. See [AppConfig](appconfig.md#cloudformation) for updates and replacement. |
| Step Functions | `StateMachine` |
| CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` |
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/io/floci/aws/core/common/AwsEndpoints.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ public static String executeApiHost(String apiId, String region) {
return apiId + "." + host("execute-api", region);
}

/** An AppSync Events API's {@code dns.HTTP}: {@code <apiId>.appsync-api.<region>.<dnsSuffix>}. */
public static String appsyncEventsHttpHost(String apiId, String region) {
return apiId + "." + host("appsync-api", region);
}

/** An AppSync Events API's {@code dns.REALTIME}: {@code <apiId>.appsync-realtime-api.<region>.<dnsSuffix>}. */
public static String appsyncEventsRealtimeHost(String apiId, String region) {
return apiId + "." + host("appsync-realtime-api", region);
}

/** The region-less bucket host, {@code <bucket>.s3.<dnsSuffix>} (CloudFormation's {@code DomainName}). */
public static String s3Host(String bucket, String region) {
return bucket + ".s3." + AwsRegions.dnsSuffixFor(region);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import io.floci.aws.services.appconfig.AppConfigController;
import io.floci.aws.services.appconfig.AppConfigDataController;
import io.floci.aws.services.appintegrations.AppIntegrationsController;
import io.floci.aws.services.appsync.AppSyncApiController;
import io.floci.aws.services.appsync.AppSyncController;
import io.floci.aws.services.appsync.graphql.AppSyncExecutionController;
import io.floci.aws.services.aps.ApsController;
Expand Down Expand Up @@ -736,7 +737,7 @@ public ResolvedServiceCatalog(EmulatorConfig config) {
config.storage().services().appsync().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("appsync"), Set.of(), Set.of(AppSyncController.class,
AppSyncExecutionController.class)),
AppSyncApiController.class, AppSyncExecutionController.class)),
descriptor("s3vectors", "s3vectors", config.services().s3vectors().enabled(), true,
"s3vectors", storageMode(config.storage().services().s3vectors().mode(), config.storage().mode()),
config.storage().services().s3vectors().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package io.floci.aws.services.appsync;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.appsync.model.Api;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

import java.io.IOException;
import java.util.Map;

/**
* AppSync Events API management: {@code CreateApi}, {@code GetApi}, {@code UpdateApi},
* {@code DeleteApi} and {@code ListApis}. AWS serves them on {@code /v2/apis}, which API Gateway
* v2 also claims, so {@link AppSyncEventsRouteFilter} moves an appsync-signed request onto this
* controller's internal prefix.
*/
@Path(AppSyncEventsRouteFilter.INTERNAL_PREFIX + "/v2/apis")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class AppSyncApiController {

private final AppSyncService service;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;

@Inject
public AppSyncApiController(AppSyncService service, RegionResolver regionResolver, ObjectMapper objectMapper) {
this.service = service;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}

@POST
public Response createApi(@Context HttpHeaders headers, String body) throws IOException {
Api api = service.createApi(readRequest(body), regionResolver.resolveRegion(headers));
return Response.ok(wrap(api)).build();
Comment on lines +50 to +52

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

5. Query-signed apis get the wrong region 🐞 Bug ≡ Correctness

createApi passes RegionResolver.resolveRegion(headers) to the service, but that method does not
read the credential in a query-signed request. When such a request has no Authorization header and
signs for a region other than the configured default, the created API receives the default region in
its ARN and DNS names.
Agent Prompt
## Issue description
Query-signed creates use the deployment default instead of the credential's region.
## Fix Focus Areas
- src/main/java/io/floci/aws/services/appsync/AppSyncApiController.java[49-52]
## Recommended Fix
Use the region already established in request context for API creation, including query-signed requests, rather than resolving it solely from headers.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

}

@GET
public Response listApis(@QueryParam("maxResults") Integer maxResults,
@QueryParam("nextToken") String nextToken) {
AppSyncService.Page<Api> page = service.listApis(maxResults, nextToken);
ObjectNode root = objectMapper.createObjectNode();
ArrayNode items = root.putArray("apis");
for (Api api : page.items()) {
items.add(objectMapper.valueToTree(api));
}
if (page.nextToken() != null) {
root.put("nextToken", page.nextToken());
}
return Response.ok(root).build();
}

@GET
@Path("/{apiId}")
public Response getApi(@PathParam("apiId") String apiId) {
return Response.ok(wrap(service.getApi(apiId))).build();
}

@POST
@Path("/{apiId}")
public Response updateApi(@PathParam("apiId") String apiId, String body) throws IOException {
return Response.ok(wrap(service.updateApi(apiId, readRequest(body)))).build();
}

@DELETE
@Path("/{apiId}")
public Response deleteApi(@PathParam("apiId") String apiId) {
service.deleteApi(apiId);
return Response.ok(objectMapper.createObjectNode()).build();
}

private ObjectNode wrap(Api api) {
ObjectNode root = objectMapper.createObjectNode();
root.set("api", objectMapper.valueToTree(api));
return root;
}

private Map<String, Object> readRequest(String body) throws IOException {
if (body == null || body.isBlank()) {
return Map.of();
}
Map<String, Object> request = objectMapper.readValue(body, new TypeReference<Map<String, Object>>() {});
if (request == null) {
throw new AwsException("BadRequestException", "The request body must be a JSON object", 400);
}
return request;
}
}
Loading
Loading