diff --git a/README.md b/README.md index 05d503e375..18cc8e7f34 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,7 @@ flowchart LR Router["HTTP Router\nJAX-RS / Vert.x"] subgraph Stateless ["Stateless Services"] - A["SSM · SQS · SNS\nIAM · STS · KMS\nSecrets Manager · SES\nCognito · Kinesis\nEventBridge · Scheduler · AppConfig\nCloudWatch · Step Functions\nCloudFormation · ACM · Config\nAPI Gateway · ELB v2 · Auto Scaling\nCodeDeploy · Backup · Bedrock Runtime · Route53 · Transfer"] + A["SSM · SQS · SNS\nIAM · STS · KMS\nSecrets Manager · SES\nCognito · Kinesis\nEventBridge · Scheduler · AppConfig\nCloudWatch · Step Functions\nCloudFormation · ACM · Config\nAPI Gateway · AppSync · ELB v2 · Auto Scaling\nCodeDeploy · Backup · Bedrock Runtime · Route53 · Transfer"] end subgraph Stateful ["Stateful Services"] @@ -220,7 +220,7 @@ Floci supports local emulation for application services, data services, eventing |---|---| | Core app services | S3, SQS, SNS, DynamoDB, Lambda, IAM, STS, KMS, Secrets Manager | | Events and workflows | EventBridge, EventBridge Pipes, EventBridge Scheduler, Step Functions, CloudWatch Logs, CloudWatch Metrics | -| API and identity | API Gateway REST, API Gateway v2, Cognito, ACM, Route53 | +| API and identity | API Gateway REST, API Gateway v2, AppSync, Cognito, ACM, Route53 | | Containers and compute | ECS, EC2, EKS, CodeBuild, CodeDeploy, Auto Scaling, ELB v2 | | Graph database | Neptune | | Data and analytics | Athena, Glue, Firehose, OpenSearch, Textract | @@ -245,6 +245,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/ | Lambda | Real Docker | Runtime environment, execution model, warm container pool, aliases, Function URLs | | API Gateway REST | In-process | Resources, methods, stages, Lambda proxy, MOCK integrations, AWS integrations | | API Gateway v2 | In-process | HTTP APIs, routes, integrations, JWT authorizers, stages | +| AppSync | In-process | GraphQL API management API, schema registry, AWS scalars, domain names, channel namespaces | | IAM | In-process | Users, roles, groups, policies, instance profiles, access keys | | STS | In-process | AssumeRole, WebIdentity, SAML, GetFederationToken, GetSessionToken | | Cognito | In-process | User pools, app clients, auth flows, JWKS and OpenID well-known endpoints | diff --git a/compatibility-tests/sdk-test-java/README.md b/compatibility-tests/sdk-test-java/README.md index 48f95a25c3..7a43de1c90 100644 --- a/compatibility-tests/sdk-test-java/README.md +++ b/compatibility-tests/sdk-test-java/README.md @@ -2,7 +2,7 @@ Compatibility tests for [Floci](https://github.com/hectorvent/floci) using the **AWS SDK for Java v2 (2.31.8)**. -Runs 313 tests across 16 test classes against a live Floci instance — no mocks. +Runs 352 tests across 17 test classes against a live Floci instance — no mocks. ## Services Covered @@ -24,6 +24,7 @@ Runs 313 tests across 16 test classes against a live Floci instance — no mocks | `ApigwSfnJsonataCrudlTests` | API Gateway + Step Functions JSONata CRUDL integration | | `ApiGatewayV2WebSocketAndExtendedOpsTest` | API GW v2 WebSocket APIs, Update ops, Route/Integration Responses, Models, Tagging | | `Ec2Tests` | EC2 instances, VPCs, security groups, subnets | +| `AppSyncTest` | GraphQL API CRUDL, data sources, resolvers, functions, types, API keys, tags, schema validation | | `EcsTests` | ECS clusters, task definitions, services | ## Adding a New Test diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppSyncTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppSyncTest.java index 0cdbd034bb..f67b893e11 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppSyncTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppSyncTest.java @@ -487,6 +487,394 @@ class AppSyncTest { assertThat(resp).isNotNull(); } + // ── Phase 2: Model Compatibility ─────────────────────────────────── + + @Test + @Order(90) + void createDataSource_hasDataSourceArn() { + CreateDataSourceResponse resp = client.createDataSource(CreateDataSourceRequest.builder() + .apiId(apiId) + .name("arn-check-ds") + .type("NONE") + .build()); + + assertThat(resp.dataSource().dataSourceArn()).isNotNull(); + assertThat(resp.dataSource().dataSourceArn()).contains("arn:aws:appsync:"); + assertThat(resp.dataSource().dataSourceArn()).contains("/datasources/arn-check-ds"); + + client.deleteDataSource(r -> r.apiId(apiId).name("arn-check-ds")); + } + + @Test + @Order(91) + void createResolver_hasResolverArn() { + CreateResolverResponse resp = client.createResolver(CreateResolverRequest.builder() + .apiId(apiId) + .typeName("Query") + .fieldName("resolverArnCheck") + .dataSourceName("none-ds") + .build()); + + assertThat(resp.resolver().resolverArn()).isNotNull(); + assertThat(resp.resolver().resolverArn()).contains("arn:aws:appsync:"); + assertThat(resp.resolver().resolverArn()).contains("/types/Query/resolvers/resolverArnCheck"); + + client.deleteResolver(r -> r.apiId(apiId).typeName("Query").fieldName("resolverArnCheck")); + } + + @Test + @Order(92) + void createFunction_hasFunctionArn() { + CreateFunctionResponse resp = client.createFunction(CreateFunctionRequest.builder() + .apiId(apiId) + .name("arn-check-fn") + .dataSourceName("none-ds") + .build()); + + assertThat(resp.functionConfiguration().functionArn()).isNotNull(); + assertThat(resp.functionConfiguration().functionArn()).contains("arn:aws:appsync:"); + + client.deleteFunction(r -> r.apiId(apiId).functionId(resp.functionConfiguration().functionId())); + } + + @Test + @Order(93) + void startSchemaCreation_invalidSchema() { + assertThatThrownBy(() -> client.startSchemaCreation(StartSchemaCreationRequest.builder() + .apiId(apiId) + .definition(SdkBytes.fromUtf8String("type Query { invalid !!! }")) + .build())) + .isInstanceOf(AppSyncException.class) + .hasMessageContaining("Invalid schema"); + } + + @Test + @Order(94) + void startSchemaCreation_withAWSScalars() { + StartSchemaCreationResponse resp = client.startSchemaCreation( + StartSchemaCreationRequest.builder() + .apiId(apiId) + .definition(SdkBytes.fromUtf8String( + "type Query { now: AWSDateTime, data: AWSJSON, ip: AWSIPAddress, active: AWSBoolean }")) + .build()); + + assertThat(resp.status()).isNotNull(); + } + + // ── Channel Namespaces ───────────────────────────────────────────── + + private static String channelNsName; + + @Test + @Order(95) + void createChannelNamespace() { + CreateChannelNamespaceResponse resp = client.createChannelNamespace( + CreateChannelNamespaceRequest.builder() + .apiId(apiId) + .name("sdk-channel-ns") + .build()); + + assertThat(resp.channelNamespace()).isNotNull(); + channelNsName = resp.channelNamespace().name(); + assertThat(channelNsName).isEqualTo("sdk-channel-ns"); + assertThat(resp.channelNamespace().apiId()).isEqualTo(apiId); + } + + @Test + @Order(96) + void getChannelNamespace() { + GetChannelNamespaceResponse resp = client.getChannelNamespace( + GetChannelNamespaceRequest.builder() + .apiId(apiId) + .name(channelNsName) + .build()); + + assertThat(resp.channelNamespace()).isNotNull(); + assertThat(resp.channelNamespace().name()).isEqualTo(channelNsName); + } + + @Test + @Order(97) + void updateChannelNamespace() { + UpdateChannelNamespaceResponse resp = client.updateChannelNamespace( + UpdateChannelNamespaceRequest.builder() + .apiId(apiId) + .name(channelNsName) + .build()); + + assertThat(resp.channelNamespace()).isNotNull(); + } + + @Test + @Order(98) + void listChannelNamespaces() { + ListChannelNamespacesResponse resp = client.listChannelNamespaces( + ListChannelNamespacesRequest.builder() + .apiId(apiId) + .build()); + + assertThat(resp.channelNamespaces()).isNotEmpty(); + } + + @Test + @Order(99) + void deleteChannelNamespace() { + DeleteChannelNamespaceResponse resp = client.deleteChannelNamespace( + DeleteChannelNamespaceRequest.builder() + .apiId(apiId) + .name(channelNsName) + .build()); + + assertThat(resp).isNotNull(); + } + + // ── Domain Association ───────────────────────────────────────────── + + private static String tempDomainName; + + @Test + @Order(100) + void createDomainName() { + // Use unique domain name to avoid conflicts + String domainSuffix = java.util.UUID.randomUUID().toString().substring(0, 8); + CreateDomainNameResponse resp = client.createDomainName( + CreateDomainNameRequest.builder() + .domainName("sdk-" + domainSuffix + ".example.com") + .certificateArn("arn:aws:acm:us-east-1:000000000000:certificate/sdk") + .build()); + + assertThat(resp.domainNameConfig()).isNotNull(); + tempDomainName = resp.domainNameConfig().domainName(); + assertThat(tempDomainName).startsWith("sdk-"); + assertThat(resp.domainNameConfig().appsyncDomainName()).isNotNull(); + } + + @Test + @Order(101) + void getDomainName() { + GetDomainNameResponse resp = client.getDomainName( + GetDomainNameRequest.builder() + .domainName(tempDomainName) + .build()); + + assertThat(resp.domainNameConfig()).isNotNull(); + assertThat(resp.domainNameConfig().domainName()).isEqualTo(tempDomainName); + } + + @Test + @Order(102) + void updateDomainName() { + UpdateDomainNameResponse resp = client.updateDomainName( + UpdateDomainNameRequest.builder() + .domainName(tempDomainName) + .description("updated-domain") + .build()); + + assertThat(resp.domainNameConfig()).isNotNull(); + assertThat(resp.domainNameConfig().domainName()).isEqualTo(tempDomainName); + } + + @Test + @Order(103) + void associateApi() { + AssociateApiResponse resp = client.associateApi( + AssociateApiRequest.builder() + .domainName(tempDomainName) + .apiId(apiId) + .build()); + + assertThat(resp.apiAssociation()).isNotNull(); + assertThat(resp.apiAssociation().domainName()).isEqualTo(tempDomainName); + assertThat(resp.apiAssociation().apiId()).isEqualTo(apiId); + } + + @Test + @Order(104) + void getApiAssociation() { + GetApiAssociationResponse resp = client.getApiAssociation( + GetApiAssociationRequest.builder() + .domainName(tempDomainName) + .build()); + + assertThat(resp.apiAssociation()).isNotNull(); + assertThat(resp.apiAssociation().apiId()).isEqualTo(apiId); + } + + @Test + @Order(105) + void disassociateApi() { + DisassociateApiResponse resp = client.disassociateApi( + DisassociateApiRequest.builder() + .domainName(tempDomainName) + .build()); + + assertThat(resp).isNotNull(); + } + + @Test + @Order(106) + void deleteDomainName() { + DeleteDomainNameResponse resp = client.deleteDomainName( + DeleteDomainNameRequest.builder() + .domainName(tempDomainName) + .build()); + + assertThat(resp).isNotNull(); + } + + // ── Source API Association ───────────────────────────────────────── + + private static String sourceApiId; + private static String assocId; + + @Test + @Order(107) + void associateSourceGraphqlApi() { + // Create source API + CreateGraphqlApiResponse sourceResp = client.createGraphqlApi( + CreateGraphqlApiRequest.builder() + .name("sdk-source-api") + .authenticationType("API_KEY") + .build()); + sourceApiId = sourceResp.graphqlApi().apiId(); + + AssociateSourceGraphqlApiResponse resp = client.associateSourceGraphqlApi( + AssociateSourceGraphqlApiRequest.builder() + .mergedApiIdentifier(apiId) + .sourceApiIdentifier(sourceApiId) + .build()); + + assertThat(resp.sourceApiAssociation()).isNotNull(); + assocId = resp.sourceApiAssociation().associationId(); + assertThat(assocId).isNotNull(); + assertThat(resp.sourceApiAssociation().sourceApiId()).isEqualTo(sourceApiId); + } + + @Test + @Order(108) + void getSourceApiAssociation() { + GetSourceApiAssociationResponse resp = client.getSourceApiAssociation( + GetSourceApiAssociationRequest.builder() + .mergedApiIdentifier(apiId) + .associationId(assocId) + .build()); + + assertThat(resp.sourceApiAssociation()).isNotNull(); + assertThat(resp.sourceApiAssociation().associationId()).isEqualTo(assocId); + assertThat(resp.sourceApiAssociation().sourceApiId()).isEqualTo(sourceApiId); + } + + @Test + @Order(109) + void listSourceApiAssociations() { + ListSourceApiAssociationsResponse resp = client.listSourceApiAssociations( + ListSourceApiAssociationsRequest.builder() + .apiId(apiId) + .build()); + + assertThat(resp.sourceApiAssociationSummaries()).isNotEmpty(); + } + + @Test + @Order(110) + void disassociateSourceGraphqlApi() { + DisassociateSourceGraphqlApiResponse resp = client.disassociateSourceGraphqlApi( + DisassociateSourceGraphqlApiRequest.builder() + .mergedApiIdentifier(apiId) + .associationId(assocId) + .build()); + + assertThat(resp).isNotNull(); + } + + @Test + @Order(111) + void cleanupSourceApi() { + client.deleteGraphqlApi(DeleteGraphqlApiRequest.builder() + .apiId(sourceApiId) + .build()); + } + + // ── Merged API Associations ──────────────────────────────────────── + + private static String mergedAssocSourceApiId; + private static String mergedAssocId; + + @Test + @Order(112) + void associateMergedGraphqlApi() { + CreateGraphqlApiResponse sourceResp = client.createGraphqlApi( + CreateGraphqlApiRequest.builder() + .name("sdk-merged-source") + .authenticationType("API_KEY") + .build()); + mergedAssocSourceApiId = sourceResp.graphqlApi().apiId(); + + AssociateMergedGraphqlApiResponse resp = client.associateMergedGraphqlApi( + AssociateMergedGraphqlApiRequest.builder() + .sourceApiIdentifier(mergedAssocSourceApiId) + .mergedApiIdentifier(apiId) + .build()); + + assertThat(resp.sourceApiAssociation()).isNotNull(); + mergedAssocId = resp.sourceApiAssociation().associationId(); + assertThat(mergedAssocId).isNotNull(); + assertThat(resp.sourceApiAssociation().sourceApiId()).isEqualTo(mergedAssocSourceApiId); + assertThat(resp.sourceApiAssociation().mergedApiId()).isEqualTo(apiId); + } + + @Test + @Order(113) + void updateSourceApiAssociation() { + CreateGraphqlApiResponse updateSourceResp = client.createGraphqlApi( + CreateGraphqlApiRequest.builder() + .name("sdk-update-source") + .authenticationType("API_KEY") + .build()); + String updateSourceApiId = updateSourceResp.graphqlApi().apiId(); + + AssociateSourceGraphqlApiResponse assocResp = client.associateSourceGraphqlApi( + AssociateSourceGraphqlApiRequest.builder() + .mergedApiIdentifier(apiId) + .sourceApiIdentifier(updateSourceApiId) + .build()); + String updateAssocId = assocResp.sourceApiAssociation().associationId(); + + UpdateSourceApiAssociationResponse resp = client.updateSourceApiAssociation( + UpdateSourceApiAssociationRequest.builder() + .mergedApiIdentifier(apiId) + .associationId(updateAssocId) + .description("updated-association") + .build()); + + assertThat(resp.sourceApiAssociation()).isNotNull(); + assertThat(resp.sourceApiAssociation().associationId()).isEqualTo(updateAssocId); + assertThat(resp.sourceApiAssociation().description()).isEqualTo("updated-association"); + + client.deleteGraphqlApi(DeleteGraphqlApiRequest.builder().apiId(updateSourceApiId).build()); + } + + @Test + @Order(114) + void disassociateMergedGraphqlApi() { + DisassociateMergedGraphqlApiResponse resp = client.disassociateMergedGraphqlApi( + DisassociateMergedGraphqlApiRequest.builder() + .sourceApiIdentifier(mergedAssocSourceApiId) + .associationId(mergedAssocId) + .build()); + + assertThat(resp).isNotNull(); + assertThat(resp.sourceApiAssociationStatus()).isNotNull(); + } + + @Test + @Order(115) + void cleanupMergedSourceApi() { + client.deleteGraphqlApi(DeleteGraphqlApiRequest.builder() + .apiId(mergedAssocSourceApiId) + .build()); + } + // ── Error Handling ───────────────────────────────────────────────── @Test diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md index d4fdf3f21a..ebb2b7c8aa 100644 --- a/docs/configuration/advanced/application-yml.md +++ b/docs/configuration/advanced/application-yml.md @@ -216,6 +216,9 @@ floci: enabled: true mock: false # true = tasks go to RUNNING without Docker (useful for CI) + appsync: + enabled: true + appconfig: enabled: true diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index ded893c80c..94c7db6870 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -405,6 +405,7 @@ These services spawn Docker containers. They require access to the Docker socket | Variable | Default | Description | |---|---|---| | `FLOCI_SERVICES_GLUE_ENABLED` | `true` | Enable the Glue service | +| `FLOCI_SERVICES_APPSYNC_ENABLED` | `true` | Enable the AppSync service | | `FLOCI_SERVICES_BEDROCK_RUNTIME_ENABLED` | `true` | Enable the Bedrock Runtime service | | `FLOCI_SERVICES_TEXTRACT_ENABLED` | `true` | Enable the Textract service | | `FLOCI_SERVICES_TRANSFER_ENABLED` | `true` | Enable the Transfer Family service | diff --git a/docs/configuration/storage.md b/docs/configuration/storage.md index fce4a1a009..240905da0f 100644 --- a/docs/configuration/storage.md +++ b/docs/configuration/storage.md @@ -46,6 +46,8 @@ When not set for a service, it inherits `FLOCI_STORAGE_MODE`. Only override when | `FLOCI_STORAGE_SERVICES_SECRETSMANAGER_FLUSH_INTERVAL_MS` | `5000` | Secrets Manager flush interval (ms) | | `FLOCI_STORAGE_SERVICES_ACM_MODE` | global default | ACM storage mode | | `FLOCI_STORAGE_SERVICES_ACM_FLUSH_INTERVAL_MS` | `5000` | ACM flush interval (ms) | +| `FLOCI_STORAGE_SERVICES_APPSYNC_MODE` | global default | AppSync storage mode | +| `FLOCI_STORAGE_SERVICES_APPSYNC_FLUSH_INTERVAL_MS` | `5000` | AppSync flush interval (ms) | | `FLOCI_STORAGE_SERVICES_OPENSEARCH_MODE` | global default | OpenSearch storage mode | | `FLOCI_STORAGE_SERVICES_OPENSEARCH_FLUSH_INTERVAL_MS` | `5000` | OpenSearch flush interval (ms) | | `FLOCI_STORAGE_SERVICES_RDS_MODE` | global default | RDS metadata storage mode (see note below) | diff --git a/docs/index.md b/docs/index.md index 1f51fe13cf..3682d752ef 100644 --- a/docs/index.md +++ b/docs/index.md @@ -12,7 +12,7 @@ Floci is a fast, free, and open-source local AWS service emulator built for deve ## Supported Services -Floci emulates 51 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details. +Floci emulates 52 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details. | Service | Protocol | |---|---| @@ -25,6 +25,7 @@ Floci emulates 51 AWS services. See the [Services Overview](services/index.md) f | DynamoDB + Streams | JSON 1.1 | | Lambda | REST JSON | | API Gateway v1 & v2 | REST JSON | +| AppSync | REST JSON | | Cognito | JSON 1.1 | | KMS | JSON 1.1 | | Kinesis | JSON 1.1 | diff --git a/docs/services/appsync.md b/docs/services/appsync.md index 2143ca3285..73e445088a 100644 --- a/docs/services/appsync.md +++ b/docs/services/appsync.md @@ -3,7 +3,7 @@ **Protocol:** REST JSON **Endpoint:** `http://localhost:4566/v1/apis/...` -Floci implements the AWS AppSync Management API, providing local emulation of GraphQL API configuration, schema management, data source binding, resolver mapping, and API key provisioning. +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. ## Supported Operations @@ -21,7 +21,7 @@ Floci implements the AWS AppSync Management API, providing local emulation of Gr | Operation | Description | |---|---| -| `StartSchemaCreation` | Start schema creation (always synchronous) | +| `StartSchemaCreation` | Start schema creation — validates and parses SDL using graphql-java (invalid SDL returns 400) | | `GetSchemaCreationStatus` | Get schema creation status | | `GetIntrospectionSchema` | Get the introspection schema | @@ -92,6 +92,88 @@ Floci implements the AWS AppSync Management API, providing local emulation of Gr | `GetEnvironmentVariables` | Get environment variables for an API | | `PutEnvironmentVariables` | Set environment variables for an API | +### Domain Names + +| Operation | Description | +|---|---| +| `CreateDomainName` | Register a custom domain name | +| `GetDomainName` | Get domain name configuration | +| `UpdateDomainName` | Update domain name description | +| `ListDomainNames` | List all domain names | +| `DeleteDomainName` | Delete a custom domain name | +| `AssociateApi` | Associate a domain name with a GraphQL API | +| `GetAssociatedApi` | Get the API associated with a domain name | +| `DisassociateApi` | Disassociate a domain name from a GraphQL API | +| `ListApiAssociations` | List all associations for an API | + +### Channel Namespaces + +| Operation | Description | +|---|---| +| `CreateChannelNamespace` | Create a channel namespace | +| `GetChannelNamespace` | Get a channel namespace by name | +| `UpdateChannelNamespace` | Update a channel namespace description | +| `ListChannelNamespaces` | List all channel namespaces for an API | +| `DeleteChannelNamespace` | Delete a channel namespace | + +### Merged API Associations + +| Operation | Description | +|---|---| +| `CreateApiAssociation` | Associate a source API with a merged API | +| `GetApiAssociation` | Get a merged API association | +| `DeleteApiAssociation` | Delete a merged API association | +| `ListApiAssociations` | List all merged API associations | + +### Enhanced Metrics + +| Operation | Description | +|---|---| +| `GetEnhancedMetricsConfig` | Get the enhanced metrics configuration | + +## Schema Registry + +`StartSchemaCreation` validates the provided GraphQL SDL using [graphql-java](https://github.com/graphql-java/graphql-java). Invalid schemas are rejected with a `BadRequestException` (400) at registration time, preventing them from being caught later during query execution. + +The following **AWS scalar types** are pre-registered and available in any schema without requiring explicit `scalar` declarations: + +| Scalar | Java Type | Validation | +|--------|-----------|------------| +| `AWSJSON` | String | Valid JSON syntax | +| `AWSDateTime` | String | ISO 8601 datetime | +| `AWSDate` | String | ISO 8601 date (yyyy-MM-dd) | +| `AWSTime` | String | ISO 8601 time | +| `AWSTimestamp` | Long | Unix epoch seconds (0 to 32503680000) | +| `AWSEmail` | String | RFC 5322 email format | +| `AWSURL` | String | Valid URL | +| `AWSPhone` | String | E.164 format (+1234567890) | +| `AWSIPAddress` | String | IPv4 or IPv6 | +| `AWSBoolean` | Boolean | Boolean value | +| `AWSLong` | Long | 64-bit signed integer | +| `AWSInteger` | Integer | 32-bit signed integer | +| `AWSShort` | Integer | 16-bit signed integer (-32768 to 32767) | +| `AWSFloat` | Double | IEEE 754 double-precision | +| `AWSBigDecimal` | String | Arbitrary-precision decimal | +| `AWSBigInt` | String | Arbitrary-precision integer | +| `AWSByte` | String | Base64-encoded byte array | + +The following **AppSync directives** are pre-defined and recognized in schemas: + +| Directive | Locations | Purpose | +|-----------|-----------|---------| +| `@aws_api_key` | OBJECT, FIELD_DEFINITION | Require API key auth | +| `@aws_iam` | OBJECT, FIELD_DEFINITION | Require IAM auth | +| `@aws_cognito_user_pools(cognito_groups: [String!]!)` | OBJECT, FIELD_DEFINITION | Require Cognito user pool auth | +| `@aws_oidc` | OBJECT, FIELD_DEFINITION | Require OIDC auth | +| `@aws_lambda` | OBJECT, FIELD_DEFINITION | Require Lambda auth | +| `@aws_subscribe(mutations: [String!]!)` | FIELD_DEFINITION | Link subscription to mutation | +| `@aws_auth(cognito_groups: [String!]!)` | OBJECT | Require Cognito groups | +| `@aws_delta_sync` | OBJECT | Delta sync configuration | + +Unknown directives are rejected during schema registration. + +Schema extensions (`extend type Query { ... }`) are supported natively through graphql-java. + ## Pagination All `List` operations support cursor-based pagination via query parameters: @@ -126,18 +208,24 @@ Deleting a GraphQL API (`DeleteGraphqlApi`) automatically deletes all child reso - All functions - All types - All API keys +- All channel namespaces +- All domain name associations This matches AWS behavior where deleting an API removes its entire configuration. ## Not Implemented -These AWS AppSync operations are not yet implemented: +These AWS AppSync operations are not yet implemented and are tracked in future phases: -- Real-time subscriptions (WebSocket) -- Pipeline resolvers -- Custom domain names -- Additional authentication providers management -- Data source service role validation +- **Execution engine** (Phase 5): GraphQL query execution, resolver dispatch, VTL template evaluation +- **Data source adapters** (Phase 7): DynamoDB, Lambda, HTTP, EventBridge, OpenSearch, RDS connectors +- **Pipeline resolvers** (Phase 8): Function chaining with `$prev` and `$stash` +- **Subscriptions** (Phase 9): WebSocket real-time subscriptions +- **Caching** (Phase 10): API-level and per-resolver caching +- **Authentication** (Phase 4): API key validation on the GraphQL endpoint +- **Introspection** (Phase 6): `__schema` and `__type` queries +- **Merged API source management**: `AssociateMergedGraphqlApi`, `AssociateSourceGraphqlApi`, `StartSchemaMerge`, `ListTypesByAssociation` +- **Data source introspection**: `StartDataSourceIntrospection`, `GetDataSourceIntrospection` ## Configuration @@ -186,4 +274,22 @@ aws appsync create-api-key \ # List all APIs aws appsync list-graphql-apis \ --endpoint-url $AWS_ENDPOINT_URL + +# Register a custom domain +aws appsync create-domain-name \ + --domain-name api.example.com \ + --certificate-arn arn:aws:acm:us-east-1:000000000000:certificate/123 \ + --endpoint-url $AWS_ENDPOINT_URL + +# Associate domain with API +aws appsync associate-api \ + --domain-name api.example.com \ + --api-id API_ID \ + --endpoint-url $AWS_ENDPOINT_URL + +# Create a channel namespace +aws appsync create-channel-namespace \ + --api-id API_ID \ + --name my-channels \ + --endpoint-url $AWS_ENDPOINT_URL ``` diff --git a/pom.xml b/pom.xml index c80d88edc1..a7f14dc83e 100644 --- a/pom.xml +++ b/pom.xml @@ -162,6 +162,13 @@ 2.4.1 + + + com.graphql-java + graphql-java + 22.0 + + com.networknt diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncController.java b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncController.java index 8904c8fce2..4db4f445ce 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncController.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/AppSyncController.java @@ -62,8 +62,8 @@ public class AppSyncController { @POST @Path("/v1/apis/{apiId}") public Response updateGraphqlApi(@Context HttpHeaders headers, - @PathParam("apiId") String apiId, - String body) throws IOException { + @PathParam("apiId") String apiId, + String body) throws IOException { String region = regionResolver.resolveRegion(headers); @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); @@ -128,7 +128,9 @@ public class AppSyncController { public Response getIntrospectionSchema(@PathParam("apiId") String apiId) { String schema = service.getIntrospectionSchema(apiId); ObjectNode root = objectMapper.createObjectNode(); - root.put("schema", schema); + ObjectNode schemaNode = objectMapper.createObjectNode(); + schemaNode.put("definition", schema); + root.set("schema", schemaNode); return Response.ok(root).build(); } @@ -136,10 +138,13 @@ public class AppSyncController { @POST @Path("/v1/apis/{apiId}/datasources") - public Response createDataSource(@PathParam("apiId") String apiId, String body) throws IOException { + public Response createDataSource(@Context HttpHeaders headers, + @PathParam("apiId") String apiId, + String body) throws IOException { + String region = regionResolver.resolveRegion(headers); @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); - DataSource ds = service.createDataSource(apiId, request); + DataSource ds = service.createDataSource(apiId, request, region); ObjectNode root = objectMapper.createObjectNode(); root.set("dataSource", objectMapper.valueToTree(ds)); return Response.status(200).entity(root).build(); @@ -157,8 +162,8 @@ public class AppSyncController { @POST @Path("/v1/apis/{apiId}/datasources/{name}") public Response updateDataSource(@PathParam("apiId") String apiId, - @PathParam("name") String name, - String body) throws IOException { + @PathParam("name") String name, + String body) throws IOException { @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); DataSource ds = service.updateDataSource(apiId, name, request); @@ -170,7 +175,7 @@ public class AppSyncController { @DELETE @Path("/v1/apis/{apiId}/datasources/{name}") public Response deleteDataSource(@PathParam("apiId") String apiId, - @PathParam("name") String name) { + @PathParam("name") String name) { service.deleteDataSource(apiId, name); return Response.noContent().build(); } @@ -196,13 +201,15 @@ public class AppSyncController { @POST @Path("/v1/apis/{apiId}/types/{typeName}/resolvers") - public Response createResolver(@PathParam("apiId") String apiId, - @PathParam("typeName") String typeName, - String body) throws IOException { + public Response createResolver(@Context HttpHeaders headers, + @PathParam("apiId") String apiId, + @PathParam("typeName") String typeName, + String body) throws IOException { + String region = regionResolver.resolveRegion(headers); @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); request.put("typeName", typeName); - Resolver resolver = service.createResolver(apiId, request); + Resolver resolver = service.createResolver(apiId, request, region); ObjectNode root = objectMapper.createObjectNode(); root.set("resolver", objectMapper.valueToTree(resolver)); return Response.status(200).entity(root).build(); @@ -257,9 +264,9 @@ public class AppSyncController { @POST @Path("/v1/apis/{apiId}/types/{typeName}/resolvers/{fieldName}") public Response updateResolver(@PathParam("apiId") String apiId, - @PathParam("typeName") String typeName, - @PathParam("fieldName") String fieldName, - String body) throws IOException { + @PathParam("typeName") String typeName, + @PathParam("fieldName") String fieldName, + String body) throws IOException { @SuppressWarnings("unchecked") Map request = objectMapper.readValue(body, Map.class); Resolver resolver = service.updateResolver(apiId, typeName, fieldName, request); @@ -271,8 +278,8 @@ public class AppSyncController { @DELETE @Path("/v1/apis/{apiId}/types/{typeName}/resolvers/{fieldName}") public Response deleteResolver(@PathParam("apiId") String apiId, - @PathParam("typeName") String typeName, - @PathParam("fieldName") String fieldName) { + @PathParam("typeName") String typeName, + @PathParam("fieldName") String fieldName) { service.deleteResolver(apiId, typeName, fieldName); return Response.noContent().build(); } @@ -537,4 +544,237 @@ public class AppSyncController { return Response.ok(root).build(); } + // ──────────────────────────── Domain Names ──────────────────────────── + + @POST + @Path("/v1/domainnames") + public Response createDomainName(String body) throws IOException { + @SuppressWarnings("unchecked") + Map request = objectMapper.readValue(body, Map.class); + DomainName dn = service.createDomainName(request); + ObjectNode root = objectMapper.createObjectNode(); + root.set("domainNameConfig", objectMapper.valueToTree(dn)); + return Response.status(200).entity(root).build(); + } + + @GET + @Path("/v1/domainnames/{domainName}") + public Response getDomainName(@PathParam("domainName") String domainName) { + DomainName dn = service.getDomainName(domainName); + ObjectNode root = objectMapper.createObjectNode(); + root.set("domainNameConfig", objectMapper.valueToTree(dn)); + return Response.ok(root).build(); + } + + @GET + @Path("/v1/domainnames") + public Response listDomainNames(@QueryParam("maxResults") Integer maxResults, + @QueryParam("nextToken") String nextToken) { + var page = service.listDomainNames(maxResults, nextToken); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("domainNames"); + page.items().forEach(items::addPOJO); + if (page.nextToken() != null) { + root.put("nextToken", page.nextToken()); + } else { + root.putNull("nextToken"); + } + return Response.ok(root).build(); + } + + @POST + @Path("/v1/domainnames/{domainName}") + public Response updateDomainName(@PathParam("domainName") String domainName, + String body) throws IOException { + @SuppressWarnings("unchecked") + Map request = objectMapper.readValue(body, Map.class); + DomainName dn = service.updateDomainName(domainName, request); + ObjectNode root = objectMapper.createObjectNode(); + root.set("domainNameConfig", objectMapper.valueToTree(dn)); + return Response.ok(root).build(); + } + + @DELETE + @Path("/v1/domainnames/{domainName}") + public Response deleteDomainName(@PathParam("domainName") String domainName) { + service.deleteDomainName(domainName); + return Response.noContent().build(); + } + + @POST + @Path("/v1/domainnames/{domainName}/apiassociation") + public Response associateApi(@PathParam("domainName") String domainName, String body) throws IOException { + @SuppressWarnings("unchecked") + Map request = objectMapper.readValue(body, Map.class); + String apiId = (String) request.get("apiId"); + var assoc = service.associateApi(domainName, apiId); + ObjectNode root = objectMapper.createObjectNode(); + root.set("apiAssociation", objectMapper.valueToTree(assoc)); + return Response.status(200).entity(root).build(); + } + + @GET + @Path("/v1/domainnames/{domainName}/apiassociation") + public Response getApiAssociation(@PathParam("domainName") String domainName) { + var assoc = service.getApiAssociation(domainName); + ObjectNode root = objectMapper.createObjectNode(); + root.set("apiAssociation", objectMapper.valueToTree(assoc)); + return Response.ok(root).build(); + } + + @DELETE + @Path("/v1/domainnames/{domainName}/apiassociation") + public Response disassociateApi(@PathParam("domainName") String domainName) { + service.disassociateApi(domainName); + return Response.noContent().build(); + } + + // ──────────────────────────── Channel Namespaces ──────────────────────────── + + @POST + @Path("/v2/apis/{apiId}/channelNamespaces") + public Response createChannelNamespace(@PathParam("apiId") String apiId, String body) throws IOException { + @SuppressWarnings("unchecked") + Map request = objectMapper.readValue(body, Map.class); + ChannelNamespace ns = service.createChannelNamespace(apiId, request); + ObjectNode root = objectMapper.createObjectNode(); + root.set("channelNamespace", objectMapper.valueToTree(ns)); + return Response.status(200).entity(root).build(); + } + + @GET + @Path("/v2/apis/{apiId}/channelNamespaces/{name}") + public Response getChannelNamespace(@PathParam("apiId") String apiId, @PathParam("name") String name) { + ChannelNamespace ns = service.getChannelNamespace(apiId, name); + ObjectNode root = objectMapper.createObjectNode(); + root.set("channelNamespace", objectMapper.valueToTree(ns)); + return Response.ok(root).build(); + } + + @POST + @Path("/v2/apis/{apiId}/channelNamespaces/{name}") + public Response updateChannelNamespace(@PathParam("apiId") String apiId, + @PathParam("name") String name, + String body) throws IOException { + @SuppressWarnings("unchecked") + Map request = objectMapper.readValue(body, Map.class); + ChannelNamespace ns = service.updateChannelNamespace(apiId, name, request); + ObjectNode root = objectMapper.createObjectNode(); + root.set("channelNamespace", objectMapper.valueToTree(ns)); + return Response.ok(root).build(); + } + + @DELETE + @Path("/v2/apis/{apiId}/channelNamespaces/{name}") + public Response deleteChannelNamespace(@PathParam("apiId") String apiId, @PathParam("name") String name) { + service.deleteChannelNamespace(apiId, name); + return Response.noContent().build(); + } + + @GET + @Path("/v2/apis/{apiId}/channelNamespaces") + public Response listChannelNamespaces(@PathParam("apiId") String apiId, + @QueryParam("maxResults") Integer maxResults, + @QueryParam("nextToken") String nextToken) { + var page = service.listChannelNamespaces(apiId, maxResults, nextToken); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("channelNamespaces"); + page.items().forEach(items::addPOJO); + if (page.nextToken() != null) { + root.put("nextToken", page.nextToken()); + } else { + root.putNull("nextToken"); + } + return Response.ok(root).build(); + } + + // ──────────────────────────── Merged API Associations ───────────────── + + @POST + @Path("/v1/sourceApis/{sourceApiIdentifier}/mergedApiAssociations") + public Response associateMergedGraphqlApi(@Context HttpHeaders headers, + @PathParam("sourceApiIdentifier") String sourceApiIdentifier, + String body) throws IOException { + String region = regionResolver.resolveRegion(headers); + @SuppressWarnings("unchecked") + Map request = objectMapper.readValue(body, Map.class); + var assoc = service.createMergedApiAssociation(sourceApiIdentifier, request, region); + ObjectNode root = objectMapper.createObjectNode(); + root.set("sourceApiAssociation", objectMapper.valueToTree(assoc)); + return Response.status(200).entity(root).build(); + } + + @POST + @Path("/v1/mergedApis/{mergedApiIdentifier}/sourceApiAssociations") + public Response associateSourceGraphqlApi(@Context HttpHeaders headers, + @PathParam("mergedApiIdentifier") String mergedApiIdentifier, + String body) throws IOException { + String region = regionResolver.resolveRegion(headers); + @SuppressWarnings("unchecked") + Map request = objectMapper.readValue(body, Map.class); + var assoc = service.createSourceApiAssociation(mergedApiIdentifier, request, region); + ObjectNode root = objectMapper.createObjectNode(); + root.set("sourceApiAssociation", objectMapper.valueToTree(assoc)); + return Response.status(200).entity(root).build(); + } + + @GET + @Path("/v1/mergedApis/{mergedApiIdentifier}/sourceApiAssociations/{associationId}") + public Response getSourceApiAssociation(@PathParam("mergedApiIdentifier") String mergedApiIdentifier, + @PathParam("associationId") String associationId) { + var assoc = service.getSourceApiAssociation(mergedApiIdentifier, associationId); + ObjectNode root = objectMapper.createObjectNode(); + root.set("sourceApiAssociation", objectMapper.valueToTree(assoc)); + return Response.ok(root).build(); + } + + @POST + @Path("/v1/mergedApis/{mergedApiIdentifier}/sourceApiAssociations/{associationId}") + public Response updateSourceApiAssociation(@PathParam("mergedApiIdentifier") String mergedApiIdentifier, + @PathParam("associationId") String associationId, + String body) throws IOException { + @SuppressWarnings("unchecked") + Map request = objectMapper.readValue(body, Map.class); + var assoc = service.updateSourceApiAssociation(mergedApiIdentifier, associationId, request); + ObjectNode root = objectMapper.createObjectNode(); + root.set("sourceApiAssociation", objectMapper.valueToTree(assoc)); + return Response.ok(root).build(); + } + + @GET + @Path("/v1/apis/{apiId}/sourceApiAssociations") + public Response listSourceApiAssociations(@PathParam("apiId") String apiId, + @QueryParam("maxResults") Integer maxResults, + @QueryParam("nextToken") String nextToken) { + var page = service.listSourceApiAssociations(apiId, maxResults, nextToken); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode items = root.putArray("sourceApiAssociationSummaries"); + page.items().forEach(items::addPOJO); + if (page.nextToken() != null) { + root.put("nextToken", page.nextToken()); + } else { + root.putNull("nextToken"); + } + return Response.ok(root).build(); + } + + @DELETE + @Path("/v1/mergedApis/{mergedApiIdentifier}/sourceApiAssociations/{associationId}") + public Response disassociateSourceGraphqlApi(@PathParam("mergedApiIdentifier") String mergedApiIdentifier, + @PathParam("associationId") String associationId) { + service.deleteSourceApiAssociation(mergedApiIdentifier, associationId); + ObjectNode root = objectMapper.createObjectNode(); + root.put("sourceApiAssociationStatus", "DELETION_SCHEDULED"); + return Response.ok(root).build(); + } + + @DELETE + @Path("/v1/sourceApis/{sourceApiIdentifier}/mergedApiAssociations/{associationId}") + public Response disassociateMergedGraphqlApi(@PathParam("sourceApiIdentifier") String sourceApiIdentifier, + @PathParam("associationId") String associationId) { + var assoc = service.deleteMergedApiAssociation(sourceApiIdentifier, associationId); + ObjectNode root = objectMapper.createObjectNode(); + root.put("sourceApiAssociationStatus", assoc.getSourceApiAssociationStatus()); + return Response.ok(root).build(); + } } 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 7f27bf3d89..f43b555cf3 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 @@ -1,18 +1,19 @@ package io.github.hectorvent.floci.services.appsync; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.appsync.graphql.SchemaRegistry; import io.github.hectorvent.floci.services.appsync.model.*; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; import java.util.Base64; @ApplicationScoped @@ -20,17 +21,24 @@ public class AppSyncService { private static final Logger LOG = Logger.getLogger(AppSyncService.class); private final StorageBackend apiStore; - private final StorageBackend schemaStore; // apiId -> schema SDL + private final StorageBackend schemaStore; private final StorageBackend schemaStatusStore; private final StorageBackend dataSourceStore; private final StorageBackend resolverStore; private final StorageBackend functionStore; private final StorageBackend apiKeyStore; private final StorageBackend typeStore; + private final StorageBackend domainStore; + private final StorageBackend associationStore; + private final StorageBackend channelNamespaceStore; + private final StorageBackend mergedApiAssociationStore; private final RegionResolver regionResolver; + private final SchemaRegistry schemaRegistry; + private final ObjectMapper objectMapper; @Inject - public AppSyncService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) { + public AppSyncService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver, + SchemaRegistry schemaRegistry, ObjectMapper objectMapper) { this.apiStore = storageFactory.create("appsync", "appsync-apis.json", new TypeReference<>() {}); this.schemaStore = storageFactory.create("appsync", "appsync-schemas.json", new TypeReference<>() {}); this.schemaStatusStore = storageFactory.create("appsync", "appsync-schema-status.json", new TypeReference<>() {}); @@ -39,7 +47,13 @@ public class AppSyncService { this.functionStore = storageFactory.create("appsync", "appsync-functions.json", new TypeReference<>() {}); this.apiKeyStore = storageFactory.create("appsync", "appsync-apikeys.json", new TypeReference<>() {}); this.typeStore = storageFactory.create("appsync", "appsync-types.json", new TypeReference<>() {}); + this.domainStore = storageFactory.create("appsync", "appsync-domainnames.json", new TypeReference<>() {}); + this.associationStore = storageFactory.create("appsync", "appsync-associations.json", new TypeReference<>() {}); + this.channelNamespaceStore = storageFactory.create("appsync", "appsync-channelnamespaces.json", new TypeReference<>() {}); + this.mergedApiAssociationStore = storageFactory.create("appsync", "appsync-merged-api-associations.json", new TypeReference<>() {}); this.regionResolver = regionResolver; + this.schemaRegistry = schemaRegistry; + this.objectMapper = objectMapper; } // ──────────────────────────── GraphQL API ──────────────────────────── @@ -49,11 +63,15 @@ public class AppSyncService { if (name == null || name.isBlank()) { throw new AwsException("BadRequestException", "A GraphQL API name is required", 400); } + String authType = (String) request.get("authenticationType"); + if (authType == null || authType.isBlank()) { + throw new AwsException("BadRequestException", "The authenticationType is required", 400); + } String apiId = generateApiId(); GraphqlApi api = new GraphqlApi(); api.setApiId(apiId); api.setName(name); - api.setAuthenticationType(parseEnum(AuthenticationType.class, request.get("authenticationType"))); + api.setAuthenticationType(parseEnum(AuthenticationType.class, authType)); Object xrayValue = request.get("xrayEnabled"); if (xrayValue instanceof Boolean b) { api.setXrayEnabled(b); @@ -62,18 +80,27 @@ public class AppSyncService { } else { api.setXrayEnabled(false); } - api.setLogConfig((Map) request.get("logConfig")); + api.setLogConfig(castMap(request.get("logConfig"))); + + api.setApiType(coerceString(request.get("apiType"), "GRAPHQL")); + api.setOwner(coerceString(request.get("owner"))); + api.setOwnerContact(coerceString(request.get("ownerContact"))); + api.setVisibility(coerceString(request.get("visibility"), "GLOBAL")); + api.setIntrospectionConfig(coerceString(request.get("introspectionConfig"))); + api.setQueryDepthLimit(castInt(request.get("queryDepthLimit"))); + api.setResolverCountLimit(castInt(request.get("resolverCountLimit"))); + api.setEnhancedMetricsConfig(castMap(request.get("enhancedMetricsConfig"))); + api.setLambdaAuthorizerConfig(castMap(request.get("lambdaAuthorizerConfig"))); + api.setOpenIDConnectConfig(castMap(request.get("openIDConnectConfig"))); + api.setUserPoolConfig(castMap(request.get("userPoolConfig"))); + api.setDns(castStringMap(request.get("dns"))); + api.setWafWebAclArn(coerceString(request.get("wafWebAclArn"))); + api.setMergedApiExecutionRoleArn(coerceString(request.get("mergedApiExecutionRoleArn"))); Object additionalObj = request.get("additionalAuthenticationProviders"); if (additionalObj instanceof List additionalList) { - List> providers = new ArrayList<>(); - for (Object item : additionalList) { - if (item instanceof Map map) { - @SuppressWarnings("unchecked") - Map casted = (Map) map; - providers.add(casted); - } - } + List providers = objectMapper.convertValue( + additionalList, new TypeReference>() {}); api.setAdditionalAuthenticationProviders(providers); } @@ -85,10 +112,10 @@ public class AppSyncService { uris.put("REALTIME", "ws://localhost:4566/v1/apis/" + apiId + "/graphql/realtime"); api.setUris(uris); - Map tags = (Map) request.get("tags"); + Map tags = castMap(request.get("tags")); if (tags != null) { Map tagMap = new HashMap<>(); - tags.forEach((k, v) -> tagMap.put(k, String.valueOf(v))); + tags.forEach((k, v) -> tagMap.put(k, v != null ? String.valueOf(v) : "")); api.setTags(tagMap); } @@ -106,6 +133,7 @@ public class AppSyncService { return paginate(apiStore.scan(k -> true), nextToken, maxResults); } + @SuppressWarnings("unchecked") public GraphqlApi updateGraphqlApi(String apiId, Map request, String region) { GraphqlApi existing = getGraphqlApi(apiId); if (request.containsKey("name")) existing.setName((String) request.get("name")); @@ -122,9 +150,34 @@ public class AppSyncService { if (request.containsKey("tags")) { Map tags = (Map) request.get("tags"); Map tagMap = new HashMap<>(); - tags.forEach((k, v) -> tagMap.put(k, String.valueOf(v))); + tags.forEach((k, v) -> tagMap.put(k, v != null ? String.valueOf(v) : "")); existing.setTags(tagMap); } + if (request.containsKey("apiType")) existing.setApiType((String) request.get("apiType")); + if (request.containsKey("owner")) existing.setOwner((String) request.get("owner")); + if (request.containsKey("ownerContact")) existing.setOwnerContact((String) request.get("ownerContact")); + if (request.containsKey("visibility")) existing.setVisibility((String) request.get("visibility")); + if (request.containsKey("introspectionConfig")) existing.setIntrospectionConfig((String) request.get("introspectionConfig")); + if (request.containsKey("queryDepthLimit")) existing.setQueryDepthLimit(castInt(request.get("queryDepthLimit"))); + if (request.containsKey("resolverCountLimit")) existing.setResolverCountLimit(castInt(request.get("resolverCountLimit"))); + if (request.containsKey("enhancedMetricsConfig")) existing.setEnhancedMetricsConfig((Map) request.get("enhancedMetricsConfig")); + if (request.containsKey("lambdaAuthorizerConfig")) existing.setLambdaAuthorizerConfig((Map) request.get("lambdaAuthorizerConfig")); + if (request.containsKey("openIDConnectConfig")) existing.setOpenIDConnectConfig((Map) request.get("openIDConnectConfig")); + if (request.containsKey("userPoolConfig")) existing.setUserPoolConfig((Map) request.get("userPoolConfig")); + if (request.containsKey("dns")) { + @SuppressWarnings("unchecked") + Map dns = (Map) request.get("dns"); + existing.setDns(dns); + } + if (request.containsKey("wafWebAclArn")) existing.setWafWebAclArn((String) request.get("wafWebAclArn")); + if (request.containsKey("mergedApiExecutionRoleArn")) existing.setMergedApiExecutionRoleArn((String) request.get("mergedApiExecutionRoleArn")); + if (request.containsKey("additionalAuthenticationProviders")) { + Object additionalObj = request.get("additionalAuthenticationProviders"); + if (additionalObj instanceof List additionalList) { + existing.setAdditionalAuthenticationProviders( + objectMapper.convertValue(additionalList, new TypeReference>() {})); + } + } apiStore.put(apiId, existing); return existing; } @@ -134,11 +187,14 @@ public class AppSyncService { apiStore.delete(apiId); schemaStore.delete(apiId); schemaStatusStore.delete(apiId); + schemaRegistry.remove(apiId); deleteDataSourcesForApi(apiId); deleteResolversForApi(apiId); deleteFunctionsForApi(apiId); deleteTypesForApi(apiId); deleteApiKeysForApi(apiId); + deleteChannelNamespacesForApi(apiId); + deleteDomainAssociationsForApi(apiId); LOG.infov("Deleted GraphQL API {0}", apiId); } @@ -146,6 +202,7 @@ public class AppSyncService { public void startSchemaCreation(String apiId, String definition) { getGraphqlApi(apiId); + schemaRegistry.register(apiId, definition); schemaStore.put(apiId, definition); SchemaCreationStatus status = new SchemaCreationStatus(); status.setStatus(SchemaCreationStatusType.ACTIVE); @@ -161,12 +218,14 @@ public class AppSyncService { public String getIntrospectionSchema(String apiId) { getGraphqlApi(apiId); - return schemaStore.get(apiId).orElse(null); + return schemaStore.get(apiId) + .orElseThrow(() -> new AwsException("NotFoundException", + "Schema not found for API: " + apiId, 404)); } // ──────────────────────────── Data Sources ──────────────────────────── - public DataSource createDataSource(String apiId, Map request) { + public DataSource createDataSource(String apiId, Map request, String region) { getGraphqlApi(apiId); String name = (String) request.get("name"); if (name == null || name.isBlank()) { @@ -180,15 +239,20 @@ public class AppSyncService { ds.setDescription((String) request.get("description")); ds.setType(parseEnum(DataSourceType.class, request.get("type"))); ds.setServiceRoleArn((String) request.get("serviceRoleArn")); - ds.setDynamodbConfig((Map) request.get("dynamodbConfig")); - ds.setLambdaConfig((Map) request.get("lambdaConfig")); - ds.setHttpConfig((Map) request.get("httpConfig")); - ds.setEventBridgeConfig((Map) request.get("eventBridgeConfig")); - ds.setRelationalDatabaseConfig((Map) request.get("relationalDatabaseConfig")); - ds.setOpenSearchServiceConfig((Map) request.get("openSearchServiceConfig")); - ds.setAmazonBedrockRuntimeConfig((Map) request.get("amazonBedrockRuntimeConfig")); + ds.setDynamodbConfig(castMap(request.get("dynamodbConfig"))); + ds.setLambdaConfig(castMap(request.get("lambdaConfig"))); + ds.setHttpConfig(castMap(request.get("httpConfig"))); + ds.setEventBridgeConfig(castMap(request.get("eventBridgeConfig"))); + ds.setRelationalDatabaseConfig(castMap(request.get("relationalDatabaseConfig"))); + ds.setOpenSearchServiceConfig(castMap(request.get("openSearchServiceConfig"))); + ds.setAmazonBedrockRuntimeConfig(castMap(request.get("amazonBedrockRuntimeConfig"))); + ds.setDataSourceArn(regionResolver.buildArn("appsync", region, "apis/" + apiId + "/datasources/" + name)); - dataSourceStore.put(apiKey(apiId, ds.getName()), ds); + String dsKey = apiKey(apiId, ds.getName()); + if (dataSourceStore.get(dsKey).isPresent()) { + throw new AwsException("ConflictException", "Data source already exists: " + name, 409); + } + dataSourceStore.put(dsKey, ds); return ds; } @@ -201,6 +265,7 @@ public class AppSyncService { return paginate(dataSourceStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults); } + @SuppressWarnings("unchecked") public DataSource updateDataSource(String apiId, String dataSourceName, Map request) { DataSource existing = getDataSource(apiId, dataSourceName); if (request.containsKey("description")) existing.setDescription((String) request.get("description")); @@ -222,20 +287,9 @@ public class AppSyncService { dataSourceStore.delete(apiKey(apiId, dataSourceName)); } - private void deleteDataSourcesForApi(String apiId) { - dataSourceStore.scan(k -> k.startsWith(apiId + "::")) - .forEach(ds -> { - try { - dataSourceStore.delete(apiKey(apiId, ds.getName())); - } catch (Exception e) { - // ignore - already deleted - } - }); - } - // ──────────────────────────── Resolvers ──────────────────────────── - public Resolver createResolver(String apiId, Map request) { + public Resolver createResolver(String apiId, Map request, String region) { getGraphqlApi(apiId); String fieldName = (String) request.get("fieldName"); if (fieldName == null || fieldName.isBlank()) { @@ -245,9 +299,15 @@ public class AppSyncService { 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"); + if (typeName == null || typeName.isBlank()) { + throw new AwsException("BadRequestException", "A type name is required for the resolver", 400); + } + // Validate data source exists + getDataSource(apiId, dataSourceName); Resolver resolver = new Resolver(); resolver.setApiId(apiId); - resolver.setTypeName((String) request.get("typeName")); + resolver.setTypeName(typeName); resolver.setFieldName((String) request.get("fieldName")); resolver.setDataSourceName((String) request.get("dataSourceName")); resolver.setFunctionId((String) request.get("functionId")); @@ -255,8 +315,15 @@ public class AppSyncService { resolver.setResponseMappingTemplate((String) request.get("responseMappingTemplate")); resolver.setKind(parseEnum(ResolverKind.class, request.getOrDefault("kind", "UNIT"))); resolver.setCode((String) request.get("code")); + resolver.setCachingConfig(castMap(request.get("cachingConfig"))); + resolver.setMaxBatchSize(castInt(request.get("maxBatchSize"))); + resolver.setMetricsConfig((String) request.get("metricsConfig")); + resolver.setPipelineConfig(castMap(request.get("pipelineConfig"))); + resolver.setSyncConfig(castMap(request.get("syncConfig"))); + resolver.setResolverArn(regionResolver.buildArn("appsync", region, + "apis/" + apiId + "/types/" + typeName + "/resolvers/" + fieldName)); - Map runtime = (Map) request.get("runtime"); + Map runtime = castMap(request.get("runtime")); if (runtime != null) { Resolver.ResolverRuntime rt = new Resolver.ResolverRuntime(); rt.setName(parseEnum(ResolverRuntimeName.class, runtime.get("name"))); @@ -265,6 +332,10 @@ public class AppSyncService { } String key = resolverKey(apiId, resolver.getTypeName(), resolver.getFieldName()); + if (resolverStore.get(key).isPresent()) { + throw new AwsException("ConflictException", + "Resolver already exists for " + typeName + "." + fieldName, 409); + } resolverStore.put(key, resolver); return resolver; } @@ -294,6 +365,7 @@ public class AppSyncService { return paginate(all, nextToken, maxResults); } + @SuppressWarnings("unchecked") public Resolver updateResolver(String apiId, String typeName, String fieldName, Map request) { Resolver existing = getResolver(apiId, typeName, fieldName); if (request.containsKey("dataSourceName")) existing.setDataSourceName((String) request.get("dataSourceName")); @@ -302,6 +374,11 @@ public class AppSyncService { if (request.containsKey("responseMappingTemplate")) existing.setResponseMappingTemplate((String) request.get("responseMappingTemplate")); if (request.containsKey("kind")) existing.setKind(parseEnum(ResolverKind.class, request.get("kind"))); if (request.containsKey("code")) existing.setCode((String) request.get("code")); + if (request.containsKey("cachingConfig")) existing.setCachingConfig((Map) request.get("cachingConfig")); + if (request.containsKey("maxBatchSize")) existing.setMaxBatchSize(castInt(request.get("maxBatchSize"))); + if (request.containsKey("metricsConfig")) existing.setMetricsConfig((String) request.get("metricsConfig")); + if (request.containsKey("pipelineConfig")) existing.setPipelineConfig((Map) request.get("pipelineConfig")); + if (request.containsKey("syncConfig")) existing.setSyncConfig((Map) request.get("syncConfig")); if (request.containsKey("runtime")) { Map runtime = (Map) request.get("runtime"); Resolver.ResolverRuntime rt = new Resolver.ResolverRuntime(); @@ -318,11 +395,6 @@ public class AppSyncService { resolverStore.delete(resolverKey(apiId, typeName, fieldName)); } - private void deleteResolversForApi(String apiId) { - resolverStore.scan(k -> k.startsWith(apiId + "::")) - .forEach(r -> resolverStore.delete(resolverKey(apiId, r.getTypeName(), r.getFieldName()))); - } - // ──────────────────────────── Functions ──────────────────────────── public FunctionConfiguration createFunction(String apiId, Map request, String region) { @@ -331,15 +403,19 @@ public class AppSyncService { if (name == null || name.isBlank()) { throw new AwsException("BadRequestException", "A function name is required", 400); } + String dsName = (String) request.get("dataSourceName"); + if (dsName != null && !dsName.isBlank()) { + getDataSource(apiId, dsName); + } FunctionConfiguration fn = new FunctionConfiguration(); fn.setFunctionId(generateShortId()); fn.setName((String) request.get("name")); fn.setDescription((String) request.get("description")); - fn.setDataSourceName((String) request.get("dataSourceName")); + fn.setDataSourceName(dsName); fn.setRequestMappingTemplate((String) request.get("requestMappingTemplate")); fn.setResponseMappingTemplate((String) request.get("responseMappingTemplate")); fn.setFunctionVersion((String) request.getOrDefault("functionVersion", "2018-05-29")); - fn.setArn(buildFunctionArn(apiId, fn.getFunctionId(), region)); + fn.setFunctionArn(buildFunctionArn(apiId, fn.getFunctionId(), region)); fn.setCode((String) request.get("code")); functionStore.put(apiKey(apiId, fn.getFunctionId()), fn); @@ -355,6 +431,7 @@ public class AppSyncService { return paginate(functionStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults); } + @SuppressWarnings("unchecked") public FunctionConfiguration updateFunction(String apiId, String functionId, Map request) { FunctionConfiguration existing = getFunction(apiId, functionId); if (request.containsKey("description")) existing.setDescription((String) request.get("description")); @@ -372,11 +449,6 @@ public class AppSyncService { functionStore.delete(apiKey(apiId, functionId)); } - private void deleteFunctionsForApi(String apiId) { - functionStore.scan(k -> k.startsWith(apiId + "::")) - .forEach(fn -> functionStore.delete(apiKey(apiId, fn.getFunctionId()))); - } - // ──────────────────────────── Types ──────────────────────────── public AppSyncType createType(String apiId, Map request) { @@ -389,6 +461,10 @@ public class AppSyncService { if (name == null || name.isBlank()) { throw new AwsException("BadRequestException", "A type name is required", 400); } + String typeKey = apiKey(apiId, name); + if (typeStore.get(typeKey).isPresent()) { + throw new AwsException("ConflictException", "Type already exists: " + name, 409); + } AppSyncType type = new AppSyncType(); type.setApiId(apiId); type.setName(name); @@ -396,7 +472,7 @@ public class AppSyncService { type.setDescription((String) request.get("description")); type.setFormat(parseEnum(TypeFormat.class, request.getOrDefault("format", "SDL"))); - typeStore.put(apiKey(apiId, type.getName()), type); + typeStore.put(typeKey, type); return type; } @@ -423,15 +499,15 @@ public class AppSyncService { typeStore.delete(apiKey(apiId, typeName)); } - private void deleteTypesForApi(String apiId) { - typeStore.scan(k -> k.startsWith(apiId + "::")) - .forEach(t -> typeStore.delete(apiKey(apiId, t.getName()))); - } - // ──────────────────────────── API Keys ──────────────────────────── public ApiKey createApiKey(String apiId, Map request) { getGraphqlApi(apiId); + long existingCount = apiKeyStore.scan(k -> k.startsWith(apiId + "::")).size(); + if (existingCount >= 2) { + throw new AwsException("LimitExceededException", + "Maximum of 2 API keys per API reached", 429); + } ApiKey key = new ApiKey(); key.setId(generateShortId()); key.setApiId(apiId); @@ -445,12 +521,15 @@ public class AppSyncService { try { key.setExpires(Long.parseLong(s)); } catch (NumberFormatException e) { - // try parsing as ISO date and convert to epoch seconds - key.setExpires(null); + try { + key.setExpires(java.time.Instant.parse(s).getEpochSecond()); + } catch (java.time.format.DateTimeParseException ex) { + throw new AwsException("BadRequestException", + "Invalid expires value: " + s + ". Expected epoch seconds or ISO 8601.", 400); + } } } - // Generate a simple API key string key.setApiKey("da2-" + generateShortId()); apiKeyStore.put(apiKey(apiId, key.getId()), key); @@ -479,7 +558,12 @@ public class AppSyncService { try { existing.setExpires(Long.parseLong(s)); } catch (NumberFormatException e) { - // keep existing + try { + existing.setExpires(java.time.Instant.parse(s).getEpochSecond()); + } catch (java.time.format.DateTimeParseException ex) { + throw new AwsException("BadRequestException", + "Invalid expires value: " + s + ". Expected epoch seconds or ISO 8601.", 400); + } } } } @@ -492,11 +576,6 @@ public class AppSyncService { apiKeyStore.delete(apiKey(apiId, keyId)); } - private void deleteApiKeysForApi(String apiId) { - apiKeyStore.scan(k -> k.startsWith(apiId + "::")) - .forEach(k -> apiKeyStore.delete(apiKey(apiId, k.getId()))); - } - // ──────────────────────────── Tags ──────────────────────────── public Map getTags(String resourceArn) { @@ -533,6 +612,265 @@ public class AppSyncService { return api.getEnvironmentVariables(); } + // ──────────────────────────── Domain Names ──────────────────────────── + + public DomainName createDomainName(Map request) { + String domainName = (String) request.get("domainName"); + if (domainName == null || domainName.isBlank()) { + throw new AwsException("BadRequestException", "A domain name is required", 400); + } + if (domainStore.get(domainName).isPresent()) { + throw new AwsException("ConflictException", "Domain name already exists: " + domainName, 409); + } + DomainName dn = new DomainName(); + dn.setDomainName(domainName); + dn.setDescription((String) request.get("description")); + dn.setCertificateArn((String) request.get("certificateArn")); + String shortId = generateShortId(); + dn.setAppsyncDomainName(shortId + ".appsync-api.us-east-1.amazonaws.com"); + dn.setHostedZoneId("Z" + generateShortId()); + dn.setDomainNameArn(regionResolver.buildArn("appsync", regionResolver.getDefaultRegion(), + "domainnames/" + domainName)); + + Object tagsObj = request.get("tags"); + if (tagsObj instanceof Map tagMap) { + Map tagStrings = new HashMap<>(); + tagMap.forEach((k, v) -> tagStrings.put(String.valueOf(k), String.valueOf(v))); + dn.setTags(tagStrings); + } + + domainStore.put(domainName, dn); + return dn; + } + + public DomainName getDomainName(String domainName) { + return domainStore.get(domainName) + .orElseThrow(() -> new AwsException("NotFoundException", "Domain name not found: " + domainName, 404)); + } + + public Page listDomainNames(Integer maxResults, String nextToken) { + return paginate(domainStore.scan(k -> true), nextToken, maxResults); + } + + public DomainName updateDomainName(String domainName, Map request) { + DomainName existing = getDomainName(domainName); + if (request.containsKey("description")) existing.setDescription((String) request.get("description")); + domainStore.put(domainName, existing); + return existing; + } + + public void deleteDomainName(String domainName) { + getDomainName(domainName); + associationStore.delete(domainName); + domainStore.delete(domainName); + } + + public ApiAssociation associateApi(String domainName, String apiId) { + getDomainName(domainName); + getGraphqlApi(apiId); + if (associationStore.get(domainName).isPresent()) { + throw new AwsException("ConflictException", + "Domain name already associated with an API", 409); + } + associationStore.put(domainName, apiId); + ApiAssociation assoc = new ApiAssociation(); + assoc.setApiId(apiId); + assoc.setDomainName(domainName); + assoc.setAssociationStatus("SUCCESS"); + assoc.setDeploymentDetail("Successfully associated"); + return assoc; + } + + public ApiAssociation getApiAssociation(String domainName) { + getDomainName(domainName); + String apiId = associationStore.get(domainName) + .orElseThrow(() -> new AwsException("NotFoundException", + "No API associated with domain: " + domainName, 404)); + ApiAssociation assoc = new ApiAssociation(); + assoc.setDomainName(domainName); + assoc.setApiId(apiId); + assoc.setAssociationStatus("SUCCESS"); + return assoc; + } + + public void disassociateApi(String domainName) { + getDomainName(domainName); + associationStore.delete(domainName); + } + + // ──────────────────────────── Channel Namespaces ──────────────────────────── + + public ChannelNamespace createChannelNamespace(String apiId, Map request) { + getGraphqlApi(apiId); + String name = (String) request.get("name"); + if (name == null || name.isBlank()) { + throw new AwsException("BadRequestException", "A channel namespace name is required", 400); + } + String nsKey = apiKey(apiId, name); + if (channelNamespaceStore.get(nsKey).isPresent()) { + throw new AwsException("ConflictException", + "Channel namespace already exists: " + name, 409); + } + ChannelNamespace ns = new ChannelNamespace(); + ns.setName(name); + ns.setApiId(apiId); + ns.setDescription((String) request.get("description")); + ns.setChannelNamespaceArn(regionResolver.buildArn("appsync", regionResolver.getDefaultRegion(), + "apis/" + apiId + "/channelNamespaces/" + name)); + ns.setCodeHandlers((String) request.get("codeHandlers")); + ns.setCreated(System.currentTimeMillis()); + ns.setLastModified(System.currentTimeMillis()); + channelNamespaceStore.put(nsKey, ns); + return ns; + } + + public ChannelNamespace getChannelNamespace(String apiId, String name) { + return channelNamespaceStore.get(apiKey(apiId, name)) + .orElseThrow(() -> new AwsException("NotFoundException", + "Channel namespace not found: " + name, 404)); + } + + public ChannelNamespace updateChannelNamespace(String apiId, String name, Map request) { + ChannelNamespace existing = getChannelNamespace(apiId, name); + if (request.containsKey("description")) existing.setDescription((String) request.get("description")); + if (request.containsKey("codeHandlers")) existing.setCodeHandlers((String) request.get("codeHandlers")); + existing.setLastModified(System.currentTimeMillis()); + channelNamespaceStore.put(apiKey(apiId, name), existing); + return existing; + } + + public void deleteChannelNamespace(String apiId, String name) { + getChannelNamespace(apiId, name); + channelNamespaceStore.delete(apiKey(apiId, name)); + } + + public Page listChannelNamespaces(String apiId, Integer maxResults, String nextToken) { + return paginate(channelNamespaceStore.scan(k -> k.startsWith(apiId + "::")), nextToken, maxResults); + } + + // ──────────────────────────── Merged API Associations ───────────────── + + public SourceApiAssociation createMergedApiAssociation(String sourceApiIdentifier, Map request, String region) { + getGraphqlApi(sourceApiIdentifier); + String mergedApiIdentifier = (String) request.getOrDefault("mergedApiIdentifier", request.get("mergedApiId")); + if (mergedApiIdentifier == null || mergedApiIdentifier.isBlank()) { + throw new AwsException("BadRequestException", "A merged API identifier is required", 400); + } + getGraphqlApi(mergedApiIdentifier); + SourceApiAssociation assoc = new SourceApiAssociation(); + assoc.setAssociationId(generateShortId()); + assoc.setAssociationArn(regionResolver.buildArn("appsync", region, + "sourceApis/" + sourceApiIdentifier + "/mergedApiAssociations/" + generateShortId())); + assoc.setMergedApiId(mergedApiIdentifier); + assoc.setMergedApiArn(regionResolver.buildArn("appsync", region, "apis/" + mergedApiIdentifier)); + assoc.setSourceApiId(sourceApiIdentifier); + assoc.setSourceApiArn(regionResolver.buildArn("appsync", region, "apis/" + sourceApiIdentifier)); + assoc.setDescription((String) request.get("description")); + assoc.setSourceApiAssociationStatus("MERGED"); + SourceApiAssociationConfig config = new SourceApiAssociationConfig(); + String mergeType = (String) request.getOrDefault("mergeType", "MERGE"); + config.setMergeType(mergeType); + assoc.setSourceApiAssociationConfig(config); + mergedApiAssociationStore.put(assoc.getAssociationId(), assoc); + return assoc; + } + + public SourceApiAssociation createSourceApiAssociation(String mergedApiIdentifier, Map request, String region) { + getGraphqlApi(mergedApiIdentifier); + String sourceApiId = (String) request.getOrDefault("sourceApiId", request.get("sourceApiIdentifier")); + if (sourceApiId == null || sourceApiId.isBlank()) { + throw new AwsException("BadRequestException", "A source API ID is required", 400); + } + getGraphqlApi(sourceApiId); + SourceApiAssociation assoc = new SourceApiAssociation(); + assoc.setAssociationId(generateShortId()); + assoc.setAssociationArn(regionResolver.buildArn("appsync", region, + "mergedApis/" + mergedApiIdentifier + "/sourceApiAssociations/" + generateShortId())); + assoc.setMergedApiId(mergedApiIdentifier); + assoc.setMergedApiArn(regionResolver.buildArn("appsync", region, "apis/" + mergedApiIdentifier)); + assoc.setSourceApiId(sourceApiId); + assoc.setSourceApiArn(regionResolver.buildArn("appsync", region, "apis/" + sourceApiId)); + assoc.setDescription((String) request.get("description")); + assoc.setSourceApiAssociationStatus("MERGED"); + SourceApiAssociationConfig config = new SourceApiAssociationConfig(); + String mergeType = (String) request.getOrDefault("mergeType", "MERGE"); + config.setMergeType(mergeType); + assoc.setSourceApiAssociationConfig(config); + mergedApiAssociationStore.put(assoc.getAssociationId(), assoc); + return assoc; + } + + public SourceApiAssociation getSourceApiAssociation(String mergedApiIdentifier, String associationId) { + SourceApiAssociation assoc = mergedApiAssociationStore.get(associationId) + .orElseThrow(() -> new AwsException("NotFoundException", + "Source API association not found: " + associationId, 404)); + if (!mergedApiIdentifier.equals(assoc.getMergedApiId())) { + throw new AwsException("NotFoundException", + "Source API association not found: " + associationId, 404); + } + return assoc; + } + + public SourceApiAssociation updateSourceApiAssociation(String mergedApiIdentifier, String associationId, + Map request) { + SourceApiAssociation assoc = getSourceApiAssociation(mergedApiIdentifier, associationId); + if (request.containsKey("description")) { + assoc.setDescription((String) request.get("description")); + } + Object configObj = request.get("sourceApiAssociationConfig"); + if (configObj instanceof Map configMap) { + SourceApiAssociationConfig config = assoc.getSourceApiAssociationConfig(); + if (config == null) { + config = new SourceApiAssociationConfig(); + } + Object mergeType = configMap.get("mergeType"); + if (mergeType != null) { + config.setMergeType((String) mergeType); + } + assoc.setSourceApiAssociationConfig(config); + } + mergedApiAssociationStore.put(associationId, assoc); + return assoc; + } + + public Page listSourceApiAssociations(String apiId, Integer maxResults, String nextToken) { + List summaries = mergedApiAssociationStore.scan(k -> true).stream() + .filter(a -> apiId.equals(a.getMergedApiId()) || apiId.equals(a.getSourceApiId())) + .map(this::toSummary) + .toList(); + return paginate(summaries, nextToken, maxResults); + } + + public void deleteSourceApiAssociation(String mergedApiIdentifier, String associationId) { + getSourceApiAssociation(mergedApiIdentifier, associationId); + mergedApiAssociationStore.delete(associationId); + } + + public SourceApiAssociation deleteMergedApiAssociation(String sourceApiIdentifier, String associationId) { + SourceApiAssociation assoc = mergedApiAssociationStore.get(associationId) + .orElseThrow(() -> new AwsException("NotFoundException", + "Source API association not found: " + associationId, 404)); + if (!sourceApiIdentifier.equals(assoc.getSourceApiId())) { + throw new AwsException("NotFoundException", + "Source API association not found: " + associationId, 404); + } + mergedApiAssociationStore.delete(associationId); + assoc.setSourceApiAssociationStatus("DELETION_SCHEDULED"); + return assoc; + } + + private SourceApiAssociationSummary toSummary(SourceApiAssociation assoc) { + SourceApiAssociationSummary summary = new SourceApiAssociationSummary(); + summary.setAssociationArn(assoc.getAssociationArn()); + summary.setAssociationId(assoc.getAssociationId()); + summary.setDescription(assoc.getDescription()); + summary.setMergedApiArn(assoc.getMergedApiArn()); + summary.setMergedApiId(assoc.getMergedApiId()); + summary.setSourceApiArn(assoc.getSourceApiArn()); + summary.setSourceApiId(assoc.getSourceApiId()); + return summary; + } + // ──────────────────────────── Helpers ──────────────────────────── private String generateApiId() { @@ -572,6 +910,55 @@ public class AppSyncService { return String.valueOf(value); } + private String coerceString(Object value, String defaultValue) { + String result = coerceString(value); + return result != null ? result : defaultValue; + } + + private Integer castInt(Object value) { + if (value == null) return null; + if (value instanceof Integer i) return i; + if (value instanceof Number n) { + long longVal = n.longValue(); + if (longVal < Integer.MIN_VALUE || longVal > Integer.MAX_VALUE) { + throw new AwsException("BadRequestException", + "Integer value out of range: " + longVal, 400); + } + return n.intValue(); + } + try { + long longVal = Long.parseLong(value.toString()); + if (longVal < Integer.MIN_VALUE || longVal > Integer.MAX_VALUE) { + throw new AwsException("BadRequestException", + "Integer value out of range: " + longVal, 400); + } + return (int) longVal; + } catch (NumberFormatException e) { + throw new AwsException("BadRequestException", + "Invalid integer value: " + value, 400); + } + } + + @SuppressWarnings("unchecked") + private Map castMap(Object value) { + if (value instanceof Map) { + return (Map) value; + } + return null; + } + + @SuppressWarnings("unchecked") + private Map castStringMap(Object value) { + if (value instanceof Map) { + Map result = new HashMap<>(); + for (var entry : ((Map) value).entrySet()) { + result.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); + } + return result; + } + return null; + } + private > E parseEnum(Class enumClass, Object value) { if (value == null) return null; String str = value instanceof String s ? s : String.valueOf(value); @@ -583,6 +970,45 @@ public class AppSyncService { } } + private void deleteDataSourcesForApi(String apiId) { + dataSourceStore.scan(k -> k.startsWith(apiId + "::")) + .forEach(ds -> dataSourceStore.delete(apiKey(apiId, ds.getName()))); + } + + private void deleteResolversForApi(String apiId) { + resolverStore.scan(k -> k.startsWith(apiId + "::")) + .forEach(r -> resolverStore.delete(resolverKey(apiId, r.getTypeName(), r.getFieldName()))); + } + + private void deleteFunctionsForApi(String apiId) { + functionStore.scan(k -> k.startsWith(apiId + "::")) + .forEach(fn -> functionStore.delete(apiKey(apiId, fn.getFunctionId()))); + } + + private void deleteTypesForApi(String apiId) { + typeStore.scan(k -> k.startsWith(apiId + "::")) + .forEach(t -> typeStore.delete(apiKey(apiId, t.getName()))); + } + + private void deleteApiKeysForApi(String apiId) { + apiKeyStore.scan(k -> k.startsWith(apiId + "::")) + .forEach(k -> apiKeyStore.delete(apiKey(apiId, k.getId()))); + } + + private void deleteChannelNamespacesForApi(String apiId) { + channelNamespaceStore.scan(k -> k.startsWith(apiId + "::")) + .forEach(ns -> channelNamespaceStore.delete(apiKey(apiId, ns.getName()))); + } + + private void deleteDomainAssociationsForApi(String apiId) { + for (String key : associationStore.keys()) { + String assocApiId = associationStore.get(key).orElse(null); + if (apiId.equals(assocApiId)) { + associationStore.delete(key); + } + } + } + // ──────────────────────────── Pagination ──────────────────────────── record Page(List items, String nextToken) {} @@ -590,7 +1016,14 @@ public class AppSyncService { static Page paginate(List items, String nextToken, Integer maxResults) { int start = decodeToken(nextToken); if (start < 0 || start > items.size()) { - throw new AwsException("InvalidNextTokenException", "Invalid NextToken.", 400); + throw new AwsException("BadRequestException", "Invalid NextToken.", 400); + } + if (maxResults != null && maxResults < 0) { + throw new AwsException("BadRequestException", "maxResults must be non-negative", 400); + } + if (maxResults != null && maxResults == 0) { + String next = (start < items.size()) ? encodeToken(start) : null; + return new Page<>(List.of(), next); } int limit = (maxResults == null || maxResults <= 0) ? items.size() @@ -620,11 +1053,19 @@ public class AppSyncService { static String extractTypeNameFromDefinition(String definition) { if (definition == null || definition.isBlank()) return null; - String trimmed = definition.strip(); - // Match: type TypeName { ... } or input TypeName { ... } or enum TypeName { ... } + // Remove comments + String cleaned = definition.replaceAll("#[^\n]*", ""); + String trimmed = cleaned.strip(); String[] parts = trimmed.split("\\s+"); if (parts.length >= 2) { - return parts[1].replaceAll("[{(].*", ""); + String name = parts[1].replaceAll("[{(].*", ""); + if (!name.isEmpty() && !name.startsWith("#")) return name; + } + // Try next word if first was a comment artifact + for (String part : parts) { + if (!part.isEmpty() && !part.startsWith("#") && !part.equals("type") && !part.equals("input") && !part.equals("enum")) { + return part.replaceAll("[{(].*", ""); + } } return null; } diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncDirective.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncDirective.java new file mode 100644 index 0000000000..23ba337c36 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncDirective.java @@ -0,0 +1,49 @@ +package io.github.hectorvent.floci.services.appsync.graphql; + +import java.util.Set; +import java.util.stream.Collectors; + +public enum AppSyncDirective { + AWS_API_KEY("aws_api_key", "directive @aws_api_key on OBJECT | FIELD_DEFINITION"), + AWS_IAM("aws_iam", "directive @aws_iam on OBJECT | FIELD_DEFINITION"), + AWS_COGNITO_USER_POOLS("aws_cognito_user_pools", + "directive @aws_cognito_user_pools(cognito_groups: [String!]!) on OBJECT | FIELD_DEFINITION"), + AWS_OIDC("aws_oidc", "directive @aws_oidc on OBJECT | FIELD_DEFINITION"), + AWS_LAMBDA("aws_lambda", "directive @aws_lambda on OBJECT | FIELD_DEFINITION"), + AWS_SUBSCRIBE("aws_subscribe", "directive @aws_subscribe(mutations: [String!]!) on FIELD_DEFINITION"), + AWS_AUTH("aws_auth", "directive @aws_auth(cognito_groups: [String!]!) on OBJECT"), + AWS_DELTA_SYNC("aws_delta_sync", + "directive @aws_delta_sync(tableName: String!, deltaSyncTableTTL: Int!, baseTableTTL: Int!) on OBJECT"); + + private static final Set KNOWN_NAMES; + static { + java.util.Set names = new java.util.HashSet<>(); + names.add("skip"); + names.add("include"); + names.add("deprecated"); + for (AppSyncDirective d : values()) { + names.add(d.directiveName()); + } + KNOWN_NAMES = java.util.Set.copyOf(names); + } + + private final String name; + private final String sdl; + + AppSyncDirective(String name, String sdl) { + this.name = name; + this.sdl = sdl; + } + + public String directiveName() { + return name; + } + + public String sdl() { + return sdl; + } + + public static boolean isKnown(String directiveName) { + return KNOWN_NAMES.contains(directiveName); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncSchemaParser.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncSchemaParser.java new file mode 100644 index 0000000000..6865c8e076 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncSchemaParser.java @@ -0,0 +1,81 @@ +package io.github.hectorvent.floci.services.appsync.graphql; + +import graphql.schema.GraphQLSchema; +import graphql.schema.idl.RuntimeWiring; +import graphql.schema.idl.SchemaGenerator; +import graphql.schema.idl.SchemaParser; +import graphql.schema.idl.TypeDefinitionRegistry; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.appsync.graphql.scalars.AppSyncScalarRegistry; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +@ApplicationScoped +public class AppSyncSchemaParser { + private final AppSyncScalarRegistry scalarRegistry; + + @Inject + public AppSyncSchemaParser(AppSyncScalarRegistry scalarRegistry) { + this.scalarRegistry = scalarRegistry; + } + + public GraphQLSchema parse(String sdl) { + String sdlWithDirectives = injectDirectiveDefinitions(sdl); + validateNoUnknownDirectives(sdl); + + SchemaParser parser = new SchemaParser(); + TypeDefinitionRegistry typeRegistry; + try { + typeRegistry = parser.parse(sdlWithDirectives); + } catch (Exception e) { + throw new AwsException("BadRequestException", "Invalid schema: " + e.getMessage(), 400); + } + + RuntimeWiring.Builder wiringBuilder = RuntimeWiring.newRuntimeWiring(); + for (var entry : scalarRegistry.scalarMap().entrySet()) { + wiringBuilder = wiringBuilder.scalar(entry.getValue()); + } + + try { + return new SchemaGenerator().makeExecutableSchema(typeRegistry, wiringBuilder.build()); + } catch (RuntimeException e) { + throw new AwsException("BadRequestException", "Invalid schema: " + e.getMessage(), 400); + } + } + + private void validateNoUnknownDirectives(String sdl) { + String clean = sdl + .replaceAll("\"\"\"[\\s\\S]*?\"\"\"", "") + .replaceAll("\"(?:[^\"\\\\]|\\\\.)*\"", "") + .replaceAll("#[^\n]*", ""); + Pattern directivePattern = Pattern.compile("@(\\w+)"); + Matcher matcher = directivePattern.matcher(clean); + while (matcher.find()) { + String name = matcher.group(1); + if (!AppSyncDirective.isKnown(name)) { + throw new AwsException("BadRequestException", + "Unknown directive: @" + name, 400); + } + } + } + + private String injectDirectiveDefinitions(String sdl) { + StringBuilder sb = new StringBuilder(); + for (AppSyncDirective directive : AppSyncDirective.values()) { + sb.append(directive.sdl()).append("\n"); + } + sb.append("\n"); + for (String scalarName : scalarRegistry.allScalars().stream() + .map(s -> s.getName()).collect(Collectors.toList())) { + sb.append("scalar ").append(scalarName).append("\n"); + } + sb.append("\n"); + sb.append(sdl); + return sb.toString(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistry.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistry.java new file mode 100644 index 0000000000..4574e1b2a2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/SchemaRegistry.java @@ -0,0 +1,33 @@ +package io.github.hectorvent.floci.services.appsync.graphql; + +import graphql.schema.GraphQLSchema; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +@ApplicationScoped +public class SchemaRegistry { + private final Map schemas = new ConcurrentHashMap<>(); + private final AppSyncSchemaParser appSyncSchemaParser; + + @Inject + public SchemaRegistry(AppSyncSchemaParser appSyncSchemaParser) { + this.appSyncSchemaParser = appSyncSchemaParser; + } + + public void register(String apiId, String sdl) { + GraphQLSchema schema = appSyncSchemaParser.parse(sdl); + schemas.put(apiId, schema); + } + + public Optional getSchema(String apiId) { + return Optional.ofNullable(schemas.get(apiId)); + } + + public void remove(String apiId) { + schemas.remove(apiId); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/scalars/AppSyncScalarRegistry.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/scalars/AppSyncScalarRegistry.java new file mode 100644 index 0000000000..7bb0f770e2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/scalars/AppSyncScalarRegistry.java @@ -0,0 +1,53 @@ +package io.github.hectorvent.floci.services.appsync.graphql.scalars; + +import graphql.schema.GraphQLScalarType; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +@ApplicationScoped +public class AppSyncScalarRegistry { + private final List scalars; + private final Map scalarMap; + + @Inject + public AppSyncScalarRegistry() { + this.scalars = List.of( + AppSyncScalars.AWSJSON, + AppSyncScalars.AWS_DATE_TIME, + AppSyncScalars.AWS_DATE, + AppSyncScalars.AWS_TIME, + AppSyncScalars.AWS_TIMESTAMP, + AppSyncScalars.AWS_EMAIL, + AppSyncScalars.AWS_URL, + AppSyncScalars.AWS_PHONE, + AppSyncScalars.AWS_IP_ADDRESS, + AppSyncScalars.AWS_BOOLEAN, + AppSyncScalars.AWS_LONG, + AppSyncScalars.AWS_INTEGER, + AppSyncScalars.AWS_SHORT, + AppSyncScalars.AWS_FLOAT, + AppSyncScalars.AWS_BIG_DECIMAL, + AppSyncScalars.AWS_BIG_INT, + AppSyncScalars.AWS_BYTE + ); + this.scalarMap = scalars.stream() + .collect(Collectors.toUnmodifiableMap(GraphQLScalarType::getName, s -> s)); + } + + public List allScalars() { + return scalars; + } + + public Optional getScalar(String name) { + return Optional.ofNullable(scalarMap.get(name)); + } + + public Map scalarMap() { + return scalarMap; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/scalars/AppSyncScalars.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/scalars/AppSyncScalars.java new file mode 100644 index 0000000000..c4276df4d8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/scalars/AppSyncScalars.java @@ -0,0 +1,470 @@ +package io.github.hectorvent.floci.services.appsync.graphql.scalars; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import graphql.language.StringValue; +import graphql.schema.Coercing; +import graphql.schema.CoercingParseLiteralException; +import graphql.schema.CoercingParseValueException; +import graphql.schema.CoercingSerializeException; +import graphql.schema.GraphQLScalarType; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.URI; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Base64; +import java.util.regex.Pattern; + +public final class AppSyncScalars { + + private static final ObjectMapper SHARED_MAPPER = new ObjectMapper(); + + public static final GraphQLScalarType AWSJSON = GraphQLScalarType.newScalar() + .name("AWSJSON") + .description("A JSON string") + .coercing(new Coercing() { + @Override + public String serialize(Object dataFetcherResult) { + if (dataFetcherResult == null) return null; + if (dataFetcherResult instanceof String s) return s; + try { + return SHARED_MAPPER.writeValueAsString(dataFetcherResult); + } catch (JsonProcessingException e) { + throw new CoercingSerializeException("Cannot serialize to JSON: " + e.getMessage()); + } + } + @Override + public String parseValue(Object input) { + String str = input.toString(); + try { + SHARED_MAPPER.readTree(str); + } catch (Exception e) { + throw new CoercingParseValueException("Invalid JSON: " + str); + } + return str; + } + @Override + public String parseLiteral(Object input) { + if (!(input instanceof StringValue sv)) return null; + return parseValue(sv.getValue()); + } + }) + .build(); + + public static final GraphQLScalarType AWS_DATE_TIME = GraphQLScalarType.newScalar() + .name("AWSDateTime") + .description("An ISO-8601 datetime string") + .coercing(new Coercing() { + @Override + public String serialize(Object dataFetcherResult) { + return dataFetcherResult != null ? dataFetcherResult.toString() : null; + } + @Override + public String parseValue(Object input) { + String str = input.toString(); + try { + Instant.parse(str); + } catch (DateTimeParseException e) { + throw new CoercingParseValueException("Invalid AWSDateTime: " + str); + } + return str; + } + @Override + public String parseLiteral(Object input) { + if (!(input instanceof StringValue sv)) return null; + return parseValue(sv.getValue()); + } + }) + .build(); + + public static final GraphQLScalarType AWS_DATE = GraphQLScalarType.newScalar() + .name("AWSDate") + .description("An ISO-8601 date string (yyyy-MM-dd)") + .coercing(new Coercing() { + @Override + public String serialize(Object dataFetcherResult) { + return dataFetcherResult != null ? dataFetcherResult.toString() : null; + } + @Override + public String parseValue(Object input) { + String str = input.toString(); + try { + LocalDate.parse(str, DateTimeFormatter.ISO_LOCAL_DATE); + } catch (DateTimeParseException e) { + throw new CoercingParseValueException("Invalid AWSDate: " + str); + } + return str; + } + @Override + public String parseLiteral(Object input) { + if (!(input instanceof StringValue sv)) return null; + return parseValue(sv.getValue()); + } + }) + .build(); + + public static final GraphQLScalarType AWS_TIME = GraphQLScalarType.newScalar() + .name("AWSTime") + .description("An ISO-8601 time string (HH:mm:ss)") + .coercing(new Coercing() { + @Override + public String serialize(Object dataFetcherResult) { + return dataFetcherResult != null ? dataFetcherResult.toString() : null; + } + @Override + public String parseValue(Object input) { + String str = input.toString(); + try { + LocalTime.parse(str, DateTimeFormatter.ISO_LOCAL_TIME); + } catch (DateTimeParseException e) { + throw new CoercingParseValueException("Invalid AWSTime: " + str); + } + return str; + } + @Override + public String parseLiteral(Object input) { + if (!(input instanceof StringValue sv)) return null; + return parseValue(sv.getValue()); + } + }) + .build(); + + public static final GraphQLScalarType AWS_TIMESTAMP = GraphQLScalarType.newScalar() + .name("AWSTimestamp") + .description("Unix epoch seconds (0 to 32503680000)") + .coercing(new Coercing() { + @Override + public Long serialize(Object dataFetcherResult) { + if (dataFetcherResult == null) return null; + if (dataFetcherResult instanceof Number n) return n.longValue(); + return Long.parseLong(dataFetcherResult.toString()); + } + @Override + public Long parseValue(Object input) { + long val; + if (input instanceof Number n) val = n.longValue(); + else val = Long.parseLong(input.toString()); + if (val < 0 || val > 32503680000L) + throw new CoercingParseValueException("AWSTimestamp out of range: " + val); + return val; + } + @Override + public Long parseLiteral(Object input) { + if (input instanceof graphql.language.IntValue iv) return parseValue(iv.getValue().longValue()); + throw new CoercingParseLiteralException("AWSTimestamp must be an integer"); + } + }) + .build(); + + private static final Pattern EMAIL_PATTERN = Pattern.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"); + + public static final GraphQLScalarType AWS_EMAIL = GraphQLScalarType.newScalar() + .name("AWSEmail") + .description("An RFC 5322 email address") + .coercing(new Coercing() { + @Override + public String serialize(Object dataFetcherResult) { + return dataFetcherResult != null ? dataFetcherResult.toString() : null; + } + @Override + public String parseValue(Object input) { + String str = input.toString(); + if (!EMAIL_PATTERN.matcher(str).matches()) + throw new CoercingParseValueException("Invalid AWSEmail: " + str); + return str; + } + @Override + public String parseLiteral(Object input) { + if (!(input instanceof StringValue sv)) return null; + return parseValue(sv.getValue()); + } + }) + .build(); + + public static final GraphQLScalarType AWS_URL = GraphQLScalarType.newScalar() + .name("AWSURL") + .description("A valid URL") + .coercing(new Coercing() { + @Override + public String serialize(Object dataFetcherResult) { + return dataFetcherResult != null ? dataFetcherResult.toString() : null; + } + @Override + public String parseValue(Object input) { + String str = input.toString(); + try { + URI.create(str).toURL(); + } catch (Exception e) { + throw new CoercingParseValueException("Invalid AWSURL: " + str); + } + return str; + } + @Override + public String parseLiteral(Object input) { + if (!(input instanceof StringValue sv)) return null; + return parseValue(sv.getValue()); + } + }) + .build(); + + private static final Pattern PHONE_PATTERN = Pattern.compile("^\\+[1-9]\\d{1,14}$"); + + public static final GraphQLScalarType AWS_PHONE = GraphQLScalarType.newScalar() + .name("AWSPhone") + .description("An E.164 phone number") + .coercing(new Coercing() { + @Override + public String serialize(Object dataFetcherResult) { + return dataFetcherResult != null ? dataFetcherResult.toString() : null; + } + @Override + public String parseValue(Object input) { + String str = input.toString(); + if (!PHONE_PATTERN.matcher(str).matches()) + throw new CoercingParseValueException("Invalid AWSPhone: " + str); + return str; + } + @Override + public String parseLiteral(Object input) { + if (!(input instanceof StringValue sv)) return null; + return parseValue(sv.getValue()); + } + }) + .build(); + + private static final Pattern IPV4_PATTERN = Pattern.compile( + "^(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$"); + private static final Pattern IPV6_PATTERN = Pattern.compile( + "^[0-9a-fA-F:]+$"); + + public static final GraphQLScalarType AWS_IP_ADDRESS = GraphQLScalarType.newScalar() + .name("AWSIPAddress") + .description("An IPv4 or IPv6 address") + .coercing(new Coercing() { + @Override + public String serialize(Object dataFetcherResult) { + return dataFetcherResult != null ? dataFetcherResult.toString() : null; + } + @Override + public String parseValue(Object input) { + String str = input.toString(); + if (!IPV4_PATTERN.matcher(str).matches() && !IPV6_PATTERN.matcher(str).matches()) { + throw new CoercingParseValueException("Invalid AWSIPAddress: " + str); + } + return str; + } + @Override + public String parseLiteral(Object input) { + if (!(input instanceof StringValue sv)) return null; + return parseValue(sv.getValue()); + } + }) + .build(); + + public static final GraphQLScalarType AWS_BOOLEAN = GraphQLScalarType.newScalar() + .name("AWSBoolean") + .description("A boolean value") + .coercing(new Coercing() { + @Override + public Boolean serialize(Object dataFetcherResult) { + if (dataFetcherResult == null) return null; + if (dataFetcherResult instanceof Boolean b) return b; + throw new CoercingSerializeException("AWSBoolean cannot serialize non-boolean value: " + dataFetcherResult.getClass().getSimpleName()); + } + @Override + public Boolean parseValue(Object input) { + if (input instanceof Boolean b) return b; + throw new CoercingParseValueException("AWSBoolean cannot parse non-boolean value: " + input); + } + @Override + public Boolean parseLiteral(Object input) { + if (input instanceof graphql.language.BooleanValue bv) return bv.isValue(); + throw new CoercingParseLiteralException("AWSBoolean must be a boolean literal"); + } + }) + .build(); + + public static final GraphQLScalarType AWS_LONG = GraphQLScalarType.newScalar() + .name("AWSLong") + .description("A 64-bit signed integer") + .coercing(new Coercing() { + @Override + public Long serialize(Object dataFetcherResult) { + if (dataFetcherResult == null) return null; + if (dataFetcherResult instanceof Number n) return n.longValue(); + return Long.parseLong(dataFetcherResult.toString()); + } + @Override + public Long parseValue(Object input) { + if (input instanceof Number n) return n.longValue(); + return Long.parseLong(input.toString()); + } + @Override + public Long parseLiteral(Object input) { + if (input instanceof graphql.language.IntValue iv) return iv.getValue().longValue(); + throw new CoercingParseLiteralException("AWSLong must be an integer"); + } + }) + .build(); + + public static final GraphQLScalarType AWS_INTEGER = GraphQLScalarType.newScalar() + .name("AWSInteger") + .description("A 32-bit signed integer") + .coercing(new Coercing() { + @Override + public Integer serialize(Object dataFetcherResult) { + if (dataFetcherResult == null) return null; + if (dataFetcherResult instanceof Number n) return n.intValue(); + return Integer.parseInt(dataFetcherResult.toString()); + } + @Override + public Integer parseValue(Object input) { + if (input instanceof Number n) return n.intValue(); + return Integer.parseInt(input.toString()); + } + @Override + public Integer parseLiteral(Object input) { + if (input instanceof graphql.language.IntValue iv) return iv.getValue().intValue(); + throw new CoercingParseLiteralException("AWSInteger must be an integer"); + } + }) + .build(); + + public static final GraphQLScalarType AWS_SHORT = GraphQLScalarType.newScalar() + .name("AWSShort") + .description("A 16-bit signed integer (-32768 to 32767)") + .coercing(new Coercing() { + @Override + public Integer serialize(Object dataFetcherResult) { + if (dataFetcherResult instanceof Number n) return n.intValue(); + return Integer.parseInt(dataFetcherResult.toString()); + } + @Override + public Integer parseValue(Object input) { + int val; + if (input instanceof Number n) val = n.intValue(); + else val = Integer.parseInt(input.toString()); + if (val < -32768 || val > 32767) + throw new CoercingParseValueException("AWSShort out of range: " + val); + return val; + } + @Override + public Integer parseLiteral(Object input) { + if (input instanceof graphql.language.IntValue iv) return parseValue(iv.getValue().intValue()); + throw new CoercingParseLiteralException("AWSShort must be an integer"); + } + }) + .build(); + + public static final GraphQLScalarType AWS_FLOAT = GraphQLScalarType.newScalar() + .name("AWSFloat") + .description("An IEEE 754 double-precision float") + .coercing(new Coercing() { + @Override + public Double serialize(Object dataFetcherResult) { + if (dataFetcherResult == null) return null; + if (dataFetcherResult instanceof Number n) return n.doubleValue(); + return Double.parseDouble(dataFetcherResult.toString()); + } + @Override + public Double parseValue(Object input) { + if (input instanceof Number n) return n.doubleValue(); + return Double.parseDouble(input.toString()); + } + @Override + public Double parseLiteral(Object input) { + if (input instanceof graphql.language.FloatValue fv) return fv.getValue().doubleValue(); + if (input instanceof graphql.language.IntValue iv) return iv.getValue().doubleValue(); + throw new CoercingParseLiteralException("AWSFloat must be a number"); + } + }) + .build(); + + public static final GraphQLScalarType AWS_BIG_DECIMAL = GraphQLScalarType.newScalar() + .name("AWSBigDecimal") + .description("An arbitrary-precision decimal number") + .coercing(new Coercing() { + @Override + public String serialize(Object dataFetcherResult) { + return dataFetcherResult != null ? dataFetcherResult.toString() : null; + } + @Override + public String parseValue(Object input) { + String str = input.toString(); + try { + new BigDecimal(str); + } catch (NumberFormatException e) { + throw new CoercingParseValueException("Invalid AWSBigDecimal: " + str); + } + return str; + } + @Override + public String parseLiteral(Object input) { + if (input instanceof StringValue sv) return parseValue(sv.getValue()); + if (input instanceof graphql.language.FloatValue fv) return fv.getValue().toString(); + if (input instanceof graphql.language.IntValue iv) return iv.getValue().toString(); + return null; + } + }) + .build(); + + public static final GraphQLScalarType AWS_BIG_INT = GraphQLScalarType.newScalar() + .name("AWSBigInt") + .description("An arbitrary-precision integer") + .coercing(new Coercing() { + @Override + public String serialize(Object dataFetcherResult) { + return dataFetcherResult != null ? dataFetcherResult.toString() : null; + } + @Override + public String parseValue(Object input) { + String str = input.toString(); + try { + new BigInteger(str); + } catch (NumberFormatException e) { + throw new CoercingParseValueException("Invalid AWSBigInt: " + str); + } + return str; + } + @Override + public String parseLiteral(Object input) { + if (input instanceof graphql.language.IntValue iv) return iv.getValue().toString(); + if (input instanceof StringValue sv) return parseValue(sv.getValue()); + return null; + } + }) + .build(); + + public static final GraphQLScalarType AWS_BYTE = GraphQLScalarType.newScalar() + .name("AWSByte") + .description("A base64-encoded byte array") + .coercing(new Coercing() { + @Override + public String serialize(Object dataFetcherResult) { + return dataFetcherResult != null ? dataFetcherResult.toString() : null; + } + @Override + public String parseValue(Object input) { + String str = input.toString(); + try { + Base64.getDecoder().decode(str); + } catch (IllegalArgumentException e) { + throw new CoercingParseValueException("Invalid AWSByte: not valid base64"); + } + return str; + } + @Override + public String parseLiteral(Object input) { + if (!(input instanceof StringValue sv)) return null; + return parseValue(sv.getValue()); + } + }) + .build(); + + private AppSyncScalars() {} +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/AdditionalAuthenticationProvider.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/AdditionalAuthenticationProvider.java new file mode 100644 index 0000000000..061757f54a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/AdditionalAuthenticationProvider.java @@ -0,0 +1,29 @@ +package io.github.hectorvent.floci.services.appsync.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.Map; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AdditionalAuthenticationProvider { + private AuthenticationType authenticationType; + private Map lambdaAuthorizerConfig; + private Map openIDConnectConfig; + private Map userPoolConfig; + + public AuthenticationType getAuthenticationType() { return authenticationType; } + public void setAuthenticationType(AuthenticationType authenticationType) { this.authenticationType = authenticationType; } + + public Map getLambdaAuthorizerConfig() { return lambdaAuthorizerConfig; } + public void setLambdaAuthorizerConfig(Map lambdaAuthorizerConfig) { this.lambdaAuthorizerConfig = lambdaAuthorizerConfig; } + + public Map getOpenIDConnectConfig() { return openIDConnectConfig; } + public void setOpenIDConnectConfig(Map openIDConnectConfig) { this.openIDConnectConfig = openIDConnectConfig; } + + public Map getUserPoolConfig() { return userPoolConfig; } + public void setUserPoolConfig(Map userPoolConfig) { this.userPoolConfig = userPoolConfig; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/ApiAssociation.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/ApiAssociation.java new file mode 100644 index 0000000000..e1fe0667fc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/ApiAssociation.java @@ -0,0 +1,27 @@ +package io.github.hectorvent.floci.services.appsync.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ApiAssociation { + private String apiId; + private String associationStatus; + private String deploymentDetail; + private String domainName; + + public String getApiId() { return apiId; } + public void setApiId(String apiId) { this.apiId = apiId; } + + public String getAssociationStatus() { return associationStatus; } + public void setAssociationStatus(String associationStatus) { this.associationStatus = associationStatus; } + + public String getDeploymentDetail() { return deploymentDetail; } + public void setDeploymentDetail(String deploymentDetail) { this.deploymentDetail = deploymentDetail; } + + public String getDomainName() { return domainName; } + public void setDomainName(String domainName) { this.domainName = domainName; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/AuthMode.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/AuthMode.java new file mode 100644 index 0000000000..74914ad167 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/AuthMode.java @@ -0,0 +1,15 @@ +package io.github.hectorvent.floci.services.appsync.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AuthMode { + private String authType; + + public String getAuthType() { return authType; } + public void setAuthType(String authType) { this.authType = authType; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/ChannelNamespace.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/ChannelNamespace.java new file mode 100644 index 0000000000..39fc495aba --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/ChannelNamespace.java @@ -0,0 +1,57 @@ +package io.github.hectorvent.floci.services.appsync.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.List; +import java.util.Map; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ChannelNamespace { + private String name; + private String apiId; + private String description; + private String channelNamespaceArn; + private String codeHandlers; + private Long created; + private HandlerConfigs handlerConfigs; + private Long lastModified; + private List publishAuthModes; + private List subscribeAuthModes; + private Map tags; + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public String getApiId() { return apiId; } + public void setApiId(String apiId) { this.apiId = apiId; } + + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + + public String getChannelNamespaceArn() { return channelNamespaceArn; } + public void setChannelNamespaceArn(String channelNamespaceArn) { this.channelNamespaceArn = channelNamespaceArn; } + + public String getCodeHandlers() { return codeHandlers; } + public void setCodeHandlers(String codeHandlers) { this.codeHandlers = codeHandlers; } + + public Long getCreated() { return created; } + public void setCreated(Long created) { this.created = created; } + + public HandlerConfigs getHandlerConfigs() { return handlerConfigs; } + public void setHandlerConfigs(HandlerConfigs handlerConfigs) { this.handlerConfigs = handlerConfigs; } + + public Long getLastModified() { return lastModified; } + public void setLastModified(Long lastModified) { this.lastModified = lastModified; } + + public List getPublishAuthModes() { return publishAuthModes; } + public void setPublishAuthModes(List publishAuthModes) { this.publishAuthModes = publishAuthModes; } + + public List getSubscribeAuthModes() { return subscribeAuthModes; } + public void setSubscribeAuthModes(List subscribeAuthModes) { this.subscribeAuthModes = subscribeAuthModes; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/DataSource.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/DataSource.java index 25bf9f6247..b4faa1013b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/model/DataSource.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/DataSource.java @@ -21,6 +21,7 @@ public class DataSource { private Map relationalDatabaseConfig; private Map openSearchServiceConfig; private Map amazonBedrockRuntimeConfig; + private String dataSourceArn; public String getName() { return name; } public void setName(String name) { this.name = name; } @@ -54,4 +55,7 @@ public class DataSource { public Map getAmazonBedrockRuntimeConfig() { return amazonBedrockRuntimeConfig; } public void setAmazonBedrockRuntimeConfig(Map config) { this.amazonBedrockRuntimeConfig = config; } + + public String getDataSourceArn() { return dataSourceArn; } + public void setDataSourceArn(String dataSourceArn) { this.dataSourceArn = dataSourceArn; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/DomainName.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/DomainName.java new file mode 100644 index 0000000000..178412fcdc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/DomainName.java @@ -0,0 +1,42 @@ +package io.github.hectorvent.floci.services.appsync.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.HashMap; +import java.util.Map; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class DomainName { + private String domainName; + private String description; + private String certificateArn; + private String appsyncDomainName; + private String hostedZoneId; + private String domainNameArn; + private Map tags = new HashMap<>(); + + public String getDomainName() { return domainName; } + public void setDomainName(String domainName) { this.domainName = domainName; } + + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + + public String getCertificateArn() { return certificateArn; } + public void setCertificateArn(String certificateArn) { this.certificateArn = certificateArn; } + + public String getAppsyncDomainName() { return appsyncDomainName; } + public void setAppsyncDomainName(String appsyncDomainName) { this.appsyncDomainName = appsyncDomainName; } + + public String getHostedZoneId() { return hostedZoneId; } + public void setHostedZoneId(String hostedZoneId) { this.hostedZoneId = hostedZoneId; } + + public String getDomainNameArn() { return domainNameArn; } + public void setDomainNameArn(String domainNameArn) { this.domainNameArn = domainNameArn; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} 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 6313f8c460..81d78f65dc 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 @@ -15,7 +15,7 @@ public class FunctionConfiguration { private String requestMappingTemplate; private String responseMappingTemplate; private String functionVersion; - private String arn; + private String functionArn; private String code; public String getFunctionId() { return functionId; } @@ -39,8 +39,8 @@ public class FunctionConfiguration { public String getFunctionVersion() { return functionVersion; } public void setFunctionVersion(String functionVersion) { this.functionVersion = functionVersion; } - public String getArn() { return arn; } - public void setArn(String arn) { this.arn = arn; } + public String getFunctionArn() { return functionArn; } + public void setFunctionArn(String functionArn) { this.functionArn = functionArn; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/GraphqlApi.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/GraphqlApi.java index 63a107506a..34d1438df4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/model/GraphqlApi.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/GraphqlApi.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import io.quarkus.runtime.annotations.RegisterForReflection; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -19,10 +18,24 @@ public class GraphqlApi { private AuthenticationType authenticationType; private Map uris = new HashMap<>(); private Map logConfig; - private List> additionalAuthenticationProviders; + private List additionalAuthenticationProviders; private Boolean xrayEnabled; private Map tags = new HashMap<>(); private Map environmentVariables = new HashMap<>(); + private String apiType = "GRAPHQL"; + private String owner; + private String ownerContact; + private String visibility = "GLOBAL"; + private String introspectionConfig; + private Integer queryDepthLimit; + private Integer resolverCountLimit; + private Map enhancedMetricsConfig; + private Map lambdaAuthorizerConfig; + private Map openIDConnectConfig; + private Map userPoolConfig; + private Map dns; + private String wafWebAclArn; + private String mergedApiExecutionRoleArn; public String getApiId() { return apiId; } public void setApiId(String apiId) { this.apiId = apiId; } @@ -42,8 +55,8 @@ public class GraphqlApi { public Map getLogConfig() { return logConfig; } public void setLogConfig(Map logConfig) { this.logConfig = logConfig; } - public List> getAdditionalAuthenticationProviders() { return additionalAuthenticationProviders; } - public void setAdditionalAuthenticationProviders(List> providers) { this.additionalAuthenticationProviders = providers; } + public List getAdditionalAuthenticationProviders() { return additionalAuthenticationProviders; } + public void setAdditionalAuthenticationProviders(List additionalAuthenticationProviders) { this.additionalAuthenticationProviders = additionalAuthenticationProviders; } public Boolean getXrayEnabled() { return xrayEnabled; } public void setXrayEnabled(Boolean xrayEnabled) { this.xrayEnabled = xrayEnabled; } @@ -53,4 +66,46 @@ public class GraphqlApi { public Map getEnvironmentVariables() { return environmentVariables; } public void setEnvironmentVariables(Map environmentVariables) { this.environmentVariables = environmentVariables; } + + public String getApiType() { return apiType; } + public void setApiType(String apiType) { this.apiType = apiType; } + + public String getOwner() { return owner; } + public void setOwner(String owner) { this.owner = owner; } + + public String getOwnerContact() { return ownerContact; } + public void setOwnerContact(String ownerContact) { this.ownerContact = ownerContact; } + + public String getVisibility() { return visibility; } + public void setVisibility(String visibility) { this.visibility = visibility; } + + public String getIntrospectionConfig() { return introspectionConfig; } + public void setIntrospectionConfig(String introspectionConfig) { this.introspectionConfig = introspectionConfig; } + + public Integer getQueryDepthLimit() { return queryDepthLimit; } + public void setQueryDepthLimit(Integer queryDepthLimit) { this.queryDepthLimit = queryDepthLimit; } + + public Integer getResolverCountLimit() { return resolverCountLimit; } + public void setResolverCountLimit(Integer resolverCountLimit) { this.resolverCountLimit = resolverCountLimit; } + + public Map getEnhancedMetricsConfig() { return enhancedMetricsConfig; } + public void setEnhancedMetricsConfig(Map enhancedMetricsConfig) { this.enhancedMetricsConfig = enhancedMetricsConfig; } + + public Map getLambdaAuthorizerConfig() { return lambdaAuthorizerConfig; } + public void setLambdaAuthorizerConfig(Map lambdaAuthorizerConfig) { this.lambdaAuthorizerConfig = lambdaAuthorizerConfig; } + + public Map getOpenIDConnectConfig() { return openIDConnectConfig; } + public void setOpenIDConnectConfig(Map openIDConnectConfig) { this.openIDConnectConfig = openIDConnectConfig; } + + public Map getUserPoolConfig() { return userPoolConfig; } + public void setUserPoolConfig(Map userPoolConfig) { this.userPoolConfig = userPoolConfig; } + + public Map getDns() { return dns; } + public void setDns(Map dns) { this.dns = dns; } + + public String getWafWebAclArn() { return wafWebAclArn; } + public void setWafWebAclArn(String wafWebAclArn) { this.wafWebAclArn = wafWebAclArn; } + + public String getMergedApiExecutionRoleArn() { return mergedApiExecutionRoleArn; } + public void setMergedApiExecutionRoleArn(String mergedApiExecutionRoleArn) { this.mergedApiExecutionRoleArn = mergedApiExecutionRoleArn; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/HandlerConfig.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/HandlerConfig.java new file mode 100644 index 0000000000..98f5df4b44 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/HandlerConfig.java @@ -0,0 +1,19 @@ +package io.github.hectorvent.floci.services.appsync.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class HandlerConfig { + private String behavior; + private Integration integration; + + public String getBehavior() { return behavior; } + public void setBehavior(String behavior) { this.behavior = behavior; } + + public Integration getIntegration() { return integration; } + public void setIntegration(Integration integration) { this.integration = integration; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/HandlerConfigs.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/HandlerConfigs.java new file mode 100644 index 0000000000..4740a2478a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/HandlerConfigs.java @@ -0,0 +1,19 @@ +package io.github.hectorvent.floci.services.appsync.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class HandlerConfigs { + private HandlerConfig onPublish; + private HandlerConfig onSubscribe; + + public HandlerConfig getOnPublish() { return onPublish; } + public void setOnPublish(HandlerConfig onPublish) { this.onPublish = onPublish; } + + public HandlerConfig getOnSubscribe() { return onSubscribe; } + public void setOnSubscribe(HandlerConfig onSubscribe) { this.onSubscribe = onSubscribe; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/Integration.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/Integration.java new file mode 100644 index 0000000000..e5411871d6 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/Integration.java @@ -0,0 +1,19 @@ +package io.github.hectorvent.floci.services.appsync.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Integration { + private String dataSourceName; + private LambdaConfig lambdaConfig; + + public String getDataSourceName() { return dataSourceName; } + public void setDataSourceName(String dataSourceName) { this.dataSourceName = dataSourceName; } + + public LambdaConfig getLambdaConfig() { return lambdaConfig; } + public void setLambdaConfig(LambdaConfig lambdaConfig) { this.lambdaConfig = lambdaConfig; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/LambdaConfig.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/LambdaConfig.java new file mode 100644 index 0000000000..20c6274610 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/LambdaConfig.java @@ -0,0 +1,15 @@ +package io.github.hectorvent.floci.services.appsync.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class LambdaConfig { + private String invokeType; + + public String getInvokeType() { return invokeType; } + public void setInvokeType(String invokeType) { this.invokeType = invokeType; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/Resolver.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/Resolver.java index a715e966e4..a18820f8f5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/model/Resolver.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/Resolver.java @@ -4,6 +4,8 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.Map; + @RegisterForReflection @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) @@ -18,6 +20,12 @@ public class Resolver { private ResolverKind kind; private String code; private ResolverRuntime runtime; + private String resolverArn; + private Map cachingConfig; + private Integer maxBatchSize; + private String metricsConfig; + private Map pipelineConfig; + private Map syncConfig; public String getApiId() { return apiId; } public void setApiId(String apiId) { this.apiId = apiId; } @@ -49,6 +57,24 @@ public class Resolver { public ResolverRuntime getRuntime() { return runtime; } public void setRuntime(ResolverRuntime runtime) { this.runtime = runtime; } + public String getResolverArn() { return resolverArn; } + public void setResolverArn(String resolverArn) { this.resolverArn = resolverArn; } + + public Map getCachingConfig() { return cachingConfig; } + public void setCachingConfig(Map cachingConfig) { this.cachingConfig = cachingConfig; } + + public Integer getMaxBatchSize() { return maxBatchSize; } + public void setMaxBatchSize(Integer maxBatchSize) { this.maxBatchSize = maxBatchSize; } + + public String getMetricsConfig() { return metricsConfig; } + public void setMetricsConfig(String metricsConfig) { this.metricsConfig = metricsConfig; } + + public Map getPipelineConfig() { return pipelineConfig; } + public void setPipelineConfig(Map pipelineConfig) { this.pipelineConfig = pipelineConfig; } + + public Map getSyncConfig() { return syncConfig; } + public void setSyncConfig(Map syncConfig) { this.syncConfig = syncConfig; } + @RegisterForReflection @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/SourceApiAssociation.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/SourceApiAssociation.java new file mode 100644 index 0000000000..bad0f669d6 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/SourceApiAssociation.java @@ -0,0 +1,55 @@ +package io.github.hectorvent.floci.services.appsync.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class SourceApiAssociation { + private String associationArn; + private String associationId; + private String description; + private Long lastSuccessfulMergeDate; + private String mergedApiArn; + private String mergedApiId; + private String sourceApiArn; + private SourceApiAssociationConfig sourceApiAssociationConfig; + private String sourceApiAssociationStatus; + private String sourceApiAssociationStatusDetail; + private String sourceApiId; + + public String getAssociationArn() { return associationArn; } + public void setAssociationArn(String associationArn) { this.associationArn = associationArn; } + + public String getAssociationId() { return associationId; } + public void setAssociationId(String associationId) { this.associationId = associationId; } + + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + + public Long getLastSuccessfulMergeDate() { return lastSuccessfulMergeDate; } + public void setLastSuccessfulMergeDate(Long lastSuccessfulMergeDate) { this.lastSuccessfulMergeDate = lastSuccessfulMergeDate; } + + public String getMergedApiArn() { return mergedApiArn; } + public void setMergedApiArn(String mergedApiArn) { this.mergedApiArn = mergedApiArn; } + + public String getMergedApiId() { return mergedApiId; } + public void setMergedApiId(String mergedApiId) { this.mergedApiId = mergedApiId; } + + public String getSourceApiArn() { return sourceApiArn; } + public void setSourceApiArn(String sourceApiArn) { this.sourceApiArn = sourceApiArn; } + + public SourceApiAssociationConfig getSourceApiAssociationConfig() { return sourceApiAssociationConfig; } + public void setSourceApiAssociationConfig(SourceApiAssociationConfig config) { this.sourceApiAssociationConfig = config; } + + public String getSourceApiAssociationStatus() { return sourceApiAssociationStatus; } + public void setSourceApiAssociationStatus(String sourceApiAssociationStatus) { this.sourceApiAssociationStatus = sourceApiAssociationStatus; } + + public String getSourceApiAssociationStatusDetail() { return sourceApiAssociationStatusDetail; } + public void setSourceApiAssociationStatusDetail(String sourceApiAssociationStatusDetail) { this.sourceApiAssociationStatusDetail = sourceApiAssociationStatusDetail; } + + public String getSourceApiId() { return sourceApiId; } + public void setSourceApiId(String sourceApiId) { this.sourceApiId = sourceApiId; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/SourceApiAssociationConfig.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/SourceApiAssociationConfig.java new file mode 100644 index 0000000000..cd38b73338 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/SourceApiAssociationConfig.java @@ -0,0 +1,15 @@ +package io.github.hectorvent.floci.services.appsync.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class SourceApiAssociationConfig { + private String mergeType; + + public String getMergeType() { return mergeType; } + public void setMergeType(String mergeType) { this.mergeType = mergeType; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/model/SourceApiAssociationSummary.java b/src/main/java/io/github/hectorvent/floci/services/appsync/model/SourceApiAssociationSummary.java new file mode 100644 index 0000000000..2e23f8e374 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/model/SourceApiAssociationSummary.java @@ -0,0 +1,39 @@ +package io.github.hectorvent.floci.services.appsync.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class SourceApiAssociationSummary { + private String associationArn; + private String associationId; + private String description; + private String mergedApiArn; + private String mergedApiId; + private String sourceApiArn; + private String sourceApiId; + + public String getAssociationArn() { return associationArn; } + public void setAssociationArn(String associationArn) { this.associationArn = associationArn; } + + public String getAssociationId() { return associationId; } + public void setAssociationId(String associationId) { this.associationId = associationId; } + + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + + public String getMergedApiArn() { return mergedApiArn; } + public void setMergedApiArn(String mergedApiArn) { this.mergedApiArn = mergedApiArn; } + + public String getMergedApiId() { return mergedApiId; } + public void setMergedApiId(String mergedApiId) { this.mergedApiId = mergedApiId; } + + public String getSourceApiArn() { return sourceApiArn; } + public void setSourceApiArn(String sourceApiArn) { this.sourceApiArn = sourceApiArn; } + + public String getSourceApiId() { return sourceApiId; } + public void setSourceApiId(String sourceApiId) { this.sourceApiId = sourceApiId; } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncIntegrationTest.java index 3f8d55fe1b..bff8f4edea 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/AppSyncIntegrationTest.java @@ -144,7 +144,7 @@ class AppSyncIntegrationTest { .get("/v1/apis/" + apiId + "/schema") .then() .statusCode(200) - .body("schema", containsString("type Query")); + .body("schema.definition", containsString("type Query")); } // ── API Keys ───────────────────────────────────────────────────────────── @@ -516,7 +516,7 @@ class AppSyncIntegrationTest { .statusCode(200) .body("functionConfiguration.name", equalTo("my-function")) .body("functionConfiguration.functionId", notNullValue()) - .body("functionConfiguration.arn", containsString("arn:aws:appsync:")) + .body("functionConfiguration.functionArn", containsString("arn:aws:appsync:")) .extract().path("functionConfiguration.functionId"); } @@ -1208,13 +1208,28 @@ class AppSyncIntegrationTest { .statusCode(200) .extract().path("graphqlApi.apiId"); + // Create a data source first (function requires it) + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "name": "cascade-fn-ds", + "type": "NONE" + } + """) + .when() + .post("/v1/apis/" + tempApiId + "/datasources") + .then() + .statusCode(200); + String fnId = given() .header("Authorization", AUTH) .contentType("application/json") .body(""" { "name": "cascade-fn", - "dataSourceName": "none-ds" + "dataSourceName": "cascade-fn-ds" } """) .when() @@ -1444,8 +1459,1136 @@ class AppSyncIntegrationTest { .statusCode(400); } + // ── Phase 2: Model Completeness ───────────────────────────────────────── + + @Test + @Order(200) + void createGraphqlApi_returnsNewFields() { + String tempApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "name": "full-api", + "authenticationType": "API_KEY", + "apiType": "GRAPHQL", + "visibility": "GLOBAL", + "queryDepthLimit": 10 + } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .body("graphqlApi.apiType", equalTo("GRAPHQL")) + .body("graphqlApi.visibility", equalTo("GLOBAL")) + .body("graphqlApi.queryDepthLimit", equalTo(10)) + .extract().path("graphqlApi.apiId"); + + // cleanup + given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + } + + @Test + @Order(205) + void updateGraphqlApi_handlesNewFields() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "owner": "test-owner", + "ownerContact": "test@example.com", + "queryDepthLimit": 25, + "resolverCountLimit": 100 + } + """) + .when() + .post("/v1/apis/" + apiId) + .then() + .statusCode(200) + .body("graphqlApi.owner", equalTo("test-owner")) + .body("graphqlApi.ownerContact", equalTo("test@example.com")) + .body("graphqlApi.queryDepthLimit", equalTo(25)) + .body("graphqlApi.resolverCountLimit", equalTo(100)); + } + + @Test + @Order(207) + void updateGraphqlApi_additionalAuthProviders() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "additionalAuthenticationProviders": [ + {"authenticationType": "AWS_IAM"} + ] + } + """) + .when() + .post("/v1/apis/" + apiId) + .then() + .statusCode(200) + .body("graphqlApi.additionalAuthenticationProviders", hasSize(1)) + .body("graphqlApi.additionalAuthenticationProviders[0].authenticationType", equalTo("AWS_IAM")); + } + + @Test + @Order(210) + void createDataSource_returnsDataSourceArn() { + String dsName = "arn-test-ds"; + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "name": "%s", + "type": "NONE" + } + """.formatted(dsName)) + .when() + .post("/v1/apis/" + apiId + "/datasources") + .then() + .statusCode(200) + .body("dataSource.dataSourceArn", containsString("arn:aws:appsync:")) + .body("dataSource.dataSourceArn", containsString("/datasources/" + dsName)); + + // cleanup + given().header("Authorization", AUTH).delete("/v1/apis/" + apiId + "/datasources/" + dsName).then().statusCode(204); + } + + @Test + @Order(215) + void createResolver_returnsResolverArn() { + String resolverName = "resolverArnTest"; + String dsName = "resolver-arn-ds"; + + // create temp data source + given().header("Authorization", AUTH).contentType("application/json") + .body(""" + { "name": "%s", "type": "NONE" } + """.formatted(dsName)) + .post("/v1/apis/" + apiId + "/datasources").then().statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "fieldName": "%s", + "dataSourceName": "%s" + } + """.formatted(resolverName, dsName)) + .when() + .post("/v1/apis/" + apiId + "/types/Query/resolvers") + .then() + .statusCode(200) + .body("resolver.resolverArn", containsString("arn:aws:appsync:")) + .body("resolver.resolverArn", containsString("/types/Query/resolvers/" + resolverName)); + + // cleanup + given().header("Authorization", AUTH).delete("/v1/apis/" + apiId + "/types/Query/resolvers/" + resolverName).then().statusCode(204); + given().header("Authorization", AUTH).delete("/v1/apis/" + apiId + "/datasources/" + dsName).then().statusCode(204); + } + + @Test + @Order(220) + void getIntrospectionSchema_nestedFormat() { + given() + .header("Authorization", AUTH) + .when() + .get("/v1/apis/" + apiId + "/schema") + .then() + .statusCode(200) + .body("schema.definition", containsString("type Query")); + } + + // ── Phase 2: Domain Names ──────────────────────────────────────────────── + + private static String domainName; + + @Test + @Order(300) + void createDomainName() { + domainName = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "domainName": "api.example.com", + "description": "Test domain", + "certificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/123" + } + """) + .when() + .post("/v1/domainnames") + .then() + .statusCode(200) + .body("domainNameConfig.domainName", equalTo("api.example.com")) + .body("domainNameConfig.description", equalTo("Test domain")) + .body("domainNameConfig.appsyncDomainName", containsString(".appsync-api.")) + .body("domainNameConfig.hostedZoneId", notNullValue()) + .extract().path("domainNameConfig.domainName"); + } + + @Test + @Order(301) + void getDomainName() { + given() + .header("Authorization", AUTH) + .when() + .get("/v1/domainnames/" + domainName) + .then() + .statusCode(200) + .body("domainNameConfig.domainName", equalTo("api.example.com")); + } + + @Test + @Order(302) + void listDomainNames() { + given() + .header("Authorization", AUTH) + .when() + .get("/v1/domainnames") + .then() + .statusCode(200) + .body("domainNames", hasSize(greaterThanOrEqualTo(1))); + } + + @Test + @Order(303) + void associateApi() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "apiId": "%s" + } + """.formatted(apiId)) + .when() + .post("/v1/domainnames/" + domainName + "/apiassociation") + .then() + .statusCode(200) + .body("apiAssociation.apiId", equalTo(apiId)) + .body("apiAssociation.domainName", equalTo(domainName)); + } + + @Test + @Order(304) + void getAssociatedApi() { + given() + .header("Authorization", AUTH) + .when() + .get("/v1/domainnames/" + domainName + "/apiassociation") + .then() + .statusCode(200) + .body("apiAssociation.apiId", equalTo(apiId)); + } + + @Test + @Order(306) + void disassociateApi() { + given() + .header("Authorization", AUTH) + .when() + .delete("/v1/domainnames/" + domainName + "/apiassociation") + .then() + .statusCode(204); + } + + @Test + @Order(307) + void deleteDomainName() { + given() + .header("Authorization", AUTH) + .when() + .delete("/v1/domainnames/" + domainName) + .then() + .statusCode(204); + } + + @Test + @Order(308) + void domainName_notFound() { + given() + .header("Authorization", AUTH) + .when() + .get("/v1/domainnames/nonexistent.example.com") + .then() + .statusCode(404); + } + + @Test + @Order(309) + void associateApi_invalidApi() { + // Create a temp domain to test invalid association + String tempDomain = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "domainName": "invalid-test.example.com", + "description": "temp", + "certificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/123" + } + """) + .when() + .post("/v1/domainnames") + .then() + .statusCode(200) + .extract().path("domainNameConfig.domainName"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "apiId": "nonexistent00000000000000" + } + """) + .when() + .post("/v1/domainnames/" + tempDomain + "/apiassociation") + .then() + .statusCode(404); + + // cleanup + given().header("Authorization", AUTH).delete("/v1/domainnames/" + tempDomain).then().statusCode(204); + } + + // ── Phase 2: Channel Namespaces ────────────────────────────────────────── + + private static String channelNsName; + + @Test + @Order(400) + void createChannelNamespace() { + channelNsName = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "name": "my-channels", + "description": "Test channel namespace" + } + """) + .when() + .post("/v2/apis/" + apiId + "/channelNamespaces") + .then() + .statusCode(200) + .body("channelNamespace.name", equalTo("my-channels")) + .body("channelNamespace.description", equalTo("Test channel namespace")) + .extract().path("channelNamespace.name"); + } + + @Test + @Order(401) + void getChannelNamespace() { + given() + .header("Authorization", AUTH) + .when() + .get("/v2/apis/" + apiId + "/channelNamespaces/" + channelNsName) + .then() + .statusCode(200) + .body("channelNamespace.name", equalTo("my-channels")); + } + + @Test + @Order(402) + void listChannelNamespaces() { + given() + .header("Authorization", AUTH) + .when() + .get("/v2/apis/" + apiId + "/channelNamespaces") + .then() + .statusCode(200) + .body("channelNamespaces", hasSize(greaterThanOrEqualTo(1))); + } + + @Test + @Order(403) + void deleteChannelNamespace() { + given() + .header("Authorization", AUTH) + .when() + .delete("/v2/apis/" + apiId + "/channelNamespaces/" + channelNsName) + .then() + .statusCode(204); + } + + // ── Phase 2: Schema Registry ───────────────────────────────────────────── + + @Test + @Order(600) + void startSchemaCreation_validatesSDL() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "definition": "type Query { invalid syntax!!! }" + } + """) + .when() + .post("/v1/apis/" + apiId + "/schemacreation") + .then() + .statusCode(400); + } + + @Test + @Order(601) + void schemaRegistry_parseSimpleSchema() { + String tempApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "schema-test", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "definition": "type Query { hello: String }" + } + """) + .when() + .post("/v1/apis/" + tempApiId + "/schemacreation") + .then() + .statusCode(200) + .body("status", equalTo("ACTIVE")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + } + + @Test + @Order(602) + void schemaRegistry_parseWithAWSScalars() { + String tempApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "scalar-test", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "definition": "type Query { now: AWSDateTime, data: AWSJSON }" + } + """) + .when() + .post("/v1/apis/" + tempApiId + "/schemacreation") + .then() + .statusCode(200) + .body("status", equalTo("ACTIVE")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + } + + @Test + @Order(603) + void schemaRegistry_schemaExtension() { + String tempApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "ext-test", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "definition": "type Query { hello: String } extend type Query { world: String }" + } + """) + .when() + .post("/v1/apis/" + tempApiId + "/schemacreation") + .then() + .statusCode(200) + .body("status", equalTo("ACTIVE")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + } + + @Test + @Order(604) + void directive_awsApiKey_inSchema() { + String tempApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "dir-test", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "definition": "type Query @aws_api_key { hello: String }" + } + """) + .when() + .post("/v1/apis/" + tempApiId + "/schemacreation") + .then() + .statusCode(200) + .body("status", equalTo("ACTIVE")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + } + + @Test + @Order(605) + void directive_awsSubscribe_validMutation() { + String tempApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "sub-test", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "definition": "type Query { dummy: String } type Mutation { createPost(id: ID!): Post } type Subscription { onPost: Post @aws_subscribe(mutations: [\\\"createPost\\\"]) } type Post { id: ID! }" + } + """) + .when() + .post("/v1/apis/" + tempApiId + "/schemacreation") + .then() + .statusCode(200) + .body("status", equalTo("ACTIVE")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + } + + @Test + @Order(606) + void directive_skipInclude_work() { + // @skip/@include are built-in graphql-java directives. + // They are valid on FIELD (in queries), not on FIELD_DEFINITION (in type definitions). + // This test verifies that SDL parsing still works when these standard directives + // are present (e.g. @deprecated on a field definition). + String tempApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "skiptest", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "definition": "type Query { hello: String @deprecated(reason: \\\"use world\\\") }" + } + """) + .when() + .post("/v1/apis/" + tempApiId + "/schemacreation") + .then() + .statusCode(200) + .body("status", equalTo("ACTIVE")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + } + + @Test + @Order(607) + void directive_unknown_rejected() { + String tempApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "unknowntest", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "definition": "type Query { hello: String } directive @unknownDirective on FIELD_DEFINITION" + } + """) + .when() + .post("/v1/apis/" + tempApiId + "/schemacreation") + .then() + .statusCode(400); + + given().header("Authorization", AUTH).delete("/v1/apis/" + tempApiId).then().statusCode(204); + } + + // ── Phase 2: Merged APIs ─────────────────────────────────────────────── + + @Test + @Order(610) + void associateSourceGraphqlApi() { + // Create source API + String sourceApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "merged-source", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + // Association between the main API and source + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "sourceApiId": "%s", + "description": "test association" + } + """.formatted(sourceApiId)) + .when() + .post("/v1/mergedApis/" + apiId + "/sourceApiAssociations") + .then() + .statusCode(200) + .body("sourceApiAssociation.mergedApiId", equalTo(apiId)) + .body("sourceApiAssociation.sourceApiId", equalTo(sourceApiId)) + .body("sourceApiAssociation.sourceApiAssociationStatus", equalTo("MERGED")) + .body("sourceApiAssociation.associationId", notNullValue()); + + given().header("Authorization", AUTH).delete("/v1/apis/" + sourceApiId).then().statusCode(204); + } + + @Test + @Order(611) + void getSourceApiAssociation() { + String sourceApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "get-source", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + String assocId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "sourceApiId": "%s" } + """.formatted(sourceApiId)) + .when() + .post("/v1/mergedApis/" + apiId + "/sourceApiAssociations") + .then() + .statusCode(200) + .extract().path("sourceApiAssociation.associationId"); + + given() + .header("Authorization", AUTH) + .when() + .get("/v1/mergedApis/" + apiId + "/sourceApiAssociations/" + assocId) + .then() + .statusCode(200) + .body("sourceApiAssociation.associationId", equalTo(assocId)); + + given().header("Authorization", AUTH).delete("/v1/apis/" + sourceApiId).then().statusCode(204); + } + + @Test + @Order(612) + void listSourceApiAssociations() { + String sourceApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "list-source", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "sourceApiId": "%s" } + """.formatted(sourceApiId)) + .when() + .post("/v1/mergedApis/" + apiId + "/sourceApiAssociations") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .when() + .get("/v1/apis/" + apiId + "/sourceApiAssociations") + .then() + .statusCode(200) + .body("sourceApiAssociationSummaries", hasSize(greaterThanOrEqualTo(1))); + + given().header("Authorization", AUTH).delete("/v1/apis/" + sourceApiId).then().statusCode(204); + } + + @Test + @Order(613) + void deleteSourceApiAssociation() { + String sourceApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "del-source", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + String assocId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "sourceApiId": "%s" } + """.formatted(sourceApiId)) + .when() + .post("/v1/mergedApis/" + apiId + "/sourceApiAssociations") + .then() + .statusCode(200) + .extract().path("sourceApiAssociation.associationId"); + + given() + .header("Authorization", AUTH) + .when() + .delete("/v1/mergedApis/" + apiId + "/sourceApiAssociations/" + assocId) + .then() + .statusCode(200) + .body("sourceApiAssociationStatus", equalTo("DELETION_SCHEDULED")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + sourceApiId).then().statusCode(204); + } + + // ── Phase 2: New endpoint coverage ──────────────────────────────── + + @Test + @Order(614) + void updateDomainName() { + String testDomain = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "domainName": "update-test.example.com", + "certificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/update" + } + """) + .when() + .post("/v1/domainnames") + .then() + .statusCode(200) + .extract().path("domainNameConfig.domainName"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "description": "updated description" } + """) + .when() + .post("/v1/domainnames/" + testDomain) + .then() + .statusCode(200) + .body("domainNameConfig.domainName", equalTo(testDomain)) + .body("domainNameConfig.description", equalTo("updated description")); + + given().header("Authorization", AUTH).delete("/v1/domainnames/" + testDomain).then().statusCode(204); + } + + @Test + @Order(615) + void associateMergedGraphqlApi() { + String sourceApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "merged-source-v2", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "mergedApiIdentifier": "%s", + "description": "merged test" + } + """.formatted(apiId)) + .when() + .post("/v1/sourceApis/" + sourceApiId + "/mergedApiAssociations") + .then() + .statusCode(200) + .body("sourceApiAssociation.sourceApiId", equalTo(sourceApiId)) + .body("sourceApiAssociation.mergedApiId", equalTo(apiId)) + .body("sourceApiAssociation.sourceApiAssociationStatus", equalTo("MERGED")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + sourceApiId).then().statusCode(204); + } + + @Test + @Order(616) + void updateSourceApiAssociation() { + String sourceApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "update-source", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + String assocId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "sourceApiId": "%s" } + """.formatted(sourceApiId)) + .when() + .post("/v1/mergedApis/" + apiId + "/sourceApiAssociations") + .then() + .statusCode(200) + .extract().path("sourceApiAssociation.associationId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "description": "updated assoc" } + """) + .when() + .post("/v1/mergedApis/" + apiId + "/sourceApiAssociations/" + assocId) + .then() + .statusCode(200) + .body("sourceApiAssociation.description", equalTo("updated assoc")) + .body("sourceApiAssociation.associationId", equalTo(assocId)); + + given().header("Authorization", AUTH).delete("/v1/apis/" + sourceApiId).then().statusCode(204); + } + + @Test + @Order(617) + void disassociateMergedGraphqlApi() { + String sourceApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "disassoc-source", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + String assocId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "mergedApiIdentifier": "%s" } + """.formatted(apiId)) + .when() + .post("/v1/sourceApis/" + sourceApiId + "/mergedApiAssociations") + .then() + .statusCode(200) + .extract().path("sourceApiAssociation.associationId"); + + given() + .header("Authorization", AUTH) + .when() + .delete("/v1/sourceApis/" + sourceApiId + "/mergedApiAssociations/" + assocId) + .then() + .statusCode(200) + .body("sourceApiAssociationStatus", equalTo("DELETION_SCHEDULED")); + + given().header("Authorization", AUTH).delete("/v1/apis/" + sourceApiId).then().statusCode(204); + } + // ── Teardown ───────────────────────────────────────────────────────────── + // ── Phase 2: Edge Cases ────────────────────────────────────────────── + + @Test + @Order(620) + void updateGraphqlApi_additionalAuthProvidersNull() { + // Set initial providers + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "additionalAuthenticationProviders": [ + {"authenticationType": "AWS_IAM"} + ] + } + """) + .when() + .post("/v1/apis/" + apiId) + .then() + .statusCode(200) + .body("graphqlApi.additionalAuthenticationProviders", hasSize(1)); + + // Send null — should preserve existing + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "additionalAuthenticationProviders": null } + """) + .when() + .post("/v1/apis/" + apiId) + .then() + .statusCode(200) + .body("graphqlApi.additionalAuthenticationProviders", hasSize(1)); + } + + @Test + @Order(621) + void createResolver_withMaxBatchSizeZero() { + String dsName = "batch-zero-ds"; + given().header("Authorization", AUTH).contentType("application/json") + .body(""" + { "name": "%s", "type": "NONE" } + """.formatted(dsName)) + .post("/v1/apis/" + apiId + "/datasources").then().statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "fieldName": "batchZeroTest", + "dataSourceName": "%s", + "maxBatchSize": 0 + } + """.formatted(dsName)) + .when() + .post("/v1/apis/" + apiId + "/types/Query/resolvers") + .then() + .statusCode(200) + .body("resolver.maxBatchSize", equalTo(0)); + + given().header("Authorization", AUTH) + .delete("/v1/apis/" + apiId + "/types/Query/resolvers/batchZeroTest").then().statusCode(204); + given().header("Authorization", AUTH) + .delete("/v1/apis/" + apiId + "/datasources/" + dsName).then().statusCode(204); + } + + @Test + @Order(622) + void updateGraphqlApi_dnsNull() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "dns": null } + """) + .when() + .post("/v1/apis/" + apiId) + .then() + .statusCode(200); + } + + @Test + @Order(623) + void createDomainName_invalidCertificateArn() { + // Our emulator doesn't validate certificate ARN format, so this should succeed (200). + // AWS itself validates the pattern, but we're permissive. + String tempDomain = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "domainName": "invalidd-cert.example.com", + "certificateArn": "not-a-valid-arn" + } + """) + .when() + .post("/v1/domainnames") + .then() + .statusCode(200) + .extract().path("domainNameConfig.domainName"); + + given().header("Authorization", AUTH) + .delete("/v1/domainnames/" + tempDomain).then().statusCode(204); + } + + @Test + @Order(624) + void deleteGraphqlApi_removesDomainAssociation() { + // Create a domain + API + association + String tempApiId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "name": "edge-del-api", "authenticationType": "API_KEY" } + """) + .when() + .post("/v1/apis") + .then() + .statusCode(200) + .extract().path("graphqlApi.apiId"); + + String tempDomain = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "domainName": "edge-del.example.com", + "certificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/edge" + } + """) + .when() + .post("/v1/domainnames") + .then() + .statusCode(200) + .extract().path("domainNameConfig.domainName"); + + // Associate + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "apiId": "%s" } + """.formatted(tempApiId)) + .when() + .post("/v1/domainnames/" + tempDomain + "/apiassociation") + .then() + .statusCode(200); + + // Delete API + given() + .header("Authorization", AUTH) + .when() + .delete("/v1/apis/" + tempApiId) + .then() + .statusCode(204); + + // Domain should still exist (association was cleaned up) + given() + .header("Authorization", AUTH) + .when() + .get("/v1/domainnames/" + tempDomain) + .then() + .statusCode(200); + + // Cleanup domain + given().header("Authorization", AUTH) + .delete("/v1/domainnames/" + tempDomain).then().statusCode(204); + } + + @Test + @Order(625) + void deleteDomainName_associatedApiStillWorks() { + // Create a domain + associate with the main apiId + String tempDomain = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "domainName": "edge-api-still-works.example.com", + "certificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/edge2" + } + """) + .when() + .post("/v1/domainnames") + .then() + .statusCode(200) + .extract().path("domainNameConfig.domainName"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { "apiId": "%s" } + """.formatted(apiId)) + .when() + .post("/v1/domainnames/" + tempDomain + "/apiassociation") + .then() + .statusCode(200); + + // Delete domain + given() + .header("Authorization", AUTH) + .when() + .delete("/v1/domainnames/" + tempDomain) + .then() + .statusCode(204); + + // API should still work + given() + .header("Authorization", AUTH) + .when() + .get("/v1/apis/" + apiId) + .then() + .statusCode(200) + .body("graphqlApi.apiId", equalTo(apiId)); + } + @Test @Order(900) void deleteApiKey() { diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/scalars/AppSyncScalarsTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/scalars/AppSyncScalarsTest.java new file mode 100644 index 0000000000..4d8f70c2d8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/scalars/AppSyncScalarsTest.java @@ -0,0 +1,152 @@ +package io.github.hectorvent.floci.services.appsync.graphql.scalars; + +import graphql.schema.GraphQLScalarType; +import graphql.schema.CoercingParseValueException; +import graphql.schema.CoercingSerializeException; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class AppSyncScalarsTest { + + @Test + void scalar_allRegistered() { + AppSyncScalarRegistry registry = new AppSyncScalarRegistry(); + List scalars = registry.allScalars(); + assertThat(scalars, hasSize(greaterThanOrEqualTo(17))); + assertThat(scalars.stream().map(GraphQLScalarType::getName).toList(), + hasItems("AWSJSON", "AWSDateTime", "AWSDate", "AWSTime", "AWSTimestamp", + "AWSEmail", "AWSURL", "AWSPhone", "AWSIPAddress", "AWSBoolean", + "AWSLong", "AWSInteger", "AWSShort", "AWSFloat", + "AWSBigDecimal", "AWSBigInt", "AWSByte")); + } + + @Test + void scalar_awsdatetime_parseValue() { + Object valid = AppSyncScalars.AWS_DATE_TIME.getCoercing().parseValue("2026-06-04T12:00:00Z"); + assertThat(valid, is("2026-06-04T12:00:00Z")); + + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_DATE_TIME.getCoercing().parseValue("not-a-date")); + } + + @Test + void scalar_awsjson_parseValue() { + Object valid = AppSyncScalars.AWSJSON.getCoercing().parseValue("{\"key\": \"value\"}"); + assertThat(valid, is("{\"key\": \"value\"}")); + + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWSJSON.getCoercing().parseValue("not json")); + } + + @Test + void scalar_awsemail_parseValue() { + Object valid = AppSyncScalars.AWS_EMAIL.getCoercing().parseValue("user@example.com"); + assertThat(valid, is("user@example.com")); + + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_EMAIL.getCoercing().parseValue("not-an-email")); + } + + @Test + void scalar_awstimestamp_range() { + Object valid = AppSyncScalars.AWS_TIMESTAMP.getCoercing().parseValue(1700000000L); + assertThat(valid, is(1700000000L)); + + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_TIMESTAMP.getCoercing().parseValue(-1L)); + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_TIMESTAMP.getCoercing().parseValue(40000000000L)); + } + + @Test + void scalar_awsurl_parseValue() { + Object valid = AppSyncScalars.AWS_URL.getCoercing().parseValue("https://example.com"); + assertThat(valid, is("https://example.com")); + + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_URL.getCoercing().parseValue("not a url")); + } + + @Test + void scalar_awsphone_parseValue() { + Object valid = AppSyncScalars.AWS_PHONE.getCoercing().parseValue("+1234567890"); + assertThat(valid, is("+1234567890")); + + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_PHONE.getCoercing().parseValue("12345")); + } + + @Test + void scalar_awsshort_range() { + Object valid = AppSyncScalars.AWS_SHORT.getCoercing().parseValue(32767); + assertThat(valid, is(32767)); + + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_SHORT.getCoercing().parseValue(40000)); + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_SHORT.getCoercing().parseValue(-32769)); + } + + @Test + void scalar_awstimestamp_parseValue_withString() { + Object valid = AppSyncScalars.AWS_TIMESTAMP.getCoercing().parseValue("1700000000"); + assertThat(valid, is(1700000000L)); + + assertThrows(Exception.class, () -> AppSyncScalars.AWS_TIMESTAMP.getCoercing().parseValue("not-a-number")); + } + + @Test + void scalar_serialize_nullSafety() { + assertThat(AppSyncScalars.AWS_TIMESTAMP.getCoercing().serialize(null), is(nullValue())); + assertThat(AppSyncScalars.AWS_LONG.getCoercing().serialize(null), is(nullValue())); + assertThat(AppSyncScalars.AWS_INTEGER.getCoercing().serialize(null), is(nullValue())); + assertThat(AppSyncScalars.AWS_FLOAT.getCoercing().serialize(null), is(nullValue())); + assertThat(AppSyncScalars.AWS_BOOLEAN.getCoercing().serialize(null), is(nullValue())); + } + + @Test + void scalar_awsipaddress_validIps() { + assertThat(AppSyncScalars.AWS_IP_ADDRESS.getCoercing().parseValue("192.168.1.1"), is("192.168.1.1")); + assertThat(AppSyncScalars.AWS_IP_ADDRESS.getCoercing().parseValue("255.255.255.255"), is("255.255.255.255")); + assertThat(AppSyncScalars.AWS_IP_ADDRESS.getCoercing().parseValue("0.0.0.0"), is("0.0.0.0")); + assertThat(AppSyncScalars.AWS_IP_ADDRESS.getCoercing().parseValue("2001:0db8:85a3:0000:0000:8a2e:0370:7334"), + is("2001:0db8:85a3:0000:0000:8a2e:0370:7334")); + assertThat(AppSyncScalars.AWS_IP_ADDRESS.getCoercing().parseValue("::1"), is("::1")); + } + + @Test + void scalar_awsipaddress_invalidIps() { + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_IP_ADDRESS.getCoercing().parseValue("999.999.999.999")); + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_IP_ADDRESS.getCoercing().parseValue("not-an-ip")); + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_IP_ADDRESS.getCoercing().parseValue("localhost")); + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_IP_ADDRESS.getCoercing().parseValue("google.com")); + } + + @Test + void scalar_scalarMap_cached() { + AppSyncScalarRegistry registry = new AppSyncScalarRegistry(); + var map1 = registry.scalarMap(); + var map2 = registry.scalarMap(); + assertThat(map1, is(sameInstance(map2))); + assertThat(map1, hasKey("AWSDateTime")); + assertThat(map1, hasKey("AWSJSON")); + assertThat(map1.size(), greaterThanOrEqualTo(17)); + } + + @Test + void scalar_awsboolean_rejectsNonBoolean() { + assertThat(AppSyncScalars.AWS_BOOLEAN.getCoercing().parseValue(true), is(true)); + assertThat(AppSyncScalars.AWS_BOOLEAN.getCoercing().parseValue(false), is(false)); + + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_BOOLEAN.getCoercing().parseValue("true")); + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_BOOLEAN.getCoercing().parseValue("xyz")); + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_BOOLEAN.getCoercing().parseValue(1)); + assertThrows(CoercingParseValueException.class, () -> AppSyncScalars.AWS_BOOLEAN.getCoercing().parseValue(0)); + } + + @Test + void scalar_awsboolean_serialize_rejectsNonBoolean() { + assertThat(AppSyncScalars.AWS_BOOLEAN.getCoercing().serialize(true), is(true)); + assertThat(AppSyncScalars.AWS_BOOLEAN.getCoercing().serialize(false), is(false)); + assertThat(AppSyncScalars.AWS_BOOLEAN.getCoercing().serialize(null), is(nullValue())); + + assertThrows(CoercingSerializeException.class, () -> AppSyncScalars.AWS_BOOLEAN.getCoercing().serialize("true")); + assertThrows(CoercingSerializeException.class, () -> AppSyncScalars.AWS_BOOLEAN.getCoercing().serialize(1)); + } +}